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
|
|---|---|---|---|---|---|---|
0798fc99c0a4d13202a3d57624bc15dd273af4ac
|
TypeScript
|
jimmyn/pinpoint-playground
|
/src/lib/modelUtils.ts
| 2.640625
| 3
|
import {Model, Query, Scan} from 'dynogels-promisified';
import {NotFound, UnprocessableEntity} from 'http-errors';
import {capitalize, decodeJSON, encodeJSON} from './utils';
/**
* Gets an item from dynamoDB table
* Throws a NotFound http error if item is not found
* This is an example of functional approach to extending dynogels model functionality
* @param model - dynogels Model
*/
export const getItem = (model: Model) => {
return async (hashKey: string, rangeKey?: string) => {
const item = await model.getAsync(hashKey, rangeKey);
if (!item) {
throw new NotFound(`${capitalize(model.config().name)} not found`);
}
return item;
};
};
export type ListPaginatedParams = {
from?: string;
size: number;
};
export type ListPaginatedResult = {
items: any[];
next?: string;
};
/**
* Gets items from dynamoDB table with cursor based pagination
* @param query - dynogels Query or Scan
*/
export const listPaginated = (query: Query | Scan) => {
return async ({from, size}: ListPaginatedParams): Promise<ListPaginatedResult> => {
query = query.limit(size);
if (from) {
const [err, startKey] = decodeJSON(from);
if (err) throw new UnprocessableEntity('Invalid "from" parameter');
query = query.startKey(startKey);
}
const {Items, LastEvaluatedKey} = await query.execAsync();
const result: ListPaginatedResult = {items: Items};
if (LastEvaluatedKey) {
result.next = encodeJSON(LastEvaluatedKey);
}
return result;
};
};
|
0423fca431502e7e9a34a64b81db3144c5303210
|
TypeScript
|
CJAC35/Golf-Game
|
/src/Player.ts
| 2.703125
| 3
|
import * as MRE from '@microsoft/mixed-reality-extension-sdk';
export class Player{
public user: MRE.User;
public scores: number[];
public currLevel: number;
public totalScore: number;
public constructor(user: MRE.User){
this.user = user;
this.scores = [];
this.currLevel = 0;
this.totalScore = 0;
}
addPointToHole(holeNumber: number){
if(this.scores.length <= holeNumber){
this.scores.push(0);
}
this.scores[holeNumber] += 1
this.totalScore +=1
}
scoreGoal(){
this.currLevel += 1;
if(this.scores.length <= this.currLevel){
this.scores.push(0);
}
}
resetScores(){
this.scores = [];
this.currLevel = 0;
this.totalScore = 0;
}
resetCurrentScore(){
this.totalScore -= this.scores[this.currLevel];
if(this.scores.length > 0){
this.scores[this.currLevel] = 0;
}
}
}
|
a8ed0c6d70beb8998896e81ba79854479e477efd
|
TypeScript
|
ringteki/ringteki
|
/server/game/cards/19.1-AS01/Unicorn/IchigoKun.ts
| 2.625
| 3
|
import AbilityContext = require('../../../AbilityContext');
import { CardTypes, Elements, Players, TargetModes } from '../../../Constants';
import AbilityDsl = require('../../../abilitydsl');
import DrawCard = require('../../../drawcard');
const VULNERABLE_ELEMENT = 'ichigo-kun-fire';
const MORE_MIL_LESS_GLORY = 'Increase own military, reduce other glory';
const LESS_MIL_MORE_GLORY = 'Reduce own military, increase other glory';
export default class IchigoKun extends DrawCard {
static id = 'ichigo-kun';
public setupCardAbilities() {
this.persistentEffect({
condition: (context) =>
context.game.currentConflict &&
context.game.currentConflict.hasElement(this.getCurrentElementSymbol(VULNERABLE_ELEMENT)),
effect: AbilityDsl.effects.setBaseMilitarySkill(0)
});
this.action({
title: 'Modify military skill and glory',
targets: {
otherCharacter: {
cardType: CardTypes.Character,
controller: Players.Self,
cardCondition: (card, context) => card.isParticipating() && card !== context.source
},
select: {
mode: TargetModes.Select,
dependsOn: 'otherCharacter',
choices: (context) => ({
[MORE_MIL_LESS_GLORY]: this.actionSequence(context, { military: +2, glory: -2 }),
[LESS_MIL_MORE_GLORY]: this.actionSequence(context, { military: -2, glory: +2 })
})
}
},
effect: 'give {0} {1} {2} and {3} {4} glory - {0} {5}',
effectArgs: (context) =>
context.selects.select.choice === MORE_MIL_LESS_GLORY
? ['+2', 'military', context.targets.otherCharacter, '-2', 'is wild today!']
: ['-2', 'military', context.targets.otherCharacter, '+2', 'is well-behaved. Impressive!']
});
}
public getPrintedElementSymbols() {
const symbols = super.getPrintedElementSymbols();
symbols.push({ key: VULNERABLE_ELEMENT, prettyName: 'Restricted Ring', element: Elements.Fire });
return symbols;
}
private actionSequence(context: AbilityContext, modifiers: { military: number; glory: number }) {
return AbilityDsl.actions.sequential([
AbilityDsl.actions.moveToConflict({ target: context.source }),
AbilityDsl.actions.multiple([
AbilityDsl.actions.cardLastingEffect({
target: context.source,
effect: AbilityDsl.effects.modifyMilitarySkill(modifiers.military)
}),
AbilityDsl.actions.cardLastingEffect({
target: context.targets.otherCharacter,
effect: AbilityDsl.effects.modifyGlory(modifiers.glory)
})
])
]);
}
}
|
2abc43225bb509a06997db532ccf6a43414dd9c7
|
TypeScript
|
dyhaz/angular4-coreui
|
/src/app/views/animations/animations.component.ts
| 2.515625
| 3
|
import { Component } from '@angular/core';
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
@Component({
templateUrl: 'animations.component.html',
styles: [`
p {
width:200px;
background:lightgray;
margin:100px auto;
text-align:center;
padding:20px;
font-size:1.5em;
}
`],
animations: [
trigger('myAwesomeAnimation', [
state('small', style( {
transform: 'scale(1)',
})),
state('large', style({
transform: 'scale(1.2)',
})),
transition('small <=> large', animate('300ms ease-in', keyframes([
style({opacity: 0, transform: 'translateY(-75%)', offset: 0}),
style({opacity: 1, transform: 'translateY(35px)', offset: .5}),
style({opacity: 1, transform: 'translateY(0)', offset: 1}),
]))),
])
]
})
export class AnimationsComponent {
public brandPrimary = '#20a8d8';
public brandSuccess = '#4dbd74';
public brandInfo = '#63c2de';
public brandWarning = '#f8cb00';
public brandDanger = '#f86c6b';
state: string = 'small';
private items = [{
name: 'Blup',
description: 'Nemo says blup'
},{
name: 'FooBar',
description: 'foobar is awesome'
}]
animateMe() {
this.state = (this.state === 'small' ? 'large' : 'small');
}
}
|
07c61d0f65bce270a5b6545e2d6086c60cd1dc70
|
TypeScript
|
franpsif/final-app
|
/src/app/recipes/recipe.service.ts
| 2.515625
| 3
|
import { AuthService } from '../auth/auth.service';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Ingredient } from '../shared/ingredient.model';
import { Recipe } from './recipe.model';
import { Subject } from 'rxjs/Subject';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class RecipeService {
recipesChanged = new Subject<Recipe[]>();
private recipes: Recipe[] = [
new Recipe('A test recipe 1', 'A test 1', 'https://c1.staticflickr.com/6/5514/18218250593_2f8a956a35_b.jpg', [
new Ingredient('Banana', 3),
new Ingredient('Meat', 1)
]),
new Recipe('A test recipe 2', 'A test 2', 'https://c1.staticflickr.com/6/5514/18218250593_2f8a956a35_b.jpg', [
new Ingredient('Orange', 5),
new Ingredient('Fish', 2)
])
];
constructor(private http: Http, private authservice: AuthService) {}
getRecipe(index: number) {
return this.recipes[index];
}
getRecipes() {
return this.recipes.slice();
}
addRecipe(recipe: Recipe) {
this.recipes.push(recipe);
this.recipesChanged.next(this.getRecipes());
}
updateRecipe(index: number, newRecipe: Recipe) {
this.recipes[index] = newRecipe;
this.recipesChanged.next(this.getRecipes());
}
deleteRecipe(index: number) {
this.recipes.splice(index, 1);
this.recipesChanged.next(this.getRecipes());
}
saveRecipes() {
const token = this.authservice.getToken();
return this.http.put('https://ng-recipe-book-d1fa5.firebaseio.com/recipes.json?auth=' + token, this.recipes);
}
fetchRecipes() {
const token = this.authservice.getToken();
return this.http.get('https://ng-recipe-book-d1fa5.firebaseio.com/recipes.json?auth=' + token)
.map(
(response: Response) => {
const data = response.json();
const recipesFromServer: Recipe[] = [];
for (const recipe of data) {
recipesFromServer.push(recipe);
}
this.recipes = recipesFromServer;
this.recipesChanged.next(this.getRecipes());
return true;
}).catch(
(error: Response) => {
return Observable.throw('Something went wrong');
}
);
}
}
|
1cf038b20afee18f392e5e738e0a3238f1066c81
|
TypeScript
|
SupertigerDev/express-deno
|
/Response.ts
| 2.65625
| 3
|
import { ServerRequest } from "https://deno.land/std@v0.42.0/http/server.ts";
export default class Response {
_status: number;
req: ServerRequest;
constructor(req: ServerRequest) {
this.req = req;
this._status = 200
}
send(body: string) {
this.req.respond({body, status: this._status})
}
json(json: any) {
this.send(JSON.stringify(json));
}
status(code: number) {
this._status = code;
return this;
}
}
|
13809b0c979bab2f03e24ea1728a9b3be78bb21f
|
TypeScript
|
bartversluijs/simple-custom-errors
|
/examples/handling.ts
| 3.328125
| 3
|
import SimpleCustomErrors from '../build/index';
// Create FooError
const FooError = SimpleCustomErrors.createError('FooError', [
{
code: 'Bar',
description: 'Bar {{foo}}',
params: [
'foo',
],
},
]);
try {
// Throw error
throw new SimpleCustomErrors.Errors.FooError('Bar', {
foo: ['Test'],
});
} catch (e) {
// Handling the error nicely
// We can check if it's a default javascript, because it's based on top of the default javascript error
if (e instanceof Error) {
console.log('It\'s a default javascript error!');
}
// We can also check if it's an error from the SimpleCustomErrors like this
if (e instanceof SimpleCustomErrors.Error) {
console.log('It\'s an SimpleCustomErrors Error!');
}
// But, for more detailed error handling, we can also check if it's the FooError we've just created
if (e instanceof FooError) {
console.log('It\'s our created custom FooError!');
}
// Last but not least, we have the following fields available for more detailed error handling
console.log(`Type: ${e.type}`); // The error (FooError)
console.log(`Code: ${e.code}`); // The suberror code (Bar)
console.log('Params:', e.params); // The params of the suberror ({foo: ['Test']})
}
|
69879b2f06f16b276383a73e6f62496b198c6b70
|
TypeScript
|
gustavom12/PokedexSimulation
|
/src/app/directives/pokemon-type.directive.ts
| 2.78125
| 3
|
import { Directive, Input,ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[PokemonType]'
})
export class PokemonTypeDirective implements AfterViewInit{
@Input("PokemonType")text: String
//Set color to pokemon types
constructor(public el:ElementRef) { }
$el:HTMLElement = this.el.nativeElement
ngAfterViewInit(){
const text = this.$el.textContent
//console.log(text)
if(text === "Poison"){
this.$el.style.background = "#b97fc9"
}
if(text === "Grass"){
this.$el.style.background = "#9bcc50"
}
if(text === "Fire"){
this.$el.style.background = "#fd7d24"
}
if(text === "Flying"){
this.$el.classList.add("Flyingtype")
}
if(text === "Water"){
this.$el.style.background = "#4592c4"
}
if(text === "Bug"){
this.$el.style.background = "#729f3f"
}
if(text === "Normal"){
this.$el.style.background = "#a4acaf"
this.$el.style.color = "#000000"
}
if(text === "Electric"){
this.$el.style.background = "#eed535"
this.$el.style.color = "#000000"
}
if(text === "Ground"){
this.$el.style.background = "#ab9842"
}
if(text === "Fairy"){
this.$el.style.background = "#fdb9e9"
this.$el.style.color = "#000000"
}
if(text === "Fighting"){
this.$el.style.background = "#d56723"
this.$el.style.color = "#000000"
}
if(text === "Psychic"){
this.$el.style.background = "#f366b9"
}
if(text === "Rock"){
this.$el.style.background = "#a38c21"
}
if(text === "Steel"){
this.$el.style.background = "#9eb7b8"
this.$el.style.color = "#000000"
}
if(text === "Ice"){
this.$el.style.background = "#51c4e7"
this.$el.style.color = "#000000"
}
if(text === "Ghost"){
this.$el.style.background = "#7b62a3"
}
if(text === "Dragon"){
this.$el.classList.add("DragonType")
}
if(text === "Dark"){
this.$el.style.background = "#707070"
}
}
}
|
87c40845f14a34269f8db3c5e004bfeba10dd110
|
TypeScript
|
projectcemetery/NimesisOld
|
/minimalClient/typescript/Packets.ts
| 3.40625
| 3
|
namespace Utils {
/**
* Request types
*/
export enum RequestType {
ADD_CLASS_REQUEST
}
/**
* Response types
*/
export enum ResponseType {
INTERNAL_ERROR,
ADD_CLASS_RESPONSE
}
/**
* Response codes
*/
export enum ResponseCode {
OK_CODE,
ERROR_CODE
}
/**
* Base packet
*/
export class BasePacket {
/**
* Empty entity Id
*/
static EMPTY_ID = "0000000000000000";
}
/**
* Packet of request
*/
export abstract class RequestPacket {
/**
* Convert packet to binary data
*/
abstract pack() : BinaryData;
}
/**
* Response packet
*/
export abstract class ResponsePacket {
/**
* Response id
*/
id : ResponseType;
/**
* Response code
*/
code : ResponseCode;
/**
* Unpack binary data to packet
*/
static unpack(data : BinaryData) : ResponsePacket {
let id = data.readUint8();
let code = data.readUint8();
if (code == ResponseCode.ERROR_CODE) {
let errorCode = data.readUint8();
return new ErrorResponse(id, errorCode);
}
let resp : ResponsePacket
switch(id) {
case ResponseType.ADD_CLASS_RESPONSE:
resp = AddClassResponse.unpack(data);
break;
}
if (resp == null) throw new Error("Unknown response");
resp.id = id;
resp.code = code;
return resp;
}
}
/**
* Error response
*/
export class ErrorResponse extends ResponsePacket {
/**
* Error code
*/
errorCode : number;
/**
* Constructor
* @param id
* @param errorCode
*/
constructor(id : ResponseType, errorCode : number) {
super();
this.id = id;
this.code = ResponseCode.ERROR_CODE;
this.errorCode = errorCode;
}
}
/**
* Add class request
*/
export class AddClassRequest extends RequestPacket {
/**
* Class name
*/
name : string;
/**
* Parent id
*/
parentId : string;
/**
* Constructor
* @param name
* @param parentId
*/
constructor(name : string, parentId : string) {
super();
this.name = name;
this.parentId = parentId;
}
/**
* Convert packet to binary data
*/
pack() : BinaryData {
let bd = new BinaryData();
bd.addUint8(RequestType.ADD_CLASS_REQUEST);
bd.addStringWithLen(this.name);
if (this.parentId != null) {
bd.addId(this.parentId);
} else {
bd.addId(BasePacket.EMPTY_ID);
}
return bd;
}
}
/**
* Add class request
*/
export class AddInstanceRequest extends RequestPacket {
/**
* Class name
*/
name : string;
/**
* Parent id
*/
classId : string;
/**
* Constructor
* @param name
* @param classId
*/
constructor(name : string, classId : string) {
super();
this.name = name;
this.classId = classId;
}
/**
* Convert packet to binary data
*/
pack() : BinaryData {
let bd = new BinaryData();
bd.addUint8(RequestType.ADD_CLASS_REQUEST);
bd.addStringWithLen(this.name);
bd.addId(this.classId);
return bd;
}
}
/**
* Response for add class request
*/
export class AddClassResponse extends ResponsePacket {
/**
* Class id
*/
classId : string;
/**
* Unpack
* @param data
*/
static unpack(data : BinaryData) : AddClassResponse {
let res = new AddClassResponse();
res.classId = data.readId();
return res;
}
}
}
|
9218ec487bb3dc58ab4dd6280b6ecaad5e12a149
|
TypeScript
|
bravehager/marionette
|
/src/routine.ts
| 2.890625
| 3
|
import fs from "fs";
import path from "path";
import * as Puppeteer from "puppeteer";
import { Command, parse } from "./parser";
import { CommandType } from "./token";
/** A Routine is a sequence of Puppeteer commands. */
export class Routine {
/** An array of commands which defines the routine. */
private commands: Command[];
constructor(commands: Command[]) {
this.commands = commands;
}
/**
* Execute a Marionette routine.
* @param browser
*/
async run(browser: Puppeteer.Browser): Promise<void> {
let pages: Puppeteer.Page[] = await browser.pages();
let page: Puppeteer.Page = pages[0];
let commands = JSON.parse(JSON.stringify(this.commands)); // pass by value
let variableMap: Map<string, string> = new Map();
let routineMap: Map<string, Command[]> = new Map();
await this._execute(commands, variableMap, routineMap, browser, page);
}
/** Recursively execute each discrete step in a Marionette routine */
private async _execute(
commands: Command[],
variableMap: Map<string, string>,
routineMap: Map<string, Command[]>,
browser: Puppeteer.Browser,
page: Puppeteer.Page
): Promise<void> {
let command: Command = commands[0];
command.args = command.args.map(
arg => variableMap.get(arg as string) || arg
);
switch (command.type) {
case CommandType.ROUTINE:
routineMap.set(
command.args[0] as string,
this._getSubRoutine(commands)
);
break;
case CommandType.RUN:
let routine: Command[] | undefined = routineMap.get(command
.args[0] as string);
if (routine)
await this._execute(routine, variableMap, routineMap, browser, page);
commands.shift();
break;
case CommandType.DEF:
variableMap.set(command.args[0] as string, command.args[1] as string);
commands.shift();
break;
case CommandType.GOTO:
await page.goto(command.args[0] as string);
commands.shift();
break;
case CommandType.EVALUATE:
let filePath: string = path.join(".", command.args[0] as string);
let script: string = fs.readFileSync(filePath, { encoding: "utf-8" });
await page.evaluate(script);
commands.shift();
break;
case CommandType.EXIT:
await browser.close();
return;
default:
commands.shift();
break;
}
if (commands[0])
return await this._execute(
commands,
variableMap,
routineMap,
browser,
page
);
else return;
}
private _getSubRoutine(commands: Command[]): Command[] {
let routine: Command[] = [];
let command: Command | undefined = commands.shift() as Command;
let stack: Command[] = [command];
while (stack.length > 0) {
command = commands.shift();
if (command && command.type == CommandType.ROUTINE) stack.push(command);
else if (command && command.type == CommandType.END) stack.pop();
else if (command) routine.push(command);
else throw new Error(`Error evaluating subroutine at ${stack.pop()}`);
}
routine.pop();
return routine;
}
}
|
61455f5875e2cf31f79fe494855471086649a9f7
|
TypeScript
|
RobertBeilich/hashcode_2021
|
/src/app.ts
| 3.03125
| 3
|
import {Car} from "./Car";
import {Intersection} from "./Intersection";
import {Street} from "./Street";
import fs from 'fs';
import {Simulation} from "./Simulation";
const getMatchingIntersectionOrNew = (intersections: Intersection[], id: number): Intersection => {
if(!intersections[id]) {
intersections[id] = new Intersection(id);
}
return intersections[id];
}
const readInput = () => {
let i = 0;
const filename: string = process.argv[2];
const file = fs.readFileSync(`input/${filename}`, "utf-8");
const lines = file.split("\n");
const [duration, countIntersection, countStreets, countCars, score] = lines[i].split(" ").map(x => parseInt(x));
i++;
const intersections: Intersection[] = new Array<Intersection>(countIntersection);
const streets = [];
const cars = [];
for(; i <= countStreets; i++) {
const [startId, endId, name, length] = lines[i].split(" ").map((x, index) => index !== 2 ? parseInt(x) : x);
const start = getMatchingIntersectionOrNew(intersections, startId as number);
const end = getMatchingIntersectionOrNew(intersections, endId as number);
const street = new Street(name as string, length as number, start, end);
streets.push(street);
end.lights.push(street.trafficLight);
}
for (; i <= countCars + countStreets; i++) {
const [pathLengthStr, ...streetNames] = lines[i].split(" ");
let path: Street[] = [];
for (const name of streetNames) {
path.push(streets.filter(x => x.name == name)[0]);
}
cars.push(new Car(path));
}
return new Simulation(filename, duration, streets, intersections, cars);
}
const simulation = readInput();
simulation.start();
|
d705deb6b8d52edd9e468632a2c3169a1a680a10
|
TypeScript
|
jpalumickas/react-native-activestorage
|
/src/lib/createBlobRecord.ts
| 2.671875
| 3
|
import getChecksum from './checksum';
import { File } from '../types';
interface CreateBlobRecordParams {
directUploadsUrl: string;
file: File;
headers?: object;
}
interface BlobParams {
filename: string;
content_type: string;
byte_size: number;
checksum: string;
metadata?: object;
}
const createBlobRecord = async ({ directUploadsUrl, file, headers = {} }: CreateBlobRecordParams) => {
const checksum = await getChecksum({ path: file.path });
if (!checksum) {
throw new Error(`Failed to get file checksum. Path: ${file.path}`)
}
const params: BlobParams = {
filename: file.name,
content_type: file.type || 'image/jpeg',
byte_size: file.size,
checksum,
}
if (file.metadata) {
params.metadata = file.metadata;
}
const response = await fetch(directUploadsUrl, {
method: 'POST',
body: JSON.stringify({ blob: params }),
headers: { 'Content-Type': 'application/json', ...headers },
});
return response.json();
}
export default createBlobRecord;
|
0942fa3634cc07364f48fa3d38afaebda690c62c
|
TypeScript
|
caravelx/magento2
|
/packages/composables/src/composables/getters/addressGetter.ts
| 2.5625
| 3
|
import { Countries, Country } from '@vue-storefront/magento-api';
import { AddressGetter } from '../../types';
const countriesList: AddressGetter['countriesList'] = (countries: Countries[]) => countries
.filter((c) => c.id && c.full_name_english && c.full_name_locale)
.map((c) => ({
id: c.id,
label: c.full_name_locale,
englishLabel: c.full_name_english,
abbreviation: c.two_letter_abbreviation,
}))
.sort((a, b) => a.label.localeCompare(b.label));
const regionList: AddressGetter['regionList'] = (country: Country) => (country?.available_regions ? country.available_regions
.filter((c) => c.id && c.code && c.name)
.map((c) => ({
id: c.id,
label: c.name,
abbreviation: c.code,
} as {
id: number;
label: string;
abbreviation: string;
}))
.sort((a, b) => a.label.localeCompare(b.label)) : []);
export default {
countriesList,
regionList,
} as AddressGetter;
|
726ab1c55d96294c0d54009b264c716a0187248e
|
TypeScript
|
Loppik/lemonade
|
/frontend/src/modules/homeEvents/types.ts
| 2.671875
| 3
|
type DataType = null|undefined|EventType[];
type ErrorType = null|undefined|string;
export interface HomeEventsState {
data: DataType
isLoading: boolean
isError: ErrorType
}
export interface GetHomeEventsAction {
type: string,
payload: {
location?: { longitude: number, latitude: number },
data?: DataType,
error?: ErrorType
}
}
export type EventType = {
cost: number
cover: string
currency: string
start: string
host_expanded: {image_avatar: string}
latitude: number
longitude: number
title: string
}
export type HomeEventsActionTypes = GetHomeEventsAction;
|
1c11c7c5274968baef1fe523d478601242eada5b
|
TypeScript
|
dominique-mueller/angular-package-builder
|
/src/transformer/external-resources/angular-external-resources.analyzer.ts
| 2.78125
| 3
|
import { posix as path } from 'path';
import { ObjectLiteralExpression, ClassDeclaration, SourceFile, Decorator, PropertyAssignment, StringLiteral } from 'ts-simple-ast';
/**
* [Abstract] Angular External Resources Analyzer
*/
export abstract class AngularExternalResourcesAnalyzer {
/**
* Get a component decorator property, throws if it does not exist
*
* @param classDeclaration Potential component class
* @param propertyName Property name
* @returns Component decorator proeprty
*/
protected static getComponentDecoratorPropertyOrThrow( classDeclaration: ClassDeclaration, propertyName: string ): PropertyAssignment {
const componentDecorator: Decorator = classDeclaration.getDecoratorOrThrow( 'Component' );
const componentDecoratorArgument: ObjectLiteralExpression = <ObjectLiteralExpression>componentDecorator.getArguments()[ 0 ] ||
( () => { throw new Error( 'Component decorator does not have an argument.' ) } )();
const componentDecoratorProperty: PropertyAssignment = <PropertyAssignment>componentDecoratorArgument.getPropertyOrThrow( propertyName );
return componentDecoratorProperty;
}
/**
* Get external resource path of value
*
* @param externalResourceAssigmentValue External resource value
* @returns External resource path
*/
protected static getExternalResourcePath( externalResourceAssigmentValue: StringLiteral ): string {
return externalResourceAssigmentValue
.getText()
.replace( /['"`]/g, '' );
}
/**
* Resolve external resource path to an absolute path, based on the source file
*
* @param externalResourcePath External resource path (relative or absolute)
* @returns Absolute resource path, based on the source file
*/
protected static resolveExternalResourcePath( externalResourcePath: string, file: SourceFile ): string {
return path.isAbsolute( externalResourcePath )
? externalResourcePath
: path.join( path.dirname( file.getFilePath() ), externalResourcePath );
}
}
|
24bbda449f8f21a70c1cd806666e4290636ab6cc
|
TypeScript
|
PriyankaMali-13/CaseStudy-Eshop
|
/client/src/app/orders/order.service.ts
| 2.515625
| 3
|
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Order } from '../models/orders';
@Injectable({
providedIn: 'root',
})
export class OrderService {
orderPlaceUrl = 'http://localhost:7000/add/orders';
getUserAllOrders = 'http://localhost:7000/orders';
constructor(private http: HttpClient) {}
//method to place an order
placeOrder(orderInfo: OrderInfo) {
return this.http.post(this.orderPlaceUrl, orderInfo);
}
//method to get all orders
getUserOrders() {
return this.http.get<any>(this.getUserAllOrders)
}
}
export interface OrderInfo {
firstName: string;
lastName: string;
address: string;
products: ProductInfo[];
}
export interface ProductInfo {
productId: string;
quantity: number;
price: number;
name : string;
}
|
29af212cbb49fbab7c2c569c12d4cc9b1fcab93a
|
TypeScript
|
jonnyboyC/kos-language-server
|
/server/test/directives/include.spec.ts
| 2.921875
| 3
|
import { DirectiveTokens } from '../../src/directives/types';
import { createToken } from '../utilities/factories';
import { TokenType } from '../../src/models/tokentypes';
import { Include } from '../../src/directives/include';
import { DiagnosticSeverity } from 'vscode-languageserver';
import { DIAGNOSTICS } from '../../src/utilities/diagnosticsUtils';
import { scanSource } from '../utilities/setup';
const createDirective = (
source: string,
): DirectiveTokens<TokenType.include> => {
const result = scanSource(source);
expect(result.tokens).toHaveLength(0);
expect(result.diagnostics).toHaveLength(0);
expect(result.directiveTokens).toHaveLength(1);
expect(result.directiveTokens[0].directive.type).toBe(TokenType.include);
return result.directiveTokens[0] as any;
};
describe('Include', () => {
describe('when parsing', () => {
describe('when valid', () => {
it('parse into an Include', () => {
const directive = createDirective(
'// #include "0://somePath.ks" some comment',
);
const result = Include.parse(directive);
expect(result).toBeInstanceOf(Include);
if (result instanceof Include) {
expect(result.directive).toBe(directive.directive);
expect(result.path).toBe(directive.tokens[0]);
expect(result.includePath()).toBe('0://somePath.ks');
}
});
});
describe('when invalid', () => {
describe('when there is no path', () => {
it('parser returns a diagnostics', () => {
const directive = createDirective('// #include');
const result = Include.parse(directive);
expect(result).not.toBeInstanceOf(Include);
if (!(result instanceof Include)) {
expect(result.message).toBe(
'Must include string or bare path in #include directive',
);
expect(result.severity).toBe(DiagnosticSeverity.Information);
expect(result.code).toBe(DIAGNOSTICS.DIRECTIVE_INVALID_INCLUDE);
}
});
});
describe('when path is wrong type', () => {
it('parser returns a diagnostics', () => {
const directive = createDirective('// #include 123');
const result = Include.parse(directive);
expect(result).not.toBeInstanceOf(Include);
if (!(result instanceof Include)) {
expect(result.message).toBe(
'Must include string or bare path in #include directive',
);
expect(result.severity).toBe(DiagnosticSeverity.Information);
expect(result.code).toBe(DIAGNOSTICS.DIRECTIVE_INVALID_INCLUDE);
}
});
});
});
});
describe('include path', () => {
describe('when path is a string', () => {
it('returns the string literal', () => {
const include = new Include(
createToken(TokenType.include, '// #include') as any,
createToken(
TokenType.string,
'"0://somePath.ks"',
'0://somePath.ks',
) as any,
);
expect(include.includePath()).toBe('0://somePath.ks');
});
});
describe('when path is a file identifier', () => {
it('returns the string literal', () => {
const include = new Include(
createToken(TokenType.include, '// #include') as any,
createToken(TokenType.fileIdentifier, 'file.ks') as any,
);
expect(include.includePath()).toBe('file.ks');
});
});
});
});
|
64a3f0eac13755956f322d7208de3f8d175e1c57
|
TypeScript
|
pb82/waml-compiler
|
/src/parser/ExpressionParser.ts
| 3.28125
| 3
|
import {Parser, Parsing} from "./Parser";
import {TokenProvider} from "../tokenizer/TokenProvider";
import {ASTNode} from "./types/ASTNode";
import {Token} from "../tokenizer/Token";
import {TOKEN_TYPE} from "../tokenizer/Definitions";
import {UnknownBuiltinError} from "../errors/UnknownBuiltinError";
import NumberNode from "./types/impls/NumberNode";
import ReferenceNode from "./types/impls/ReferenceNode";
import {UnexpectedTokenError} from "../errors/UnexpectedTokenError";
import OperationNode from "./types/impls/OperationNode";
import FunctionCallNode from "./types/impls/FunctionCallNode";
import InnerExpressionNode from "./types/impls/InnerExpressionNode";
const MATH_CONSTANTS: Map<string, number> = new Map();
MATH_CONSTANTS.set("@pi", 3.14159265359);
const MATH_FUNCTIONS: Map<string, string> = new Map();
MATH_FUNCTIONS.set("@sin", "Math.sin");
MATH_FUNCTIONS.set("@cos", "Math.cos");
export class ExpressionParser extends Parser implements Parsing {
constructor(tokens: TokenProvider) {
super(tokens);
}
// Replaces constants in the source code with their value. Constants are always numbers
// e.g. `value: @pi` will be replaced with `value: 3.14159265359`
private replaceConstants(token: Token): void {
if (token.type === TOKEN_TYPE.BUILTIN && MATH_CONSTANTS.get(token.value)) {
token.type = TOKEN_TYPE.NUMBER;
token.value = MATH_CONSTANTS.get(token.value) + '';
} else if (token.type === TOKEN_TYPE.BUILTIN && !MATH_FUNCTIONS.get(token.value)) {
throw new UnknownBuiltinError(token);
}
}
// Return the operation (+,-,*,/) if the next node is an operation node. Otherwise return null.
private getOperation(): Token {
return this.tokens.peekIfEither(TOKEN_TYPE.ADD, TOKEN_TYPE.SUBTRACT, TOKEN_TYPE.MULTIPLY, TOKEN_TYPE.DIVIDE);
}
// Expressions can only contain numbers or references (other than operations and parenthesis but they
// are resolved elsewhere)
private getValueFromToken(token: Token): ASTNode {
if (token.type === TOKEN_TYPE.NUMBER) {
return new NumberNode(token);
} else if (token.type === TOKEN_TYPE.NAME) {
return new ReferenceNode(token);
}
throw new UnexpectedTokenError(token, TOKEN_TYPE.NUMBER, TOKEN_TYPE.NAME);
}
// Parse an operation in the form
// <left> <operation> <right>
// where the value of the left side is passed as an argument and the right side is parsed
// from the stream
private parseOperation(left: ASTNode): ASTNode {
const operation = this.getOperation();
if (operation) {
this.tokens.next();
const operationNode = new OperationNode(operation);
operationNode.left = left;
operationNode.right = this.parse();
return operationNode;
} else {
return left;
}
}
/**
* Expression parser entry point
* @returns {ASTNode} An ASTNode representing the expression
*/
parse(): ASTNode {
const token = this.tokens.next();
this.replaceConstants(token);
if (token.type === TOKEN_TYPE.NUMBER || token.type === TOKEN_TYPE.NAME) {
// Ordinary expression
const valueNode = this.getValueFromToken(token);
return this.parseOperation(valueNode);
} else if (token.type === TOKEN_TYPE.BUILTIN) {
// Function call
this.tokens.expect(TOKEN_TYPE.LPAREN);
const expressionNode = this.parse();
this.tokens.expect(TOKEN_TYPE.RPAREN);
const functionCallNode = new FunctionCallNode(MATH_FUNCTIONS.get(token.value));
functionCallNode.argument = expressionNode;
return this.parseOperation(functionCallNode);
} else {
// Parenthesis
const expressionNode = this.parse();
this.tokens.expect(TOKEN_TYPE.RPAREN);
const operation = this.getOperation();
if (operation) {
return this.parseOperation(expressionNode);
} else {
return new InnerExpressionNode(expressionNode);
}
}
}
}
|
ade31b48e4b8542842eb7d89c04713f3852eef6e
|
TypeScript
|
Voya100/VoyaCode
|
/src/app/projects/color-picker/sliders/color-slider/color-slider.component.ts
| 2.59375
| 3
|
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
Output,
SimpleChanges,
ViewChild
} from '@angular/core';
/**
* Slider component that displays data input as a background and adds selector to x position that matches value input.
*/
@Component({
selector: 'color-slider',
templateUrl: 'color-slider.component.html',
styleUrls: ['./color-slider.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ColorSliderComponent implements AfterViewInit, OnChanges {
@ViewChild('sliderCanvas') sliderCanvas: ElementRef;
context: CanvasRenderingContext2D;
@Input() width: number;
@Input() height: number;
@Input() data: ImageData;
@Input() value: number;
@Input() selectorColor: string;
@Output() valueChange: EventEmitter<number> = new EventEmitter();
@Output() contextInit: EventEmitter<CanvasRenderingContext2D> = new EventEmitter();
constructor() {}
ngAfterViewInit() {
this.context = this.sliderCanvas.nativeElement.getContext('2d');
this.contextInit.emit(this.context);
}
// Updates background and/or color selector
ngOnChanges(changes: SimpleChanges) {
if (!this.context) {
return;
}
this.drawSlider();
}
drawSlider() {
this.context.putImageData(this.data, 0, 0);
this.drawSelectedValueIndicator();
}
drawSelectedValueIndicator() {
this.context.strokeStyle = this.selectorColor;
this.context.beginPath();
this.context.moveTo(this.value, 0);
this.context.lineTo(this.value, this.height);
this.context.stroke();
}
emitValueChange(value: number) {
this.valueChange.emit(Math.max(0, Math.min(value, this.width - 1)));
}
}
|
95fb262421ae3fde206abb0897a66e455b2d1190
|
TypeScript
|
hsuanxyz/ts-simple-ast
|
/src/structurePrinters/namespace/NamespaceDeclarationStructurePrinter.ts
| 2.5625
| 3
|
import { CodeBlockWriter } from "../../codeBlockWriter";
import { NamespaceDeclarationStructure } from "../../structures";
import { StructurePrinterFactory } from "../../factories";
import { FactoryStructurePrinter } from "../FactoryStructurePrinter";
import { BlankLineFormattingStructuresPrinter } from "../formatting";
export class NamespaceDeclarationStructurePrinter extends FactoryStructurePrinter<NamespaceDeclarationStructure> {
private readonly blankLineFormattingWriter = new BlankLineFormattingStructuresPrinter(this);
constructor(factory: StructurePrinterFactory, private readonly options: { isAmbient: boolean; }) {
super(factory);
}
printTexts(writer: CodeBlockWriter, structures: NamespaceDeclarationStructure[] | undefined) {
this.blankLineFormattingWriter.printText(writer, structures);
}
printText(writer: CodeBlockWriter, structure: NamespaceDeclarationStructure) {
this.factory.forJSDoc().printDocs(writer, structure.docs);
this.factory.forModifierableNode().printText(writer, structure);
writer.write(`${structure.hasModuleKeyword ? "module" : "namespace"} ${structure.name} `).inlineBlock(() => {
this.factory.forBodyText({
isAmbient: structure.hasDeclareKeyword || this.options.isAmbient
}).printText(writer, structure);
});
}
}
|
f5f5695d6b95e1048d5116106b4efcd0046410ba
|
TypeScript
|
matibm/padron-frontend
|
/src/app/pipes/primer-nombre.pipe.ts
| 2.609375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'primerNombre'
})
export class PrimerNombrePipe implements PipeTransform {
transform(nombreCompleto: String, ...args: unknown[]): unknown {
let nombre = nombreCompleto
nombre = nombre.split(' ')[0]
return nombre;
}
}
|
01a3968910af18d3bad5cf2577987814fedd2016
|
TypeScript
|
akshaynair319/infinite-canvas
|
/src/instructions/path-instruction-builders/from-point-to-point/path-instruction-builder-from-point-to-point.ts
| 2.71875
| 3
|
import {PathInstructionBuilder} from "../path-instruction-builder";
import {Position} from "../../../geometry/position";
import {isPointAtInfinity} from "../../../geometry/is-point-at-infinity";
import { PathInstructionBuilderProvider } from "../path-instruction-builder-provider";
import { InfiniteCanvasPathInstructionBuilder } from "../infinite-canvas-path-instruction-builder";
import { FromPointToPoint } from "./from-point-to-point";
import { FromPointToPointAtInfinity } from "../from-point-to-point-at-infinity/from-point-to-point-at-infinity";
import { InstructionUsingInfinity } from "../../instruction-using-infinity";
import { instructionSequence } from "../../../instruction-utils";
export class PathInstructionBuilderFromPointToPoint extends InfiniteCanvasPathInstructionBuilder<FromPointToPoint> implements PathInstructionBuilder{
constructor(private readonly pathBuilderProvider: PathInstructionBuilderProvider, shape: FromPointToPoint) {
super(shape);
}
protected getInstructionToMoveToBeginningOfShape(shape: FromPointToPoint): InstructionUsingInfinity{
return this.moveTo(shape.initialPoint);
}
protected getInstructionToExtendShapeWithLineTo(shape: FromPointToPoint, position: Position): InstructionUsingInfinity{
if(isPointAtInfinity(position)){
const lineToInfinityFromCurrent: InstructionUsingInfinity = this.lineToInfinityFromPointInDirection(shape.currentPosition, position.direction);
if(shape.currentPosition.minus(shape.initialPoint).cross(position.direction) === 0){
return lineToInfinityFromCurrent;
}
const lineToInfinityFromInitial: InstructionUsingInfinity = this.lineFromInfinityFromPointToInfinityFromPoint(shape.currentPosition, shape.initialPoint, position.direction);
return instructionSequence(lineToInfinityFromCurrent, lineToInfinityFromInitial);
}
return this.lineTo(position);
}
public canAddLineTo(position: Position): boolean{
return true;
}
public containsFinitePoint(): boolean{
return true;
}
public isClosable(): boolean{
return true;
}
public addPosition(position: Position): PathInstructionBuilder{
if(isPointAtInfinity(position)){
return this.pathBuilderProvider.fromPointToPointAtInfinity(new FromPointToPointAtInfinity(this.shape.initialPoint, position));
}
return this.pathBuilderProvider.fromPointToPoint(new FromPointToPoint(this.shape.initialPoint, position));
}
}
|
133a14d65b49dfaf92d81424cb9151726adabf3c
|
TypeScript
|
ldrly-tristan/dankest-dungeon
|
/src/app/lib/entity/static-entity-data-accessor.ts
| 2.875
| 3
|
import { AssetKey, AssetType } from '../../asset-enums';
import { StaticEntityDataId } from '../../lib/entity';
import { StaticEntityData } from '../../models/entity';
/**
* Static entity data accessor.
*/
export class StaticEntityDataAccessor<T, U extends StaticEntityData<T>, V> {
/**
* Instantiate static entity data accessor.
*
* @param cache Cache manager.
* @param assetType Asset type.
* @param assetKey Asset key.
*/
public constructor(
protected readonly cache: Phaser.Cache.CacheManager,
protected readonly assetType: AssetType,
protected readonly assetKey: AssetKey
) {}
/**
* Get static data index.
*/
public get index(): V {
return this.cache[this.assetType].get(this.assetKey);
}
/**
* Get static entity data.
*
* @param staticEntityDataId Static entity data id.
*/
public get(staticEntityDataId: StaticEntityDataId): U | void {
return this.index[staticEntityDataId];
}
}
|
5674b51d3265efa7258a852ae54898a51e1abf72
|
TypeScript
|
TeikokuDB/unacast
|
/src/main/youtube-chat/live-chat.ts
| 2.546875
| 3
|
import { EventEmitter } from 'events';
import axios from 'axios';
import { actionToRenderer, CommentItem, parseData } from './parser';
import { sleep } from '../util';
type LiveChatResponse = [
{
page: string;
csn: string;
},
{
url: string;
response: {
responseContext: any;
contents: {
liveChatRenderer: {
actions: Action[];
};
};
};
timing: any;
page: string;
endpoint: string;
csn: string;
xsrf_token: string;
},
];
/**
* YouTubeライブチャット取得イベント
*/
export class LiveChat extends EventEmitter {
private static readonly headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' };
/** チャンネルID */
public readonly channelId?: string;
/** 配信ID */
public liveId?: string;
/** 表示済みのID */
private displayedId: { [commentId: string]: true } = {};
private isFirst = true;
private observer?: NodeJS.Timeout;
/** 停止要求をされた */
private isStop = false;
constructor(options: { channelId: string } | { liveId: string }, private interval = 1000) {
super();
if ('channelId' in options) {
this.channelId = options.channelId;
} else if ('liveId' in options) {
this.liveId = options.liveId;
} else {
throw TypeError('Required channelId or liveId.');
}
}
public start() {
this.isFirst = true;
this.isStop = false;
this.fetchLiveId();
}
private async fetchLiveId() {
if (this.isStop) return;
if (this.channelId) {
const url = `https://www.youtube.com/channel/${this.channelId}/live`;
try {
const liveRes = await axios.get(url, { headers: LiveChat.headers });
// if (liveRes.data.match(/LIVE_STREAM_OFFLINE/)) {
// this.emit('error', new Error('Live stream offline'));
// return false;
// }
this.liveId = liveRes.data.match(/videoId\\":\\"(.+?)\\/)?.[1] as string;
} catch (e) {
// チャンネルID自体が違うのはもうどうしようもないので止める
this.emit('error', new Error(`connection error url = ${url}`));
return;
}
}
if (this.liveId) {
this.observer = setInterval(() => this.fetchChat(), this.interval);
this.emit('start', this.liveId);
} else {
// 配信が開始してないパターンが考えられるのでリトライ
this.emit('error', new Error('Live stream not found'));
await sleep(2000);
this.fetchLiveId();
}
}
public stop(reason?: string) {
this.isStop = true;
if (this.observer) {
clearInterval(this.observer);
this.emit('end', reason);
}
this.displayedId = {};
}
private async fetchChat() {
const url = `https://www.youtube.com/live_chat?v=${this.liveId}&pbj=1`;
try {
const res = await axios.get<LiveChatResponse>(url, { headers: LiveChat.headers });
// if (res.data[1].response.contents.messageRenderer) {
// this.stop('Live stream is finished');
// return;
// }
// 前回取得したidより新しいチャットを取得する
// actions配列の末尾は入室メッセージみたいなやつなので除外する
const temp = res.data[1].response.contents.liveChatRenderer.actions.slice(0, -1).filter((v: Action) => {
const messageRenderer = actionToRenderer(v);
return messageRenderer !== null && messageRenderer;
});
const items = temp.map((v: Action) => parseData(v));
// 初回取得の場合は初期データとして出力
items.forEach((v) => {
if (v) {
if (this.isFirst) {
this.emit('firstComment', v);
} else {
// 表示済みならスキップ
if (!this.displayedId[v.id]) {
this.emit('comment', v);
}
}
}
});
this.isFirst = false;
// 末尾のidを取得
console.log(`[Youtube-chat] items = ${items.length}`);
items.forEach((v) => {
const id = v?.id;
if (id) this.displayedId[id] = true;
});
} catch (e) {
this.emit('error', new Error(`Error occured at fetchchat url=${url}`));
}
}
public on(event: 'firstComment', listener: (comment: CommentItem) => void): this;
public on(event: 'comment', listener: (comment: CommentItem) => void): this;
public on(event: 'start', listener: (liveId: string) => void): this;
public on(event: 'end', listener: (reason?: string) => void): this;
public on(event: 'error', listener: (err: Error) => void): this;
public on(event: string | symbol, listener: (...args: any[]) => void): this {
return super.on(event, listener);
}
}
|
2ef7f5493f8c288331015b8dd6a1974d36afabdf
|
TypeScript
|
jonamat/telegram-socket-bot
|
/tests/unit/utils/getAlias.test.ts
| 2.53125
| 3
|
/* ----------------------------- Unit test suite ---------------------------- *
*
* Target: getAlias function
* Tests:
* - Behavior
* - Data consistency
*
* -------------------------------------------------------------------------- */
import { mocked } from 'ts-jest/utils';
import validatePartialSchema from '@Tests/validatePartialSchema';
import Alias from '@App/models/Alias';
import getAlias from '@App/utils/getAlias';
/* -------------------------------------------------------------------------- */
/* Mocks */
/* -------------------------------------------------------------------------- */
jest.mock('@App/utils/report');
const mockedAlias = mocked<any>(Alias);
jest.mock('@App/models/Alias', () => ({
findOne: jest.fn<any, any>(() => Alias),
create: jest.fn(),
exec: jest.fn<any, any>(() =>
Promise.resolve({
alias: 'mock_alias',
}),
),
}));
/* -------------------------------------------------------------------------- */
/* Bridge operations */
/* -------------------------------------------------------------------------- */
beforeEach(() => {
jest.clearAllMocks();
mockedAlias.exec.mockImplementation(() =>
Promise.resolve({
alias: 'mock_alias',
}),
);
});
/* -------------------------------------------------------------------------- */
/* Wrapper function */
/* -------------------------------------------------------------------------- */
/**
* Run the target function with the test configuration
* @param userId Override user id arg
* @param socketId Override socket id arg
*/
const run = (userId = 'mock_userId', socketId = 'mock_socketId') => {
return getAlias(userId, socketId);
};
/* -------------------------------------------------------------------------- */
/* Tests */
/* -------------------------------------------------------------------------- */
describe('Behavior', () => {
it('returns a string alias if it was found in the db', async () => {
const alias = await run();
expect(alias).toBe('mock_alias');
});
it('returns a generated string alias if not present in db', async () => {
mockedAlias.exec.mockImplementation(() => Promise.resolve(null));
const alias = await run();
expect(mockedAlias.exec).toBeCalledTimes(2);
expect(alias).not.toBe('mock_alias');
expect(parseInt(alias)).toBeTruthy();
});
it('upload a new alias document if it was been generated locally', async () => {
mockedAlias.exec.mockImplementation(() => Promise.resolve(null));
const alias = await run();
expect(alias).not.toBe('mock_alias');
expect(mockedAlias.create).toBeCalledTimes(1);
});
it('throws an exception on db error', async () => {
mockedAlias.exec.mockImplementationOnce(() => Promise.reject());
await run().catch((error) => expect(error).toBeTruthy());
});
});
describe('Data consistency', () => {
it('searches for existent socketIds with valid properties', async () => {
await run();
await validatePartialSchema(
jest.requireActual('@App/models/Alias').default,
mockedAlias.findOne.mock.calls[0][0],
);
expect(mockedAlias.findOne).toBeCalledTimes(1);
expect(mockedAlias.findOne).toBeCalledWith({ userId: 'mock_userId', socketId: 'mock_socketId' });
});
it('searches for existent alias with valid properties', async () => {
mockedAlias.exec.mockImplementation(() => Promise.resolve(null));
await run();
await validatePartialSchema(
jest.requireActual('@App/models/Alias').default,
mockedAlias.findOne.mock.calls[1][0],
);
expect(mockedAlias.findOne).toBeCalledTimes(2);
});
it('create a new valid alias document', async () => {
mockedAlias.exec.mockImplementation(() => Promise.resolve(null));
await run();
await validatePartialSchema(
jest.requireActual('@App/models/Alias').default,
mockedAlias.create.mock.calls[0][0],
);
expect(mockedAlias.create).toBeCalledTimes(1);
});
});
|
7adaf9de8aa4bf7e4237fb3d56237b0641db4464
|
TypeScript
|
Gui-dev/node-next
|
/api/src/modules/users/infra/typeorm/entities/User.ts
| 2.65625
| 3
|
import { Column, CreateDateColumn, Entity, PrimaryColumn } from 'typeorm'
import { v4 as uuid } from 'uuid'
@Entity('users')
export class User {
@PrimaryColumn()
public readonly id: string
@Column()
public name: string
@Column()
public email: string
@CreateDateColumn()
// eslint-disable-next-line camelcase
public created_at: Date
constructor () {
if (!this.id) {
this.id = uuid()
}
}
}
|
96cace83451837d19fb21391092f884054191305
|
TypeScript
|
stv94/fun-di
|
/main.ts
| 3.265625
| 3
|
import {injectable, Kernel} from "./src"
abstract class IPerson{
abstract name: string;
}
@injectable
class Human implements IPerson {
constructor(public name: string){};
}
abstract class IWeapon{
abstract kill(person: IPerson);
}
@injectable
class FiberWire implements IWeapon {
kill(person: IPerson) {
console.log(person.name + " has strangled");
}
}
@injectable
class Hitman{
constructor(private person : IPerson, private weapon: IWeapon){}
public doWork(){
this.weapon.kill(this.person);
}
}
var kernel = new Kernel()
.setBind(String, "007")
.setBindType(IWeapon, FiberWire)
.setBindType(IPerson, Human)
//.setBind(IPerson, new Human("008"))
.setBindType(Hitman, Hitman);
let hitman = kernel.get(Hitman);
hitman.doWork();
|
c53026609013bfcad137d3181ff51b2727b52866
|
TypeScript
|
Nishant1500/discord-economy-super
|
/typings/interfaces/WorkObject.d.ts
| 2.734375
| 3
|
import TimeObject from './TimeObject'
/**
* Object that returns on 'Economy.work()' method.
*/
declare class WorkObject {
/**
* The status of receiving money.
*/
status: boolean
/**
* If reward is already claimed: time object; else: work reward.
*/
value: TimeObject
/**
* If reward is already claimed: formatted time in string; else: work reward.
*/
pretty: string | number
/**
* Work reward.
*/
reward: number | Number[]
}
export = WorkObject
|
e6c07f77e7d0f279215174f7931b03b71bb48231
|
TypeScript
|
lightningkite/butterfly-web
|
/src/views/html.ts
| 2.6875
| 3
|
import {post} from "../delay";
import {xViewRemovedGet} from "../rx/DisposeCondition.ext";
import {DisposableLambda} from "../rx/DisposableLambda";
export function loadHtmlFromString(data: string): HTMLElement {
const d = document.createElement("div");
d.innerHTML = data;
return d.firstChild as HTMLElement;
}
export function findViewById<T extends HTMLElement>(view: HTMLElement, id: string): T | null {
if(view.classList.contains(`id-${id}`)) return view as (T | undefined) ?? null;
return (view.getElementsByClassName(`id-${id}`)[0] as (T | undefined)) ?? null;
}
export function getViewById<T extends HTMLElement>(view: HTMLElement, id: string): T {
if(view.classList.contains(`id-${id}`)) return view as T;
return view.getElementsByClassName(`id-${id}`)[0] as T;
}
export function replaceViewWithId(base: HTMLElement, withElement: () => HTMLElement, id: string) {
const existing = findViewById(base, id);
if (existing) {
const newElement = withElement();
newElement.setAttribute('style', newElement.getAttribute('style') + '; ' + existing.getAttribute('style'));
existing.parentNode!.replaceChild(newElement, existing);
}
}
declare global {
interface HTMLElement {
khrysalisResizeBoundaryAction?: ()=>void
}
}
export function startupAutoResize(element: HTMLElement, sizeBoundaries: Array<number>){
// function doIt(){
// const startSize = window.innerWidth
// let minSize = 0
// let maxSize = Number.MAX_SAFE_INTEGER
// for(const boundary of sizeBoundaries){
// if(startSize > boundary) {
// minSize = boundary
// break
// }
// maxSize = boundary
// }
// let lastCall = Date.now()
// const listener = () => {
// const newSize = window.innerWidth
// if(newSize > 0 && newSize < minSize || newSize > maxSize) {
// if(element.khrysalisResizeBoundaryAction && Date.now() - lastCall > 2000) {
// window.removeEventListener("resize", listener)
// lastCall = Date.now()
// console.log(`Broke boundary box from ${minSize} to ${maxSize} with ${newSize}`)
// element.khrysalisResizeBoundaryAction()
// }
// }
// }
// window.addEventListener("resize", listener)
// xViewRemovedGet(element).call(new DisposableLambda(() => {
// window.removeEventListener("resize", listener)
// }))
// }
// function wait(){
// post(()=>{
// if(element.scrollWidth > 0) {
// doIt()
// } else {
// wait()
// }
// })
// }
// wait()
}
|
72f5cbb99b9f72e63cc0e46669c93390d20ff0b9
|
TypeScript
|
yujidxl/background-application
|
/src/utils/index.ts
| 2.90625
| 3
|
export function param2Obj(url: string) {
const search = url.split('?')[1];
if (!search) {
return {};
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
}
export function fixNum(num: number): string {
return num > 9 ? '' + num : '0' + num;
}
export function formatTime(time: Date) {
if (time instanceof Date) {
const year = time.getFullYear();
const month = time.getMonth() + 1;
const date = time.getDate();
const hours = time.getHours();
const minutes = time.getMinutes();
const seconds = time.getSeconds();
return (
[year, fixNum(month), fixNum(date)].join('/') +
' ' +
[fixNum(hours), fixNum(minutes), fixNum(seconds)].join(':')
);
}
return '';
}
|
899413e568e90902db71e00cd8710c18cda1b752
|
TypeScript
|
bolinfest/typescript
|
/tests/ls/getInScopeNamesAndTypesFromPosition.ts
| 2.625
| 3
|
///<reference path='..\..\src\compiler\typescript.ts' />
///<reference path='..\..\src\harness\harness.ts' />
describe('getInScopeNamesAndTypesFromPosition', function () {
var code: string = Harness.readFile('ls/testCode/scopelist.ts');
var script: TypeScript.Script = null;
var ls: TypeScript.TypeScriptCompiler = null;
function initCompiler(code: string) {
if (!script) {
Harness.Compiler.recreate();
Harness.Compiler.compileString(code, "test.ts", function (result) {
script = result.scripts[0];
}, true);
ls = Harness.Compiler.compiler;
}
}
function namesAndTypesAtPos(code: string, line: number, col: number) {
initCompiler(code);
var lineMap = script.locationInfo.lineMap;
var offset = lineMap[line] + col;
var text = new TypeScript.StringSourceText(code);
var pos = offset;
var isMemberCompletion = false;
var logger = new TypeScript.NullLogger();
var enclosingScopeContext = TypeScript.findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion);
return new TypeScript.ScopeTraversal(ls).getScopeEntries(enclosingScopeContext);
}
function memberCompletionAtPos(code: string, line: number, col: number) {
initCompiler(code);
var lineMap = script.locationInfo.lineMap;
var offset = lineMap[line] + col;
var text = new TypeScript.StringSourceText(code);
var pos = offset;
var isMemberCompletion = true;
var logger = new TypeScript.NullLogger();
var enclosingScopeContext = TypeScript.findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion);
return new TypeScript.ScopeTraversal(ls).getScopeEntries(enclosingScopeContext);
}
function verifyNamesAndTypes(namesAndTypes: TypeScript.ScopeEntry[], spec: any) {
var found: bool;
var names = namesAndTypes;
for (name in spec) {
found = false;
for (var i = 0; i < names.length; i++) {
if (names[i].name === name) {
found = true;
if (names[i].type !== spec[name]) {
throw new Error("Expected " + name + " to be of type " + spec[name] + ", is of type " + names[i].type);
}
break;
}
}
if (!found)
throw new Error("Expected to find name '" + name + "'");
}
}
function verifyEmptyList(namesAndTypes: TypeScript.ScopeEntry[]) {
var names = namesAndTypes;
if (names.length > 0) {
throw new Error("Item contains more then expected. Expected 0, had " + names.length);
}
}
function verifyNotListed(namesAndTypes: TypeScript.ScopeEntry[], spec: any) {
var found: bool;
var names = namesAndTypes;
for(var item in spec) {
found = false;
for (var i = 0; i < names.length; i++) {
if (names[i] === spec[item]) {
throw new Error("Expected to not have " + spec[item] + " on the list");
}
}
}
}
describe('scope completion', function () {
it("gets names from global scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 1, 0);
verifyNotListed(namesAndTypes, [
'mod1var',
'mod1fn',
'mod1cls',
'mod1int',
'mod1mod',
'mod1evar',
'mod1efn',
'mod1ecls',
'mod1eint',
'mod1emod',
'mod1eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1': 'mod1',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint'
});
});
it("gets names from module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 4, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'mod1exvar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'mod2': 'mod2',
'mod3': 'mod3'
});
});
it("gets names from function scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 244, 0);
verifyNotListed(namesAndTypes, [
'mod1var',
'mod1fn',
'mod1cls',
'mod1int',
'mod1mod',
'mod1evar',
'mod1efn',
'mod1ecls',
'mod1eint',
'mod1emod',
'mod1eexvar',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'sfvar': 'number',
'sffn': '() => void'
});
});
it("gets types from class scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 250, 0);
verifyNotListed(namesAndTypes, [
'mod1var',
'mod1fn',
'mod1cls',
'mod1int',
'mod1mod',
'mod1evar',
'mod1efn',
'mod1ecls',
'mod1eint',
'mod1emod',
'mod1eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'sivar',
'sifn',
'scpfn',
'scpvar'
]);
});
it("gets types from interface scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 260, 0);
verifyNotListed(namesAndTypes, [
'mod1var',
'mod1fn',
'mod1cls',
'mod1int',
'mod1mod',
'mod1evar',
'mod1efn',
'mod1ecls',
'mod1eint',
'mod1emod',
'mod1eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn'
]);
verifyNamesAndTypes(namesAndTypes, {
'sivar': 'any',
'sifn': '(bar: any) => any'
});
});
it("gets types from function inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 6, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'mod1exvar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'bar': 'number',
'foob': '() => void',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint'
});
});
it("gets types from class inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 12, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'foovar',
'foosfunc',
'mod1exvar',
'ceFunc',
'ceVar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
});
});
it("gets types from interface inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 20, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'foovar',
'foosfunc'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'bar': 'any',
'foob': '(bar: any) => any'
});
});
it("gets types from exported function inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 6, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'mod1exvar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'bar': 'number',
'foob': '() => void',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint'
});
});
it("gets types from an exported class inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 34, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'foovar',
'foosfunc',
'mod1exvar',
'ceFunc',
'ceVar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint'
// 'csVar': 'number',
// 'csFunc': '() => void'
});
});
it("gets types from exported interface inside a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 42, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'foovar',
'foosfunc'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'bar': 'any',
'foob': '(bar: any) => any'
});
});
it("gets names from module in a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 49, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'mod1exvar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'mod2': 'mod2',
'mod3': 'mod3',
'm1X': 'number',
'm1Func': 'm1Func',
'm1Class': '{ csVar: number; csFunc(): void; new(): m1Class; }',
'm1Int': 'm1Int',
'm1Mod': 'm1Mod',
'm1eX': 'number',
'm1eFunc': 'm1eFunc',
'm1eClass': '{ csVar: number; csFunc(): void; new(): m1eClass; }',
'm1eInt': 'm1eInt',
'm1eMod': 'm1eMod'
});
});
it("gets names from an exported module in a module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 95, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn',
'mod1exvar'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1var': 'number',
'mod1fn': 'mod1fn',
'mod1cls': '{ csVar: number; csFunc(): void; new(): mod1cls; }',
'mod1int': 'mod1int',
'mod1mod': 'mod1mod',
'mod1evar': 'number',
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'mod2': 'mod2',
'mod3': 'mod3',
'mX': 'number',
'mFunc': 'mFunc',
'mClass': '{ csVar: number; csFunc(): void; new(): mClass; }',
'mInt': 'mInt',
'mMod': 'mMod',
'meX': 'number',
'meFunc': 'meFunc',
'meClass': '{ csVar: number; csFunc(): void; new(): meClass; }',
'meInt': 'meInt',
'meMod': 'meMod'
});
});
it("gets names from an extended module scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 143, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1efn': 'mod1efn',
'mod1ecls': '{ csVar: number; csFunc(): void; new(): mod1ecls; }',
'mod1eint': 'mod1eint',
'mod1emod': 'mod1emod',
'mod1eexvar': 'number',
'mod1exvar': 'number',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'mod2': 'mod2',
'mod3': 'mod3'
});
});
it("gets names from a module with from", function () {
var namesAndTypes = namesAndTypesAtPos(code, 277, 0);
verifyNotListed(namesAndTypes, [
'mod1var',
'mod1fn',
'mod1cls',
'mod1int',
'mod1mod',
'mod1evar',
'mod1efn',
'mod1ecls',
'mod1eint',
'mod1emod',
'mod1eexvar',
'mX',
'mFunc',
'mClass',
'mInt',
'mMod',
'meX',
'meFunc',
'meClass',
'meInt',
'meMod',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1': 'mod1',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'string',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
});
});
it("gets names from a shadow module with no export", function () {
var namesAndTypes = namesAndTypesAtPos(code, 194, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'shwvar': 'string',
'shwfn': 'shwfn',
'shwcls': '{ csVar: number; csFunc(): void; new(shadow: any): shwcls; }',
'shwint': 'shwint',
});
});
it("gets names from a shadow module with export", function () {
var namesAndTypes = namesAndTypesAtPos(code, 219, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'shwvar': 'string',
'shwfn': 'shwfn',
'shwcls': '{ csVar: number; csFunc(): void; new(shadow: any): shwcls; }',
'shwint': 'shwint',
});
});
it("gets names from extended class scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 4, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint',
'mod2': 'mod2',
'mod3': 'mod3'
});
});
it("checks for the type of shadow var (#1)", function () {
var namesAndTypes = namesAndTypesAtPos(code, 280, 0);
verifyNamesAndTypes(namesAndTypes, {
'shwvar': 'string'
});
});
it("checks for the type of shadow var (#2)", function () {
var namesAndTypes = namesAndTypesAtPos(code, 281, 0);
verifyNamesAndTypes(namesAndTypes, {
'shwvar': 'string'
});
});
it("gets names from object literal scope", function () {
var namesAndTypes = namesAndTypesAtPos(code, 287, 0);
verifyNotListed(namesAndTypes, [
'mod2var',
'mod2fn',
'mod2cls',
'mod2int',
'mod2mod',
'mod2evar',
'mod2efn',
'mod2ecls',
'mod2eint',
'mod2emod',
'mod2eexvar',
'mod1exvar',
'sfvar',
'sffn',
'sfsvar',
'sfsfn',
'scvar',
'scfn',
'scpfn',
'scpvar',
'scsvar',
'scsfn',
'sivar',
'sifn'
]);
verifyNamesAndTypes(namesAndTypes, {
'mod1': 'mod1',
'mod2': 'mod2',
'mod3': 'mod3',
'shwvar': 'number',
'shwfn': 'shwfn',
'shwcls': '{ scsvar: number; scsfn(): void; new(): shwcls; }',
'shwint': 'shwint'
});
});
});
});
|
c5f77f13bfd6ffaaa98c59fce17c633d9ca4f280
|
TypeScript
|
jirevwe/ts-starter
|
/src/data/base/base.repo.ts
| 2.734375
| 3
|
import { injectable, unmanaged } from 'inversify';
import mongoose, { Model, Schema, FilterQuery } from 'mongoose';
import { DuplicateModelError, ModelNotFoundError } from '.';
import { Repository, Query, QueryResult, PaginationQuery } from '.';
@injectable()
export class BaseRepository<T> implements Repository<T> {
protected model: Model<T>;
constructor(
@unmanaged() private name: string,
@unmanaged() schema: Schema<T>
) {
this.model = mongoose.model<T>(name, schema);
}
/**
* checks if the archived argument is either undefined
* or passed as a false string in the cause of query params, and
* converts it to a boolean.
* @param archived string or boolean archived option
*/
convertArchived = (archived: string | boolean) =>
archived === undefined || archived === 'false' ? false : true;
/**
* Converts a passed condition argument to a query
* @param condition string or object condition
*/
getQuery = (condition: string | object): FilterQuery<any> => {
return typeof condition === 'string'
? { _id: condition }
: { ...condition };
};
/**
* Creates one or more documets.
*/
create(attributes: any): Promise<T> {
return new Promise((resolve, reject) => {
this.model.create(
attributes,
(err: { code: number }, result: T | PromiseLike<T>) => {
if (err && err.code === 11000)
return reject(
new DuplicateModelError(`${this.name} exists already`)
);
if (err) return reject(err);
resolve(result);
}
);
});
}
/**
* Finds a document by it's id
* @param _id
* @param projections
* @param archived
*/
byID(_id: string, projections?: any, archived?: boolean): Promise<T> {
return new Promise((resolve, reject) => {
archived = this.convertArchived(archived);
const query: FilterQuery<any> = {
_id,
...(!archived
? { deleted_at: undefined }
: { deleted_at: { $ne: undefined } })
};
this.model
.findOne(query)
.select(projections)
.exec((err, result) => {
if (err) return reject(err);
if (!result)
return reject(new ModelNotFoundError(`${this.name} not found`));
resolve(result);
});
});
}
/**
* Finds a document by an object query.
* @param query
* @param projections
* @param archived
*/
async byQuery(query: any, projections?: any, archived?: boolean | string) {
archived = this.convertArchived(archived);
return this.model
.findOne({
...query,
...(!archived
? { deleted_at: undefined }
: { deleted_at: { $ne: undefined } })
})
.select(projections);
}
/**
* Finds all documents that match a query
* @param query
*/
all(query: Query): Promise<T[]> {
return new Promise((resolve, reject) => {
const sort = query.sort || 'created_at';
this.model
.find({
...query.conditions,
deleted_at: undefined
})
.select(query.projections)
.sort(sort)
.exec((err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}
/**
* Same as `all()` but returns paginated results.
* @param query Query
*/
list(query: PaginationQuery): Promise<QueryResult<T>> {
return new Promise((resolve, reject) => {
const page = Number(query.page) - 1 || 0;
const per_page = Number(query.per_page) || 20;
const offset = page * per_page;
const sort = query.sort || 'created_at';
const archived = this.convertArchived(query.archived);
this.model
.find({
...query.conditions,
...(!archived
? { deleted_at: undefined }
: { deleted_at: { $ne: undefined } })
})
.limit(per_page)
.select(query.projections)
.skip(offset)
.sort(sort)
.exec((err, result) => {
if (err) return reject(err);
const queryResult = {
page: page + 1,
per_page,
sort,
result
};
resolve(queryResult);
});
});
}
/**
* Updates a single document that matches a particular condition.
* Triggers mongoose `save` hooks.
* @param condition
* @param update
*/
update(condition: string | object, update: any): Promise<T> {
const query = this.getQuery(condition);
return new Promise((resolve, reject) => {
this.model.findOne(
query,
(
err: any,
result: {
set: (arg0: any) => void;
save: (arg0: (err: any, updatedDocument: any) => void) => void;
}
) => {
if (err) return reject(err);
if (!result)
return reject(new ModelNotFoundError(`${this.name} not found`));
result.set(update);
result.save((err: any, updatedDocument: T | PromiseLike<T>) => {
if (err) return reject(err);
resolve(updatedDocument);
});
}
);
});
}
/**
* Allows the user of atomic operators such as $inc in updates.
* Note: It does not trigger mongoose `save` hooks.
* @param condition Query condition to match against documents
* @param update The document update
*/
updateWithOperators(condition: string | object, update: any): Promise<T> {
const query = this.getQuery(condition);
return new Promise((resolve, reject) => {
this.model.findOneAndUpdate(
query,
update,
{ new: true },
(err, result) => {
if (err) return reject(err);
if (!result)
return reject(new ModelNotFoundError(`${this.name} not found`));
resolve(result);
}
);
});
}
/**
* Updates multiple documents that match a query
* @param condition
* @param update
*/
updateAll(condition: string | object, update: any): Promise<T[]> {
const query = this.getQuery(condition);
return new Promise((resolve, reject) => {
this.model.updateMany(query, update, {}, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}
/**
* Soft deletes a document by created `deleted_at` field in the document and setting it to true.
* @param condition
*/
remove(condition: string | object): Promise<T> {
return new Promise((resolve, reject) => {
const query: FilterQuery<any> = this.getQuery(condition);
const updateQuery: any = {
deleted_at: new Date()
};
const opt = {
new: true
};
this.model.findOneAndUpdate(query, updateQuery, opt, (err, result) => {
if (err) return reject(err);
if (!result)
return reject(new ModelNotFoundError(`${this.name} not found`));
resolve(result);
});
});
}
/**
* Permanently deletes a document by removing it from the collection(DB)
* @param condition
*/
destroy(condition: string | object): Promise<T> {
return new Promise((resolve, reject) => {
const query = this.getQuery(condition);
this.model.findOneAndDelete(query, {}, (err, result) => {
if (err) return reject(err);
if (!result)
return reject(new ModelNotFoundError(`${this.name} not found`));
resolve(result);
});
});
}
}
|
bcdbdac4d5460931f0969df88e74c9125138df3a
|
TypeScript
|
Klynger/nest-rest-generator
|
/src/templates/model.template.ts
| 2.75
| 3
|
import { pipe } from 'ramda';
import { addIdentationSpacesFn } from '../utils';
import { DEFAULT_TAB_SIZE, FileType } from '../shared/constants';
import { Import, FileImport, generateImports } from './imports.template';
import { CreateModelDto, ModelAttribute, ImportableModelAttribute } from '../shared/models/create-model.dto';
export function generateClass(createModelDto: CreateModelDto, imports: Import[], tabSize: number = DEFAULT_TAB_SIZE) {
const { attributes, entityName } = createModelDto;
const generateAttributeWithIdentation = pipe(generateAttribute, addIdentationSpacesFn(tabSize));
const attrs = attributes.map(generateAttributeWithIdentation).join('\n');
const modelName = `${entityName}Model`;
let importsCode = '';
if (imports.length > 0) {
importsCode = generateImports(imports) + '\n\n';
}
if (attributes.length > 0) {
return `${importsCode}export class ${modelName} {
${attrs}
}
`;
}
return `export class ${modelName} {}
`;
}
function isImportable(attr: ModelAttribute) {
return typeof attr.type !== 'string' && attr.type.importable;
}
// Remove Array if the type is an Array
function transformToEntityName(importableTypeName: string) {
return importableTypeName.replace(/\[\]/g, '');
}
function transformToImports(entityName: string): FileImport {
return {
fileType: FileType.model,
sameFolder: false,
namePascalCase: entityName,
};
}
/**
* I'm assuming that models can only import models.
*/
export function discoverModelImports(attrs: ModelAttribute[]) {
return attrs
.filter(isImportable)
.map((attr: ImportableModelAttribute) => attr.type.typeName)
.map(transformToEntityName)
.map(transformToImports);
}
function generateAttribute(attr: ModelAttribute) {
const { name, required, type } = attr;
const requiredCode = required ? '' : '?';
const typeCode = typeof type === 'string' ? type : type.typeName;
const attributeCode = `${name}${requiredCode}: ${typeCode};`;
return attributeCode;
}
|
e0c7433da15407bb83d2dbb02b369306c2471ab6
|
TypeScript
|
wuzinong/JsLearning
|
/DotNetCoreSingleApplication/SSR-REACT/Scripts/async-thunks.ts
| 2.515625
| 3
|
import {receiveHelloWorldData,IHelloWorldData} from './redux-actions';
import {fetch,addTask} from 'domain-task';
// export function retrieveData() {
// return (dispatch: <T>(action: any) => T, getState: () => any) => {
// fetch('/Home/GetHelloWorldData', { method: 'get' })
// .then(response => response.json())
// .then((data: IHelloWorldData) => dispatch(receiveHelloWorldData(data)))
// .catch(() => { }); // ignore errors in this example
// }
// }
export function retrieveData() {
return (dispatch: <T>(action: any) => T, getState: () => any) => {
var p = fetch('/Home/GetHelloWorldData', { method: 'get' })
.then(response => response.json())
.then((data: IHelloWorldData) => dispatch(receiveHelloWorldData(data)))
.catch(() => { }); // ignore errors in this example
addTask(p);
}
}
|
116a92cf886c7ee706321e9469f3bea737958c1b
|
TypeScript
|
exegesis-js/exegesis
|
/samples/typescript-example/server.ts
| 2.796875
| 3
|
//Import librarys used
import * as express from 'express';
import * as exegesisExpress from 'exegesis-express';
import * as path from 'path';
//You may choose HTTP or HTTPS, if HTTPS you need a SSL Cert
import * as http from 'http';
import * as https from 'https';
const PORT = 3000;
async function createServer() {
// See https://github.com/exegesis-js/exegesis/blob/master/docs/Options.md
const options = {
controllers: path.resolve(__dirname, './controllers'),
controllersPattern: "**/*.@(ts|js)"
};
// This creates an exegesis middleware, which can be used with express,
// connect, or even just by itself.
const exegesisMiddleware = await exegesisExpress.middleware(
path.resolve(__dirname, './openapi.yaml'),
options
);
const app = express();
// If you have any body parsers, this should go before them.
app.use(exegesisMiddleware);
// Return a 404
app.use((req, res) => {
res.status(404).json({message: `Not found`});
});
// Handle any unexpected errors
app.use((err, req, res, next) => {
res.status(500).json({message: `Internal error: ${err.message}`});
});
//Used to create a HTTP Server
const server = http.createServer(app);
/**
* If you want to run a HTTPS server instead you must:
* + Get a SSL Cert and Key to use
* + Change the server type from http to https as shown below
*
const httpsOptions = {
key: fs.readFileSync('./config/key.pem'),
cert: fs.readFileSync('./config/cert.pem')
}
const server = https.createServer(httpsOptions,app);
*/
return server;
}
//Run our createServer function
createServer()
.then(server => {
server.listen(PORT);
console.log("Listening on port 3000");
console.log("Try visiting http://localhost:3000/greet?name=Jason");
})
.catch(err => {
console.error(err.stack);
process.exit(1);
});
|
3e300f423282c697ddf59ef21f0c61344553120d
|
TypeScript
|
TJAlferes/nobullshitcooking-api
|
/src/modules/chat/message/model.ts
| 2.9375
| 3
|
import { assert, string } from 'superstruct';
import { GenerateUUIDv7StringId, UUIDv7StringId } from './shared';
export class Chatmessage {
private chatmessage_id;
private kind;
private chatroom_id;
private sender_id;
private receiver_id;
private content;
private image_id;
private video_id;
// Timestamps -- handled by MySQL
private created_at: Date | null = null;
private updated_at: Date | null = null;
private constructor(params: ConstructorParams) {
this.chatmessage_id = UUIDv7StringId(params.chatmessage_id);
this.kind = Kind(params.kind);
this.chatroom_id = UUIDv7StringId(params.chatroom_id);
this.sender_id = Username(params.sender_id); // ALSO ALLOW SOCKETS ?
this.receiver_id = Username(params.receiver_id); // ALSO ALLOW SOCKETS ?
this.content = Content(params.content);
this.image_id = params.image_id ? UUIDv7StringId(params.image_id) : undefined;
this.video_id = params.video_id ? UUIDv7StringId(params.video_id) : undefined;
}
static create(params: CreateParams) {
const chatmessage_id = GenerateUUIDv7StringId();
const chatMessage = new Chatmessage({...params, chatmessage_id});
return chatMessage;
}
//static update(params: UpdateParams) {}
}
export function Kind(kind: typeof PRIVATE | typeof PUBLIC) {
if (kind === "private" || kind === "public") {
return kind;
}
throw new Error ("Chat message kind must be 'private' or 'public'");
}
export function Username(username: string) {
assert(username, string());
if (username.length < 6) {
throw new Error("Username must be at least 6 characters.");
}
if (username.length > 20) {
throw new Error("Username must be no more than 20 characters.");
}
return username;
}
export function Content(content: string) {
assert(content, string());
if (content.length > 1000) {
throw new Error("Chatmessage content must be no more than 1,000 characters.");
}
return content;
}
export type CreateParams = {
kind: typeof PRIVATE | typeof PUBLIC;
chatroom_id: string; // make optional and provide default?
sender_id: string;
receiver_id: string;
content: string;
image_id?: string;
video_id?: string;
};
export type UpdateParams = CreateParams & {
chatmessage_id: string;
}
export type ConstructorParams = UpdateParams;
export const PRIVATE = "private" as const;
export const PUBLIC = "public" as const;
|
33613b652db568d1d3a9b9499b89351fa31c066a
|
TypeScript
|
GZJack/wensdk
|
/src/cache/src/drivers/Storage.ts
| 2.96875
| 3
|
// 引入接口
import {CacheInterface} from './Inf';
import {Tools,Crypto,cyt} from '../../lib/Index';
import {Data} from '../Data';
/**
* 实现本地缓存 localStorage 且必须继承 统一的接口
*
* @export
* @class WStorage
* @implements {CacheInterface}
*/
export class WStorage implements CacheInterface{
/**
* 当前的用户 key,每一个用户都会有一个本地的key,即便是同一个数据名称,不同的用户是读不到别的用户信息
*
* @type {string}
* @memberof WStorage
*/
public key:string = '';
/**
* 是否对数据进行加密
*
* @private
* @type {boolean}
* @memberof WStorage
*/
private _IsEncode:boolean;
/**
* 这个为主要控制加解密
*
* @private
* @type {boolean|null}
* @memberof WStorage
*/
private _IsCrypto:boolean|null=null;
/**
* 加密模块
*
* @private
* @type {Crypto}
* @memberof WStorage
*/
private _Crypto:Crypto;
/**
* aes 加解密实例对象
*
* @private
* @type {*}
* @memberof WStorage
*/
private _aes:any;
/**
* localStorage 缩写实例
*
* @private
* @type {Storage}
* @memberof WStorage
*/
private l:Storage;
/**
* Creates an instance of WStorage.
* @param {string} [key='']
* @memberof WStorage
*/
constructor(key:string='',isEncode:boolean=true){
// 赋值到属性上
this.key = Tools._IsString(key) ? key : '';
this._IsEncode = isEncode;
// 挂载加密,使用统一的内部加密实例
this._Crypto = cyt;
// 挂载 localStorage
this.l = localStorage;
// 挂载加解密对象
this._aes = new cyt.Aes(key);
}
/**
* 拿到 key
*
* @private
* @param {string} name
* @returns {string}
* @memberof WStorage
*/
private _getKey(name:string):string{
// 保证必须是字符串
name = Tools._IsString(name) ? name : '';
// 继续加密并获得 缓存的 key
return this._Crypto.sha1(this.key + name);
}
/**
* 校验数据缓存是否存在,存在且过期,则删除,返回并不存在
*
* @param {string} name
* @returns {boolean}
* @memberof WStorage
*/
public has(name:string):boolean{
// 拿到 key
let key = this._getKey(name);
let hasValue = this.l.getItem(key);
// 先看看返回的值是不是null
if(!Tools._IsString(hasValue)){
return false;
}
// 看看是否使用了加密
if(this._IsEncode){
// 解密... 等待解密函数
hasValue = this.d(hasValue);
}
// 最后将其转成对象
let ObjectData:any = {};
try {
ObjectData = JSON.parse(hasValue);
} catch (e) {
ObjectData = null;
// 删除掉
this.remove(name);
}
// 再校验是否过期了
if(Tools._IsObject(ObjectData)){
// 拿到当前时间戳
let Time = Data.t();
let Timeout = ObjectData['timeout'];
// 必须是存在的,且是数字,且不超时
if(!Tools._IsNull(Timeout) && !isNaN(Timeout) && parseInt(Timeout) >= Time){
return true;
}else{
// 删除过期的
this.remove(name);
return false;
}
}else{
// 这是不存在的
return false;
}
}
/**
* 对写入的缓存内容加密
*
* @private
* @param {string} str
* @returns {string}
* @memberof WStorage
*/
private e(str:string):string{
// let encode:(text:string)=>string = this._aes.encode;
// console.log(this._IsCrypto,this._IsEncode,Tools._IsNull,encode);
// 如果等于null,则使用默认的
if(Tools._IsNull(this._IsCrypto)){
return this._IsEncode ? this._aes.encode(str) : str;
}else{
// 加密
return this._IsCrypto ? this._aes.encode(str) : str;
}
}
/**
* 对读取的缓存内容解密
*
* @private
* @param {string} str
* @returns {string}
* @memberof WStorage
*/
private d(str:string):string{
// let decode:(text:string)=>string = ;
// 为null的时候使用默认的
if(Tools._IsNull(this._IsCrypto)){
return this._IsEncode ? this._aes.decode(str) : str;
}else{
// 解密
return this._IsCrypto ? this._aes.decode(str) : str;
}
}
/**
* 这个加解密是可以绕开 new 时构造定义的加解密
*
* @param {boolean} [isCrypto=true]
* @returns {WStorage}
* @memberof WStorage
*/
public isCrypto(isCrypto:boolean=true):WStorage{
// 赋值控制加解密
this._IsCrypto = isCrypto;
// 返回当前实例
return this;
}
/**
* 设置某一个缓存
*
* @param {string} name
* @param {*} value
* @param {number} [expire=0]
* @memberof WStorage
*/
public set(name:string,value:any,expire:number=0):void{
let key = this._getKey(name);
// 设置,要求 不存在则新增,存在则修改
if(this.has(name)){
// 修改
this.l.setItem(key,this.e(Data.u(this.d(this.l.getItem(key)),value)));
}else{
this.l.setItem(key,this.e(Data.c(value,expire)));
}
// 当使用了 isCrypto 篡改全局配置时,设置完成后需要还原
this._IsCrypto = null;
}
/**
* 读取某一个缓存
*
* @param {string} name
* @param {*} [defualt=null]
* @returns {*}
* @memberof WStorage
*/
public get(name:string,defualt:any=null):any{
// 现在是否存在或过期
if(this.has(name)){
// 读取
let value:any = this.l.getItem(this._getKey(name));
// 先去加解密
value = this.d(value);
// 将其转成对象,这里是不可能报错的了
try {
value = JSON.parse(value);
} catch (e) {
this.remove(name);
value = {'data':defualt};
}
// 当使用了 isCrypto 篡改全局配置时,设置完成后需要还原
this._IsCrypto = null;
// 最后返回结果
return value.data;
}else{
return defualt;
}
}
/**
* 删除某一个缓存
*
* @param {string} name
* @memberof WStorage
*/
public remove(name:string):void{
this.l.removeItem(this._getKey(name));
}
/**
* 清除所有缓存
*
* @memberof WStorage
*/
public clear():void{
this.l.clear();
}
}
|
f252f36f5e9faaae66a1f9eb83236f2fe1b36e98
|
TypeScript
|
kellyjandrews/todo-cli
|
/src/commands/delete.ts
| 2.625
| 3
|
import { Command, flags } from '@oclif/command'
import { getTodos, deleteTodos } from '../helpers'
import { prompt } from 'prompts'
export default class Delete extends Command {
static description = 'Delete a todo.'
static examples = [
`$ todo delete
`,
]
static strict = false
static flags = {
help: flags.help({ char: 'h' }),
}
static args = [
{ name: "todos", hidden: true }
]
async run() {
let todos = await getTodos(this.config.dataDir)
let choices = todos.map((todo: any, index: any) => {
return { title: todo, value: index };
})
const response = await prompt([
{
type: 'multiselect',
name: 'todos',
message: "Pick todos",
choices
}
]);
let deleteIndex = response.todos.reverse();
for (let i = 0; i < deleteIndex.length; i++) {
todos.splice(deleteIndex[i], 1);
}
deleteTodos(this.config.dataDir, todos)
let plural = deleteIndex.length > 1 ? 's' : '';
this.log(`${deleteIndex.length} todo${plural} removed.`)
}
}
|
db0d1603985c70d31e2edb338e4fd5f3d2fac386
|
TypeScript
|
eugen-eugen/sudoku
|
/lib/Cell.ts
| 3.828125
| 4
|
import { Group } from './Group';
/**
* This class represents a single cell of a sudoku field.
*
* A cell's model is the set of values, which the cell can yet have.
* The class have a couple of utility methods which evolve the cell
* while sudoku is being be solved.
*/
export class Cell{
/**
* This array represents values the cell can have.
*
* The first element corresponds to the value "1" and so on to "Group.N".
* "true" at the i. position means that the cell can have the value i.
* Initially the call can have all possible values.
*/
allowedValues: boolean[] = [...Array(Group.N)].map(v=>v=true);
/**
* @returns the string representation of the cell
*/
toString(): string{
if (1 === this.uncertainty()){
return (this.allowedValues.findIndex(v=>v) + 1).toString()
} else{
return '-'
}
}
/**
* Allows the cell to have only one value.
*
* @param value only value which a cell can have
*/
set(value: number){
this.allowedValues.forEach((allowedValue, i)=>{
this.allowedValues[i] = (i===value-1)
});
}
/**
* Disallows some values, whicht this cell can have.
*
* @param restricties values, which the cell cannot more have
*/
disallow(restricties: boolean[]): boolean{
let ret: boolean = false;
restricties.forEach((value, i) =>{
if (value){
if (this.allowedValues[i]){
ret = true;
}
this.allowedValues[i] = false;
}
})
return ret;
}
/**
* @param cell another cell
* @returns true, if this cell and another cell are equivalent
*/
equals(cell: Cell): boolean{
let firstUnequal = this.allowedValues.find((v, i)=>cell.allowedValues[i] != v)
return firstUnequal === undefined
}
/**
* @returns the number of yet possible values of the cell.
*/
uncertainty(): number{
let ret: number=0;
return this.allowedValues.filter(v=>v).length;
}
/**
* Creates an equivalent copy of the cell.
*
* @returns equivalent copy of the cell
*/
clone(): Cell{
let cell = new Cell();
cell.allowedValues = [...this.allowedValues];
return cell;
}
}
|
5b7eca4c1ca408ee31c26c5d99bb6232902aa5e5
|
TypeScript
|
zalari/ts-analyze
|
/base/src/classes/walker-language-service.class.ts
| 2.9375
| 3
|
import { Node, Project, Symbol, SyntaxKind } from 'ts-morph';
export class WalkerLanguageService {
constructor(private _project: Project) {
}
/**
* Gets the respective project-attached node for a given unattached node.
*
* @param unattachedNode
*/
attach<T extends Node>(unattachedNode: T): Node {
const sourceFile = this._project.getSourceFileOrThrow(unattachedNode.getSourceFile()
.getFilePath());
const child = sourceFile.getDescendantAtStartWithWidth(unattachedNode.getStart(), unattachedNode.getWidth());
return child as T;
}
/**
* Tries to get a symbol for a given node suppressing exceptions.
*
* @param node
*/
public getSymbolSafe(node: Node): Symbol | undefined {
try {
const symbol = node.getSymbol();
return symbol;
} catch {
try {
return this.attach(node)
.getSymbol();
} catch {
return undefined;
}
}
}
/**
* Tries to get the symbol that declares the given symbol (for example the class declaring a method).
*
* @param symbol
*/
public getDeclaringSymbol(symbol: Symbol): Symbol | undefined {
const declarations = symbol.getDeclarations();
if (declarations.length === 0) {
return undefined;
}
const firstDeclaration = declarations[0];
const classDeclaration = firstDeclaration.getParentIfKind(SyntaxKind.ClassDeclaration);
if (!classDeclaration) {
return undefined;
}
return this.getSymbolSafe(classDeclaration);
}
}
|
62ba76d1564704890537267e17135b4d414e57d3
|
TypeScript
|
SaioAU/ingrid_website
|
/src/routes/seasons.ts
| 2.65625
| 3
|
import { Request, Response, Router } from 'express';
import { StatusCodes } from 'http-status-codes';
import { Season, Product } from '../entities';
import { checkJwt } from './middlewares';
const router = Router();
const { BAD_REQUEST, INTERNAL_SERVER_ERROR, NOT_FOUND, OK } = StatusCodes;
// curl http://localhost:3000/seasons/read/all
router.get(
'/read/all',
async (_: Request, res: Response): Promise<void> => {
const seasons = await Season.find();
res.status(OK).json(seasons);
},
);
// curl http://localhost:3000/seasons/read?id=9d573d0b-6909-4637-a51d-48535d0c1482
router.get(
'/read',
async (req: Request, res: Response): Promise<void> => {
const { id } = req.query;
if (typeof id !== 'string') {
res.status(BAD_REQUEST).send('Missing id');
return;
}
const season = await Season.get(id, true);
res.status(OK).json(season);
},
);
/*
curl -H "Auth: ..." -XPOST -H "Content-Type: application/json" http://localhost:3000/seasons/create \
--data '{"name": "autumn", "year": 1985}'
*/
router.post(
'/create',
[checkJwt],
async (
req: Request<GenericObject, GenericObject, SeasonInput>,
res: Response,
): Promise<void> => {
const { name, year} = req.body;
if (!name || !year ) {
res.status(BAD_REQUEST).send('Missing name or year');
return;
}
const season = await Season.createSeason(name, Number(year));
if (!season) {
res.status(INTERNAL_SERVER_ERROR).send('Could not create season');
return;
}
res.status(OK).json(season);
},
);
/*
curl -H "Auth: ..." -XPATCH -H "Content-Type: application/json" http://localhost:3000/seasons/update \
--data --data '{"id": "b4f7b015-3fbc-4fe9-b5ce-244d11bb87d2", "category": "handbag", "name": "classy", "size": 4, "price": 1000, "colour": "blue", "description": "awesome", "material": "cotton", "care": "handwashed", "season": "summer"}'
*/
router.patch(
'/update',
[checkJwt],
async (
req: Request<GenericObject, GenericObject, SeasonInput>,
res: Response,
): Promise<void> => {
const { id, year, name} = req.body;
if (typeof id !== 'string') {
res.status(BAD_REQUEST).send('Missing id');
return;
}
if(typeof name !== 'string'){
res.status(BAD_REQUEST).send('Missing name');
return;
}
if(typeof year !== 'number'){
res.status(BAD_REQUEST).send('Missing year');
return;
}
const season = await Season.findOne({ id });
if (!season) {
res.status(NOT_FOUND).send('Season not found');
return;
}
season.year = year
season.name = name
await season.save()
res.status(OK).json(season);
},
);
/*
curl -H "Auth: ..." -XDELETE -H "Content-Type: application/json" http://localhost:3000/seasons/delete \
--data '{"id": 1}'
*/
router.delete(
'/delete',
[checkJwt],
async (
req: Request<GenericObject, GenericObject, SeasonInput>,
res: Response,
): Promise<void> => {
const { id } = req.body;
if (typeof id !== 'string') {
res.status(BAD_REQUEST).send('Missing id');
return;
}
const season = await Season.findOne({ id });
if (!season) {
res.status(NOT_FOUND).send('Season not found');
return;
}
await Season.delete(season);
res.status(OK).json({ id });
},
);
export default router;
|
3987cee04f1b1b001bbdb623649ed8e36498d47c
|
TypeScript
|
3darkman/Infinity2d20
|
/WebTools/src/helpers/careerEvents.ts
| 2.546875
| 3
|
import {character} from '../common/character';
import {EventModel} from '../common/eventModel';
import {Faction, FactionsHelper} from './factions';
import {YouthEventsHelper} from './youthEvents';
import {Career} from'./careers';
import {SocialClassesHelper} from './socialClasses';
import {Attribute} from './attributes';
import {Skill} from './skills';
import {BirthPlacesHelper} from './birthPlaces';
import {AlienHost} from './alienHosts';
import {DiceRoller} from './diceRoller';
import {Source} from './sources';
export class CareerEventModel extends EventModel {
onApply: () => void;
constructor(base: EventModel, onApply?: () => void) {
super(base.event, base.trait, base.effect, base.detailView);
this.onApply = onApply;
}
}
export class CareerEvents {
generateEvent(): CareerEventModel {
var event = null;
var table = Math.floor(Math.random() * 6) + 1;
var ev = Math.floor(Math.random() * 19) + 1;
if (character.host === AlienHost.Antipode && character.faction === Faction.Ariadna && character.hasSource(Source.Ariadna)) {
event = this.rollOnAntipodeTable(ev, character.isUnemployed());
event.table = "Antipode";
event.eventNumber = ev;
return event;
}
if (character.faction === Faction.Ariadna && character.hasSource(Source.Ariadna)) {
switch (table) {
case 1:
case 2:
case 3:
if (character.isDogBlooded()) {
event = this.rollOnDogfaceAndWulverTable(ev, character.isUnemployed());
event.table = "Dog-Blooded";
event.eventNumber = ev;
}
else {
event = this.rollOnAriadnaTable(ev, character.isUnemployed());
event.table = "Ariadna";
event.eventNumber = ev;
}
break;
case 4:
event = this.rollOnTableA(ev, character.isUnemployed());
event.table = "A";
event.eventNumber = ev;
break;
case 5:
event = this.rollOnTableB(ev, character.isUnemployed());
event.table = "B";
event.eventNumber = ev;
break;
case 6:
event = this.rollOnTableC(ev, character.isUnemployed());
event.table = "C";
event.eventNumber = ev;
break;
}
}
else if (character.faction === Faction.Haqqislam && character.hasSource(Source.Haqqislam)) {
switch (table) {
case 1:
case 2:
case 3:
event = this.rollOnHaqqislamTable(ev, character.isUnemployed());
event.table = "Haqqislam";
event.eventNumber = ev;
break;
case 4:
event = this.rollOnTableA(ev, character.isUnemployed());
event.table = "A";
event.eventNumber = ev;
break;
case 5:
event = this.rollOnTableB(ev, character.isUnemployed());
event.table = "B";
event.eventNumber = ev;
break;
case 6:
event = this.rollOnTableC(ev, character.isUnemployed());
event.table = "C";
event.eventNumber = ev;
break;
}
}
else if (character.faction === Faction.PanOceania && character.hasSource(Source.PanOceania)) {
switch (table) {
case 1:
case 2:
case 3:
event = this.rollOnPanOceaniaTable(ev, character.isUnemployed());
event.table = "PanOceania";
event.eventNumber = ev;
break;
case 4:
event = this.rollOnTableA(ev, character.isUnemployed());
event.table = "A";
event.eventNumber = ev;
break;
case 5:
event = this.rollOnTableB(ev, character.isUnemployed());
event.table = "B";
event.eventNumber = ev;
break;
case 6:
event = this.rollOnTableC(ev, character.isUnemployed());
event.table = "C";
event.eventNumber = ev;
break;
}
}
else if (character.faction === Faction.Nomads && character.hasSource(Source.Nomads)) {
switch (table) {
case 1:
case 2:
case 3:
if (character.isUplift()) {
event = this.rollOnUpliftTable(ev, character.isUnemployed());
event.table = "Uplift";
event.eventNumber = ev;
}
else {
event = this.rollOnNomadsTable(ev, character.isUnemployed());
event.table = "Nomads";
event.eventNumber = ev;
}
break;
case 4:
event = this.rollOnTableA(ev, character.isUnemployed());
event.table = "A";
event.eventNumber = ev;
break;
case 5:
event = this.rollOnTableB(ev, character.isUnemployed());
event.table = "B";
event.eventNumber = ev;
break;
case 6:
event = this.rollOnTableC(ev, character.isUnemployed());
event.table = "C";
event.eventNumber = ev;
break;
}
}
else {
switch (table) {
case 1:
case 2:
event = this.rollOnTableA(ev, character.isUnemployed());
event.table = "A";
event.eventNumber = ev;
break;
case 3:
case 4:
event = this.rollOnTableB(ev, character.isUnemployed());
event.table = "B";
event.eventNumber = ev;
break;
case 5:
case 6:
event = this.rollOnTableC(ev, character.isUnemployed());
event.table = "C";
event.eventNumber = ev;
break;
}
}
return event;
}
getEvents() {
let events: { [category: string]: CareerEventModel[] } = {};
if (character.host === AlienHost.Antipode && character.hasSource(Source.Ariadna)) {
events["Antipode"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnAntipodeTable(i, character.isUnemployed());
ev.table = "Antipode";
events["Antipode"].push(ev);
}
}
else if (character.faction === Faction.Ariadna && character.hasSource(Source.Ariadna)) {
if (character.isDogBlooded()) {
events["Dog-Blooded"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnDogfaceAndWulverTable(i, character.isUnemployed());
ev.table = "Dog-Blooded";
events["Dog-Blooded"].push(ev);
}
}
else {
events["Ariadna"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnAriadnaTable(i, character.isUnemployed());
ev.table = "Ariadna";
events["Ariadna"].push(ev);
}
}
}
else if (character.faction === Faction.Haqqislam && character.hasSource(Source.Haqqislam)) {
events["Haqqislam"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnHaqqislamTable(i, character.isUnemployed());
ev.table = "Haqqislam";
events["Haqqislam"].push(ev);
}
}
else if (character.faction === Faction.PanOceania && character.hasSource(Source.PanOceania)) {
events["PanOceania"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnPanOceaniaTable(i, character.isUnemployed());
ev.table = "PanOceania";
events["PanOceania"].push(ev);
}
}
else if (character.faction === Faction.Nomads && character.hasSource(Source.Nomads)) {
if (character.isUplift()) {
events["Uplift"] = [];
for (var i = 1; i < 19; i++) {
let ev = this.rollOnUpliftTable(i, character.isUnemployed());
ev.table = "Uplift";
events["Uplift"].push(ev);
}
}
else {
events["Nomads"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnNomadsTable(i, character.isUnemployed());
ev.table = "Nomads";
events["Nomads"].push(ev);
}
}
}
events["A"] = [];
events["B"] = [];
events["C"] = [];
for (var i = 1; i < 20; i++) {
let ev = this.rollOnTableA(i, character.isUnemployed());
ev.table = "A";
events["A"].push(ev);
}
for (var i = 1; i < 20; i++) {
let ev = this.rollOnTableB(i, character.isUnemployed());
ev.table = "B";
events["B"].push(ev);
}
for (var i = 1; i < 20; i++) {
let ev = this.rollOnTableC(i, character.isUnemployed());
ev.table = "C";
events["C"].push(ev);
}
return events;
}
private rollOnTableA(roll: number, isUnemployed: boolean) {
switch (roll) {
case 1: {
const cost = 10 + DiceRoller.rollSpecial(5, 0).hits;
return new CareerEventModel(new EventModel(
`You develop a rare genetic disorder or are afflicted by a genomic toxin. Your genetic order reduces your maximum Vigour by 1. The treatment required to cure your condition will cost ${cost} assets.`,
"",
`You develop a rare genetic disorder or are afflicted by a genomic toxin. Your genetic order reduces your maximum Vigour by 1. The treatment required to cure your condition will cost ${cost} assets.`),
() => {
character.vigourReduction++;
});
}
case 2:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"Both the authorities and organised crime are hunting for you. What do you know, or what have you got that they want? Gain both a criminal enemy and a police enemy. You must pass an Average(D1) hazard test for your current career or you are Fired.",
"",
"Both the authorities and organised crime are hunting for you. What do you know, or what have you got that they want? You have a criminal enemy and a police enemy.",
"HazardTestOrFired"));
case 3:
return new CareerEventModel(new EventModel(
"You are on the run. Who is after you, and why?",
"Hunted",
"You are on the run. Who is after you, and why?"));
case 4:
return new CareerEventModel(new EventModel(
"You’ve accrued the enmity of a powerful enemy. They might be a district authority, well-connected ex-lover, or a jealous colleague.",
"Persecuted",
"You’ve accrued the enmity of a powerful enemy. They might be a district authority, well-connected ex-lover, or a jealous colleague."));
case 5:
return new CareerEventModel(new EventModel(
"An old debt has caught up with you. Who is it to, and what will happen if you do not pay? Gain a conflict with an organization. You have a 20 asset debt that must be paid off with that organisation. Once it is paid, the conflict is removed. This debt does not prevent you from using earnings to make purchases.",
"Conflict with an Organization",
"An old debt has caught up with you. Who is it to, and what will happen if you do not pay? You have a conflict with an organization. You have a 20 asset debt that must be paid off with that organisation. Once it is paid, the conflict is removed. This debt does not prevent you from using earnings to make purchases."));
case 6:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You’re involved in a serious crime. Guilty or not, you are sentenced to hard labour and lose your job. Add 1-6 years to your age. You are Fired and gain a Criminal Record.",
"",
"You’re involved in a serious crime. Guilty or not, you are sentenced to hard labour and lose your job. You are Fired and gain a Criminal Record.",
"CriminalRecord|Fired"),
() => {
character.age += Math.floor(Math.random() * 6) + 1;
character.hasCriminalRecord = true;
});
case 7:
return new CareerEventModel(new EventModel(
"You develop a fierce rivalry with someone in your organisation or faction. Gain a character trait describing your rivalry or its consequences.",
"Fierce Rivalry",
"You develop a fierce rivalry with someone in your organisation or faction. Gain a character trait describing your rivalry or its consequences."));
case 8:
{
var faction = FactionsHelper.generateFaction(false, true);
var factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
"You have an affair with someone wealthy, but it ends poorly. Was it your fault? Gain an enemy in the " + factionName + " faction.",
"Wealthy Ex-Lover",
"You have an affair with someone wealthy, but it ends poorly. Was it your fault? You have an enemy in the " + factionName + " faction."));
}
case 9:
{
var faction = FactionsHelper.generateFaction(false, true);
var factionName = FactionsHelper.getFaction(faction).name;
var debt = Math.floor(Math.random() * 6) + 1;
return new CareerEventModel(new EventModel(
"You are called in for questioning by the authorities. What do they want to know? They let you go, but on what condition? Gain a debt worth " + debt + " assets to the " + factionName + " faction.",
"",
"You are called in for questioning by the authorities. What do they want to know? They let you go, but on what condition? You have a debt worth " + debt + " assets to the " + factionName + " faction."));
}
case 10:
return new CareerEventModel(new EventModel(
"You gain a criminal record. What happened? Are you guilty or innocent?",
"",
"You gain a criminal record. What happened? Are you guilty or innocent?",
"CriminalRecord"),
() => {
character.hasCriminalRecord = true;
});
case 11: {
var location = DiceRoller.rollHitLocation();
return new CareerEventModel(new EventModel(
"You are injured in a shooting accident. What were you doing? Who shot you? You have a gunshot wound that has not healed well in your " + location + ".",
"Old Wound",
"You are injured in a shooting accident. What were you doing? Who shot you? You have a gunshot wound that has not healed well in your " + location + "."));
}
case 12:
return new CareerEventModel(new EventModel(
"Someone has been keeping an eye on you. They always seem to be there when you look around. What do you think they are interested in? Who are they?",
"Under Surveillance",
"Someone has been keeping an eye on you. They always seem to be there when you look around. What do you think they are interested in? Who are they?"));
case 13:
return new CareerEventModel(new EventModel(
"You become tangled up in a plot being run by a rival faction. What do you do for them? Why do you do it? You must pass a Challenging (D2) hazard test for your current career or you gain a Criminal Record.",
"",
"You become tangled up in a plot being run by a rival faction. What do you do for them? Why do you do it?",
"HazardTestOrCriminalRecord"));
case 14:
return new CareerEventModel(new EventModel(
"They are on to you! Who are they and what have you done?",
"Paranoia",
"They are on to you! Who are they and what have you done?"));
case 15:
return new CareerEventModel(new EventModel(
"Someone you know is a criminal, but you cannot turn him or her in. What hold do they have over you?",
"Blackmailed",
"Someone you know is a criminal, but you cannot turn him or her in. What hold do they have over you?"));
case 16:
return new CareerEventModel(new EventModel(
"Whatever you did, and it was bad, you’ve paid for it now — but they will not give up. Gain a character trait describing your nemesis.",
"Nemesis",
"Whatever you did, and it was bad, you’ve paid for it now — but they will not give up."));
case 17:
return new CareerEventModel(new EventModel(
"You volunteered to take part in a secret medical experiment which succeeded. Well, almost. You may roll an aging test to regain an Infinity Point once per session.",
"Curse of the Mayfly",
"You volunteered to take part in a secret medical experiment which succeeded. Well, almost. You may roll an aging test to regain an Infinity Point once per session."));
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You are Fired. What did you do?",
"",
"You are Fired. What did you do?",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"While doing your job, you are killed. What happened? Your character died and was resurrected.",
"",
"While doing your job, you are killed. What happened? Your character died and was resurrected.",
"Resurrection"),
() => {
character.applyDeath();
});
case 20:
return new CareerEventModel(new EventModel(
"You are suffering from the Chinese Curse: May you live in interesting times! You gain three career events for this career phase.",
"",
"",
"ChineseCurse"));
}
return null;
}
private rollOnTableB(roll: number, isUnemployed: boolean) {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"You are dating a wealthy and generous person. Increase Earnings Rating by one (to a maximum of six) whilst they are still in love with you, but they are very demanding or vulnerable.",
"Vulnerable Lover",
"You are dating a wealthy and generous person. Increase Earnings Rating by one (to a maximum of six) whilst they are still in love with you, but they are very demanding or vulnerable."),
() => {
character.earnings = Math.min(character.earnings + 1, 6);
});
case 2:
return new CareerEventModel(new EventModel(
"You are forced to evacuate. What is the threat? Where do you have to go? Immediately spend 5 assets or gain the trait Homeless.",
"",
"You are forced to evacuate. What is the threat? Where do you have to go?",
"Homeless"));
case 3: {
var faction = FactionsHelper.generateFaction(false, true);
while (faction === character.faction) {
faction = FactionsHelper.generateFaction(false, true);
}
var factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
"You foil some form of nefarious plot on your own (or with the help of your friends). Why didn’t you go to the authorities? Gain an enemy in the " + factionName + " faction. Gain 5 assets in ‘liberated’ equipment.",
"",
"You foil some form of nefarious plot on your own (or with the help of your friends). Why didn’t you go to the authorities? Gain an enemy in the " + factionName + " faction."),
() => {
character.addEquipment("5 assets worth of liberated equipment from the " + factionName + " faction.");
});
}
case 4:
return new CareerEventModel(new EventModel(
"You survive a serious natural disaster.",
"Nightmares",
"You survive a serious natural disaster."));
case 5:
return new CareerEventModel(new EventModel(
"You are remembered in the will of a relative. Who died? What were your feelings for them? Gain 2 Assets.",
"",
"You are remembered in the will of a relative. Who died? What were your feelings for them?"),
() => {
character.assets += 2;
});
case 6:
return new CareerEventModel(new EventModel(
"You help solve a serious crime. Gain a favour with a senior figure in either law enforcement or the intelligence community in your faction.",
"",
"You help solve a serious crime. You have earned a favour from a senior figure in either law enforcement or the intelligence community in your faction."));
case 7:
return new CareerEventModel(new EventModel(
"You discover that you have a talent for something you’d never considered trying before. What happened? Why do you love it? Gain 1 rank of training in a skill you currently have no training in.",
"",
"You discover that you have a talent for something you’d never considered trying before. What happened? Why do you love it?",
"IncreaseUntrained"));
case 8:
return new CareerEventModel(new EventModel(
"You are scouted by an unexpected employer. If you hazard your next career, reduce the difficulty of the hazard test by two steps. If you stay in your current career or roll randomly, increase your Earnings Rating by one.",
"",
"You are scouted by an unexpected employer."),
() => {
character.hazardDecrease = 2;
});
case 9:
return new CareerEventModel(new EventModel(
"You discover that your friend is a traitor working for a rival faction. The authorities request your help in arresting them. If you cooperate with the authorities, gain 5 assets as a reward. If you help your friend, you gain a contact in a random faction but you must make an Average (D1) hazard test in your current career or gain a Criminal Record.",
"",
"You discover that your friend is a traitor working for a rival faction. The authorities request your help in arresting them.",
"HelpFriend"));
case 10:
return new CareerEventModel(new EventModel(
"You stumbled on a previously unknown alien ruin (possibly while on vacation). You found something before you got out. What was it? Gain an item worth 10 Assets.",
"",
"You stumbled on a previously unknown alien ruin (possibly while on vacation). You found something before you got out. What was it?"),
() => {
character.assets += 10;
});
case 11:
return new CareerEventModel(new EventModel(
"Your lucky day! Something paid off — a lottery ticket, a risky business venture, or a hard won contract. Gain 5 Assets.",
"",
"Your lucky day! Something paid off — a lottery ticket, a risky business venture, or a hard won contract."),
() => {
character.assets += 5;
});
case 12: {
var faction = FactionsHelper.generateFaction(false, true);
var factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
"You save someone from a terrible accident. Gain an ally in the " + factionName + " faction.",
"",
"You save someone from a terrible accident. You have an ally in the " + factionName + " faction."));
}
case 13:
return new CareerEventModel(new EventModel(
"You achieve notoriety or fame as a minor Maya star. You gain 1 bonus Momentum on successful Social tests, but all Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem.",
"",
"You achieve notoriety or fame as a minor Maya star. You gain 1 bonus Momentum on successful Social tests, but all Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem."));
case 14:
return new CareerEventModel(new EventModel(
"Your Cube experiences a malfunction in which its input is fed back into your brain. You’ll need a completely new Cube to solve the problem.",
"Cube Echoes",
"Your Cube experiences a malfunction in which its input is fed back into your brain. You’ll need a completely new Cube to solve the problem."));
case 15:
return new CareerEventModel(new EventModel(
"A pseudo-AI personality you’ve had since childhood begins to degrade, but you can’t bear to part with it. The pseudo-AI provides one momentum to Education tests, but the GM can use it as a trait when purchasing complications that are related to the outcome of the test.",
"Pseudo-AI",
"A pseudo-AI personality you’ve had since childhood begins to degrade, but you can’t bear to part with it. The pseudo-AI provides one momentum to Education tests, but the GM can use it as a trait when purchasing complications that are related to the outcome of the test."));
case 16:
return new CareerEventModel(new EventModel(
"You join a new religion. What prompted your conversion? What article of faith is most important to you in your new belief? Gain a character trait describing your religion or religious experience.",
"New Religion",
"You join a new religion. What prompted your conversion? What article of faith is most important to you in your new belief? Gain a character trait describing your religion or religious experience."));
case 17:
return new CareerEventModel(new EventModel(
"You volunteered to take part in a secret medical experiment that succeeded. Well, almost. Gain a talent in a talent tree of your choice and describe how you can do this as a result of the experiment. However, sometimes you lose the plot or wake up in strange places.",
"Experimental Subject",
"You volunteered to take part in a secret medical experiment that succeeded. Well, almost. Gain a talent in a talent tree of your choice and describe how you can do this as a result of the experiment. However, sometimes you lose the plot or wake up in strange places.",
"SelectTalent"));
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"A co-worker frames you for something they did. You are Fired.",
"",
"A co-worker frames you for something they did. You are Fired.",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"You are violently killed. What happened? Who killed you? Your character died and was resurrected.",
"",
" You are violently killed. What happened? Who killed you? Your character died and was resurrected.",
"Resurrection"),
() => {
character.applyDeath();
});
case 20:
return new CareerEventModel(new EventModel(
"You are suffering from the Chinese Curse: May you live in interesting times! You gain three career events for this career phase.",
"",
"",
"ChineseCurse"));
}
return null;
}
private rollOnTableC(roll: number, isUnemployed: boolean) {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"A family member tells you a dark family secret. What has been hidden from you for all these years? Gain a character trait related to your family’s secret.",
"Family Secret",
"A family member tells you a dark family secret. What has been hidden from you for all these years? Gain a character trait related to your family’s secret."));
case 2:
return new CareerEventModel(new EventModel(
"You receive exotic cosmetic surgery. What do you look like now? Do you have tapered ears? Lizard scales? A prehensile tail? Gain a character trait describing your new look. And 3 Assets worth of cosmetic biomodifications.",
"Exotic Cosmetic Surgery",
"You receive exotic cosmetic surgery. What do you look like now? Do you have tapered ears? Lizard scales? A prehensile tail? Gain a character trait describing your new look."),
() => {
character.equipment.push("3 Assets worth of cosmetic biomodifications");
});
case 3:
return new CareerEventModel(new EventModel(
"The building you call home burns down. You lose 5 Assets.",
"Homeless",
"The building you call home burns down."),
() => {
character.assets = Math.max(character.assets - 5, 0);
});
case 4:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"Your employer hits a slump and is struggling to make ends meet. You can either agree to a pay cut (reduce your Earnings Rating by 1) or you can choose to make a Challenging (D2) hazard test for your current career. If you fail the test, you are Fired. But if you succeed, your Earnings Rating is unchanged as you swap to a new employer.",
"",
"Your employer hits a slump and is struggling to make ends meet.",
"HazardTestOrReduceEarnings"));
case 5:
return new CareerEventModel(new EventModel(
"You’re betrayed by someone you trust. Who was it? What did they do to you?",
"Untrusting",
"You’re betrayed by someone you trust. Who was it? What did they do to you?"));
case 6:
return new CareerEventModel(new EventModel(
"You have survived a Combined Army attack. Where were you? What form did the attack take?",
"Shell Shocked",
"You have survived a Combined Army attack. Where were you? What form did the attack take?"));
case 7:
return new CareerEventModel(new EventModel(
"You get enrolled in an advanced training program at your job (possibly experimental or cybernetic in nature). Gain 1 rank in the elective skill from your current career that you did NOT choose to advance during this career phase.",
"",
"You get enrolled in an advanced training program at your job (possibly experimental or cybernetic in nature).",
"IncreaseSkippedElective"));
case 8: {
let faction = FactionsHelper.generateFaction(true, true);
let planet = BirthPlacesHelper.generateBirthPlace(faction);
while (planet.name === character.birthPlace) {
faction = FactionsHelper.generateFaction(true, true);
planet = BirthPlacesHelper.generateBirthPlace(faction);
}
return new CareerEventModel(new EventModel(
"You are recruited or selected to travel to " + planet.name + " in order to continue your career.",
"Mudhopper",
"You are recruited or selected to travel to " + planet.name + " in order to continue your career."));
}
case 9:
return new CareerEventModel(new EventModel(
"A family member is in desperate financial need and they come to you for help. How bad is it and how did they get into this situation? Gain a debt worth 10 Assets.",
"Disowned",
"A family member is in desperate financial need and they come to you for help. How bad is it and how did they get into this situation? You have a debt worth 10 Assets."));
case 10: {
let languages: string[] = [];
const num = Math.floor(Math.random() * 6) + 1;
for (var i = 0; i < num; i++) {
const lang = BirthPlacesHelper.generateRandomLanguage(character.faction, true, true)[0];
if (character.languages.indexOf(lang) > -1) {
i--;
continue;
}
else {
languages.push(lang);
}
}
return new CareerEventModel(new EventModel(
"You are sent out into the field as a roving specialist (either in person or through immersive VR). Where do you go? What do you experience? Gain " + num + " languages.",
"",
"You are sent out into the field as a roving specialist (either in person or through immersive VR). Where do you go? What do you experience?"),
() => {
languages.forEach(lang => {
character.addLanguage(lang);
});
});
}
case 11:
return new CareerEventModel(new EventModel(
"A family member is murdered. Who was killed? Do you know who did it? And, if so, why?",
"Thirst for Vengeance",
"A family member is murdered. Who was killed? Do you know who did it? And, if so, why?"));
case 12:
return new CareerEventModel(new EventModel(
"You are one of the only survivors when a ship you were travelling on broke down or crashed, and rescue was a long time coming. Add one year to your age.",
"Space Sickness",
"You are one of the only survivors when a ship you were travelling on broke down or crashed, and rescue was a long time coming."),
() => {
character.age++;
});
case 13:
return new CareerEventModel(new EventModel(
"You earn a big promotion. Increase Earnings Rating by one.",
"",
"You earn a big promotion."),
() => {
character.earnings++;
});
case 14: {
const faction = FactionsHelper.generateFaction(false, true);
const factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
"Your childhood friend moves back home. It’s great to see them again, but they’re acting strangely. Gain an ally from the " + factionName + " faction.",
"",
"Your childhood friend moves back home. It’s great to see them again, but they’re acting strangely. You have gained an ally from the " + factionName + " faction."));
}
case 15:
return new CareerEventModel(new EventModel(
"You thought that you’d gotten away with the crime you committed ten years ago, but new evidence has been discovered. Gain a Criminal Record.",
"",
"You thought that you’d gotten away with the crime you committed ten years ago, but new evidence has been discovered. You gain a Criminal Record.",
"CriminalRecord"));
case 16:
return new CareerEventModel(new EventModel(
"Due to what’s claimed to be a clerical error, your stored personality back-up is placed in a Lhost. Your IQ-doppelganger disappears before the error can be corrected.",
"IQ-Doppleganger",
"Due to what’s claimed to be a clerical error, your stored personality back-up is placed in a Lhost. Your IQ-doppelganger disappears before the error can be corrected."));
case 17: {
const attribute = Math.floor(Math.random() * character.attributes.length);
const attr = Attribute[attribute];
return new CareerEventModel(new EventModel(
"You volunteered to take part in a secret medical experiment. It failed. Reduce " + attr + " by 1 point.",
"",
"You volunteered to take part in a secret medical experiment. It failed."),
() => {
character.attributes[attribute].value--;
});
}
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You show up for work one day and your employer is gone. The office is empty. Nobody is there. What happened? You are Fired.",
"Surrounded by Conspiracy",
"You show up for work one day and your employer is gone. The office is empty. Nobody is there. What happened? You are Fired.",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"Your death is a famous event. How did it happen? Why is it so well known? Your character died and was resurrected. You gain 1 bonus Momentum on successful Social tests, but all Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem.",
"",
"Your death is a famous event. How did it happen? Why is it so well known? Your character died and was resurrected. You gain 1 bonus Momentum on successful Social tests, but all Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem.",
"Resurrection"),
() => {
character.applyDeath();
});
case 20:
return new CareerEventModel(new EventModel(
"You are suffering from the Chinese Curse: May you live in interesting times! You gain three career events for this career phase.",
"",
"",
"ChineseCurse"));
}
return null;
}
private rollOnAriadnaTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"Your work carries you to a different Ariadnan nation. Why did that go as well — or as poorly — as it did? Choose a different homeland.",
"A Different Home",
"Your work carries you to a different Ariadnan nation. Why did that go as well — or as poorly — as it did?",
"SelectHomeland"
));
case 2:
return new CareerEventModel(new EventModel(
"Bureau Toth brings you in for questioning. What do they want to know? They let you go, but under what condition?",
"On the Watchlist",
"Bureau Toth brings you in for questioning. What do they want to know? They let you go, but under what condition?"
));
case 3:
return new CareerEventModel(new EventModel(
"An Antipode attack demolishes your place of business, leaving it in shambles. You may not repeat or extend this career unless you lose 1 Earnings.",
"Harried",
"An Antipode attack demolishes your place of business, leaving it in shambles.",
"PayToContinue"
));
case 4:
return new CareerEventModel(new EventModel(
"When everything went to hell, through sheer stubbornness, you somehow kept it together.",
"Ariadnan Grit",
"When everything went to hell, through sheer stubbornness, you somehow kept it together."
));
case 5:
return new CareerEventModel(new EventModel(
"While out hiking, you stumble on to some interesting ruins.",
"Amateur Archaeologist",
"While out hiking, you stumble on to some interesting ruins."
));
case 6:
return new CareerEventModel(new EventModel(
"Your employer is incredibly enthusiastic for an offworld technological solution. How does it end in disaster? And why does it leave you suspicious of advanced technology?",
"Luddite",
"Your employer is incredibly enthusiastic for an offworld technological solution. How does it end in disaster? And why does it leave you suspicious of advanced technology?"
));
case 7:
return new CareerEventModel(new EventModel(
"You are the 'lucky winner' of a transfer to the front line.",
"Unwanted Draft",
"You are the 'lucky winner' of a transfer to the front line."
));
case 8: {
const faction = FactionsHelper.generateFaction(false, true);
const factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`You save a tourist from a horrible fate. Gain an ally in the ${factionName} faction.`,
"",
`You save a tourist from a horrible fate. Gain an ally in the ${factionName} faction.`
));
}
case 9:
return new CareerEventModel(new EventModel(
"You find yourself caught in between a Dog Nation protest, and police forces. Why do people think you put the protesters 'in their place'? And what did you actually mean to do? Your new reputation precedes you; gain an additional point of momentum on Leadership tests.",
"Wolfsbane",
"You find yourself caught in between a Dog Nation protest, and police forces. Why do people think you put the protesters 'in their place'? And what did you actually mean to do? Your new reputation precedes you; gain an additional point of momentum on Leadership tests."
));
case 10:
return new CareerEventModel(new EventModel(
"You agree to let some Nomad 'friends' Install a Cube for you This goes shockingly well.",
"",
"You agree to let some Nomad 'friends' Install a Cube for you This goes shockingly well."
));
case 11:
return new CareerEventModel(new EventModel(
"You agree to let some Nomad 'friends' Install a Cube for you Unsurprisingly, this ends poorly. All Infowar attacks deal you an extra 1[CD] damage.",
"",
"You agree to let some Nomad 'friends' Install a Cube for you Unsurprisingly, this ends poorly. All Infowar attacks deal you an extra 1[CD] damage."
));
case 12:
return new CareerEventModel(new EventModel(
"You grow close to a Dog-Bowl player. What's the nature of your relationship?",
"Dog-Blooded Relation",
"You grow close to a Dog-Bowl player. What's the nature of your relationship?"
));
case 13:
return new CareerEventModel(new EventModel(
"Somehow, you find yourself in a duel. What brought this on? And what did it cost to succeed?",
"Duelling Scars",
"Somehow, you find yourself in a duel. What brought this on? And what did it cost to succeed?"
));
case 14: {
const faction = FactionsHelper.generateFaction(false, true);
var factionName = FactionsHelper.getFaction(faction).name;
if (faction === Faction.Ariadna) {
const birthplace = BirthPlacesHelper.generateBirthPlace(faction);
const homeland = BirthPlacesHelper.generateHomeland(birthplace.name);
if (homeland) {
factionName += ` (${homeland.name})`;
}
}
return new CareerEventModel(new EventModel(
`Someone you were close to (${factionName}) dies in an attack. Who was behind it? And what do you plan to do about it?`,
"Lost Friend",
`Someone you were close to (${factionName}) dies in an attack. Who was behind it? And what do you plan to do about it?`
));
}
case 15:
return new CareerEventModel(new EventModel(
"You foiled an act of Galactic sabotage. Increase your Earnings by one for your act of balance sheet-friendly heroism.",
"Patriotism",
"You foiled an act of Galactic sabotage."
),
() => { character.earnings++; });
case 16:
return new CareerEventModel(new EventModel(
"A disaster occurs; you grit your teeth and keep going. You gain one Life Point.",
"True Grit",
"A disaster occurs; you grit your teeth and keep going."
),
() => { character.lifePoints++; });
case 17:
return new CareerEventModel(new EventModel(
"You are scouted by an unlikely employer. You may hazard your next career, even if you don’t meet the Faction or Homeland prerequisite.",
"",
"You are scouted by an unlikely employer."
),
() => { character.ignoreHazardRequirements = true; });
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You are fired. What did you do, and why was it worth it?",
"Fired Relief",
"You are fired. What did you do, and why was it worth it?",
"Fired"
));
case 19:
return new CareerEventModel(new EventModel(
"You were killed, fighting for offworld employers. At least, that's the official story — only you know what really happened.",
"Officially Dead",
"You were killed, fighting for offworld employers. At least, that's the official story — only you know what really happened.",
"Resurrection"
));
case 20:
return new CareerEventModel(new EventModel(
"You’ve got the Devil’s Own Luck. Interesting Times ahead. You gain three career events for this career phase.",
"",
"",
"ChineseCurse"
));
}
}
private rollOnAntipodeTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"Your Trinary link is violently severed. While in Mind-Shock, you’re taken in by a group of humans who nurse you back to health, though their reasons are hardly benevolent. You must take Assault Pack Member as your next career.",
"",
"Your Trinary link is violently severed. While in Mind-Shock, you’re taken in by a group of humans who nurse you back to health, though their reasons are hardly benevolent."),
() => { character.firstCareer = Career.AssaultPackMember; });
case 2: {
var location = DiceRoller.rollHitLocation();
return new CareerEventModel(new EventModel(
"You are injured in a shooting accident. What were you doing? Who shot you? You have a gunshot wound that has not healed well in your " + location + ".",
"Old Wound",
"You are injured in a shooting accident. What were you doing? Who shot you? You have a gunshot wound that has not healed well in your " + location + "."));
}
case 3:
return new CareerEventModel(new EventModel(
"You’ve been singled out as a problem by a group intent on solving you.",
"Priority Target",
"You’ve been singled out as a problem by a group intent on solving you."));
case 4:
return new CareerEventModel(new EventModel(
"A Rodinan strike force deploys makeshift biological weapons at you. You survive, but it’s difficult to think straight. Reduce your Intelligence by 1.",
"",
"A Rodinan strike force deploys makeshift biological weapons at you. You survive, but it’s difficult to think straight."),
() => { character.attributes[Attribute.Intelligence].value--; });
case 5:
return new CareerEventModel(new EventModel(
"A USAriadnan strike force shells your den. You make it out alive, but your hearing is permanently damaged. Increase the difficulty of all Observation tests based on hearing by +1.",
"",
"A USAriadnan strike force shells your den. You make it out alive, but your hearing is permanently damaged. Increase the difficulty of all Observation tests based on hearing by +1."));
case 6:
return new CareerEventModel(new EventModel(
"A Merovingian strike force attacks with experimental tranquilizers. You survive, but you’re still a little drowsy. Increase the difficulty of Surprise tests by +1.",
"Sleepy",
"A Merovingian strike force attacks with experimental tranquilizers. You survive, but you’re still a little drowsy. Increase the difficulty of Surprise tests by +1."));
case 7:
return new CareerEventModel(new EventModel(
"A Caledonian strike force attacks; it’s a bloody mess.",
"Scarred",
"A Caledonian strike force attacks; it’s a bloody mess."));
case 8:
return new CareerEventModel(new EventModel(
"You accidentally save a tourist from a horrible fate. Little did you know, they were Mayacasting at the time.",
"Entirely Misunderstood",
"You accidentally save a tourist from a horrible fate. Little did you know, they were Mayacasting at the time."));
case 9:
return new CareerEventModel(new EventModel(
"You encounter another tribe’s shaman, and something just clicks. Do you convert? And what article of faith spoke to you?",
"Religious/Spiritual Experience",
"You encounter another tribe’s shaman, and something just clicks. Do you convert? And what article of faith spoke to you?"));
case 10:
return new CareerEventModel(new EventModel(
"Outside of your Trinary, no one knows what you did. What did you do?",
"Paranoid",
"Outside of your Trinary, no one knows what you did. What did you do?"));
case 11:
return new CareerEventModel(new EventModel(
"You encounter a Dogface in battle; they feel impossibly familiar.",
"Vengeful Progeny",
"You encounter a Dogface in battle; they feel impossibly familiar."));
case 12:
return new CareerEventModel(new EventModel(
"You solved a puzzle that stumped your peers. Gain the Analysis talent: Pattern Recognition or another Analysis talent you meet the prerequisites for.",
"",
"You solved a puzzle that stumped your peers.",
"SelectTalentAnalysis"));
case 13:
return new CareerEventModel(new EventModel(
"You survive a terrible accident, but you’re not quite the same afterwards. Reduce your Agility, Brawn, or Coordination by 1.",
"",
"You survive a terrible accident, but you’re not quite the same afterwards.",
"ReduceAttributeAgility|Brawn|Coordination"));
case 14:
return new CareerEventModel(new EventModel(
"They say you can’t teach an old dog new tricks; you learn one anyway. Gain 1 rank of training in a skill you currently have no training in.",
"",
"They say you can’t teach an old dog new tricks; you learn one anyway.",
"IncreaseUntrained"));
case 15:
return new CareerEventModel(new EventModel(
"You survive a terrible accident... barely. Reduce your Vigour by 2.",
"",
"You survive a terrible accident... barely."),
() => { character.vigourReduction += 2; });
case 16:
return new CareerEventModel(new EventModel(
"You easily survive a terrible accident; you feel invincible.",
"Overconfident",
"You easily survive a terrible accident; you feel invincible."));
case 17:
return new CareerEventModel(new EventModel(
"You discover a human language that actually works for you.",
"",
"You discover a human language that actually works for you.",
"LearnLanguage"));
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"After what you did, your pack could no longer stomach the sight of you. You are fired.",
"Unfriended",
"After what you did, your pack could no longer stomach the sight of you.",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"After what happened, the rest of the pack thinks you’re cursed; they might not be wrong. Reduce your Infinity Point refresh rate (min 0).",
"",
"After what happened, the rest of the pack thinks you’re cursed; they might not be wrong."),
() => { character.infinityPoints = Math.max(0, character.infinityPoints - 1); });
case 20:
return new CareerEventModel(new EventModel(
"It seems you’re Destined for Greatness; what comes next may not be pleasant, but it will at least be interesting.",
"",
"It seems you’re Destined for Greatness; what comes next may not be pleasant, but it will at least be interesting.",
"ChineseCurse"));
}
}
private rollOnDogfaceAndWulverTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"Your work carries you to a different Ariadnan nation. Why did that go as well — or as poorly — as it did? Choose a nation besides your own.",
"Relation to Another Nation",
"Your work carries you to a different Ariadnan nation. Why did that go as well — or as poorly — as it did?",
"SelectHomeland"));
case 2: {
const faction = FactionsHelper.getFaction(FactionsHelper.generateFaction(false, true)).name;
return new CareerEventModel(new EventModel(
`You and an offworlder discover a shared interest, and bond immediately. Gain an ally in the ${faction} faction.`,
"",
`You and an offworlder discover a shared interest, and bond immediately. Gain an ally in the ${faction} faction.`));
}
case 3:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You catch your superior embezzling. You are fired the next morning.",
"Relieved of Duty",
"You catch your superior embezzling. You are fired the next morning.",
"Fired"));
case 4:
return new CareerEventModel(new EventModel(
"Some people have good luck. Others have bad luck. You, it seems, have luck. Gain 1 Life Point, but increase your complication range by +1 on Action Scene skill tests.",
"",
"Increase your complication range by +1 on Action Scene skill tests."),
() => { character.lifePoints++; });
case 5:
return new CareerEventModel(new EventModel(
"Your co-workers routinely decide to dump their work on you. To their surprise, you handle it with ease. Gain 1 rank of training in the elective skill you didn’t select for this career.",
"",
"Your co-workers routinely decide to dump their work on you. To their surprise, you handle it with ease.",
"IncreaseSkippedElective"));
case 6:
return new CareerEventModel(new EventModel(
"Despite being cut-off for weeks, you endure whatever the storm throws at you. Gain the Resistance talent: Sturdy, or another Resistance talent you meet the prerequisites for.",
"",
"Despite being cut-off for weeks, you endure whatever the storm throws at you.",
"SelectTalentResistance"));
case 7: {
const faction = FactionsHelper.getFaction(FactionsHelper.generateFaction(false, true)).name;
return new CareerEventModel(new EventModel(
`Your whirlwind romance turns out to be part of a Galactic spy’s mission. Gain a contact in the ${faction} faction.`,
"",
`Your whirlwind romance turns out to be part of a Galactic spy’s mission. Gain a contact in the ${faction} faction.`));
}
case 8:
return new CareerEventModel(new EventModel(
"You save a tourist from a horrible fate. Little did you know, they were Mayacasting at the time.",
"Unlikely Hero",
"You save a tourist from a horrible fate. Little did you know, they were Mayacasting at the time."));
case 9:
return new CareerEventModel(new EventModel(
"You encounter a Galactic missionary, and something just clicks. Do you convert? And what article of faith spoke to you?",
"Religious/Spiritual Experience",
"You encounter a Galactic missionary, and something just clicks. Do you convert? And what article of faith spoke to you?"));
case 10:
return new CareerEventModel(new EventModel(
"A distant relative passes, bequeathing you their treasures — some of which are even interesting — and their debts. Gain 10 doses of painkillers, 2 tiny Pets, a USAriadnan Entrenching tool, 2 Assets worth of Teseum, and debts worth 5 Assets.",
"",
"A distant relative passes, bequeathing you their treasures — some of which are even interesting — and their debts. You have a 5 Asset debt."),
() => {
character.addEquipment("Painkillers (10 doses)");
character.addEquipment("2 tiny Pets");
character.addEquipment("USAriadnan Entrenching Tool");
character.assets += 2;
});
case 11:
return new CareerEventModel(new EventModel(
"Desperate to prove yourself, you turn to stimulants to help you keep the pace. It works — sort of — but the cost is real. You can reduce the difficulty of hazarding your next career by 1. Also, choose a drug — you begin play at that drug's addiction threshold.",
"",
"Desperate to prove yourself, you turn to stimulants to help you keep the pace. It works — sort of — but the cost is real.",
"Rockstar"),
() => { character.hazardDecrease++; });
case 12:
return new CareerEventModel(new EventModel(
"You come home one night, and your partner is gone, leaving no notice, but taking their belongings with them.",
"Abandoned By Love",
"You come home one night, and your partner is gone, leaving no notice, but taking their belongings with them."));
case 13:
return new CareerEventModel(new EventModel(
"You survive a terrible accident, but you can’t get it out of your head. Reduce your Resolve by 2.",
"",
"You survive a terrible accident, but you can’t get it out of your head."),
() => { character.resolveReduction += 2; });
case 14:
return new CareerEventModel(new EventModel(
"They say you can’t teach an old dog new tricks; you learn one anyway. Gain 1 rank of training in a skill you currently have no training in.",
"",
"They say you can’t teach an old dog new tricks; you learn one anyway.",
"IncreaseUntrained"));
case 15:
return new CareerEventModel(new EventModel(
"You survive a terrible accident... barely. Reduce your Vigour by 2.",
"",
"You survive a terrible accident... barely."),
() => { character.vigourReduction += 2; });
case 16:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You are fired. What did you do?",
"",
"You are fired. What did you do?",
"Fired"));
case 17:
return new CareerEventModel(new EventModel(
"You discover a language that’s far easier to speak.",
"",
"You discover a language that’s far easier to speak.",
"LearnLanguage"));
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You are fired for no apparent reason; local news coverage is surprisingly sympathetic. You are fired. You may reduce the difficulty of hazarding your next career by 1. ",
"Relieved of Duty",
"You are fired for no apparent reason; local news coverage is surprisingly sympathetic."),
() => { character.hazardDecrease++; });
case 19:
return new CareerEventModel(new EventModel(
"You survive a terrible accident, but you’re not quite the same afterwards. Reduce three attributes of your choice by 1 each.",
"",
"You survive a terrible accident, but you’re not quite the same afterwards.",
"ReduceAttributes3"));
case 20:
return new CareerEventModel(new EventModel(
"You’ve got the Devil’s Own Luck. Interesting Times ahead.",
"",
"You’ve got the Devil’s Own Luck. Interesting Times ahead.",
"ChineseCurse"));
}
}
private rollOnHaqqislamTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"An old mentor puts in a good word for you. Were there strings attached? You may hazard your next career, even if you don't meet the faction or other prerequisites.",
"",
"An old mentor puts in a good word for you. Were there strings attached?"
),
() => { character.ignoreHazardRequirements = true; });
case 2:
return new CareerEventModel(new EventModel(
"Muhafiz Agents followed you home one night. What did they think you know? Do you?",
"On the Watchlist",
"Muhafiz Agents followed you home one night. What did they think you know? Do you?"
));
case 3:
return new CareerEventModel(new EventModel(
"You’re forced to choose between your ideals and keeping your job. Either become Fired or reduce your Status by 1.",
"Idealistic Choice",
"You’re forced to choose between your ideals and keeping your job.",
"PayStatusToContinue"
));
case 4:
return new CareerEventModel(new EventModel(
"You stepped in to mediate a conflict before it turned violent. Gain 1 rank in Psychology.",
"",
"You stepped in to mediate a conflict before it turned violent.",
"IncreasePsychology"
));
case 5:
return new CareerEventModel(new EventModel(
"During a midnight visit to Medina’s coffeehouses, you played a competitive game of dominoes with a kindly older man. As he leaves, the barista looks like they’ve seen a ghost. If you attempt to hazard the Hassassin Fiday or Exemplar careers, reduce the difficulty by 1. If you choose to stay in your current career, increase your Status by 1.",
"",
"During a midnight visit to Medina’s coffeehouses, you played a competitive game of dominoes with a kindly older man. As he leaves, the barista looks like they’ve seen a ghost."
),
() => {
character.hassassinEvent = true;
});
case 6:
return new CareerEventModel(new EventModel(
"You spend so much time on caravanserai it starts to feel like home. You may choose the Trader or Caravaner career as your next career without making a hazard test.",
"",
"You spend so much time on caravanserai it starts to feel like home."
),
() => {
character.freeCareers.push(Career.Trader);
character.freeCareers.push(Career.Caravaner);
});
case 7:
return new CareerEventModel(new EventModel(
"You develop a rivalry with another Haqqislamite. Is it friendly? Deadly serious? What does your rival want?",
"Rivalry",
"You develop a rivalry with another Haqqislamite. Is it friendly? Deadly serious? What does your rival want?"
));
case 8: {
const faction = FactionsHelper.generateFaction(false, true);
const factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`You save a health tourist from a costly, serpent-related mistake. Gain an ally in the ${factionName} faction.`,
"",
`You save a health tourist from a costly, serpent-related mistake. Gain an ally in the ${factionName} faction.`
));
}
case 9:
return new CareerEventModel(new EventModel(
"You embrace the faith’s teachings wholeheartedly. Some would say a little too much. You may choose Hassassin Fiday or Exemplar as your next career without making a hazard test.",
"Zealot",
"You embrace the faith’s teachings wholeheartedly. Some would say a little too much."
),
() => {
character.freeCareers.push(Career.HassassinFidayHaqqislam);
character.freeCareers.push(Career.HassassinExemplar);
});
case 10:
return new CareerEventModel(new EventModel(
"While on a solitary desert pilgrimage, you happen across a prominent figure in a bad way; your quick thinking and natural knowledge saves their life. Gain 1 rank in Survival. You may select the Akbar Doctor career without making a hazard test.",
"",
"While on a solitary desert pilgrimage, you happen across a prominent figure in a bad way; your quick thinking and natural knowledge saves their life.",
"IncreaseSurvival"
),
() => { character.freeCareers.push(Career.AkbarDoctor); });
case 11:
return new CareerEventModel(new EventModel(
"You participate in the Ocean of Fire race. Gain 1 rank in either Animal Handling or Pilot.",
"",
"You participate in the Ocean of Fire race.",
"IncreaseAnimal Handling|Pilot"
));
case 12:
return new CareerEventModel(new EventModel(
"You’re caught in the middle of a three-way grey market espionage tangle; someone needs to take the fall. You must pass a hazard test or become Fired.",
"",
"You’re caught in the middle of a three-way grey market espionage tangle; someone needs to take the fall.",
"HazardTestOrFired"
));
case 13:
return new CareerEventModel(new EventModel(
"A Silk Lord bequeaths you a portion of their wealth. Are you related? If not, why have they chosen you? Gain 5 assets.",
"",
"A Silk Lord bequeaths you a portion of their wealth. Are you related? If not, why have they chosen you?"
),
() => { character.assets += 5; });
case 14: {
const assets = DiceRoller.rollSpecial(4, 0).hits;
return new CareerEventModel(new EventModel(
`Travelling on the Silk Route maglev, your train is ambushed in the Azar Desert. The fighting is brief, but intense. Your Vigour is reduced by 1 while you recover. You gain ${assets} assets has hazard pay.`,
"",
`Travelling on the Silk Route maglev, your train is ambushed in the Azar Desert. The fighting is brief, but intense.`
),
() => {
character.vigourReduction++;
character.assets += assets;
});
}
case 15: {
const faction = FactionsHelper.generateFaction(false, true);
const factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`Walking through Khadijah’s Garden of Dreaming Pillars, you chance across a secret meeting. What was it? You gain a rival in the ${factionName} faction. Lose 3 assets as they extract a modicum of financial revenge on you.`,
"",
`Walking through Khadijah’s Garden of Dreaming Pillars, you chance across a secret meeting. What was it? You gain a rival in the ${factionName} faction.`
),
() => { character.assets = Math.max(0, character.assets - 3); });
}
case 16:
return new CareerEventModel(new EventModel(
"You volunteered for experimental medical treatments. They went well. Increase your Vigour by 1.",
"",
"You volunteered for experimental medical treatments. They went well."
),
() => { character.vigourReduction--; });
case 17:
return new CareerEventModel(new EventModel(
"You volunteered for experimental medical treatments. They went badly. Decrease your Vigour by 1.",
"",
"You volunteered for experimental medical treatments. They went badly."
),
() => { character.vigourReduction++; });
case 18:
if (isUnemployed) {
return this.generateEvent();
}
return new CareerEventModel(new EventModel(
"You are fired. What did you do? Why did you feel you had to do it?",
"Fired",
"You are fired. What did you do? Why did you feel you had to do it?",
"Fired"
));
case 19:
if (character.isAlMustaslaha()) {
return new CareerEventModel(new EventModel(
"You were murdered, or so the perpetrator thought. On the brink of death you are returned to life. Who was blamed for this, and who do you hold responsible?",
"Murdered",
"You were murdered, or so the perpetrator thought. On the brink of death you are returned to life. Who was blamed for this, and who do you hold responsible?"
),
() => {
character.vigourReduction += 2;
character.resolveReduction--;
});
}
else {
return new CareerEventModel(new EventModel(
"You are murdered. Who was blamed for this, and who do you hold responsible? Your character died and was Resurrected.",
"Murdered",
"You are murdered. Who was blamed for this, and who do you hold responsible?",
"Resurrection"
));
}
case 20:
return new CareerEventModel(new EventModel(
"If you see the Lion’s Teeth, don’t assume that it’s smiling. And right now, you’re seeing a lot of teeth.",
"",
"",
"ChineseCurse"
));
}
}
private rollOnPanOceaniaTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"Some of your investments pay off. You get 4 Assets.",
"",
"Some of your investments paid off."),
() => { character.assets += 4; });
case 2:
return new CareerEventModel(new EventModel(
"Bureau Toth brings you in for questioning. What do they want to know? They let you go, but under what condition?",
"On the Watchlist",
"Bureau Toth brings you in for questioning. What do they want to know? They let you go, but under what condition?"));
case 3:
return new CareerEventModel(new EventModel(
"Your words are badly misconstrued in an interview. Increase the difficulty of hazarding your next career by +1.",
"Antisocial Media",
"Your words were badly misconstrued in an interview."),
() => { character.hazardDecrease--; });
case 4: {
let roll = DiceRoller.rollSpecial(4, 0);
let assets = roll.hits;
assets -= roll.special;
if (assets < 0) assets = 0;
return new CareerEventModel(new EventModel(
`You invest in some high-risk stocks. You gain ${assets} Assets.`,
"",
"You invested in some high-risk stocks."),
() => { character.assets += assets; });
}
case 5:
return new CareerEventModel(new EventModel(
"An old Maya post of yours goes viral overnight.",
"Fringe Celebrity",
"An old Maya post of yours went viral overnight."));
case 6:
return new CareerEventModel(new EventModel(
"Pitting rival employers against each other costs you your job but opens some doors. You are Fired, but you can reduce the difficulty of hazarding careers by 1.",
"The Door Swings Both Ways",
"Pitting rival employers against each other cost you your job but opens some doors.",
"Fired"),
() => { character.hazardDecrease++; });
case 7:
return new CareerEventModel(new EventModel(
"You are the “lucky winner” of a transfer to Paradiso. You may take Croc Man or Special Forces as your next Career without making a hazard test. ",
"Trouble in Paradiso",
"You became the “lucky winner” of a transfer to Paradiso."),
() => { character.freeCareers.push(Career.CrocMan); });
case 8: {
let faction = FactionsHelper.generateFaction(false, true);
let factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`You save a tourist from a horrible fate. You gain an ally in the ${factionName} faction.`,
"",
`You save a tourist from a horrible fate. You gain an ally in the ${factionName} faction.`));
}
case 9:
return new CareerEventModel(new EventModel(
"You embrace the Church’s teachings wholeheartedly.",
"Zealot",
"You embrace the Church’s teachings wholeheartedly."),
() => {
character.freeCareers.push(Career.Priest);
character.freeCareers.push(Career.OrderSergeant);
character.freeCareers.push(Career.Knight);
});
case 10:
return new CareerEventModel(new EventModel(
"Circumstances converge to put you at the helm of a ship. What brought this on? Gain 1 rank in Spacecraft. You may choose Pilot, Ship Crew or Fighter Pilot as your next career.",
"",
"Circumstances converge to put you at the helm of a ship. What brought this on?",
"IncreaseSpacecraft"),
() => {
character.freeCareers.push(Career.Pilot);
character.freeCareers.push(Career.ShipCrew);
character.freeCareers.push(Career.FighterPilot);
});
case 11:
return new CareerEventModel(new EventModel(
"You arrive for work to find nothing. It’s as though your employer never existed. You may not elect to extend or repeat your current career.",
"Left in the Dark",
"You arrive for work to find nothing. It’s as though your employer never existed."),
() => { character.canExtendCareer = false; });
case 12:
return new CareerEventModel(new EventModel(
"You developed an obsession with a professional sports team. As go their fortunes, so go your moods.",
"Sports Fanatic",
"You developed an obsession with a professional sports team. As go their fortunes, so go your moods."));
case 13:
return new CareerEventModel(new EventModel(
"A Hexahedron agent visits your employer. The next day, your employee access has been revoked. What happened? You are Fired. You may choose either Hexas Agent or Criminal as your next career.",
"Hexahedron Casualty",
"A Hexahedron agent visits your employer. The next day, your employee access has been revoked. What happened?",
"Fired"),
() => {
character.freeCareers.push(Career.HexasAgent);
character.freeCareers.push(Career.Criminal);
});
case 14:
return new CareerEventModel(new EventModel(
"Someone close to you is a criminal, but you can’t bring yourself to turn them in. Why not?",
"Dirty Little Secret",
"Someone close to you is a criminal, but you can’t bring yourself to turn them in. Why not?"));
case 15:
return new CareerEventModel(new EventModel(
"You foiled an act of espionage against your employer. Gain +1 Earnings for your act of balance-sheet-friendly heroism.",
"Dangerously Curious",
"You foiled an act of espionage against your employer."),
() => { character.earnings++; });
case 16:
return new CareerEventModel(new EventModel(
"You are fired. What did you do, and why was it worth it?",
"",
"You are fired. What did you do, and why was it worth it?",
"Fired"));
case 17:
return new CareerEventModel(new EventModel(
"You are scouted by an unlikely employer. You may hazard your next career, even if you don’t meet the faction prerequisite.",
"",
"You were scouted by an unlikely employer."),
() => { character.ignoreHazardRequirements = true; });
case 18:
return new CareerEventModel(new EventModel(
"Some old Maya posts of yours get the wrong kind of attention before you can delete them. You are Fired.",
"Old Sins",
"Some old Maya posts of yours got the wrong kind of attention before you could delete them.",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"You are murdered. Who was blamed for this, and who do you think was actually responsible? Your character died and was Resurrected.",
"Murdered",
"You are murdered. Who was blamed for this, and who do you think was actually responsible? Your character died and was Resurrected.",
"Resurrection"));
case 20:
return new CareerEventModel(new EventModel(
"You pay the Price of Ambition: things are about to get interesting. ",
"",
""));
}
}
private rollOnNomadsTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"An old contact from Praxis gets you into an experimental program after the first test subjects found the risks. Most of them. Either increase an Attribute of your choice by 1, gaining a 10 Asset debt along the way, or gain a contact in Praxis’s Black Labs.",
"",
"An old contact from Praxis gets you into an experimental program after the first test subjects found the risks. Most of them.",
"Praxis"));
case 2:
return new CareerEventModel(new EventModel(
"While on assignment, a hypercorp purchases a controlling interest in your client, resulting in mass layoffs. You’re in the process of organising a noisy response when an executive approaches you with a juicy offer. If you take the offer, increase Earnings by 1. Otherwise you are Fired.",
"",
"While on assignment, a hypercorp purchases a controlling interest in your client, resulting in mass layoffs. You’re in the process of organising a noisy response when an executive approaches you with a juicy offer.",
"JuicyOffer"));
case 3:
return new CareerEventModel(new EventModel(
"Someone looking exactly like you crashes through a window, accuses you of stealing their identity, and opens fire. After they’re chased off, you receive a notice: the technician who does your Cube backups has disappeared.",
"Cube Doppleganger",
"Someone looking exactly like you crashes through a window, accuses you of stealing their identity, and opens fire. After they’re chased off, you receive a notice: the technician who does your Cube backups has disappeared."));
case 4:
return new CareerEventModel(new EventModel(
"Coming back from a job, your pilot has a medical emergency, and you get shoved into the cockpit. It was certainly a learning experience. Gain 1 rank in Spacecraft.",
"",
"Coming back from a job, your pilot has a medical emergency, and you get shoved into the cockpit. It was certainly a learning experience.",
"IncreaseSpacecraft"));
case 5: {
let faction = FactionsHelper.generateFaction(false, true);
let factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`During some routine external repairs, a sudden impact knocked you and your fellows loose. Your quick thinking managed to save some but not all of the crew. How did you choose? You gain contacts in ${factionName}.`,
"",
`During some routine external repairs, a sudden impact knocked you and your fellows loose. Your quick thinking managed to save some but not all of the crew. How did you choose? You gain contacts in ${factionName}.`));
}
case 6:
return new CareerEventModel(new EventModel(
"You’re involved in spreading a memetic virus through Maya. ALEPH thanks you for your contributions with a quantronic virus of its own. Reduce Firewall by 1.",
"",
"You’re involved in spreading a memetic virus through Maya. ALEPH thanks you for your contributions with a quantronic virus of its own."),
() => { character.firewallReduction++; });
case 7:
return new CareerEventModel(new EventModel(
"When your ship was damaged in transit, everyone looked to you to make the zero-G repairs. Gain 1 rank in Extraplanetary.",
"",
"When your ship was damaged in transit, everyone looked to you to make the zero-G repairs.",
"IncreaseExtraplanetary"));
case 8:
return new CareerEventModel(new EventModel(
"Tinkering with your geist’s personality emulator, you wind up with mixed results. Increase your geist's Personality by 1.",
"Quirky Geist",
"Tinkering with your geist’s personality emulator, you wind up with mixed results."),
() => { character.geist.attributes[Attribute.Personality].value++; });
case 9:
return new CareerEventModel(new EventModel(
"While working planetside, you get a rare taste of terrestrial weather when you’re stranded for a week. Did it rain? Snow? Something worse? Gain 1 rank in Survival but gain a 2 Asset debt to your eventual rescuers.",
"",
"While working planetside, you get a rare taste of terrestrial weather when you’re stranded for a week. Did it rain? Snow? Something worse? Gain a 2 Asset debt to your eventual rescuers.",
"IncreaseSurvival"));
case 10:
return new CareerEventModel(new EventModel(
"Whether in salvage, falling off the back of a truck, or other means, you find a perfectly good Tinbot just lying around. Gain a Tinbot Remote.",
"Tinbot with Issues",
"Whether in salvage, falling off the back of a truck, or other means, you find a perfectly good Tinbot just lying around. Gain a Tinbot Remote."));
case 11:
return new CareerEventModel(new EventModel(
"After a workplace accident leaves you hospitalised, you opt to get some structural reinforcement. Reduce Vigour by 1 but gain a Subdermal Graft Augmentation.",
"",
"After a workplace accident leaves you hospitalised, you opt to get some structural reinforcement. Gain a Subdermal Graft Augmentation."),
() => { character.vigourReduction++; });
case 12:
return new CareerEventModel(new EventModel(
"The good news is that experimental brain surgery managed to remove all the shrapnel. The bad news is that some of your synapses are firing a little slower. The worse news is that you had shrapnel in your brain; how’d it get there? Reduce Intelligence by 1.",
"",
"The good news is that experimental brain surgery managed to remove all the shrapnel. The bad news is that some of your synapses are firing a little slower. The worse news is that you had shrapnel in your brain; how’d it get there?"),
() => { character.attributes[Attribute.Intelligence].value--; });
case 13: {
let faction = FactionsHelper.generateFaction(false, true);
let factionName = FactionsHelper.getFaction(faction).name;
return new CareerEventModel(new EventModel(
`You met the love of your life. But over time, you’ve come to suspect that they’re an Aspect of ALEPH. Do you confront them? Gain an ally/rival/something else in ${factionName}.`,
"",
`You met the love of your life. But over time, you’ve come to suspect that they’re an Aspect of ALEPH. Do you confront them? Gain an ally/rival/something else in ${factionName}.`));
}
case 14:
return new CareerEventModel(new EventModel(
"You become part of a truly esoteric subculture.",
"Strange Life",
"You become part of a truly esoteric subculture."));
case 15:
return new CareerEventModel(new EventModel(
"You find yourself caught up in a controversy. A Tunguskan lawyer can help, but it won’t be cheap. Either reduce Social Status by one step, or gain an Asset debt, as expensive legal trickery saves you.",
"",
"You find yourself caught up in a controversy. A Tunguskan lawyer can help, but it won’t be cheap.",
"SocialReductionOrDebt"));
case 16:
return new CareerEventModel(new EventModel(
"You come across a Tunguskan Elite in some serious hot water. They lean on you to help them out, while Bureau Aegis tries to warn you away. Either course will have benefits and consequences. What do you do? If you choose to help them you gain a Criminal Record and spent time in jail, but gain 10 Assets. If you refuse to help, reduce Social Status by 1 and gain a rank in Discipline.",
"",
"You come across a Tunguskan Elite in some serious hot water. They lean on you to help them out, while Bureau Aegis tries to warn you away. Either course will have benefits and consequences. What do you do?",
"TunguskanElite"));
case 17:
return new CareerEventModel(new EventModel(
"A hobby invention of yours becomes a brief fad. Gain 5 Assets.",
"",
"A hobby invention of yours becomes a brief fad."),
() => { character.assets += 5; });
case 18:
return new CareerEventModel(new EventModel(
"You strongly disagree with your supervisor, and in grand Nomad tradition, express this by punching them in the face. You are Fired.",
"Stick to Your Principles",
"You strongly disagree with your supervisor, and in grand Nomad tradition, express this by punching them in the face.",
"Fired"));
case 19:
return new CareerEventModel(new EventModel(
"Whether by accident, recklessness, or something more sinister, you found out exactly how well those airlocks work and what it’s like to experience the wonders of space without a suit. You died and was resurrected.",
"Void Breather",
"Whether by accident, recklessness, or something more sinister, you found out exactly how well those airlocks work and what it’s like to experience the wonders of space without a suit. You died and was resurrected.",
"Resurrection"));
case 20:
return new CareerEventModel(new EventModel(
"",
"",
""));
}
}
private rollOnUpliftTable(roll: number, isUnemployed: boolean): CareerEventModel {
switch (roll) {
case 1:
return new CareerEventModel(new EventModel(
"During a routine checkup, the doctors discover an incompatibility in two of your artificial organs; at least one is going to need replaced. Increase either Awareness or Agility by 1. However, decrease the Attribute you didn’t select by 1.",
"",
"During a routine checkup, the doctors discover an incompatibility in two of your artificial organs; at least one is going to need replaced.",
"IncreaseOneAttribute"));
case 2:
return new CareerEventModel(new EventModel(
"An Arachne series runs a feature on you. It isn’t exactly flattering, but it gets your name out there. Increase Lifestyle by 1 rank, but all Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem.",
"",
"Stealth tests are increased in difficulty by one step in situations where being recognised would cause you a problem.",
"IncreaseLifestyle"));
case 3:
return new CareerEventModel(new EventModel(
"You spend some time in a VaudeVille amateur performance troupe. Gain 1 rank in Acrobatics.",
"",
"You spend some time in a VaudeVille amateur performance troupe.",
"IncreaseAcrobatics"));
case 4:
return new CareerEventModel(new EventModel(
"Your geist was acting up, so you got it examined by some Clockmakers. Bad news: the quantronic virus wreaked havoc on your network. Good news: your geist is running better than ever. Reduce Firewall by 1, but add 4 skill ranks to your geist.",
"",
"Your geist was acting up, so you got it examined by some Clockmakers. Bad news: the quantronic virus wreaked havoc on your network. Good news: your geist is running better than ever.",
"IncreaseGeistSkills"));
case 5:
return new CareerEventModel(new EventModel(
"Doctors discover a strange growth. It’s removed without complications, but your musculature atrophies from the treatments. Reduce Brawn by 1.",
"",
"Doctors discover a strange growth. It’s removed without complications, but your musculature atrophies from the treatments"),
() => { character.attributes[Attribute.Brawn].value--; });
case 6: {
const debt = DiceRoller.rollSpecial(4, 4).hits;
return new CareerEventModel(new EventModel(
`You enter a high-stakes card game and lose, badly. You gain a ${debt} Asset debt.`,
"",
`You enter a high-stakes card game and lose, badly. You gain a ${debt} Asset debt.`));
}
case 7:
return new CareerEventModel(new EventModel(
"When your shuttle pilot has an accident, everyone looks to you to take the helm. Gain 1 rank in Spacecraft.",
"",
"When your shuttle pilot has an accident, everyone looks to you to take the helm.",
"IncreaseSpacecraft"));
case 8:
return new CareerEventModel(new EventModel(
"Sick of being treated like a mascot, you express your displeasure in dramatic, public fashion. You are Fired.",
"Sick and Tired",
"Sick of being treated like a mascot, you express your displeasure in dramatic, public fashion.",
"Fired"));
case 9:
return new CareerEventModel(new EventModel(
"When some of your biografts start wearing out, you don’t repair or replace; you upgrade. Increase Brawn by 1 and gain a 5 Asset debt.",
"",
"When some of your biografts start wearing out, you don’t repair or replace; you upgrade. You have a 5 Asset debt."),
() => { character.attributes[Attribute.Brawn].value++; });
case 10:
return new CareerEventModel(new EventModel(
"Most people are immune to animal-specific diseases, and vice versa. You, however, seem to have gotten the worst of both worlds. Reduce Vigour by 1.",
"Allergic to Everything",
"Most people are immune to animal-specific diseases, and vice versa. You, however, seem to have gotten the worst of both worlds."),
() => { character.vigourReduction++; });
case 11:
return new CareerEventModel(new EventModel(
"You overclock your personal area network; while your Comlog sometimes runs hot, the results speak for themselves. Increase Hacking by 1 rank.",
"Overclocked Network",
"You overclock your personal area network; while your Comlog sometimes runs hot, the results speak for themselves.",
"IncreaseHacking"));
case 12:
return new CareerEventModel(new EventModel(
"You spend some time on assignment with Corregidor . Did you make any friends? Enemies? Gain 1 rank in Extraplanetary and a contact on Corregidor.",
"",
"You spend some time on assignment with Corregidor . Did you make any friends? Enemies? You have a contact on Corregidor.",
"IncreaseExtraplanetary"));
case 13:
case 20: {
const assets = DiceRoller.rollSpecial(4, 4).hits;
return new CareerEventModel(new EventModel(
`You enter—and win—a high stakes card game though the Submondo running it are convinced you cheated. Did you? Gain ${assets} Assets and a Submondo rival.`,
"",
`You enter—and win—a high stakes card game though the Submondo running it are convinced you cheated. Did you? You have a Submondo rival.`),
() => { character.assets += assets; });
}
case 14:
return new CareerEventModel(new EventModel(
"Caught in the same firefight, you’re saved by a Reverend Healer-Killer. After some tense discussion on whether or not Uplifts have a soul, you think you hit it off. Gain a contact in the Observance of Saint Mary the Knife.",
"",
"Caught in the same firefight, you’re saved by a Reverend Healer-Killer. After some tense discussion on whether or not Uplifts have a soul, you think you hit it off. Gain a contact in the Observance of Saint Mary the Knife."));
case 15:
case 19:
return new CareerEventModel(new EventModel(
"As someone who underwent an Awakening, you can’t help but notice that your geist is asking increasingly self-aware questions. Your Geist's Awareness and Intelligence are increased by 2.",
"Rogue Geist",
"As someone who underwent an Awakening, you can’t help but notice that your geist is asking increasingly self-aware questions."),
() => {
character.attributes[Attribute.Awareness].value += 2;
character.attributes[Attribute.Intelligence].value += 2;
});
case 16:
return new CareerEventModel(new EventModel(
"Your supervisor puts you in charge of a charity petting zoo. Jokes aside, it goes well. Gain 1 ranki in Animal Handling.",
"",
"Your supervisor puts you in charge of a charity petting zoo. Jokes aside, it goes well",
"IncreaseAnimal Handling"));
case 17:
return new CareerEventModel(new EventModel(
"A minor celebrity freaks out when they see you at work, and their rant goes viral. You are Fired.",
"Subject of Discrimination",
" minor celebrity freaks out when they see you at work, and their rant goes viral. You were Fired.",
"Fired"));
case 18: {
const faction = FactionsHelper.getFaction(FactionsHelper.generateFaction(false, true));
return new CareerEventModel(new EventModel(
`Clandestine operatives abduct you, but Nomad Infiltrators puts a bullet in your head before the vivisection begins. Much to your surprise, you wake up in Praxis. You were dead and has become resurrected. You gain an enemy in ${faction.name}.`,
"",
`Clandestine operatives abduct you, but Nomad Infiltrators puts a bullet in your head before the vivisection begins. Much to your surprise, you wake up in Praxis. You were dead and has became resurrected. You gain an enemy in ${faction.name}.`,
"Resurrection"));
}
}
}
}
export const CareerEventsHelper = new CareerEvents();
|
245dc8353c582392272d0699456ed744bd668aaa
|
TypeScript
|
jaquelineramosit/projeto_zenklub_entrega
|
/src/middlewares/errorHandlerMiddleware.ts
| 2.578125
| 3
|
import { NextFunction, Request, Response } from 'express';
import HttpException from './httpException';
const errorHandler = (err: HttpException, req: Request, res: Response, next: NextFunction) => {
interface ErrorHandler {
status: number,
message: string
}
const error: ErrorHandler = {
status: err.status || 500,
message: err.message || 'Internal server error',
};
res.status(error.status).json(error);
};
export default errorHandler;
|
e6b2871a9912fb58db259aacee3271e689657b9a
|
TypeScript
|
julia-vscode/julia-vscode
|
/src/notebook/helpers.ts
| 3.09375
| 3
|
import { NotebookDocument, workspace, WorkspaceEdit } from 'vscode'
/**
* Use this to perform updates on all cells.
* We cannot update cells in parallel, this could result in data loss.
* E.g. assume we update execution order, while that's going on, assume we update the output (as output comes back from jupyter).
* At this point, VSC is still updating the execution order & we then update the output.
* Depending on the sequence its possible for some of the updates to get lost.
*
* Excellent example:
* Assume we perform the following updates without awaiting on the promise.
* Without awaiting, its very easy to replicate issues where the output is never displayed.
* - We update execution count
* - We update output
* - We update status after completion
*/
const pendingCellUpdates = new WeakMap<NotebookDocument, Promise<unknown>>()
export async function chainWithPendingUpdates(
document: NotebookDocument,
update: (edit: WorkspaceEdit) => void
): Promise<void> {
const notebook = document
const pendingUpdates = pendingCellUpdates.has(notebook) ? pendingCellUpdates.get(notebook)! : Promise.resolve()
const aggregatedPromise = new Promise((resolve, reject) => {
pendingUpdates
// We need to ensure the update operation gets invoked after previous updates have been completed.
// This way, the callback making references to cell metadata will have the latest information.
// Even if previous update fails, we should not fail this current update.
.finally(async () => {
const edit = new WorkspaceEdit()
update(edit)
await workspace.applyEdit(edit).then(
(result) => resolve(result),
(ex) => reject(ex)
)
})
})
pendingCellUpdates.set(notebook, aggregatedPromise)
await aggregatedPromise
}
|
55b02008eb48f5b0c31ae84f023ca7577dd44965
|
TypeScript
|
yuanhjty/code-template-tool
|
/src/utils/path.ts
| 2.6875
| 3
|
import { statSync } from 'fs';
import { dirname, resolve } from 'path';
import { homedir } from 'os';
import { workspace, window } from 'vscode';
import { pipe } from './function';
function parseDirPath(filePath: string | undefined): string | undefined {
if (!filePath) {
return undefined;
}
try {
const stats = statSync(filePath);
const folderPath = stats.isDirectory() ? filePath : dirname(filePath);
return resolve(folderPath);
} catch (e) {}
return undefined;
}
function getCurrentDirPath(): string | undefined {
const activeEditor = window.activeTextEditor;
const filePath = activeEditor && activeEditor.document.fileName;
return parseDirPath(filePath);
}
function getSelectedDirPath(...contextArgs: any[]): string | undefined {
const selectedPath = contextArgs[0] && contextArgs[0].fsPath;
return parseDirPath(selectedPath);
}
export function getWorkspacePath(): string {
const { workspaceFolders } = workspace;
const workspaceFolder = workspaceFolders && workspaceFolders[0];
if (!workspaceFolder) {
return homedir();
}
return workspaceFolder.uri.fsPath;
}
export function getDestDirPath(...contextArgs: any[]): string {
return getSelectedDirPath(...contextArgs) || getCurrentDirPath() || getWorkspacePath();
}
/**
* Resolve params in path
*/
export const resolveParams = (function getResolvePath(): (str: string) => string {
const params = [['{home}', homedir()], ['{workspace}', getWorkspacePath()]];
function getReplacer(subStr: string, newSubStr: string): (str: string) => string {
return (str: string): string => str.replace(subStr, newSubStr);
}
const replacers = params.map(item => getReplacer(item[0], item[1]));
return function resolvePath(path: string): string {
return pipe(...replacers)(path);
};
})();
|
5ec86e74be107a1ceb25f121d4fc42aaf07bba75
|
TypeScript
|
jakemmarsh/react-native-diff-view
|
/src/tokenize/to_token_trees.ts
| 2.96875
| 3
|
import { IHunk, IChange, Side } from '../types';
import { INode } from './back_to_tree';
import { computeOldLineNumber, computeNewLineNumber } from '../utils';
import { last } from '../utils/diff/util';
// This function mutates `linesOfCode` argument.
const applyHunk = (linesOfCode: string[], { newStart, changes }: IHunk): string[] => {
// Within each hunk, changes are continous, so we can use a sequential algorithm here.
//
// When `linesOfCode` is received here, it has already patched by previous hunk,
// thus the starting line number has changed due to possible unbanlanced deletions and insertions,
// we should use `newStart` as the first line number of current reduce.
const [patchedLines] = changes.reduce(
([lines, cursor], { content, isInsert, isDelete }) => {
if (isDelete) {
lines.splice(cursor, 1);
return [lines, cursor];
}
if (isInsert) {
lines.splice(cursor, 0, content);
}
return [lines, cursor + 1];
},
[linesOfCode, newStart - 1],
);
return patchedLines;
};
const applyDiff = (oldSource: string, hunks: IHunk[]): string => {
// `hunks` must be ordered here.
const patchedLines = hunks.reduce(applyHunk, oldSource.split('\n'));
return patchedLines.join('\n');
};
const mapChanges = (changes: IChange[], side: Side, toValue: (change: IChange) => any): IChange[] => {
if (!changes.length) {
return [];
}
const computeLineNumber = side === 'old' ? computeOldLineNumber : computeNewLineNumber;
const changesByLineNumber = changes.reduce(
(acc, change) => {
acc[computeLineNumber(change)] = change;
return acc;
},
{} as Record<number, IChange>,
);
const maxLineNumber = computeLineNumber(last(changes));
return Array.from({ length: maxLineNumber }).map((_value, i) => toValue(changesByLineNumber[i + 1]));
};
const groupChanges = (hunks: IHunk[]): IChange[][] => {
const changes = hunks.reduce((acc, hunk) => {
acc.push(...hunk.changes);
return acc;
}, []);
return changes.reduce(
([oldChanges, newChanges], change) => {
if (change.isNormal) {
oldChanges.push(change);
newChanges.push(change);
} else if (change.isDelete) {
oldChanges.push(change);
} else {
newChanges.push(change);
}
return [oldChanges, newChanges];
},
[[], []],
);
};
const toTextPair = (hunks: IHunk[]): [string, string] => {
const toText = (change: IChange): string => (change ? change.content : '');
const [oldChanges, newChanges] = groupChanges(hunks);
const oldText = mapChanges(oldChanges, 'old', toText).join('\n');
const newText = mapChanges(newChanges, 'new', toText).join('\n');
return [oldText, newText];
};
const createRoot = (children: INode[]): INode => ({ type: 'root', children });
export default (hunks: IHunk[], { highlight, refractor, oldSource, language }: any): INode[] => {
if (oldSource) {
const newSource = applyDiff(oldSource, hunks);
const highlightText = highlight
? (text: string, language: string) => refractor.highlight(text, language)
: (text: string) => [{ type: 'text', value: text }];
return [createRoot(highlightText(oldSource, language)), createRoot(highlightText(newSource, language))];
}
const textPair = toTextPair(hunks);
const toTree = highlight
? (text: string) => createRoot(refractor.highlight(text, language))
: (text: string) => createRoot([{ type: 'text', value: text }]);
return textPair.map(toTree);
};
|
0ba8cd87dbb15edca9aec554f057039d8eb87223
|
TypeScript
|
bookwormdevelopment/typescript-uml
|
/src/uml/node.ts
| 2.765625
| 3
|
import { Association } from './association';
import { Stereotype } from './stereotype';
export class Node {
private _identifier: string;
private _stereotype: Stereotype;
public get identifier(): string {
return this._identifier;
}
public set identifier(value: string) {
this._identifier = value;
}
public get stereotype(): Stereotype {
return this._stereotype;
}
public set stereotype(value: Stereotype) {
this._stereotype = value;
}
constructor(identifier: string, stereotype: Stereotype = Stereotype.None) {
this._identifier = identifier;
this._stereotype = stereotype;
}
}
|
d96ba87cfd29b1d0567bebaa7518ad4f2549d207
|
TypeScript
|
mwojslaw/new-layout
|
/src/mixins/withFlex.ts
| 2.703125
| 3
|
import { CSSObject } from 'styled-components';
import { WithTheme } from '../Theme';
import * as CSS from 'csstype';
import { Length, ResponsiveLength, ResponsiveProp, getLengthValueFactory, getBreakpointsFromProps, isResponsiveProp } from '../utils';
export type WithFlexConfig = {
flexWrap?: CSS.Property.FlexWrap;
flexDirection?: CSS.Property.FlexDirection | ResponsiveProp<CSS.Property.FlexDirection>;
justifyContent?: CSS.Property.JustifyContent;
alignItems?: CSS.Property.AlignItems;
gap?: Length | ResponsiveLength;
};
export const withFlex = ({ theme, ...config }: WithTheme<WithFlexConfig>): CSSObject => {
const breakpoints = getBreakpointsFromProps(config);
const getLengthValue = getLengthValueFactory(theme);
return {
display: 'flex',
...(config.gap && { gap: getLengthValue(config.gap) }),
...(config.flexWrap && { flexWrap: config.flexWrap }),
...(config.alignItems && { alignItems: config.alignItems }),
...(config.flexDirection && !isResponsiveProp(config.flexDirection) && { flexDirection: config.flexDirection }),
...(config.justifyContent && { justifyContent: config.justifyContent }),
...breakpoints.reduce(
(rules, breakpoint) => ({
...rules,
[`@media(min-width: ${theme.breakpoints[breakpoint]})`]: {
...(config.gap && { gap: getLengthValue(config.gap) }),
...(config.flexDirection &&
isResponsiveProp(config.flexDirection) && { flexDirection: config.flexDirection[breakpoint] }),
},
}),
{},
),
};
};
|
e658b57161d55d17efee1c71cc148428dc05f80b
|
TypeScript
|
toketeeman/Ng8-Production-BioLab-FrontEnd
|
/src/app/dialogs/error-dialog/error-dialog.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
@Injectable({
providedIn: 'root'
})
export class ErrorDialogService {
constructor(private dialog: MatDialog) { }
openDialogForMessages(errorMessages: string | string[]): void {
let combinedMessages: string[] = [];
combinedMessages = combinedMessages.concat(errorMessages);
const dialogConfig = new MatDialogConfig();
dialogConfig.hasBackdrop = true;
dialogConfig.disableClose = true;
dialogConfig.panelClass = 'standard-modalbox';
dialogConfig.data = {
errorMessages: combinedMessages
};
dialogConfig.width = "400px";
this.dialog.open(ErrorDialogComponent, dialogConfig);
}
openDialogForErrorResponse(errorResponse: object, errorKeys: string[], errorDefaultMessage?: string): void {
let combinedMessages: string[] = [];
if ( errorDefaultMessage !== undefined && errorDefaultMessage !== null ) {
combinedMessages.push(errorDefaultMessage);
}
for ( const errorKey of errorKeys as string[] ) {
const errorValue: string[] = this.findValueForErrorKey( errorResponse, errorKey );
if (errorValue) {
combinedMessages = combinedMessages.concat(errorValue);
}
}
const dialogConfig = new MatDialogConfig();
dialogConfig.hasBackdrop = true;
dialogConfig.disableClose = true;
dialogConfig.panelClass = 'standard-modalbox';
dialogConfig.data = {
errorMessages: combinedMessages
};
dialogConfig.width = "400px";
this.dialog.open(ErrorDialogComponent, dialogConfig);
}
// It is presumed an object is being supplied at the top level and the value of the desired key is a string array.
findValueForErrorKey(obj: any, errorKey: string): string[] {
let value = null;
for ( const key in obj ) {
if (!obj.hasOwnProperty(key)) {
continue;
}
if (key === errorKey) {
value = obj[key];
} else if (typeof obj[key] === 'object') {
value = this.findValueForErrorKey(obj[key], errorKey);
}
if (value) {
return value;
}
}
return value;
}
}
|
f48c9e018bc57ccd688ce2ed9e531d878d440093
|
TypeScript
|
nicolaspayot/bic
|
/test/bic.test.ts
| 3.015625
| 3
|
import bic from '../src/index';
describe('bic.isValid', () => {
test('Undefined should not be valid as BIC', () => {
// @ts-expect-error
expect(bic.isValid()).toBe(false);
});
test('An empty string should not be valid as BIC', () => {
expect(bic.isValid('')).toBe(false);
});
test('A number should not be valid as BIC', () => {
// @ts-expect-error
expect(bic.isValid(12345678)).toBe(false);
});
test('A BIC with less than 8 characters should not be valid', () => {
expect(bic.isValid('ABCDE')).toBe(false);
expect(bic.isValid('ABCDEFG')).toBe(false);
expect(bic.isValid('ABCD123')).toBe(false);
});
test('A BIC with length between 8 and 11 should not be valid', () => {
expect(bic.isValid('ABCDEFGHI')).toBe(false);
expect(bic.isValid('ABCDEFGHIJ')).toBe(false);
});
test('A BIC with more than 11 characters should not be valid', () => {
expect(bic.isValid('ABCDEFGHIJKL')).toBe(false);
});
test('A BIC with numbers on the 6 first characters should not be valid', () => {
expect(bic.isValid('1ABCDEFG')).toBe(false);
expect(bic.isValid('A1BCDEFG')).toBe(false);
expect(bic.isValid('AB1CDEFG')).toBe(false);
expect(bic.isValid('ABC1DEFG')).toBe(false);
expect(bic.isValid('ABCD1EFG')).toBe(false);
expect(bic.isValid('ABCDE1FG')).toBe(false);
});
test('A BIC with special characters should not be valid', () => {
expect(bic.isValid('ABCDEFG*')).toBe(false);
expect(bic.isValid('_BCDEFG')).toBe(false);
expect(bic.isValid('ABC-EFG')).toBe(false);
});
test('A BIC with 8 characters (last 2 can be numbers) should be valid', () => {
expect(bic.isValid('ABCDEFGH')).toBe(true);
expect(bic.isValid('ABCDEFG1')).toBe(true);
expect(bic.isValid('ABCDEF12')).toBe(true);
});
test('A BIC with 11 characters (last 5 can be numbers) should be valid', () => {
expect(bic.isValid('ABCDEFGHIJK')).toBe(true);
expect(bic.isValid('ABCDEFGHIJ1')).toBe(true);
expect(bic.isValid('ABCDEFGHI12')).toBe(true);
expect(bic.isValid('ABCDEFGH123')).toBe(true);
expect(bic.isValid('ABCDEFG1234')).toBe(true);
expect(bic.isValid('ABCDEF12345')).toBe(true);
});
test('BIC of popular known banks should be valid', () => {
expect(bic.isValid('CHASUS33')).toBe(true);
expect(bic.isValid('BOFAUS3N')).toBe(true);
expect(bic.isValid('WFBIUS6S')).toBe(true);
expect(bic.isValid('CITIUS33')).toBe(true);
expect(bic.isValid('GOLDUS33')).toBe(true);
});
});
|
25bcf1e17d86e462428c5bf80dd545efa9c03450
|
TypeScript
|
GeorgDV/turbulenz_engine
|
/apps/multiworm/tsscripts/worm/gamebadges.ts
| 2.765625
| 3
|
// Copyright (c) 2011-2012 Turbulenz Limited
/*global TurbulenzEngine: false*/
/*global Badge: false*/
//
// GameBadges: Class to manage game badges, and their html elements
//
class GameBadges
{
badgesManager: BadgeManager;
onInitialization: { (): void; };
unachievedBadges: { [name: string]: Badge; };
achievedBadges: { [name: string]: Badge; };
// Stores badges that will be awarded irrespective of current progress
awardedBadges: { [name: string]: boolean; };
hasChanged: boolean;
// Used to know when to write html output
hasChangedData: boolean;
// True only if we have a leaderboard manager, and we are initialised
isActive: boolean;
// Vars to manage situation where connection to badges server is lost
hasConnection: boolean;
updateInterval: number;
maxInterval: number;
lastUpdateTime: number;
// Adds the badges structure into the element div
init()
{
var that = this;
function localInitialiseBadges(badges)
{
that.initialiseBadges(badges);
}
function localErrorCallback(msg, status)
{
that.initialiseBadgesErrorCallback(msg, status);
}
// Store and categorise badges
this.badgesManager.listBadges(localInitialiseBadges, localErrorCallback);
}
// Error function when we fail to list & initialise badges
initialiseBadgesErrorCallback(msg, status)
{
this.isActive = false;
this.onInitialization();
}
// Add all badges to unachieved badge dictionary
initialiseBadges(badges)
{
var that = this;
var unachievedBadges = this.unachievedBadges;
function localInitialiseUserBadges(badges)
{
that.initialiseUserBadges(badges);
}
function localErrorCallback(msg, status)
{
that.initialiseBadgesErrorCallback(msg, status);
}
var i;
var name;
var badge;
var length = badges.length;
for (i = 0; i < length; i += 1)
{
badge = badges[i];
name = badge.key;
// Create an unachieved badge
unachievedBadges[name] = Badge.create(badge.total, badge.predescription, badge.description, badge.title);
}
// Add user badges to badges dictionary
this.badgesManager.listUserBadges(localInitialiseUserBadges, localErrorCallback);
}
// Add user badges to unachieved and achieved badge dictionaries
initialiseUserBadges(badges)
{
var achievedBadges = this.achievedBadges;
var unachievedBadges = this.unachievedBadges;
var i;
var name;
var badge;
var unachievedBadge;
var length = badges.length;
for (i = 0; i < length; i += 1)
{
badge = badges[i];
name = badge.badge_key;
unachievedBadge = unachievedBadges[name];
if (unachievedBadge !== undefined)
{
// If already achieved then store as such
if (!badge.current ||
badge.current >= unachievedBadge.totalRequired)
{
achievedBadges[name] = unachievedBadge;
delete unachievedBadges[name];
}
else
{
// Create an unachieved badge
unachievedBadge.currentProgress = badge.current;
}
}
}
this.isActive = true;
this.onInitialization();
}
// Adds a user badge (with how much they have achieved towards it)
addBadge(badgeName)
{
var unachievedBadge;
// If badge has not been achieved then update
if (this.isActive &&
!this.achievedBadges[badgeName])
{
unachievedBadge = this.unachievedBadges[badgeName];
// If badge is non-progress then award it
if (unachievedBadge.isNonProgress)
{
this.awardBadge(badgeName);
}
// Else update current badge progress
else
{
unachievedBadge.addProgress();
this.hasChanged = true;
}
}
}
// Awards a user badge no matter what the current progress
awardBadge(badgeName)
{
if (this.isActive &&
!this.achievedBadges[badgeName])
{
this.awardedBadges[badgeName] = true;
this.hasChanged = true;
}
}
// Updates the state of all badges
refresh()
{
var that = this;
var unachievedBadges = this.unachievedBadges;
var awardedBadges = this.awardedBadges;
var badgesManager = this.badgesManager;
var badge;
var unachievedBadge;
function localUpdateUserBadgeProgressCallback(badge)
{
that.updateUserBadgeProgressCallback(badge);
}
function localAwardUserBadgeCallback(badge)
{
that.awardUserBadgeCallback(badge);
}
function localUpdateUserBadgeErrorCallback(msg, status, badge)
{
that.updateUserBadgeErrorCallback(msg, status, badge);
}
function localAwardUserBadgeErrorCallback(msg, status, badge)
{
that.awardUserBadgeErrorCallback(msg, status, badge);
}
// Set awarded badges first
for (badge in awardedBadges)
{
if (awardedBadges.hasOwnProperty(badge) &&
!unachievedBadges[badge].isUpdating)
{
unachievedBadges[badge].award();
badgesManager.awardUserBadge(badge, localAwardUserBadgeCallback, localAwardUserBadgeErrorCallback);
}
}
// Update badges which have been incremented
for (badge in unachievedBadges)
{
if (unachievedBadges.hasOwnProperty(badge))
{
unachievedBadge = unachievedBadges[badge];
if (!unachievedBadge.isUpdating &&
unachievedBadge.hasProgressed)
{
unachievedBadge.onBeforeSet();
badgesManager.updateUserBadgeProgress(badge, unachievedBadge.currentProgress,
localUpdateUserBadgeProgressCallback, localUpdateUserBadgeErrorCallback);
}
}
}
}
// Callback when user badge has been added
updateUserBadgeProgressCallback(badge)
{
var unachievedBadges = this.unachievedBadges;
var badgeName = badge.badge_key;
var unachievedBadge = unachievedBadges[badgeName];
this.hasConnection = true;
unachievedBadge.onSuccessfulSet(badge.current);
// Used for writing html output on local
this.hasChangedData = true;
// If badge is now achieved
if (unachievedBadge.isAchieved())
{
this.achievedBadges[badgeName] = unachievedBadges[badgeName];
delete unachievedBadges[badgeName];
}
}
// Error callback when user badge failed to add
updateUserBadgeErrorCallback(msg, status, badgeData)
{
var badgeName = badgeData[0];
var unachievedBadge = this.unachievedBadges[badgeName];
this.hasConnection = false;
this.hasChanged = true;
unachievedBadge.onUnsuccessfulSet();
}
// Callback when user badge has been awarded
awardUserBadgeCallback(badge)
{
var badgeName = badge.badge_key;
this.achievedBadges[badgeName] = this.unachievedBadges[badgeName];
delete this.unachievedBadges[badgeName];
delete this.awardedBadges[badgeName];
this.hasConnection = true;
this.hasChangedData = true;
}
// Callback when user badge has been awarded
awardUserBadgeErrorCallback(msg, status, badgeData)
{
var badgeName = badgeData[0];
this.hasConnection = false;
this.hasChanged = true;
this.unachievedBadges[badgeName].onUnsuccessfulSet();
}
// Update function called in main loop
update(currentTime)
{
var updateInterval = this.updateInterval;
if (this.isActive &&
this.hasChanged)
{
if (!this.hasConnection)
{
if (currentTime - this.lastUpdateTime > updateInterval)
{
this.updateInterval = Math.min((updateInterval * 2), this.maxInterval);
this.lastUpdateTime = currentTime;
this.refresh();
}
}
else
{
this.lastUpdateTime = currentTime;
this.hasChanged = false;
this.refresh();
}
}
}
static create(badgesManager, onInitialization): GameBadges
{
var gameBadges = new GameBadges();
gameBadges.badgesManager = badgesManager;
gameBadges.onInitialization = onInitialization;
gameBadges.unachievedBadges = {};
gameBadges.achievedBadges = {};
// Stores badges that will be awarded irrespective of current progress
gameBadges.awardedBadges = {};
gameBadges.hasChanged = true;
// Used to know when to write html output
gameBadges.hasChangedData = true;
// True only if we have a leaderboard manager, and we are initialised
gameBadges.isActive = false;
// Vars to manage situation where connection to badges server is lost
gameBadges.hasConnection = true;
gameBadges.updateInterval = 1;
gameBadges.maxInterval = 120;
gameBadges.lastUpdateTime = TurbulenzEngine.time;
if (badgesManager)
{
gameBadges.init();
}
else
{
onInitialization();
}
return gameBadges;
}
}
|
6e3fcc41b1640f72d50d140bf04ed4e66dd4b8c0
|
TypeScript
|
vladimirdotk/auth-service
|
/app/src/services/userService.ts
| 2.546875
| 3
|
import url = require('url');
import bcrypt = require('bcrypt');
import { NOT_FOUND } from 'http-status-codes';
import { getRandomName } from './../utils';
import { User, IUser } from './../models/User';
import * as mailService from './../services/mailService';
import { IError } from './../interfaces/error';
interface IUserData {
userId: IUser['id'];
protocol: string;
hostname: string;
port: number;
userData: IUser;
confirmCode?: string;
}
export default class UserService {
public readonly confirmText = 'Please confirm user data changes';
public async getAll(): Promise<User[]> {
return User.query();
}
public async getById(userId: IUser['id']): Promise<User> {
const user = await User
.query()
.findById(<number>userId);
this.checkUser(user);
return user!;
}
public async findOne(data: IUser): Promise<User | undefined> {
return await User.query().findOne(data);
}
public async create(data: IUser): Promise<User> {
if (data.password) {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(data.password, salt);
data.password = hash;
}
return User.query().insert(<User>data);
}
public async removeById(userId: IUser['id']): Promise<number> {
return User.query().deleteById(<number>userId);
}
public async changeUser(data: IUserData) {
const user = await User.query().findById(<number>data.userId);
const confirmCode = getRandomName();
this.checkUser(user);
await User
.query()
.update({ confirmCode })
.where('id', user!.id);
const confirmUrl = this.createConfirmUrl(Object.assign(data, { confirmCode }));
const mailOptions = this.createConfirmMailOptions(user!.email!, confirmUrl);
await mailService.send(mailOptions);
return confirmUrl;
}
public async confirmChanges(data: Partial<IUserData>): Promise<User> {
const user = await User.query().findById(<number>data.userId);
this.checkUser(user);
return user!
.$query()
.updateAndFetch({ confirmCode: undefined, ...data.userData });
}
public async comparePassword (candidatePassword: string, hash: string): Promise<boolean> {
const isMatch = await bcrypt.compare(candidatePassword, hash);
return Promise.resolve(isMatch);
}
private checkUser(user: IUser | undefined) {
if (!user) {
const error: IError = new Error('User not found');
error.status = NOT_FOUND;
throw error;
}
}
private createConfirmUrl(data: IUserData) {
return url.format({
protocol: data.protocol,
hostname: data.hostname,
port: data.port,
pathname: `/users/${data.userId}/confirm-changes`,
query: Object.assign(data.userData, { confirmCode: data.confirmCode }),
});
}
private createConfirmMailOptions(email: string, confirmUrl: string) {
return {
from: process.env.MAILER_EMAIL,
to: email,
subject: this.confirmText,
text: `${this.confirmText}: ${confirmUrl}`,
html: `<div>${this.confirmText}: ${confirmUrl}</div>`,
};
}
}
|
119dd6c38a4e8fc972129a53db99ceb5dc40ee01
|
TypeScript
|
rmalibiran/98labs-api-starter-project
|
/src/models/user.ts
| 2.671875
| 3
|
import {
Sequelize,
Model,
DataTypes,
BuildOptions,
} from 'sequelize';
export class User extends Model {
public id!: number;
public email: string;
public password: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
export type UserRepository = typeof Model & {
new (values?: object, options?: BuildOptions): User;
};
export const userInitializer = (sequelize: Sequelize): any => {
const attributes = {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
};
const initParams = {
sequelize,
schema: 'public',
tableName: 'users',
timestamps : true,
underscored : true,
};
User.init(attributes, initParams);
};
|
cd60ea13dafc701ce9cfa7fbf7786862fb2bf8b2
|
TypeScript
|
dusanbass/ts-new-test
|
/Point3D.ts
| 3.34375
| 3
|
import Point2D from "./Point2D";
export default class Point3D extends Point2D {
z: number;
constructor(x: number = 0, y: number = 0, z: number = 0) {
super(x, y); // new Point2D(x, y)
this.z = z;
};
// overwrite - write over some previously defined method
position(): string { // this should be called toString actually...
return `${super.position()} z: ${this.z}` // template string + super method
}
}
|
b0ce595b03c869fad21880e81ed55e183031653d
|
TypeScript
|
jupyterlab/jupyterlab
|
/packages/apputils/src/toolbar/registry.ts
| 2.546875
| 3
|
/*
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/
import {
CommandToolbarButton,
LabIcon,
Toolbar
} from '@jupyterlab/ui-components';
import { CommandRegistry } from '@lumino/commands';
import { Widget } from '@lumino/widgets';
import { IToolbarWidgetRegistry, ToolbarRegistry } from '../tokens';
import { ISignal, Signal } from '@lumino/signaling';
/**
* Concrete implementation of IToolbarWidgetRegistry interface
*/
export class ToolbarWidgetRegistry implements IToolbarWidgetRegistry {
constructor(options: ToolbarRegistry.IOptions) {
this._defaultFactory = options.defaultFactory;
}
/**
* Default toolbar item factory
*/
get defaultFactory(): (
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
) => Widget {
return this._defaultFactory;
}
set defaultFactory(
factory: (
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
) => Widget
) {
this._defaultFactory = factory;
}
/**
* A signal emitted when a factory widget has been added.
*/
get factoryAdded(): ISignal<this, string> {
return this._factoryAdded;
}
/**
* Create a toolbar item widget
*
* @param widgetFactory The widget factory name that creates the toolbar
* @param widget The newly widget containing the toolbar
* @param toolbarItem The toolbar item definition
* @returns The widget to be inserted in the toolbar.
*/
createWidget(
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
): Widget {
const factory = this._widgets.get(widgetFactory)?.get(toolbarItem.name);
return factory
? factory(widget)
: this._defaultFactory(widgetFactory, widget, toolbarItem);
}
/**
* Add a new toolbar item factory
*
* @param widgetFactory The widget factory name that creates the toolbar
* @param toolbarItemName The unique toolbar item
* @param factory The factory function that receives the widget containing the toolbar and returns the toolbar widget.
* @returns The previously defined factory
*/
addFactory<T extends Widget = Widget>(
widgetFactory: string,
toolbarItemName: string,
factory: (main: T) => Widget
): ((main: T) => Widget) | undefined {
let namespace = this._widgets.get(widgetFactory);
const oldFactory = namespace?.get(toolbarItemName);
if (!namespace) {
namespace = new Map<string, (main: Widget) => Widget>();
this._widgets.set(widgetFactory, namespace);
}
namespace.set(toolbarItemName, factory);
this._factoryAdded.emit(toolbarItemName);
return oldFactory;
}
/**
* Register a new toolbar item factory
*
* @param widgetFactory The widget factory name that creates the toolbar
* @param toolbarItemName The unique toolbar item
* @param factory The factory function that receives the widget containing the toolbar and returns the toolbar widget.
* @returns The previously defined factory
*
* @deprecated since v4 use `addFactory` instead
*/
registerFactory<T extends Widget = Widget>(
widgetFactory: string,
toolbarItemName: string,
factory: (main: T) => Widget
): ((main: T) => Widget) | undefined {
return this.addFactory(widgetFactory, toolbarItemName, factory);
}
protected _defaultFactory: (
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
) => Widget;
protected _widgets: Map<string, Map<string, (main: Widget) => Widget>> =
new Map<string, Map<string, (main: Widget) => Widget>>();
protected _factoryAdded = new Signal<this, string>(this);
}
/**
* Create the default toolbar item widget factory
*
* @param commands Application commands registry
* @returns Default factory
*/
export function createDefaultFactory(
commands: CommandRegistry
): (
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
) => Widget {
return (
widgetFactory: string,
widget: Widget,
toolbarItem: ToolbarRegistry.IWidget
) => {
switch (toolbarItem.type ?? 'command') {
case 'command': {
const {
command: tId,
args: tArgs,
label: tLabel,
caption: tCaption,
icon: tIcon
} = toolbarItem;
const id = tId ?? '';
const args = { toolbar: true, ...tArgs };
const icon = tIcon ? LabIcon.resolve({ icon: tIcon }) : undefined;
// If there is an icon, undefined label will results in no label
// otherwise the label will be set using the setting or the command label
const label = icon ?? commands.icon(id, args) ? tLabel ?? '' : tLabel;
return new CommandToolbarButton({
commands,
id,
args,
icon,
label,
caption: tCaption as string
});
}
case 'spacer':
return Toolbar.createSpacerItem();
default:
return new Widget();
}
};
}
|
8f74a668ce81eace0c8ce61ff8123b55829c915f
|
TypeScript
|
michitaro/gl-wrapper
|
/src/index_buffer.ts
| 3.046875
| 3
|
import * as glUtils from './utils'
export interface DataOption {
usage?: number,
array: Int16Array,
}
export class IndexBuffer {
private name: WebGLBuffer
private usage!: number
private _length!: number
constructor(readonly gl: WebGLRenderingContext, dataOption?: DataOption) {
this.name = glUtils.nonNull(this.gl.createBuffer())
if (dataOption)
this.setData(dataOption)
}
release() {
this.gl.deleteBuffer(this.name)
}
bind(cb: () => void) {
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.name)
cb()
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null)
}
setData({ usage, array }: DataOption) {
this.usage = usage || this.gl.STATIC_DRAW
this._length = array.length
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, this.name)
this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, array, this.usage)
this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null)
}
get length() {
return this._length
}
}
|
1dc341d9a488fa60ceb42dc4d04c041a808de5b1
|
TypeScript
|
Ihor-Kulpekin/social_media_backend
|
/src/entities/User.ts
| 2.96875
| 3
|
import {Entity as TOEntity, Column, Index, BeforeInsert} from 'typeorm';
import {IsEmail, Length} from 'class-validator';
import BaseEntity from "./Entity";
import {hashPassword} from "../utils/hashPassword";
import { Exclude } from 'class-transformer';
@TOEntity('user')
export default class User extends BaseEntity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user)
}
@Index()
@IsEmail()
@Column({unique: true})
email: string = '';
@Index()
@Length(3, 255, {message: 'name must be at least 3 chracters long.'})
@Column()
name: string = '';
@Exclude()
@Column()
@Length(6, 255, {message: 'Password must be at least 6 chracters long.'})
password: string = '';
@Index()
@Length(3, 255, {message: 'Lastname must be at least 3 chracters long.'})
@Column()
lastName: string = '';
@BeforeInsert()
async hashPassword() {
this.password = await hashPassword(this.password, 10);
}
}
|
57740c46151d5840c200e0601952a59c3b11e8ab
|
TypeScript
|
2284730142/G2Plot
|
/src/plots/tiny-area/adaptor.ts
| 2.5625
| 3
|
import { isFunction } from '@antv/util';
import { theme, scale } from '../../adaptor/common';
import { Params } from '../../core/adaptor';
import { flow } from '../../utils';
import { DEFAULT_TOOLTIP_OPTIONS } from '../tiny-line/constants';
import { TinyAreaOptions } from './types';
/**
* 字段
* @param params
*/
function field(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart, options } = params;
const { data } = options;
const seriesData = data.map((y: number, x: number) => {
return { x, y };
});
chart.data(seriesData);
chart.area().position('x*y');
chart.line().position('x*y');
return params;
}
/**
* axis 配置
* @param params
*/
function axis(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart } = params;
chart.axis(false);
return params;
}
/**
* legend 配置
* @param params
*/
function legend(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart } = params;
chart.legend(false);
return params;
}
/**
* tooltip 配置
* @param params
*/
export function tooltip(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart, options } = params;
const { tooltip = false } = options;
if (tooltip) {
if (typeof tooltip === 'object') {
const { formatter, domStyles, position, offset, showCrosshairs } = tooltip;
chart.tooltip({
...DEFAULT_TOOLTIP_OPTIONS,
showCrosshairs,
domStyles,
position,
offset,
});
chart.geometries.map((geometry) => {
geometry.tooltip('x*y', (x, y) => {
return {
value: formatter(x, y),
};
});
});
} else {
chart.tooltip(DEFAULT_TOOLTIP_OPTIONS);
}
} else {
chart.tooltip(false);
}
return params;
}
/**
* 样式
* @param params
*/
function style(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart, options } = params;
const { lineStyle, areaStyle } = options;
const areaGeometry = chart.geometries[0];
if (areaStyle && areaGeometry) {
if (isFunction(areaStyle)) {
areaGeometry.style('x*y', areaStyle);
} else {
areaGeometry.style(areaStyle);
}
}
const lineGeometry = chart.geometries[1];
if (lineStyle && lineGeometry) {
if (isFunction(lineStyle)) {
lineGeometry.style('x*y', lineStyle);
} else {
lineGeometry.style(lineStyle);
}
}
return params;
}
/**
* shape 的配置处理
* @param params
*/
function shape(params: Params<TinyAreaOptions>): Params<TinyAreaOptions> {
const { chart, options } = params;
const { smooth } = options;
const areaGeometry = chart.geometries[0];
areaGeometry.shape(smooth ? 'smooth' : 'area');
const lineGeometry = chart.geometries[1];
lineGeometry.shape(smooth ? 'smooth' : 'line');
return params;
}
/**
* 迷你面积图适配器
* @param chart
* @param options
*/
export function adaptor(params: Params<TinyAreaOptions>) {
return flow(field, scale({}), axis, legend, tooltip, style, shape, theme)(params);
}
|
413921bb520e001d3c159c6f04694e64f38358e1
|
TypeScript
|
tommck/hoopy
|
/postProcessing/HoopHouseProcessor.ts
| 2.546875
| 3
|
import {IStatsProcessor} from './IStatsProcessor';
import {config} from '../config';
import {sendPushbulletNotification} from '../services/pushbullet';
import {ITableEntry} from '../TableEntry';
export class HoopHouseProcessor implements IStatsProcessor {
processEntries(hostName: string, entries: ITableEntry[]) {
if (hostName !== 'hoopy-inside') {
return;
}
let exceededMax: ITableEntry = null;
let exceededMin: ITableEntry = null;
let exceededSoilMin: ITableEntry = null;
let exceededSoilMax: ITableEntry = null;
let ambientLimits = config.hoopHouseThresholds.ambient;
let soilLimits = config.hoopHouseThresholds.soil;
entries.forEach(function(entry) {
if (entry.temp > ambientLimits.max) {
exceededMax = entry;
}
else if (entry.temp < ambientLimits.min) {
exceededMin = entry;
}
if (entry.soilTemp !== -1) {
if (entry.soilTemp > soilLimits.max) {
exceededSoilMax = entry;
}
else if (entry.soilTemp < soilLimits.min) {
exceededSoilMin = entry;
}
}
});
if (exceededMax) {
const msg = 'Hoopy House is HOT!';
let body = `Exceeded Maximum temperature of ${ambientLimits.max}F.\nLast Temp: ${exceededMax.temp}F\nSoil Temp: ${exceededMax.soilTemp}F`;
sendPushbulletNotification(config.hoopHouseThresholds.email, msg, body);
sendPushbulletNotification(config.pushbullet.devices.tomsPhone, msg, body);
}
if (exceededMin) {
const msg = 'Hoopy House is COLD!';
let body = `Hit Temp below min of ${ambientLimits.min}F.\nLast Temp: ${exceededMin.temp}F\nSoil Temp: ${exceededMin.soilTemp}F`;
sendPushbulletNotification(config.hoopHouseThresholds.email, msg, body);
sendPushbulletNotification(config.pushbullet.devices.tomsPhone, msg, body);
}
if (exceededSoilMin) {
const msg = 'Hoopy House SOIL is COLD!';
let body = `Hit Temp below min of ${soilLimits.min}F.\nLast Temp: ${exceededSoilMin.soilTemp}F\nAmbient Temp: ${exceededSoilMin.temp}F`;
sendPushbulletNotification(config.hoopHouseThresholds.email, msg, body);
sendPushbulletNotification(config.pushbullet.devices.tomsPhone, msg, body);
}
if (exceededSoilMax) {
const msg = 'Hoopy House SOIL is HOT!';
let body = `Exceeded Maximum temperature of ${soilLimits.max}F.\nLast Temp: ${exceededSoilMax.soilTemp}F\nAmbient Temp: ${exceededSoilMax.temp}F`;
sendPushbulletNotification(config.hoopHouseThresholds.email, msg, body);
sendPushbulletNotification(config.pushbullet.devices.tomsPhone, msg, body);
}
}
}
|
eb2928afbc8a220579442fdf7de9c315ee76f862
|
TypeScript
|
briggySmalls/late-train-mate
|
/src/app/national-rail/hsp-details.model.ts
| 2.75
| 3
|
import { List } from 'linqts';
import * as moment from 'moment';
import { HspApiData, Station, TimeOnly, DateOnly } from './shared/hsp-core.model';
import { ResourceService } from './resource.service';
export class StopDetails extends HspApiData {
public station: Station;
public scheduledDeparture: moment.Moment;
public scheduledArrival: moment.Moment;
public actualDeparture: moment.Moment;
public actualArrival: moment.Moment;
public disruptionCode: number;
constructor(stopData: any,
date: DateOnly,
originTime: moment.Moment,
resourceService: ResourceService) {
super();
// Populate class from json data
resourceService.lookupStation(stopData['location']).subscribe(station => { this.station = station; });
this.scheduledDeparture = stopData['gbtt_ptd'] ? this.dateFromTime(this.toTime(stopData['gbtt_ptd'], date), originTime) : undefined;
this.scheduledArrival = stopData['gbtt_pta'] ? this.dateFromTime(this.toTime(stopData['gbtt_pta'], date), originTime) : undefined;
this.actualDeparture = stopData['actual_td'] ? this.dateFromTime(this.toTime(stopData['actual_td'], date), originTime) : undefined;
this.actualArrival = stopData['actual_ta'] ? this.dateFromTime(this.toTime(stopData['actual_ta'], date), originTime) : undefined;
this.disruptionCode = stopData['late_canc_reason'] ? +stopData['late_canc_reason'] : undefined;
}
private dateFromTime(time: TimeOnly, originTime: TimeOnly): moment.Moment {
if (time) {
// Handle times that occur other side of midnight
if (time.diff(originTime) < 0) {
time.add(1, 'days');
}
}
return time;
}
}
export class JourneyDetails extends HspApiData {
private attributeDetails: any;
/**
* @brief Date of the scheduled departure of the journey from the
* @TODO origin/from station?
*
*/
public date: DateOnly;
public tocCode: String;
public serviceId: number;
public stops: List<StopDetails>;
constructor(journeyData: any, resourceService: ResourceService) {
super();
// Populate class from json data
const attributeDetails = journeyData['serviceAttributesDetails'];
this.date = this.toDate(attributeDetails['date_of_service']);
this.tocCode = attributeDetails['toc_code'];
this.serviceId = +attributeDetails['rid'];
// Get the first stop
const originTime = this.toTime(
attributeDetails['locations'][0]['gbtt_ptd'],
this.date);
// Map the JSON of stop details into a list of objects
this.stops = new List<StopDetails>(
attributeDetails['locations'].map((locationData: any) => new StopDetails(
locationData,
this.date,
originTime,
resourceService)
)
);
}
}
|
a1e321b5c062e722cb68c01aabc11b5a54856365
|
TypeScript
|
42BV/jarb-final-form
|
/tests/utils.test.ts
| 2.671875
| 3
|
import {
mostSpecificInputTypeFor,
getFieldConstraintsFor,
isRequired,
hasFractionLength,
hasMaximumLength,
hasMinimumLength,
hasRadix,
hasPattern,
hasMin,
hasMax,
getFieldConstraints
} from '../src/utils';
import { Constraints } from '../src/models';
import { setConstraints } from '../src';
test('mostSpecificInputTypeFor', () => {
expect(mostSpecificInputTypeFor(undefined)).toBe('text');
expect(mostSpecificInputTypeFor(null)).toBe('text');
expect(mostSpecificInputTypeFor([])).toBe('text');
expect(
mostSpecificInputTypeFor([
'color',
'datetime-local',
'datetime',
'month',
'week',
'date',
'time',
'email',
'tel',
'number',
'url',
'password',
'file',
'image',
'text'
])
).toBe('color');
expect(
mostSpecificInputTypeFor([
'text',
'image',
'file',
'password',
'url',
'number',
'tel',
'email',
'time',
'date',
'week',
'month',
'datetime',
'datetime-local',
'color'
])
).toBe('color');
expect(mostSpecificInputTypeFor(['color', 'text'])).toBe('color');
});
const constraints: Constraints = {
SuperHero: {
name: {
javaType: 'java.lang.String',
types: ['text'],
required: true,
minimumLength: 4,
maximumLength: 50,
fractionLength: null,
radix: null,
pattern: null,
min: null,
max: null,
name: 'name'
},
email: {
javaType: 'java.lang.String',
types: ['email', 'text'],
required: true,
minimumLength: null,
maximumLength: 255,
fractionLength: null,
radix: null,
pattern: '/^.+@.+..+$/',
min: null,
max: null,
name: 'email'
},
'address.city': {
javaType: 'java.lang.String',
types: ['text'],
required: false,
minimumLength: null,
maximumLength: null,
fractionLength: 1337,
radix: null,
pattern: null,
min: null,
max: null,
name: 'address.city'
},
test: {
javaType: 'java.lang.Long',
types: ['number'],
required: false,
minimumLength: null,
maximumLength: null,
fractionLength: null,
radix: 20,
pattern: null,
min: 1,
max: 50,
name: 'test'
}
}
};
test('getFieldConstraintsFor', () => {
expect(getFieldConstraintsFor('Villain.email', constraints)).toBe(false);
expect(getFieldConstraintsFor('SuperHero.secrectIdentity', constraints)).toBe(
false
);
expect(getFieldConstraintsFor('SuperHero.email', constraints)).toEqual({
javaType: 'java.lang.String',
types: ['email', 'text'],
required: true,
minimumLength: null,
maximumLength: 255,
fractionLength: null,
radix: null,
pattern: '/^.+@.+..+$/',
min: null,
max: null,
name: 'email'
});
expect(getFieldConstraintsFor('SuperHero.address.city', constraints)).toEqual(
{
javaType: 'java.lang.String',
types: ['text'],
required: false,
minimumLength: null,
maximumLength: null,
fractionLength: 1337,
radix: null,
pattern: null,
min: null,
max: null,
name: 'address.city'
}
);
});
test('getFieldConstraints', () => {
setConstraints(undefined);
expect(getFieldConstraints('SuperHero.email')).toBe(false);
expect(getFieldConstraints('SuperHero.secrectIdentity')).toBe(false);
setConstraints(constraints);
expect(getFieldConstraints('SuperHero.email')).toEqual({
javaType: 'java.lang.String',
types: ['email', 'text'],
required: true,
minimumLength: null,
maximumLength: 255,
fractionLength: null,
radix: null,
pattern: '/^.+@.+..+$/',
min: null,
max: null,
name: 'email'
});
expect(getFieldConstraints('SuperHero.secrectIdentity')).toBe(false);
});
test('isRequired', () => {
setConstraints(constraints);
expect(isRequired('SuperHero.email')).toBe(true);
expect(isRequired('SuperHero.secrectIdentity')).toBe(false);
expect(isRequired('SuperHero.address.city')).toBe(false);
});
test('hasMinimumLength', () => {
setConstraints(constraints);
expect(hasMinimumLength('SuperHero.email')).toBe(false);
expect(hasMinimumLength('SuperHero.secrectIdentity')).toBe(false);
expect(hasMinimumLength('SuperHero.name')).toBe(true);
});
test('hasMaximumLength', () => {
setConstraints(constraints);
expect(hasMaximumLength('SuperHero.email')).toBe(true);
expect(hasMaximumLength('SuperHero.secrectIdentity')).toBe(false);
expect(hasMaximumLength('SuperHero.address.city')).toBe(false);
});
test('hasFractionLength', () => {
setConstraints(constraints);
expect(hasFractionLength('SuperHero.email')).toBe(false);
expect(hasFractionLength('SuperHero.secrectIdentity')).toBe(false);
expect(hasFractionLength('SuperHero.address.city')).toBe(true);
});
test('hasRadix', () => {
setConstraints(constraints);
expect(hasRadix('SuperHero.email')).toBe(false);
expect(hasRadix('SuperHero.secrectIdentity')).toBe(false);
expect(hasRadix('SuperHero.test')).toBe(true);
});
test('hasPattern', () => {
setConstraints(constraints);
expect(hasPattern('SuperHero.email')).toBe(true);
expect(hasPattern('SuperHero.secrectIdentity')).toBe(false);
expect(hasPattern('SuperHero.test')).toBe(false);
});
test('hasMin', () => {
setConstraints(constraints);
expect(hasMin('SuperHero.email')).toBe(false);
expect(hasMin('SuperHero.secrectIdentity')).toBe(false);
expect(hasMin('SuperHero.test')).toBe(true);
});
test('hasMax', () => {
setConstraints(constraints);
expect(hasMax('SuperHero.email')).toBe(false);
expect(hasMax('SuperHero.secrectIdentity')).toBe(false);
expect(hasMax('SuperHero.test')).toBe(true);
});
|
f4e1222bdf946c3cc3741bd6911a2ee32e67a06f
|
TypeScript
|
superdev0505/angular-billy
|
/src/features/directives/range-validator.directive.spec.ts
| 2.515625
| 3
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import createTestComponent from '@test/create-test-component';
import RangeValidatorDirective from './range-validator.directive';
@Component({
selector: 'test-cmp',
template: ''
})
class TestComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
number: new FormControl(10)
});
}
}
describe('RangeValidatorDirective', () => {
let comp: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [RangeValidatorDirective, TestComponent]
});
const template = `
<form [formGroup]="form">
<input type="text" [formControlName]="'number'" [validateRange]="'0-100'" />
</form>
`;
fixture = createTestComponent(template, TestComponent);
comp = fixture.componentInstance;
});
it('should validate the FormControl value on init', () => {
expect(comp.form.controls['number'].valid).toBe(true);
expect(comp.form.valid).toBe(true);
});
it('should validate the FormControl value on change', () => {
comp.form.controls['number'].setValue('20');
fixture.detectChanges();
expect(comp.form.controls['number'].valid).toBe(true);
expect(comp.form.valid).toBe(true);
});
it('should invalidate the FormControl value on change', () => {
comp.form.controls['number'].setValue('101');
fixture.detectChanges();
expect(comp.form.controls['number'].valid).toBe(false);
expect(comp.form.valid).toBe(false);
});
});
|
f1999dff3fbc387d16c2739e641a94c1c1cae873
|
TypeScript
|
MusixNotMusic/drawMind
|
/src/constants/utils.ts
| 3.390625
| 3
|
/**
* 下划线转换驼峰
* stroke-line --> strokeLine
*/
export function lineToCamel(name: string) {
return name.replace(/\-(\w)/g, function(all, letter){
return letter.toUpperCase();
});
}
/**
* 驼峰转换下划线
* strokeLine --> stroke-line
*/
export function camel2Line(name: string) {
return name.replace(/([A-Z])/g,"-$1").toLowerCase();
}
/**
*
*/
export function obj2PropsStr(obj: Object) {
return Object.entries(obj).reduce((cur: string, next: any) => {
next[0] = camel2Line(next[0])
return cur + `${next.join('=')} `},
' ')
}
|
e80c48f608a2a26b79705b1395164169b574ba38
|
TypeScript
|
bliny/fe-demo
|
/src/app/base-module/components/multiple-select-with-autocomplete/multiple-select-with-autocomplete.pipe.ts
| 2.625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import {PatrolAction} from "../../services/patrol-action.service";
@Pipe({ name: 'autoCompleteNamePipe'})
export class AutoCompleteNamePipe implements PipeTransform {
transform(arrayWithNames: Array<any>, nameAutoComplete: string): Array<PatrolAction> {
if (!arrayWithNames || !nameAutoComplete) {
return arrayWithNames;
}
return arrayWithNames.filter( action => {
if(action.name) {
return action.name.toLocaleLowerCase().includes(nameAutoComplete.toLocaleLowerCase())
}else{
return action.toLocaleLowerCase().includes(nameAutoComplete.toLocaleLowerCase())
}
});
}
}
|
31fc1113eaedbdf1a4fa6ddbf146e2cf81ee1512
|
TypeScript
|
LucaScorpion/advent-of-code
|
/2021/day_8/solution.ts
| 3.296875
| 3
|
import fs from 'fs';
const input = fs.readFileSync(0).toString().trim().split('\n');
const segmentLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
interface Entry {
patterns: string[];
value: string[];
}
function alphabetize(value: string): string {
return value.split('').sort().join('');
}
const entries: Entry[] = input.map((l) => {
const [rawPatterns, rawValue] = l.split(' | ');
const patterns = rawPatterns.split(' ').map(alphabetize);
const value = rawValue.split(' ').map(alphabetize);
return { patterns, value };
});
// Length of pattern string to number value.
const simpleValueMappings: Record<number, number> = {
2: 1,
3: 7,
4: 4,
7: 8,
};
let simpleValueCount = entries
.flatMap((e) => e.value)
.map((v) => v.length)
.filter((l) => simpleValueMappings[l] != null)
.length;
console.log(`Found ${simpleValueCount} simple values.`);
const numberSegments: string[][] = [
['a', 'b', 'c', 'e', 'f', 'g'],
['c', 'f'],
['a', 'c', 'd', 'e', 'g'],
['a', 'c', 'd', 'f', 'g'],
['b', 'c', 'd', 'f'],
['a', 'b', 'd', 'f', 'g'],
['a', 'b', 'd', 'e', 'f', 'g'],
['a', 'c', 'f'],
['a', 'b', 'c', 'd', 'e', 'f', 'g'],
['a', 'b', 'c', 'd', 'f', 'g'],
];
function getNumberMapping(oldNumberMapping: Record<string, number[]>, segmentMapping: Record<string, string>): Record<string, number[]> {
return Object.fromEntries(
Object.entries(oldNumberMapping)
.map(([pattern, options]) => {
const newOptions = options.filter((o) => {
const realSegments = numberSegments[o];
return pattern
.split('')
.map((l) => segmentMapping[l]) // Map the segment.
.filter(l => !!l) // Filter out unmapped segments.
.every((l) => realSegments.includes(l)); // Check if the segment works.
});
return [pattern, newOptions];
}),
);
}
function search(numberMapping: Record<string, number[]>, segmentMapping: Record<string, string>): Record<string, number> | undefined {
// Check if every segment is mapped.
if (Object.entries(segmentMapping).length === segmentLetters.length) {
return Object.fromEntries(
Object.entries(numberMapping).map(([p, o]) => [p, o[0]]),
);
}
// Try to map all segments.
for (const sFrom of segmentLetters) {
// Check if we already mapped from this segment.
if (segmentMapping[sFrom]) {
continue;
}
for (const sTo of segmentLetters) {
// Check if we already mapped to this segment.
if (Object.values(segmentMapping).includes(sTo)) {
continue;
}
// Add the segment mapping.
const newSegmentMapping = {
...segmentMapping,
[sFrom]: sTo,
};
// Update the possible number mappings.
const newNumberMapping = getNumberMapping(numberMapping, newSegmentMapping);
// Check if there are any number mappings without value.
if (Object.values(newNumberMapping).find((v) => v.length === 0)) {
continue;
}
// Check the next level.
const next = search(newNumberMapping, newSegmentMapping);
if (next) {
return next;
}
}
}
}
let outputSum = 0;
entries.forEach((entry) => {
const initNumberMapping: Record<string, number[]> = {};
// Initialize with all options.
entry.patterns.forEach((p) => {
numberSegments.forEach((s, i) => {
if (s.length === p.length) {
const opts = initNumberMapping[p] || [];
opts.push(i);
initNumberMapping[p] = opts;
}
});
});
const numberMapping = search(initNumberMapping, {});
if (!numberMapping) {
throw new Error('Could not find mapping!');
}
const outputString = entry.value.map((v) => numberMapping[v]).join('');
outputSum += parseInt(outputString, 10);
});
console.log(`Sum of outputs: ${outputSum}`);
|
06301462e729e770597d6783797524eb5d10f887
|
TypeScript
|
kant/varnish
|
/theme/spacing.ts
| 2.9375
| 3
|
import { convertPixelsToRem, convertRemToPx } from '../utils/base';
export class Spacing {
constructor(public displayName: string, public px: string, public rem: string) {}
static fromPixels(displayName: string, px: number) {
return new Spacing(displayName, `${px}px`, convertPixelsToRem(px));
}
static fromRems(displayName: string, rem: number) {
return new Spacing(displayName, convertRemToPx(rem), `${rem}rem`);
}
toString() {
return this.rem;
}
getRemValue() {
return parseFloat(this.rem);
}
getPxValue() {
return parseFloat(this.px);
}
}
export const spacing = {
xxs: Spacing.fromPixels('xxs', 4),
xs: Spacing.fromPixels('xs', 8),
sm: Spacing.fromPixels('sm', 12),
md: Spacing.fromPixels('md', 16),
lg: Spacing.fromPixels('lg', 24),
xl: Spacing.fromPixels('xl', 36),
xxl: Spacing.fromPixels('xxl', 48),
xxxl: Spacing.fromPixels('xxxl', 64)
};
|
f2c122a96ea60c8a9afe97bd37b2dc10986a896a
|
TypeScript
|
wmattei/thoughts-infra
|
/wolke/di/injector.ts
| 2.65625
| 3
|
const Injector = {
register: function (name: string, obj: {}) {
const t = {} as any;
t[name] = obj;
Object.assign(this, t);
},
getRegistered: function (key: string): any {
const that: any = this;
return that[key];
},
};
export default Injector;
|
f66d99888a2f96e0cebfeed4ff89f8c8fab8cb42
|
TypeScript
|
kingdom0608/H6-server
|
/resources/posts.resource.ts
| 2.875
| 3
|
export class PostsResource {
private userIndex;
private postsCategoryIndex;
private title;
private content;
constructor(postsData) {
this.setUserIndex(postsData.userIndex);
this.setPostsCategoryIndex(postsData.postsCategoryIndex);
this.setTitle(postsData.title);
this.setContent(postsData.content);
}
getUserIndex() {
return this.userIndex;
}
setUserIndex(userIndex) {
this.userIndex = userIndex;
}
getPostsCategoryIndex() {
return this.postsCategoryIndex;
}
setPostsCategoryIndex(postsCategoryIndex) {
this.postsCategoryIndex = postsCategoryIndex;
}
getTitle() {
return this.title;
}
setTitle(title) {
this.title = title;
}
getContent() {
return this.content;
}
setContent(content) {
this.content = content;
}
getPosts() {
let postsData: object = {
userIndex: this.getUserIndex(),
postsCategoryIndex: this.getPostsCategoryIndex(),
title: this.getTitle(),
content: this.getContent()
};
return postsData;
}
}
|
b0560114b242f31218321bdbd8a737de6a54c92f
|
TypeScript
|
parthraghav/United-Poll
|
/functions/src/Requests/User.ts
| 2.609375
| 3
|
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as firebaseHelper from 'firebase-functions-helper';
import * as express from 'express';
import * as bodyParser from "body-parser";
const db = admin.firestore();
const app = express();
const main = express();
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
main.use('/api/v1', app);
const collection = 'User';
export const webApi = functions.https.onRequest(main);
interface Usr {
id: String;
name: String;
location: String;
starredElections: Array<String>;
auth_token: String;
}
// Add new Usr
app.post('/User', async (req, res) => {
try {
const Usr: Usr = {
id: req.body['id'],
name: req.body['name'],
location: req.body['location'],
starredElections: req.body['starredElections'],
auth_token: req.body['auth_token'],
}
const newDoc = await firebaseHelper.firestore
.createNewDocument(db, collection, Usr);
res.status(201).send(`Created a new User: ${newDoc.id}`);
} catch (error) {
res.status(400).send(`Make sure data model is correct!`)
}
})
// Update new Usr
app.patch('/User/:documentId', async (req, res) => {
const updatedDoc = await firebaseHelper.firestore
.updateDocument(db, collection, req.params.documentId, req.body);
res.status(204).send(`Update a new Usr: ${updatedDoc}`);
})
// View a Usr
app.get('/User/:documentId', (req, res) => {
firebaseHelper.firestore
.getDocument(db, collection, req.params.documentId)
.then(Usr => res.status(200).send(Usr))
.catch(error => res.status(400).send(`Cannot get User: ${error}`));
})
// View all User
app.get('/User', (req, res) => {
firebaseHelper.firestore
.backup(db, collection)
.then(data => res.status(200).send(data))
.catch(error => res.status(400).send(`Cannot get User: ${error}`));
})
// Delete a Usr
app.delete('/User/:documentId', async (req, res) => {
const deletedDocument = await firebaseHelper.firestore
.deleteDocument(db, collection, req.params.documentId);
res.status(204).send(`User is deleted: ${deletedDocument}`);
})
export { app };
|
87074caf2d920e8c70070533d20a735fdbded462
|
TypeScript
|
workgames/otus-react-lessons
|
/scripts/calc/RPNTransform.ts
| 2.984375
| 3
|
import {
mathematicalFormulasFunc,
mathOperatorsIds,
mathOperatorsPriorities,
scalarFunc,
trigonomenticFunc,
} from './operators';
/**
* Класс перевода infix в postfix
*/
class RPNTransform {
/**
*
* @param val
* @returns
*/
isValid(val: string): boolean {
return !isNaN(parseFloat(val)) || this.isOperator(val);
}
/**
*
* @param operator
* @returns
*/
private leftAssoc(operator: string): boolean {
return operator !== '^';
}
/**
*
* @param operator
* @returns
*/
private priority(operator: string): number {
return mathOperatorsPriorities[operator] || 0;
}
/**
*
* @param operator
* @returns
*/
private isOperator(operator: string): boolean {
return !!mathOperatorsPriorities[operator];
}
/**
*
* @param expr
* @returns
*/
isPostfix(expr: string): boolean {
const patt = new RegExp('[(]');
if (patt.test(expr)) {
return false;
}
const arr = expr.split(' ');
if (isNaN(parseFloat(arr[0])) && !mathOperatorsPriorities[arr[0]]) {
return false;
}
if (
!isNaN(parseFloat(arr[0])) &&
(trigonomenticFunc[arr[1]] || mathematicalFormulasFunc[arr[1]])
) {
return true;
}
if (!isNaN(parseFloat(arr[0])) && scalarFunc[arr[1]]) {
return false;
}
if (trigonomenticFunc[arr[0]] || mathematicalFormulasFunc[arr[0]]) {
return false;
}
return true;
}
/**
*
* @param expr
* @returns
*/
toPostfix(expr: string): string {
let i = 0;
const nextToken = (): string => {
while (i < expr.length && expr[i] == ' ') {
i++;
}
if (i == expr.length) {
return '';
}
let b = '';
while (
i < expr.length &&
expr[i] != ' ' &&
expr[i] != '(' &&
expr[i] != ')' &&
!this.isOperator(expr[i])
) {
b += expr[i++];
}
if (b != '') {
return b;
}
return expr[i++];
};
const S: Array<string> = [];
const O: Array<string | undefined> = [];
let tok: string;
let prevTok = '';
while ((tok = nextToken()) != '') {
if (this.isOperator(tok) && this.isOperator(prevTok)) {
if (mathOperatorsIds[tok] === mathOperatorsIds[prevTok]) {
throw new Error('Ввели несколько операторов подряд');
}
}
prevTok = tok;
if (tok == '(') {
S.push(tok);
} else if (tok == ')') {
while (S.length > 0 && S[S.length - 1] != '(') {
O.push(S.pop());
}
if (S.length == 0) {
throw new Error('Несоответствующие скобки или оператор');
}
S.pop();
} else if (this.isOperator(tok)) {
while (
S.length > 0 &&
this.isOperator(S[S.length - 1]) &&
((this.leftAssoc(tok) && this.priority(tok) <= this.priority(S[S.length - 1])) ||
(!this.leftAssoc(tok) && this.priority(tok) < this.priority(S[S.length - 1])))
) {
O.push(S.pop());
}
S.push(tok);
} else {
O.push(tok);
}
}
while (S.length > 0) {
if (!this.isOperator(S[S.length - 1])) {
throw new Error('Несоответствующие скобки или оператор');
}
O.push(S.pop());
}
if (O.length == 0) {
throw new Error('Ошибка ввода');
}
let s = '';
for (let i = 0; i < O.length; i++) {
if (!this.isValid(O[i] as string)) {
throw new Error('Несоответствующие скобки или оператор');
}
if (i != 0) s += ' ';
s += O[i];
}
return s;
}
}
export const rpnTransform = new RPNTransform();
|
098bad7e8d1fcb8c1366cef93eacd30e8db4eaaa
|
TypeScript
|
Geass1000/argen
|
/src/@core/di/entity.di.ts
| 2.734375
| 3
|
import * as _ from 'lodash';
import * as Interfaces from '../interfaces';
import * as Consts from '../consts';
import * as Errors from '../errors';
export class Entity {
public readonly className: string = 'DI:Entity';
private reflect: typeof Reflect;
/**
* `active` status flag.
*
* @type {Map<string,Interfaces.DI.Injector>}
*/
private fromEntity: boolean;
/**
* List of injectors.
*
* @type {Map<string,Interfaces.DI.Injector>}
*/
private injectors: Map<string, Interfaces.DI.Injector>;
/**
* Entity options.
*
* @type {Interfaces.DI.EntityOptions}
*/
public options: Interfaces.DI.EntityOptions;
constructor (private target: any) {
this.reflect = Reflect;
this.fromEntity = false;
this.options = _.cloneDeep(Consts.DI.defEntityOptions);
this.injectors = new Map();
}
/**
* Returns the params for the instance of the DI Entity.
*
* @return {type}
*/
public getInstanceParams (): any {
if (!this.fromEntity) {
throw new Errors.DIError(`${this.className} - get: Entity is not registred!`);
}
const injectors = Array.from(this.injectors.values());
const constructorInjectors = _.filter(injectors, (injector) => {
return _.isUndefined(injector.propertyName) && _.isNumber(injector.index);
});
const listOfInstanceParams = this.getMethodParams('constructor', constructorInjectors);
// TODO: Maybe unused.
_.map(listOfInstanceParams, (param, index) => {
if (param.injector) {
return;
}
if (this.isNativeType(param.value)) {
throw new Errors.DIError(`${this.className} - get: Param ${index} has \`native\` type!`);
}
});
return listOfInstanceParams;
}
/**
* Returns the params of the specific method of the DI Entity.
*
* @param {string} methodName - name of the method of the DI Entity
* @param {Interfaces.DI.Injector[]} injectors - list of the param injectors
* @return {Interfaces.DI.MethodParam[]}
*/
public getMethodParams (methodName: string, injectors: Interfaces.DI.Injector[]): Interfaces.DI.MethodParam[] {
const reflectMethodName = methodName === 'constructor' ? undefined : methodName;
const reflectListOfParams: any[] = this.reflect
.getMetadata('design:paramtypes', this.target, reflectMethodName);
if (_.isNil(reflectListOfParams)) {
throw new Errors.DIError(`${this.className} - get: Entity method is not registred!`);
}
const listOfMethodParams: Interfaces.DI.MethodParam[] = _.map(reflectListOfParams, (param) => ({
injector: false,
value: param,
}));
const numOfMethodParams = listOfMethodParams.length;
_.map(injectors, (injector) => {
if (numOfMethodParams <= injector.index) {
throw new Errors.DIError(`${this.className} - get: Param ${injector.index} is not exist!`);
}
listOfMethodParams[injector.index] = {
injector: true,
value: injector,
};
});
return listOfMethodParams;
}
/**
* Activate the DI Entity. DI Entity will have to be activated if the
* target has `Service` decorator.
*
* @param {Interfaces.DI.EntityOptions} options
* @return {void}
*/
public acitvate (options: Interfaces.DI.EntityOptions): void {
this.options = options;
this.fromEntity = true;
}
/**
* Return `active` status of the DI Entity.
*
* @return {boolean} - `active` status
*/
public isActivated (): boolean {
return this.fromEntity;
}
/**
* Adds the injector to the DI Entity.
*
* @return {boolean} - `active` status
*/
public addInjector (injector: Interfaces.DI.Injector) {
const injectorKey: string = this.getInjectorKey(injector);
if (this.injectors.has(injectorKey)) {
throw new Errors.DIError(`${this.className} - addInjector: Injector already exist!`);
}
this.injectors.set(injectorKey, injector);
}
/**
* HELPERs
*/
/**
* Calculates and returns the injector key.
*
* @param {Interfaces.DI.Injector} injector - injector entity
* @return {string} - injector key
*/
private getInjectorKey (injector: Interfaces.DI.Injector): string {
return `${injector.propertyName}:${injector.index}`;
}
/**
* Checks the metatype. If metatype is a `native` type method will return `true'.
*
* @return {boolean}
*/
private isNativeType (metatype: any): boolean {
const types: any[] = [ String, Boolean, Number, Object ];
const metatypeName: string = _.get(metatype, 'name', '');
return _.includes(types, (type) => metatypeName === type.name);
}
}
|
cdc92977f450da636010dd045fe49e7db068e4a0
|
TypeScript
|
JirkaDellOro/SofDesSS2020
|
/L02_Zufallsgedicht_Kommilitone/main.ts
| 2.921875
| 3
|
let subjects: string[] = ["Hermine", "Ron", "Dumbledore", "Hagrid", "McGonnegal", "Snape"];
let objects: string[] = [" zaubert ", " bekämpft ", " liebt ", " zerstört ", " hasst ", " braut "];
let verbs: string[] = ["Voldemort", "Flittwick", "Sprout", "Malfoy", "Bellatrix", "Zaubertränke"];
let poem: string[] = Array(6);
for (let i: number = 0; i < 6; i++) {
poem.push(getVerse(subjects, objects, verbs));
}
console.log(poem);
function getVerse(subjects: string[], objects: string[], verbs: string[]): string {
let soon_Verse: string[] = Array(3);
let randomSubjectInd: number = (Math.floor(Math.random() * subjects.length));
let randomObjectInd: number = (Math.floor(Math.random() * subjects.length));
let randomVerbInd: number = (Math.floor(Math.random() * subjects.length));
soon_Verse.push(subjects[randomSubjectInd]);
soon_Verse.push(objects[randomVerbInd]);
soon_Verse.push(verbs[randomObjectInd]);
let verse: string = soon_Verse.join(" ");
return verse;
}
|
fb2687f844c2f214cd4d6993f3859804cbc82be7
|
TypeScript
|
cancerberoSgx/magica
|
/apps/node-gtk-tests/src/gobjectTypes.ts
| 2.90625
| 3
|
// /**
// * Using public APIs example:
// *
// ```js
// import { equal } from 'assert';
// const nodegtk = require('node-gtk');
// const Gtk = nodegtk.require('Gtk')
// const GObject = nodegtk.require('GObject')
// nodegtk.startLoop();
// Gtk.init()
// const win = new Gtk.Window()
// equal(GObject.typeName(win.__gtype__), "GtkWindow")
// ```
// */
// export namespace nodeGtk {
// /**
// * Heads up ! everything inside [_GIRepository] namespace is consider internal APIs and might not be supported in the future.
// *
// * Also notice that functions starting with upper-case need to be manually bind to [this] context instead of calling them directly. The following example funciton will fetch all types from given library like `Gtk` and version like `3.0`. Notice that some types could reference names in other libraries like `Gdk`:
// ````
// import from 'node-gtk'
// gi.startLoop();
// function parseNamespace(ns:string, ver:string) {
// currentParsedNamespaceDependencies.length=0
// const namespace = Object.create(null);
// const repo = GI.Repository_get_default();
// if (!gi._isLoaded(ns, ver))
// GI.Repository_require.call(repo, ns, ver, 0);
// const nInfos = GI.Repository_get_n_infos.call(repo, ns);
// for (let i = 0;i < nInfos;i++) {
// const info = GI.Repository_get_info.call(repo, ns, i);
// const baseinfo = getInfo(info);
// const basename = name(info);
// namespace[basename] = baseinfo;
// }
// return {namespace, dependencies: currentParsedNamespaceDependencies}
// // return Object.values(m).map(format);
// }
// ```
// *
// *
// * with theh [GIRepository] instance. i.e: `Repository_get_n_infos.call(Gtk ,)`
// * @internal
// */
// export namespace _GIRepository {
// /**
// * Usage:
// ```js
// if (!nodegtk._isLoaded(ns, ver))
// GI.Repository_require.call(repo, ns, ver, 0);
// ```
// */
// export declare function Repository_require(this: GiRepository, ns: string, ver: string, n: number): void
// /**
// * Usage:
// ```js
// const nInfos = GI.Repository_get_n_infos.call(repo, ns);
// for (let i = 0;i < nInfos;i++) {
// const info = GI.Repository_get_info.call(repo, ns, i);
// ```
// */
// export declare function Repository_get_n_infos(this: GiRepository, ns: string): number
// /**
// * Usage:
// ```js
// const nInfos = GI.Repository_get_n_infos.call(repo, ns);
// for (let i = 0;i < nInfos;i++) {
// const info = GI.Repository_get_info.call(repo, ns, i);
// ```
// */
// export declare function Repository_get_info(this: GiRepository, ns: string, index: number): GiInfo | undefined
// /**
// * Usage:
// ```js
// GI.Repository_require.call(repo, ns);
// ```
// */
// export declare function Repository_get_info(this: GiRepository, ns: string): void
// export declare function Repository_get_version(this: GiRepository, ns: string): string
// export declare function BaseInfo_get_name(this: GiInfo): string | undefined
// export declare function BaseInfo_get_namespace(this: GiInfo): string | undefined
// export declare function BaseInfo_get_type(this: GiInfo): BaseInfoType | undefined
// export declare function info_type_to_string(infotype: BaseInfoType): string | undefined
// export declare function type_info_get_tag(i: GiInfo): BaseInfoTag | undefined
// export declare function type_tag_to_string(t: BaseInfoTag): string | undefined
// }
// export type BaseInfoType = number
// export type BaseInfoTag = number
// export declare function require(ns: string, ver: string): GiRepository
// export declare function startLoop(): void
// export declare enum GIArrayType {
// GI_ARRAY_TYPE_C,
// GI_ARRAY_TYPE_ARRAY,
// GI_ARRAY_TYPE_PTR_ARRAY,
// GI_ARRAY_TYPE_BYTE_ARRAY
// }
// //TODO:
// // object_info_get_parent
// // struct_info_get_method
// // object_info_get_n_interfaces
// // object_info_get_n_properties
// // object_info_get_n_constants
// // function _isLoaded(ns: string, ver: string): boolean
// // function Repository_get_default(): Repository
// // BaseInfo_get_name
// // }
// // const name = (info) => GI.BaseInfo_get_name.call(info);
// // const namespace = (info) => GI.BaseInfo_get_namespace.call(info);
// // const getInfoType = (info) => GI.BaseInfo_get_type.call(info);
// // const type_string = (infotype) => GI.info_type_to_string(infotype);
// // const tag = (type_info) => GI.type_info_get_tag(type_info);
// // const tag_string = (type_tag) => GI.type_tag_to_string(type_tag);
// // const isDeprecated = (info) => GI.BaseInfo_is_deprecated.call(info)
// // gtk
// // const repo = GI.Repository_get_default();
// // if (!nodegtk._isLoaded(ns, ver))
// // GI.Repository_require.call(repo, ns, ver, 0);
// // const nInfos = GI.Repository_get_n_infos.call(repo, ns);
// // for (let i = 0;i < nInfos;i++) {
// // const info = GI.Repository_get_info.call(repo, ns, i);
// // exports.require = giRequire
// // exports.startLoop = internal.StartLoop
// // exports.prependSearchPath = prependSearchPath
// // exports.prependLibraryPath = prependLibraryPath
// // exports.System = internal.System
// }
// export interface GiRepository {
// }
// export interface GiInfo {
// parent: GiInfo|string
// name: GiInfo|string
// infoType: 'function'|'interface'|'object'
// }
|
92b6f67bf6b118288055c44ac2ebca407cb392f8
|
TypeScript
|
thibautRe/othrworld
|
/packages/app/src/hooks/useEscKeyHandler.ts
| 3.1875
| 3
|
import React from 'react'
// Keep track of all event handlers in a global array
// Implementation note: an event handler to the document for each item does not work
// when using nested items that can be esc-keyed.
const _handlers = [] as Array<() => void>
// Keep track of if the global event listener is mounted or not
let _globalMounted = false
// Global event listener
const escKeyCallHandler = (e: KeyboardEvent) => {
if (_handlers.length === 0) {
return
}
if (e.keyCode === 27) {
_handlers[_handlers.length - 1]()
}
}
// Add a handler in the stack
const addHandler = (handler: () => void) => {
_handlers.push(handler)
}
// Remove a handler from the stack
const removeHandler = (handler: () => void) => {
_handlers.splice(_handlers.indexOf(handler), 1)
}
// Hook to attach a global document escape key event listener
// NOTE: try to memoize as much as possible your handler using `useCallback`
export const useEscKeyHandler = (handler: (() => void) | null) => {
// Add and remove the handler in the stack, if present
React.useEffect(() => {
if (!handler) return
addHandler(handler)
return () => removeHandler(handler)
}, [handler])
// Manage the global document handler
// NOTE - because of the decentralized behaviour, the hooks' returned effect
// can be ran regardless of if it ran the addEventListener itself.
React.useEffect(() => {
if (!_globalMounted && handler) {
document.addEventListener('keydown', escKeyCallHandler)
_globalMounted = true
}
return () => {
if (_handlers.length === 0) {
document.removeEventListener('keydown', escKeyCallHandler)
_globalMounted = false
}
}
}, [handler])
}
|
2e4286b22a65b311ab6649a113c3f801aa6c8f4e
|
TypeScript
|
wuzhenquan/thing
|
/frontend/react-tsx/src/api/index.ts
| 2.5625
| 3
|
// interface RequestInit {
// body?: any;
// cache?: RequestCache;
// credentials?: RequestCredentials;
// headers?: HeadersInit;
// integrity?: string;
// keepalive?: boolean;
// method?: string;
// mode?: RequestMode;
// redirect?: RequestRedirect;
// referrer?: string;
// referrerPolicy?: ReferrerPolicy;
// window?: any;
// }
interface CONFIG {
readonly baseUrl: string;
readonly init: {
credentials: RequestCredentials;
};
}
const config: CONFIG = {
baseUrl: process.env.REACT_APP_API_URL || '',
init: { credentials: 'include' }
}
function get(params: { a: string }) {
return fetch(`${config.baseUrl}/${params.a}`, {
method: 'GET',
...config.init
})
.then(res => res.json())
}
function post(params: { a: string, data?: object }) {
const a = params.a
const data = params.data || {}
return fetch(`${config.baseUrl}/${a}`, {
method: 'POST',
...config.init,
cache: 'no-cache',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify(data)
})
.then(res => res.json())
.catch(error => error)
}
function put(params: { a: string, data?: object }) {
const a = params.a
const data = params.data || {}
return fetch(`${config.baseUrl}/${a}`, {
method: 'PUT',
...config.init,
cache: 'no-cache',
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: JSON.stringify(data)
})
.then(res => res.json())
.catch(error => error)
}
function deleteReq(params: { a: string }) {
const a = params.a
return fetch(`${config.baseUrl}/${a}`, {
method: 'DELETE',
...config.init
})
.then(res => res.json())
.catch(error => error)
}
export function getPublicKey() {
return get({ a: 'publickey' })
}
export function getUserSession() {
return get({ a: 'users/session' })
}
export function getHomePage() {
return get({ a: '' })
}
export function signIn(data: object) {
return post({ a: 'users/signin', data })
}
export function signUp(data: object) {
return post({ a: 'users/signup', data })
}
export function signOut() {
return post({ a: 'users/signout' })
}
export function getTodos() {
return get({ a: 'todos' })
}
export function addTodo(data: object) {
return post({ a: 'todos', data })
}
export function updateTodo(data: object) {
return put({ a: 'todos', data })
}
export function deleteTodo(id: number) {
return deleteReq({ a: `todos/${id}` })
}
|
bff4e8d847468146659ea12035e0a184c5c3a0dc
|
TypeScript
|
kiruba48/SKY_TECHTEST
|
/src/state/reducers/betSlipReducer.ts
| 2.65625
| 3
|
import { ActionType } from '../constants/eventsConstants';
import { BetSlipAction } from '../actions/betSlipInterface';
import { EventOutcomeInterface } from '../actions/outcomeInterfaces';
export const betSlipReducer = (
state: EventOutcomeInterface[] = [],
action: BetSlipAction
) => {
switch (action.type) {
case ActionType.BET_SLIP_ADD_ITEM:
const item = action.payload;
return [...state, item];
case ActionType.BET_SLIP_REMOVE_ITEM:
return state.filter((item) => item.outcomeId !== action.payload);
case ActionType.BET_SLIP_RESET:
return [];
default:
return state;
}
};
|
de71997036a280bc1d43ea35f008289dd2fd8496
|
TypeScript
|
oppia/oppia
|
/core/templates/domain/story/story-summary.model.ts
| 2.515625
| 3
|
// Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Model class for creating instances of frontend
* story summary domain objects.
*/
import {
StoryNode, StoryNodeBackendDict
} from './story-node.model';
export interface StorySummaryBackendDict {
'id': string;
'title': string;
'node_titles': string[];
'thumbnail_filename': string;
'thumbnail_bg_color': string;
'description': string;
'story_is_published': boolean;
'completed_node_titles': string[];
'url_fragment': string;
'all_node_dicts': StoryNodeBackendDict[];
'published_chapters_count'?: number;
'total_chapters_count'?: number;
'upcoming_chapters_count'?: number;
'overdue_chapters_count'?: number;
'upcoming_chapters_expected_days'?: number[];
'visited_chapter_titles'?: string[];
// This property is optional because it is only present in the
// story summary dict of learner dashboard page.
'topic_name'?: string;
'topic_url_fragment'?: string;
'classroom_url_fragment'?: string;
}
export class StorySummary {
constructor(
private _id: string,
private _title: string,
private _nodeTitles: string[],
private _thumbnailFilename: string,
private _thumbnailBgColor: string,
private _description: string,
private _storyIsPublished: boolean,
private _completedNodeTitles: string[],
private _urlFragment: string,
private _allNodes: StoryNode[],
private _topicName: string | undefined,
private _topicUrlFragment: string | undefined,
private _classroomUrlFragment: string | undefined,
private _publishedChaptersCount: number | undefined,
private _totalChaptersCount: number | undefined,
private _upcomingChaptersCount: number | undefined,
private _upcomingChaptersExpectedDays: number[] | undefined,
private _overdueChaptersCount: number | undefined,
private _visitedChapterTitles: string[] | undefined
) {}
getId(): string {
return this._id;
}
getTitle(): string {
return this._title;
}
getNodeTitles(): string[] {
return this._nodeTitles.slice();
}
getThumbnailFilename(): string {
return this._thumbnailFilename;
}
isNodeCompleted(nodeTitle: string): boolean {
return (this._completedNodeTitles.indexOf(nodeTitle) !== -1);
}
getThumbnailBgColor(): string {
return this._thumbnailBgColor;
}
getDescription(): string | undefined {
return this._description;
}
getCompletedNodeTitles(): string[] {
return this._completedNodeTitles;
}
getTopicName(): string | undefined {
return this._topicName;
}
isStoryPublished(): boolean {
return this._storyIsPublished;
}
getUrlFragment(): string {
return this._urlFragment;
}
getAllNodes(): StoryNode[] {
return this._allNodes;
}
getTopicUrlFragment(): string | undefined {
return this._topicUrlFragment;
}
getClassroomUrlFragment(): string | undefined {
return this._classroomUrlFragment;
}
getPublishedChaptersCount(): number | undefined {
return this._publishedChaptersCount;
}
getTotalChaptersCount(): number | undefined {
return this._totalChaptersCount;
}
getUpcomingChaptersCount(): number | undefined {
return this._upcomingChaptersCount;
}
getOverdueChaptersCount(): number | undefined {
return this._overdueChaptersCount;
}
getVisitedChapterTitles(): string[] | undefined {
return this._visitedChapterTitles;
}
getUpcomingChaptersExpectedDays(): number[] | undefined {
return this._upcomingChaptersExpectedDays;
}
static createFromBackendDict(
storySummaryBackendDict: StorySummaryBackendDict): StorySummary {
let allNodes = (
storySummaryBackendDict.all_node_dicts.map(storyNodeDict => {
return StoryNode.createFromBackendDict(
storyNodeDict);
}));
return new StorySummary(
storySummaryBackendDict.id,
storySummaryBackendDict.title,
storySummaryBackendDict.node_titles,
storySummaryBackendDict.thumbnail_filename,
storySummaryBackendDict.thumbnail_bg_color,
storySummaryBackendDict.description,
storySummaryBackendDict.story_is_published,
storySummaryBackendDict.completed_node_titles,
storySummaryBackendDict.url_fragment,
allNodes,
storySummaryBackendDict.topic_name,
storySummaryBackendDict.topic_url_fragment,
storySummaryBackendDict.classroom_url_fragment,
storySummaryBackendDict.published_chapters_count,
storySummaryBackendDict.total_chapters_count,
storySummaryBackendDict.upcoming_chapters_count,
storySummaryBackendDict.upcoming_chapters_expected_days,
storySummaryBackendDict.overdue_chapters_count,
storySummaryBackendDict.visited_chapter_titles
);
}
}
|
03ea28ee7886b254682132ae395570f4f2f89454
|
TypeScript
|
Arkator7/project_euler
|
/src/euler034.ts
| 3.328125
| 3
|
import {factorial} from './generic_library';
export function euler034() {
let result : number = 0;
//409113 = 9! + 8! + ... + 1!
for (let i = 10; i <= 409113; i++) {
result += checkFactSum(i);
}
return result;
}
export function checkFactSum(i: number) : number {
let sumOfFacts : number = 0;
let num : number = i;
while (num >= 1) {
let d : number = num % 10;
num = Math.floor(num / 10);
sumOfFacts += factorial(d);
}
if (sumOfFacts == i) {
return i;
} else {
return 0;
}
}
|
d1ce42485c9e14a5e981b118d7323c62198d4ac8
|
TypeScript
|
AntonellaM/upplication-coding-test-angular
|
/src/app/point-card.ts
| 2.578125
| 3
|
import {PointCardDetail} from './point-card-detail';
export class PointCard {
private _points: number;
private _pointsCard: Array<PointCardDetail>;
get points(): number {
return this._points;
}
set points(value: number) {
this._points = value;
}
get pointsCard(): Array<PointCardDetail> {
return this._pointsCard;
}
set pointsCard(value: Array<PointCardDetail>) {
this._pointsCard = value;
}
}
|
d2c0fd15b5175a124216ed48ac1aace48342b388
|
TypeScript
|
yuritopia-net/graph-view
|
/src/index.ts
| 3
| 3
|
export class GraphView {
root: HTMLElement;
elements: GraphElement[];
constructor(element: HTMLElement) {
this.root = element;
this.elements = [];
}
addSimpleElement(title: string, body: string) {
const elm = GraphElement.createSimpleElement(title, body);
this.elements.push(elm);
this.root.appendChild(elm.root);
}
};
export class GraphElement {
root: HTMLElement;
constructor(element: HTMLElement) {
this.root = element;
}
static createSimpleElement(title: string, body: string) {
const root = document.createElement("div");
const elm_title = document.createElement("div");
const elm_body = document.createElement("div");
root.classList.add("graphview-element");
elm_title.classList.add("graphview-title");
elm_body.classList.add("graphview-body");
elm_title.textContent = title;
elm_body.textContent = body;
root.appendChild(elm_title);
root.appendChild(elm_body);
return new GraphElement(root);
}
};
|
0bf3e914268997d146797483c4e812e003891325
|
TypeScript
|
pmndrs/jotai
|
/src/vanilla/utils/atomFamily.ts
| 3.21875
| 3
|
import type { Atom } from '../../vanilla.ts'
type ShouldRemove<Param> = (createdAt: number, param: Param) => boolean
export interface AtomFamily<Param, AtomType> {
(param: Param): AtomType
remove(param: Param): void
setShouldRemove(shouldRemove: ShouldRemove<Param> | null): void
}
export function atomFamily<Param, AtomType extends Atom<unknown>>(
initializeAtom: (param: Param) => AtomType,
areEqual?: (a: Param, b: Param) => boolean
): AtomFamily<Param, AtomType>
export function atomFamily<Param, AtomType extends Atom<unknown>>(
initializeAtom: (param: Param) => AtomType,
areEqual?: (a: Param, b: Param) => boolean
) {
type CreatedAt = number // in milliseconds
let shouldRemove: ShouldRemove<Param> | null = null
const atoms: Map<Param, [AtomType, CreatedAt]> = new Map()
const createAtom = (param: Param) => {
let item: [AtomType, CreatedAt] | undefined
if (areEqual === undefined) {
item = atoms.get(param)
} else {
// Custom comparator, iterate over all elements
for (const [key, value] of atoms) {
if (areEqual(key, param)) {
item = value
break
}
}
}
if (item !== undefined) {
if (shouldRemove?.(item[1], param)) {
createAtom.remove(param)
} else {
return item[0]
}
}
const newAtom = initializeAtom(param)
atoms.set(param, [newAtom, Date.now()])
return newAtom
}
createAtom.remove = (param: Param) => {
if (areEqual === undefined) {
atoms.delete(param)
} else {
for (const [key] of atoms) {
if (areEqual(key, param)) {
atoms.delete(key)
break
}
}
}
}
createAtom.setShouldRemove = (fn: ShouldRemove<Param> | null) => {
shouldRemove = fn
if (!shouldRemove) return
for (const [key, value] of atoms) {
if (shouldRemove(value[1], key)) {
atoms.delete(key)
}
}
}
return createAtom
}
|
357a4d24396568aded089ef53bfb970cbe7b917d
|
TypeScript
|
green-fox-academy/feketeakos23
|
/week-03/day-03/animal.ts
| 3.5
| 4
|
'use strict';
class Animal {
hunger: number;
thirst: number;
constructor(hunger: number = 50, thirst: number = 50) {
this.hunger = hunger;
this.thirst = thirst;
}
public eat(): number {
return this.hunger = this.hunger - 1;
}
public drink(): number {
return this.thirst = this.thirst - 1;
}
public play(): void {
this.hunger = this.hunger + 1;
this.thirst = this.thirst + 1;
}
}
let dog = new Animal();
dog.eat();
dog.drink();
console.log(dog);
|
aac941b5a73c7b9ff1bc1eb1f931e3eb5a6df520
|
TypeScript
|
jonasoesch/morphingchart
|
/Drawable.ts
| 2.6875
| 3
|
export interface Drawable {
name:string // It's presumed that there is an element in the HTML with an id of name
draw():void
drawScene():void
drawCharacters():void
hide():void
hideCharacters():void
}
|
373a585d8fe621ee7cb5c692109c3749eed7818f
|
TypeScript
|
robt1019/algorithms-etc.-
|
/binary-search.ts
| 4.03125
| 4
|
class TreeNode {
data: number;
left: TreeNode;
right: TreeNode;
constructor(data: number) {
this.data = data;
}
}
function insert(node: TreeNode, data: number) {
if (data <= node.data) {
if (node.left) {
insert(node.left, data);
} else {
node.left = new TreeNode(data);
}
} else {
if (node.right) {
insert(node.right, data);
} else {
node.right = new TreeNode(data);
}
}
}
function inOrderTraversal(node: TreeNode, callBack: (node: TreeNode) => any) {
if (!node) {
return;
}
inOrderTraversal(node.left, callBack);
callBack(node);
inOrderTraversal(node.right, callBack);
}
function preOrderTraversal(node: TreeNode, callBack: (node: TreeNode) => any) {
if (!node) {
return;
}
callBack(node);
inOrderTraversal(node.left, callBack);
inOrderTraversal(node.right, callBack);
}
function postOrderTraversal(node: TreeNode, callBack: (node: TreeNode) => any) {
if (!node) {
return;
}
inOrderTraversal(node.left, callBack);
inOrderTraversal(node.right, callBack);
callBack(node);
}
function makeRandomTree(size: number, maxNumber: number): TreeNode {
const tree = new TreeNode(Math.floor(Math.random() * maxNumber));
for (let i = 0; i < size; i++) {
insert(tree, Math.floor(Math.random() * maxNumber));
}
return tree;
}
function swap(array: number[], left: number, right: number) {
const temp = array[left];
array[left] = array[right];
array[right] = temp;
}
function partition(array: number[], left: number, right: number): number {
const pivot = array[right];
let i = left - 1;
for (let j = left; j < right; j++) {
if (array[j] <= pivot) {
i++;
swap(array, i, j);
}
}
swap(array, i+1, right);
return i + 1;
}
function quickSort(array: number[], left: number, right: number) {
if(left >= right) {
return;
}
const pivotRestPoint = partition(array, left, right);
quickSort(array, left, pivotRestPoint - 1);
quickSort(array, pivotRestPoint + 1, right);
}
function sort(array: any[]) {
quickSort(array, 0, array.length - 1);
}
function makeRandomNumberArray(size: number, maxElementSize: number): number[] {
const array = [];
for (let i = 0; i < size; i++) {
array.push(Math.floor(Math.random() * maxElementSize));
}
return array;
}
function binarySearch(
searchTarget: number,
array: number[],
left: number,
right: number
) {
if (left >= right) {
return `array does not contain ${searchTarget}`;
}
const middle = Math.floor((right + left) / 2);
if (array[middle] === searchTarget) {
return `found ${searchTarget} at element ${left + middle}`;
} else if (searchTarget < array[middle]) {
console.log("first half");
return binarySearch(searchTarget, array, left, middle - 1);
} else {
console.log("second half");
return binarySearch(searchTarget, array, middle + 1, right);
}
}
const testArray = makeRandomNumberArray(100000, 1000);
sort(testArray);
console.log(testArray);
console.log(binarySearch(5, testArray, 0, testArray.length - 1));
const testTree = makeRandomTree(50, 1000);
inOrderTraversal(testTree, node => console.log(node.data));
|
2bfba5577faff6ad0c40614dfcb00054d4c7d611
|
TypeScript
|
huangyuer/tsTest
|
/src/utils/sClickOutside.ts
| 2.671875
| 3
|
const on = (element, event, handler)=> {
if (element && event && handler) {
element.addEventListener(event, handler, false);
}
};
const off = (element, event, handler)=> {
if (element && event && handler) {
element.removeEventListener(event, handler, false);
}
};
let elem: any = null;
let vn: any = null;
let fn: any = null;
on(document, 'mousedown', e => {
if (!elem) {
return;
}
if (elem.contains(e.target)) {
return;
}
if (!vn) {
return;
}
if (vn.context && vn.context.popperElm && vn.context.popperElm.contains(e.target)) {
return;
}
if (vn.child && vn.child.popperElm && vn.child.popperElm.contains(e.target)) {
return;
}
if (fn) {
fn();
}
elem = null;
vn = null;
fn = null;
});
const bindFn = (el, binding, vnode)=> {
let innerFn: any = ()=> {};
if (binding.expression && vnode[binding.expressiontx]) {
innerFn = vnode[binding.expressiontx];
} else if (binding.value) {
innerFn = binding.value;
}
off(el, 'mousedown', el.clickOutsideFn);
el.clickOutsideFn = e => {
elem = el;
vn = vnode;
fn = innerFn;
};
on(el, 'mousedown', el.clickOutsideFn);
};
export default {
bind: bindFn,
update: bindFn,
unbind(el) {
off(el, 'mousedown', el.clickOutsideFn);
}
};
|
99e5892633bdb01e36d7f06b1b2d8a6242efb1de
|
TypeScript
|
dbz-tribute-reforged/dbz-tribute-reforged
|
/src/Core/SagaSystem/Sagas/SagaBuuGroup.ts
| 2.5625
| 3
|
import { AdvancedSaga } from "./AdvancedSaga";
import { Saga } from "./BaseSaga";
import { SagaHelper } from "../SagaHelper";
import { Constants } from "Common/Constants";
export class BabidiSaga extends AdvancedSaga implements Saga {
name: string = '[DBZ] Babidi Saga';
protected dabura: unit | undefined;
protected babidi: unit | undefined;
protected fatBuu: unit | undefined;
constructor() {
super();
this.delay = 60;
}
spawnSagaUnits(): void {
super.spawnSagaUnits();
SagaHelper.showMessagesChanceOfJoke(
[
"Babidi's minions have come to collect energy for the release of Majin Buu!",
],
);
this.addHeroListToSaga(["Pui Pui", "Yakon", "Dabura", "Babidi", "Fat Buu"], true);
for (const boss of this.bosses) {
SetUnitAcquireRange(boss, Constants.sagaMaxAcquisitionRange);
}
this.dabura = this.bosses[2];
this.babidi = this.bosses[3];
this.fatBuu = this.bosses[4];
SagaHelper.sagaHideUnit(this.babidi);
SagaHelper.sagaHideUnit(this.fatBuu);
this.ping();
this.setupBossDeathActions(this);
}
update(t: number): void {
super.update(t);
if (
this.dabura && this.babidi && this.fatBuu &&
SagaHelper.checkUnitHp(this.dabura, 0.1, false, true, false) &&
SagaHelper.isUnitSagaHidden(this.babidi)
) {
SagaHelper.showMessagesChanceOfJoke(
[
"|cffffcc00Babidi|r: Finally, enough energy to release Majin Buu!",
"|cffffcc00Babidi|r: Paparapapa!",
],
);
SagaHelper.sagaShowUnitAtUnit(this.fatBuu, this.dabura);
SagaHelper.genericTransformAndPing(this.babidi, this.dabura, this);
}
}
canStart(): boolean {
return true;
}
canComplete(): boolean {
return super.canComplete();
}
start(): void {
super.start();
this.spawnWhenDelayFinished();
}
spawnWhenDelayFinished(): void {
if (this.delay <= 0) {
this.spawnSagaUnits();
} else {
TimerStart(this.delayTimer, this.delay, false, ()=> {
this.spawnSagaUnits();
DestroyTimer(GetExpiredTimer());
});
}
}
complete(): void {
super.complete();
}
}
export class BuuSaga extends AdvancedSaga implements Saga {
name: string = '[DBZ] Buu Saga';
protected superBuu: unit | undefined;
protected kidBuu: unit | undefined;
protected isKid: boolean;
constructor() {
super();
this.delay = 30;
this.isKid = false;
}
spawnSagaUnits(): void {
super.spawnSagaUnits();
SagaHelper.showMessagesChanceOfJoke(
[
"Evil Buu has absorbed Majin Buu to become Super Buu!",
],
);
this.addHeroListToSaga(["Super Buu", "Kid Buu"], true);
for (const boss of this.bosses) {
SetUnitAcquireRange(boss, Constants.sagaMaxAcquisitionRange);
}
this.superBuu = this.bosses[0];
this.kidBuu = this.bosses[1];
SagaHelper.sagaHideUnit(this.kidBuu);
this.ping();
this.setupBossDeathActions(this);
}
update(t: number): void {
super.update(t);
if (
this.superBuu && this.kidBuu && !this.isKid &&
SagaHelper.checkUnitHp(this.superBuu, 0.1, false, true, false) &&
SagaHelper.isUnitSagaHidden(this.kidBuu)
) {
this.isKid = true;
SagaHelper.showMessagesChanceOfJoke(
[
"Majin Buu has returned to his original form!"
],
);
SagaHelper.genericTransformAndPing(this.kidBuu, this.superBuu, this);
}
}
canStart(): boolean {
return true;
}
canComplete(): boolean {
return super.canComplete();
}
start(): void {
super.start();
this.spawnWhenDelayFinished();
}
spawnWhenDelayFinished(): void {
if (this.delay <= 0) {
this.spawnSagaUnits();
} else {
TimerStart(this.delayTimer, this.delay, false, ()=> {
this.spawnSagaUnits();
DestroyTimer(GetExpiredTimer());
});
}
}
complete(): void {
super.complete();
}
}
export class FutureBabidiSaga extends AdvancedSaga implements Saga {
name: string = '[DB Super] Future Babidi Saga';
protected yakon: unit | undefined;
protected dabura: unit | undefined;
protected babidi: unit | undefined;
constructor() {
super();
this.delay = 30;
}
spawnSagaUnits(): void {
super.spawnSagaUnits();
SagaHelper.showMessagesChanceOfJoke(
[
"Future Babidi is trying to collect enough energy for the release of Future Majin Buu!",
],
);
this.addHeroListToSaga(["Future Pui Pui", "Future Yakon", "Future Dabura", "Future Babidi"], true);
for (const boss of this.bosses) {
SetUnitAcquireRange(boss, 4000);
}
this.yakon = this.bosses[1];
this.dabura = this.bosses[2];
this.babidi = this.bosses[3];
SagaHelper.sagaHideUnit(this.dabura);
SagaHelper.sagaHideUnit(this.babidi);
this.ping();
this.setupBossDeathActions(this);
}
update(t: number): void {
super.update(t);
if (
this.dabura && this.babidi && this.yakon &&
SagaHelper.checkUnitHp(this.yakon, 0.1, false, true, false) &&
SagaHelper.isUnitSagaHidden(this.babidi)
) {
SagaHelper.showMessagesChanceOfJoke(
[
"|cffffcc00Babidi|r: Paparapapa!",
],
[
"|cffffcc00Babidi|r: Dabura, don't just stand there, do soemething!",
],
);
SagaHelper.sagaShowUnitAtUnit(this.babidi, this.yakon);
SagaHelper.genericTransformAndPing(this.dabura, this.yakon, this);
}
}
canStart(): boolean {
return true;
}
canComplete(): boolean {
return super.canComplete();
}
start(): void {
super.start();
this.spawnWhenDelayFinished();
}
spawnWhenDelayFinished(): void {
if (this.delay <= 0) {
this.spawnSagaUnits();
} else {
TimerStart(this.delayTimer, this.delay, false, ()=> {
this.spawnSagaUnits();
DestroyTimer(GetExpiredTimer());
});
}
}
complete(): void {
super.complete();
SagaHelper.showMessagesChanceOfJoke(
[
"|cffffcc00Babidi:|r I'll take you down with me, Supreme Kaioshin!",
],
);
}
}
|
f698f5c93b9c8558d64358bb2aa16bb189497108
|
TypeScript
|
sravyaysk/Type-script-calculator
|
/calc.ts
| 3.375
| 3
|
class Calculate{
calculate(buttonobj,dispobj,current){
var value=buttonobj.value;
if(value=='=')
{
current = eval(current);
}
else if(value=='C')
{
current='0';
}
else{
if(current=='0'){
current=value;
}
else{
current+=value;
}
}
//alert(current);
dispobj.displayResult(current);
return current;
}
}
class Buttons{
create(dispobj,current){
//var buttonThis = this;
var button_values = ['7','8','9','*',
'4','5','6','-',
'1','2','3','+',
'=','0','C','/'];
var calcobj=new Calculate();
var table=document.createElement('table');
var i = 0, j = 0, count = 0;
for(i = 0; i < 4; i++)
{
count = 0;
var tr = document.createElement('tr');
while(count < 4)
{
count++;
var td = document.createElement('td');
var button = document.createElement('input');
button.type = 'button';
button.value = button_values[j];
button.addEventListener("click",function(){
current=calcobj.calculate(this,dispobj,current)});
td.appendChild(button);
tr.appendChild(td);
j++;
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
}
class TextField {
text_field : any;
constructor() {
var text = document.createElement('input');
text.type="text";
text.id="textfield";
text.value = "0";
this.text_field=text;
document.body.appendChild(text);
}
displayResult(val:string) {
//alert(val);
this.text_field.value = val;
}
}
class Calculator {
constructor(){
var current='0';
var displayobj = new TextField();
var btnobj = new Buttons();
btnobj.create(displayobj,current);
}
}
new Calculator();
new Calculator();
|
f290a96b44f6de74ad95269fae7cc5506143a311
|
TypeScript
|
sergeysova/sova.dev
|
/src/data/forem.ts
| 2.546875
| 3
|
import * as t from 'runtypes';
import {cachedFetch} from './server-request';
const foremServices = {
'dev.to': {
url: 'https://dev.to',
apiKey: import.meta.env.DEVTO_API_KEY,
},
'community.effector': {
url: 'https://community.effector.dev',
apiKey: import.meta.env.EFFECTOR_COMMUNITY_API_KEY,
},
};
export function getUniqueArticles(): Promise<Article[]> {
const uniqueNamesArticlesMap = new Map<string, Article>();
return Promise.all([getArticlesOf('dev.to'), getArticlesOf('community.effector')])
.catch((error) => {
console.error('failed to get articles', error);
throw error;
})
.then(([dev, effector]) => [...effector, ...dev])
.then((articles) => articles.filter((article) => !article.tag_list.includes('video')))
.then((articles) =>
articles.filter((article) => {
if (!uniqueNamesArticlesMap.has(article.title)) {
uniqueNamesArticlesMap.set(article.title, article);
return true;
}
return false;
}),
);
}
const Article = t.Record({
id: t.Number,
title: t.String,
description: t.String,
cover_image: t.String.nullable(),
tag_list: t.Array(t.String),
slug: t.String,
url: t.String,
created_at: t.String,
published_at: t.String,
});
export type Article = t.Static<typeof Article>;
const Response = t.Array(Article);
async function getArticlesOf(serviceName: keyof typeof foremServices): Promise<Array<Article>> {
console.log('fetching articles of', serviceName);
const service = foremServices[serviceName];
const url = new URL(service.url);
url.pathname = '/api/articles';
url.searchParams.set('username', 'sergeysova');
url.searchParams.set('per_page', '1000');
const response = await cachedFetch(url, {
headers: {Accept: 'application/vnd.forem.api-v1+json', 'api-key': service.apiKey},
});
try {
return Response.check(await response.json());
} catch (error) {
console.error('Failed to check articles of', serviceName);
throw error;
}
}
|
3b1bfec4a1380eafc6909acb00bc3f84a4f726bc
|
TypeScript
|
mrsekut/react-hook-form-website
|
/src/components/codeExamples/v6/useWatchTs.ts
| 3.125
| 3
|
export default `import React from "react";
import { useForm, useWatch } from "react-hook-form";
interface FormInputs {
firstName: string;
lastName: string;
}
function FirstNameWatched({ control }: { control: Control<FormInputs> }) {
const firstName = useWatch({
control,
name: "firstName", // without supply name will watch the entire form, or ['firstName', 'lastName'] to watch both
defaultValue: "default" // default value before the render
});
return <p>Watch: {firstName}</p>; // only re-render at the component level, when firstName changes
}
function App() {
const { register, control, handleSubmit } = useForm<FormInputs>();
const onSubmit = (data: FormInputs) => {
console.log(data)
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First Name:</label>
<input ref={register} name="firstName" />
<input ref={register} name="lastName" />
<input type="submit" />
<FirstNameWatched control={control} />
</form>
);
}`
|
d35dbb34b308d97f160a6a93a2f5716f28c292a6
|
TypeScript
|
matheusfischer0/matheusfischer-api
|
/src/modules/shipmentRoutes/services/CreateShipmentRouteService.ts
| 2.546875
| 3
|
import { startOfHour } from 'date-fns';
import { inject, injectable } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import ShipmentRoute from '@modules/shipmentRoutes/infra/typeorm/entities/ShipmentRoute';
import IShipmentRoutesRepository from '../repositories/IShipmentRoutesRepository';
interface IRequest {
id_shipment_from_city: string;
id_shipment_to_city: string;
price: number;
}
@injectable()
class CreateShipmentRouteService {
constructor(
@inject('ShipmentRoutesRepository')
private shipmentRoutesRepository: IShipmentRoutesRepository,
) {}
public async execute({ id_shipment_from_city, id_shipment_to_city, price }: IRequest): Promise<ShipmentRoute> {
const findShipment = await this.shipmentRoutesRepository.findShipment(
id_shipment_from_city, id_shipment_to_city
);
if (findShipment) {
throw new AppError('This shipment is already exists');
}
const shipment = this.shipmentRoutesRepository.create({
id_shipment_from_city,
id_shipment_to_city,
price,
});
return shipment;
}
}
export default CreateShipmentRouteService;
|
d4af25570fa97dde00888d200b7c37f24ebfd804
|
TypeScript
|
kstdn/react-graph
|
/example/mock-backend.ts
| 2.75
| 3
|
import { GraphNodeDef } from './..';
let nodes = new Map<string, GraphNodeDef<string>>();
nodes.set('1', new GraphNodeDef('Node 1', '1', ['2', '3', '5']));
nodes.set('2', new GraphNodeDef('Node 2', '2', ['4', '6']));
nodes.set('3', new GraphNodeDef('Node 3', '3', ['2', '4']));
nodes.set('4', new GraphNodeDef('Node 4', '4', []));
nodes.set('5', new GraphNodeDef('Node 5', '5', ['4']));
nodes.set('6', new GraphNodeDef('Node 6', '6', []));
export function getNodes(ids: string[]): Promise<GraphNodeDef<string>[]> {
return new Promise((resolve, reject) => {
const found = ids.reduce<GraphNodeDef<string>[]>((prev, curr) => {
const foundNode = nodes.get(curr);
if (foundNode) {
return [...prev, foundNode];
} else return prev;
}, []);
if (found.length) {
setTimeout(() => {
resolve(found);
}, 3000);
} else {
reject();
}
});
}
|
48565cc1e61bfbc80389453615861208c1684c0a
|
TypeScript
|
WaywardGame/tars
|
/src/core/planning/IPlanner.ts
| 2.984375
| 3
|
/*!
* Copyright 2011-2023 Unlok
* https://www.unlok.ca
*
* Credits & Thanks:
* https://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide:
* https://github.com/WaywardGame/types/wiki
*/
import type Context from "../context/Context";
import type { IObjective, ObjectivePipeline } from "../objective/IObjective";
import type { IPlan } from "./IPlan";
/**
* Creates plans for executing objectives
*
* The plan will contain the optimal tree for completing the objective
*
* Related reading:
*
* https://en.wikipedia.org/wiki/Automated_planning_and_scheduling
* https://en.wikipedia.org/wiki/Backward_chaining
* https://en.wikipedia.org/wiki/Game_tree
*
* Or ask Spacetech about it
*/
export interface IPlanner {
/**
* Returns true if a plan is currently being created
*/
readonly isCreatingPlan: boolean;
/**
* Enables debug mode, which emits additional logs to the console
*/
debug: boolean;
/**
* Reset the cached difficulties for objectives
*/
reset(): void;
/**
* Creates a plan that completes the given objective
* @param context The context
* @param objective The objective for the Plan
* @returns The plan or undefined if no plan can be found
*/
createPlan(context: Context, objective: IObjective): Promise<IPlan | undefined>;
/**
* Determines the easiest objective pipeline to execute
* @param context The context
* @param objectives List of objective pipelines
* @returns The objective pipeline to execute
*/
pickEasiestObjectivePipeline(context: Context, objectives: IObjective[][]): Promise<ObjectivePipeline>;
}
|
226d3d549cfa7153f9861e1fad8b058772f8026e
|
TypeScript
|
bwrrp/slimdom.js
|
/test/NodeType.tests.ts
| 2.609375
| 3
|
import * as slimdom from '../src/index';
describe('NodeType', () => {
it('is exposed as constants on the Node constructor', () => {
expect(slimdom.Node.ELEMENT_NODE).toBe(1);
expect(slimdom.Node.ATTRIBUTE_NODE).toBe(2);
expect(slimdom.Node.TEXT_NODE).toBe(3);
expect(slimdom.Node.CDATA_SECTION_NODE).toBe(4);
expect(slimdom.Node.ENTITY_REFERENCE_NODE).toBe(5);
expect(slimdom.Node.ENTITY_NODE).toBe(6);
expect(slimdom.Node.PROCESSING_INSTRUCTION_NODE).toBe(7);
expect(slimdom.Node.COMMENT_NODE).toBe(8);
expect(slimdom.Node.DOCUMENT_NODE).toBe(9);
expect(slimdom.Node.DOCUMENT_TYPE_NODE).toBe(10);
expect(slimdom.Node.DOCUMENT_FRAGMENT_NODE).toBe(11);
expect(slimdom.Node.NOTATION_NODE).toBe(12);
});
it('is exposed as properties on Node instances', () => {
const node = slimdom.document.createElement('test');
expect(node.ELEMENT_NODE).toBe(1);
expect(node.ATTRIBUTE_NODE).toBe(2);
expect(node.TEXT_NODE).toBe(3);
expect(node.CDATA_SECTION_NODE).toBe(4);
expect(node.ENTITY_REFERENCE_NODE).toBe(5);
expect(node.ENTITY_NODE).toBe(6);
expect(node.PROCESSING_INSTRUCTION_NODE).toBe(7);
expect(node.COMMENT_NODE).toBe(8);
expect(node.DOCUMENT_NODE).toBe(9);
expect(node.DOCUMENT_TYPE_NODE).toBe(10);
expect(node.DOCUMENT_FRAGMENT_NODE).toBe(11);
expect(node.NOTATION_NODE).toBe(12);
});
});
|
048e2f74f9d22d4b9ed8377c3ab4318baba413f0
|
TypeScript
|
x3rAx/nuxt-testable
|
/modules/example/store/__tests__/todos.api.mock.ts
| 2.71875
| 3
|
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { ITodo } from '../types';
const $instance = axios.create();
const mock = new MockAdapter($instance);
const todos: ITodo[] = []
/**
* get todos
*/
mock.onGet('/todos').reply((config) => {
return [200, JSON.stringify(todos)]
})
/**
* create a new todo
*/
mock.onPost('/todos').reply((config) => {
const todo: ITodo = JSON.parse(config.data);
todo.id = Math.random().toString();
todos.push(todo);
return [200, todo]
})
/**
* update todo
*/
mock.onPut(/\/todos\/\.*/).reply((config) => {
const id = config.url!.replace('/todos/', '')
const data = JSON.parse(config.data)
delete data.id;
const index = todos.map((t) => t.id).indexOf(id)
Object.assign(todos[index], data)
return [200, 'ok']
})
/**
* delete todo
*/
mock.onDelete(/\/todos\/\.*/).reply((config) => {
const id = config.url!.replace('/todos/', '')
const index = todos.map((t) => t.id).indexOf(id)
todos.splice(index, 1)
return [200, 'ok']
})
export default $instance;
|
9a272fef0dac4d034320e5460bd805981b53f97d
|
TypeScript
|
mass10/typescript.note
|
/code/stacktrace/src/Main.ts
| 2.765625
| 3
|
import { Logger } from './Logger';
namespace Main {
function style1(): void {
var obj = {};
Error.captureStackTrace(obj);
// @ts-ignore
console.log(obj?.stack);
}
export function run(): void {
Logger.trace("### start ###");
Logger.trace("%d", 999);
Logger.trace("%s >> %s", "aaa", "AAA");
// style1();
Logger.trace("--- end ---");
}
}
Logger.trace("static scope $$$ begin $$$");
Main.run();
Logger.trace("static scope --- end ---");
|
8f130e49bdc7531fdda5567da6bc32dd3d7b8ac7
|
TypeScript
|
TheColorRed/phoenix
|
/src/core/GameObject.ts
| 2.765625
| 3
|
namespace Phoenix {
export class GameObject extends Object {
private _isActive: boolean = true
public sprite: Sprite
public tag: string = ''
public get isActive(): boolean { return this._isActive }
public readonly name: string
public constructor(name?: string) {
super()
this.name = name || `GameObject ${Game.gameObjects.length > 0 ? `(${Game.gameObjects.length})` : ''}`.trim()
this['_gameObject'] = this
this['_transform'] = this.addComponent(Transform)
Game.gameObjects.push(this)
}
public static findGameObjectsWithTag(tag: string): GameObject[] {
return Game.gameObjects.filter(go => go.isActive && go.tag == tag)
}
public static findWithTag(tag: string) {
return Game.gameObjects.find(go => go.isActive && go.tag == tag)
}
}
}
|
d6e618fd6cb1e9453560cccd2e138d1bb7eb5432
|
TypeScript
|
martijnvanduijneveldt/picklesdoc-compare
|
/src/util/jsdiff.util.ts
| 2.828125
| 3
|
import { diffWords, Change } from 'diff';
import { JsonTableDataRow } from '../models/json-table';
import { JsonTableDataRowCompare } from '../compare-models/json-table-compare';
import { Comparable } from '../helper-models/comparable';
import { JsonTestResult } from '../models/json-test-result';
import { DiffEle } from './diff.util';
function isJsonTestResult(toBeDetermined: JsonTableDataRow): toBeDetermined is JsonTestResult {
return toBeDetermined instanceof JsonTestResult;
}
export class JsDiffUtil {
static fullDiff(oldStr: string | null | undefined, newStr: string | null | undefined): string {
if (oldStr !== newStr) {
if (!oldStr) {
return `<ins>${newStr}</ins>`;
}
if (!newStr) {
return `<del>${oldStr}</del>`;
}
return `<del>${oldStr}</del><ins>${newStr}</ins>`;
}
return oldStr ? oldStr : '';
}
static diffMarkdown(newStr: string | null | undefined, oldStr: string | null | undefined): string {
return oldStr ? oldStr : '';
}
static diffWords(newStr: string | null | undefined, oldStr: string | null | undefined): string {
const parts = diffWords(oldStr ? oldStr : '', newStr ? newStr : '');
const output = parts.map(p => JsDiffUtil.getChangeVal(p));
return output.join('');
}
static diffArrayByIndex(newArray: string[] | undefined, oldArray: string[] | undefined): string[] {
let i = 0;
const result: string[] = [];
const oldArr = oldArray ? oldArray : [];
const newArr = newArray ? newArray : [];
while (i < oldArr.length && i < newArr.length) {
result[i] = JsDiffUtil.diffWords(oldArr[i], newArr[i]);
i += 1;
}
for (i; i < oldArr.length; i += 1) {
result[i] = `<del>${oldArr[i]}</del>`;
}
for (i; i < newArr.length; i += 1) {
result[i] = `<ins>${newArr[i]}</ins>`;
}
return result;
}
private static diffDataRow(
newArray: JsonTableDataRow[] | undefined,
oldArray: JsonTableDataRow[] | undefined,
): JsonTableDataRowCompare[] {
let i = 0;
const result: JsonTableDataRowCompare[] = [];
const oldArr = oldArray ? oldArray : [];
const newArr = newArray ? newArray : [];
let oldLastCell: JsonTestResult | undefined = undefined;
let newLastCell: JsonTestResult | undefined = undefined;
let oldLength = oldArr.length;
if (isJsonTestResult(oldArr[oldLength - 1])) {
oldLastCell = oldArr[oldLength - 1] as JsonTestResult;
oldLength -= 1;
}
let newLength = newArr.length;
if (isJsonTestResult(newArr[newLength - 1])) {
newLastCell = newArr[newLength - 1] as JsonTestResult;
newLength -= 1;
}
while (i < oldLength && i < newLength) {
result[i] = JsDiffUtil.diffWords(newArr[i] as string, oldArr[i] as string);
i += 1;
}
for (i; i < oldLength; i += 1) {
result[i] = `<del>${oldArr[i]}</del>`;
}
for (i; i < newLength; i += 1) {
result[i] = `<ins>${newArr[i]}</ins>`;
}
if (oldLastCell || newLastCell) {
result.push(new Comparable(newLastCell, oldLastCell));
}
return result;
}
static diffNesterDataRows(
newArray: JsonTableDataRow[][] | undefined,
oldArray: JsonTableDataRow[][] | undefined,
): JsonTableDataRowCompare[][] {
let i = 0;
const result: JsonTableDataRowCompare[][] = [];
const oldArr = oldArray ? oldArray : [];
const newArr = newArray ? newArray : [];
while (i < oldArr.length && i < newArr.length) {
result[i] = this.diffDataRow(newArr[i], oldArr[i]);
i += 1;
}
for (i; i < oldArr.length; i += 1) {
result[i] = this.diffDataRow(undefined, oldArr[i]);
}
for (i; i < newArr.length; i += 1) {
result[i] = this.diffDataRow(newArr[i], undefined);
}
return result;
}
private static getChangeVal(change: Change): string {
if (change.added) {
return `<ins>${change.value}</ins>`;
}
if (change.removed) {
return `<del>${change.value}</del>`;
}
return change.value;
}
}
|
8e7ff8852aead078236d93b42de08eb2438fa1d4
|
TypeScript
|
sarahbacha/watson
|
/server/apis/wa-adapter.ts
| 2.515625
| 3
|
var prompt = require('prompt-sync')();
var conversation = require('watson-developer-cloud/conversation/v1');
export class WatsonAssistantAdapter {
private conv;
private workspace_id;
constructor() {
this.conv = new conversation({
username: 'f808e1b8-6041-476a-9314-4d3ae2e026d5', // replace with service username
password: 'cUWEapMErMUh', // replace with service password
version_date: '2017-05-26'
});
this.workspace_id = 'e94c98ed-e5cf-4457-a719-4f999b3d7b33'; // replace with workspace ID
}
processResponse(err, response) {
if (err) {
console.error(err); // something went wrong
return;
}
var endConversation = false;
// Check for action flags.
if (response.output.action === 'display_time') {
// User asked what time it is, so we output the local system time.
console.log('The current time is ' + new Date().toLocaleTimeString());
} else if (response.output.action === 'end_conversation') {
// User said goodbye, so we're done.
console.log(response.output.text[0]);
endConversation = true;
} else {
// Display the output from dialog, if any.
if (response.output.text.length != 0) {
console.log(response.output.text[0]);
}
}
// If we're not done, prompt for the next round of input.
if (!endConversation) {
var newMessageFromUser = prompt('>> ');
this.conv.message({
workspace_id: this.workspace_id,
input: { text: newMessageFromUser },
// Send back the context to maintain state.
context: response.context,
}, this.processResponse)
}
}
}
|
000de155706e5406b637137372c1b8480de944d3
|
TypeScript
|
noramehesz/timesheet
|
/timesheet_server/src/models/User.ts
| 2.734375
| 3
|
import mongoose from 'mongoose';
import TimeSheetModel from './Timesheet';
enum UserType {
student = 'student',
studentClub = 'studentClub',
company = 'company',
}
const UserSchema = new mongoose.Schema({
email: {type: String, required: true},
name: {type: String, required: false},
password: {type: String, required: true},
username: {type: String, required: true},
school: {type: String, required: false},
timesheets: {type: Array<any>(), required: false},
students: {type: Array<any>(), required: false},
companies: {type: [this], required: false},
employees: {type: [this], required: false},
role: {type: UserType, required: true},
});
const UserModel = mongoose.model('User', UserSchema);
class User extends mongoose.Document {
static async createUser(data: any) {
const user = new UserModel({
email: data.email,
name: data.name,
username: data.username,
password: data.password,
school: data.school,
timesheets: data.timesheets,
students: data.students,
companies: data.companies,
employees: data.employees,
role: data.role,
});
let errorMessage: string = '';
await user.save((error, document) => {
if (error) {
errorMessage = error;
}
console.log(`create a user with id: ${user.id}`);
});
return {message: `creat a user witn id: ${user.id}`, createdUser: user, error: errorMessage}; // -pw
}
static getUsers() {
return UserModel.find((error, document) => {
console.log(`get all users`);
return document;
});
}
static getUserById(id: string) {
return UserModel.findById(id, (error, document) => {
console.log(`get user with id: ${id}`);
return document;
});
}
static login(username: string, password: string) {
let errorMessage: any = null;
return UserModel.findOne({password, username}, (error, document) => {
if (error) {
errorMessage = error;
}
console.log(`try to get user, username: ${username}`);
return {doc: document, error: errorMessage};
})
}
static deleteUserById(id: string) {
return UserModel.findByIdAndDelete(id, (error, document) => {
console.log(`delet a user with id: ${id}`);
return document;
})
}
static updateUserById(id: string, data: any) {
return UserModel.findByIdAndUpdate(id, data, (error, document) => {
if (error) {
console.log(error);
}
console.log(`update a user with id: ${id}`);
})
}
}
export default User;
|
d90160b77ded39857e9c83a0ef26ac6ef8519fcc
|
TypeScript
|
anhducc13/react-typescript-boilerplate
|
/src/helpers/user.ts
| 2.59375
| 3
|
import commonConstants from 'constants/common';
import { userServices } from 'services';
import { IRoute } from 'interfaces';
const { ALL } = commonConstants;
const permission = (app: string, resource: string, action?: string) => {
return [app, resource, action].filter(x => !!x).join(':');
};
const checkPermission = (
permissions: string[],
app: string,
resource: string,
action?: string
) => {
const perform = permission(app, resource, action);
const performAllAction = permission(app, resource, ALL);
const performAllResource = permission(app, ALL, ALL);
const allPerforms = [perform, performAllAction, performAllResource];
return !!(permissions && permissions.find(p => allPerforms.includes(p)));
};
const filterHasPermissions = (
items: IRoute[],
currentPermissions: string[]
) => {
return items.filter(item => {
const { permissions, children } = item;
if (!permissions) return true;
const intersection = permissions.find(x => {
const { app, resource, action } = x;
if (children) {
if (!currentPermissions) return false;
return currentPermissions.some(p => {
return (
p.startsWith(permission(app, resource, action)) ||
p.startsWith(permission(app, resource, ALL)) ||
p.startsWith(permission(app, ALL, ALL))
);
});
}
return checkPermission(currentPermissions, app, resource, action);
});
return !!intersection;
});
};
const logout = () => {
userServices.logout();
};
export default {
permission,
checkPermission,
filterHasPermissions,
logout,
};
|