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
|
|---|---|---|---|---|---|---|
2105fe61a2ad6629ee6ab1693a159ddd226e7d61
|
TypeScript
|
haakon-gun/bachelor2021
|
/src/common/d3.ts
| 2.65625
| 3
|
import { D3Edge, LabelTransform } from '../types/d3/simulation';
import { GraphEdge, GraphNode, Ontology, UniqueObject, Edge } from '../types/ontologyTypes';
import { mapIdToEdge } from './node';
export const mapOntologyToGraphEdge = (ontology: Ontology): GraphEdge => {
const edge = mapIdToEdge(ontology.Predicate.id);
if (!edge) throw new Error('Could not map ontology to graph edge');
return {
...edge,
source: ontology.Subject.id,
target: ontology.Object.id,
sourceToTarget: [ontology.Predicate],
targetToSource: [],
};
};
export const removeDuplicates = <T extends UniqueObject>(
node: T,
index: number,
self: T[],
): boolean => index === self.findIndex((n) => node.id === n.id);
export const mergeParallelEdges = (
edge: GraphEdge | D3Edge,
_: number,
self: Array<GraphEdge | D3Edge>,
): boolean =>
self.every((e) => {
if (edge.sourceToTarget.some((child) => child.id === e.sourceToTarget[0].id)) {
return true;
}
if (edge.targetToSource.some((child) => child.id === e.sourceToTarget[0].id)) {
return true;
}
if (e.sourceToTarget.some((child) => child.id === edge.sourceToTarget[0].id)) {
return false;
}
if (e.targetToSource.some((child) => child.id === edge.sourceToTarget[0].id)) {
return false;
}
if (edge.source === e.target && edge.target === e.source) {
edge.targetToSource.push(...e.sourceToTarget);
return true;
}
if (edge.source === e.source && edge.target === e.target) {
edge.sourceToTarget.push(...e.sourceToTarget);
return true;
}
return true;
});
export const makePredicateUnique = (ontology: Ontology): Ontology => ({
...ontology,
Predicate: {
...ontology.Predicate,
id: ontology.Predicate.id + ontology.Subject.id + ontology.Object.id,
},
});
export const changeColorBasedOnType = (type: string) => {
let nodeColor = '#4299e1';
if (type.includes('SDG')) nodeColor = '#EA5F41';
if (type.includes('Trippel bunnlinje')) nodeColor = '#85E664';
if (type.includes('Delmål')) nodeColor = '#E0E73F';
return nodeColor;
};
export const mapNodeToGraphNodeAtDefaultPosition = (x?: number, y?: number) => (
node: GraphNode,
) => {
if (node.x) return node; // if node is already a GraphNode, just return it
const newNode: GraphNode = node;
newNode.x = x;
newNode.y = y;
newNode.vx = 0;
newNode.vy = 0;
return newNode;
};
export const mapOntologyToNonClickedGraphNode = (clickedNode: GraphNode) => (
ontology: Ontology,
): GraphNode => (ontology.Subject.id === clickedNode.id ? ontology.Object : ontology.Subject);
export const isD3Edge = (edge: GraphEdge | D3Edge) => typeof edge.target === 'string';
export const isGraphEdge = (edge: GraphEdge | D3Edge) => typeof edge.target !== 'string';
export const getRotationAndPosition = (edge: any): LabelTransform => {
let degree =
(Math.atan2(edge.target.y! - edge.source.y!, edge.target.x! - edge.source.x!) * 180) / Math.PI;
let radian = degree / 180;
let x = 0;
let y = 0;
let flip = false;
if (degree >= 90) {
radian = ((degree - 90) * 2) / 180;
x = -(1 - radian);
y = -radian;
degree -= 180;
flip = true;
} else if (degree >= -90) {
radian = (degree * 2) / 180;
x = radian;
y = -(1 + radian);
flip = false;
} else if (degree >= -180) {
radian = ((degree + 90) * 2) / 180;
x = 1 + radian;
y = radian;
degree += 180;
flip = true;
}
return { x, y, degree, flip };
};
const addDirectionArrowToEdgeLabelText = (text: string, direction: boolean): string => {
if (direction) return `<-- ${text}`;
return `${text} -->`;
};
export const createEdgeLabelText = (edge: Edge[], flipDirection: boolean): string => {
switch (edge.length) {
case 0:
return '';
case 1:
return addDirectionArrowToEdgeLabelText(edge[0].name, flipDirection);
default:
return addDirectionArrowToEdgeLabelText(`${edge.length} Predicates`, flipDirection);
}
};
export const removingNodeWillMakeGraphEmpty = (
node: GraphNode,
edges: Array<D3Edge | GraphEdge>,
): boolean =>
edges.every((edge) => {
const source = typeof edge.source === 'string' ? edge.source : edge.source.id;
const target = typeof edge.target === 'string' ? edge.target : edge.target.id;
return node.id === source || node.id === target;
});
|
f7d2cdfaf558bcb97d3bca5d010a01c7cc4f5379
|
TypeScript
|
TXZdream/websocket-echo-server_end
|
/static/xterm/src/EscapeSequences.ts
| 3.046875
| 3
|
/**
* @license MIT
*/
/**
* C0 control codes
* See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
*/
export namespace C0 {
/** Null (Caret = ^@, C = \0) */
export const NUL = '\x00';
/** Start of Heading (Caret = ^A) */
export const SOH = '\x01';
/** Start of Text (Caret = ^B) */
export const STX = '\x02';
/** End of Text (Caret = ^C) */
export const ETX = '\x03';
/** End of Transmission (Caret = ^D) */
export const EOT = '\x04';
/** Enquiry (Caret = ^E) */
export const ENQ = '\x05';
/** Acknowledge (Caret = ^F) */
export const ACK = '\x06';
/** Bell (Caret = ^G, C = \a) */
export const BEL = '\x07';
/** Backspace (Caret = ^H, C = \b) */
export const BS = '\x08';
/** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */
export const HT = '\x09';
/** Line Feed (Caret = ^J, C = \n) */
export const LF = '\x0a';
/** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */
export const VT = '\x0b';
/** Form Feed (Caret = ^L, C = \f) */
export const FF = '\x0c';
/** Carriage Return (Caret = ^M, C = \r) */
export const CR = '\x0d';
/** Shift Out (Caret = ^N) */
export const SO = '\x0e';
/** Shift In (Caret = ^O) */
export const SI = '\x0f';
/** Data Link Escape (Caret = ^P) */
export const DLE = '\x10';
/** Device Control One (XON) (Caret = ^Q) */
export const DC1 = '\x11';
/** Device Control Two (Caret = ^R) */
export const DC2 = '\x12';
/** Device Control Three (XOFF) (Caret = ^S) */
export const DC3 = '\x13';
/** Device Control Four (Caret = ^T) */
export const DC4 = '\x14';
/** Negative Acknowledge (Caret = ^U) */
export const NAK = '\x15';
/** Synchronous Idle (Caret = ^V) */
export const SYN = '\x16';
/** End of Transmission Block (Caret = ^W) */
export const ETB = '\x17';
/** Cancel (Caret = ^X) */
export const CAN = '\x18';
/** End of Medium (Caret = ^Y) */
export const EM = '\x19';
/** Substitute (Caret = ^Z) */
export const SUB = '\x1a';
/** Escape (Caret = ^[, C = \e) */
export const ESC = '\x1b';
/** File Separator (Caret = ^\) */
export const FS = '\x1c';
/** Group Separator (Caret = ^]) */
export const GS = '\x1d';
/** Record Separator (Caret = ^^) */
export const RS = '\x1e';
/** Unit Separator (Caret = ^_) */
export const US = '\x1f';
/** Space */
export const SP = '\x20';
/** Delete (Caret = ^?) */
export const DEL = '\x7f';
};
|
0a9ccf28760ae70915a88cbbedcca4dff2ea3737
|
TypeScript
|
YeZhikang/im-server
|
/src/util/time.ts
| 3.125
| 3
|
export const isEqualDate = (a, b) => {
if(a.length !== b.length || a.length !== 3){
return false
}
for(let i = 0; i < a.length; i++){
console.log(parseInt(a[i]), parseInt(b[i]))
if(parseInt(a[i]) !== parseInt(b[i])){
return false
}
}
return true
}
export const getYearMonthDay = (date) => {
return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
}
|
828308d9fee1782fe4a8325accfbfa039f924bcd
|
TypeScript
|
detochko/ts-utils
|
/src/dom/getWindow.ts
| 2.90625
| 3
|
let cache: Window|null|undefined;
/**
* @returns {Window|undefined}
*/
export const getWindow = (): Window|undefined => {
if (undefined === cache) {
cache = typeof window !== 'undefined' ? window : null;
}
return cache || undefined;
};
|
c40c415329093abd1975882391e797a178bc5f79
|
TypeScript
|
kichkinproject/wsm2-client
|
/src/app/models/controller.ts
| 2.671875
| 3
|
import {ControllerType} from './entity-type';
export class Controller {
id: number;
// uniqId: string;
name: string;
description: string;
type: ControllerType;
master: number;
constructor(id: number, /*uni: string,*/ name: string, description: string, type: ControllerType = ControllerType.CONTROLLER_TYPE_1, master: number = -1) {
this.id = id;
// this.uniqId = uni;
this.name = name;
this.description = description;
this.type = type;
this.master = master;
}
}
|
e0364b33c2fdbde6b2a1b538a8bfd9b72f29c31f
|
TypeScript
|
MaxBrokhman/excel-js
|
/src/components/dashboard/Dashboard.ts
| 2.546875
| 3
|
import map from 'lodash/map'
import {Wp} from '../../core/Wp';
import {localStorageManager} from '../../core/LocalStorageManager';
class Dashboard extends Wp {
private tableRecords: Array<string>
constructor() {
super()
this.tableRecords = localStorageManager.getAllTableRecords()
}
get dashboardHeader(): string {
return `
<div class="dashboard__header">
<h1>Excel Dashboard</h1>
</div>
<div class="dashboard__new">
<div class="dashboard__view">
<a href="#excel" class="dashboard__create">New table</a>
</div>
</div>
`
}
get html(): string {
return `
<div class="dashboard">
${this.dashboardHeader}
<div class="dashboard__list-container dashboard__view">
${this.tableRecordsList}
</div>
</div>
`
}
get tableRecordsList(): string {
return this.tableRecords.length
? `
<div class="dashboard__list-header">
<span>Table name</span>
<span>Opening date</span>
</div>
<ul class="dashboard__list">
${map(this.tableRecords, (key) => {
const record = localStorageManager.getTableRecord(key)
return `
<li class="dashboard__record">
<a href="#excel/${key}">
${record.tableName}
</a>
<strong>
${new Date(record.openDate).toLocaleDateString()}
${new Date(record.openDate).toLocaleTimeString()}
</strong>
</li>
`
})
.join('')}
</ul>
`
: '<p>You did\'nt create any tables yet</p>'
}
}
customElements.define('dash-board', Dashboard)
|
3d3e380684b31ade0ac141b702f4e990e1a84eef
|
TypeScript
|
HPDell/baidu-business-circle
|
/routes/model/BusinessCircle.ts
| 3.140625
| 3
|
export interface BusinessCircle {
/**
* 商圈所在的坐标范围,Point数组。
*/
coordinate: Point[];
/**
* 商圈所在城市名。
*/
city: string;
/**
* 商圈所在的区域。
*/
district: string;
/**
* 商圈的类型。
*/
type: string;
}
interface Point {
lng: number;
lat: number;
}
|
b0d790faa1a795c31a373876a7239a2755422fab
|
TypeScript
|
cmh114933/airbnb-basic-typeorm
|
/src/entity/Review.ts
| 2.59375
| 3
|
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn} from "typeorm";
import { Property } from "./Property";
@Entity()
export class Review {
@PrimaryGeneratedColumn()
id: number;
@Column()
rating: number;
@Column()
remark: string;
@ManyToOne(type=> Property, property => property.reviews)
@JoinColumn({name: "property_id"})
property: Property;
}
|
829e249dd2f9acb7cde33e787d2b7378f3e02472
|
TypeScript
|
im-cuttlefish/libroJS
|
/src/screen/background/index.ts
| 2.734375
| 3
|
import * as PIXI from "pixi.js";
import * as Animation from "../Animation";
import { Display } from "../interface/Display.interface";
import { BackgroundData } from "../../interface/BackgroundData.interface";
export class BackgroundDisplay implements Display {
readonly container: PIXI.Container;
private width: number;
private height: number;
private background: PIXI.Sprite;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
this.container = new PIXI.Container();
}
async set(background: BackgroundData, scene: string = "default") {
const next = PIXI.Sprite.from(background.scene[scene]);
const prev = this.background;
const is_landscape = next.width / next.height > this.width / this.height;
const scale = is_landscape
? this.height / next.height
: this.width / next.width;
next.anchor.set(0.5, 0.5);
next.position.set(this.width / 2, this.height / 2);
next.scale.set(scale, scale);
this.container.addChild(next);
if (!this.background) {
await Animation.fadeIn(next);
} else {
await Promise.all([Animation.fadeIn(next), Animation.fadeOut(prev)]);
}
this.container.removeChild(prev);
this.background = next;
}
clear() {
this.container.removeChild(this.background);
}
}
|
df630ab2c3e809cda5cefe996dc30fff5fa58ea6
|
TypeScript
|
jimmy818/mexico-angular
|
/soloperformance/soloperformance-solo-performance-frontend-12ba8ff551a0/projects/admin/src/app/modules/auth/shared/auth.validators.ts
| 3.03125
| 3
|
import { FormGroup } from '@angular/forms';
export class AuthValidators {
/**
* Validador de confirmación de contraseña.
* @param g Formulario con los campos correspondientes: contraseña y confirmación.
* Es necesario que los campos se llamen 'password' y 'passwordConfirm' respectivamente.
*/
static confirmPassword(
g: FormGroup
): { [key: string]: boolean } | null {
const password = g.get('password').value;
const confirmPassword = g.get('passwordConfirm').value;
// Verifica que ambos tengan un valor.
if (!password || !confirmPassword) {
return null;
}
// Verifica si la contraseña y su confirmación corresponden.
if (password === confirmPassword) {
return null;
}
// Retorna que los campos no corresponden.
return { 'match': true };
}
}
|
ba4cd40409bfe321fc555fee1b31f485d46abca1
|
TypeScript
|
Silvestr-b/async-dicontainer
|
/src/tests/get.ts
| 2.859375
| 3
|
import { expect } from 'chai'
import * as sinon from 'sinon'
import { Container } from '../'
import { Interfaces } from './data/interfaces/index'
import { TYPES } from './data/types/index'
import { Dog } from './data/entities/Dog'
import { Cat } from './data/entities/Cat'
import { Sheep } from './data/entities/Sheep'
import { SyncPromise } from 'syncasync/lib/SyncPromise'
describe('.get', () => {
let container: Container<Interfaces>;
let spy: sinon.SinonSpy;
let notCallableSpy: sinon.SinonSpy
beforeEach(() => {
container = new Container<Interfaces>();
spy = sinon.spy();
notCallableSpy = sinon.spy();
})
it('When module is not registered, should be rejected with that exception', done => {
container.get(TYPES.ISheepName)
.then(notCallableSpy, spy)
.then(() => {
expect(spy.firstCall.args[0]).to.be.instanceof(Error)
expect(notCallableSpy.notCalled).to.be.true
})
.then(() => done())
})
it('When one module name is passed, should be resolved with value that was returned by resolver', done => {
container.register(TYPES.ISheepName)
.resolver(deps => 'FakeSheepName')
container.get(TYPES.ISheepName)
.then(spy, notCallableSpy)
.then(() => {
expect(spy.calledWith('FakeSheepName')).to.be.true
expect(notCallableSpy.notCalled).to.be.true
})
.then(() => done())
})
it('When several names is passed, should be resolved with values by name', done => {
container.register(TYPES.ISheepName)
.resolver(deps => 'FakeSheepName')
container.register(TYPES.ISomeString)
.resolver(deps => 'FakeString')
container.get(TYPES.ISheepName, TYPES.ISomeString)
.then(spy, notCallableSpy)
.then(() => {
expect(spy.firstCall.args[0].ISheepName).to.be.equal('FakeSheepName')
expect(spy.firstCall.args[0].ISomeString).to.be.equal('FakeString')
expect(notCallableSpy.notCalled).to.be.true
})
.then(() => done())
})
it('When declaration or dependency declaration do not has Promises or SyncPromises, should return SyncPromise', done => {
container.register(TYPES.ISheepName)
.resolver(deps => 'FakeSheepName')
container.register(TYPES.ISheep)
.deps(TYPES.ISheepName)
.require('Fake', () => 'FakeString')
.resolver(deps => new Sheep(deps.ISheepName))
expect(container.get(TYPES.ISheepName)).to.be.instanceof(SyncPromise)
expect(container.get(TYPES.ISheep)).to.be.instanceof(SyncPromise)
done()
})
it('When declaration or dependency declaration do not has Promises but has SyncPromises, should return SyncPromise', done => {
container.register(TYPES.ISomeString)
.require('Fake', () => SyncPromise.resolve('FakeString'))
.resolver(deps => 'FakeString')
container.register(TYPES.ISheepName)
.resolver(deps => SyncPromise.resolve('FakeSheepName'))
container.register(TYPES.ISheep)
.deps(TYPES.ISheepName)
.resolver(deps => new Sheep(deps.ISheepName))
expect(container.get(TYPES.ISomeString)).to.be.instanceof(SyncPromise)
expect(container.get(TYPES.ISheepName)).to.be.instanceof(SyncPromise)
expect(container.get(TYPES.ISheep)).to.be.instanceof(SyncPromise)
done()
})
it('When declaration or dependency declaration has Promise, should return Promise', done => {
container.register(TYPES.ISomeString)
.require('Fake', () => Promise.resolve('FakeString'))
.resolver(deps => 'FakeString')
container.register(TYPES.ISheepName)
.resolver(deps => Promise.resolve('FakeSheepName'))
container.register(TYPES.ISheep)
.deps(TYPES.ISheepName)
.resolver(deps => new Sheep(deps.ISheepName))
expect(container.get(TYPES.ISomeString)).to.be.instanceof(Promise)
expect(container.get(TYPES.ISheepName)).to.be.instanceof(Promise)
expect(container.get(TYPES.ISheep)).to.be.instanceof(Promise)
done()
})
})
|
85e336db7c63784adeed3e2842ced72d501f6ad5
|
TypeScript
|
ChicoState/CareerFair
|
/career-fair-app/src/app/about/volunteer.component.ts
| 2.59375
| 3
|
import { Component,Input } from '@angular/core';
class Volunteer {
firstName: string;
lastName: string;
constructor (first: string, last: string)
{
this.firstName = first;
this.lastName = last;
}
}
@Component({
selector: 'volunteer',
templateUrl: './volunteer.component.html',
styleUrls: ['./volunteer.component.css'],
})
export class VolunteerComponent {
/////
title = "Volunteer Registration";
volunteerList: Volunteer[];
newVolunteer: Volunteer;
tempVolunteer: Volunteer = {
firstName: "",
lastName: ""
}
temp2Volunteer: Volunteer = {
firstName: "",
lastName: ""
}
constructor ()
{
this.volunteerList = [];
}
onSubmit(): void {
this.newVolunteer = new Volunteer(this.tempVolunteer.firstName,this.tempVolunteer.lastName)
this.volunteerList.push(this.newVolunteer);
}
}
|
c9f22aaab7ef21a43aace240aa5309d4fe4ef50f
|
TypeScript
|
zeroEvidence/SOLID_ToyRobot
|
/src/ui/interfaces/UserInterfaceAdapterFactory.interface.ts
| 2.59375
| 3
|
import { ISurface } from "../../entities/surface/interfaces/Surface.interface";
import { IToy } from "../../entities/toy/interfaces/Toy.interface";
import { ICommand } from "../../interfaces/Command.interface";
/**
* IUserInterfaceAdapterFactory defines the specification for
* user interface adapter factories.
*
* @export
* @interface IUserInterfaceAdapterFactory
*/
export interface IUserInterfaceAdapterFactory {
createUIAdapter(UIType: number, toy: IToy, surface: ISurface): ICommand;
}
|
5e94a636144802c01026ee4434ce81fa1150670a
|
TypeScript
|
gpasq/deno-sendgrid
|
/test.ts
| 2.59375
| 3
|
import {
assertEquals,
assertStrictEq,
assert,
} from "https://deno.land/std/testing/asserts.ts";
import {
sendMail,
IRequestBody,
sendSimpleMail,
ISimpleRequestBody,
} from "./mod.ts";
// This is a throwaway key for testing a limited number of emails only,
// from a throwaway account. Sorta like giving you my keys, but the keys
// are to an outhouse.
const key =
"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";
Deno.test({
name: "Testing Simple Email",
async fn(): Promise<void> {
let response = await sendSimpleMail(
{
subject: "Hello world",
to: [{ email: "denotest2020@gmail.com" }],
from: { email: "denotest2020@gmail.com" },
content: [
{ type: "text/plain", value: "Hello world" },
{ type: "text/html", value: "<h1>Hello world</h1>" },
],
},
{ apiKey: key },
);
console.log(response);
assertEquals(response.success, true);
},
});
Deno.test({
name: "Testing Full Email",
async fn(): Promise<void> {
let mail: IRequestBody = {
personalizations: [
{
subject: "Hello world",
to: [{ name: "DenoTest2020", email: "denotest2020@gmail.com" }],
},
],
from: { email: "denotest2020@gmail.com" },
content: [
{ type: "text/plain", value: "Hello world" },
{ type: "text/html", value: "<h1>Hello world</h1>" },
],
};
let response = await sendMail(mail, { apiKey: key });
console.log(response);
assertEquals(response.success, true);
},
});
|
d3cbc3d61d7a979c42db4b26c7ed1348a056cc0b
|
TypeScript
|
pasha-shestakov/WebpackTutorial
|
/src/test.ts
| 2.734375
| 3
|
class test{
var testInt: number;
testInt = 5;
var testString: string = "hello world 31 this works";
console.log(testString);
document.getElementById("test").innerHTML = "Test = " + testString;
}
|
8cb55f7ab94912fe14a492d2006cf7aa430161f6
|
TypeScript
|
cgiovanni96/Ruddit
|
/server/src/resolver/user/forgotPassword.ts
| 2.671875
| 3
|
import argon2 from 'argon2'
import { Arg, Ctx, Mutation, Resolver } from 'type-graphql'
import { v4 } from 'uuid'
import Context from '../../app/server/context'
import { isEmail, sendEmail } from '../../app/util/email'
import User from '../../database/entity/User'
import UserResponse from '../../database/schema/response/UserResponse'
import {
NoUsernameError,
PasswordLengthError,
TokenExpiredError
} from './errors'
export const FORGOT_PWD_PREFIX = 'forgot-password:'
@Resolver()
export default class ForgotPasswordResolver {
@Mutation(() => Boolean)
async forgotPassword(
@Arg('email') email: string,
@Ctx() { redis }: Context
): Promise<boolean> {
if (!isEmail(email)) return true
const user = await User.findOne({ email })
if (!user) {
return true
}
const token = v4()
const forgotPasswordHtml = `<a href="http://localhost:3000/change-password/${token}">Reset Password</a>`
redis.set(FORGOT_PWD_PREFIX + token, user.id, 'ex', 1000 * 60 * 60 * 12) // 12 hours
sendEmail(user.email, 'Password Reset', forgotPasswordHtml)
return true
}
@Mutation(() => UserResponse)
async changePassword(
@Arg('token') token: string,
@Arg('newPassword') newPassword: string,
@Ctx() { req, redis }: Context
): Promise<UserResponse> {
const redisKey = FORGOT_PWD_PREFIX + token
console.log('newPassword: ', newPassword)
if (newPassword.length <= 2) return PasswordLengthError
const userId = await redis.get(redisKey)
if (!userId) return TokenExpiredError
const user = await User.findOne({ id: userId })
if (!user) return NoUsernameError
user.password = await argon2.hash(newPassword)
req.session.userId = user.id
await redis.del(redisKey)
const userRet = await user.save()
return { user: userRet }
}
}
|
93d8785c205479bc16e5324c3533cb975984cd07
|
TypeScript
|
ByDSA/datune
|
/packages/core/src/time/symbolic/rhythm/pattern/cache.ts
| 2.578125
| 3
|
import { Arrays, StringHashCache } from "@datune/utils";
import Pattern from "./Pattern";
type HashingObject = Arrays.Number;
const cache = new StringHashCache<Pattern, HashingObject>( {
hash(hashingObject: HashingObject): string {
return hashingObject.toString();
},
toDto(pattern: Pattern): HashingObject {
return pattern.array;
},
create(hashingObject: HashingObject): Pattern {
return (Pattern as any).create(...hashingObject);
},
} );
export default cache;
|
be96973cdcad77e51a1c61ba5b6eb46ae661c3a2
|
TypeScript
|
zhanglijie5997/zhanglijie123
|
/api/posts/apiDeletePost.ts
| 2.53125
| 3
|
import { RequestHandler } from "express";
import { DataStore } from "../../data/data";
import { publicInfo, apiError } from "../../model/todo/message";
export const apiDeletePost:RequestHandler = (req,res,next) => {
const postIndex = DataStore.post.findIndex((item:any) => {
return item.id == req.params.id;
})
if(postIndex > -1) {
DataStore.post.splice(postIndex,1);
res.status(200).json(new publicInfo("success",1000,{
post:"success"
}))
}else {
res.status(404).json(new apiError("don\'t have","default",4004))
}
}
|
e7b859f21e8187295f0f1a743be78805484eeeda
|
TypeScript
|
Noah-1994/web-utils
|
/src/object/index.ts
| 2.953125
| 3
|
/* eslint-disable no-unused-expressions */
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/* eslint-disable no-self-compare */
/* eslint-disable no-use-before-define */
export function clone(obj:any) {
if (typeof obj === 'function') {
return obj;
}
const result:any = Array.isArray(obj) ? [] : {};
for (const key in obj) {
// include prototype properties
const value = obj[key];
const type = {}.toString.call(value).slice(8, -1);
if (type === 'Array' || type === 'Object') {
result[key] = clone(value);
} else if (type === 'Date') {
result[key] = new Date(value.getTime());
} else if (type === 'RegExp') {
result[key] = RegExp(value.source, getRegExpFlags(value));
} else {
result[key] = value;
}
}
return result;
}
function getRegExpFlags(regExp:any) {
if (typeof regExp.source.flags === 'string') {
return regExp.source.flags;
}
const flags = [];
regExp.global && flags.push('g');
regExp.ignoreCase && flags.push('i');
regExp.multiline && flags.push('m');
regExp.sticky && flags.push('y');
regExp.unicode && flags.push('u');
return flags.join('');
}
export function compare(value1:any, value2:any) {
if (value1 === value2) {
return true;
}
if (value1 !== value1 && value2 !== value2) {
return true;
}
if ({}.toString.call(value1) !== {}.toString.call(value2)) {
return false;
}
if (value1 !== Object(value1)) {
// non equal primitives
return false;
}
if (!value1) {
return false;
}
if (Array.isArray(value1)) {
return compareArrays(value1, value2);
}
if ({}.toString.call(value1) === '[object Object]') {
return compareObjects(value1, value2);
}
return compareNativeSubtypes(value1, value2);
}
function compareNativeSubtypes(value1:any, value2:any) {
// e.g. Function, RegExp, Date
return value1.toString() === value2.toString();
}
function compareArrays(value1:any, value2:any) {
const len = value1.length;
if (len !== value2.length) {
return false;
}
let alike = true;
for (let i = 0; i < len; i++) {
if (!compare(value1[i], value2[i])) {
alike = false;
break;
}
}
return alike;
}
function compareObjects(value1:any, value2:any) {
const keys1 = Object.keys(value1).sort();
const keys2 = Object.keys(value2).sort();
const len = keys1.length;
if (len !== keys2.length) {
return false;
}
for (let i = 0; i < len; i++) {
const key1 = keys1[i];
const key2 = keys2[i];
if (!(key1 === key2 && compare(value1[key1], value2[key2]))) {
return false;
}
}
return true;
}
export function flush(collection:any) {
let result: any;
let len: number;
let i: number;
if (!collection) {
return undefined;
}
if (Array.isArray(collection)) {
result = [];
len = collection.length;
for (i = 0; i < len; i++) {
const elem = collection[i];
if (elem != null) {
result.push(elem);
}
}
return result;
}
if (typeof collection === 'object') {
result = {};
const keys = Object.keys(collection);
len = keys.length;
for (i = 0; i < len; i++) {
const key = keys[i];
const value = collection[key];
if (value != null) {
result[key] = value;
}
}
return result;
}
return undefined;
}
export default {
clone,
compare,
flush,
};
|
dfa025d297dc4d257df3a486d6bfb3d07d2187b7
|
TypeScript
|
marckassay/DemoOfIonicIssues
|
/e2e/src/helpers/WebView.ts
| 3.046875
| 3
|
import Gestures from './Gestures';
export const CONTEXT_REF = {
NATIVE: 'native',
WEBVIEW: 'webview',
};
const DOCUMENT_READY_STATE = {
COMPLETE: 'complete',
INTERACTIVE: 'interactive',
LOADING: 'loading',
};
class WebView {
constructor() {
}
/**
* Wait for the webview context to be loaded
*
* By default you have `NATIVE_APP` as the current context. If a webview is loaded it will be
* added to the current contexts and will looks something like this
* `["NATIVE_APP","WEBVIEW_28158.2"]`
* The number behind `WEBVIEW` can be any string
*/
waitForWebViewContextLoaded() {
browser.waitUntil(
() => {
let result: boolean;
const currentContexts = this.getCurrentContexts();
if (currentContexts.length > 1) {
result = !!currentContexts.find(context => context.toLowerCase().includes(CONTEXT_REF.WEBVIEW));
}
return result;
},
10000,
'Webview context not loaded',
100
);
}
/**
* Switch to native or webview context
*
* @param {string} context should be native of webview
*/
switchToContext(context) {
browser.switchContext(this.getCurrentContexts()[context === CONTEXT_REF.WEBVIEW ? 1 : 0]);
}
/**
* Returns an object with the list of all available contexts
*
* @return {object} An object containing the list of all available contexts
*/
getCurrentContexts() {
return browser.getContexts();
}
/**
* Wait for the document to be full loaded
*/
waitForDocumentFullyLoaded() {
browser.waitUntil(
() => browser.execute(() => document.readyState) === DOCUMENT_READY_STATE.COMPLETE,
15000,
'Website not loaded',
100
);
}
/**
* Wait for the website in the webview to be loaded
*/
waitForWebsiteLoaded() {
this.waitForWebViewContextLoaded();
this.switchToContext(CONTEXT_REF.WEBVIEW);
this.waitForDocumentFullyLoaded();
this.switchToContext(CONTEXT_REF.NATIVE);
}
/* swipeLeftUntilWebsiteLoaded() {
browser.waitUntil(() => browser.execute(() => {
if (document && document.readyState === 'loading') {
Gestures.swipeLeft();
console.log('swiping!');
}
return document && document.readyState === 'complete';
}),
15000,
'Website not loaded',
100
);
} */
}
export default new WebView();
|
1c53e94a6cfec17527155e803020eda883bea0c9
|
TypeScript
|
okumurakengo/til
|
/js/ts/02_doc/119_compability.ts
| 3.15625
| 3
|
let identity = function<T>(x: T): T {
return x;
}
let reverse = function<U>(y: U): U {
return y;
}
identity = reverse; // OK, because (x: any) => any matches (y: any) => any
|
760ad2d7a5e603766e18b5d3609287cc63140fd6
|
TypeScript
|
reddybushan/employeedeptfrontend
|
/src/app/Employee.ts
| 2.6875
| 3
|
import { Department } from "./Department";
export class Employee {
employeeId: number;
firstName: string;
lastName: string;
phoneNumber: string;
managerId: number;
salary: number;
department: Department;
email: string;
constructor(employeeId: number, firstName: string, lastName:string, salary: number, email:string,phoneNo :string, managerId:number,department:Department,
) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.email = email;
this.phoneNumber = phoneNo;
this.managerId = managerId;
this.department = department;
}
}
|
f23dd75a3b1dd6c4652e057c8ae36256d6b3a45c
|
TypeScript
|
expo/expo-cli
|
/packages/expo-cli/src/appleApi/pushKey.ts
| 2.671875
| 3
|
import { Keys } from '@expo/apple-utils';
import chalk from 'chalk';
import dateformat from 'dateformat';
import CommandError from '../CommandError';
import Log from '../log';
import { ora } from '../utils/ora';
import { AppleCtx, getRequestContext } from './authenticate';
export type PushKeyInfo = {
id: string;
name: string;
};
export type PushKey = {
apnsKeyP8: string;
apnsKeyId: string;
teamId: string;
teamName?: string;
};
export function isPushKey(obj: { [key: string]: any }): obj is PushKey {
return (
obj.apnsKeyP8 &&
typeof obj.apnsKeyP8 === 'string' &&
obj.apnsKeyId &&
typeof obj.apnsKeyId === 'string' &&
obj.teamId &&
typeof obj.teamId === 'string'
);
}
const { MaxKeysCreatedError } = Keys;
const APPLE_KEYS_TOO_MANY_GENERATED_ERROR = `
You can have only ${chalk.underline('two')} Apple Keys generated on your Apple Developer account.
Please revoke the old ones or reuse existing from your other apps.
Please remember that Apple Keys are not application specific!
`;
async function listPushKeysAsync(authCtx: AppleCtx): Promise<PushKeyInfo[]> {
const spinner = ora(`Fetching Apple push keys`).start();
try {
const context = getRequestContext(authCtx);
const keys = await Keys.getKeysAsync(context);
spinner.succeed(`Fetched Apple push keys`);
return keys;
} catch (error: any) {
spinner.fail(`Failed to fetch Apple push keys`);
throw error;
}
}
async function createPushKeyAsync(
authCtx: AppleCtx,
name: string = `Expo Push Notifications Key ${dateformat('yyyymmddHHMMss')}`
): Promise<PushKey> {
const spinner = ora(`Creating Apple push key`).start();
try {
const context = getRequestContext(authCtx);
const key = await Keys.createKeyAsync(context, { name, isApns: true });
const apnsKeyP8 = await Keys.downloadKeyAsync(context, { id: key.id });
spinner.succeed(`Created Apple push key`);
return {
apnsKeyId: key.id,
apnsKeyP8,
teamId: authCtx.team.id,
teamName: authCtx.team.name,
};
} catch (err: any) {
spinner.fail('Failed to create Apple push key');
const resultString = err.rawDump?.resultString;
if (
err instanceof MaxKeysCreatedError ||
(resultString && resultString.match(/maximum allowed number of Keys/))
) {
throw new CommandError(APPLE_KEYS_TOO_MANY_GENERATED_ERROR);
}
throw err;
}
}
async function revokePushKeyAsync(authCtx: AppleCtx, ids: string[]): Promise<void> {
const name = `Apple push key${ids?.length === 1 ? '' : 's'}`;
const spinner = ora(`Revoking ${name}`).start();
try {
const context = getRequestContext(authCtx);
await Promise.all(ids.map(id => Keys.revokeKeyAsync(context, { id })));
spinner.succeed(`Revoked ${name}`);
} catch (error: any) {
Log.error(error);
spinner.fail(`Failed to revoke ${name}`);
throw error;
}
}
export class PushKeyManager {
ctx: AppleCtx;
constructor(appleCtx: AppleCtx) {
this.ctx = appleCtx;
}
async list(): Promise<PushKeyInfo[]> {
return listPushKeysAsync(this.ctx);
}
async create(name?: string): Promise<PushKey> {
return createPushKeyAsync(this.ctx, name);
}
async revoke(ids: string[]) {
return revokePushKeyAsync(this.ctx, ids);
}
format({ id, name }: PushKeyInfo): string {
return `${name} - ID: ${id}`;
}
}
|
7e05535d36797cd57b16457a22cb448781529a10
|
TypeScript
|
xiaoxin0573128/egret-framework
|
/source/src/ECS/Components/Camera.ts
| 2.59375
| 3
|
///<reference path="../Component.ts"/>
class Camera extends Component {
private _zoom;
private _origin: Vector2;
private _transformMatrix: Matrix2D = Matrix2D.identity;
private _inverseTransformMatrix = Matrix2D.identity;
private _minimumZoom = 0.3;
private _maximumZoom = 3;
private _areMatrixesDirty = true;
public get zoom(){
if (this._zoom == 0)
return 1;
if (this._zoom < 1)
return MathHelper.map(this._zoom, this._minimumZoom, 1, -1, 0);
return MathHelper.map(this._zoom, 1, this._maximumZoom, 0, 1);
}
public set zoom(value: number){
this.setZoom(value);
}
public get minimumZoom(){
return this._minimumZoom;
}
public set minimumZoom(value: number){
this.setMinimumZoom(value);
}
public get maximumZoom(){
return this._maximumZoom;
}
public set maximumZoom(value: number){
this.setMaximumZoom(value);
}
public get origin(){
return this._origin;
}
public set origin(value: Vector2){
if (this._origin != value){
this._origin = value;
this._areMatrixesDirty = true;
}
}
public get transformMatrix(){
this.updateMatrixes();
return this._transformMatrix;
}
constructor() {
super();
this.setZoom(0);
}
public setMinimumZoom(minZoom: number): Camera{
if (this._zoom < minZoom)
this._zoom = this.minimumZoom;
this._minimumZoom = minZoom;
return this;
}
public setMaximumZoom(maxZoom: number): Camera {
if (this._zoom > maxZoom)
this._zoom = maxZoom;
this._maximumZoom = maxZoom;
return this;
}
public setZoom(zoom: number){
let newZoom = MathHelper.clamp(zoom, -1, 1);
if (newZoom == 0){
this._zoom = 1;
} else if(newZoom < 0){
this._zoom = MathHelper.map(newZoom, -1, 0, this._minimumZoom, 1);
} else {
this._zoom = MathHelper.map(newZoom, 0, 1, 1, this._maximumZoom);
}
this._areMatrixesDirty = true;
return this;
}
public initialize() {
}
public update(){
SceneManager.getActiveScene().entities.buffer.forEach(entity => entity.components.buffer.forEach(component => {
if (component.displayRender){
let has = this.entity.scene.$children.indexOf(component.displayRender)
if (has == -1){
this.entity.scene.stage.addChild(component.displayRender);
}
}
}));
}
public setPosition(position: Vector2){
this.entity.transform.setPosition(position);
return this;
}
public updateMatrixes(){
if (!this._areMatrixesDirty)
return;
let tempMat: Matrix2D;
this._transformMatrix = Matrix2D.createTranslation(-this.entity.transform.position.x, -this.entity.transform.position.y);
if (this._zoom != 1){
tempMat = Matrix2D.createScale(this._zoom, this._zoom);
this._transformMatrix = Matrix2D.multiply(this._transformMatrix, tempMat);
}
tempMat = Matrix2D.createTranslation(this._origin.x, this._origin.y, tempMat);
this._transformMatrix = Matrix2D.multiply(this._transformMatrix, tempMat);
this._inverseTransformMatrix = Matrix2D.invert(this._transformMatrix);
this._areMatrixesDirty = false;
}
public destory() {
}
}
|
7608f04e247e71172bac36e57ab3ce7271b9d57e
|
TypeScript
|
RomanAVolodin/HoldingEvents
|
/backend/src/user/repositories/user.repository.ts
| 2.5625
| 3
|
import { EntityRepository, Repository } from 'typeorm';
import { UserEntity } from '@app/user/entity/user.entity';
import { HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
@EntityRepository(UserEntity)
export class UserRepository {
constructor(
@InjectRepository(UserEntity)
public readonly repo: Repository<UserEntity>,
) {}
async save(user: UserEntity): Promise<UserEntity> {
return await this.repo.save(user);
}
async remove(user: UserEntity): Promise<UserEntity> {
return await this.repo.remove(user);
}
getById = async (id: string): Promise<UserEntity> => {
const user = await this.repo.findOne(id);
if (!user) {
throw new HttpException("User wasn't found by ID", HttpStatus.NOT_FOUND);
}
return user;
};
findByEmail = async (email: string): Promise<UserEntity | null> => {
return await this.repo.findOne({ email });
};
findByEmailForLogin = async (email: string): Promise<UserEntity | null> => {
return await this.repo.findOne({
where: {
email,
},
select: ['id', 'email', 'password', 'status'],
});
};
async getAll(): Promise<UserEntity[]> {
return await this.repo.find();
}
}
|
4f21c51f236055669b6479e8826cfc6a7121f5f7
|
TypeScript
|
tiagomaradei/design-patterns
|
/src/FactoryMethod/Pizza.ts
| 3.078125
| 3
|
abstract class Pizza {
protected name: string;
protected dough: string;
protected suace: string;
protected topPings: string[] = [];
public prepare(): void {
console.log(`Preparing... ${this.getName()}`);
console.log(`Tossing dough...`);
console.log(`Adding sauce...`);
console.log(`Adding toppings: ${this.topPings.join(',')}`);
}
public bake(): void {
console.log(`Bake for 25 minutes...`);
}
public cut(): void {
console.log(`Cutting pizza...`);
}
public box(): void {
console.log(`Boxing pizza...`);
}
public getName(): string {
return this.name;
}
}
export default Pizza;
|
01ad33e991d9232f366c053277001191d71ffb1b
|
TypeScript
|
chrisguttandin/subscribable-things
|
/src/factories/on.ts
| 2.703125
| 3
|
import { TEventHandler, TEventType, TOnFactory } from '../types';
export const createOn: TOnFactory = (wrapSubscribeFunction) => {
return (target, type, options) =>
wrapSubscribeFunction((observer) => {
const listener: TEventHandler<typeof target> = (event) => observer.next(<TEventType<typeof target, typeof type>>event);
target.addEventListener(type, listener, options);
return () => target.removeEventListener(type, listener, options);
});
};
|
afaaace68297e072a55b1cbf3a24b504819767d9
|
TypeScript
|
DarkMatterBridge/BiddingSystem
|
/src/app/model/Bidding.ts
| 2.890625
| 3
|
export class Bidding {
nodes = [];
bids = [];
index: number;
constructor() {
this.index = 0;
}
addBid(nextBid) {
this.bids.push(nextBid[0]);
this.nodes.push(nextBid[1]);
this.index++;
}
getLastBid() {
return (this.index);
}
getBid(i) {
return [this.bids[i], this.nodes[i], this.nodes[i]["Desc"]];
}
getSequence() {
if (this.index>0)
console.log(this.bids[0])
return Array.from({ length: this.index }, (v, k) => k + 1).map(i => [this.bids[i], this.nodes[i]]);
}
cutBidding(i) {
this.bids.splice(i + 1, 100);
this.nodes.splice(i + 1, 100);
}
}
|
ac6591117b84bd3ff8e79d5844f5fa8c3f8e56a9
|
TypeScript
|
aleksandr-yakovlev/mf.messenger.praktikum.yandex
|
/src/utils/render.ts
| 2.78125
| 3
|
interface IBlock {
hide: () => void;
show: () => void;
getContent: () => HTMLElement;
}
export const render = (query: string, block: IBlock, element = document): HTMLElement => {
const root = element.querySelector(query);
return root ? root.appendChild(block.getContent()) : block.getContent();
};
|
38d82a36cd2ca9b56a39cced93e909defd914704
|
TypeScript
|
duffman/bi-realtime-module
|
/new-backend/src/core/socket-message.ts
| 2.65625
| 3
|
/**
* Copyright (c) Patrik Forsberg <patrik.forsberg@coldmind.com> - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*/
export interface ISocketMessage {
jsonObj: any;
}
export class SocketMessage implements ISocketMessage {
public jsonObj: any = {};
constructor(mess?: any) {
if (mess) {
this.parse(mess);
}
}
parse(mess: any): void {
try {
this.jsonObj = JSON.parse(mess);
} catch (ex) {
this.jsonObj = {};
}
}
}
|
3bb74ac083c20f5d60fe753e5f24b87fca463aaf
|
TypeScript
|
andyjia/leetcode-typescript
|
/solutions/maximum_subarray_test.ts
| 2.671875
| 3
|
import { test } from "https://deno.land/std/testing/mod.ts";
import { assertStrictEq } from "https://deno.land/std/testing/asserts.ts";
import maxSubArray from "./maximum_subarray.ts";
test("53. Maximum Subarray", () => {
assertStrictEq(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]), 6);
assertStrictEq(maxSubArray([-3, -2, -5, -1, -4, -1]), -1);
});
|
f041dfd33dc51e90b8701983c533e8d16ee6d5f6
|
TypeScript
|
indrimuska/ng-toolkit
|
/src/input/input.ts
| 2.546875
| 3
|
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ValueAccessor } from '../utility';
enum InputType {
text = 'text',
}
const InputTypesArray: InputType[] = Object.keys(InputType).map(type => InputType[type]);
@Component({
selector: 'ngt-input',
template: require('./input.html'),
styles: [
require('./input.scss')
],
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: InputComponent, multi: true }
]
})
export class InputComponent extends ValueAccessor<string> implements OnInit {
@Input() public disabled: boolean;
@Input() public placeholder: string = '';
@Input() public type: InputType;
@Output() public focus = new EventEmitter<FocusEvent>();
@Output() public blur = new EventEmitter<FocusEvent>();
@Output() public keydown = new EventEmitter<KeyboardEvent>();
@Output() public keypress = new EventEmitter<KeyboardEvent>();
@Output() public keyup = new EventEmitter<KeyboardEvent>();
@ViewChild('elementRef') public elementRef: ElementRef;
public ngOnInit() {
if (InputTypesArray.indexOf(this.type) < 0) {
throw new Error(`Type attribute not supported: provided ${this.type}`);
}
}
}
|
3b258c02733f3bb91c9ca9f2fb4d0394ba40863a
|
TypeScript
|
FoalTS/foal
|
/packages/core/src/sessions/http/check-user-id-type.spec.ts
| 2.8125
| 3
|
import { strictEqual, throws } from 'assert';
import { checkUserIdType } from './check-user-id-type';
describe('checkUserIdType', () => {
context('given the user ID type is "string"', () => {
it('should return the user ID if it is a string.', () => {
const userId = '123';
const userIdType = 'string';
const actual = checkUserIdType(userId, userIdType);
strictEqual(actual, userId);
});
it('should throw an error if the user ID is not a string.', () => {
const userId = 123;
const userIdType = 'string';
throws(
() => checkUserIdType(userId, userIdType),
new Error('Invalid user ID type: number')
);
});
});
context('given the user ID type is "number"', () => {
it('should return the user ID if it is a number.', () => {
const userId = 123;
const userIdType = 'number';
const actual = checkUserIdType(userId, userIdType);
strictEqual(actual, userId);
});
it('should throw an error if the user ID is not a number.', () => {
const userId = '123';
const userIdType = 'number';
throws(
() => checkUserIdType(userId, userIdType),
new Error('Invalid user ID type: string')
);
});
});
context('given the user ID type is undefined', () => {
it('should return the user ID if it is a number.', () => {
const userId = 123;
const userIdType = undefined;
const actual = checkUserIdType(userId, userIdType);
strictEqual(actual, userId);
});
it('should throw an error if the user ID is not a number.', () => {
const userId = '123';
const userIdType = undefined;
throws(
() => checkUserIdType(userId, userIdType),
new Error('Invalid user ID type: string')
);
});
});
});
|
b905a1fd2ba3d58139541d29e1c1bb04563cb8bc
|
TypeScript
|
spacejack/m-carousel
|
/src/ts/components/carousel-page.ts
| 2.8125
| 3
|
import * as m from 'mithril'
import carousel from './carousel'
import panel from './panel'
/** Contents for each panel in the carousel */
const CONTENTS = [
{title: "Panel One", image: 'panel1.jpg', body: "Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Et harum quidem rerum facilis est et expedita distinctio."},
{title: "Panel Two", image: 'panel2.jpg', body: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."},
{title: "Panel Three", image: 'panel3.jpg', body: "Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem."},
{title: "Panel Four", image: 'panel4.jpg', body: "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur."},
{title: "Panel Five", image: 'panel5.jpg', body: "Et harum quidem rerum facilis est et expedita distinctio. Consectetur adipisicing elit, sed do eiusmod tempor."}
]
interface Attrs {
// This value comes from router
panelId: string
}
export default {
view({attrs: {panelId}}) {
// Router will provide us with the current panel ID.
// Convert to an index in CONTENTS array.
const position = clamp((Number(panelId) || 1) - 1, 0, CONTENTS.length - 1)
return (
m('.carousel-page',
// Render the carousel component.
m(carousel, {panel, contents: CONTENTS, position}),
// Indicator of which panel we're on
m('.indicators',
CONTENTS.map((content, i) => {
return m('.indicator', {
class: position === i ? 'indicator-active' : undefined,
onclick: () => {m.route.set('/carousel/' + (i + 1))}
})
})
),
// Prev/Next buttons
m('.nav-block',
m('button',
{
type: 'button',
onclick: () => {
m.route.set('/carousel/' + (pmod(position - 1, CONTENTS.length) + 1))
}
},
"PREV"
),
m('button',
{
type: 'button',
onclick: () => {
m.route.set('/carousel/' + (pmod(position + 1, CONTENTS.length) + 1))
}
},
"NEXT"
)
)
)
)
}
} as m.Component<Attrs,{}>
function clamp (n: number, min: number, max: number) {
return Math.min(Math.max(n, min), max)
}
/** Always positive modulus */
export function pmod (n: number, m: number) {
return ((n % m + m) % m)
}
|
96b3ca439001ec452fbd714846c758a99fa3a798
|
TypeScript
|
tianfenglin/commonts
|
/src/baseclass/https/browser.ts
| 2.71875
| 3
|
/**获取配置信息等 */
class Browser {
/**
* 获取flash版本
*/
public getFlashVersion(): number {
let version;
try {
version = navigator.plugins["Shockwave Flash"];
version = version.description;
} catch (ex) {
try {
version = new ActiveXObject(
"ShockwaveFlash.ShockwaveFlash"
).GetVariable("$version");
} catch (ex2) {
version = "0.0";
}
}
version = version.match(/\d+/g);
return parseFloat(version[0] + "." + version[1]);
}
/**
* 获取IE版本
*/
public getIEVersion(): number {
let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
let isIE =
userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
let isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
let isIE11 =
userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
if (isIE) {
let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
let fIEVersion = parseFloat(RegExp["$1"]);
if (fIEVersion == 7) {
return 7;
} else if (fIEVersion == 8) {
return 8;
} else if (fIEVersion == 9) {
return 9;
} else if (fIEVersion == 10) {
return 10;
} else {
return 6; //IE版本<=7
}
} else if (isEdge) {
return 0; //ie的edge浏览器
} else if (isIE11) {
return 11; //IE11
} else {
return -1; //不是ie浏览器
}
}
/**
* 判断浏览器是否支持图片的base64
*/
public isSupportBase64: () => {} = function(): boolean {
let data = new Image();
let support = true;
data.onload = data.onerror = function() {
if (data.width != 1 || data.height != 1) {
support = false;
}
};
data.src =
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
return support;
};
/**
* 获取网址路径(含第一个文件目录)
*/
public getDocumentPath(): string {
let windows: Location = window.document.location as Location;
let curWwwPath = windows.href;
let pathName = windows.pathname;
let pos = curWwwPath.indexOf(pathName);
let localhostPaht = curWwwPath.substring(0, pos);
let projectName = pathName.substring(
0,
pathName.substr(1).indexOf("/") + 1
);
return localhostPaht + projectName;
}
/**
* 获取网址路径(ip+端口号)
*/
public getWindowtPath(): string {
let windows: Location = window.document.location as Location;
let curWwwPath: string = windows.href;
let pathName = windows.pathname;
let pos = curWwwPath.indexOf(pathName);
let localhostPaht = curWwwPath.substring(0, pos);
return localhostPaht;
}
/**
* 获取url参数部分
*/
public getUrlParams(): { [x: string]: string } {
let url = decodeURI(location.search); //获取url中"?"符后的字串
let theRequest;
if (url.indexOf("?") != -1) {
let str = url.substr(1);
let strs = str.split("&");
for (let i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
}
}
return theRequest;
}
/**
* 获取对应cookie值
* @param cookiename cookie键名称
*/
public getCookie(cookiename: string) {
var arrone = document.cookie.split(";");
for (let i = 0; i < arrone.length; i++) {
var arrtwo = arrone[i].split("=");
if (arrtwo[0] == cookiename) {
return arrtwo[1];
}
}
//否则返回0:没有找到对应的cookie
return "0";
}
}
export default Browser;
|
0ead075681b86de9f574a1a9b365528a482de3ae
|
TypeScript
|
rsksmart/rif-storage-pinner
|
/src/cli/db-migration.ts
| 2.5625
| 3
|
import fs from 'fs'
import path from 'path'
import { flags } from '@oclif/command'
import { OutputFlags } from '@oclif/parser'
import { loggingFactory } from '../logger'
import BaseCommand from '../utils'
import { Migration } from '../migrations'
const logger = loggingFactory('cli:db-migration')
const MigrationTemplate = `import Sequelize, { QueryInterface } from 'sequelize'
import { Sequelize as SequelizeTs } from 'sequelize-typescript'
export default {
// eslint-disable-next-line require-await
async up (queryInterface: QueryInterface, sequelize: SequelizeTs): Promise<void> {
return Promise.reject(Error('Not implemented'))
},
// eslint-disable-next-line require-await
async down (queryInterface: QueryInterface, sequelize: SequelizeTs): Promise<void> {
return Promise.reject(Error('Not implemented'))
}
}
`
export default class DbCommand extends BaseCommand {
static hidden: boolean
static flags = {
...BaseCommand.flags,
up: flags.boolean({
char: 'u',
description: 'Migrate DB',
exclusive: ['down', 'generate']
}),
down: flags.boolean({
char: 'd',
description: 'Undo db migration',
exclusive: ['up', 'generate']
}),
generate: flags.string({
char: 'd',
description: 'Generate migrations using template [--generate=migration_name]',
exclusive: ['up', 'down']
}),
to: flags.string({
char: 't',
description: 'Migrate to'
}),
migration: flags.string({
char: 'm',
description: 'Migration file',
multiple: true
})
}
static description = 'DB migration'
static examples = [
'$ rif-pinning db-migration --up',
'$ rif-pinning db-migration --down',
'$ rif-pinning db-migration --up --to 0-test',
'$ rif-pinning db-migration --up --migration 01-test --migration 02-test',
'$ rif-pinning db-migration --up --db ./test.sqlite --to 09-test',
'$ rif-pinning db-migration --down --db ./test.sqlite --to 09-test',
'$ rif-pinning db-migration --generate my_first_migration'
]
async migrate (migrator: Migration, migrations?: string[], options?: { to: string }): Promise<void> {
if (!(await migrator.pending()).length) {
this.log('No pending migrations found')
this.exit()
}
this.spinner.start('DB migration')
await migrator.up(options)
this.spinner.stop()
}
async undo (migrator: Migration, migrations?: string[], options?: { to: string }): Promise<void> {
if (!(await migrator.executed()).length) {
this.log('No executed migrations found')
this.exit()
}
this.spinner.start('Undo DB migration')
await migrator.down(options)
this.spinner.stop()
}
generateMigration (name: string): void {
const migrationsFolder = path.resolve(__dirname, '../migrations')
const scriptsFolder = path.resolve(__dirname, '../migrations/scripts')
const fileName = `./${Date.now()}-${name}.ts`
const filePath = path.resolve(scriptsFolder, fileName)
if (!fs.existsSync(migrationsFolder)) {
throw new Error('Migrations folder not found. Please run command from project root and make sure that you have \'migrations\' folder setup')
}
this.spinner.start(`Creating migration ${fileName}`)
if (!fs.existsSync(scriptsFolder)) {
fs.mkdirSync(scriptsFolder)
}
fs.writeFileSync(filePath, MigrationTemplate)
this.spinner.stop()
}
async run (): Promise<void> {
const { flags: originalFlags } = this.parse(DbCommand)
const flags = originalFlags as OutputFlags<typeof DbCommand.flags>
if (!flags.up && !flags.down && !flags.generate) throw new Error('One of \'--generate, --up, --down\' required')
if (!this.sequelize) {
throw new Error('DB not instantiated!')
}
const migrator = new Migration(this.sequelize)
if (flags.up) await this.migrate(migrator, flags.migration, flags)
if (flags.down) await this.undo(migrator, flags.migration, flags)
if (flags.generate) this.generateMigration(flags.generate)
this.exit()
}
}
|
6abbb56b83893276a1bae9d19ab74f6b7714acc2
|
TypeScript
|
HMSConnect/hms-widget-sdk
|
/app/reducers-redux/observation/observationHeartRateCard.reducer.ts
| 2.984375
| 3
|
type ObservationHeartRateCardType =
| 'INIT_PATIENT_SUMMARY'
| 'SET_STRUCTURE_OBSERVATION_HEART_RATE_CARD'
interface IObservationHeartRateCardAction {
type: ObservationHeartRateCardType
payload: any
}
export interface IObservationHeartRateCardStructure {
headerIconField: boolean
dateTimeField: boolean
}
export const initialObservationHeartRateCardStructure: IObservationHeartRateCardStructure = {
dateTimeField: true,
headerIconField: true,
}
export const observationHeartRateCardInitialState: any = {
structure: initialObservationHeartRateCardStructure,
}
const observationHeartRateCard = (
state = observationHeartRateCardInitialState,
action: IObservationHeartRateCardAction,
) => {
switch (action.type) {
case 'INIT_PATIENT_SUMMARY':
return {
...state,
...action.payload.observationHeartRateCard,
}
case 'SET_STRUCTURE_OBSERVATION_HEART_RATE_CARD':
return {
...state,
structure: {
...state.structure,
...action.payload,
},
}
default:
return state
}
}
export default observationHeartRateCard
|
ec42e430555c2557cc8653fe069d59f3c39298bf
|
TypeScript
|
stephen-ying/signalwire-js
|
/packages/web-api/src/rooms/createRoomFactory.ts
| 2.921875
| 3
|
import { HttpClient, RoomResponse } from '../types'
interface CreateRoomOptions {
name: string
displayName?: string
maxParticipants?: number
deleteOnEnd?: boolean
startsAt?: string
endsAt?: string
}
export type CreateRoom = (options: CreateRoomOptions) => Promise<RoomResponse>
type CreateRoomFactory = (client: HttpClient) => CreateRoom
export const createRoomFactory: CreateRoomFactory = (client) => async (
options
) => {
const {
name,
displayName: display_name,
maxParticipants: max_participants,
deleteOnEnd: delete_on_end,
startsAt: starts_at,
endsAt: ends_at,
} = options
const { body } = await client<RoomResponse>('video/rooms', {
method: 'POST',
body: {
name,
display_name,
max_participants,
delete_on_end,
starts_at,
ends_at,
},
})
return body
}
|
24c128d438f05b47c5bbd728dab91e433ef7e271
|
TypeScript
|
adam-stanek/chobot
|
/packages/chobot/src/utils/match.ts
| 3.09375
| 3
|
import { defaultFilter } from '../paramTypes/defaultFilter'
import { ParamDescriptor } from '../paramTypes/ParamDescriptor'
import { MatchingNode } from './MatchingNode'
export interface Match {
matchedLength: number
rank: number
params: { [k: string]: any }
}
// Matcher
export function match(
str: string,
matchingTree: MatchingNode[],
paramTypes: { [k: string]: ParamDescriptor } = {},
strIndex = 0,
treeIndex = 0,
rank = 0,
) {
var params = {} as { [k: string]: any }
var matches: Match[] = []
var initialStrIndex = strIndex
for (var i = treeIndex; i < matchingTree.length; i++) {
// Fixed string
if (matchingTree[i].s) {
// If string starts at the index we move the index by substring length
// If not we are in the dead end.
if (str.lastIndexOf(matchingTree[i].s!, strIndex) == strIndex) {
strIndex += matchingTree[i].s!.length
rank++
} else return matches
}
// Parameter
else if (matchingTree[i].p) {
// Try to apply parameter filter
const s = strIndex > 0 ? str.substring(strIndex) : str
let f = paramTypes[matchingTree[i].p!]
? paramTypes[matchingTree[i].p!].filter(s)
: defaultFilter({ matchedString: s, value: s })
// Is parameter valid?
// If so we move the index by matched length.
// If not we are in the dead end.
if (f) {
params[matchingTree[i].p!] = f.value
strIndex += f.matchedString.length
rank++
} else return matches
}
// Optional fragment
else if (matchingTree[i].o) {
// Try to match the optional subtree
let m = match(str, matchingTree[i].o!, paramTypes, strIndex, 0, rank)
// For each subtree match check if we can continue with it
for (var j = 0; j < m.length; j++) {
let params2 = Object.assign({}, params, m[j].params)
let m2 = match(
str,
matchingTree,
paramTypes,
strIndex + m[j].matchedLength,
i + 1,
m[j].rank,
)
for (var k = 0; k < m2.length; k++) {
matches.push({
matchedLength: m2[k].matchedLength + m[j].matchedLength + strIndex - initialStrIndex,
rank: m2[k].rank,
params: Object.assign({}, params2, m2[k].params),
})
}
}
}
}
// Only accept if we matched the whole dirname and not just part of it
if (
strIndex === initialStrIndex ||
strIndex === str.length ||
str[strIndex] === '/' ||
str[strIndex - 1] === '/'
) {
matches.push({
matchedLength: strIndex - initialStrIndex,
rank,
params,
})
}
return matches
}
|
2f9ede3f820aa83c9c11c0cdf1c2e343b64d8a95
|
TypeScript
|
invoke-ai/InvokeAI
|
/invokeai/frontend/web/src/common/util/randomInt.ts
| 2.71875
| 3
|
const randomInt = (min: number, max: number): number => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
export default randomInt;
|
a8295cde7e56f5e0df24fcd751b5c2b36b1eb79c
|
TypeScript
|
frydlewicz/AutoComplete
|
/public/js/jquery.autoComplete.ts
| 2.5625
| 3
|
declare const jQuery: any;
(($: any): void => {
if (typeof $ === 'undefined') {
throw new Error('No jQuery library found!');
}
const prefix = 'autoComplete';
const className = `${prefix}__list`;
const classNameItem = `${prefix}__list-item`;
const classNameActiveItem = `${prefix}__list-item--active`;
let counter = 0;
$.fn.autoComplete = function (search: any): void {
if (typeof this.val !== 'function') {
throw new Error('Invalid component used!');
}
++counter;
const self = $(this);
const idName = `${prefix}-${counter}__list`;
const $body = $('body');
const $list = $(`<div class="${className}" id="${idName}"></div>`);
let current: number = null;
const showList = (): void => {
const position = this.position();
$list.css('left', position.left);
$list.css('top', position.top + this.outerHeight() + 1);
$list.show();
};
const hideList = (): void => {
$list.hide();
current = null;
};
const isListHidden = (): boolean => $list.css('display') === 'none';
const clearList = (): void => $list.empty();
const getText = (): string => this.val().trim();
const completeList = (list: any): void => {
clearList();
for (const elem of list) {
const { display_text, output_text } = elem;
const boldText: string = getBoldText(display_text, getText());
const $elem = $(`<div class="${classNameItem}" data-output="${output_text}">${boldText}</div>`);
$list.append($elem);
}
showList();
};
const getBoldText = (text: string, sub: string): string => {
const pos: number = text.toLowerCase().indexOf(sub.toLowerCase());
const len: number = sub.length;
if (pos === -1) {
return text;
}
return text.substr(0, pos)
+ '<b>'
+ text.substr(pos, len)
+ '</b>'
+ text.substr(pos + len);
};
const changeText = (): void => {
const text: string = getText();
if (text === '') {
return clearList();
}
search(text, completeList);
};
const onKeyUp = (event: any): void => {
const key: string = event.key.toLowerCase();
if (key === 'escape' || key === 'esc') {
hideList();
} else if (key === 'arrowup') {
changeCurrent(-1);
} else if (key === 'arrowdown') {
changeCurrent(1);
} else if (key === 'enter') {
if (current !== null) {
self.val($list.find(`.${classNameItem}:eq(${current})`).data('output'));
}
hideList();
} else {
changeText();
}
};
const onClick = (): void => {
if ($(this).hasClass(classNameItem) && $(this).data('output')) {
return self.val($(this).data('output'));
}
hideList();
};
const changeCurrent = (increment: number): void => {
if (isListHidden()) {
return;
}
const $items = $list.find(`.${classNameItem}`);
const last: number = $items.length - 1;
if (current === null && increment > 0) {
current = 0;
} else if (current === null && increment < 0) {
current = last;
} else {
current += increment;
}
if (current > last) {
current = 0;
} else if (current < 0) {
current = last;
}
$items.removeClass(classNameActiveItem);
$list.find(`.${classNameItem}:eq(${current})`).addClass(classNameActiveItem);
};
this.on('keyup', onKeyUp);
$(document).on('click', '*', onClick);
$body.append($list);
};
})(jQuery);
|
c9ec111750527aa4e1fbe59555b518dc205310fd
|
TypeScript
|
flooper68/nestjs-playground
|
/src/cqrs/aggregate-root.ts
| 2.71875
| 3
|
import { IEvent } from './interfaces';
export abstract class AggregateRoot {
private _uncommittedEvents: IEvent[] = [];
dispatch<T extends IEvent>(event: T) {
this._uncommittedEvents.push(event);
}
getUncommittedEvents(): IEvent[] {
return this._uncommittedEvents;
}
}
|
775f72cf431b4d9c8e0c6a174122d170b943d63f
|
TypeScript
|
AndyRightNow/babel-plugin-transform-nej-amd
|
/src/helpers.ts
| 2.8125
| 3
|
import * as t from 'babel-types';
import { forOwn } from 'lodash';
export function createInjectedNejParamAssignment(varName: string, index: number): t.Statement {
let rightHandSide: t.FunctionExpression | t.ObjectExpression | t.ArrayExpression = t.objectExpression([]);
switch (index) {
// Injected function
case 2:
rightHandSide = t.functionExpression(undefined, [], t.blockStatement([]));
break;
// Injected array
case 3:
rightHandSide = t.arrayExpression([]);
break;
}
return t.expressionStatement(t.assignmentExpression('=', t.identifier(varName), rightHandSide));
}
export function transformArrowFunctionToFunction(
arrowFunction: t.ArrowFunctionExpression | t.FunctionExpression,
): t.FunctionExpression {
let functionBody: t.BlockStatement;
if (t.isFunctionExpression(arrowFunction)) {
return arrowFunction;
}
if (t.isExpression(arrowFunction.body)) {
functionBody = t.blockStatement([t.returnStatement(arrowFunction.body)]);
} else {
functionBody = arrowFunction.body;
}
return t.functionExpression(undefined, arrowFunction.params, functionBody);
}
export function isFunction(node: t.Node): node is t.FunctionExpression | t.ArrowFunctionExpression {
return t.isFunctionExpression(node) || t.isArrowFunctionExpression(node);
}
export function transformDependencyWithNejAliases(
dependencyDir: string,
nejAliases?: { [alias: string]: string },
): string {
if (!nejAliases) {
return dependencyDir;
}
forOwn(nejAliases, (mappedPath: string, alias: string) => {
const aliasRE = new RegExp(`(\{${alias}\})|(^${alias})(?:[\\\/]+)`);
dependencyDir = dependencyDir.replace(aliasRE, (matched: string, p1: string, p2: string) => {
if (p1) {
return matched.replace(p1, mappedPath);
} else if (p2) {
return matched.replace(p2, mappedPath);
} else {
return matched;
}
});
});
return dependencyDir.replace(/[\/\\]+/g, '/');
}
|
2ab66618011c66d3fbdff2acc827bf06a12e28e1
|
TypeScript
|
felipeleite11/theme-switcher-typescript
|
/src/utils/usePersistedState.ts
| 3.140625
| 3
|
import { useEffect, useState, Dispatch, SetStateAction } from 'react'
type Response<T> = [
T,
Dispatch<SetStateAction<T>>
]
function usePersistedState<T>(key: string, defaultValue: T): Response<T> {
const [state, setState] = useState(() => {
const storagedValue = localStorage.getItem(key)
if(storagedValue) {
return JSON.parse(storagedValue)
}
return defaultValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state))
}, [key, state])
return [state, setState]
}
export default usePersistedState
|
4428f049ae113ad43b676fe9f0fe65394bc2b8ea
|
TypeScript
|
zhikunmen/basketball
|
/src/sub_game/facebook/FacebookStorage.ts
| 2.546875
| 3
|
class FacebookStorage {
static highestScore: string = "highestScore";
static ownSkin: string = "ownSkin";
static usingSkin: string = "usingSkin";
static GAME_COIN: string = "gameCoin";
private static _instance: FacebookStorage;
public static getInstance(): FacebookStorage {
if (FacebookStorage._instance == null) {
FacebookStorage._instance = new FacebookStorage();
}
return FacebookStorage._instance;
}
loadItem(data: any, key: string, defaultValue: any) {
let itemValue = data[key];
if (itemValue != undefined) {
return itemValue;
}
else {
return defaultValue;
}
}
loadDataFormFB(keys: Array<string>, successCallback?: Function, failedCallback?: Function) {
if (!Facebook.IsApiSupport("player.getDataAsync")) {
return;
}
FBInstant.player
.getDataAsync(keys)
.then(function (data: Object) {
egret.log('data is loaded');
if (successCallback) {
successCallback(data);
}
//发送读取记录完成
this.fbStorageLoadFinish = true;
}.bind(this))
.catch(function (err) {
egret.error('failed : ' + err.code + " :: " + err.message);
if (failedCallback) {
failedCallback();
}
});
}
public saveDataToFB(data: Object, successCallback?: Function, failedCallback?: Function) {
if (!Facebook.IsApiSupport("player.setDataAsync")) {
return;
}
FBInstant.player.setDataAsync(data)
.then(function () {
egret.log('Data Presaved');
if (successCallback) {
successCallback();
}
}.bind(this))
.catch(function (err) {
egret.error('failed : ' + err.code + " :: " + err.message);
if (failedCallback) {
failedCallback();
}
});
}
flushData(successCallback?: Function, failedCallback?: Function) {
if (!Facebook.IsApiSupport("player.flushDataAsync")) {
return;
}
FBInstant.player.flushDataAsync()
.then(function () {
egret.log('Data persisted to FB!');
if (successCallback) {
successCallback();
}
}.bind(this))
.catch(function (err) {
egret.error('failed : ' + err.code + " :: " + err.message);
if (failedCallback) {
failedCallback();
}
});
}
}
|
6d58cb4d158d0cf95930ae419edfbf1417b55761
|
TypeScript
|
kornatskyi/authentication
|
/src/models/user.model.ts
| 2.78125
| 3
|
import { MysqlError } from "mysql";
import sql from "./db";
class User {
email: string;
name: string;
password: string;
constructor(email: string, name: string, password: string) {
this.email = email;
this.name = name;
this.password = password;
}
static create = (newUser: User, result: Function) => {
sql.query("INSERT INTO users SET ?", newUser, (err: Error, res: any) => {
if (err) {
console.log("Db error when creating new user: ", err);
result(err, null);
return;
}
console.log("Created user: ", { id: res.insertId, ...newUser });
result(null, { id: res.insertId, ...newUser });
});
};
static findById = (userId: number, result: Function) => {
sql.query(
`SELECT * FROM users WHERE id = ${userId}`,
(err: Error, res: any) => {
console.log(res);
if (err) {
console.log("Db error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found user: ", res[0]);
result(null, res[0]);
return;
}
// not found user with the id
result({ kind: "not_found" }, null);
}
);
};
// find user by email
static findByEmail = (email: string, result: Function) => {
sql.query(
`SELECT * FROM users WHERE email = '${email}'`,
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(err, null);
return;
}
if (res.length) {
result(null, res[0]);
return;
}
// not found user with the id
result({ kind: "not_found" }, null);
}
);
};
static getAll = (result: Function) => {
sql.query("SELECT * FROM users", (err: Error, res: any) => {
console.log("debug");
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
console.log("users: ", res);
result(null, res);
});
};
static updateById = (id: number, user: User, result: Function) => {
sql.query(
"UPDATE users SET email = ?, name = ? WHERE id = ?",
[user.email, user.name, id],
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found user with the id
result({ kind: "not_found" }, null);
return;
}
console.log("updated user: ", { id: id, ...user });
result(null, { id: id, ...user });
}
);
};
static updatePasswordByEmail = (
email: string,
password: string,
result: Function
) => {
sql.query(
"UPDATE users SET password = ? WHERE email = ?",
[password, email],
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found user with the email
result({ kind: "not_found" }, null);
return;
}
console.log("updated user password: ", { email: email });
result(null, { email: email });
}
);
};
static remove = (id: number, result: Function) => {
sql.query("DELETE FROM users WHERE id = ?", id, (err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found User with the id
result({ kind: "not_found" }, null);
return;
}
console.log("deleted user with id: ", id);
result(null, res);
});
};
static removeByEmail = (email: string, result: Function) => {
sql.query(
"DELETE FROM users WHERE email = ?",
email,
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found User with the id
result({ kind: "not_found" }, null);
return;
}
console.log("deleted user with email: ", email);
result(null, res);
}
);
};
static removeAll = (result: Function) => {
sql.query("DELETE FROM users", (err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(null, err);
return;
}
console.log(`deleted ${res.affectedRows} users`);
result(null, res);
});
};
static getEmailConfirmationStatus = (email: string, result: any) => {
sql.query(
`SELECT confirmed FROM users WHERE email = '${email}'`,
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log(`Email ${email} confirmation status is: `, res[0]);
result(null, res[0]);
return;
}
// not found user with the id
result({ kind: "not_found" }, null);
}
);
};
static confirmEmail = (email: string, result: any) => {
sql.query(
`UPDATE users SET confirmed = 1 WHERE email = '${email}'`,
(err: Error, res: any) => {
if (err) {
console.log("Db error: ", err);
result(err, null);
return;
}
console.log(res);
result(null, res);
}
);
};
static updateByEmail = (email: string, user: User, result: any) => {
sql.query(
`UPDATE users SET email = '${user.email}', name = '${user.name}', password = '${user.password}' WHERE email = '${email}'`,
(err: MysqlError, res: any) => {
if (err) {
console.log("Db error: ", err);
result(err, null);
return;
}
console.log(res);
result(null, res);
}
);
};
}
export default User;
|
ef389a438c7fa19d1d16c9b04a4a15febb14e15b
|
TypeScript
|
samuraimasa/nestJS
|
/src/tasks/task.entity.ts
| 2.5625
| 3
|
import {
BaseEntity,
BeforeInsert,
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
Generated,
IsNull,
ManyToOne,
Not,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { User } from '../auth/user.entity';
import { HashId } from '../utils/hash_id';
import { Todo } from './todo.entity';
export enum TaskStatus {
OPEN = 'OPEN',
IN_PROGRESS = 'IN_PROGRESS',
DONE = 'DONE',
}
@Entity()
export class Task extends BaseEntity {
@PrimaryGeneratedColumn({ type: 'bigint' })
readonly id: number;
@Column()
encryptedId: string;
@Column()
title: string;
@Column()
description: string;
@Column()
status: TaskStatus;
@CreateDateColumn()
readonly createdAt?: Date;
@UpdateDateColumn()
readonly updatedAt?: Date;
@DeleteDateColumn()
deletedAt?: Date;
@ManyToOne(() => User, (user) => user.tasks)
user: User;
@Column({ default: null })
userId: number;
@OneToMany(() => Todo, (todo) => todo.task)
todos: Todo[];
@BeforeInsert()
async generateEncryptedId() {
while (true) {
const encryptedId = HashId.gen();
const task = await Task.findOne({
where: { encryptedId },
withDeleted: true,
});
if (!task) {
this.encryptedId = encryptedId;
return;
}
}
}
}
|
7ad8497429e806b17ffcda6d11de75a342125c42
|
TypeScript
|
dariya-maslyukova/nestjs-angular
|
/client/src/app/models/products-query.model.ts
| 2.5625
| 3
|
import { BasicQueryModel } from './basic-query.model';
import { ProductsFilters } from '../interfaces/product/product-filters.interface';
export class ProductsQueryModel extends BasicQueryModel {
queryParams?: ProductsFilters = {};
constructor(params: any) {
super(params);
const attrs = [
'parentCategory',
'category',
'size',
'color'
];
attrs.forEach(attr => {
// All attrs from this model are strings
this.queryParams[attr] = typeof params[attr] === 'string' ? params[attr] : '';
});
}
}
|
ca0996875710b709363804c001443cabf976e3be
|
TypeScript
|
VagrantAI-c/ng-carousel-cdk
|
/projects/ng-carousel/src/lib/private/service/helpers/drag-offset/drag-offset-snapshot.spec.ts
| 2.625
| 3
|
import { CarouselAlignMode } from '../../../../carousel-align-mode';
import { CarouselWidthMode } from '../../../../carousel-width-mode';
import { dragOffsetSnapshot } from './drag-offset-snapshot';
describe('dragOffsetSnapshot test suite', () => {
// Imitate y = 2x function so we can predict results
const bezierFn = (x: number) => x / 2;
const invertedBezierFn = (x: number) => x * 2;
const maxOverscrollPercent = 20;
it('must add desired delta to looped carousel dragging right', () => {
const fromX = 30;
const toX = 40;
const offset = -5;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = true;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 120;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(5, 'incorrect modified offset');
});
it('must add desired delta to looped carousel dragging left', () => {
const fromX = 40;
const toX = 30;
const offset = -5;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = true;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 120;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-15, 'incorrect modified offset');
});
it('must travel from safe side to safe side', () => {
const fromX = 40;
const toX = 30;
const offset = -5;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 200;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-15, 'incorrect modified offset');
});
it('must travel from left safe zone to left overscroll while dragging to the right', () => {
const fromX = 40;
const toX = 51;
const offset = -5;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 200;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(0.6, 'incorrect modified offset');
});
it('must travel from right safe zone to right overscroll while dragging to the left', () => {
const fromX = 60;
const toX = 49;
const offset = -5;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 110;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-10.6, 'incorrect modified offset');
});
it('must travel from overscroll zone to safe zone with left direction', () => {
const fromX = 60;
const toX = 30;
const offset = 1;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 200;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-20, 'incorrect modified offset');
});
it('must travel from overscroll zone to safe zone with right direction', () => {
const fromX = 30;
const toX = 60;
const offset = -51;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 150;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-30, 'incorrect modified offset');
});
it('must travel from left overscroll to right overscroll', () => {
const fromX = 60;
const toX = 30;
const offset = 1;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 100;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-2, 'incorrect modified offset');
});
it('must travel from right overscroll to left overscroll', () => {
const fromX = 30;
const toX = 60;
const offset = -1;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const slideWidth = 10;
const slideSumWidth = 100;
const viewportWidth = 100;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(2, 'incorrect modified offset');
});
it('must travel from left overscroll to left overscroll', () => {
const fromX = 60;
const toX = 55;
const offset = 1;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 100;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(0.5, 'incorrect modified offset');
});
it('must travel from right overscroll to right overscroll', () => {
const fromX = 30;
const toX = 35;
const offset = -1;
const widthMode = CarouselWidthMode.PX;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 100;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-0.5, 'incorrect modified offset');
});
it('must calculate drag for centered carousel from safe zone with overscroll', () => {
const fromXPercents = 50;
const toXPercents = 100;
const viewportWidthInPx = 1400;
const fromX = viewportWidthInPx / 100 * fromXPercents;
const toX = viewportWidthInPx / 100 * toXPercents;
const offset = 40;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 30;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(49.5, 'incorrect offset');
});
it('must calculate for centered carousel from safe zone to overscroll zone', () => {
const fromX = 40;
const toX = 50;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 30;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(46, 'incorrect offset');
});
it('must calculate for centered carousel from safe zone to safe zone', () => {
const fromX = 40;
const toX = 30;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const slideWidth = 10;
const slideSumWidth = 30;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidth,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(35, 'incorrect offset');
});
it('must calculate correctly with percent carousel', () => {
const fromX = 800;
const toX = 1200;
const offset = 1;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 2000;
const slideWidth = 10;
const slideSumWidth = 200;
const initialX = 20; // 400 in pixels, 20 in percent: initialX always aligned to current width mode
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(3, 'incorrect modified offset');
});
it('should travel from left overscroll zone to left overscroll zone with dragging to the right', () => {
const fromX = 60;
const toX = 80;
const offset = 5;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 200;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(7, 'incorrect modified offset');
});
it('should calculate overscroll distance on unknown initialX with reaching drag border', () => {
const fromX = 60;
const toX = 280;
const offset = 5;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 200;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(10, 'incorrect modified offset');
});
it('should calculate for left-centered carousels with slide sum width lesser than viewport and positive offset', () => {
const fromX = 60;
const toX = 100;
const offset = 0;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 50;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(4, 'incorrect modified offset');
});
it('should calculate for left-centered carousels with slide sum width lesser than viewport and negative offset', () => {
const fromX = 100;
const toX = 60;
const offset = 0;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 50;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(-4, 'incorrect modified offset');
});
it('should calculate for left-centered carousels with slide sum width lesser than viewport with existing offset', () => {
const fromX = 60;
const toX = 100;
const offset = 1;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.LEFT;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 50;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(5, 'incorrect modified offset');
});
it('should calculate for centered carousels with slide sum width lesser than viewport and negative offset', () => {
const fromX = 100;
const toX = 60;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 10;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(41, 'incorrect modified offset');
});
it('should calculate for centered carousels with slide sum width lesser than viewport and positive offset', () => {
const fromX = 60;
const toX = 100;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 10;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(49, 'incorrect modified offset');
});
it('should avoid calculation when no offset present', () => {
const fromX = 2;
const toX = 2;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 10;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(45, 'incorrect modified offset');
});
it('should not amend offset when no bezier functions are present', () => {
const fromX = 2;
const toX = 20;
const offset = 45;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 10;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
maxOverscrollPercent,
null,
null,
);
expect(result).toBe(45, 'incorrect modified offset');
});
it('should not amend offset when overscroll value is not available', () => {
const fromX = 2;
const toX = 20;
const offset = 33;
const widthMode = CarouselWidthMode.PERCENT;
const alignMode = CarouselAlignMode.CENTER;
const shouldLoop = false;
const viewportWidth = 100;
const viewportWidthInPx = 100;
const slideWidth = 10;
const slideSumWidth = 10;
const result = dragOffsetSnapshot(
fromX,
toX,
offset,
widthMode,
alignMode,
shouldLoop,
viewportWidth,
viewportWidthInPx,
slideWidth,
slideSumWidth,
null,
bezierFn,
invertedBezierFn,
);
expect(result).toBe(33, 'incorrect modified offset');
});
});
|
ee2ce4df496349a3748a7d9b67e8352faca046ee
|
TypeScript
|
furkleindustries/twine-tree
|
/src/AbstractSyntaxTree/isAbstractSyntaxTree.ts
| 2.515625
| 3
|
import {
isAbstractSyntaxContent,
} from './isAbstractSyntaxContent';
import {
isProgram,
} from './isProgram';
import {
isStylesheet
} from './isStylesheet';
import {
TAbstractSyntaxTree,
} from './TAbstractSyntaxTree';
export function isAbstractSyntaxTree(maybe: any): maybe is TAbstractSyntaxTree {
return typeof maybe === 'object' &&
maybe &&
(isAbstractSyntaxContent(maybe) ||
isProgram(maybe) ||
isStylesheet(maybe));
}
export default isAbstractSyntaxTree;
|
8814e461de9529e0056578915fb83db1e48e1395
|
TypeScript
|
galganif/arcs
|
/src/runtime/test/manifest-parser-test.ts
| 2.765625
| 3
|
/**
* @license
* Copyright (c) 2017 Google Inc. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import {parse} from '../../gen/runtime/manifest-parser.js';
import {assert} from '../../platform/chai-web.js';
describe('manifest parser', () => {
it('parses an empy manifest', () => {
parse('');
});
it('parses a trivial recipe', () => {
parse(`recipe Recipe &tag1 &tag2`);
});
it('parses with indentation', () => {
parse(`
recipe Recipe`);
});
it('parses recipes that map handles', () => {
parse(`
recipe Thing
map #someTag
map 'some-id' #someTag`);
});
it('parses recipes with particles', () => {
parse(`
recipe Recipe
SomeParticle`);
});
it('parses recipes that connect particles to handles', () => {
parse(`
recipe Recipe
SomeParticle
a -> #something
b <- #somethingElse
* = #someOtherParticle`);
});
it('parses trivial particles', () => {
parse(`
particle SomeParticle`);
});
it('parses recipes that name handles and particles', () => {
parse(`
recipe Recipe
SomeParticle as thing
map #thing as anotherThing`);
});
it('parses manifests with comments', () => {
parse(`
// comment
recipe // comment
// comment
// comment
A//comment
// comment
// comment
B //comment
`);
});
it('parses recipes with recipe level connections', () => {
parse(`
recipe
X -> Y
X.a -> Y.a
&foo.bar -> &far.#bash #fash
a = b
a.a = b.b
X.a #tag <- a.y`);
});
it('parses manifests with stores', () => {
parse(`
schema Person
Text lastName
Text firstName
description \`person\`
plural \`people\`
value \`\${firstName} \${lastName}\`
store Store0 of [Person] in 'people.json'
description \`my store\`
store Store1 of Person 'some-id' @7 in 'person.json'
store Store2 of BigCollection<Person> in 'population.json'`);
});
it('fails to parse an argument list that use a reserved word as an identifier', () => {
try {
parse(`
particle MyParticle
in MyThing consume
out? BigCollection<MyThing> output`);
assert.fail('this parse should have failed, identifiers should not be reserved words!');
} catch (e) {
assert.include(e.message, 'Expected', `bad error: '${e}'`);
}
});
it('allows identifiers to start with reserved words', () => {
parse(`
particle MyParticle
in MyThing mapped
out? BigCollection<MyThing> import_export`);
});
it('allows reserved words for schema field names', () => {
// Test with a non-word char following the token
parse(`
schema Reserved
Text schema // comment`);
// Test with end-of-input following the token
parse(`
schema Reserved
URL map`);
});
it('allows reserved words for inline schema field names', () => {
parse(`
particle Foo
in A {Text handle} a
out B {Boolean import, Number particle} b`);
});
it('fails to parse a nonsense argument list', () => {
try {
parse(`
particle AParticle
Nonsense()`);
assert.fail('this parse should have failed, no nonsense!');
} catch (e) {
assert.include(e.message, 'N', 'bad error: '+e);
}
});
it('parses particles with optional handles', () => {
parse(`
particle MyParticle
in MyThing mandatory
in? MyThing optional1
out? [MyThing] optional2
out? BigCollection<MyThing> optional3`);
});
it('parses manifests with search', () => {
parse(`
recipe
search \`hello World!\`
`);
});
it('parses manifests with search and tokens', () => {
parse(`
recipe
search \`Hello dear world\`
tokens \`hello\` \`World\` // \`dear\`
`);
});
it('parses manifests particle verbs', () => {
parse(`
particle SomeParticle
in Energy energy
out Height height
modality dom`);
});
it('parses recipe with particle verbs', () => {
parse(`
recipe
&jump
* <- energy
* -> height`);
});
it('parses recipe with particle verb shorthand', () => {
parse(`
recipe
&jump
* <- energy
* <- height`);
});
it('parses inline schemas', () => {
parse(`
particle Foo
in MySchema {Text value} mySchema
`);
parse(`
particle Foo
in [MySchema {Text value}] mySchema
`);
parse(`
particle Foo
in [* {Text value, Number num}] anonSchema
`);
parse(`
particle Foo
in * {(Text or Number) value} union
`);
parse(`
particle Foo
in * {value} optionalType
`);
});
it('parses a schema with a bytes field', () => {
parse(`
schema Avatar
Text name
Bytes profileImage
`);
});
it('parses a schema with a reference field', () => {
parse(`
schema Product
Reference<Review> review
`);
});
it('parses a schema with a referenced inline schema', () => {
parse(`
schema Product
Reference<Review {Text reviewText}> review
`);
});
it('parses an inline schema with a reference to a schema', () => {
parse(`
particle Foo
in Product {Reference<Review> review} inReview
`);
});
it('parses an inline schema with a collection of references to schemas', () => {
parse(`
particle Foo
in Product {[Reference<Review>] review} inResult
`);
});
it('parses an inline schema with a referenced inline schema', () => {
parse(`
particle Foo
in Product {Reference<Review {Text reviewText}> review} inReview
`);
});
it('parses an inline schema with a collection of references to inline schemas', () => {
parse(`
particle Foo
in Product {[Reference<Review {Text reviewText}>] review} productReviews
`);
});
it('parses reference types', () => {
parse(`
particle Foo
in Reference<Foo> inRef
out Reference<Bar> outRef
`);
});
it('parses require section using local name', () => {
parse(`
recipe
require
handle as thing`);
});
it('parses require section using id', () => {
parse(`
recipe
require
handle 'an-id'`);
});
it('parses require section using local name and id', () => {
parse(`
recipe
require
handle as thing 'an-id'`);
});
it('parses require section using upperIdent', () => {
parse(`
recipe
require
handle Thing`);
});
it('parses require section with tags', () => {
parse(`
recipe
require
handle as thing Thing #tag1 #tag2`);
});
it('parses require section with handles, slots and particles', () => {
parse(`
recipe
require
handle as thing
slot as thing2
Particle
* <- thing
consume thing2
`);
});
it('parses handle creation using the handle keyword', () => {
parse(`
recipe
handle as h0
Particle
input <- h0
`);
});
});
|
d86851f9596d28169dde5e901faebd5a6190b39f
|
TypeScript
|
betagouv/delta-v
|
/front/src/stores/users/useCase.store.ts
| 2.625
| 3
|
/* eslint-disable import/no-cycle */
import jwtDecode from 'jwt-decode';
import { StoreSlice } from '../store';
import { USER_EMPTY_STATE } from './appState.store';
export interface UsersUseCaseSlice {
setUserFromToken: (accessToken: string, refreshToken: string) => Promise<void>;
clearUser: () => Promise<void>;
}
interface IAuthObject {
userId: string;
email: string;
}
export const createUseCaseUserSlice: StoreSlice<UsersUseCaseSlice> = (set) => ({
setUserFromToken: async (accessToken, refreshToken) => {
if (!accessToken || !refreshToken) {
return;
}
set((state: any) => {
const newState = { ...state };
const { exp } = jwtDecode<{ exp: number }>(refreshToken);
const { userId, email } = jwtDecode<IAuthObject>(accessToken);
newState.users.appState.user.userId = userId;
newState.users.appState.user.email = email;
newState.users.appState.user.isAgent = true;
newState.users.appState.user.exp = exp;
return newState;
});
},
clearUser: async () => {
set((state: any) => {
const newState = { ...state };
newState.users.appState = USER_EMPTY_STATE;
return newState;
});
},
});
|
d31255c2800bf426f29979b00299ea1c7d26acae
|
TypeScript
|
abhisekp/yup-phone
|
/src/yup-phone.ts
| 2.96875
| 3
|
import * as Yup from 'yup';
import gPhoneNumber from 'google-libphonenumber';
const phoneUtil = gPhoneNumber.PhoneNumberUtil.getInstance();
declare module 'yup' {
export interface StringSchema {
/**
* Check for phone number validity.
*
* @param {String} [countryCode=IN] The country code to check against.
* @param {Boolean} [strict=false] How strictly should it check.
* @param {String} [errorMessage=DEFAULT_MESSAGE] The error message to return if the validation fails.
*/
phone(
countryCode?: string,
strict?: boolean,
errorMessage?: string
): StringSchema;
}
}
const YUP_PHONE_METHOD = 'phone';
const CLDR_REGION_CODE_SIZE = 2;
const isValidCountryCode = (countryCode: any): boolean =>
typeof countryCode === 'string' &&
countryCode.length === CLDR_REGION_CODE_SIZE;
Yup.addMethod(Yup.string, YUP_PHONE_METHOD, function yupPhone(
countryCode?: string,
strict: boolean = false,
errorMessage: string = ''
) {
const errMsg =
typeof errorMessage === 'string' && errorMessage
? errorMessage
: isValidCountryCode(countryCode)
? `\${path} must be a valid phone number for region ${countryCode}`
: '${path} must be a valid phone number.';
// @ts-ignore
return this.test(YUP_PHONE_METHOD, errMsg, (value: string) => {
if (!isValidCountryCode(countryCode)) {
// if not valid countryCode, then set default country to India (IN)
countryCode = 'IN';
strict = false;
}
try {
const phoneNumber = phoneUtil.parseAndKeepRawInput(value, countryCode);
if (!phoneUtil.isPossibleNumber(phoneNumber)) {
return false;
}
const regionCodeFromPhoneNumber = phoneUtil.getRegionCodeForNumber(
phoneNumber
);
/* check if the countryCode provided should be used as
default country code or strictly followed
*/
return strict
? phoneUtil.isValidNumberForRegion(phoneNumber, countryCode)
: phoneUtil.isValidNumberForRegion(
phoneNumber,
regionCodeFromPhoneNumber
);
} catch {
return false;
}
});
});
|
06613d1bed379df72d9ae30ce6d6edd3a0f6377a
|
TypeScript
|
chrsep/statmin
|
/src/redux/user/userAction.ts
| 2.5625
| 3
|
import { ActionsUnion, createAction } from "../actionHelpers"
export const SET_TOKEN_USER = "SET_TOKEN_USER"
export const LOGIN_USER = "LOGIN_USER"
export const UserActions = {
login: () => createAction(LOGIN_USER),
setAcessToken: (token: string) => createAction(SET_TOKEN_USER, token)
}
export type UserActions = ActionsUnion<typeof UserActions>
|
cb81d8496dcfe039bf81910e35ba4174a3ada871
|
TypeScript
|
standardgalactic/svg
|
/src/demo/rotating.ts
| 2.59375
| 3
|
import { Canvas } from '../lib/svg/canvas';
import { Line } from '../lib/svg/line';
import { Color } from '../lib/color/color';
import { Shape } from './shape';
import { TweenConfig } from '../lib/tween/tween';
import { Tweens } from '../lib/tween/tweens';
import { Back, Bounce, Circ, Quad } from '../lib/tween/ease';
import { XY, Point } from '../lib/ds/xy';
import { TemplateFactory, Template, controls, blob, square, pin, eye, pie, bullet } from './templates';
import { PathConfig } from '../lib/svg/path';
import { Updater } from './updater';
export interface FactoryConfig {
factory: TemplateFactory,
color: Color,
}
export interface RotatingConfig {
center: XY,
size: number,
duration: number,
delay: number,
tweens: Tweens,
tweenConfig: TweenConfig,
factories: FactoryConfig[],
strokeConfig: PathConfig,
fillConfig: PathConfig,
}
export class Rotating {
constructor(
readonly canvas: Canvas,
readonly config: RotatingConfig,
) {
const template = blob(config.center, config.size);
canvas.append(new Shape(
config.fillConfig,
template,
));
new TweenController(
config.factories,
config,
template,
).start(square);
}
}
class TweenController {
private readonly updater: Updater;
private lastCalled: TemplateFactory;
private queue: FactoryConfig[];
constructor(
readonly templates: FactoryConfig[],
readonly config: RotatingConfig,
readonly template: Template,
) {
this.updater = new Updater(config.tweens, config.tweenConfig, template);
this.queue = shuffle(templates);
}
start(factory: TemplateFactory): this {
this.lastCalled = factory;
this.tweenShape(factory);
setInterval(() => this.iterate(), this.config.duration + this.config.delay);
return this;
}
private iterate() {
const { factory, color } = this.getFactory();
factory && this.tweenShape(factory);
color && this.tweenColor(color);
this.lastCalled = factory;
}
private getFactory(): FactoryConfig {
if (!this.queue.length) this.queue = shuffle(this.templates);
return this.queue.shift();
}
private tweenShape(fn: (center: XY, size: number) => Template) {
const update = fn(this.config.center, this.config.size);
this.updater.update(update);
}
private tweenColor(color: Color) {
this.config.tweens.tween(
this.config.fillConfig.fill,
color,
this.config.duration,
);
}
}
function shuffle<T>(list: T[]): T[] {
const output: T[] = [];
const input = list.concat();
while (input.length) {
const item = input.splice(Math.floor(Math.random() * input.length), 1)[0];
output.push(item);
}
return output;
}
|
f958d9fc41c5e54b02fae319fdfe9fb1ac7cc68d
|
TypeScript
|
maxint137/KanjiNav
|
/views/scripts/localDictionary.ts
| 2.65625
| 3
|
import { DbKanji, DbWord, IJapaneseDictionary, JlptLevel } from "./knApi";
import { kanjis, words } from "./data";
export class LocalDictionary implements IJapaneseDictionary {
private static loadKanji: (word: string) => any = (word: string) => {
return kanjis.filter((k: any) => 0 <= word.indexOf(k.character))
.map((k: any) => {
const kWords = k.words.map((kw: any) =>
words.filter((w: any) =>
// tslint:disable-next-line:no-string-literal
w["_id"]["$oid"] === kw["$oid"])[0]);
return {
JLPT: parseInt(k.JLPT, 10),
__v: 1,
// tslint:disable-next-line:no-string-literal
_id: "58883418e46ff154dc7-" + k["_id"]["$oid"],
character: k.character,
words: kWords,
};
});
}
public parseJlpt(jlpt: string): JlptLevel {
switch (parseInt(jlpt, 10)) {
default:
case 0: return 0;
case 1: return 1;
case 2: return 2;
case 3: return 3;
case 4: return 4;
case 5: return 5;
}
}
public lookupKanji(id: string): Promise<DbKanji> {
const promise: Promise<DbKanji> = new Promise<DbKanji>((resolve, reject) => {
const kanji = kanjis.filter((k: any) => k.character === id)[0];
if (!kanji) {
return reject(`Kanji not found for id=${id}`);
}
const kanjiApiRes: DbKanji = {
JLPT: this.parseJlpt(kanji.JLPT),
// tslint:disable-next-line:no-string-literal
character: kanji.character,
// tslint:disable-next-line:no-string-literal
dbId: "58883418e46ff154dc7-" + kanji["_id"]["$oid"],
english: kanji.english,
kunyomi: kanji.kunyomi,
onyomi: kanji.onyomi,
words: LocalDictionary.loadKanji(id)[0].words,
};
setTimeout(() => resolve(kanjiApiRes), 137);
});
return promise;
}
public lookupWord(id: string): Promise<DbWord> {
const promise: Promise<DbWord> = new Promise((resolve, reject) => {
const word = words.filter((w: any) => w.word === id)[0];
if (!word) {
return reject(`Word not found for id=${id}`);
}
const wordApiRes: DbWord = {
JLPT: this.parseJlpt(word.JLPT),
// tslint:disable-next-line:no-string-literal
dbId: "5882353f4df6c031640-" + word["_id"]["$oid"],
english: word.english,
hiragana: word.hiragana,
kanjis: LocalDictionary.loadKanji(word.word),
word: word.word,
};
setTimeout(() => resolve(wordApiRes), 137);
});
return promise;
}
}
export let Dictionary: IJapaneseDictionary = new LocalDictionary();
|
1a7f06f416eb37c1c0355d8ebde17631a45a8b03
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/browser/client-eventbridge-browser/types/_BatchArrayProperties.ts
| 3
| 3
|
/**
* <p>The array properties for the submitted job, such as the size of the array. The array size can be between 2 and 10,000. If you specify array properties for a job, it becomes an array job. This parameter is used only if the target is an AWS Batch job.</p>
*/
export interface _BatchArrayProperties {
/**
* <p>The size of the array, if this is an array batch job. Valid values are integers between 2 and 10,000.</p>
*/
Size?: number;
}
export type _UnmarshalledBatchArrayProperties = _BatchArrayProperties;
|
82ebcc1b5e4e321d8755f996a0e159a110acaedc
|
TypeScript
|
riccardo-gallini/Screens
|
/Screens.Hosting.WebTerm/wwwroot/scripts/terminal.ts
| 2.875
| 3
|
class Terminal
{
conn: any; //signalR connection that receives updates from server
termControl: HTMLElement; //term dom element used for display
height: number;
width: number;
constructor(conn, term: HTMLElement)
{
this.conn = conn;
this.conn.on("Beep", ()=>this.Beep);
this.conn.on("Clear", ()=>this.Clear);
this.conn.on("HideCursor", ()=>this.HideCursor);
this.conn.on("SetScreenSize", (w,h)=>this.SetScreenSize(w,h));
this.conn.on("ShowCursor", ()=>this.ShowCursor);
this.conn.on("SetCursorPosition", (x,y)=>this.SetCursorPosition(x,y));
this.conn.on("SubmitChanges", (changes)=>this.SubmitChanges(changes));
this.termControl = term;
this.termControl.addEventListener("keydown", (evt)=>this.KeyDown(evt));
}
initTerm()
{
this.termControl.innerHTML = "";
for (let i = 0; i < this.height; i++)
{
let lineSpan = document.createElement("span");
lineSpan.id = "L" + i;
lineSpan.className = "term_line";
lineSpan.appendChild(this.emptyText(this.width));
this.termControl.appendChild(lineSpan);
let cr = document.createTextNode("\n");
this.termControl.appendChild(cr);
}
};
emptyText(n: number): Node
{
let emp = "";
for (let j = 0; j < n; j++)
emp += " ";
let emptyLine = document.createTextNode(emp);
return emptyLine;
}
//expect all spans are consecutive
drawLine(line: ChangedLine)
{
let lineSpan = document.getElementById("L" + line.y);
lineSpan.innerHTML = "";
for (let span of line.spans)
{
let hs = document.createElement("span");
hs.style.backgroundColor = get_color(span.backColor);
hs.style.color = get_color(span.foreColor);
let t = document.createTextNode(span.text);
hs.appendChild(t);
lineSpan.appendChild(hs);
}
}
KeyDown(evt: KeyboardEvent)
{
this.conn.send("SendKey", evt.key);
}
Beep()
{
}
Clear()
{
this.initTerm();
}
HideCursor()
{
}
SetScreenSize(w: number, h: number)
{
this.height = h;
this.width = w;
this.initTerm();
}
ShowCursor()
{
}
SetCursorPosition(x: number, y: number)
{
}
SubmitChanges(changes: TerminalChanges)
{
for (let changed_line of changes.lines)
{
this.drawLine(changed_line);
}
}
}
class TerminalChanges
{
public lines: Array<ChangedLine>;
}
class ChangedLine
{
public spans: Array<Span>;
public y: number;
}
class Span
{
public text: string;
public foreColor: ConsoleColor;
public backColor: ConsoleColor;
public x: number;
}
function get_color(inp: ConsoleColor) {
switch (inp)
{
case ConsoleColor.Black:
return '#000000';
case ConsoleColor.DarkBlue:
return '#000080';
case ConsoleColor.DarkGreen:
return '#008000';
case ConsoleColor.DarkCyan:
return '#008080';
case ConsoleColor.DarkRed:
return '#800000';
case ConsoleColor.DarkMagenta:
return '#800080';
case ConsoleColor.DarkYellow:
return '#808000';
case ConsoleColor.Gray:
return '#C0C0C0';
case ConsoleColor.DarkGray:
return '#808080';
case ConsoleColor.Blue:
return '#0000FF';
case ConsoleColor.Green:
return '#00FF00';
case ConsoleColor.Cyan:
return '#00FFFF';
case ConsoleColor.Red:
return '#FF0000';
case ConsoleColor.Magenta:
return '#FF00FF';
case ConsoleColor.Yellow:
return '#FFFF00';
case ConsoleColor.White:
return '#FFFFFF';
default:
return '#000000';
}
}
enum ConsoleColor
{
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkCyan = 3,
DarkRed = 4,
DarkMagenta = 5,
DarkYellow = 6,
Gray = 7,
DarkGray = 8,
Blue = 9,
Green = 10,
Cyan = 11,
Red = 12,
Magenta = 13,
Yellow = 14,
White = 15
}
function setup()
{
var termControl = document.getElementById("term");
var connection = new signalR.HubConnection("/hubs/term");
var Term = new Terminal(connection, termControl);
connection.start();
}
//you start here
declare var signalR: any;
setup();
|
f236214359f8f000e245363878e3ad37f1fe8267
|
TypeScript
|
HubSpot/hubspot-api-nodejs
|
/codegen/automation/actions/models/InputFieldDefinition.ts
| 2.546875
| 3
|
/**
* Custom Workflow Actions
* Create custom workflow actions
*
* OpenAPI spec version: v4
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { FieldTypeDefinition } from '../models/FieldTypeDefinition';
/**
* Configuration for an input field on the custom action
*/
export class InputFieldDefinition {
'typeDefinition': FieldTypeDefinition;
/**
* Controls what kind of input a customer can use to specify the field value. Must contain exactly one of `STATIC_VALUE` or `OBJECT_PROPERTY`. If `STATIC_VALUE`, the customer will be able to choose a value when configuring the custom action; if `OBJECT_PROPERTY`, the customer will be able to choose a property from the enrolled workflow object that the field value will be copied from. In the future we may support more than one input control type here.
*/
'supportedValueTypes'?: Array<InputFieldDefinitionSupportedValueTypesEnum>;
/**
* Whether the field is required for the custom action to be valid
*/
'isRequired': boolean;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "typeDefinition",
"baseName": "typeDefinition",
"type": "FieldTypeDefinition",
"format": ""
},
{
"name": "supportedValueTypes",
"baseName": "supportedValueTypes",
"type": "Array<InputFieldDefinitionSupportedValueTypesEnum>",
"format": ""
},
{
"name": "isRequired",
"baseName": "isRequired",
"type": "boolean",
"format": ""
} ];
static getAttributeTypeMap() {
return InputFieldDefinition.attributeTypeMap;
}
public constructor() {
}
}
export type InputFieldDefinitionSupportedValueTypesEnum = "STATIC_VALUE" | "OBJECT_PROPERTY" | "FIELD_DATA" ;
|
4a23bd3dd2e598168861b51a8402976f58deda9b
|
TypeScript
|
StevenLOL/VisualDL
|
/frontend/packages/mock/data/text/text.ts
| 2.5625
| 3
|
/**
* Copyright 2020 Baidu Inc. 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 {Request, Response} from 'express';
const texts = [
'不要以为抹消过去,重新来过,即可发生什么改变',
'这只是谁也不会伤害到的,温柔的谎言。虽然听上去不时闪现着希望,实际上却是迂回地饱含着绝望的说法。可能做不到 这件事本身说话人自己也了然于心,而向众人留有回旋的余地。',
'自称理解了能教他人什么的都太狂妄了 自以为理解了是罪与恶 虽然如此 我们不得不自欺欺人地活下去',
'自己的过去会被当做笑话或者捏他的形式,被他人随随便便的共有化。最终只会被他和她们当做方便好用的交流素材, 快乐的使用着',
'怎么办?没怎么办。只想就这件事随便说说而已。就好比,在电视里看到战争和贫困的场景,只能一边说着“真是可怜啊 ”“真是不得了啊”“这是我们无能为力的事情啊”,而同时我们在舒适的屋子里吃着好吃的晚饭的事情也没有改变。 我们无法在此之后着手做些什么,到最后不过只能想到“要对目前为止自己的幸福心怀感激”这种程度的事',
'世上没有像一个模子刻出来样的恶人哦 平时大家都是善人 至少大家都是普通人 但是 一到紧要关头 就会突然变成恶人 所以很 可怕 因为不能大意 人不可轻信',
'人类要是遇到真心害怕的事 完全不会在意别人 就算牺牲周围的人也要获救 只要暴露出这份丑陋的嘴脸 就再也无法好好相处了 不能逃避只是强身的想法 错的并不会总是自己 社会上 人世间 身边 总会有人做错 自己可以改变它 这只是顺应了这个垃圾一 般的冷酷且残酷的世界 承认自己的失败并顺从的行为 只是用漂亮话装饰起来 连自己都要欺骗罢了'
];
export default async (req: Request, res: Response) => {
const index = (+req.query.index ?? 0) % texts.length;
res.setHeader('Content-Type', 'text/plain');
return texts[index];
};
|
9d62dd70a232ee730aeb7ff4a32a765b07b97c1f
|
TypeScript
|
jgke/fgj21
|
/front/src/morning.ts
| 2.96875
| 3
|
import { distance } from './distance';
import { hideDrunk } from './drunkCanvas';
function h2(text: string) {
const elem = document.createElement("h2");
elem.textContent = text;
return elem;
}
function span(text: string) {
const elem = document.createElement("span");
elem.textContent = text;
return elem;
}
function clamp(a: number, x: number, b: number) {
if (a > x) {
return a;
} else if (b < x) {
return b;
}
return x;
}
function swapNodes(node: HTMLElement, beforeIndex: number, afterIndex: number) {
node.parentNode.insertBefore(
node.parentNode.children[clamp(0, afterIndex, node.parentNode.children.length - 1)],
node.parentNode.children[clamp(0, beforeIndex, node.parentNode.children.length - 1)])
};
function shuffle<T>(arr: T[]) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
export function initMorning(history: string[], initNext: (percentage: number) => void) {
hideDrunk();
let start = history[0];
let end = history[history.length - 1];
let middle = history.slice(1, history.length - 1);
let scrambledMiddle = shuffle([...middle]);
const container = document.createElement("div");
container.id = "retraceList"
container.appendChild(h2("Retrace your steps!"));
container.appendChild(span(`You started from ${start}, but what happened then?`));
const nl = document.createElement("ol");
scrambledMiddle.forEach((element, i) => {
const li = document.createElement("li");
const up = document.createElement("button");
up.textContent = "Move up";
up.className = "moveUp";
up.onclick = () => {
const index = [...li.parentNode.childNodes as any as HTMLElement[]].indexOf(li);
swapNodes(li, index - 1, index);
}
const down = document.createElement("button");
down.textContent = "Move down";
down.className = "moveDown";
down.onclick = () => {
const index = [...li.parentNode.childNodes as any as HTMLElement[]].indexOf(li);
swapNodes(li, index, index + 1);
}
li.appendChild(span(`${element}`));
li.appendChild(up);
li.appendChild(down);
nl.appendChild(li);
});
container.appendChild(nl);
container.appendChild(span(`Finally you end up at ${end}`));
let cont = false;
const continueButton = document.createElement("button");
continueButton.id = "continueButton";
continueButton.textContent = "Continue";
continueButton.onclick = () => { cont = true; };
container.appendChild(continueButton);
document.body.appendChild(container);
return (delta: number) => {
if (cont) {
let options = new Set(history);
let indices = {};
let index = 0;
options.forEach(key => {
indices[key] = index;
index += 1;
});
let answers = [...nl.childNodes as any as HTMLElement[]].map(elem => elem.firstChild.textContent);
console.log(answers)
console.log(middle)
console.log(scrambledMiddle)
const dist = distance(
answers.map(key => indices[key]),
middle.map(key => indices[key])
);
const percentage = (answers.length - dist) / answers.length;
document.body.removeChild(container);
const secondContainer = document.createElement("div");
secondContainer.id = "retraceList"
const continueButton = document.createElement("button");
continueButton.id = "continueButton";
continueButton.textContent = `You got ${Math.round(100 * percentage)}% correct`;
continueButton.onclick = () => {
document.body.removeChild(secondContainer);
initNext(Math.round(100 * percentage));
};
secondContainer.appendChild(continueButton);
document.body.appendChild(secondContainer);
cont = false;
}
};
}
|
77e22b6a6f2ee2b7cb404c54d063024d5dcb451f
|
TypeScript
|
yadavsarika93/News-Widget
|
/src/app/data.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Inews } from './inews';
import { mergeMap, groupBy, reduce } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService
{
public article :object;
private _url='https://newsapi.org/v2/top-headlines?language=en&apiKey=d948c11e91b04de9bbcd5bb0065a395c';
private apiKey='d948c11e91b04de9bbcd5bb0065a395c'
constructor(private http: HttpClient) { }
getinfo():Observable<Inews[]>
{
this.article=this.http.get<Inews[]>(this._url)
/* to convert the json object */
// const values = Object.keys(this.article).map(it => this.article[it])
// console.log("Inside service data" +values)
// //for returning data from API
return this.http.get<Inews[]>(this._url);
}
}
|
97fb947643f00526bd6a74b44ddf3a3a9565dacc
|
TypeScript
|
lambdulus/core
|
/src/lexer/errors.ts
| 3.0625
| 3
|
import { PositionRecord } from "./position"
export class InvalidIdentifier extends Error {
constructor (
public readonly value : string,
public readonly position : PositionRecord,
) { super() }
}
export class InvalidNumber extends Error {
constructor (
public readonly value : string,
public readonly position : PositionRecord
) { super() }
}
export class InvalidOperator extends Error {
constructor (
public readonly value : string,
public readonly position : PositionRecord
) { super() }
}
export class InvalidCharacter extends Error {
constructor (
public readonly value : string,
public readonly position : PositionRecord
) { super() }
}
export function hintOperator (error : InvalidOperator, operators : Array<string>) : string {
const { value : invalid } = error
const relevant : Array<string> = operators.filter(
(operator) =>
operator.indexOf(invalid) !== -1
||
invalid.indexOf(operator) !== -1
)
if ( ! relevant.length) {
return ''
}
return (
`Hint: Did you mean to write one of these?
${ relevant.map((operator) => `${ operator }\n`) }`
)
}
|
fd45b6179fda545d1f1336744edf0a474395e167
|
TypeScript
|
fogre/TypeScript
|
/Patientor/backend/src/routes/patients.ts
| 2.578125
| 3
|
import express from 'express';
import patientService from '../services/patientService';
const router = express.Router();
router.get('/', (_req, res) => {
res.json(patientService.getNonSensPatients());
});
router.get('/:id', (req, res) => {
res.json(patientService.getPatient(req.params.id));
});
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
router.post('/', (req, res) => {
const {
name,
dateOfBirth,
ssn,
gender,
occupation
} = req.body;
const newPatient = patientService.addPatient({
name, dateOfBirth, ssn, gender, occupation
});
res.json(newPatient);
});
router.post('/:id/entries', (req, res) => {
const {
//basefields
description,
date,
specialist,
diagnosisCodes,
type,
//occupational
employerName,
sickLeave,
//Hospital
discharge,
//healtcheck
healthCheckRating
} = req.body;
const newEntry = patientService.addEntry({
//basefields
description,
date,
specialist,
diagnosisCodes,
type,
//occupational
employerName,
sickLeave,
//Hospital
discharge,
//healtcheck
healthCheckRating
}, req.params.id);
res.json(newEntry);
});
export default router;
|
47f195297b4da05b59be0302823695c2640aee33
|
TypeScript
|
bugzpodder/ui-lib
|
/src/utils/url-utils/url-util-get-query.spec.ts
| 2.53125
| 3
|
import { getQuery } from "./url-util";
describe("getQuery", () => {
it("handles no search query", () => {
expect(getQuery()).toEqual({});
});
it("handles props with no location", () => {
expect(getQuery({})).toEqual({});
});
it("handles props with location but no location", () => {
const props = {
location: {},
};
expect(getQuery(props)).toEqual({});
});
it("handles props with location with pathname, but no search", () => {
const props = {
location: {
pathname: "/some/route",
},
};
expect(getQuery(props)).toEqual({});
});
it("handles props with location with pathname, and empty search", () => {
const props = {
location: {
pathname: "/some/route",
search: "",
},
};
expect(getQuery(props)).toEqual({});
});
it("handles search query", () => {
const props = {
location: {
pathname: "/some/route",
search: "?someQuery=5&anotherQuery=abc",
},
};
expect(getQuery(props)).toEqual({ someQuery: "5", anotherQuery: "abc" });
});
});
|
da41cc7ae906f30f941a9d70fd6d24497b34b498
|
TypeScript
|
meirkr/angular2Labs
|
/step6.1/src/app/common/ellipsis.pipe.ts
| 2.90625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: "ellipsis"
})
export class EllipsisPipe implements PipeTransform {
// adds ... if the string length > lettersLength
transform(val:string, lettersLength:number=10) {
return val.length > lettersLength ? val.substring(0, lettersLength) + '...': val;
}
}
|
6e330e641184caed02d8ff13dd09869757a0faaa
|
TypeScript
|
mschilling/chrome-developers-assistant
|
/functions/src/services/people-service.ts
| 2.859375
| 3
|
import { Person } from "../models/person";
import { CoreService } from "./abstract-service";
import { FirestoreCollections } from "../enums/firestore-collections";
import { GenericCard } from "../models/card";
export interface IPeopleService {
getPeople(limit?: number): Promise<Person[]>;
getPerson(id: string): Promise<Person>;
}
export class PeopleService extends CoreService implements IPeopleService {
constructor(db: any) {
super(db);
}
async getPeople(limit: number = 10): Promise<Person[]> {
const query: any = this.db.collection(FirestoreCollections.People);
return query
.orderBy('rank', 'desc')
.limit(limit)
.get()
.then(snapshot => this.wrapAll<Person>(snapshot));
}
async getPerson(id: string): Promise<Person> {
if(!id) {
return null;
}
console.log('getPerson ' + id);
const query: any = this.db.collection(FirestoreCollections.People);
return query
.doc(id)
.get()
.then(snapshot => {
return snapshot.data();
});
}
}
export class PeopleServiceExt {
static asCards(items: Person[]): GenericCard[] {
if (items === null) {
console.log("items is null");
return [];
}
return items.map(p => PeopleServiceExt.asCard(p));
}
static asCard(item: Person): GenericCard {
const card = new GenericCard();
card._id = item.id;
card.title = `${item.first_name} ${item.last_name}`;
card.description = item.short_bio || item.bio || "n.a.";
card.imageUrl = item.pictureUrl || "http://lorempixel.com/200/400";
card.imageAlt = card.title;
card.buttonUrl = item.homepage;
card.buttonTitle = "Visit homepage";
card._optionType = 'person#name'
card._optionValue = card.title;
return card;
}
}
|
b597dc8da80ffdc7dafbd71d02cd1a32bf3932eb
|
TypeScript
|
AmadeusITGroup/xjs
|
/src/pre-processors/md.ts
| 2.578125
| 3
|
import { XjsParamHost, XjsParamDictionary, XjsPreProcessorCtxt, XjsCData } from './../xjs/types';
import marked from 'marked';
import { createElement, createParam, addParam, XjsParserContext, parse } from '../xjs/parser';
const U = undefined;
const RX_S_QUOTE = /\&\#39;/g,
RX_BANG = /\!/g,
RX_SLASH = /\\\//g, // forward slashes must be encoded like \/ in markdown content
RX_LT = /\</g,
RX_GT = /\>/g,
RX_AMP = /\&/g,
RX_QUOT = /\"/g,
RX_CB_OPEN = /\{/g,
RX_CB_CLOSE = /\}/g,
RX_NBSP = /\ /g,
RX_DOLLAR = /\$/g,
RX_CR = /\n/,
RX_START_SPACES = /^(\s+)/;
export function md() {
return {
async process(target: XjsParamHost, params: XjsParamDictionary, ctxt: XjsPreProcessorCtxt) {
if (target.kind !== "#cdata") {
ctxt.error("Pre-processor can only run on <!cdata> elements");
}
const classParam = params["class"] || params["$$default"];
let classValue = "md";
if (classParam) {
classValue = "md " + (classParam.value || "");
}
// replace the cdata by a div element
const p = ctxt.parent,
content = p!.content!,
idx = content.indexOf(target as any),
mdText = removeStartSpaces((target as XjsCData).text);
if (idx === -1) {
// fwk error - should not occur
ctxt.error("Unexpected error: cdata not found in parent element");
}
target = createElement("div"); // could also be createFragment
addParam(createParam("class", classValue), target);
content.splice(idx, 1, target);
// generate markdown and parse resulting html
try {
marked.setOptions({
gfm: true,
breaks: false,
sanitize: false,
smartLists: false,
smartypants: false,
xhtml: true
});
const mdHTML = marked(mdText)
.replace(RX_S_QUOTE, "'")
.replace(RX_BANG, "!!")
.replace(RX_LT, "!<")
.replace(RX_GT, "!>")
.replace(RX_AMP, "&")
.replace(RX_QUOT, "\"")
.replace(RX_SLASH, "!/")
.replace(RX_CB_OPEN, "!{")
.replace(RX_CB_CLOSE, "!}")
.replace(RX_NBSP, "!s")
.replace(RX_DOLLAR, "!$");
// parse the generated HTML
let fragment = await parse(mdHTML, {
fileId: "[@@md inline HTML]",
templateType: "$fragment"
});
// move generated fragment content to the target element
target.content = fragment.content;
fragment.content = U;
} catch (ex) {
let msg = ex.message || ex;
if (msg.match(/^XJS\:/)) {
// error was triggered through context.error()
throw ex;
} else {
ctxt.error(msg);
}
}
}
}
}
function removeStartSpaces(text: string) {
const arr = text.split(RX_CR);
if (arr.length > 1) {
if (arr[1].match(RX_START_SPACES)) {
const startSpaces = RegExp.$1, startLength = startSpaces.length;
let s: string;
for (let i = 0; arr.length > i; i++) {
s = arr[i];
if (s.slice(0, startLength) === startSpaces) {
arr[i] = s.slice(startLength);
}
}
return arr.join("\n");
}
}
return text;
}
|
3de4005b1e6175502ba73498d5cc46e1c7d62135
|
TypeScript
|
enwrought/continual2
|
/src/server/entities/CalendarEntry.ts
| 2.6875
| 3
|
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { User } from './User';
import { ModifyEntryDTO } from '../dto';
/**
* CalendarEntries can be exported from other sources and are not shown to the public.
*/
@Entity()
export class CalendarEntry {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(type => User, author => author.entries)
author: Promise<User>;
@Column({ type: 'timestamp' })
startTime: Date;
@Column({ type: 'timestamp' })
endTime: Date;
@UpdateDateColumn({ type: 'timestamp' })
lastUpdated: Date;
@Column({ length: 36 })
title: string;
@Column({ type: 'text' })
description: string;
// constructor(entryValues?: ModifyEntryDTO) {
// if (entryValues) {
// this.setValues(entryValues);
// }
// }
// setValues(entryValues: ModifyEntryDTO) {
// this.title = entryValues.title || '';
// this.description = entryValues.text || '';
// }
}
|
6f0a31ca10b87cdaa3f35cc169e9b1095a877310
|
TypeScript
|
azangru/advent-of-code-2020
|
/challenges/day6/solutions.ts
| 2.6875
| 3
|
import fs from 'fs';
import path from 'path';
import {
countAllDistinctAnswers,
countAllCommonAnswers
} from './count';
const fileContent = fs.readFileSync(path.resolve(__dirname, 'input.txt'), { encoding: 'utf8' });
const solvePart1 = () => {
return countAllDistinctAnswers(fileContent);
};
const solvePart2 = () => {
return countAllCommonAnswers(fileContent);
};
console.log('Solution to part 1 of day 6 is:', solvePart1());
console.log('Solution to part 2 of day 6 is:', solvePart2());
|
2b3a84997acaa53f28cafd4b25adbdf5f16ebd26
|
TypeScript
|
mkmukesh892/AngularRoutingExample
|
/src/app/users/users.service.ts
| 2.546875
| 3
|
import {Injectable , OnInit} from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UsersService implements OnInit {
/*user: {id: number, name: string} ;
// onChanged = new EventEmitter<{id: number, name: string} []>();*/
private users = [
{id: 1, name: 'Max'},
{id: 2, name: 'Tim'},
{id: 3, name: 'Mukesh'}
];
userActivated = new Subject();
constructor() { }
ngOnInit() {
}
/* updateUsers(userData: {id: number, name: string}) {
// alert(userData.id);
// this.users.push(userData);
this.user.id = userData.id;
this.user.name = userData.name;
}*/
/*getUser() {
// console.log(this.user);
// return this.users[this.users.length - 1];
return this.user;
}*/
getUsers() {
return this.users.slice();
}
}
|
80883594ca107ac317beb704cffe6cd1506f1d5c
|
TypeScript
|
electron/sheriff
|
/src/helpers.ts
| 2.734375
| 3
|
import { RepositoryCreatedEvent } from '@octokit/webhooks-types';
export const isMainRepo = (repo: RepositoryCreatedEvent['repository']) => {
// electron/electron or foo/foo
return repo.name === repo.owner.login;
};
type HookContext = {
log: (...args: any[]) => void;
error: (...args: any[]) => void;
};
export const hook = <T extends { id: string; name: string }>(
fn: (event: T, context: HookContext) => Promise<void>,
): ((event: T) => Promise<void>) => {
return async (event) => {
const context = {
error: (...args: any[]) => console.error(`hook(${event.id}):`, ...args),
log: (...args: any[]) => console.log(`hook(${event.id}):`, ...args),
};
try {
await fn(event, context);
} catch (err) {
context.error('an error occurred while handling an event:', event.name, '\n', err);
}
};
};
export const memoize = <A extends any[], T>(
fn: (...args: A) => Promise<T>,
): ((...args: A) => Promise<T>) & { invalidate: () => void } => {
let val: T | null = null;
const f = async (...args: A) => {
if (!val) {
val = await fn(...args);
}
return val;
};
(f as any).invalidate = () => {
val = null;
};
return f as any as ((...args: A) => Promise<T>) & { invalidate: () => void };
};
export const IS_DRY_RUN = !process.argv.includes('--do-it-for-real-this-time');
|
697ca5b428e3b89be6bd964d03611262c6204f1d
|
TypeScript
|
pissang/tweakpane
|
/src/main/js/controller/monitor-binding.ts
| 2.609375
| 3
|
import MonitorBinding from '../binding/monitor';
import LabeledView from '../view/labeled';
import {MonitorController} from './monitor/monitor';
interface Config<In> {
binding: MonitorBinding<In>;
controller: MonitorController<In>;
label: string;
}
/**
* @hidden
*/
export default class MonitorBindingController<In> {
public readonly binding: MonitorBinding<In>;
public readonly controller: MonitorController<In>;
public readonly view: LabeledView;
constructor(document: Document, config: Config<In>) {
this.binding = config.binding;
this.controller = config.controller;
this.view = new LabeledView(document, {
label: config.label,
view: this.controller.view,
});
}
public dispose(): void {
this.binding.dispose();
this.controller.dispose();
this.view.dispose();
}
}
|
fbc82b9ddd03130793557f82b11270c883e920fd
|
TypeScript
|
RinatRezyapov/recognize-client
|
/src/api/domain/User.ts
| 2.53125
| 3
|
import ProtocolObject from './ProtocolObject';
import TypeId from './TypeId';
import { Option } from 'fp-ts/lib/Option';
import Id from './Id';
import Course from './Course';
export default class User extends ProtocolObject {
static $Type = new TypeId<User>({ value: 'User' });
name: string;
email: string;
avatar: Option<Id<File>>;
joinedDate: Option<number>;
courses: Array<Id<Course>>;
followers: Array<Id<User>>;
following: Array<Id<User>>;
constructor({
name,
email,
avatar,
joinedDate,
courses,
followers,
following,
} : {
name: string,
email: string,
avatar: Option<Id<File>>,
joinedDate: Option<number>,
courses: Array<Id<Course>>,
followers: Array<Id<User>>,
following: Array<Id<User>>,
}) {
super({ tpe: User.$Type });
this.name = name;
this.email = email;
this.avatar = avatar;
this.joinedDate = joinedDate;
this.courses = courses;
this.followers = followers;
this.following = following;
}
}
|
77a894c3ddc860cb063862b4b06be1c44df4b035
|
TypeScript
|
hgehlhausen/student-manager-crud
|
/src/services/database.service.ts
| 2.71875
| 3
|
import {Client, ClientConfig, QueryResult} from "pg";
/**
* @type {string}
*/
const connectionString: string = 'postgres://studentmgr:studentmgr@localhost:5432/studentmgr';
export class PgClient {
private client: Client;
private static clientConfig: ClientConfig = {
connectionString: connectionString
};
constructor() {
this.client = new Client(PgClient.clientConfig);
}
/**
*
* @param {string} sqlString
* @param {*[]} args
* @param {Function} afterFn
*/
public query(sqlString: string, args: any[], afterFn: Function): void {
let queryPromise: Promise<QueryResult> = this.client.query(sqlString, args);
this.client.connect()
.then(() => queryPromise.then((result: QueryResult) => afterFn(result.rows)))
.catch(function () {
console.log('Error', arguments);
});
}
}
|
7552e571ae0a864bbcfac60db70b87f2b666d428
|
TypeScript
|
iamvishnusankar/next-sitemap
|
/packages/next-sitemap/src/utils/array.ts
| 3.5625
| 4
|
import { matcher } from './matcher.js'
/**
* Split an array based on size
* @param arr
* @param chunkSize
* @returns
*/
export const toChunks = <T>(arr: T[], chunkSize: number): T[][] => {
return arr.reduce<Array<T[]>>(
(prev, _, i) =>
i % chunkSize ? prev : [...prev, arr.slice(i, i + chunkSize)],
[]
)
}
/**
* simple method to normalize any string to array
* @param inp
*/
export const toArray = (inp: string | string[]): string[] => {
return typeof inp === 'string' ? [inp] : inp
}
/**
* Returns the difference between two arrays
* @param inputArr input array
* @param toRemoveArr array of elements to be removed
*/
export const removeFromArray = <T>(inputArr: T[], toRemoveArr: T[]): T[] => {
return inputArr.filter((x) => !toRemoveArr.includes(x))
}
/**
* Returns the difference between two arrays, which match input array pattern
* @param inputArr input array
* @param toRemoveArr array of elements to be removed
*/
export const removeIfMatchPattern = (
inputArr: string[],
toRemoveArr: string[]
): string[] => {
const matchedArr = matcher(inputArr, toRemoveArr)
return removeFromArray(inputArr, matchedArr)
}
|
9525f3793d84dc4045a3115152f32e63caaf402a
|
TypeScript
|
cbodtorf/shopify-klaviyo-order-sync
|
/src/KlaviyoApi.ts
| 2.6875
| 3
|
import axios from 'axios';
import { Event } from './Event'
import { I$CustomerProperties, IOrder, IOrderLineItem, RequestInterface, IEventLineItem } from './contracts'
export class KlaviyoApi {
urlBase: string = 'https://a.klaviyo.com/api/track';
constructor(public publicApiKey: string) {}
// https://github.com/axios/axios#creating-an-instance
// Could specifc more of config here
private klaviyoAxios = axios.create();
// simple utility for converting Date to unix timestamp.
private unix(date: Date): number {
return date.getTime()/1000|0;
}
public createEventsFromOrder(order: IOrder): Event[] {
// Explicitly annotate type when instantiating blank value;
// Order Props that depend on Line Item Iteration:
const itemNames: string[] = [];
const brands: string[] = [];
const eventItems: IEventLineItem[] = [];
const events: Event[] = [];
const time = this.unix(new Date(order.processed_at));
const customerProperties: I$CustomerProperties = {
$email: order.email,
$first_name: order.customer.first_name,
$last_name: order.customer.last_name,
$phone_number: order.customer.phone_number,
};
// Address is not guaranteed on an order.
if (order.shipping_address) {
customerProperties.$address1 = order.shipping_address.address1
customerProperties.$address2 = order.shipping_address.address2
customerProperties.$city = order.shipping_address.city
customerProperties.$zip = order.shipping_address.zip
customerProperties.$region = order.shipping_address.province
customerProperties.$country = order.shipping_address.country
};
// Iterate through line items and push 'Ordered Product' events to queue
order.line_items.forEach((item: IOrderLineItem): void => {
// Set Klaviyo Specific Props for Item
const eventItem: IEventLineItem = {
$event_id: `${order.id}_${item.variant_id}`,
$value: item.price,
ProductName: item.name,
ProductID: item.product_id,
Quantity: item.quantity,
SKU: item.sku,
"Variant Name": item.variant_title,
Brand: item.vendor,
ItemPrice: item.price,
RowTotal: item.price,
}
// push order level properties/
itemNames.push(item.name);
brands.push(item.vendor);
eventItems.push(eventItem);
const orderedProductEvent = new Event({
token: this.publicApiKey,
event: 'Ordered Product',
customer_properties: customerProperties,
properties: eventItem,
time: time,
});
events.push(orderedProductEvent);
});
// Push 'Placed Order' event to queue
const placeOrderEvent = new Event({
token: this.publicApiKey,
event: 'Placed Order',
customer_properties: customerProperties,
properties: {
$event_id: `${order.id}`,
$value: order.total_price,
ItemNames: itemNames,
Brands: brands,
"Discount Code": order.discount_codes[0],
"Discount Value": order.total_discounts,
shipping_address: order.shipping_address,
billing_address: order.billing_address,
Items: eventItems
},
time: time,
});
events.push(placeOrderEvent);
return events;
}
public async track(event: Event): Promise<void>{
// Convert payload to string before converting to Base64
const jsonString = JSON.stringify(event);
// console.log('track event:', event.event, ' => ', 'e:', event);
const data = Buffer.from(jsonString).toString('base64');
await this.klaviyoAxios.get<RequestInterface>(this.urlBase, {
params: { data } // Using destructing here
});
}
}
|
9ac6002a2b36f7b95ccd1323868f85be97564cbf
|
TypeScript
|
mengtest/home3
|
/core/clientLaya/game/src/commonGame/net/request/scene/unit/CUnitStopMoveRequest.ts
| 2.59375
| 3
|
namespace Shine
{
/** 客户端单位停止移动消息(generated by shine) */
export class CUnitStopMoveRequest extends CUnitRRequest
{
/** 数据类型ID */
public static dataID:number=GameRequestType.CUnitStopMove;
/** 停止的客户端位置 */
public posDir:PosDirData;
constructor()
{
super();
this._dataID=GameRequestType.CUnitStopMove;
}
protected copyData():void
{
super.copyData();
var posDirTemp:PosDirData=this.posDir;
this.posDir=new PosDirData();
this.posDir.copy(posDirTemp);
}
/** 获取数据类名 */
public getDataClassName():string
{
return "CUnitStopMoveRequest";
}
/** 写入字节流(简版) */
protected toWriteBytesSimple(stream:BytesWriteStream):void
{
super.toWriteBytesSimple(stream);
this.posDir.writeBytesSimple(stream);
}
/** 创建实例 */
public static createCUnitStopMove(instanceID:number,posDir:PosDirData):CUnitStopMoveRequest
{
var re:CUnitStopMoveRequest=new CUnitStopMoveRequest();
re.instanceID=instanceID;
re.posDir=posDir;
return re;
}
}
}
|
3814b65e4bc0babdc557c4b8e689c5f947eb661c
|
TypeScript
|
ThiagoGuy/typescript-generator
|
/src/app/generator/models/instance.ts
| 2.671875
| 3
|
export class Instance {
className: string;
fieldName: string;
constructor(fieldName: string, className: string) {
this.fieldName = fieldName;
this.className = className;
}
}
|
64319b150bf6e0da207e778c58b756726ca60299
|
TypeScript
|
RodrigoMattosoSilveira/space-monad
|
/src/option.ts
| 3.734375
| 4
|
import { Err, Ok, Result } from './result'
import { iteratorSymbol, singleValueIterator } from './iterator'
export interface Option<A> extends Iterable<A> {
/**
* Returns the value contained in this Option.
* This will always return undefined if this Option instance is None.
* This method never throws.
*/
get(): A | undefined
/**
* Returns whether this Option has a defined value (i.e, it's a Some(value))
*/
isDefined(): this is Some<A>
/**
* Applies the given procedure to the option's value, if it is non empty.
*/
forEach(fn: (a: A) => void): void
/**
* Maps the value contained in this Some, else returns None.
* Depending on the map function return value, a Some could be tranformed into a None.
*/
map<B>(fn: (a: A) => null | undefined): Option<B>
/**
* Maps the value contained in this Some, else returns None.
* Depending on the map function return value, a Some could be tranformed into a None.
*/
map<B>(fn: (a: A) => B | null | undefined): Option<B>
/**
* Maps the value contained in this Some, else returns None.
* Depending on the map function return value, a Some could be tranformed into a None.
*/
map<B>(fn: (a: A) => B | null | undefined): Option<B>
/**
* Maps the value contained in this Some to a new Option, else returns None.
*/
flatMap<B>(fn: (a: A) => Option<B>): Option<B>
/**
* If this Option is a Some and the predicate returns true, keep that Some.
* In all other cases, return None.
*/
filter<B extends A>(fn: (a: A) => a is B): Option<B>
/**
* If this Option is a Some and the predicate returns true, keep that Some.
* In all other cases, return None.
*/
filter(fn: (a: A) => boolean): Option<A>
/**
* Applies the first function if this is a None, else applies the second function.
* Note: Since this method creates 2 functions everytime it runs, don't use in tight loops; use isDefined() instead.
*/
fold<B, C>(ifEmpty: () => B, ifDefined: (a: A) => C): B | C
/**
* Returns this Option unless it's a None, in which case the provided alternative is returned
*/
orElse(alternative: () => Option<A>): Option<A>
/**
* Returns this Option's value if it's a Some, else return the provided alternative
*/
getOrElse(alternative: A): A
/**
* Returns whether this option is a Some with a value satisfying the predicate.
*/
exists<B extends A>(predicate: (a: A) => a is B): this is Option<B>
/**
* Returns whether this option is a Some with a value satisfying the predicate.
*/
exists(predicate: (a: A) => boolean): boolean
/**
* Returns whether this option is a Some that contain a specific value, using ===
*/
contains(a: A): boolean
/**
* Converts this Option to an Array.
*/
toArray(): Array<A>
/**
* Converts this Option to a Result.
*/
toResult<ERR>(ifNone: () => ERR): Result<ERR, A>
toString(): string
}
export interface Some<T> extends Option<T> {
type: 'some'
get(): T
}
export interface None extends Option<never> {
type: 'none'
get(): never
}
export type NullableValue<T> = T | Option<T> | null | undefined
export interface OptionObject {
/**
* Creates an Option from a value.
* If the value is null or undefined, it will create a None, else a Some.
*/
<T>(value: T | null | undefined): Option<T>
/**
* Returns whether the passed value is an Option (either a Some or a None).
*/
isOption(value: any): value is Option<{}>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
xs: [
NullableValue<T1>,
NullableValue<T2>,
NullableValue<T3>,
NullableValue<T4>,
NullableValue<T5>,
NullableValue<T6>,
NullableValue<T7>,
NullableValue<T8>,
NullableValue<T9>,
NullableValue<T10>
]
): Option<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
xs: [
NullableValue<T1>,
NullableValue<T2>,
NullableValue<T3>,
NullableValue<T4>,
NullableValue<T5>,
NullableValue<T6>,
NullableValue<T7>,
NullableValue<T8>,
NullableValue<T9>
]
): Option<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5, T6, T7, T8>(
xs: [
NullableValue<T1>,
NullableValue<T2>,
NullableValue<T3>,
NullableValue<T4>,
NullableValue<T5>,
NullableValue<T6>,
NullableValue<T7>,
NullableValue<T8>
]
): Option<[T1, T2, T3, T4, T5, T6, T7, T8]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5, T6, T7>(
xs: [
NullableValue<T1>,
NullableValue<T2>,
NullableValue<T3>,
NullableValue<T4>,
NullableValue<T5>,
NullableValue<T6>,
NullableValue<T7>
]
): Option<[T1, T2, T3, T4, T5, T6, T7]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5, T6>(
xs: [
NullableValue<T1>,
NullableValue<T2>,
NullableValue<T3>,
NullableValue<T4>,
NullableValue<T5>,
NullableValue<T6>
]
): Option<[T1, T2, T3, T4, T5, T6]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4, T5>(
xs: [NullableValue<T1>, NullableValue<T2>, NullableValue<T3>, NullableValue<T4>, NullableValue<T5>]
): Option<[T1, T2, T3, T4, T5]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3, T4>(
xs: [NullableValue<T1>, NullableValue<T2>, NullableValue<T3>, NullableValue<T4>]
): Option<[T1, T2, T3, T4]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2, T3>(xs: [NullableValue<T1>, NullableValue<T2>, NullableValue<T3>]): Option<[T1, T2, T3]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T1, T2>(xs: [NullableValue<T1>, NullableValue<T2>]): Option<[T1, T2]>
/**
* Creates a new Option holding the tuple of all the values contained in the passed array
* if they were all Some or non null/undefined values,
* else returns None
*/
all<T>(ts: Array<NullableValue<T>>): Option<T[]>
}
// The Option factory / static object
const OptionObject = function <T>(value: T): Option<T> {
return isDef(value) ? Some(value) : None
} as OptionObject
OptionObject.all = (arr: any[]): any => {
const values: any[] = []
for (let i = 0; i < arr.length; i++) {
let value = arr[i]
if (Option.isOption(value)) value = value.get()
if (!isDef(value)) return None
values.push(value)
}
return Some(values)
}
OptionObject.isOption = function (value: any): value is Option<{}> {
return !!value && (value.type === 'some' || value.type === 'none')
}
function makeNone() {
const self: any = {}
function returnNone() {
return None
}
function returnFalse() {
return false
}
self.type = 'none'
self.Option = OptionObject
self.get = () => undefined
self.isDefined = returnFalse
self.forEach = () => {}
self.map = returnNone
self.flatMap = returnNone
self.filter = returnNone
self.fold = (ifEmpty: Function) => ifEmpty()
self.orElse = (alt: Function) => alt()
self.getOrElse = (alt: any) => alt
self.contains = returnFalse
self.exists = returnFalse
self.toArray = () => []
self.toResult = (ifNone: Function) => Err(ifNone())
self.toString = () => 'None'
self.toJSON = () => null
self[iteratorSymbol] = function () {
return {
next() {
return { done: true }
}
}
}
return self as None
}
function _Some<T>(this: Some<T> & { value: T }, value: T) {
this.value = value
}
_Some.prototype = {
type: 'some',
Option: OptionObject,
get() {
return this.value
},
isDefined() {
return true
},
forEach(fn: any) {
fn(this.value)
},
map(fn: any): any {
return Option(fn(this.value))
},
flatMap(fn: any) {
return fn(this.value)
},
filter(fn: any) {
return fn(this.value) ? this : None
},
fold(ifEmpty: any, ifDefined: any) {
return ifDefined(this.value)
},
orElse() {
return this
},
getOrElse() {
return this.value
},
contains(value: any) {
return this.value === value
},
exists(predicate: any) {
return predicate(this.value)
},
toArray() {
return [this.value]
},
toResult() {
return Ok(this.value)
},
toString() {
return `Some(${this.value})`
},
toJSON() {
return this.value.toJSON ? this.value.toJSON() : this.value
},
[iteratorSymbol]: singleValueIterator(self => self.value)
}
function isDef<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined
}
export const Option = OptionObject
/** Creates a new Some instance using a non nullable value */
// extends {} to prevent null and undefined being passed
export function Some<T extends {}>(value: T): Some<T> {
return new (_Some as any)(value)
}
export const None = makeNone()
|
6a08b335b613ebe056981d8a79f1fa3b3ba691c1
|
TypeScript
|
SoundFractures/DoneAndDoneServer
|
/src/utils/controller.functions.ts
| 2.734375
| 3
|
export type MakeJSON = {
message: string
}
export const makeJSON = (message: string): MakeJSON => {
return {
message
}
}
|
7d29c0491611125e0e8fcab94cd5b6eabea70f5a
|
TypeScript
|
Tullerpeton/units-autumn-2021
|
/src/utils/sortOrders.test.ts
| 3.296875
| 3
|
import {getSortFunction, sortByItemCount, sortByDate, sortTypes, sortOrders} from './sortOrders';
describe('sortOrders', () => {
it('valid sort function', () => {
const func = jest.fn();
sortOrders([{}, {}], func);
expect(func).toHaveBeenCalledTimes(1);
});
it('valid sort function of empty list', () => {
const func = jest.fn();
sortOrders([], func);
expect(func).toHaveBeenCalledTimes(0);
});
test.each([
undefined,
null,
])('invalid sort function of empty orders', (sortFunction) => {
const result = sortOrders([{}, {}], sortFunction);
expect(result).toBeUndefined();
});
});
describe('getSortFunction', () => {
it('sortType = DATE', () => {
expect(getSortFunction(sortTypes.DATE)).toBe(sortByDate);
});
it('sortType = COUNT', () => {
expect(getSortFunction(sortTypes.COUNT)).toBe(sortByItemCount);
});
});
describe('sortByItemCount function', () => {
test.each([
[{}, { items: ['3', '2', '1'] }],
[{ items: ['3', '2', '1'] }, {}],
])('undefined orders', (order1, order2) => {
const result = sortByItemCount(order1, order2);
expect(result).toBe(0);
});
test.each([
[{ items: [] }, { items : [] }],
[{ items: ['3', '2', '1'] }, { items : ['item1', 'item2', 'item3'] }],
])('same items count', (order1, order2) => {
const result = sortByItemCount(order1, order2);
expect(result).toBe(0);
});
test.each([
[{ items: [] }, { items : ['3', '2', '4', '1'] }],
[{ items: ['3', '2'] }, { items : ['item1', 'item2', 'item3'] }],
])('first order less than second order', (order1, order2) => {
const result = sortByItemCount(order1, order2);
expect(result).toBe(-1);
});
test.each([
[{ items: ['3', '2', '4', '1'] }, { items : [] }],
[{ items: ['item1', 'item2', 'item3'] }, { items : ['3', '2'] }],
])('second order less than first order', (order1, order2) => {
const result = sortByItemCount(order1, order2);
expect(result).toBe(1);
});
});
describe('sortByDate function', () => {
test.each([
[{}, { date: 1 }],
[{ date: 3 }, {}],
])('undefined date', (order1, order2) => {
const result = sortByDate(order1, order2);
expect(result).toBe(0);
});
test.each([
[{}, { date: 0 }],
[{ date: 0 }, {}],
])('date = 0', (order1, order2) => {
const result = sortByDate(order1, order2);
expect(result).toBe(0);
});
it('same date', ()=> {
const order1 = { date: 343 }, order2 = { date: 343 };
const result = sortByDate(order1, order2);
expect(result).toBe(0);
});
it('first date less than second date', ()=> {
const order1 = { date: 1 }, order2 = { date: 2 };
const result = sortByDate(order1, order2);
expect(result).toBe(1);
});
it('second date less than first date', ()=> {
const order1 = { date: 2 }, order2 = { date: 1 };
const result = sortByDate(order1, order2);
expect(result).toBe(-1);
});
});
|
947c5324a5579758cff05f0224e4460ce53e4e9c
|
TypeScript
|
Chili1995/TypeScriptDemo
|
/demo10.ts
| 4.0625
| 4
|
/**
* 类的构造函数
*/
class Per{
// public name: string;
// constructor(name: string) {
// this.name = name
// }
constructor(public name:string){}
}
// 子类一定要写super调用父类构造函数
class perex extends Per{
constructor(public age:number){
super('子的名字')
}
}
// const per1 = new Per('你的名字')
const per1 = new perex(123)
console.log(per1.age);
console.log(per1.name);
|
2c8be46cb0af44994feb394fcd970b5256437a41
|
TypeScript
|
ondfavourmachine/WPE-App
|
/src/services/eventService/events.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import * as eventsJson from '../../app/event.json'
@Injectable({
providedIn: 'root'
})
export class EventsService {
constructor(private http: HttpClient) {
}
getEvents(): Observable<any>{
return of(eventsJson)
}
trimAString(str: string, num: number){
let tempStr = [], trimmedStr = [], count = 0;
if(str.split(' ').length < num ) {
return str
}else{
tempStr = str.split(' ');
// console.log(tempStr);
for(let i of tempStr){
if(count < num){
// console.log(true, count, i);
trimmedStr.push(i);
count++
}else{
break;
}
}
return trimmedStr.join(' ').concat(' ...')
}
}
}
|
84fff090723742ba3d0b777f4b32b46d3b69c085
|
TypeScript
|
robert-harbison/super-validator
|
/lib/core/Validator.test.ts
| 3
| 3
|
/* eslint-disable @typescript-eslint/no-unused-vars */
import { max, min, required } from '..'
import { ErrorReturnTypes, exportedForTesting, validateSchema, ValidatorSchema } from './Validator'
const { processSingleValidator, processListOfValidators, validateSingle } = exportedForTesting
describe('Validator:processSingleValidator()', () => {
test('Should return a string as the validation result.', () => {
expect(processSingleValidator((fieldKey: string, value: unknown) => 'Error', 'field', 'theValue')).toEqual('Error')
})
test('Should return a array of string as the validation result.', () => {
expect(processSingleValidator((fieldKey: string, value: unknown) => ['Error1', 'Error2'], 'field', 'theValue')).toEqual(['Error1', 'Error2'])
})
test('Should return null if there is no errors.', () => {
expect(processSingleValidator((fieldKey: string, value: unknown) => null, 'field', 'theValue')).toEqual(null)
})
})
describe('Validator:processListOfValidators()', () => {
const validatorString = (fieldKey: string, value: unknown) => 'Error'
const validatorArray = (fieldKey: string, value: unknown) => ['Error1', 'Error2']
test('Should return a array of strings for each error in the list', () => {
expect(processListOfValidators([validatorString, validatorString, validatorString], 'field', 'theValue')).toEqual(['Error', 'Error', 'Error'])
})
test('Should return a array of strings with all strings from each error.', () => {
expect(processListOfValidators([validatorArray, validatorArray, validatorArray], 'field', 'theValue')).toEqual(['Error1', 'Error2', 'Error1', 'Error2', 'Error1', 'Error2'])
})
test('Should return no errors if the validator does not return anything or null.', () => {
expect(
processListOfValidators(
[
(fieldKey: string, value: unknown): ErrorReturnTypes => {
return null
},
],
'field',
'value',
),
).toEqual(null)
expect(processListOfValidators([(fieldKey: string, value: unknown) => null], 'field', 'value')).toEqual(null)
})
})
describe('Validator:validateSingle()', () => {
const validatorString = (fieldKey: string, value: unknown) => 'Error'
const validatorArray = (fieldKey: string, value: unknown) => ['Error1', 'Error2']
describe('validateSingle() should return proper values regardless of it being a single validator or a list of validators', () => {
test('Should return a string as the validation result.', () => {
expect(validateSingle('field', 'theValue', validatorString)).toEqual('Error')
})
test('Should return a array of string as the validation result.', () => {
expect(validateSingle('field', 'theValue', validatorArray)).toEqual(['Error1', 'Error2'])
})
test('Should return a array of strings for each error in the list', () => {
expect(validateSingle('field', 'theValue', [validatorString, validatorString, validatorString])).toEqual(['Error', 'Error', 'Error'])
})
test('Should return a array of strings with all strings from each error.', () => {
expect(validateSingle('field', 'theValue', [validatorArray, validatorArray, validatorArray])).toEqual(['Error1', 'Error2', 'Error1', 'Error2', 'Error1', 'Error2'])
})
})
})
describe('Validator:validateSchema()', () => {
const validatorStringEqualsTest = (fieldKey: string, value: unknown) => {
return !value || value !== 'test' ? 'Value does not equal test' : null
}
test('Should return no errors if schema passes', () => {
const schema = {
firstName: validatorStringEqualsTest,
}
expect(validateSchema({ firstName: 'test' }, schema)).toEqual(null)
})
test('Should return errors if schema does not pass', () => {
const schema = {
firstName: validatorStringEqualsTest,
}
expect(validateSchema({ firstName: 'test123' }, schema)).toEqual({ firstName: 'Value does not equal test' })
})
test('Should return errors if value does not exist therefore schema does not pass', () => {
const schema = {
firstName: validatorStringEqualsTest,
}
expect(validateSchema({}, schema)).toEqual({ firstName: 'Value does not equal test' })
})
test('Should return proper response for tested objects.', () => {
const schema: ValidatorSchema = {
test: required(),
test2: required(),
test3: required(),
options: {
testa: [required(), min(5)],
test2: required(),
testb: {
testc: [required(), min(5), max(2)],
testd: required(),
testf: required(),
},
},
}
// No errors obj has no errors.
const test = validateSchema(
{
test: 'test',
test3: 'test2',
options: {
test124: 'tasd',
testa: 'tesasdasd',
testb: { testc: 'aas', testd: 'asdasd' },
},
},
schema,
)
expect(test).toEqual({
test2: '`test2` is required.',
options: { test2: '`test2` is required.', testb: { testc: ['`testc` is too short.', '`testc` is too long.'], testf: '`testf` is required.' } },
})
})
})
|
8d253bc9bade1b482e16b6ae34af20e216baba8d
|
TypeScript
|
cancerberoSgx/javascript-documentation-examples
|
/examples/events-002/src/index.ts
| 3.328125
| 3
|
// # Documenting Events
// (Part of [this project](https://github.com/cancerberoSgx/javascript-documentation-examples))
// IMO, this is the best way of documenting events with typedoc. See the [typedoc output result](https://cancerberosgx.github.io/javascript-documentation-examples/examples/events-002/docs/interfaces/vehicle.html)
// ### Features
// * Events optimally represented in typedoc output with separate definitions and unique names so they can be referenced from other entities
// * Listener signatures fully defined in one place
// * Don't contaminate the interface or class with artificial definitions
// * Strict type checking for listeners
// ### Some background
// In previous experiments [1](https://cancerberosgx.github.io/javascript-documentation-examples/examples/events-001/docs/docco/src/index.html) and [2](https://cancerberosgx.github.io/javascript-documentation-examples/examples/events-noEventEmitter/docs/docco/src/index.html) we tried to document events with typedoc but facing several difficulties: events appear all stacked under the same method signature, or we needed to contaminate our interfaces with artificial methods. **None of these were acceptable.**
// ### Solution summary
// The **solution** we found is declaring events as separate functions declarations and using the typedoc plugin [as-member-of](https://github.com/cancerberoSgx/typedoc-plugins-of-mine/tree/master/plugins/typedoc-plugin-as-member-of) we annotate these functions with @asMemberOf so they will be moved as members of the host class `Vehicle`.
// Also we add the annotation `@event` so the plugin will mutate de functions to events.
// Since functions declarations don't generate any real js code, this won't impact the production code generate at all
import { EventEmitter } from 'events';
// ### The interface
// We are declaring `EventEmitter.on` overrides for enforcing our interface users to use the correct signatures as we did in [example 1](https://cancerberosgx.github.io/javascript-documentation-examples/examples/events-001/docs/docco/src/index.html). But we don't annotate them with `@event` ! Notice how the listener argument references the event listener function declaration, for example, `listener: typeof beforeStart`
/**
* A machine for transportation
*/
interface Vehicle extends EventEmitter {
/** Subscribes to [[beforeStart]] event */
on(eventName: 'beforeStart', listener: typeof beforeStart): this;
/** Subscribes to [[beforeStart]] event */
on(eventName: 'afterStop', listener: typeof afterStop): this;
/** Make this Vehicle tart moving. It triggers events events [[beforeStart]] and [[afterStop]] . */
start();
}
// ### Event function declarations
// We define now the events as separate function declarations. We annotate them with `@asMemberOf Vehicle` and with `@event` so the typedoc plugin [as-member-of](https://github.com/cancerberoSgx/typedoc-plugins-of-mine/tree/master/plugins/typedoc-plugin-as-member-of) will move these funcions as Vehicle members and also transform them into events.
/**
* Event triggered by [[Vehicle.start]] just before the engine of the vehicle starts.
* @asMemberOf Vehicle
* @event
*/
declare function beforeStart(event: VehicleBeforeStartEvent): void;
// This event handler has a complicate signature. Fortunately is fully defined here, in one place. Notice how in the `on` overrides we are referencing this declaration with `listener: typeof beforeStart`.
/**
* Event triggered right after the vehicle stop its movement.
* TODO: document my arguments better
* @asMemberOf Vehicle
* @event
*/
declare function afterStop(
when: Date,
engineStatus: {temp: number, cont: number[]},
coolDown: Promise<boolean>,
): void;
/** The data for [[beforeStart]] event */
interface VehicleBeforeStartEvent{
suit: string;
card: number[];
}
|
c33da0ab96fde1692344c946f8d451360ee4eb91
|
TypeScript
|
lrenc/leetcode
|
/ts/67.add-binary.ts
| 3.5625
| 4
|
function addBinary(a: string, b: string): string {
let lA = a.length - 1;
let lB = b.length - 1;
let flag = 0;
let sum = '';
while (lA >= 0 && lB >= 0) {
const itemA = a[lA];
const itemB = b[lB];
let res = parseInt(itemA) + parseInt(itemB) + flag;
if (res >= 2) {
flag = 1;
res -= 2;
} else {
flag = 0;
}
sum = `${res}${sum}`;
lA --;
lB --;
}
while (lA >= 0) {
const itemA = a[lA];
let res = parseInt(itemA) + flag;
if (res >= 2) {
flag = 1;
res -= 2;
} else {
flag = 0;
}
sum = `${res}${sum}`;
lA --;
}
while (lB >= 0) {
const itemB = b[lB];
let res = parseInt(itemB) + flag;
if (res >= 2) {
flag = 1;
res -= 2;
} else {
flag = 0;
}
sum = `${res}${sum}`;
lB --;
}
if (flag) {
sum = `${flag}${sum}`
}
return sum;
};
console.log(addBinary('1', '111'))
|
3706f9584cbdbdd074f67edb1008034f5bd2bc81
|
TypeScript
|
IronPTSolutions/auth-web
|
/src/app/shared/services/auth.service.ts
| 2.515625
| 3
|
import { User } from './../models/user.model';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';
import { environment } from '../../../environments/environment';
const CURRENT_USER_KEY = 'currentUser';
@Injectable()
export class AuthService {
private baseUrl = `${environment.apiUrl}/auth`;
private headers = new Headers({ 'Content-Type' : 'application/json'});
private options = new RequestOptions({ headers: this.headers, withCredentials: true });
private user: User;
private userSubject: Subject<User>;
constructor(private http: Http) {
this.user = JSON.parse(localStorage.getItem(CURRENT_USER_KEY));
this.userSubject = new Subject<User>();
}
isAuthenticated() {
return this.user !== null && this.user !== undefined;
}
onUserChanges(): Observable<User> {
return this.userSubject.asObservable();
}
authenticate(user: User): Observable<User> {
return this.http.post(this.baseUrl, JSON.stringify(user), this.options)
.map(res => {
return this.doAuthentication(res.json());
})
.catch(this.handleError);
}
private doAuthentication(user: User): User {
this.user = user;
localStorage.setItem(CURRENT_USER_KEY, JSON.stringify(this.user));
this.userSubject.next(this.user);
return this.user;
}
protected handleError(error: Response | any): Observable<any> {
return Observable.throw(error.json());
}
}
|
f08c2112faaee456217216ccb7778d7954e8d50c
|
TypeScript
|
alonethending/joker.front
|
/test/src/core/parser/element.test.ts
| 2.703125
| 3
|
import { Parser } from "@joker/template-compiler";
import { Component } from "@joker/core/src/component";
import { TemplateParser } from "@joker/core/src/parser/index";
import { ElementNodeInfo } from "@joker/core";
class TestView extends Component {
model = {
attr1: "v1",
attr2: "v2",
class1: "v3"
};
event1() {}
event2() {}
}
function mainTest() {
let result = new Parser(`
<div class="className @model.class1" @click="event1" attr="@model.attr1" attr1="@(model.attr2+1)" @tap="event2(2)"></div>`);
let ast = result.elements;
let templates = new TemplateParser(ast, new TestView());
if (templates.nodes.length === 0) return false;
let node = templates.nodes[0] as ElementNodeInfo;
if (
(node.attrs &&
node.attrs.class === "className v3" &&
node.attrs.attr === "v1" &&
node.attrs.attr1 === "v21" &&
node.events &&
node.events.length === 2) === false
) {
throw new Error("Element 渲染错误");
}
return true;
}
function changeTest() {
let result = new Parser(`
<div class="className @model.class1" attr="@model.attr1" attr2="@model.attr1"></div>`);
let ast = result.elements;
let view = new TestView().ComponentInitialize();
let templates = new TemplateParser(ast, view);
if (templates.nodes.length === 0) return false;
let node = templates.nodes[0] as ElementNodeInfo;
if (node.attrs && node.attrs.class === "className v3" && node.attrs.attr === "v1") {
view.model.class1 = "new3";
view.model.attr1 = "new1";
return <any>node.attrs.class === "className new3" && <any>node.attrs.attr === "new1";
}
return false;
}
test("next/parser/element", () => {
expect(mainTest()).toBe(true);
expect(changeTest()).toBe(true);
});
|
ea512311706e529fdd66e03deec4f5b582597015
|
TypeScript
|
ovikariy/bewell
|
/src/modules/securityService.ts
| 2.515625
| 3
|
import { AES, HmacSHA256, enc, lib } from 'crypto-js';
import { ErrorCode, ErrorMessage, StoreConstants } from './constants';
import * as SecureStore from 'expo-secure-store';
import { consoleColors, consoleLogWithColor, isNullOrEmpty } from './utils';
import { isNumber, toNumber } from 'lodash';
import { AppError } from './types';
export interface LoginInfo {
loginAttempts: number;
isPinLocked: boolean;
isEncrypted: boolean;
isInitialized: boolean;
isSignedIn: boolean;
}
interface DataEncryptionInterface {
canEncryptDecrypt: boolean;
encryptData: ((data: string) => string) | null;
decryptData: ((data: string) => string) | null;
getHash: ((data: string) => string) | null;
}
export async function getAllHashedStoreKeysAsync() {
return getMultipleHashedKeysAsync(StoreConstants.AllEncryptedStoreKeys);
}
export async function getMultipleHashedKeysAsync(keysToHash: string[]) {
if (!keysToHash || keysToHash.length < 0)
throw new AppError(ErrorMessage.InvalidKey, ErrorCode.MissingKey7);
if (!DataEncryption.getHash)
throw new AppError(ErrorMessage.Unauthorized, ErrorCode.MissingKey7);
const hashedKeys = [];
for (const key of keysToHash) {
const keyHash = DataEncryption.getHash(key);
hashedKeys.push(keyHash);
}
return hashedKeys;
}
export async function setupNewPINAsync(password: string, pin: string, dataEncryptionKeyEncrypted: string) {
if (isSignedIn() !== true)
throw new AppError(ErrorMessage.Unauthorized);
if (isNullOrEmpty(password) || isNullOrEmpty(pin) || isNullOrEmpty(dataEncryptionKeyEncrypted))
throw new AppError(ErrorMessage.InvalidParameter);
const dataEncryptionKeyDecrypted = decrypt(dataEncryptionKeyEncrypted, password);
if (!dataEncryptionKeyDecrypted)
throw new AppError(ErrorMessage.InvalidPassword, ErrorCode.Security10);
const reEncryptedWithPin = encrypt(dataEncryptionKeyDecrypted, pin);
await setToSecureStoreAsync(StoreConstants.DataEncryptionStoreKey, reEncryptedWithPin);
}
export function signOut() {
resetEncryptDecryptDataFunctions();
}
export async function initializeAsync() {
await setToSecureStoreAsync(StoreConstants.isInitialized, 'true');
}
//TODO: revisit
export async function firstTimeEncryptAllAsync(items: [string, string][], password: string) {
/* data will be encrypted with a random Data Encryption Key and that
key is going to be encrypted with user's password and stored in Async Storage;
if the user changes the password the Data Encryption Key will not change */
const encryptionKey = generateRandomKey();
const encryptionKeyEncrypted = encrypt(encryptionKey, password);
const resultArray: [string, string][] = [];
// 1. encrypt the encryption key
resultArray.push([StoreConstants.DataEncryptionStoreKey, encryptionKeyEncrypted]);
// items format is [['k1', 'val1'], ['k2', 'val2']] keys need to be hashed and values encrypted
for (const index in items) {
const item = items[index];
// 2. hash item key with encryption key
const existingItemTypeHash = await getHash(item[0], encryptionKey);
const existingItemValue = item[1];
if (!existingItemValue)
continue;
// 3. encrypt item value with encryption key
const existingItemValueEncrypted = encrypt(existingItemValue, encryptionKey);
resultArray.push([existingItemTypeHash, existingItemValueEncrypted]);
}
createEncryptDecryptDataFunctions(encryptionKeyEncrypted, password);
return resultArray;
}
export async function decryptAllItemsAsync(items: [string, string][]) {
if (!DataEncryption.getHash || !DataEncryption.decryptData)
throw new AppError(ErrorMessage.Unauthorized, ErrorCode.Decrypt10);
return decryptAllItemsInternalAsync(items, DataEncryption.getHash, DataEncryption.decryptData);
}
export async function decryptAllItemsFromImportAsync(items: [string, string][], getHashAsync: any, decryptDataAsync: any) {
if (!getHashAsync || !decryptDataAsync)
throw new AppError(ErrorMessage.UnableToDecrypt, ErrorCode.Decrypt4);
return decryptAllItemsInternalAsync(items, getHashAsync, decryptDataAsync);
}
async function decryptAllItemsInternalAsync(items: [string, string][], getHashAsyncFunction: any, decryptDataAsyncFunction: any) {
/* items are an array of arrays of itemTypeNameHash and itemValue
e.g. [[ 'itemType1hash', 'item1value' ], [ 'itemType2hash, 'item2value' ]] */
/* create a mapping of item type names and their hashes so we know which item is which */
const itemKeyHashMap: { [hash: string]: string; } = {};
for (const encryptedStoreKey of StoreConstants.AllEncryptedStoreKeys) {
const itemKeyHash = await getHashAsyncFunction(encryptedStoreKey);
itemKeyHashMap[itemKeyHash] = encryptedStoreKey;
}
const decryptedItems = [];
for (const item of items) {
if (!item || item.length !== 2)
throw new AppError(ErrorMessage.InvalidData);
if (item[0] === StoreConstants.DataEncryptionStoreKey)
continue; /* we don't want to process this */
if (item[0] === StoreConstants.SETTINGS) {
decryptedItems.push([item[0], item[1]]); /* SETTINGS are not encrypted */
continue;
}
const hash = item[0];
const value = item[1];
const key = itemKeyHashMap[hash];
if (!key)
throw new AppError(ErrorMessage.InvalidKey, ErrorCode.MissingKey10);
const valueDecrypted = await decryptDataAsyncFunction(value);
if (value && !valueDecrypted)
throw new AppError(ErrorMessage.UnableToDecrypt, ErrorCode.Decrypt9);
decryptedItems.push([key, valueDecrypted]);
}
return decryptedItems;
}
export function getItemKeyHash(itemKey: string) {
if (!itemKey)
throw new AppError(ErrorMessage.General, ErrorCode.Hash1);
if (!DataEncryption.getHash)
throw new AppError(ErrorMessage.Unauthorized, ErrorCode.Hash1);
try {
return DataEncryption.getHash(itemKey);
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.General, ErrorCode.Hash2);
}
}
export function decryptData(value: any) {
if (!value)
return value;
if (!DataEncryption.decryptData)
throw new AppError(ErrorMessage.Unauthorized, ErrorCode.Decrypt1);
try {
const valueDecrypted = DataEncryption.decryptData(value);
if (value && !valueDecrypted)
throw new AppError(ErrorMessage.General, ErrorCode.Decrypt2);
return valueDecrypted;
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.General, ErrorCode.Decrypt3);
}
}
export async function tryDecryptDataAsync(value: any, key: string) {
try {
const valueDecrypted = decrypt(value, key);
if (value && valueDecrypted)
return true;
return false;
}
catch (error) {
return false;
}
}
export function encryptData(value: string) {
if (!DataEncryption.encryptData)
throw new AppError(ErrorMessage.Unauthorized, ErrorCode.Encrypt4);
try {
return DataEncryption.encryptData(value);
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.General, ErrorCode.Decrypt5);
}
}
export async function reEncryptAsync(value: string, oldPassword: string, newPassword: string) {
// 1. decrypt with the old password
const decrypted = decrypt(value, oldPassword);
if (isNullOrEmpty(decrypted))
throw new AppError(ErrorMessage.InvalidPassword, ErrorCode.Decrypt6);
// 2. encrypt with the new password
const encrypted = encrypt(decrypted, newPassword);
if (isNullOrEmpty(encrypted))
throw new AppError(ErrorMessage.General, ErrorCode.Encrypt1);
return encrypted;
}
export async function getLoginInfoAsync(): Promise<LoginInfo> {
const loginAttempts = await getFromSecureStoreAsync(StoreConstants.loginAttempts);
let loginAttemptsNumber = -1;
if (isNumber(loginAttempts))
loginAttemptsNumber = toNumber(loginAttempts);
const isInitialized = await isInitializedAsync();
const isPinLocked = await isPinLockedAsync();
return { loginAttempts: loginAttemptsNumber, isPinLocked, isInitialized, isSignedIn: DataEncryption.canEncryptDecrypt } as LoginInfo;
}
async function isInitializedAsync(): Promise<boolean> {
const isInitialized = await getFromSecureStoreAsync(StoreConstants.isInitialized);
return (isInitialized === 'true');
}
async function isPinLockedAsync(): Promise<boolean> {
try {
const hasDataEncryptionKeyInSecureStore = await getFromSecureStoreAsync(StoreConstants.DataEncryptionStoreKey);
if (hasDataEncryptionKeyInSecureStore && (hasDataEncryptionKeyInSecureStore + '').trim().length > 0)
return true;
return false;
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.AccessStorage, ErrorCode.Storage7);
}
}
const DataEncryption = { canEncryptDecrypt: false } as DataEncryptionInterface;
export function resetEncryptDecryptDataFunctions() {
DataEncryption.canEncryptDecrypt = false;
DataEncryption.decryptData = null;
DataEncryption.encryptData = null;
DataEncryption.getHash = null;
}
export function createEncryptDecryptDataFunctions(dataEncryptionKeyEncrypted: string, passphrase: string) {
const functions = createCryptoFunctions(dataEncryptionKeyEncrypted, passphrase);
/** if we're here then we passed authentication, clear login attempts flag */
resetInvalidPINAttemptsAsync().catch(() => { throw new AppError(ErrorMessage.General, ErrorCode.Auth12); });
DataEncryption.canEncryptDecrypt = functions.canEncryptDecrypt;
DataEncryption.decryptData = functions.decryptData;
DataEncryption.encryptData = functions.encryptData;
DataEncryption.getHash = functions.getHash;
}
/**
* @description createCryptoFunctions that takes password or PIN entered by the user during the logon process or import,
* decrypts the dataEncryptionKey and creates the functions that handle crypto without
* re-retrieving the data encryption key or the need to pass it around
*/
export function createCryptoFunctions(dataEncryptionKeyEncrypted: string, passphrase: string): DataEncryptionInterface {
if (!dataEncryptionKeyEncrypted || !passphrase)
throw new AppError(ErrorMessage.InvalidParameter, ErrorCode.Auth1);
const dataEncryptionKeyDecrypted = decrypt(dataEncryptionKeyEncrypted, passphrase);
if (!dataEncryptionKeyDecrypted)
throw new AppError(ErrorMessage.InvalidPassword, ErrorCode.Auth2);
const functions = { canEncryptDecrypt: true } as DataEncryptionInterface;
functions.decryptData = (data: string) => {
return decrypt(data, dataEncryptionKeyDecrypted);
};
functions.encryptData = (data: string) => {
return encrypt(data, dataEncryptionKeyDecrypted);
};
functions.getHash = (data: string) => {
return getHash(data, dataEncryptionKeyDecrypted);
};
return functions;
}
/* retrieve encrypted DataEncryptionStoreKey from SecureStore and try to decrypt it with PIN */
export async function validatePINAsync(pin: string): Promise<void> {
if (!pin)
throw new AppError(ErrorMessage.InvalidPIN);
const dataEncryptionKeyEncrypted = await getFromSecureStoreAsync(StoreConstants.DataEncryptionStoreKey);
if (isNullOrEmpty(dataEncryptionKeyEncrypted))
throw new AppError(ErrorMessage.InvalidPIN);
const decrypted = decrypt(dataEncryptionKeyEncrypted + '', pin);
if (isNullOrEmpty(decrypted))
throw new AppError(ErrorMessage.InvalidPIN);
}
/* user signing in with PIN number; after StoreConstants.maxLoginAttempts failed attempts clear PIN so user has to re-enter password */
export async function createEncryptDecryptDataFunctionsPINAsync(dataEncryptionKeyEncrypted: string, pin: string) {
try {
createEncryptDecryptDataFunctions(dataEncryptionKeyEncrypted, pin);
}
catch (error) {
await incrementInvalidPINAttemptsAsync();
throw new AppError(ErrorMessage.InvalidPIN, ErrorCode.Auth6);
}
}
async function incrementInvalidPINAttemptsAsync() {
/** run this function at other places where PIN re-entry is required */
const loginAttempts = await getFromSecureStoreAsync(StoreConstants.loginAttempts);
const loginAttemptsNumber = parseInt(loginAttempts + '') ?? 0;
if (loginAttemptsNumber >= StoreConstants.maxLoginAttempts) {
//disable ability to login with PIN so user has to enter the password
await setToSecureStoreAsync(StoreConstants.DataEncryptionStoreKey, '');
throw new AppError(ErrorMessage.MaxLoginAttempts);
}
if (loginAttemptsNumber >= 0 && loginAttemptsNumber <= StoreConstants.maxLoginAttempts) {
await setToSecureStoreAsync(StoreConstants.loginAttempts, (loginAttemptsNumber + 1).toString());
return;
}
await setToSecureStoreAsync(StoreConstants.loginAttempts, (1).toString());
}
async function resetInvalidPINAttemptsAsync() {
getFromSecureStoreAsync(StoreConstants.loginAttempts)
.then((loginAttempts) => {
const loginAttemptsNumber = parseInt(loginAttempts + '') ?? 0;
if (loginAttemptsNumber !== 0)
setToSecureStoreAsync(StoreConstants.loginAttempts, (0).toString());
});
}
/**
* When PIN Lock is used in the app, the DataEncryptionStoreKey is encrypted with PIN and stored in SecureStore
* When PIN Lock is NOT used, the DataEncryptionStoreKey is encrypted with Password and stored in AsyncStorage
*/
export async function getDataEncryptionKeyAsync(): Promise<string | null> {
const dataEncryptionKey = await getFromSecureStoreAsync(StoreConstants.DataEncryptionStoreKey);
if (dataEncryptionKey)
return dataEncryptionKey as string;
return null;
}
export function isSignedIn(): boolean {
return DataEncryption.canEncryptDecrypt;
}
function generateRandomKey() {
return lib.WordArray.random(256 / 8).toString(); /* convert to string, important for decryption, otherwise the encodings will be different Utf8 vs Hex after re-encryption */
}
function getHash(value: string, key: string) {
if (!key)
throw new AppError(ErrorMessage.General, ErrorCode.UnableToHashWithoutPassword);
const hash = HmacSHA256(value, key);
return enc.Base64.stringify(hash);
}
function encrypt(value: string, key: string) {
if (!key)
throw new AppError(ErrorMessage.General, ErrorCode.Encrypt2);
if (!value || value === '')
return value;
try {
return AES.encrypt(value, key).toString();
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.General, ErrorCode.Encrypt3);
}
}
function decrypt(value: string, key: string) {
if (!key)
throw new AppError(ErrorMessage.General, ErrorCode.Decrypt7);
if (!value || value === '')
return value;
try {
const bytes = AES.decrypt(value, key);
const decrypted = bytes.toString(enc.Utf8);
return decrypted;
}
catch (error) {
consoleLogWithColor(error);
throw new AppError(ErrorMessage.InvalidData, ErrorCode.Decrypt8);
}
}
function getFromSecureStoreAsync(key: string) {
return SecureStore.getItemAsync(key, {});
}
function setToSecureStoreAsync(key: string, value: string) {
return SecureStore.setItemAsync(key, value, {});
}
|
f25bbb5a05ba3101e84b1538c880b88b8e030212
|
TypeScript
|
muzea/aliyun-sdk-node
|
/dist/ros/SetStackPolicy/req.d.ts
| 2.65625
| 3
|
interface SetStackPolicyRequest {
/**
* 资源栈所属的地域ID。您可以调用[DescribeRegions](~~131035~~)查看最新的阿里云地域列表。
* @example `cn-hangzhou`
*/ "RegionId": string;
/**
* 资源栈ID。
* @example `4a6c9851-3b0f-4f5f-b4ca-a14bf691f2ff`
*/ "StackId": string;
/**
* 包含资源栈策略主体的结构,最小长度为1个字节,最大长度为16384个字节。
* 您可以指定StackPolicyBody或StackPolicyURL参数,但不能同时指定两者。
* @example `{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}`
*/ "StackPolicyBody"?: string;
/**
* 包含资源栈策略的文件的位置。 URL必须指向位于Web服务器(http,https)中的策略(最大大小:16384字节),或阿里云OSS存储桶(例如oss://ros/stack-policy/demo、oss://ros/stack-policy/demo?RegionId=cn-hangzhou。oss地域如未指定,默认与接口参数RegionId相同。)。
* 您可以指定StackPolicyBody或StackPolicyURL参数,但不能同时指定两者。
* URL最大长度为1350字节。
* @example `oss://ros/stack-policy/demo`
*/ "StackPolicyURL"?: string;
}
export { SetStackPolicyRequest };
|
fb9de83935982f57b585af06f3079d957daa4112
|
TypeScript
|
Yarden-Tal/fullstack-itc-may21
|
/05-Node/99-Assignments/04-Online-Store/Yaniv1/models/usersModel.ts
| 2.6875
| 3
|
export {};
const { v4: uuidv4 } = require("uuid");
const fs = require("fs");
const path = require("path");
const usersJsonPath = path.resolve(__dirname, "../users.json");
const storeJsonPath = path.resolve(__dirname, "../store.json");
const { readStoreJson, Product, Store } = require('./storeModel');
const readUsersJson = () => {
try {
const users: any = fs.readFileSync(usersJsonPath);
return JSON.parse(users);
} catch (error) {
console.error(error.message);
}
}
export class CartProduct {
productUuid: string;
productName: string;
totalPrice: number;
quantity: number;
constructor(productUuid: string) {
this.productUuid = productUuid;
this.totalPrice = 0;
this.quantity = 0;
}
}
export class User {
userUuid: string;
email: string;
username: string;
password: string;
stores: Array<string>; // for admins
cart: Array<CartProduct>;
purchased: Array<CartProduct>; // previous carts products
constructor(email: string, username: string, password: string) {
this.userUuid = uuidv4();
this.email = email;
this.username = username;
this.password = password;
this.stores = [];
this.cart = [];
this.purchased = [];
}
}
export class Users {
users: Array<User>;
constructor() {
this.users = readUsersJson();
}
updateUsersJson() {
try {
fs.writeFileSync(usersJsonPath, JSON.stringify(this.users));
} catch (error) {
console.error(error.message);
}
}
findUserIndex(userUuid: string, userEmail: string): number {
try {
const userIndex: number = (userUuid) ? this.users.findIndex(user => user.userUuid === userUuid)
: this.users.findIndex(user => user.email === userEmail);
if ((userIndex === -1) && (userUuid)) throw new Error(`no user with uuid ${userUuid}`);
return userIndex;
} catch (error) {
console.error(error.message);
}
}
storeUuid(): string {
try {
const firstAdminIndex: number = this.users.findIndex(user => user.stores.length > 0);
let storeUuid: string;
if (firstAdminIndex === -1) {
storeUuid = uuidv4(); /// if a store doesn't exist - create it
const store: Store = readStoreJson();
store.storeUuid = storeUuid;
fs.writeFileSync(storeJsonPath, JSON.stringify(store));
} else storeUuid = this.users[firstAdminIndex].stores[0]; // else - assign the existing store (currently only 1 exists)
return storeUuid;
} catch (error) {
console.error(error.message);
}
}
addUser(userEmail: string, userUsername: string, userPassword: string, shopperToAdmin: boolean, userIndex: number, role: string): object {
try {
const user = new User(userEmail, userUsername, userPassword);
const storeUuid: string = (role === 'admin') ? this.storeUuid() : undefined;
const userUuid: string = (shopperToAdmin) ? this.users[userIndex].userUuid : user.userUuid;
if (role === 'admin') {
if (shopperToAdmin) {
this.users[userIndex].stores.push(storeUuid); // convert shopper to admin
} else {
user.stores.push(storeUuid);
this.users.push(user); // add admin
}
} else this.users.push(user); // add shopper
this.updateUsersJson();
return { userUuid, storeUuid };
} catch (error) {
console.error(error.message);
}
}
completeCartProductDetails(quantity: number, productUuid: string): CartProduct {
try {
const store: Store = readStoreJson();
const product: Product = store.products.find(product => product.productUuid === productUuid);
const productPrice: number = product.productPrice;
const cartProduct = new CartProduct(productUuid);
cartProduct.productName = product.productName;
cartProduct.quantity = quantity;
cartProduct.totalPrice = productPrice * quantity;
return cartProduct;
} catch (error) {
console.error(error.message);
}
}
addCartProduct(shopperUuid: string, productUuid: string): number {
try {
const shopperIndex: number = this.findUserIndex(shopperUuid, null);
const cartProduct: CartProduct = this.completeCartProductDetails(0, productUuid);
this.users[shopperIndex].cart.push(cartProduct);
const cartProductIndex: number = this.users[shopperIndex].cart.length - 1;
this.updateUsersJson();
return cartProductIndex;
} catch (error) {
console.error(error.message);
}
}
findCartProduct(shopperIndex: number, productUuid: string, mathSign: string): number {
try {
let cartProductIndex: number = this.users[shopperIndex].cart.findIndex(cartProduct => cartProduct.productUuid === productUuid);
if ((cartProductIndex === -1) && (mathSign === '+')) cartProductIndex = this.addCartProduct(this.users[shopperIndex].userUuid, productUuid);
return cartProductIndex;
} catch (error) {
console.error(error.message);
}
}
deleteCartProduct(shopperUuid: string, productUuid: string) { // on direct deletion or when quantity === 0
try {
const shopperIndex: number = this.findUserIndex(shopperUuid, null);
this.users[shopperIndex].cart = this.users[shopperIndex].cart.filter(cartProduct => cartProduct.productUuid !== productUuid);
this.updateUsersJson();
} catch (error) {
console.error(error.message);
}
}
updateCartProductQuantity(shopperUuid: string, productUuid: string, mathSign: string): CartProduct {
try {
const shopperIndex: number = this.findUserIndex(shopperUuid, null);
const cartProductIndex: number = this.findCartProduct(shopperIndex, productUuid, mathSign);
if (mathSign === '+') this.users[shopperIndex].cart[cartProductIndex].quantity++;
else this.users[shopperIndex].cart[cartProductIndex].quantity--;
const cartProductQuantity: number = this.users[shopperIndex].cart[cartProductIndex].quantity;
let cartProduct: CartProduct;
if (cartProductQuantity === 0) this.deleteCartProduct(shopperUuid, productUuid);
else {
cartProduct = this.completeCartProductDetails(cartProductQuantity, productUuid);
this.users[shopperIndex].cart[cartProductIndex] = cartProduct;
}
this.updateUsersJson();
return cartProduct;
} catch (error) {
console.error(error.message);
}
}
updatePurcased(shopperIndex: number/*, storeUuid: string*/) { // seperated from emptyCart for clarity
try {
this.users[shopperIndex].cart.forEach(cartProduct => { // update quantities&totalPrice in purchased according to shppoer purchase
const cartProductIndex: number = this.users[shopperIndex].purchased.findIndex(cartProductPurchased => cartProductPurchased.productUuid == cartProduct.productUuid);
if (cartProductIndex === -1) this.users[shopperIndex].purchased.push(cartProduct);
else {
this.users[shopperIndex].purchased[cartProductIndex].quantity += cartProduct.quantity;
this.users[shopperIndex].purchased[cartProductIndex].totalPrice += cartProduct.totalPrice;
}
});
const store: Store = readStoreJson();
this.users[shopperIndex].cart.forEach(cartProduct => { // update stock quantities in store according to shppoer purchase
const productIndex: number = store.products.findIndex(product => product.productUuid === cartProduct.productUuid);
store.products[productIndex].inStock -= cartProduct.quantity;
});
fs.writeFileSync(storeJsonPath, JSON.stringify(store));
} catch (error) {
console.error(error.message);
}
}
emptyCart(shopperUuid: string/*, storeUuid: string*/) { // after payment.
try {
const shopperIndex: number = this.findUserIndex(shopperUuid, null);
this.updatePurcased(shopperIndex/*, storeUuid*/); // storeUuid will be used when there is more than 1 store
this.users[shopperIndex].cart = [];
this.updateUsersJson();
} catch (error) {
console.error(error.message);
}
}
}
|
566adb7087d66ccee842d5c4cca5b1957963e4d7
|
TypeScript
|
Halithor/wc3-tower-defense
|
/src/lib/projectile.ts
| 2.75
| 3
|
/** @noSelfInFile **/
import {
doPeriodically,
Subject,
forDestructablesInCircle,
forUnitsInRange,
vec3,
Vec3,
} from 'w3lib/src/index';
import {Destructable, Effect, Unit, Vec2} from 'w3lib';
const interval = 0.03;
export class Projectile {
fx: Effect;
private releaseTimer: (this: void) => void;
private _impactUnits = false;
private _impactDestructables = false;
private _destroyOnImpact = false;
private originalDistance: number;
private destFilter?: (d: Destructable) => boolean;
private unitFilter?: (u: Unit) => boolean;
vertSpeed: number;
readonly onEnd: Subject<[]>;
constructor(
private pos: Vec3,
private target: Vec3 | Unit,
private groundSpeed: number,
private gravity: number,
effectPath: string,
private onImpact: (target: Vec3 | Unit | Destructable, pos: Vec2) => void
) {
this.onEnd = new Subject<[]>();
this.fx = new Effect(effectPath, pos.withoutZ());
this.fx.pos = pos;
let targetPos: Vec3;
if (target instanceof Vec3) {
targetPos = target;
} else {
targetPos = target.pos.withTerrainZ();
}
this.fx.setYaw(pos.withoutZ().angleTo(targetPos.withoutZ()).radians);
const endPeriodic = doPeriodically(interval, () => this.tick());
this.releaseTimer = () => {
endPeriodic.cancel();
};
this.originalDistance = pos.withoutZ().distanceTo(targetPos.withoutZ());
const flightTime = this.originalDistance / groundSpeed;
const z0 = pos.z;
const zEnd = targetPos.z;
// motion equation to land on the height of the platform targeted.
this.vertSpeed =
(zEnd - z0) / flightTime + (flightTime * this.gravity) / 2.0;
}
private tick() {
let targetPos: Vec3;
if (this.target instanceof Vec3) {
targetPos = this.target;
} else {
targetPos = this.target.pos.withTerrainZ();
}
const groundPos = this.pos.withoutZ();
const targetGroundPos = targetPos.withoutZ();
const distance = groundPos.distanceTo(targetGroundPos);
// const flightTime = distance / this.groundSpeed
// const heightDiff = targetZ - this.fx.z
// const verticalSpeed = heightDiff / flightTime - 0.5 * this.arc * flightTime
this.vertSpeed = this.vertSpeed - this.gravity * interval;
if (this.groundSpeed * interval >= distance) {
this.onImpact(this.target, targetGroundPos);
this.destroyProjectile();
} else {
const nextGroundPos = groundPos.moveTowards(
targetGroundPos,
this.groundSpeed * interval
);
const nextZ = math.max(
this.pos.z + this.vertSpeed * interval,
nextGroundPos.terrainZ + 80
);
const nextPos = nextGroundPos.withZ(nextZ);
this.fx.pos = nextPos;
this.pos = nextPos;
if (this._impactUnits) {
forUnitsInRange(nextGroundPos, 80, (u: Unit) => {
if (!this.unitFilter || this.unitFilter(u)) {
const absDist = u.pos
.withTerrainZ()
.add(vec3(0, 0, u.getflyHeight()))
.distanceTo(nextPos);
if (absDist > 100 + u.collisionSize) {
// don't hit units if they're not on the same vertical position
// as the projectile.
return;
}
this.onImpact(u, nextGroundPos);
if (this._destroyOnImpact) {
this.destroyProjectile();
}
}
});
}
if (this._impactDestructables) {
forDestructablesInCircle(nextGroundPos, 80, (d: Destructable) => {
if (!this.destFilter || this.destFilter(d)) {
this.onImpact(d, nextGroundPos);
if (this._destroyOnImpact) {
this.destroyProjectile();
}
}
});
}
}
}
public impactsUnits(value: boolean, filter?: (u: Unit) => boolean) {
this._impactUnits = value;
this.unitFilter = filter ? u => filter(u) : undefined;
}
public impactsDestructables(
value: boolean,
filter?: (d: Destructable) => boolean
) {
this._impactDestructables = value;
this.destFilter = filter ? d => filter(d) : undefined;
}
private destroyProjectile() {
this.fx.destroy();
this.releaseTimer();
this.onEnd.emit();
}
}
|
62fdd90d0d8b00725d2f917f6ef1e570c24d1a89
|
TypeScript
|
bizon/selling-partner-api-sdk
|
/clients/product-pricing-api-v0/src/api-model/models/prime-information-type.ts
| 2.53125
| 3
|
/* tslint:disable */
/* eslint-disable */
/**
* Selling Partner API for Pricing
* The Selling Partner API for Pricing helps you programmatically retrieve product pricing and offer information for Amazon Marketplace products.
*
* The version of the OpenAPI document: v0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Amazon Prime information.
* @export
* @interface PrimeInformationType
*/
export interface PrimeInformationType {
/**
* Indicates whether the offer is an Amazon Prime offer.
* @type {boolean}
* @memberof PrimeInformationType
*/
'IsPrime': boolean;
/**
* Indicates whether the offer is an Amazon Prime offer throughout the entire marketplace where it is listed.
* @type {boolean}
* @memberof PrimeInformationType
*/
'IsNationalPrime': boolean;
}
|
7bd718c9b3f7fc98de4d4f205be1935dee671a74
|
TypeScript
|
future4code/Paulo-Oliveira
|
/semana15/aula43/src/endpoint5.ts
| 2.625
| 3
|
import express, { Request, Response } from "express"
import cors from "cors"
import { countries } from "./countries"
const app = express()
app.use(express.json())
app.use(cors())
app.delete("/countries/:id", (req: Request, res: Response) => {
let errorCode: number = 400
try {
if (!req.headers.authorization) {
errorCode = 401
throw new Error()
}
const countryIndex: number = countries.findIndex(
(country) => country.id === Number(req.params.id)
)
if (countryIndex === -1) {
errorCode = 404
throw new Error()
}
countries.splice(countryIndex, 1)
res.status(200).send()
} catch (error) {
console.log(error)
res.status(errorCode).send()
}
})
app.listen(3003, () => {
console.log("Server is running in http://localhost:3003");
});
|
88c721ab7980927585da51840d4467c8996d17e6
|
TypeScript
|
deshion/strapi
|
/packages/core/data-transfer/src/strapi/providers/local-source/links.ts
| 2.6875
| 3
|
import { Readable } from 'stream';
import type { ILink } from '../../../../types';
import { createLinkQuery } from '../../queries/link';
/**
* Create a Readable which will stream all the links from a Strapi instance
*/
export const createLinksStream = (strapi: Strapi.Strapi): Readable => {
const uids = [...Object.keys(strapi.contentTypes), ...Object.keys(strapi.components)] as string[];
// Async generator stream that returns every link from a Strapi instance
return Readable.from(
(async function* linkGenerator(): AsyncGenerator<ILink> {
const query = createLinkQuery(strapi);
for (const uid of uids) {
const generator = query().generateAll(uid);
for await (const link of generator) {
yield link;
}
}
})()
);
};
|
86047d21e79ca69a562560789c1c6672041422cc
|
TypeScript
|
mariourena/red-blue-green
|
/src/types/types.game.ts
| 3.015625
| 3
|
export enum CellState {
Blue = "Blue",
Green = "Green",
Red = "Red",
}
export enum GameState {
NotWon,
Won,
}
export interface CellCoords {
x: number;
y: number;
}
export interface GameCell {
state: CellState;
coords: CellCoords;
}
export type GameGridCells = GameCell[][];
|
f00d83f2379920a3f38e8eab55184f2032e581a2
|
TypeScript
|
JonyCoding/lg-javascript
|
/typescript/jspang/demo6.ts
| 3.96875
| 4
|
/* =============================================================================
#
# Author: xie yanpeng
# Date: 2020-10-03 22:33:26
# LastEdit: enter your name
# LastEditTime: 2020-10-03 22:34:15
# Description:
#
============================================================================= */
const numberArr: number[] = [1, 2, 3]
const StringArr: string[] = ['a', 'b', 'c']
const undefinedArr: undefined[] = [undefined]
// 既包含数字又包含字符串
const arr: (number | string)[] = [1, 'string', 2]
// 对象数组类型(具体定义了对象内部的类型)
const xiaojiejies1 :{name:string,age:number}[]= [{
name: '刘英',
age: 19
}, {
name: '谢大脚',
age: 18
}]
// 上面的定义对象数组的方法有点啰嗦,下面有简单实现的方法
type Lady = {name:string,age:number}
const xiaojiejies2 : Lady[] = [{
name: '刘英',
age: 19
}, {
name: '谢大脚',
age: 18
}]
class Madom {
name:string;
age:number;
}
const xiaojiejies:Madom[] = [{
name: '刘英',
age: 19
}, {
name: '谢大脚',
age: 18
}]
|
dab34253c1a29c7fb7197b304643961a91fc8ab5
|
TypeScript
|
sanjithpk/opvizor
|
/frontend/src/utils/statusCodes.ts
| 2.546875
| 3
|
export const statusCodes: StatusCode = {
done: {
code: "Recently Done",
color: "#64a338" // green
},
inProgress: {
code: "In Progress",
color: "#3865a3" // blue
},
dueDatePassed: {
code: "Due Date Passed",
color: "#e03b24" // red
},
todo: {
code: "Todo",
color: "#ffcc00" // yellow
}
}
interface StatusCode {
[key: string]: {
code: string
color: string
}
}
|
36e3de43df0882d2263bb5b1a797dbe2d53bc589
|
TypeScript
|
robots-ju/fll-scoreboard
|
/src/js/2021/specs.ts
| 2.8125
| 3
|
import {FllScorer} from "./scorer";
const scorer = new FllScorer();
/**
* Robot Game 2021 specifications test suite, based on the official scoring guide
* @see https://www.first-lego-league.org/en/season/robot-game/missions.html
*/
describe('Robot Game 2021 specifications', function () {
describe('Scorer initial state', function () {
/**
* The scorer script should only take into account what is given in
* the missions state argument
*/
it('Should score no points if nothing is given', function () {
expect(scorer.getScore({})).toEqual(0);
});
/**
* Doing nothing scores points
* M12 Design & build
* > Chick statue is completely in circle: 10
* M17 Precision
* > 6 on field: 50
* 50 + 10 = 60
*/
it('Should score 60 for initial state', function () {
expect(scorer.getScore(scorer.initialMissionsState())).toEqual(60);
});
it('Should be no warnings with initial state', function () {
expect(scorer.getWarnings(scorer.initialMissionsState()).length).toEqual(0);
});
});
describe('Mission 00', function () {
it('If all your equipment fits in the small inspection space: 20', function () {
expect(scorer.getScore({
m00_small_inspection_area: true,
})).toEqual(20);
});
});
describe('Mission 01', function () {
it('If your Innovation Project Model has the following: 20', function () {
expect(scorer.getScore({
m01_innovation: true,
})).toEqual(20);
});
});
describe('Mission 02', function () {
it('Partly full of contents: 20', function () {
expect(scorer.getScore({
m02_partly: true,
})).toEqual(20);
});
it('Completely full of contents: 30', function () {
expect(scorer.getScore({
m02_completely: true,
})).toEqual(30);
});
it('Partly or completely, not both', function () {
expect(scorer.getWarnings({
m02_partly: true,
m02_completely: true,
}).indexOf(scorer.warnings.m02_cannot_score_both)).not.toEqual(-1);
});
});
describe('Mission 03', function () {
it('Prepared for unloading: 20', function () {
expect(scorer.getScore({
m03_prepared: true,
})).toEqual(20);
});
it('Unloaded: 10', function () {
expect(scorer.getScore({
m03_unloaded: true,
})).toEqual(10);
});
it('Prepared and unloaded: adds up', function () {
expect(scorer.getScore({
m03_prepared: true,
m03_unloaded: true,
})).toEqual(30);
});
});
describe('Mission 04', function () {
it('Truck: 10', function () {
expect(scorer.getScore({
m04_truck: true,
})).toEqual(10);
});
it('Plane: 10', function () {
expect(scorer.getScore({
m04_plane: true,
})).toEqual(10);
});
it('Truck and plane: bonus', function () {
expect(scorer.getScore({
m04_truck: true,
m04_plane: true,
})).toEqual(30);
});
});
describe('Mission 05', function () {
it('Engine switched: 20', function () {
expect(scorer.getScore({
m05_engine_switched: true,
})).toEqual(20);
});
});
describe('Mission 06', function () {
it('Not knocked down: 20', function () {
expect(scorer.getScore({
m06_not_knocked_down: true,
})).toEqual(20);
});
it('Knocked down: 30', function () {
expect(scorer.getScore({
m06_knocked_down: true,
})).toEqual(30);
});
it('Partly or completely, not both', function () {
expect(scorer.getWarnings({
m06_not_knocked_down: true,
m06_knocked_down: true,
}).indexOf(scorer.warnings.m06_cannot_score_both)).not.toEqual(-1);
});
});
describe('Mission 07', function () {
it('No longer touching deck: 20', function () {
expect(scorer.getScore({
m07_not_touching: true,
})).toEqual(20);
});
it('East of deck: 10', function () {
expect(scorer.getScore({
m07_east_of_deck: true,
})).toEqual(10);
});
it('Not touching and east: adds up', function () {
expect(scorer.getScore({
m07_not_touching: true,
m07_east_of_deck: true,
})).toEqual(30);
});
});
describe('Mission 08', function () {
it('Separated from your helicopter: 20', function () {
expect(scorer.getScore({
m08_separated: true,
})).toEqual(20);
});
it('In your field\'s circle: 10', function () {
expect(scorer.getScore({
m08_circle: true,
})).toEqual(10);
});
it('Both teams: 10', function () {
expect(scorer.getScore({
m08_both_teams: true,
})).toEqual(10);
});
it('Tasks add up', function () {
expect(scorer.getScore({
m08_separated: true,
m08_circle: true,
})).toEqual(30);
expect(scorer.getScore({
m08_separated: true,
m08_both_teams: true,
})).toEqual(30);
expect(scorer.getScore({
m08_circle: true,
m08_both_teams: true,
})).toEqual(20);
expect(scorer.getScore({
m07_not_touching: true,
m07_east_of_deck: true,
m08_both_teams: true,
})).toEqual(40);
});
});
describe('Mission 09', function () {
it('Repaired: 20', function () {
expect(scorer.getScore({
m09_track_repaired: true,
})).toEqual(20);
});
it('Reached destination: 20', function () {
expect(scorer.getScore({
m09_destination_reached: true,
})).toEqual(20);
});
it('Repaired and reached destination: adds up', function () {
expect(scorer.getScore({
m09_track_repaired: true,
m09_destination_reached: true,
})).toEqual(40);
});
});
describe('Mission 10', function () {
it('Containers sorted: 20', function () {
expect(scorer.getScore({
m10_sorted: true,
})).toEqual(20);
});
});
describe('Mission 11', function () {
it('Partly: 20', function () {
expect(scorer.getScore({
m11_partly: true,
})).toEqual(20);
});
it('Completely: 30', function () {
expect(scorer.getScore({
m11_completely: true,
})).toEqual(30);
});
it('Partly or completely, not both', function () {
expect(scorer.getWarnings({
m11_partly: true,
m11_completely: true,
}).indexOf(scorer.warnings.m11_cannot_score_both)).not.toEqual(-1);
});
});
describe('Mission 12', function () {
it('Turbine blade mat: 20', function () {
expect(scorer.getScore({
m12_blade_mat: true,
})).toEqual(20);
});
it('Turbine blade nothing else: 30', function () {
expect(scorer.getScore({
m12_blade_nothing: true,
})).toEqual(30);
});
it('Turbine blade mat or nothing else, not both', function () {
expect(scorer.getWarnings({
m12_blade_mat: true,
m12_blade_nothing: true,
}).indexOf(scorer.warnings.m12_cannot_score_both_blade)).not.toEqual(-1);
});
it('Chicken statue partly: 20', function () {
expect(scorer.getScore({
m12_chicken_partly: true,
})).toEqual(5);
});
it('Chicken statue nothing completely: 30', function () {
expect(scorer.getScore({
m12_chicken_completely: true,
})).toEqual(10);
});
it('Chicken statue partly or completely, not both', function () {
expect(scorer.getWarnings({
m12_chicken_partly: true,
m12_chicken_completely: true,
}).indexOf(scorer.warnings.m12_cannot_score_both_chicken)).not.toEqual(-1);
});
});
describe('Mission 13', function () {
it('Latched together: 10', function () {
expect(scorer.getScore({
m13_latched_together: true,
})).toEqual(10);
});
it('Latched to bridge: 10', function () {
expect(scorer.getScore({
m13_latched_bridge: true,
})).toEqual(10);
});
it('Together and bridge: bonus', function () {
expect(scorer.getScore({
m13_latched_together: true,
m13_latched_bridge: true,
})).toEqual(30);
});
});
describe('Mission 14', function () {
it('Lowered: 10 each', function () {
expect(scorer.getScore({
m14_lowered: 1,
})).toEqual(10);
expect(scorer.getScore({
m14_lowered: 2,
})).toEqual(20);
});
it('Lowered: max of 2', function () {
expect(scorer.getScore({
m14_lowered: 3,
})).toEqual(20);
expect(scorer.getScore({
m14_lowered: 99,
})).toEqual(20);
});
});
describe('Mission 15', function () {
it('Platooning Trucks: 10 each', function () {
expect(scorer.getScore({
m15_trucks: 1,
})).toEqual(10);
expect(scorer.getScore({
m15_trucks: 2,
})).toEqual(20);
});
it('Platooning Trucks: max 20 points', function () {
expect(scorer.getScore({
m15_trucks: 3,
})).toEqual(20);
expect(scorer.getScore({
m15_trucks: 99,
})).toEqual(20);
});
it('Train: 20 each', function () {
expect(scorer.getScore({
m15_train: 1,
})).toEqual(20);
expect(scorer.getScore({
m15_train: 2,
})).toEqual(40);
});
it('Train: max 40 points', function () {
expect(scorer.getScore({
m15_train: 3,
})).toEqual(40);
expect(scorer.getScore({
m15_train: 99,
})).toEqual(40);
});
it('Cargo Ship’s West Deck: 30 each', function () {
expect(scorer.getScore({
m15_ship: 1,
})).toEqual(30);
expect(scorer.getScore({
m15_ship: 2,
})).toEqual(60);
});
it('Cargo Ship’s West Deck: max 60 points', function () {
expect(scorer.getScore({
m15_ship: 3,
})).toEqual(60);
expect(scorer.getScore({
m15_ship: 99,
})).toEqual(60);
});
});
describe('Mission 16', function () {
it('Partly in any circle: 5 each', function () {
expect(scorer.getScore({
m16_partly_any_circle: 1,
})).toEqual(5);
expect(scorer.getScore({
m16_partly_any_circle: 2,
})).toEqual(10);
expect(scorer.getScore({
m16_partly_any_circle: 10,
})).toEqual(50);
});
it('Completely in any circle: 10 each', function () {
expect(scorer.getScore({
m16_completely_any_circle: 1,
})).toEqual(10);
expect(scorer.getScore({
m16_completely_any_circle: 2,
})).toEqual(20);
expect(scorer.getScore({
m16_completely_any_circle: 10,
})).toEqual(100);
});
it('Blue in blue: 20', function () {
expect(scorer.getScore({
m16_blue_container: true,
})).toEqual(20);
});
it('Lime in lime: 20', function () {
expect(scorer.getScore({
m16_lime_container: true,
})).toEqual(20);
});
it('Circles with at least: 10 each', function () {
expect(scorer.getScore({
m16_circles_with_container: 1,
})).toEqual(10);
expect(scorer.getScore({
m16_circles_with_container: 2,
})).toEqual(20);
expect(scorer.getScore({
m16_circles_with_container: 6,
})).toEqual(60);
});
it('Tasks add up', function () {
expect(scorer.getScore({
m16_partly_any_circle: 1,
m16_completely_any_circle: 1,
m16_blue_container: true,
m16_lime_container: true,
m16_circles_with_container: 1,
})).toEqual(65);
});
});
describe('Mission 17', function () {
it('number of precision tokens left on the field is 1: 10, 2: 15, 3: 25, 4: 35, 5: 50, 6: 50', function () {
expect(scorer.getScore({
m17_precision_tokens: 6
})).toEqual(50);
expect(scorer.getScore({
m17_precision_tokens: 5
})).toEqual(50);
expect(scorer.getScore({
m17_precision_tokens: 4
})).toEqual(35);
expect(scorer.getScore({
m17_precision_tokens: 3
})).toEqual(25);
expect(scorer.getScore({
m17_precision_tokens: 2
})).toEqual(15);
expect(scorer.getScore({
m17_precision_tokens: 1
})).toEqual(10);
});
});
});
|