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
|
|---|---|---|---|---|---|---|
79a88a8192de188c7781c3ddefe7a7923c237013
|
TypeScript
|
atschaef/typescript-react-playground
|
/test/unit/components/date_input/date_input.utils.spec.ts
| 2.828125
| 3
|
import { createSandbox, SinonSpy } from 'sinon'
import { expect } from 'chai'
import {
preventNonNumeric,
focusPreviousInput,
tryFocusNextInput,
DateFieldType,
normalizeValue,
} from '../../../../src/components/date_input/date_input_utils'
import { keyboardEvent } from '../../data/events'
describe('-- Date Input Utils --', () => {
const testSandbox = createSandbox()
const event = { ...keyboardEvent }
let preventDefault: SinonSpy
let focus: SinonSpy
let blur: SinonSpy
before(() => {
preventDefault = testSandbox.spy(event, 'preventDefault')
blur = testSandbox.spy(event.currentTarget, 'blur')
})
afterEach(() => {
testSandbox.resetHistory()
})
after(() => {
testSandbox.restore()
})
describe('preventNonNumeric', () => {
it('should call preventDefault if exponent key is entered', () => {
event.charCode = 69
preventNonNumeric(event)
expect(preventDefault.callCount).to.equal(1)
})
it('should call preventDefault if minus key is entered', () => {
event.charCode = 187
preventNonNumeric(event)
expect(preventDefault.callCount).to.equal(1)
})
it('should call preventDefault if plus key is entered', () => {
event.charCode = 189
preventNonNumeric(event)
expect(preventDefault.callCount).to.equal(1)
})
it('should call preventDefault if decimal key is entered', () => {
event.charCode = 190
preventNonNumeric(event)
expect(preventDefault.callCount).to.equal(1)
})
it('should not call preventDefault if numeric value is entered', () => {
// "charCode 48" is 0
event.charCode = 48
preventNonNumeric(event)
expect(preventDefault.callCount).to.equal(0)
})
})
describe('focusPreviousInput', () => {
const mockInput = document.createElement('input')
before(() => {
focus = testSandbox.spy(mockInput, 'focus')
})
it('should focus the previous input on delete key', () => {
event.keyCode = 8
focusPreviousInput(mockInput)(event)
expect(blur.callCount).to.equal(1)
expect(focus.callCount).to.equal(1)
expect(preventDefault.callCount).to.equal(1)
})
it('should not call focusPreviousInput if input is empty but keyCode is not the delete key', () => {
event.keyCode = 40
focusPreviousInput(mockInput)(event)
expect(blur.callCount).to.equal(0)
expect(focus.callCount).to.equal(0)
expect(preventDefault.callCount).to.equal(0)
})
it('should not call focusPreviousInput if input is not empty', () => {
event.keyCode = 8
event.currentTarget.value = '0'
focusPreviousInput(mockInput)(event)
expect(blur.callCount).to.equal(0)
expect(focus.callCount).to.equal(0)
expect(preventDefault.callCount).to.equal(0)
})
it('should not call focusPreviousInput if previous input is not provided', () => {
event.keyCode = 8
focusPreviousInput(null)(event)
expect(blur.callCount).to.equal(0)
expect(preventDefault.callCount).to.equal(0)
})
})
describe('tryFocusNextInput', () => {
const mockInput = document.createElement('input')
let focus: SinonSpy
before(() => {
focus = testSandbox.spy(mockInput, 'focus')
})
it('should focus the next input if the value is valid and max length of field has been reached', () => {
tryFocusNextInput({
isValid: true,
value: '12',
previousValueLength: 1,
fieldType: DateFieldType.Day,
nextInput: mockInput,
})
expect(focus.callCount).to.equal(1)
})
it('should focus next input if the value is greater than the max quick focus value', () => {
tryFocusNextInput({
isValid: true,
value: '2',
previousValueLength: 1,
fieldType: DateFieldType.Month,
nextInput: mockInput,
})
expect(focus.callCount).to.equal(1)
})
it('should not focus next input if the value is invalid or there is no next input', () => {
tryFocusNextInput({
isValid: false,
value: '12',
previousValueLength: 1,
fieldType: DateFieldType.Day,
nextInput: mockInput,
})
expect(focus.callCount).to.equal(0)
tryFocusNextInput({
isValid: true,
value: '12',
previousValueLength: 1,
fieldType: DateFieldType.Day,
nextInput: null,
})
expect(focus.callCount).to.equal(0)
})
it('should not focus next input if it does not meet the requirements', () => {
tryFocusNextInput({
isValid: true,
value: '200',
previousValueLength: 0,
fieldType: DateFieldType.Year,
nextInput: mockInput,
})
expect(focus.callCount).to.equal(0)
})
})
describe('normalizeValue', () => {
it('should allow zero as first digit', () => {
expect(normalizeValue('')).to.equal('')
expect(normalizeValue('00')).to.equal('0')
expect(normalizeValue('01')).to.equal('01')
expect(normalizeValue('00', 4)).to.equal('00')
expect(normalizeValue('000', 4)).to.equal('000')
expect(normalizeValue('0000', 4)).to.equal('000')
expect(normalizeValue('0001', 4)).to.equal('0001')
})
})
})
|
5355127f290f37f5c77826e0e0256ab53df68a4c
|
TypeScript
|
clubito/server
|
/src/controllers/event/admin.ts
| 2.53125
| 3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
// create/edit/delete events
import { Request, Response } from "express";
import Club from "@models/Club";
import User from "@models/User";
import logger from "@logger";
import joi from "joi";
import { CLUB_ROLE } from "@models/enums";
import { ObjectId } from "mongodb";
import Event from "@models/Event";
import { sendEventCreatedNotification, sendEventEditedNotification } from "@notifications";
const postCreateEventSchema = joi.object().keys({
name: joi.string().required(),
description: joi.string(),
startTime: joi.date().required(),
endTime: joi.date().required(),
longitude: joi.number(),
latitude: joi.number(),
shortLocation: joi.string(),
picture: joi.string(),
clubId: joi.string().custom((value, helper) => {
if (ObjectId.isValid(value)) {
return value;
} else {
return helper.message({ custom: "id is not valid" });
}
}).required(),
isOpen: joi.boolean()
});
const putEditEventSchema = joi.object().keys({
name: joi.string(),
description: joi.string(),
startTime: joi.date(),
endTime: joi.date(),
longitude: joi.number(),
latitude: joi.number(),
shortLocation: joi.string(),
picture: joi.string(),
eventId: joi.string().custom((value, helper) => {
if (ObjectId.isValid(value)) {
return value;
} else {
return helper.message({ custom: "id is not valid" });
}
}).required(),
notifyUsers: joi.boolean().required(),
isOpen: joi.boolean()
});
export const postCreateEvent = (req: Request, res: Response): void => {
const { error } = postCreateEventSchema.validate(req.body);
if (error) {
res.status(400).json({ "error": error.message });
logger.debug(error);
return;
}
const { name,
description,
startTime,
endTime,
longitude,
latitude,
shortLocation,
picture,
clubId,
isOpen } = req.body;
const userId = req.userId;
User.findById(userId)
.then(user => {
if (!user) {
res.status(400).json({ error: "User not found" });
return;
}
Club
.findOne({ _id: clubId, "deleted.isDeleted": false })
.populate("events")
.then(club => {
if (!club) {
res.status(400).json({ error: "Club does not exist" });
return;
}
// Make sure the user is allowed to make events
let userRole;
club.members.forEach(member => {
if (member.member.equals(userId)) {
userRole = member.role2;
// if (member.role == CLUB_ROLE.MEMBER || member.role == CLUB_ROLE.NONMEMBER) {
// // If the user is only a normal member or not even a member,
// // then don't let them make an event
// res.status(400).json({ error: "Current user does not have permission to do that." });
// return;
// }
}
});
if (userRole === undefined) {
userRole = {
name: "Non-Member",
permissions: []
};
}
// Event does not already exist
if (club.events.some(temp => temp.name === name)) {
res.status(400).json({ error: "An event with that name already exists. Did you mean to edit the event?" });
return;
}
const newEvent = new Event({
name,
description,
startTime: new Date(startTime),
endTime: new Date(endTime),
longitude,
latitude,
shortLocation,
picture,
club: clubId,
isOpen: isOpen
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
newEvent.save((err: any, createdEvent) => {
if (err || !createdEvent) {
if (err.code == 11000) {
res.status(400).json({ error: "1An event with that name already exists. Did you mean to edit the event?" });
return;
} else {
res.status(400).json({ error: "Error creating an event: " + err?.message });
return;
}
}
club.events.push(newEvent._id);
club.save().then(async () => {
await sendEventCreatedNotification(newEvent._id, club._id, club.name, userRole, newEvent.name);
res.status(200).json({
message: "Successfully created event",
eventId: createdEvent["_id"]
});
return;
});
});
});
})
.catch(err => {
logger.error(err);
res.status(500).json({ error: err });
return;
});
};
export const putEditEvent = (req: Request, res: Response): void => {
const { error } = putEditEventSchema.validate(req.body);
if (error) {
res.status(400).json({ "error": error.message });
logger.debug(error);
return;
}
const { name,
description,
startTime,
endTime,
longitude,
latitude,
shortLocation,
picture,
eventId,
notifyUsers,
isOpen } = req.body;
const userId = req.userId;
User.findById(userId)
.then(user => {
if (!user) {
res.status(400).json({ error: "User not found" });
return;
}
Event.findOne({ _id: eventId })
.populate("club")
.then(event => {
if (!event) {
res.status(400).json({ error: "Event does not exist" });
return;
}
let userRole;
user.clubs.forEach(club => {
if (club.club.equals(event.club)) {
userRole = club.role2;
// if (club.role != CLUB_ROLE.OFFICER && club.role != CLUB_ROLE.OWNER) {
// res.status(400).json({ error: "Current user does not have permission to do that." });
// return;
// }
}
});
if (userRole === undefined) {
userRole = {
name: "Non-Member",
permissions: []
};
}
if (name) {
event.name = name;
}
if (description) {
event.description = description;
}
if (startTime) {
event.startTime = startTime;
}
if (endTime) {
event.endTime = endTime;
}
if (longitude) {
event.longitude = longitude;
}
if (latitude) {
event.latitude = latitude;
}
if (shortLocation) {
event.shortLocation = shortLocation;
}
if (picture) {
event.picture = picture;
}
if (isOpen) {
event.isOpen = isOpen;
}
event.save().then(() => {
if (notifyUsers) {
sendEventEditedNotification(event._id, (event.club as any).name, userRole, event.name).then(() => {
res.status(200).json({ message: "Successfully updated event" });
return;
}).catch(e => {
throw e;
});
} else {
res.status(200).json({ message: "Successfully updated event " });
return;
}
}).catch(e => {
res.status(500).json({ error: "There was an error updating the event" });
logger.error(e);
return;
});
});
})
.catch(err => {
logger.error(err);
res.status(500).json({ error: err });
return;
});
};
|
5ceef28dfecafd4e365a35a6f9736b200fca0729
|
TypeScript
|
DaviiErazo/transfers-back
|
/src/modules/transfers/useCases/getTransfers/GetTransfersUseCase.ts
| 2.71875
| 3
|
import { Either, Result, left, right } from "../../../../shared/core/Result";
import { AppError } from "../../../../shared/core/AppError";
import { UseCase } from "../../../../shared/core/UseCase";
import { ITransferRepo } from "../../repos/transferRepo";
import { Transfer } from "../../domain/transfer";
type Response = Either<AppError.UnexpectedError, Result<Transfer[]>>;
export class GetTransfersUseCase implements UseCase<any, Promise<Response>> {
private transferRepo: ITransferRepo;
constructor(transferRepo: ITransferRepo) {
this.transferRepo = transferRepo;
}
public async execute(): Promise<Response> {
let results: Transfer[];
try {
results = await this.transferRepo.getTransfers();
} catch (err) {
return left(new AppError.UnexpectedError(err)) as Response;
}
return right(Result.ok<Transfer[]>(results));
}
}
|
ba3e4243fc1080d322b037c2fd74ebe20d44ae70
|
TypeScript
|
shatee/use-click-document
|
/src/index.ts
| 2.6875
| 3
|
import { RefObject, useCallback, useEffect } from 'react';
export const useClickDocument = (
onClick: (event: MouseEvent) => void,
ignoreRefs?: RefObject<HTMLElement>[]
) => {
const onClickHandler = useCallback((event: MouseEvent) => {
if (!event.target) return;
if (ignoreRefs?.length) {
for (let ref of ignoreRefs) {
if (!ref.current) continue;
if (ref.current.contains(event.target as HTMLElement)) return;
}
}
onClick(event);
}, [onClick, ignoreRefs]);
useEffect(() => {
document.addEventListener('click', onClickHandler);
return () => {
document.removeEventListener('click', onClickHandler);
}
}, []);
};
|
863b1f000fb32857ac31f7947bb2937a4684eecb
|
TypeScript
|
Kayque-Goncalves/fullstack-twitter-clone
|
/server/src/useCases/Authentication/AuthenticationController.ts
| 2.59375
| 3
|
import { Request, Response } from 'express'
import { AuthenticationCase } from './AuthenticationCase'
class AuthenticationController {
private authenticationCase: AuthenticationCase
constructor(authenticationCase: AuthenticationCase){
this.authenticationCase = authenticationCase
}
async handle(request: Request, response: Response) {
const { _id, password } = request.body
try {
let JWT_token = await this.authenticationCase.execute({
_id,
password
})
return response.status(200).json(JWT_token)
} catch (err) {
return response.status(400).json({
message: err.message || 'Unexpected Error'
})
}
}
}
export { AuthenticationController }
|
f553163753c177d9d9ca97cf1d01c2ff3fa3b222
|
TypeScript
|
lanmower/onethreethreeseven-core
|
/packages/crypto/src/builder/transactions/vote.ts
| 2.65625
| 3
|
import { TransactionTypes } from "../../constants";
import { feeManager } from "../../managers";
import { ITransactionData } from "../../transactions";
import { TransactionBuilder } from "./transaction";
export class VoteBuilder extends TransactionBuilder<VoteBuilder> {
constructor() {
super();
this.data.type = TransactionTypes.Vote;
this.data.fee = feeManager.get(TransactionTypes.Vote);
this.data.amount = 0;
this.data.recipientId = null;
this.data.senderPublicKey = null;
this.data.asset = { votes: [] };
this.signWithSenderAsRecipient = true;
}
/**
* Establish the votes on the asset.
*/
public votesAsset(votes: string[]): VoteBuilder {
this.data.asset.votes = votes;
return this;
}
public getStruct(): ITransactionData {
const struct = super.getStruct();
struct.amount = this.data.amount;
struct.recipientId = this.data.recipientId;
struct.asset = this.data.asset;
return struct;
}
protected instance(): VoteBuilder {
return this;
}
}
|
2e0b3dfc5d7ec31c92c35887c5a788ffef5623b4
|
TypeScript
|
IgorMinar/angular
|
/packages/core/test/util/array_utils_spec.ts
| 2.703125
| 3
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {flatten} from '../../src/util/array_utils';
describe('flatten', () => {
it('should flatten an empty array', () => { expect(flatten([])).toEqual([]); });
it('should flatten a flat array', () => { expect(flatten([1, 2, 3])).toEqual([1, 2, 3]); });
it('should flatten a nested array depth-first', () => {
expect(flatten([1, [2], 3])).toEqual([1, 2, 3]);
expect(flatten([[1], 2, [3]])).toEqual([1, 2, 3]);
expect(flatten([1, [2, [3]], 4])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [2, [3]], [4]])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [2, [3]], [[[4]]]])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [], 2])).toEqual([1, 2]);
});
});
|
26222e414eb92efc1cdd27eb331b6a5940e41849
|
TypeScript
|
kike1303/peliculiando-ando
|
/src/app/store/reducers/my-movies.reducer.ts
| 2.640625
| 3
|
import * as myMoviesActions from '../actions/my-movies.actions';
import { createReducer, on, Action } from '@ngrx/store';
import { initialMyMoviesState, MyMoviesState } from '../states/my-movies.state';
import { MovieDetails } from '../../models/movie-details.model';
import { MovieInfo } from 'src/app/models/movie-info.model';
export const getMyMovies = (state: MyMoviesState) => ({
...state,
});
export const setDisplayMovieDetails = (
state: MyMoviesState,
displayMovieDetails: { displayMovieDetails: boolean }
) => ({
...state,
...displayMovieDetails,
});
export const setMyMoviesMovieDetails = (
state: MyMoviesState,
movieDetails: { movieDetails: MovieDetails }
) => ({
...state,
...movieDetails,
});
export const setMyMoviesFavMovie = (
state: MyMoviesState,
movie: MovieInfo
) => ({
...state,
myFavMovies: [...state.myFavMovies, movie],
});
export const deleteMyMoviesFavMovie = (
state: MyMoviesState,
movie: MovieInfo
) => {
const myFavMovies = state.myFavMovies.filter(
(myMovie: MovieInfo) => myMovie.imdbID !== movie.imdbID
);
localStorage.setItem('favMovies', JSON.stringify(myFavMovies));
return {
...state,
myFavMovies,
};
};
export const myMoviesReducer = createReducer(
initialMyMoviesState,
on(myMoviesActions.getMyMovies, getMyMovies),
on(myMoviesActions.setMyMoviesDisplayMovieDetails, setDisplayMovieDetails),
on(myMoviesActions.setMyMoviesMovieDetails, setMyMoviesMovieDetails),
on(myMoviesActions.setMyMoviesFavMovie, setMyMoviesFavMovie),
on(myMoviesActions.deleteMyMoviesFavMovie, deleteMyMoviesFavMovie)
);
export function reducer(
state: MyMoviesState | undefined,
action: Action
): MyMoviesState {
return myMoviesReducer(state, action);
}
|
91033a8b79683a00be2593ae3bc70de3ce8ddd84
|
TypeScript
|
studiokaiji/sidetree
|
/lib/core/interfaces/IBatchWriter.ts
| 2.765625
| 3
|
/**
* Interface that defines a class that can write batches of operations to content addressable storage and blockchain.
*/
export default interface IBatchWriter {
/**
* Writes one or more batches of batches of operations to content addressable storage and blockchain.
*/
write (): Promise<void>;
}
|
89eafb8d23c5187d15c381cf9673eaec3e437e27
|
TypeScript
|
dylang/npm-check
|
/index.d.ts
| 2.625
| 3
|
declare module NpmCheck {
interface INpmCheckOptions {
global?: boolean;
update?: boolean;
skipUnused?: boolean;
devOnly?: boolean;
ignoreDev?: boolean;
cwd?: string;
saveExact?: boolean;
currentState?: Object;
}
type INpmCheckGetSetValues = "packages" | "debug" | "global" | "cwd" | "cwdPackageJson" | "emoji";
type INpmVersionBumpType = "patch" | "minor" | "major" | "prerelease" | "build" | "nonSemver" | null;
interface INpmCheckCurrentState {
get: (key: INpmCheckGetSetValues) => INpmCheckPackage[];
set: (key: INpmCheckGetSetValues, val: any) => void;
}
interface INpmCheckPackage {
moduleName: string; // name of the module.
homepage: string; // url to the home page.
regError: any; // error communicating with the registry
pkgError: any; // error reading the package.json
latest: string; // latest according to the registry.
installed: string; // version installed
isInstalled: boolean; // Is it installed?
notInstalled: boolean; // Is it installed?
packageWanted: string; // Requested version from the package.json.
packageJson: string; // Version or range requested in the parent package.json.
devDependency: boolean; // Is this a devDependency?
usedInScripts: undefined | string[], // Array of `scripts` in package.json that use this module.
mismatch: boolean; // Does the version installed not match the range in package.json?
semverValid: string; // Is the installed version valid semver?
easyUpgrade: boolean; // Will running just `npm install` upgrade the module?
bump: INpmVersionBumpType; // What kind of bump is required to get the latest
unused: boolean; // Is this module used in the code?
}
//The default function returns a promise
export default function(options: INpmCheckOptions): {
then(stateFn: (state: INpmCheckCurrentState) => void): void;
};
}
declare module "npm-check" {
export = NpmCheck.default;
}
|
d3a54c50ad9cf5d6588a332b9e24baf2cf25b162
|
TypeScript
|
Chrisaxell/radio-sheep-gcs
|
/app/api/messages/vfr-hud.ts
| 2.609375
| 3
|
import {MAVLinkMessage} from '@gardsteinsvik/node-mavlink';
import {readInt64LE, readUInt64LE} from '@gardsteinsvik/node-mavlink';
/*
Metrics typically displayed on a HUD for fixed wing aircraft.
*/
// airspeed Vehicle speed in form appropriate for vehicle type. For standard aircraft this is typically calibrated airspeed (CAS) or indicated airspeed (IAS) - either of which can be used by a pilot to estimate stall speed. float
// groundspeed Current ground speed. float
// heading Current heading in compass units (0-360, 0=north). int16_t
// throttle Current throttle setting (0 to 100). uint16_t
// alt Current altitude (MSL). float
// climb Current climb rate. float
export class VfrHud extends MAVLinkMessage {
public airspeed!: number;
public groundspeed!: number;
public heading!: number;
public throttle!: number;
public alt!: number;
public climb!: number;
public _message_id: number = 74;
public _message_name: string = 'VFR_HUD';
public _crc_extra: number = 20;
public _message_fields: [string, string, boolean, number][] = [
['airspeed', 'float', false, 0],
['groundspeed', 'float', false, 0],
['alt', 'float', false, 0],
['climb', 'float', false, 0],
['heading', 'int16_t', false, 0],
['throttle', 'uint16_t', false, 0],
];
}
|
4cf675312c8c9ac1458df403d72d18b9bbdbab4f
|
TypeScript
|
Jesusml1/euler_problems
|
/euler_06/euler_06.ts
| 3.75
| 4
|
const generator = (limit:number) => {
let numbers:number[] = [];
for(let i = 0; i < limit; i++){
numbers.push(i + 1);
}
return numbers;
}
const sample = generator(100);
const SquareSum = (numbers:number[]): number => numbers.map(number => Math.pow(number, 2)).reduce((a, b) => a + b);
const SumSquare = (numbers:number[]): number => Math.pow(numbers.reduce((a, b) => a + b), 2);
console.log(SumSquare(sample) - SquareSum(sample));
|
44e04f28c8ef558db194492ef9ee89f29fc3ca7e
|
TypeScript
|
Olddude/angular-challange
|
/src/app/tree/services/value-type/value-type.service.spec.ts
| 2.890625
| 3
|
import { ValueTypeService } from './value-type.service';
describe('ValueTypeService', () => {
let service: ValueTypeService;
beforeEach(() => {
service = new ValueTypeService();
});
it('should create', () => {
expect(service).toBeTruthy();
});
[
{ value: undefined, expected: 'undefined' },
{ value: null, expected: 'null' },
{ value: '\0', expected: 'string' },
{ value: '\.', expected: 'string' },
{ value: /^[a-z]$/g, expected: 'object' },
{ value: 0, expected: 'number' },
{ value: -0, expected: 'number' },
{ value: 'a', expected: 'string' },
{ value: 'asd', expected: 'string' },
{ value: 2484684867486486.48867468748674894, expected: 'number' },
{ value: '2021-01-01T12:00:00.000000Z', expected: 'string' },
{ value: new Date(2021, 1, 1), expected: 'object' },
{ value: true, expected: 'boolean' },
{ value: false, expected: 'boolean' },
{ value: 'true', expected: 'string' },
{ value: 'false', expected: 'string' },
].forEach(testItem => {
it(`should transform to type | value: "${testItem.value}" type: "${testItem.expected}"`, () => {
const actual = service.classify(testItem.value);
expect(actual).toEqual(testItem.expected);
});
});
});
|
a2e2a297e032f801e0835df3b3b69b4f3089a439
|
TypeScript
|
RocketCommunicationsInc/astro
|
/packages/web-components/src/utils/utils.ts
| 3.203125
| 3
|
export const hasShadowDom = (el: HTMLElement) => {
return !!el.shadowRoot && !!(el as any).attachShadow
}
export function hasSlot(el: HTMLElement, name?: string | undefined): boolean {
// Look for a named slot
if (name) {
return el.querySelector(`[slot="${name}"]`) !== null
}
// Look for a default slot
return [...el.childNodes].some((node) => {
//If node is text and not an empty string return true
if (
node.nodeType === node.TEXT_NODE &&
node?.textContent?.trim() !== ''
) {
return true
}
//If node is an element with a slot attribute return true
if (node.nodeType === node.ELEMENT_NODE) {
const el = node as HTMLElement
if (
!el.hasAttribute('slot') &&
/*
* This condition is specifically for checkbox because
* the hidden input becomes slotted content
*/
el.getAttribute('type') !== 'hidden'
) {
return true
}
}
return false
})
}
/**
* This method is used to add a hidden input to a host element that contains
* a Shadow DOM. It does not add the input inside of the Shadow root which
* allows it to be picked up inside of forms. It should contain the same
* values as the host element.
* https://github.com/ionic-team/ionic-framework/blob/ae96563fb3c4612cb8585292b389ee746f5759f7/core/src/utils/helpers.ts#L198
*
* @param always Add a hidden input even if the container does not use Shadow
* @param container The element where the input will be added
* @param name The name of the input
* @param value The value of the input
* @param disabled If true, the input is disabled
* @param checked Optional. If true, the input is checked
*/
export const renderHiddenInput = (
always: boolean,
container: HTMLElement,
name: string,
value: string | undefined | null,
disabled: boolean,
checked?: boolean
) => {
let input = container.querySelector(
'input.aux-input'
) as HTMLInputElement | null
if (always || hasShadowDom(container)) {
if (checked || checked == undefined) {
if (!input) {
input = container.ownerDocument!.createElement('input')
input.type = 'hidden'
input.classList.add('aux-input')
container.appendChild(input)
}
input.disabled = disabled
input.name = name
input.value = value || ''
} else {
if (input) {
input.remove()
}
}
}
}
export const renderHiddenSliderInput = (
always: boolean,
container: HTMLElement,
name: string,
value: string,
disabled: boolean
) => {
let input = container.querySelector(
`input[name="${name}"]`
) as HTMLInputElement | null
if (input) {
//update input values
input.value = value
input.disabled = disabled
input.name = name
} else {
if (always || hasShadowDom(container)) {
// doesn't exist, create it
input = container.ownerDocument!.createElement('input')
input.type = 'hidden'
input.classList.add('aux-input')
input.value = value || ''
input.disabled = disabled
input.name = name
container.appendChild(input)
}
}
}
/**
* Renders multiple hidden inputs from an array of values
* Used in multiselect
* @param always
* @param container
* @param name
* @param value
* @param disabled
*/
export const renderHiddenSelect = (
always: boolean,
container: HTMLElement,
name: string,
value: string | undefined | null | string[],
disabled: boolean
) => {
// Clear any existing hidden options. May be more performant to edit their values instead though.
let inputs = container.querySelectorAll(
'input.aux-select'
) as NodeListOf<HTMLInputElement>
if (inputs) {
for (const elem of inputs) {
elem.remove()
}
}
if (always || hasShadowDom(container)) {
if (Array.isArray(value)) {
for (const el in value) {
let input = container.ownerDocument!.createElement('input')
input.type = 'hidden'
input.classList.add('aux-select')
input.classList.add(`aux-select-${el}`)
input.disabled = disabled
input.name = name
if (value[el]) {
input.value = value[el]
}
container.appendChild(input)
}
} else {
let input = container.ownerDocument!.createElement('input')
input.type = 'hidden'
input.classList.add('aux-select')
input.classList.add(`aux-select-0`)
input.disabled = disabled
input.name = name
if (value) {
input.value = value
}
container.appendChild(input)
}
}
}
|
e8ebc41349e4a617a321e08be139f984a13e7b8e
|
TypeScript
|
imlihao/aktm-cs
|
/src/NetWork/NetMgr.ts
| 2.6875
| 3
|
/**
* 网络管理
*/
class NetMgr{
private socket=new MySocket();
private static _self:NetMgr;
public static get instance(){
if(!NetMgr._self){
NetMgr._self=new NetMgr();
}
return NetMgr._self;
}
public TcpSend(cmd:any){
let data=JSON.stringify(cmd);
console.log("message send:"+cmd.itype);
console.log(data);
this.socket.send(data);
}
}
|
e989a82135b3e1192f5ad84ec1adb8f8ac228484
|
TypeScript
|
merwaaan/tecs
|
/extra/motion.ts
| 2.984375
| 3
|
/// <reference path='../core/entity.ts' />
/// <reference path='../core/component.ts' />
/// <reference path='../lib/tween.js.d.ts' />
module Motion {
interface EasingFunction {
(k: number): number
}
interface CMotionOptions {
duration: number,
repetitions?: number,
yoyo?: boolean,
easing?: EasingFunction
}
class CMotion extends Core.Component {
private duration: number
private repetitions: number
private yoyo: boolean
private easing: EasingFunction
tween: TWEEN.Tween
current: any // TODO type
constructor(entity, options: CMotionOptions) {
super(entity)
this.duration = options.duration * 1000
this.repetitions = options.repetitions - 1 || 0
this.yoyo = options.yoyo || false
this.easing = options.easing || TWEEN.Easing.Linear.None
}
protected fromTo(from: any, to: any): TWEEN.Tween {
const that = this // Ugh...
return new TWEEN.Tween(from)
.to(to, this.duration)
.repeat(this.repetitions)
.yoyo(this.yoyo)
.easing(this.easing)
.onUpdate(function() {
that.current = this
})
.start()
// TODO remove component when over?
}
}
interface CTranslationOptions extends CMotionOptions {
from: Vec2,
to: Vec2
}
export class CTranslation extends CMotion {
constructor(entity, options: CTranslationOptions) {
super(entity, options)
this.tween = this.fromTo(
{x: options.from.x, y: options.from.y},
{x: options.to.x, y: options.to.y})
}
}
interface CRotationOptions extends CMotionOptions {
from: number,
to: number
}
export class CRotation extends CMotion {
constructor(entity, options: CRotationOptions) {
super(entity, options)
this.tween = this.fromTo(
{r: options.from},
{r: options.to})
}
}
export class SMotion extends Core.System {
protected shouldBind(entity) {
return entity.has(CTransform, CMotion)
}
update(t, dt) {
this.boundEntities.forEach((e) => {
const transform = e.get(CTransform) as CTransform
const motion = e.get(CMotion) as CMotion
motion.tween.update(t)
// TODO sometimes current is undefined
//console.log(motion.current)
// What if it has several of them??
if (motion instanceof CTranslation)
transform.localPosition = new Vec2(motion.current.x, motion.current.y)
else if (motion instanceof CRotation)
transform.localOrientation = motion.current.r
})
}
}
}
|
482b33afb5fd5db022f78f839a191d5f67470a0a
|
TypeScript
|
msafarigit/DreamApp
|
/src/app/component/course/shared/store/freezeState.ts
| 2.703125
| 3
|
// https://github.com/substack/deep-freeze
// https://github.com/immutable-js/immutable-js
// https://github.com/buunguyen/redux-freeze
function deepFreeze(obj) {
Object.freeze(obj); // root props of object freezed!
Object.getOwnPropertyNames(obj).forEach(prop => {
if (obj.hasOwnProperty(prop) && obj[prop] && typeof obj[prop] === 'object' && !Object.isFrozen(obj[prop])) {
deepFreeze(obj[prop]);
}
});
return obj;
}
export default function freezeState(store) {
return next => action => {
const result = next(action);
const state = store.getState();
deepFreeze(state);
return result;
}
}
|
6d665be968c373b28eba3918fa6d71f7fc6198c1
|
TypeScript
|
thaisjsoares/OmniLabs-Platform-Back
|
/src/modules/groups/useCases/UpdateGroup/UpdateGroupUseCase.ts
| 2.53125
| 3
|
import Groups from '@modules/groups/infra/typeorm/entities/Groups';
import IGroupsRepository from '@modules/groups/repositories/models/IGroupsRepository';
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
interface IRequest {
name: string;
description: string;
journey_id: string;
group_id: string;
}
@injectable()
class UpdateGroupUseCase {
constructor(
@inject('GroupsRepository')
private groupsRepository: IGroupsRepository,
) {}
public async execute({
group_id,
description,
journey_id,
name,
}: IRequest): Promise<Groups> {
const group = await this.groupsRepository.findById(group_id);
if (!group) {
throw new AppError('Not possible to find group');
}
group.name = name;
group.description = description;
group.journey_id = journey_id;
await this.groupsRepository.save(group);
return group;
}
}
export { UpdateGroupUseCase };
|
d70350590d22c95d60fa7a35abe5e2632f96d125
|
TypeScript
|
fengzhicool163/slot_party
|
/Client/UpGame/src/game/ui/general/LongPress.ts
| 2.765625
| 3
|
module ui {
export class LongPress extends egret.EventDispatcher {
public static BEGIN:string = 'onLongPressBegin';
public static END:string = 'onLongPressEnd';
public static ACTION:string = 'onLongPressAction';
public static TRIGGER:number = 1.5;
public static INTERVAL:number = 1;
// 第一次派发事件的触发时间。单位秒
public trigger:number = LongPress.TRIGGER;
// 派发onAction事件的时间间隔。单位秒。
public interval:number = LongPress.INTERVAL;
// 手指按住后,移动超出此半径范围则手势停止。
public holdRangeRadius:number = 50;
private _host:fairygui.GObject;
private _startPoint:egret.Point;
private _started:boolean = false;
public constructor(host:fairygui.GObject) {
super();
this._host = host;
this.trigger = LongPress.TRIGGER;
this.interval = LongPress.INTERVAL;
this.holdRangeRadius = 50;
}
public enable(value:boolean) {
if (value) {
this._host.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
this._host.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
} else {
this._host.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
this._host.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
egret.stopTick(this.onTime, this);
}
}
private onTouchBegin(e:egret.TouchEvent):void {
}
private onTouchEnd(e:egret.TouchEvent):void {
}
private onTime(time:number):boolean {
var p:egret.Point = this._host.globalToLocal(fairygui.GRoot.mouseX, fairygui.GRoot.mouseY);
return false;
}
}
}
|
b987f4315520e45e63397e6562cb366b9ba961d6
|
TypeScript
|
couchbaselabs/node-ottoman
|
/__test__/schema.types.spec.ts
| 3
| 3
|
import {
applyDefaultValue,
ArrayType,
BuildSchemaError,
DateType,
EmbedType,
getDefaultInstance,
IOttomanType,
model,
NumberType,
Schema,
SearchConsistency,
StringType,
validate,
ValidationError,
} from '../src';
import { isOttomanType } from '../src/schema/helpers';
import { startInTest } from './testData';
const validData = {
firstName: 'John',
lastName: 'Doe',
hasChild: true,
age: 23,
experience: 3,
};
const dataUnCasted = {
firstName: 'John',
lastName: 'Doe',
hasChild: true,
age: '23',
experience: '3',
};
const schemaDef = {
firstName: String,
lastName: {
type: String,
validator: {
message: 'Only letters',
regexp: new RegExp('\\w'),
},
},
hasChild: Boolean,
id: Number,
age: { type: Number, required: true },
experience: { type: Number, min: { val: 2, message: 'Min allowed is two' }, max: 4 },
};
describe('Schema Types with Strict Strategy', () => {
const schema = new Schema(schemaDef, { strict: true });
test('should allow to add the preHooks from the schema constructor', () => {
const options = {
preHooks: {
validate: (document) => console.log(document),
},
};
expect(new Schema({ name: String }, options)).toBeInstanceOf(Schema);
const options2 = {
preHooks: {
validate: [(document) => console.log(document)],
},
};
expect(new Schema({ name: String }, options2)).toBeInstanceOf(Schema);
});
test('should throw an error if the preHooks from the schema constructor is not valid', () => {
const options = {
preHooks: {
validate: 23,
},
};
// @ts-ignore
let schema = new Schema({ name: String }, options);
expect(schema).toBeInstanceOf(Schema);
expect(schema.preHooks).toEqual({});
const options2 = {
preHooks: {
validate: [12],
},
};
// @ts-ignore
schema = new Schema({ name: String }, options2);
expect(schema).toBeInstanceOf(Schema);
expect(schema.preHooks).toEqual({});
});
test('should allow to add the postHooks from the schema constructor', () => {
const options = {
postHooks: {
validate: (document) => console.log(document),
},
};
expect(new Schema({ name: String }, options)).toBeInstanceOf(Schema);
const options2 = {
postHooks: {
validate: [(document) => console.log(document)],
},
};
expect(new Schema({ name: String }, options2)).toBeInstanceOf(Schema);
});
test('should return the data according to the type defined in the schema when they are valid.', () => {
expect(validate(validData, schema)).toEqual(validData);
});
});
describe('Schema Types', () => {
class MocType {}
test('should throw an error when defining the unsupported type in schema.', () => {
const schema = { name: MocType };
expect(() => new Schema(schema)).toThrow(new BuildSchemaError(`Unsupported type specified in the property 'name'`));
});
test('should throw an error when defining auto value and default value on the same field', () => {
const schema = {
firstName: { type: String, default: 'John', auto: 'uuid' },
};
expect(() => new Schema(schema)).toThrow(
new BuildSchemaError(`Auto and default values cannot be used at the same time in property 'firstName'.`),
);
});
test('should return an instance of IOttomanType when using a valid path value', () => {
const schema = new Schema({
firstName: { type: String },
});
const firstName = schema.path('firstName');
expect(firstName).toBeDefined();
expect(isOttomanType(firstName)).toBeTruthy();
});
test('should return undefined when using a non-existent path value', () => {
const schema = new Schema({
firstName: { type: String },
});
const firstName = schema.path('lastName');
expect(firstName).toBeUndefined();
});
test('should return the data according to the type defined in the schema when they are valid.', () => {
const schema = new Schema(schemaDef);
expect(validate(validData, schema)).toEqual(validData);
expect(validate(dataUnCasted, schema)).toEqual(validData);
});
test('should apply correctly the default values', () => {
const personSchema = {
firstName: { type: String, default: 'John' },
lastName: { type: String, default: () => 'Doe' },
hasChild: { type: Boolean, default: true },
};
const obj = applyDefaultValue({}, personSchema);
const { firstName, lastName, hasChild } = obj;
expect(firstName).toBeDefined();
expect(firstName).toBe('John');
expect(lastName).toBeDefined();
expect(lastName).toBe('Doe');
expect(hasChild).toBeDefined();
expect(hasChild).toBeTruthy();
});
test('should throw an error when the validator fails', () => {
const validatorJohnName = (v) => {
if (v !== 'John') {
throw new Error('Only John is allowed');
}
};
const schema = {
firstName: { type: String, validator: validatorJohnName },
};
const data = {
firstName: 'Peter',
};
expect(() => validate(data, schema)).toThrow('Only John is allowed');
const schemaWithRegex = {
firstName: {
type: String,
validator: {
message: 'Only numbers',
regexp: new RegExp('d'),
},
},
};
expect(() => validate(data, schemaWithRegex)).toThrow(ValidationError);
});
test('should return the same schema when it is passed to create', () => {
const schema = new Schema({ name: String, hasChild: Boolean, age: { type: Number, intVal: true } });
expect(new Schema(schema)).toStrictEqual(schema);
});
test('should throw an exception when the schema has a property without type', () => {
const schema = {
name: String,
hasChild: Boolean,
age: { type: Number, intVal: true },
amount: { min: 23, max: 24 },
};
expect(() => new Schema(schema)).toThrow(new BuildSchemaError(`Unsupported type specified in the property 'min'`));
const schemaWithNull = {
name: String,
hasChild: Boolean,
amount: null,
};
expect(() => new Schema(schemaWithNull)).toThrow(new BuildSchemaError(`Property 'amount' is a required type`));
const schemaWithUndefined = {
name: String,
hasChild: Boolean,
amount: undefined,
};
expect(() => new Schema(schemaWithUndefined)).toThrow(new BuildSchemaError(`Property 'amount' is a required type`));
});
test('date type', () => {
const dateString = '2020-12-07T14:29:06.062Z';
const schema = new Schema({
created: Date,
});
const data = validate({ created: dateString }, schema);
expect(data.created).toBeDefined();
expect(data.created.toISOString()).toBe(dateString);
expect(data.created instanceof Date).toBe(true);
});
test('String -> should throw a ValidationError', () => {
const element = new StringType('name', { enum: undefined });
expect(() => element.validate({}, true)).toThrow(new ValidationError(`Property 'name' must be of type 'String'`));
});
test('Number -> should throw a ValidationError', () => {
const element = new NumberType('number');
expect(() => element.validate({}, true)).toThrow(new ValidationError(`Property 'number' must be of type 'Number'`));
});
test('Date -> should throw a ValidationError', () => {
const element = new DateType('date');
expect(() => element.validate({}, false)).toThrow(new ValidationError(`Property 'date' must be of type 'Date'`));
});
test('Array -> should throw a ValidationError', () => {
const element = new ArrayType('array', {} as IOttomanType);
expect(() => element.validate({}, false)).toThrow(new ValidationError(`Property 'array' must be of type 'Array'`));
});
test('Embed -> should throw a ValidationError', () => {
const schema = new Schema({ name: String });
const element = new EmbedType('name', schema);
expect(() => element.validate('name', true)).toThrow(
new ValidationError(`Property 'name' must be of type 'Embed'`),
);
});
});
describe('SchemaTypes -> String', () => {
const element = new StringType('name');
test('Option -> Min/Max length should throw ValidationError', async () => {
element.options = { minLength: 2 };
expect(() => element.validate('a', true)).toThrow(
new ValidationError(`Property 'name' is shorter than the minimum allowed length '2'`),
);
element.options = { maxLength: 2 };
expect(() => element.validate('aaa', true)).toThrow(
new ValidationError(`Property 'name' is longer than the maximum allowed length '2'`),
);
element.options = { maxLength: 1, minLength: 3 };
expect(() => element.validate('', true)).toThrow(
new ValidationError(`Property 'name' is shorter than the minimum allowed length '3'`),
);
element.options = { maxLength: 1, minLength: 3 };
expect(() => element.validate(11, true)).toThrow(
new ValidationError(
`Property 'name' is shorter than the minimum allowed length '3'\nProperty 'name' is longer than the maximum allowed length '1'`,
),
);
});
test('Option -> Min/Max length should throw ValidationError maxlengh', async () => {
const schema = new Schema(
{
email: { type: String, lowercase: true, maxLength: 4 },
code: { type: String, uppercase: true },
},
{ strict: false },
);
const User = model('User', schema);
try {
await User.create({
email: 'Dummy.ExamPle@Email.CoM',
code: 'asd',
});
} catch (e) {
const { message } = e as Error;
expect(e).toBeInstanceOf(ValidationError);
expect(message).toBe(`Property 'email' is longer than the maximum allowed length '4'`);
}
});
test('Option -> Uppercase/Lowercase', async () => {
element.options = { uppercase: true };
expect(element.cast('upper')).toBe('UPPER');
element.options = { lowercase: true };
expect(element.cast('LOWER')).toBe('lower');
const schema = new Schema({
email: { type: String, lowercase: true },
code: { type: String, uppercase: true },
});
const User = model('User', schema);
await startInTest(getDefaultInstance());
const user = await User.create({
email: 'Dummy.ExamPle@Email.CoM',
code: 'asd',
});
await User.removeById(user.id);
expect(user.email).toBe('dummy.example@email.com');
expect(user.code).toBe('ASD');
expect(() => new Schema({ value: { type: String, uppercase: true, lowercase: true } })).toThrow(
new BuildSchemaError(
`'lowercase' and 'uppercase' options cannot be used at the same time within property 'value' definition.`,
),
);
expect(() => new StringType('value', { uppercase: true, lowercase: true })).toThrow(
new BuildSchemaError(
`'lowercase' and 'uppercase' options cannot be used at the same time within property 'value' definition.`,
),
);
});
test('Option -> Trim', async () => {
element.options = { trim: true };
expect(element.cast(' trim trim ')).toBe('trim trim');
});
test('Null value for StringType', async () => {
const schema = new Schema({
text: { type: String },
review: { type: String },
});
const Message = model('Message', schema);
await startInTest(getDefaultInstance());
const review = 'test null value';
await Message.create({ text: null, review });
await Message.create({ text: 'hello', review: 'test' });
const result = await Message.find({ text: { $isNull: true } }, { consistency: SearchConsistency.LOCAL });
expect(result.rows.length).toBeGreaterThan(0);
expect(result.rows[0].review).toBe(review);
});
});
|
7e56cb248aa0fae49d2c5e6021dd9d781c71b63d
|
TypeScript
|
karo6774/key-parser
|
/src/key-solvers/and.key-solver.ts
| 2.859375
| 3
|
import {ParsedKey} from "../parsed-key";
import {KeySolver, solve} from "../key-solver";
export class ParsedAndKey implements ParsedKey
{
public static make(data: any[]): ParsedAndKey
{
let keys = [data[0]].concat(data[2].map((val: any[]) => val[2]));
return new ParsedAndKey(keys);
}
public solver: KeySolver = AndKeySolver;
public readonly subKeys: ParsedKey[];
public constructor(subKeys: ParsedKey[])
{
this.subKeys = subKeys;
}
}
export function AndKeySolver(parsed: ParsedAndKey, input: string[]): boolean
{
return parsed.subKeys.every(value => solve(value, input))
}
|
c74368068157b12de2e242b87348fdfb7ee2917a
|
TypeScript
|
feryadialoi/salesman-deploy
|
/src/localpersistent/impl/ProfileLocalPersistentImpl.ts
| 2.6875
| 3
|
import { Profile } from "../../models/Profile";
import { ProfileLocalPersistent } from "../ProfileLocalPersistent";
export class ProfileLocalPersistentImpl implements ProfileLocalPersistent {
setProfile(profile: Profile): void {
const profileString = JSON.stringify(profile);
console.log("profileString", profileString);
localStorage.setItem("profile", profileString);
}
getProfile(): Profile {
const profileString = localStorage.getItem("profile");
if (profileString) {
return JSON.parse(profileString) as Profile;
} else {
throw new Error();
}
}
removeProfile(): void {
localStorage.removeItem("profile");
}
}
|
ee8ae8150df5771abe763b40f7416fd474fc1f6b
|
TypeScript
|
stfmarkov/clock
|
/src/js/reducers/locationReducer.ts
| 2.640625
| 3
|
const locationReducer = (
state = {
location:"",
},
action:{type:string, payload:any}) => {
switch (action.type) {
case "SET_LOCATION":
state = {
location:action.payload,
}
break;
}
return state;
}
export default locationReducer
|
2f0bf4059816af814d421db105a14f1b7fed46e1
|
TypeScript
|
smallbatchdevs/27_stripe_checkout
|
/functions/src/sitemap/index.ts
| 2.609375
| 3
|
import admin = require('firebase-admin');
import * as functions from 'firebase-functions';
const { SitemapStream, streamToPromise } = require('sitemap');
// static routes that you can't easily get or generate from your database. i.e. /home or /login
const staticRoutes: string[] = [];
async function getDynamicRoutes(): Promise<string[]> {
return (
admin
.firestore()
.collection(`posts`)
.get()
.then((snapshot) => snapshot.docs.map((doc) => doc.data()))
// convert each document into an app route, these will be appended to 'https://smallbatchdevs.com/'
.then((posts) => posts.map((post) => `post/${post.prettyUrl}`))
);
}
export const generateSitemap = functions.https.onRequest(async (req, res) => {
const hostname = `https://smallbatchdevs.com`;
const changefreq = 'weekly'; // how often do your web pages change?
const smStream = new SitemapStream({ hostname });
streamToPromise(smStream)
.then((buffer: Buffer) => buffer.toString())
.then((xmlString: string) => {
console.log('Generated Sitemap: ', xmlString);
res.status(200).contentType('text/xml; charset=utf8').send(xmlString);
})
.catch((e: any) => {
console.log(`Error Generating Sitemap... `, e);
res.status(500).send(e);
});
console.log(`Adding Static Routes... `);
staticRoutes.forEach((url) => smStream.write({ url, changefreq }));
const dynamicRoutes = await getDynamicRoutes();
console.log(`Adding ${dynamicRoutes.length} Dynamic Routes... `);
dynamicRoutes.forEach((url) => smStream.write({ url, changefreq }));
smStream.end();
});
|
da870b29f284d1addfc7c23db85b88383b350319
|
TypeScript
|
drew-moore/rcv-widget
|
/src/app/core/state.ts
| 2.828125
| 3
|
import {Action} from "@ngrx/store";
export const CoreActions = {
ACTIVATE_POLL: '[Widget] activatePoll',
SESSION_USER_CHANGED: '[User] sessionUserChange'
};
export class ActivatePollAction implements Action {
public readonly type = CoreActions.ACTIVATE_POLL;
constructor(public readonly payload: string) {}
}
export class SessionUserChangedAction implements Action {
public readonly type = CoreActions.SESSION_USER_CHANGED;
constructor(public readonly payload: string) {}
}
export function activePoll(state: string|null = null, action: Action): string|null {
switch (action.type) {
case CoreActions.ACTIVATE_POLL:
return (action as ActivatePollAction).payload;
default:
return state;
}
}
export function sessionUser(state: string, action: Action): string {
switch (action.type) {
case CoreActions.SESSION_USER_CHANGED:
return (action as SessionUserChangedAction).payload;
default:
return state;
}
}
|
e0232710a44630283108c0d2cb5b90ca4883e83d
|
TypeScript
|
trustee-wallet/trusteeWallet
|
/app/services/Cards/Cards.ts
| 2.734375
| 3
|
/**
* @version 0.30
* @author ksu
*/
import Log from '../Log/Log'
import axios from 'axios'
export namespace Cards {
export const getCountryCode = async (cardNumber : string) => {
try {
cardNumber = cardNumber.split(' ').join('')
if (cardNumber.indexOf('220') === 0 || cardNumber.indexOf('533669') === 0) {
return '643'
}
const link = 'https://lookup.binlist.net/' + cardNumber
Log.log('Cards.getCountryCode axios ' + link)
const res = await axios.get(link)
Log.log('res', cardNumber, res.data)
return res.data.country.numeric
} catch (e) {
Log.log('Cards.getCountryCode error ' + e.message)
}
return false
}
}
|
8aac038fad74f58c1c66d30c9ab7c18a24e3359a
|
TypeScript
|
liebhartdevelopment/typescript-chat
|
/server/src/app.ts
| 2.578125
| 3
|
import WebSocket from "websocket";
import Http from "http";
import { ClientConnection } from "./clientConnection";
import { UserManager, UserData } from "./users";
import { ResponseType } from "./responsePackets";
export class Server {
// Hold all connections.
private static _connections: {
[connectionID: number]: ClientConnection;
} = {};
public static broadcast(response: any): void {
Object.values(Server._connections)
.map(x => x)
.forEach(x => x.send(response));
}
public constructor(public readonly port: number) {
// Create the http server.
let httpServer = Http.createServer(this.listenerCallback.bind(this));
// Create the websocket server and pass the http server to it.
let wsServer = new WebSocket.server({ httpServer: httpServer });
// Setup event handlers.
wsServer.on("request", this.onWebSocketRequest.bind(this));
// Listen
httpServer.listen(this.port, this.requestCallback.bind(this));
}
public static getConnectedUserIds(): number[] {
return Object.values(Server._connections)
.map(x => x.userId)
.filter(x => x !== -1);
}
public onClientDisconnected(client: ClientConnection): void {
// If client was authenticated, tell all the other clients about the disconnect.
if (client.userId !== -1) {
console.log("User disconnected: " + client.userId);
let user = UserManager.getUserDataForId(client.userId);
let message = (user ? user.name : "Someone") + " has gone offline.";
let response = {
responseType: ResponseType.CHAT_RESULT,
userData: UserData.SERVER,
content: message
};
Server.broadcast(response);
}
console.log("Connection id disconnected: " + client.connectionID);
Server._connections[client.connectionID] = undefined;
delete Server._connections[client.connectionID];
}
public onClientAuthenticated(client: ClientConnection): void {
// If the client is authenticated, tell all the other clients about the connection.
if (client.userId !== -1) {
console.log("User signed on: " + client.userId);
let user = UserManager.getUserDataForId(client.userId);
let message = (user ? user.name : "Someone") + " has come online.";
let response = {
responseType: ResponseType.CHAT_RESULT,
userData: UserData.SERVER,
content: message
};
Server.broadcast(response);
}
}
private listenerCallback(
message: Http.IncomingMessage,
response: Http.ServerResponse
): void {
// Handle HTTP requests. This will be useful for registration.
}
private requestCallback(): void {
console.log(
new Date() + " - Server started and listening on port: " + this.port
);
}
private onWebSocketRequest(request: WebSocket.request): void {
console.log(
new Date() + " - New client connection:" + request.remoteAddress
);
let connection = new ClientConnection(this, request);
Server._connections[connection.connectionID] = connection;
}
}
// Server config
process.title = "Chat Sever";
var server = new Server(5001);
|
6820b3fa7ea974459e4424323943a0bb16015758
|
TypeScript
|
dbknickerbocker/tcx-builder
|
/src/models/Activity/Activity.ts
| 2.5625
| 3
|
import { BaseObject } from '../_common';
import { ActivityAttributes } from './ActivityAttributes';
import { ActivityLap } from './ActivityLap';
import { Training } from '../Training';
import { isNil as _isNil } from 'lodash';
import { AbstractSource } from '../AbstractSource';
import { ActivityAttributeSport } from '../../interfaces';
export class Activity extends BaseObject {
public attributes: ActivityAttributes;
public Id: Date;
public Laps: ActivityLap[];
public Notes?: string;
public Training?: Training;
public Creator?: AbstractSource;
constructor(
sport: ActivityAttributeSport = 'Running',
options: {
Id: Date,
Laps: ActivityLap[],
Notes?: string,
Training?: Training,
Creator?: AbstractSource,
},
) {
super();
this.attributes = new ActivityAttributes(sport);
this.Id = options.Id;
this.Laps = options.Laps;
this.Notes = options.Notes;
this.Training = options.Training;
this.Creator = options.Creator;
}
toXml() {
let xmlElement = '';
xmlElement += BaseObject.buildXmlNode('Id', this.Id.toISOString());
if (!_isNil(this.Laps) && this.Laps.length) {
xmlElement += this.Laps
.map((_activityLap: ActivityLap) => BaseObject.buildXmlNode('Lap', _activityLap.toXml(), _activityLap.attributes))
.join('\n');
}
if (!_isNil(this.Notes)) {
xmlElement += BaseObject.buildXmlNode('Notes', this.Notes);
}
if (!_isNil(this.Training)) {
xmlElement += BaseObject.buildXmlNode('Training', this.Training.toXml(), this.Training.attributes);
}
if (!_isNil(this.Creator)) {
xmlElement += BaseObject.buildXmlNode('Creator', this.Creator.toXml(), this.Creator.attributes);
}
return xmlElement;
}
}
|
2f753ecd2841ca462496d1dfeca4fed2ac449706
|
TypeScript
|
SEKCJ/victory-gardens
|
/src/server/DB/Queries/herbs.ts
| 2.640625
| 3
|
import { Query } from "../index";
import { IVegetables } from "../../Models/index";
// returns all info for all herbs with image url
const allHerbs = async () => {
return Query<IVegetables[]>(
`SELECT herbs.name, herbs.sci_name, herbs.id, herbsimages.url
FROM herbs
JOIN herbsimages ON herbs.id = herbsimages.herbsid`
);
};
// returns all info for one herb with image url based on the veg's unique id
const oneHerbById = async (id: number) => {
return Query<IVegetables[]>(
`SELECT herbs.*, herbsimages.url
FROM herbs
JOIN herbsimages ON herbs.id = herbsimages.herbsid
WHERE id = ?`,
[id]
);
};
const herbByName = async (name: string) => {
let values = [name + "%"];
return Query<IVegetables[]>(
`SELECT herbs.name, herbs.sci_name, herbs.id, herbsimages.url
FROM herbs
JOIN herbsimages ON herbs.id = herbsimages.herbsid
WHERE name like ?`,
values
);
};
// adds a veg to vegs table
const postHerb = async (values: any) => {
return Query<IVegetables>(
"SET @@auto_increment_increment = 1; INSERT INTO herbs VALUES ?",
values
);
};
const putHerb = async (values: any, id: number) => {
return Query<IVegetables>("UPDATE herbs SET ? WHERE id =?", [
values,
id,
]);
};
const deleteHerb = (id: number) => {
return Query("DELETE FROM herbs WHERE id = ?", [id]);
};
export default {
allHerbs,
oneHerbById,
herbByName,
postHerb,
putHerb,
deleteHerb
};
|
609fa3a39f9546603b01804cd494da53cd808cc6
|
TypeScript
|
Tankerxyz/tappytanks
|
/src/components/player/PlayersController.ts
| 2.59375
| 3
|
import BABYLON, { Vector3 } from 'babylonjs';
import Player from './Player';
export default class PlayersController {
private players: Array<Player> = [];
private _scene: BABYLON.Scene;
constructor(players: Array<Player>, scene: BABYLON.Scene) {
this.players = players;
this._scene = scene;
}
public getPlayers(): Array<Player> {
return this.players;
}
public addPlayer(player: any): void {
this.players.push(new Player({...player, animatable: true, withGui: false}, this._scene));
}
public removePlayer(player: any): void {
const playerToRemove = this.players.filter(({ userID }) => userID === player.userID)[0];
this.players.splice(this.players.indexOf(playerToRemove), 1);
playerToRemove.dispose();
}
public changePlayerRotation(player: any): void {
const playerToChange = this.players.filter(({ userID }) => userID === player.userID)[0];
playerToChange.setRotation(player.rotation);
}
public changePlayerPosition(player: any): void {
const playerToChange = this.players.filter(({ userID }) => userID === player.userID)[0];
playerToChange.setPosition(player.position);
}
public removeAll(): void {
this.players.forEach((p) => this.removePlayer(p));
}
}
|
db7e907842806563840c9822a19a89fcfc1b8651
|
TypeScript
|
JonathonRichardson/typescript-error
|
/src/error.ts
| 3.4375
| 3
|
export interface Unwrappable<T> {
unwrap(): T | never
}
export interface Result<T, U extends Error> extends Unwrappable<T> {
unwrap(): T | never,
hasError(): boolean,
getError(): U
}
class OkResult<T> implements Result<T, Error> {
constructor(private readonly value: T) {}
unwrap(): T {
return this.value;
}
hasError(): boolean {
return false;
}
getError(): Error {
return undefined;
}
}
class ErrorResult<E extends Error> implements Result<any, E> {
constructor(private readonly error: E) {}
unwrap(): never {
throw this.error;
}
hasError(): boolean {
return true;
}
getError(): E {
return this.error;
}
}
export function Ok<T>(value: T): Result<T, Error> {
return new OkResult(value);
}
export function Err<E extends Error>(error: E): Result<any, E> {
return new ErrorResult(error);
}
|
84275a0dd56b531d4c1e767b6319de80b462b7e4
|
TypeScript
|
yujuiting/gaudi-editor
|
/src/editor/widget/type.ts
| 2.546875
| 3
|
import { JSONValue } from 'gaudi';
export enum WidgetType {
Icon,
Panel,
Props,
Styles,
Input,
}
interface Widget {
readonly type: WidgetType;
readonly title?: string;
}
export interface IconWidget extends Widget {
readonly type: WidgetType.Icon;
readonly id: string;
readonly group: string;
readonly render: React.JSXElementConstructor<{}>;
readonly useDisabled?: () => boolean;
}
export interface PanelWidget extends Widget {
readonly type: WidgetType.Panel;
readonly id: string;
readonly renderIcon: React.JSXElementConstructor<{}>;
readonly renderPanel: React.JSXElementConstructor<{}>;
}
export interface PropsWidget extends Widget {
readonly type: WidgetType.Props;
readonly id: string;
readonly render: React.JSXElementConstructor<{}>;
}
export interface StylesWidget extends Widget {
readonly type: WidgetType.Styles;
readonly id: string;
readonly render: React.JSXElementConstructor<{}>;
}
export interface InputWidgetProps<T> {
value?: T;
onChange?: (value: T) => void;
options?: { label: string; value: T; default?: boolean }[];
}
export interface InputWidget<T extends JSONValue = JSONValue> extends Widget {
readonly type: WidgetType.Input;
readonly forType: string;
readonly render: React.JSXElementConstructor<InputWidgetProps<T>>;
}
export type AnyWidget = IconWidget | PanelWidget | PropsWidget | StylesWidget | InputWidget<any>;
|
9ec96c50f48859d37a6541e0f5eab1cf03959442
|
TypeScript
|
topaxi/learning-cs
|
/utils/object/entries.test.ts
| 2.828125
| 3
|
import { entries } from './entries'
describe('utils/object/entries', () => {
test('should return an iterator over all own keys and properties', () => {
let parent = { foo: 'bar', baz: 'qux' }
let value = Object.create(parent)
value.foo = 'buz'
let expected = [['foo', 'buz']]
expect(Array.from(entries(value))).toEqual(expected)
})
})
|
a71b633a07fbb230c9e6d0fb8eeccaeaf71bc596
|
TypeScript
|
gornadan/myProject
|
/src/bll/packsReduser.ts
| 2.765625
| 3
|
import { Dispatch } from "redux";
import { CardPacksType, packsAPI } from "../api/api";
import { toggleIsFetching } from "./loginReducer";
// const initialState: Array<CardPacksType> = [];
const initialState = {
packs: [] as Array<CardPacksType>,
page: 1,
pageCount: 10,
cardPackTotalCount: 100,
packName: "",
sortPack: "",
};
type initialStateType = typeof initialState;
export const packsReducer = (state = initialState, action: ActionsType): initialStateType => {
switch (action.type) {
case "SET-PACKS": {
return {
...state,
packs: [...action.packs],
};
}
case "ADD-PACK-TITLE": {
return {
...state,
packs: [...action.packs, ...state.packs],
};
}
case "SET-PAGEP": {
return {
...state,
page: action.page,
};
}
case "PACKS/SET-PAGE-COUNT": {
return {
...state,
pageCount: action.pageCount,
};
}
case "SET-CARD-PACK-TOTAL-COUNT": {
return {
...state,
cardPackTotalCount: action.cardPackTotalCount,
};
}
case "SET-FILTER-PACK-NAME": {
return {
...state,
packName: action.name,
};
}
case "SET-SORT-PACKS": {
return {
...state,
sortPack: action.sortPack,
};
}
default:
return state;
}
};
//actions
const setPacks = (packs: Array<CardPacksType>) => ({ type: "SET-PACKS", packs } as const);
const addPackTitle = (packs: any) => ({ type: "ADD-PACK-TITLE", packs } as const);
const setPage = (page: number) => ({ type: "SET-PAGEP", page } as const);
export const setPageCount = (pageCount: number) => ({ type: "PACKS/SET-PAGE-COUNT", pageCount } as const);
const setCardPackTotalCount = (cardPackTotalCount: number) =>
({ type: "SET-CARD-PACK-TOTAL-COUNT", cardPackTotalCount } as const);
export const setFilterPackName = (name: string) => ({ type: "SET-FILTER-PACK-NAME", name } as const);
export const setSortPacks = (sortPack: string) => ({ type: "SET-SORT-PACKS", sortPack } as const);
export const setRangeCards = (min: number, max: number) => ({ type: "SET-RANGE-CARDS", min, max } as const);
//thunk
export const fetchPacksThunk =
(page: number, pageCount: number, sortPack: string, searchValue?: string, min?: number, max?: number) =>
(dispatch: Dispatch) => {
dispatch(toggleIsFetching(true));
packsAPI
.getPacks(page, pageCount, sortPack, searchValue, min, max)
.then((res) => {
dispatch(toggleIsFetching(false));
dispatch(setPacks(res.data.cardPacks));
dispatch(setPage(page));
dispatch(setCardPackTotalCount(res.data.cardPacksTotalCount));
})
.catch((error) => {
console.log(error);
});
};
export const addNewPack = (title: string) => (dispatch: any, getState: any) => {
dispatch(toggleIsFetching(true));
packsAPI.addNewPack(title).then(() => {
const { page, pageCount, sortPack } = getState();
dispatch(fetchPacksThunk(page, pageCount, sortPack));
dispatch(toggleIsFetching(false));
});
};
export const deletePack = (id: string) => (dispatch: any, getState: any) => {
dispatch(toggleIsFetching(true));
packsAPI.deletePack(id).then(() => {
const { page, pageCount, sortPack } = getState();
dispatch(toggleIsFetching(false));
dispatch(fetchPacksThunk(page, pageCount, sortPack));
});
};
export const updatedPacksTitle = (id: string, title: string) => (dispatch: any, getState: any) => {
dispatch(toggleIsFetching(true));
packsAPI.updatedCardsPack(id, title).then(() => {
const { page, pageCount, sortPack } = getState();
dispatch(toggleIsFetching(false));
dispatch(fetchPacksThunk(page, pageCount, sortPack));
});
};
type ActionsType =
| ReturnType<typeof setPacks>
| ReturnType<typeof addPackTitle>
| ReturnType<typeof setCardPackTotalCount>
| ReturnType<typeof setPage>
| ReturnType<typeof setPageCount>
| ReturnType<typeof setFilterPackName>
| ReturnType<typeof setSortPacks>
| ReturnType<typeof setRangeCards>;
export type fetchPacksThunkType = typeof fetchPacksThunk;
|
49a244a95b1016cb60ac3cd602c2ddc85403b3aa
|
TypeScript
|
emrahoner/html-processor
|
/src/dom/selector-comparer.spec.ts
| 2.8125
| 3
|
import { is } from './selector-comparer'
import { NamedNodeMap } from './named-node-map'
describe('Selector Comparer', () => {
describe('compares mixed selectors', () => {
it('finds equal when tag name and attribute matches', () => {
const attributes = new NamedNodeMap([
{
name: 'attr1',
value: 'value1'
},
{
name: 'attr2',
value: 'value2'
}
])
const result = is({ attributes, tagName: 'A' } as any, 'a[attr2]')
expect(result).toBe(true)
})
})
describe('compares attributes', () => {
it('finds equal without any attribute value in selector', () => {
const attributes = new NamedNodeMap([
{
name: 'attr1',
value: 'value1'
},
{
name: 'attr2',
value: 'value2'
}
])
const result = is({ attributes } as any, '[attr2]')
expect(result).toBe(true)
})
it('finds equal when value match without quotation marks', () => {
const attributes = new NamedNodeMap([
{
name: 'attr1',
value: 'value1'
},
{
name: 'attr2',
value: 'value2'
}
])
const result = is({ attributes } as any, '[attr2=value2]')
expect(result).toBe(true)
})
it('finds equal when value match with quotation marks', () => {
const attributes = new NamedNodeMap([
{
name: 'attr1',
value: 'value1'
},
{
name: 'attr2',
value: 'value2'
}
])
const result = is({ attributes } as any, '[attr2="value2"]')
expect(result).toBe(true)
})
it('finds not equal even when value match but with one quotation marks', () => {
const attributes = new NamedNodeMap([
{
name: 'attr1',
value: 'value1'
},
{
name: 'attr2',
value: 'value2'
}
])
const result = is({ attributes } as any, '[attr2="value2]')
expect(result).toBe(false)
})
})
})
|
a316198a408595c9767583ce0e761d4f14b0a5f9
|
TypeScript
|
TNOCS/csnext
|
/packages/cs-core/src/datasources/time-datasource.ts
| 2.6875
| 3
|
import { IDatasource, MessageBusService, Topics } from '..';
export class TimeDataSource implements IDatasource {
public start?: number;
public end?: number;
public focusTime?: number;
public id = 'timedatasource';
public events = new MessageBusService();
public setTimeRange(start: number, end: number) {
this.start = start;
this.end = end;
this.events.publish(Topics.TIME_TOPIC, Topics.SET_TIME_RANGE, { 'start': start, 'end': end });
}
public setFocusTime(time: number) {
this.focusTime = time;
this.events.publish(Topics.TIME_TOPIC, Topics.SET_FOCUS_TIME, time);
}
public execute?(
datasources?: { [id: string]: IDatasource },
data?: any
): Promise<TimeDataSource> {
return new Promise<TimeDataSource>((resolve, reject) => {
resolve(this);
});
}
}
|
838c5f928fcd51855d507c229cd590aff23887c1
|
TypeScript
|
vanovarderesyan/shemm-school-public
|
/src/services/warehouseService.ts
| 2.5625
| 3
|
import WarehouseDetail from '../domain/entities/WarehouseDetail';
import Warehouse from '../models/Warehouse';
import transform from '../utils/transform';
import WarehousePayload from '../domain/requests/WarehousePayload';
import * as object from '../utils/object';
import NotFoundError from '../exceptions/NotFoundError';
import config from '../config/config';
const { errors } = config;
export async function fetchAll(limit:number,offset:number): Promise<WarehouseDetail[]> {
const _warehouses = await Warehouse.fetchAll();
const warehouses = await (_warehouses).query().limit(limit).offset(offset)
const res = transform(warehouses, (warehouse: WarehouseDetail) => ({
id: warehouse.id,
name: warehouse.name,
address : warehouse.address,
code : warehouse.code,
responsible : warehouse.responsible
}))
return res;
}
export async function count(): Promise<object> {
const count = await (await Warehouse.fetchAll()).count();
return {count}
}
export async function insert(param: WarehousePayload): Promise<WarehousePayload> {
const warehouse = (await new Warehouse({ ...param }).save()).serialize();
return object.camelize(warehouse);
}
export async function getById(id: number): Promise<WarehouseDetail> {
const position = (await new Warehouse({ id: id }).fetch());
if (position) {
return position.serialize();
}
else {
throw new NotFoundError(errors.notFound);
}
}
export async function destroy(id: number): Promise<WarehouseDetail> {
const res = (await new Warehouse({ id: id }).destroy()).serialize();
return res;
}
export async function update(id: number, params: WarehousePayload): Promise<WarehouseDetail> {
const warehouse = (
await new Warehouse().where({ id: id }).save({ ...params }, { patch: true })
).serialize();
return object.camelize(warehouse);
}
|
ac66e31537cc3a15405613f46655a435dbdb03aa
|
TypeScript
|
reyronald/tabs-with-chasing-underline
|
/src/MediaDisplay.ts
| 2.671875
| 3
|
import styled from 'styled-components'
import { mediaQueries } from './mediaQueries'
const mediaDisplayMap = ['xs', 'sm', 'md', 'lg', 'xl'].reduce(
(acc, key, index, arr) => ({
...acc,
[key]: {
min: index > 0 && mediaQueries[arr[index - 1]].max`display: none`,
max:
index < arr.length - 1 &&
mediaQueries[arr[index + 1]].min`display: none`,
},
}),
{},
)
type MediaQueries = keyof typeof mediaQueries
type MediaDisplayProps = {
min?: MediaQueries
max?: MediaQueries
only?: MediaQueries
}
export const MediaDisplay = styled.div<MediaDisplayProps>`
display: initial;
${({ min }) => min && mediaDisplayMap[min].min};
${({ max }) => max && mediaDisplayMap[max].max};
${({ only }) => only && mediaDisplayMap[only].max};
${({ only }) => only && mediaDisplayMap[only].min};
`
|
4c2743eb9caa97f3087676e088e085085a56f0a1
|
TypeScript
|
robertcorponoi/fibtastic
|
/lib/index.d.ts
| 3.734375
| 4
|
/**
* Fibtastic provides methods to easily work with the Fibonacci sequence.
*
* @author Robert Corponoi <robertcorponoi@gmail.com>
*
* @version 2.0.0
*/
/**
* Get an array of the Fibonacci sequence from a specified start location to a specified end location.
*
* If only one parameter is specified, it will be assumed that only the end location is specified meaning
* the start location will be zero.
*
* Note that the term 'location' is used instead of 'index'. This is because we see the first value of the
* Fibonnaci sequence as being 0, instead of the 0th index being 0.
*
* @since 0.1.0
*
* @param {number} [start=0] The location in the Fibonacci sequence to begin retrieving values from.
* @param {number} end The location in the Fibonacci sequence to stop retrieving values from.
*
* @returns {Array} An array of values from the Fibonacci sequence from the start to end locations.
*/
export declare function sequence(start: number, end: number): Array<number>;
/**
* Get the Fibonacci value at the specified location in the Fibonacci sequence.
*
* This method uses the binet's formula which is used to find a Fibonacci value
* at a specific location without having to loop through the whole sequence.
*
* @since 0.1.0
*
* @param {number} location The location in the Fibonacci sequence to get the Fibonacci value from.
*
* @returns {number} The Fibonacci value at the specified location.
*/
export declare function value(location: number): number;
/**
* Check whether a specified value is a part of the Fibonacci sequence or not.
*
* Due to the restrictions of the inverse Binet's formula, this will return true
* if the exact location of the value can be determined in the sequence or false
* otherwise.
*
* @param {number} value The value to check if exists in the Fibonacci sequence or not.
*
* @returns {boolean|number} Return the location of the value in the Fibonacci sequence or false.
*/
export declare function isValue(value: number): (boolean | number);
|
c5249df7f6ffbfc1b257b1cd384a836b5b943f55
|
TypeScript
|
graycoreio/daffodil
|
/libs/content/src/models/block.interface.ts
| 2.65625
| 3
|
import { DaffIdentifiable } from '@daffodil/core';
/**
* A piece of static webpage content.
*/
export interface DaffContentBlock extends DaffIdentifiable {
/**
* The human-readable title for this content.
*/
title: string;
/**
* The HTML content.
*/
content: string;
}
|
921f1bfa7bc53295302630eff8312675e2d717ad
|
TypeScript
|
tanasats/SAM
|
/src/app/services/file-upload.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
} from '@angular/common/http';
//const endpoint = 'http://localhost:3000/api/v1/upload';
const endpoint = 'http://localhost:4000/upload-avatar'
@Injectable({
providedIn: 'root'
})
export class FileUploadService {
constructor(private http: HttpClient) {}
get httpOptions() {
let token = localStorage.getItem('access-token') || '';
return {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
'x-access-token': token,
}),
};
}
private handleError(error: HttpErrorResponse) {
//console.log('this is pipe(catchError()) in user.service-->');
//console.log(error);
switch (error.status) {
case 0:
return throwError('Out of service');
break;
case 400:
return throwError(error.error);
break;
default:
return throwError(error);
}
}
upload(file: File): Observable<any> {
var formData: any = new FormData();
//formData.append("name", name);
formData.append("avatar", file);
console.log (file);
return this.http
.post<any>(endpoint, formData, this.httpOptions)
.pipe(catchError(this.handleError));
}
//getFiles(): Observable<any> {
// return this.http.get(`${this.baseUrl}/files`);
//}
}
|
6a19802c6b7e33ebd90bfe0bfcb567ea4885e53c
|
TypeScript
|
tanaka-it/repofy
|
/src/protocols/filter/comparator.ts
| 2.921875
| 3
|
import { ComparatorOperatorEnum } from './comparator-operator-enum'
import { OptionsFilter } from './options-filter'
interface OptionsComparator extends OptionsFilter {
regex?: string
}
export class Comparator {
private constructor (
private readonly _operator: ComparatorOperatorEnum,
private readonly _key: string,
private readonly _value: any | any[],
private readonly _options?: OptionsComparator
) { }
get operator (): ComparatorOperatorEnum {
return this._operator
}
get key (): string {
return this._key
}
get value (): any {
return this._value
}
get values (): any[] {
if (Array.isArray(this._value)) {
return this._value
} else {
return [this._value]
}
}
getValueIndex (index: number): any {
if (Array.isArray(this._value)) {
return this._value[index]
}
return this._value
}
get options (): OptionsComparator {
return this._options
}
private static readonly builder = (operator: ComparatorOperatorEnum, key: string, value: any | any[], options?: OptionsComparator): Comparator => {
return new Comparator(operator, key, value, options)
}
static eq = (key: string, value: any, options?: OptionsFilter): Comparator => Comparator.builder(ComparatorOperatorEnum.EQ, key, value, options)
static neq = (key: string, value: any, options?: OptionsFilter): Comparator => Comparator.builder(ComparatorOperatorEnum.NEQ, key, value, options)
static eqId = (value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.EQ_ID, null, value)
static neqId = (value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.NEQ_ID, null, value)
static gt = (key: string, value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.GT, key, value)
static gte = (key: string, value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.GTE, key, value)
static lt = (key: string, value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.LT, key, value)
static between = (key: string, start: any, end: any): Comparator => Comparator.builder(ComparatorOperatorEnum.BETWEEN, key, [start, end])
static lte = (key: string, value: any): Comparator => Comparator.builder(ComparatorOperatorEnum.LTE, key, value)
static in = (key: string, value: any[], options?: OptionsFilter): Comparator => Comparator.builder(ComparatorOperatorEnum.IN, key, value, options)
static inId = (value: any[]): Comparator => Comparator.builder(ComparatorOperatorEnum.IN_ID, null, value)
static nin = (key: string, value: any[]): Comparator => Comparator.builder(ComparatorOperatorEnum.NIN, key, value)
static exists = (key: string, value: boolean): Comparator => Comparator.builder(ComparatorOperatorEnum.EXISTS, key, value)
static regex = (key: string, value: any, regex: string): Comparator => Comparator.builder(ComparatorOperatorEnum.REGEX, key, value, { regex })
static and = (comparators: Comparator | Comparator[]): Comparator => Comparator.builder(ComparatorOperatorEnum.OP_AND, null, comparators)
static not = (comparators: Comparator | Comparator[]): Comparator => Comparator.builder(ComparatorOperatorEnum.OP_NOT, null, comparators)
static nor = (comparators: Comparator | Comparator[]): Comparator => Comparator.builder(ComparatorOperatorEnum.OP_NOR, null, comparators)
static or = (comparators: Comparator | Comparator[]): Comparator => Comparator.builder(ComparatorOperatorEnum.OP_OR, null, comparators)
}
|
1b3e58040cfd11e4e8f694066e3ec5a263ab3c38
|
TypeScript
|
tcgdex/cards-database
|
/data/XY/Primal Clash/115.ts
| 2.796875
| 3
|
import { Card } from '../../../interfaces'
import Set from '../Primal Clash'
const card: Card = {
name: {
en: "Spinda",
fr: "Spinda",
es: "Spinda",
it: "Spinda",
pt: "Spinda",
de: "Pandir"
},
illustrator: "Mitsuhiro Arita",
rarity: "Common",
category: "Pokemon",
set: Set,
dexId: [
327,
],
hp: 80,
types: [
"Colorless",
],
stage: "Basic",
attacks: [
{
cost: [
"Colorless",
],
name: {
en: "Staggering Steps",
fr: "Démarche Branlante",
es: "Pasos Tambaleantes",
it: "Barcollio",
pt: "Passos Surpreendentes",
de: "Taumelnde Schritte"
},
effect: {
en: "Flip a coin. If heads, your opponent's Active Pokémon is now Confused. If tails, this Pokémon is now Confused.",
fr: "Lancez une pièce. Si c'est face, le Pokémon Actif de votre adversaire est maintenant Confus. Si c'est pile, ce Pokémon est maintenant Confus.",
es: "Lanza 1 moneda. Si sale cara, el Pokémon Activo de tu rival pasa a estar Confundido. Si sale cruz, este Pokémon pasa a estar Confundido.",
it: "Lancia una moneta. Se esce testa, il Pokémon attivo del tuo avversario viene confuso. Se esce croce, questo Pokémon viene confuso.",
pt: "Jogue uma moeda. Se sair cara, o Pokémon Ativo do seu oponente ficará Confuso. Se sair coroa, esse Pokémon ficará Confuso.",
de: "Wirf 1 Münze. Bei \"Kopf\" ist das Aktive Pokémon deines Gegners jetzt verwirrt. Bei \"Zahl\" ist dieses Pokémon jetzt verwirrt."
},
},
{
cost: [
"Colorless",
],
name: {
en: "Uproar",
fr: "Brouhaha",
es: "Alboroto",
it: "Baraonda",
pt: "Tumulto",
de: "Aufruhr"
},
effect: {
en: "This attack does 10 damage to each of your opponent's Pokémon. (Don't apply Weakness and Resistance for Benched Pokémon.)",
fr: "Cette attaque inflige 10 dégâts à chacun des Pokémon de votre adversaire. (N'appliquez ni la Faiblesse ni la Résistance aux Pokémon de Banc.)",
es: "Este ataque hace 10 puntos de daño a cada uno de los Pokémon de tu rival. (No apliques Debilidad y Resistencia a los Pokémon en Banca).",
it: "Questo attacco infligge 10 danni a ciascuno dei Pokémon del tuo avversario. Ricorda che non puoi applicare debolezza e resistenza ai Pokémon in panchina.",
pt: "Este ataque causa 10 de danos a cada Pokémon do seu oponente. (Não aplique Fraqueza e Resistência a Pokémon no Banco.)",
de: "Dieser Angriff fügt jedem Pokémon deines Gegners 10 Schadenspunkte zu. (Wende Schwäche und Resistenz bei Pokémon auf der Bank nicht an.)"
},
},
],
weaknesses: [
{
type: "Fighting",
value: "×2"
},
],
retreat: 1,
}
export default card
|
3567002e431c58c0c7fbf095b47896164b4eb6c7
|
TypeScript
|
NativeStream/jarviscript
|
/src/interfaces/cli/commands/player/Goto.ts
| 2.5625
| 3
|
import { EventData } from "../../../../app";
import Command, { iEventDatas } from "../../classes/Command";
import playerEvents from "../../../../interfaces/player/events";
class Goto extends Command {
public help: string = "Vai para a música no indice indicado";
public validate(eventData: EventData, args: string): boolean {
const number = parseInt(args);
return !isNaN(number);
}
public async retrive(
eventData: EventData,
args: string
): Promise<iEventDatas> {
const number = parseInt(args);
return {
eventData: {
...eventData,
data: number,
},
event: playerEvents.request.REQUEST_PLAYER_GOTO,
};
}
}
export default {
GOTO: new Goto(),
};
|
d2127ce4b5b665a9674960cf9840c546de7c6221
|
TypeScript
|
wolfzxcv/Pokemon-shop
|
/src/utils/currency.ts
| 2.75
| 3
|
export function currency(num: number) {
const n = Number(num);
return `$${n.toFixed(0).replace(/./g, (c, i, a) => {
const currency =
i && c !== '.' && (a.length - i) % 3 === 0
? `, ${c}`.replace(/\s/g, '')
: c;
return currency;
})}`;
}
|
967cf0e1939ab1167edf9a8a9a43cf4caac55ba5
|
TypeScript
|
Webiks/MapMip
|
/src/app/map-mip/position-form/color-picker/color-picker.pipe.ts
| 2.671875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'colorPicker'
})
export class ColorPickerPipe implements PipeTransform {
transform(value: any[], iconsPerRow = 1): any {
// if(iconsPerRow === 1) {
// return value;
// }
let rowsArray = [];
let rowArray = [];
value.forEach((value, index, array) => {
rowArray.push(value);
if ((index + 1) % iconsPerRow === 0) {
rowsArray.push(rowArray);
rowArray = [];
} else if (index === (array.length - 1)) {
rowsArray.push(rowArray);
}
});
return rowsArray;
}
}
|
b5315ad338557dd52886380aa2b9bb938edb80be
|
TypeScript
|
AndreLuizPedroBotelho/controlreg-backend
|
/src/modules/sales/tests/CompanyTest.ts
| 2.625
| 3
|
import faker from 'faker';
import { CompanyFactory } from '../factories/CompanyFactory';
import { createTypeormConn, deleteTypeormConn } from '../../../shared/typeorm';
import { Company } from '../entities/Company';
import CompanyController from '../controllers/CompanyController';
let companyController: CompanyController;
let companyFactory: CompanyFactory;
describe('CompanyTest', () => {
beforeAll(async () => {
await createTypeormConn();
});
afterAll(async () => {
await deleteTypeormConn();
});
beforeEach(() => {
companyController = new CompanyController();
companyFactory = new CompanyFactory();
});
it('should be able to create company', async () => {
const company = await companyFactory.create(companyController);
expect(company).toHaveProperty('id');
});
it('should be able to update company', async () => {
const company = await companyFactory.create(companyController);
company.name = faker.company.companyName();
const response = await companyController.update(company, company.id);
expect(response.name).toBe(company.name);
expect(response.id).toBe(company.id);
});
it("shouldn't be able to update company", async () => {
const company = new Company();
company.name = faker.company.companyName();
await expect(companyController.update(company, 0)).rejects.toBeInstanceOf(
Error
);
});
it('should be able to delete company', async () => {
const company = await companyFactory.create(companyController);
const response = await companyController.delete(company.id);
expect(response).toEqual('Company was delete');
});
it("shouldn't be able to delete company", async () => {
await expect(companyController.delete(0)).rejects.toBeInstanceOf(Error);
});
it('should be able to list one company', async () => {
const company = await companyFactory.create(companyController);
const response = await companyController.show(company.id);
expect(response).toEqual(company);
});
it("shouldn't be able to list one company", async () => {
await expect(companyController.show(0)).rejects.toBeInstanceOf(Error);
});
it('should be able to list all company', async () => {
const company1 = await companyFactory.create(companyController);
const company2 = await companyFactory.create(companyController);
const company3 = await companyFactory.create(companyController);
const companies = await companyController.index();
expect(companies).toEqual(
expect.arrayContaining([company1, company2, company3])
);
});
});
|
d6fe97e0740d761c6b109d2657959fa299a16e40
|
TypeScript
|
Lisianthus-A/leetcode-js
|
/answers/0001-0500/0451. 根据字符出现频率排序.ts
| 3.78125
| 4
|
function frequencySort(s: string): string {
// 统计字符出现次数
const counts: Record<string, number> = {};
for (let i = 0, len = s.length; i < len; ++i) {
const char = s[i];
counts[char] = counts[char] + 1 || 1;
}
// 二分法排序
const array: Array<string> = [];
const find = (char: string): number => {
let left = 0, right = array.length - 1;
const count = counts[char];
while (left <= right) {
const mid = left + right >> 0;
const midChar = array[mid];
if (count === counts[midChar]) {
return mid;
}
if (count > counts[midChar]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
// 按字符出现次数组成降序数组
for (let char in counts) {
const count = counts[char];
const lastChar = array[array.length - 1];
if (counts[lastChar] >= count) {
array.push(char);
} else {
const index = find(char);
array.splice(index, 0, char);
}
}
return array.reduce((acc, cur) => acc + cur.repeat(counts[cur]), '');
};
|
727668b7696f2f134b1f59fd8a9eccd5791e941a
|
TypeScript
|
wuxj00/webpaint-typescript
|
/src/plugins/DataModel.ts
| 2.578125
| 3
|
import VectorTree from '../collections/VectorTree';
const store = new Map();
const treeStore = new VectorTree();
export function get(id: string) {
return store.get(id);
}
export function add(id: string, data: any) {
// treeStore.add(data);
return store.set(id, data);
}
export function forEach(callback: (param: any) => void) {
store.forEach(callback);
}
export function getVectorTree() {
return treeStore;
}
|
e9cb9907a3c87f09c64b39c1eab22a63f64da7a4
|
TypeScript
|
kurone-kito/dantalion
|
/packages/dantalion-i18n/src/build/specialized.ts
| 2.796875
| 3
|
import type {
LifeBase,
Motivation,
Personality,
} from '@kurone-kito/dantalion-core';
import type { DetailAccessor } from '../resources/createGenericAccessor';
import type { DetailsBaseType, VectorType } from '../resources/types';
import article from './article';
import { line, list } from './list';
/**
* Create the Markdown from the LifeBase resources.
* @param resource The resource of tne LifeBase.
* @param source The source.
*/
export const fromLifeBase = (
{
getByKey,
getCategoryDetail,
}: DetailAccessor<DetailsBaseType<string[]>, LifeBase, string>,
source: LifeBase
): string => {
const { detail, name } = getByKey(source);
return line(
article({ body: name, head: getCategoryDetail(), level: 2 }),
list(...detail)
);
};
/**
* Create the Markdown from the Motivation resources.
* @param resource The resource of tne motivation.
* @param source The source.
*/
export const fromMotivation = (
{ getByKey, getCategoryDetail }: DetailAccessor<string, Motivation, string>,
source: Motivation
): string =>
article({ body: getByKey(source), head: getCategoryDetail(), level: 2 });
/**
* Create the Markdown from the Potential resources.
* @param accessor The accessor of the Potential.
* @param source The source.
*/
export const fromPotential = (
accessor: DetailAccessor<readonly string[], Personality['potentials']>,
source: Personality['potentials']
): string => {
const desc = accessor.getCategoryDetail();
return line(
article({ body: desc.detail, head: desc.name, level: 2 }),
list(...accessor.getByKey(source))
);
};
/**
* Create the Markdown from the vector resources.
* @param description The resource of tne description.
* @param source The source.
*/
export const fromVector = (description: string, source: VectorType): string =>
line(
article({ head: source.name, body: list(...source.detail), level: 3 }),
article({ head: description, body: list(...source.strategy), level: 4 })
);
|
1a61627fe26fbf2dd39112757c2d5c5da573db56
|
TypeScript
|
ijdickinson/deno-experiments
|
/data-generation.ts
| 2.984375
| 3
|
import parse from 'https://deno.land/x/date_fns@v2.22.1/parse/index.js'
/**
* Goal: read a file of texttual data, and generate a JSON file that
* encodes the data in a more regular form.
*/
interface SightingsData {
species: string
quant?: string
location: string
date: string
time?: string
spotter: string
}
const LINE_MATCHER = /(?<species>[^\(]*)(\(x(?<quant>[0-9]+)\))? - (?<location>[^0-9]*)( at (?<time>.*))? on (?<date>.*) by (?<spotter>.*)/
async function readLines(source: string) {
const sourceData = await Deno.readTextFile(source)
return sourceData.trim().split('\n')
}
function parseLine(line: string): SightingsData | undefined {
return line.match(LINE_MATCHER)?.groups as (SightingsData | undefined)
}
function asData(data: SightingsData) {
return {
species: data.species.trim(),
quantity: parseInt(data.quant || '1'),
location: data.location.trim(),
spotter: data.spotter.trim(),
date: parse(data.date, 'd LLLL yyyy', new Date(), {}),
time: data.time
}
}
readLines('./sightings-data.txt')
.then(async lines => {
const sightingsJson = lines.map(line => {
const data = parseLine(line)
return data ? asData(data) : `Unparsed: ${line}`
})
await Deno.writeTextFile(
'./sightings-data.json',
JSON.stringify(sightingsJson, null, 2)
)
console.log('Success.')
})
|
2626f93d8eec5ffb8e51b5f4086628ccde9810b6
|
TypeScript
|
Rumbleship/acl
|
/src/permissions-matrix.ts
| 3.140625
| 3
|
import { Registry } from '@rumbleship/oid';
import { Resource, Actions, Roles } from './types';
import { OneToUniqueManyMap } from './utils/one-to-unique-many-map';
/**
* Lookup table that maps OidScopes to the Authorizable Resource; critical because
* both OidScopes:Buyer|Supplier are treated as the samee core Authorizable(Division)
*/
export const ResourceAsScopesSingleton = new Map<string | Resource, Resource>([
[Registry.Buyer.name, Resource.Division],
[Registry.Supplier.name, Resource.Division],
[Resource.Division, Resource.Division],
// Strictly speaking these last two collide; opting to include for clarity.
[Registry.User.name, Resource.User],
[Resource.User, Resource.User]
]);
export class ResourceActionsMap extends OneToUniqueManyMap<Resource, Actions> {}
export class Permissions extends Map<Roles, ResourceActionsMap> {
/**
*
* @param param0 an association of Role:Resource:Actions that should be allowed
*/
allow({ role, at, to }: AllowRoleAtTo): void {
const resource = ResourceAsScopesSingleton.get(at) as Resource;
const resourceActions = this.get(role) || new ResourceActionsMap();
resourceActions.add(resource, to);
this.set(role, resourceActions);
}
/**
*
* @param param0 an association of Role:Resource:Actions that will be queried
*/
allows({ role, at, to }: AllowRoleAtTo): boolean {
const resource = ResourceAsScopesSingleton.get(at) as Resource;
const allowedActionsPerResource = this.get(role);
const actions = allowedActionsPerResource.get(resource);
let allowed = false;
for (const action of new Set<Actions>(Array.isArray(to) ? to : [to])) {
if (actions.has(action)) {
allowed = true;
break;
}
}
return allowed;
}
/**
* @param role the role to query underlying map
* @returns either the previously set ResourceActionsMap or a newly instantiated one for typesafety
*/
get(role: Roles): ResourceActionsMap {
return super.get(role) || new ResourceActionsMap();
}
}
/**
* Role: The role to be applied to the Resource
* Resource: The authorizable Resource to be considered
* To: An action or list of actions that can JWTs representing {role} at {resource} can take
*
* @example
* `{ role: Roles.User, at: Resource.Division, to: [Actions.READ]}`
* means a User of a Division can READ
*/
export interface AllowRoleAtTo {
role: Roles;
at: Resource | string;
to: Actions | Actions[];
}
|
437436e24418ce1d87836d3c5953d5dbae2b8635
|
TypeScript
|
KevReece/Dungeon
|
/src/app/model/celloccupiers/enemy.model.ts
| 3.015625
| 3
|
import { Fighter } from './fighter.model';
import { Direction } from '../direction.model';
import { FactoryService } from 'src/app/services/factory.service';
import { Cell } from '../cell.model';
import { DirectionHelper } from '../direction-helper';
import { Character } from './character.model';
import { FightService } from 'src/app/services/fight.service';
import { UserConsoleService } from 'src/app/services/user-console.service';
export abstract class Enemy extends Fighter {
name: string;
health: number;
attack: number;
defence: number;
damage: number;
experienceValue: number;
direction: Direction;
awarenessDistance: number;
constructor(
private factoryService: FactoryService,
private fightService: FightService,
private userConsoleService: UserConsoleService) {
super();
this.direction = factoryService.createRandomInteger(Direction.Up, Direction.Left);
}
die(): void {
if (this.cell) {
this.cell.occupier = null;
}
this.userConsoleService.writeEnemyDied(this);
}
turnRightDirection(): Direction {
return DirectionHelper.rotateRight(this.direction);
}
turnLeftDirection(): Direction {
return DirectionHelper.rotateLeft(this.direction);
}
backDirection(): Direction {
return DirectionHelper.opposite(this.direction);
}
act(character: Character): void {
if (this.cell.getDistance(character.cell) < 1.5) {
this.fightService.attack(this, character);
} else {
this.move(character);
}
}
private move(character: Character) {
let directionToMoveIn: Direction;
if (this.cell.getDistance(character.cell) <= this.awarenessDistance) {
directionToMoveIn = this.chaseDirection(character);
} else {
directionToMoveIn = this.wanderDirection();
}
let cellToMoveTo: Cell;
if (directionToMoveIn != null) {
cellToMoveTo = this.cell.getAdjacentCell(directionToMoveIn);
}
if (cellToMoveTo && !cellToMoveTo.isOccupied()) {
cellToMoveTo.setOccupier(this);
this.direction = directionToMoveIn;
}
}
private chaseDirection(character: Character) {
const rowDifference = character.cell.rowIndex - this.cell.rowIndex;
const columnDifference = character.cell.columnIndex - this.cell.columnIndex;
const verticalDirection = rowDifference === 0 ? null : rowDifference > 0 ? Direction.Down : Direction.Up;
const horizontalDirection = columnDifference === 0 ? null : columnDifference > 0 ? Direction.Right : Direction.Left;
const haveVerticalOption = verticalDirection != null && !this.cell.isAdjacentCellOccupied(verticalDirection);
const haveHorizontalOption = horizontalDirection != null && !this.cell.isAdjacentCellOccupied(horizontalDirection);
if (!haveVerticalOption) {
return haveHorizontalOption ? horizontalDirection : null;
}
if (!haveHorizontalOption) {
return verticalDirection;
}
const sumDifference = Math.abs(columnDifference) + Math.abs(rowDifference);
const randomFromSum = this.factoryService.createRandomInteger(1, sumDifference);
if (randomFromSum <= Math.abs(columnDifference)) {
return horizontalDirection;
}
return verticalDirection;
}
private wanderDirection() {
const weightedOptions = this.factoryService.createWeightedOptions();
if (!this.cell.isAdjacentCellOccupied(this.direction)) {
weightedOptions.add(this.direction, 6);
}
if (!this.cell.isAdjacentCellOccupied(this.turnRightDirection())) {
weightedOptions.add(this.turnRightDirection(), 2);
}
if (!this.cell.isAdjacentCellOccupied(this.turnLeftDirection())) {
weightedOptions.add(this.turnLeftDirection(), 2);
}
if (!this.cell.isAdjacentCellOccupied(this.backDirection())) {
weightedOptions.add(this.backDirection(), 1);
}
weightedOptions.add(null, 1);
return weightedOptions.choose();
}
}
|
dabedde204ddea49f10a7849ad0af4af32582a64
|
TypeScript
|
pcholuj/ecs-deploy
|
/src/deployers/adapter/adapter.interface.ts
| 2.515625
| 3
|
import { Applications } from 'api/applications/applications.entity';
export interface DeployersVersions {
name: string;
tag: string;
config?: any;
}
export interface DeployersStatus {
name: string;
tag: string;
status: number;
}
export interface AdapterInterface {
name: string;
deploy(application: Applications, tag: string, config: any);
status(application: Applications);
versions(application: Applications);
}
|
2c5d7e2620733a44edafa5fba4fe8725fe40be22
|
TypeScript
|
tyblue/blog
|
/code/accumulate/design-pattern/strategy.ts
| 3.359375
| 3
|
abstract class Strategy {
public abstract method()
}
class Strategy_1 extends Strategy {
constructor() {
super();
}
method() {
console.log('strategy_1')
}
}
class Strategy_2 extends Strategy {
constructor() {
super();
}
method() {
console.log('strategy_2')
}
}
class Context {
private strategy: Strategy;
constructor(strategy: Strategy) {
this.strategy = strategy;
}
setStrategy(strategy: Strategy) {
this.strategy = strategy;
}
getStrategy() {
return this.strategy;
}
method() {
this.strategy.method();
}
}
// test
const context = new Context(new Strategy_1());
context.method();
context.setStrategy(new Strategy_2());
context.method();
// knockout中的模板引擎采用的策略模式,默认使用原生模板引擎,检测到有jquery.tml时设置使用jquery的模板引擎
// 1. 定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。
// 2. 使用和实现分离,策略类的使用放在环境类中,算法实现放在具体的策略类中
// 低耦合 高扩展
|
a48be01aad16bdb32ff2e398b266fd1aa1bb51ff
|
TypeScript
|
nwtgck/egghead-todo-typescript-react
|
/src/reducers.ts
| 2.53125
| 3
|
import {combineReducers, Reducer} from "redux";
import {reducerWithInitialState} from "typescript-fsa-reducers";
import {List} from "immutable";
import {TodoItem} from "./datatypes";
import * as actionCreators from "./actionCreators";
import {Filter} from "./actionCreators";
import {typeSafeCombineReducers} from "./type_safe_util";
export const todosReducer = reducerWithInitialState<List<TodoItem>>(List<TodoItem>())
.case(actionCreators.addTodo, (state, payload) => {
return state.push(new TodoItem(
payload.id,
payload.text,
false
))
})
.case(actionCreators.toggleTodo, (state, payload) => {
return state
.map((item) => {
if(item.id === payload.id) {
return item.mapCopy({completed: prev => !prev})
} else {
return item;
}
})
.toList();
});
export const visibilityFilterReducer = reducerWithInitialState<Filter>("SHOW_ALL")
.case(actionCreators.setVisibilityFilter, (state, payload) => {
return payload.filter;
});
export const todoAppReducer = typeSafeCombineReducers({
todos : todosReducer,
visibilityFilter: visibilityFilterReducer
});
|
04ebd5fa0c8921a12217e9e0f2d2337b6644bacd
|
TypeScript
|
tumiMsaki/LeetCode-Recording
|
/leetcode/70.ts
| 4.03125
| 4
|
/** 爬楼梯 递归方式
* @param {number} n
* @return {number}
*/
var climbStairs = function(n: number): number{
if (n === 1) {
return 1
}
if (n === 2) {
return 2
}
return climbStairs(n - 1) + climbStairs(n - 2)
};
console.log(climbStairs(10))
/** 爬楼梯 非递归
* @param {number} n
* @return {number}
*/
var FclimbStairs = function(n: number): number{
if (n === 1) {
return 1
}
if (n === 2) {
return 2
}
let pre = 1
let preT = 2
let current = 0
for (let i = 2; i < n; i++) {
current = pre + preT
pre = preT
preT = current
}
return current
};
console.log(FclimbStairs(10))
|
164717b88ea68fb0a2133378cad170c85b3894e3
|
TypeScript
|
jmcknight-clgx/Initiate
|
/initiate.angular/src/app/models/stats.spec.ts
| 3.03125
| 3
|
import { Stats } from "./stats";
describe('stats', () => {
describe("CalculateMod", () => {
it("should return 0 when stat is 11", () => {
let target = new Stats();
target.Strength = 11;
expect(target.StrengthMod).toBe(0);
});
it("should return -1 when stat is 9", () => {
let target = new Stats();
target.Dexterity = 9;
expect(target.DexterityMod).toBe(-1);
});
it("should return 2 when stat is 15", () => {
let target = new Stats();
target.Charisma = 15;
expect(target.CharismaMod).toBe(2);
});
it("should return 3 when stat is 16", () => {
let target = new Stats();
target.Constitution = 16;
expect(target.ConstitutionMod).toBe(3);
});
it("should return 0 when stat is undefined", () => {
let target = new Stats();
target.Constitution = undefined;
expect(target.ConstitutionMod).toBe(0);
});
});
});
|
7cd7da8848fd005e05c4a7de376b59365a757d7d
|
TypeScript
|
nutanix/papiea
|
/papiea-backend-utils/src/axios_response_parser.ts
| 2.890625
| 3
|
export class AxiosResponseParser {
public static getAxiosErrorResponse(err: any): any | null {
if (err) {
if (err.response) {
return err.response
}
console.info("Received null/undefined value for error response")
} else {
console.info("Received null/undefined value for axios error")
}
return null
}
public static getAxiosResponseData(err: any): any | null {
const response = AxiosResponseParser.getAxiosErrorResponse(err)
if (response) {
if (response.data) {
return response.data
}
console.info("Received null/undefined value for response data")
}
return null
}
public static getAxiosResponseStatus(err: any): number {
const response = AxiosResponseParser.getAxiosErrorResponse(err)
if (response) {
if (response.data) {
return response.status
}
console.info("Received null/undefined value for response status")
}
return 500
}
public static getAxiosError(err: any): any | null {
const data = AxiosResponseParser.getAxiosResponseData(err)
if (data) {
if (data.error) {
return data.error
}
console.info("Recieved null/undefined for data error")
}
return null
}
public static getAxiosErrorCode(err: any): number {
const axios_error = AxiosResponseParser.getAxiosError(err)
if (axios_error) {
if (axios_error.code) {
return axios_error.code
}
console.info("Received null/undefined value for error code")
}
return 500
}
public static getAxiosErrorContext(err: any): any | null {
const axios_error = AxiosResponseParser.getAxiosError(err)
if (axios_error) {
if (axios_error.papiea_context) {
return axios_error.papiea_context
}
console.info("Received null/undefined value for papiea context")
}
return null
}
public static getAxiosErrorDetails(err: any): any | null {
const axios_error = AxiosResponseParser.getAxiosError(err)
if (axios_error) {
if (axios_error.error_details) {
return axios_error.error_details
}
console.info("Received null/undefined value for error details")
}
return null
}
public static getAxiosErrorMessage(err: any): string {
const axios_error_details = AxiosResponseParser.getAxiosErrorDetails(err)
if (axios_error_details) {
if (axios_error_details.message) {
return axios_error_details.message
}
console.info("Received null/undefined value for error message")
}
return ''
}
}
|
69ca73382325fffa56afadc9dda8a72262c3abc7
|
TypeScript
|
6thquake/react-material
|
/packages/material-ui/core/src/styles/createPalette.spec.ts
| 2.578125
| 3
|
import { Color } from '@material-ui/core';
import blue from '@material-ui/core/colors/blue';
import createPalette, {
PaletteColorOptions,
SimplePaletteColorOptions,
} from '@material-ui/core/styles/createPalette';
{
const palette = createPalette({});
const color: Color = blue;
const option: SimplePaletteColorOptions = { main: blue[400] };
const colorOrOption: PaletteColorOptions = undefined as any;
palette.augmentColor(color);
palette.augmentColor(color, 400);
palette.augmentColor(color, 400, 200, 600);
palette.augmentColor(color, 400, undefined, 600);
palette.augmentColor(option);
palette.augmentColor(option, 400); // $ExpectError
palette.augmentColor(colorOrOption);
palette.augmentColor(colorOrOption, 400); // $ExpectError
}
|
54c4d029213cd05c843e89b1ae5500048f24a37f
|
TypeScript
|
ChristianKohler/styled-webcomponents
|
/src/params.ts
| 2.859375
| 3
|
const bracesRegex = /(\(|\))/g;
export function extractDestructuredParams(fnAsString: string) {
const fnParams = extractFnParams(fnAsString);
if (fnParams.length === 1) {
const pattern = new RegExp(`${fnParams[0]}\\.(\\w+)`, "gm");
const paramMatches = fnAsString.match(pattern);
return paramMatches
? paramMatches.map(p => p.replace(`${fnParams[0]}.`, ""))
: [];
} else {
return [];
}
}
export function extractFnParams(fnAsString: string) {
const isArrowFunction = fnAsString.indexOf("function") !== 0;
const paramPart = (isArrowFunction
? getParamPartFromArrowFn(fnAsString)
: getParamFromFn(fnAsString)
).trim();
return paramPart
.split(",")
.filter(x => x !== "")
.map(x => x.trim());
}
function getParamPartFromArrowFn(fnString: string) {
return fnString.split("=>")[0].replace(bracesRegex, "");
}
function getParamFromFn(fnString: string) {
return fnString.split(bracesRegex)[2];
}
|
fb6f5c725817549fd93abc4cb964ffb92edddf38
|
TypeScript
|
ringcentral/ringcentral-js-widgets
|
/crius/packages/crius-runner/src/runner.ts
| 2.875
| 3
|
/* eslint-disable @typescript-eslint/no-use-before-define */
import { CriusNode, Children, StepFunction, CriusElement } from 'crius';
import {
isCriusNode,
isCriusStep,
isCriusStepClass,
isCriusStepFunction,
} from 'crius-is';
import { runWithLifecycle } from './lifecycle';
import { handleContext } from './context';
async function iterateChildren<C>(
children: Children,
context?: C,
): Promise<void> {
for (const child of children) {
if (isCriusStepFunction(child)) {
const result = await child({}, context!);
if (isCriusNode(result)) {
await run(result as CriusNode, context);
}
} else if (isCriusNode(child)) {
await run(child as CriusNode, context);
} else if (Array.isArray(child)) {
await iterateChildren(child, context);
} else if (typeof child !== 'undefined') {
console.warn(
`Unexpected Error Crius Step Type: ${child} in ${children.map(
(i) => i?.key,
)}.`,
);
// throw new Error(
// `Unexpected Error Crius Step Type: ${child} in ${children}.`,
// );
}
}
}
/**
* Run A CriusNode
Run flow with Crius Fragment.
For example:
<>
<Bar bar='bar' />
<FooBar fooBar='fooBar' />
</>
It will parser to:
{
key: '',
props: {
children: [
{
key: '',
props: { children: [], bar: 'bar' },
step: Bar
},
{
key: '',
props: { children: [], fooBar: 'fooBar' },
step: FooBar
}
]
}
step: undefined
}
* @param CriusNode
*/
async function run<P = {}, C = {}>(
{
step: Step,
// key: Key,
props,
}: CriusNode<P, C>,
_context?: C,
) {
const context = handleContext(_context);
if (isCriusStep(Step)) {
let nextStep: CriusElement;
let afterLifecycleAction;
if (isCriusStepClass(Step)) {
const step = new Step(props, context);
await context.beforeEach?.(props, context, Step);
[nextStep, afterLifecycleAction] = await runWithLifecycle(step);
} else {
const step: StepFunction = Step;
await context.beforeEach?.(props, context, step);
nextStep = await Step(props, context);
}
if (nextStep) {
if (typeof nextStep === 'function') {
await nextStep();
} else if (isCriusNode(nextStep)) {
await run(nextStep, context);
} else if (Array.isArray(nextStep)) {
await iterateChildren(nextStep, context);
} else {
// Ignore other type
}
}
if (isCriusStepClass(Step) && typeof afterLifecycleAction === 'function') {
await afterLifecycleAction();
}
await context.afterEach?.(props, context, Step);
} else if (Array.isArray(props.children)) {
await iterateChildren(props.children as Children, context);
}
}
export { run };
|
cf551ed7af029e645da2963c270e1d907997760c
|
TypeScript
|
Nolanus/ngx-multi-window
|
/projects/ngx-multi-window/src/lib/types/window.type.ts
| 3.046875
| 3
|
import { Message } from './message.type';
export interface WindowData {
heartbeat: number;
id: string;
name: string;
}
export interface KnownAppWindow extends WindowData {
stalled: boolean;
self: boolean;
}
/**
* Represents a window with the current application how it is stored
* in the localstorage. It has an id, name, heartbeat represented in a timestamp
* and an array of messages that that window sent out.
*
* It's named "AppWindow" to avoid confusion with the type Window
* of the global variable "window".
*/
export interface AppWindow extends WindowData {
messages: Message[];
}
|
95344e9f270e045dfdedc0a22ef766463a968047
|
TypeScript
|
morrys/wora
|
/packages/redux/src/createStore.ts
| 2.546875
| 3
|
import $$observable from 'symbol-observable';
import Cache, { ICache, CacheOptions, mutateKeysLayer, prefixLayer, DataCache } from '@wora/cache-persist';
import isPlainObject from './redux/utils/isPlainObject';
import ActionTypes from './redux/utils/actionTypes';
import { filterKeys } from '@wora/cache-persist/lib/layers/filterKeys';
export const REHYDRATE = `@@redux/REHYDRATE`; // added
export const REHYDRATE_ERROR = `@@redux/REHYDRATE_ERROR`; // added
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [preloadedState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} [enhancer] The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
export type CacheOptionsRedux = CacheOptions & {
version?: number;
key?: string;
whitelist?: Array<string>;
blacklist?: Array<string>;
migrate?: (s: any, v: number) => Promise<any>;
stateReconciler?: (s: any, o: any, r: any, c: any) => any;
};
function createStore(reducer: any, preloadedState?: any, enhancer?: any, persistOptions?: CacheOptionsRedux) {
//TODO TYPING
if (
(typeof preloadedState === 'function' && typeof enhancer === 'function') ||
(typeof enhancer === 'function' && typeof arguments[3] === 'function')
) {
throw new Error('CREATE1');
}
if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
enhancer = preloadedState;
preloadedState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('CREATE2');
}
return enhancer(createStore)(reducer, preloadedState, undefined, persistOptions);
}
if (typeof reducer !== 'function') {
throw new Error('CREATE3');
}
let promiseRestore;
const {
disablePersist = !persistOptions,
version = -1,
key = 'root', // TODO verify
whitelist = undefined,
blacklist = undefined,
mutateKeys = undefined,
mutateValues = undefined,
migrate = (s: any, v: number) => Promise.resolve(s),
stateReconciler = (s: any, o: any, r: any, c: any) => s,
} = persistOptions || {};
const prefix = `persist:${key}`;
const reduxPersistKey = `redux-persist`;
const migrateReduxPersistKey = mutateKeysLayer(
(key) => (key === `${prefix}.${reduxPersistKey}` ? prefix : key),
(key) => (key === prefix ? `${prefix}.${reduxPersistKey}` : key),
);
const internalMutateKeys = [migrateReduxPersistKey, prefixLayer(prefix)];
if (whitelist) {
internalMutateKeys.push(filterKeys((key) => whitelist.includes(key)));
}
if (blacklist) {
internalMutateKeys.push(filterKeys((key) => !blacklist.includes(key)));
}
const customMutateKeys = mutateKeys ? internalMutateKeys.concat(mutateKeys) : internalMutateKeys;
const cache: ICache = new Cache({
disablePersist,
prefix: null,
mutateKeys: customMutateKeys,
mutateValues,
initialState: preloadedState,
mergeState: async (originalRestoredState = {}, initialState = {}) => {
const restoredState = originalRestoredState[reduxPersistKey] || originalRestoredState;
const haveStoredState = !!restoredState && !!restoredState._persist;
const state = haveStoredState
? await migrate(restoredState, version).then((mState: any) =>
stateReconciler(mState, initialState, initialState, persistOptions),
)
: initialState;
return { ...state, _persist: { version, rehydrated: true, wora: true } };
},
...persistOptions,
});
if (disablePersist) {
promiseRestore = Promise.resolve();
}
let currentReducer = reducer;
let isDispatching = false;
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
if (isDispatching) {
throw new Error('GETSTATE1');
}
return cache.getState();
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener: any) {
return cache.subscribe(listener);
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action: any) {
if (!isPlainObject(action)) {
throw new Error('DISPATCH1');
}
if (typeof action.type === 'undefined') {
throw new Error('DISPATCH2');
}
if (isDispatching) {
throw new Error('DISPATCH3');
}
try {
isDispatching = true;
const { _persist, ...prevState } = cache.getState();
const state = currentReducer(prevState, action);
Object.keys(state).forEach((key) => {
if (state[key] !== prevState[key]) {
cache.set(key, state[key]);
}
});
} finally {
isDispatching = false;
}
cache.notify({ state: getState(), action });
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer: any) {
if (typeof nextReducer !== 'function') {
throw new Error('REPLACE1');
}
currentReducer = nextReducer;
// This action has a similiar effect to ActionTypes.INIT.
// Any reducers that existed in both the new and old rootReducer
// will receive the previous state. This effectively populates
// the new state tree with any relevant data from the old one.
dispatch({ type: ActionTypes.REPLACE });
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/tc39/proposal-observable
*/
function observable() {
const outerSubscribe = subscribe;
return {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe(observer: any) {
if (typeof observer !== 'object' || observer === null) {
throw new TypeError('OBSERVER1');
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
const unsubscribe = outerSubscribe(observeState);
return { unsubscribe };
},
[$$observable]() {
return this;
},
};
}
function isRehydrated(): boolean {
return disablePersist || cache.isRehydrated();
}
function restore(): Promise<DataCache> {
if (promiseRestore) {
return promiseRestore;
}
promiseRestore = cache.restore();
return promiseRestore;
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
restore()
.then(() => dispatch({ type: REHYDRATE }))
.catch((error) => dispatch({ type: REHYDRATE_ERROR, error }));
return {
dispatch,
subscribe,
getState,
replaceReducer,
restore,
isRehydrated,
[$$observable]: observable,
};
}
export default createStore;
|
c929c00ceccc8ee63345621d5b5f1a33056400d3
|
TypeScript
|
ronan583/RiddleGame-egret
|
/GuessGameClient/src/dliy/Utils/Http.ts
| 2.5625
| 3
|
module dliy.utils {
export class Http {
private loader: egret.URLLoader = new egret.URLLoader();
private variables: egret.URLVariables;
private httpReq:egret.HttpRequest = new egret.HttpRequest();;
static create(): Http {
return new Http();
}
success(handle: Function, thisObj: any = null): Http {
this.httpReq.addEventListener(egret.Event.COMPLETE, function (e: egret.Event): void {
var loader = <egret.HttpRequest>e.currentTarget;
DLog.log(this, "req success " + loader.response);
handle.call(thisObj, loader.response);
}, thisObj);
return this;
}
error(handle: Function, thisObj: any = null): Http {
this.httpReq.addEventListener(egret.IOErrorEvent.IO_ERROR, handle, thisObj);
return this;
}
add(source): Http {
if (!this.variables) {
this.variables = new egret.URLVariables();
}
this.variables.decode(source);
return this;
}
dataFormat(dataFormat: string): Http {
// this.httpReq. = dataFormat;
return this;
}
get(url: string) {
this.httpReq.timeout = 2000;
this.httpReq.open(url)
this.httpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this.httpReq.send();
DLog.log(this, "request " + url);
}
post(url: string) {
var req = new egret.URLRequest(url);
req.method = egret.URLRequestMethod.POST;
this.variables && (req.data = this.variables);
this.loader.load(req);
}
}
}
|
45187a33b188ca43c1740d49450420180a03f4d4
|
TypeScript
|
spankoj/nextjstravelplaner
|
/utils/valtio/sessionstore.ts
| 2.703125
| 3
|
import { proxy } from 'valtio';
/* eslint-disable-next-line */
export const SESSIONS = {
ANONYMOUS: 'anonymous', // Not logged in, not started the login/register process
DURINGLOGINORREGISTER: 'duringloginorregister', // Started the login/register process
LOGGEDIN: 'loggedin', // Logged in
};
type SessionStoreType = {
activeSessionType: string;
activeSessionToken: string;
csrfToken: string;
tripId: number | undefined;
fallbackSessionToken?: string;
userId: number;
setSession: (
activeSessionType: string,
activeSessionToken: string,
// needed if 5 mins session token get's invalid -> Fallback will be the 2 hours token
) => void;
setFallbackSession: () => void;
setCSRFToken: (token: string) => void;
setUserId: (userId: number) => void;
setTripId: (tripId: number) => void;
};
const sessionStore: SessionStoreType = proxy({
activeSessionType: '',
activeSessionToken: '',
csrfToken: '',
tripId: undefined,
fallbackSessionToken: '',
userId: 0,
setSession: (type, token) => {
sessionStore.activeSessionType = type;
sessionStore.activeSessionToken = token;
},
setCSRFToken: (token) => {
sessionStore.csrfToken = token;
},
setFallbackSession: () => {
sessionStore.fallbackSessionToken = sessionStore.activeSessionToken;
},
setUserId: (userId) => {
sessionStore.userId = userId;
},
setTripId: (tripId) => {
sessionStore.tripId = tripId;
},
});
export default sessionStore;
|
d88de282d83f8c3860fa88772cfe1b30f7b95fac
|
TypeScript
|
MariusAlch/json-to-ts
|
/test/array-merging.spec.ts
| 3.359375
| 3
|
import * as assert from "assert";
import { removeWhiteSpace } from "./util/index";
import JsonToTS from "../src/index";
describe("Array type merging", function() {
it("should work with arrays with same inner types", function() {
const json = {
cats: [{ name: "Kittin" }, { name: "Sparkles" }]
};
const expectedTypes = [
`interface RootObject {
cats: Cat[];
}`,
`interface Cat {
name: string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("union null type should be emited and field should be marked as optional", function() {
const json = [{ age: 42 }, { age: null }];
const expectedTypes = [
`interface RootObject {
age?: number;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
it("null should stay if it is part of array elements", function() {
const json = {
arr: [42, "42", null]
};
const expectedTypes = [
`interface RootObject {
arr: (null | number | string)[];
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
it("array types should be merge even if they are nullable", function() {
const json = [
{
field: ["string"]
},
{
field: [42]
},
{
field: null
},
{
field: [new Date()]
}
];
const expectedTypes = [
`interface RootObject {
field?: (Date | number | string )[];
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
console.log(noWhiteSpaceInterface);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
it("object types should be merge even if they are nullable", function() {
const json = [
{
field: { tag: "world" }
},
{
field: { tag: 42 }
},
{
field: null
}
];
const expectedTypes = [
`interface RootObject {
field?: Field;
}`,
`interface Field {
tag: number | string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should work with arrays with inner types that has optinal field", function() {
const json = {
cats: [{ name: "Kittin" }, { name: "Sparkles", age: 20 }]
};
const expectedTypes = [
`interface RootObject {
cats: Cat[];
}`,
`interface Cat {
name: string;
age?: number;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should work with arrays with inner types that has no common fields", function() {
const json = {
cats: [{ name: "Kittin" }, { age: 20 }]
};
const expectedTypes = [
`interface RootObject {
cats: Cat[];
}`,
`interface Cat {
name?: string;
age?: number;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should work with arrays with inner types that have common field that has different types", function() {
const json = {
cats: [{ age: "20" }, { age: 20 }]
};
const expectedTypes = [
`interface RootObject {
cats: Cat[];
}`,
`interface Cat {
age: number | string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should solve edge case 1", function() {
const json = {
cats: [{ age: [42] }, { age: ["42"] }],
dads: ["hello", 42]
};
const expectedTypes = [
`interface RootObject {
cats: Cat[];
dads: (number | string)[];
}`,
`interface Cat {
age: (number | string)[];
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should solve edge case 2", function() {
const json = {
items: [
{
billables: [
{
quantity: 2,
price: 0
}
]
},
{
billables: [
{
priceCategory: {
title: "Adult",
minAge: 0,
maxAge: 99
},
quantity: 2,
price: 226
}
]
}
]
};
const expectedTypes = [
`interface RootObject {
items: Item[];
}`,
`interface Item {
billables: Billable[];
}`,
`interface Billable {
quantity: number;
price: number;
priceCategory?: PriceCategory;
}`,
`interface PriceCategory {
title: string;
minAge: number;
maxAge: number;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 4);
});
it("should solve edge case 3", function() {
const json = [
{
nestedElements: [
{
commonField: 42,
optionalField: "field"
},
{
commonField: 42,
optionalField3: "field3"
}
]
},
{
nestedElements: [
{
commonField: "42",
optionalField2: "field2"
}
]
}
];
const expectedTypes = [
`interface RootObject {
nestedElements: NestedElement[];
}`,
`interface NestedElement {
commonField: number | string;
optionalField?: string;
optionalField3?: string;
optionalField2?: string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should merge empty array with primitive types", function() {
const json = [
{
nestedElements: []
},
{
nestedElements: ["kittin"]
}
];
const expectedTypes = [
`interface RootObject {
nestedElements: string[];
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
it("should merge empty array with object types", function() {
const json = [
{
nestedElements: []
},
{
nestedElements: [{ name: "kittin" }]
}
];
const expectedTypes = [
`interface RootObject {
nestedElements: NestedElement[];
}`,
`interface NestedElement {
name: string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 2);
});
it("should merge empty array with array types", function() {
const json = [
{
nestedElements: []
},
{
nestedElements: [["string"]]
}
];
const expectedTypes = [
`interface RootObject {
nestedElements: string[][];
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
it("should merge union types with readable names ", function() {
const json = [
{
marius: "marius"
},
{
marius: [42]
}
];
const expectedTypes = [
`interface RootObject {
marius: number[] | string;
}`
].map(removeWhiteSpace);
const interfaces = JsonToTS(json);
interfaces.forEach(i => {
const noWhiteSpaceInterface = removeWhiteSpace(i);
assert(expectedTypes.includes(noWhiteSpaceInterface));
});
assert.strictEqual(interfaces.length, 1);
});
});
|
9b01e1d43b10b179c0ada3e8156b7153749e7966
|
TypeScript
|
Tebogo-Seshibe-Retro/db-decor
|
/src/lib/util/DatabaseState.ts
| 2.859375
| 3
|
export type NameCasing = 'pascal' | 'camel' | 'snake' | 'kebab'
export interface TableProperties
{
textCasing?: NameCasing
}
export interface TableDetails
{
name?: string
primaryKey?: string
foreignKeys?: {
field: string,
table: string
}[],
textCasing?: NameCasing
}
export type ColumnType = 'number' | 'string' | 'date'
export interface ColumnProperties
{
nullable?: boolean
}
export interface ColumnDetails
{
field: string
columnName: string
columnType: ColumnType
properties: ColumnProperties
}
export interface TableInfo
{
table: TableDetails
columns: Record<string, ColumnDetails>
}
export type DatabaseState = Record<string, TableInfo>
export const State: DatabaseState = { }
|
0282e0feb2f3e8596da7f81b2c1a02de7ab042de
|
TypeScript
|
chenyijie2016/Snake
|
/SnakeVSBlock_TS/src/view/GameStart.ts
| 2.75
| 3
|
/**Created by the LayaAirIDE*/
module view {
export class GameStart extends ui.GameStartUI {
constructor() {
super();
this.gameStartButton.on(Laya.Event.CLICK, this, this.onGameStart);
this.leaderBoardButton.on(Laya.Event.CLICK, this, this.onShowLeaderBoard)
this.colorModeButton.on(Laya.Event.CLICK, this, this.onGameMode);
//绘制游戏名称
this.createTitle();
}
public onGameMode(): void {
if(GameMain.mode === GameMode.Normal){
GameMain.mode = GameMode.Color;
this.colorModeButton.selected = true;
}
else if(GameMain.mode === GameMode.Color){
GameMain.mode = GameMode.Normal;
this.colorModeButton.selected = false;
}
}
public onShowLeaderBoard(): void {
if(!GameMain.leaderBoard)
{
GameMain.leaderBoard = new view.LeaderBoard();
}
super.removeSelf()
Laya.stage.addChild(GameMain.leaderBoard)
GameMain.leaderBoard.setLeaderBoard(null);
}
public onGameStart(): void {
Laya.SoundManager.playSound(Const.BUTTON_SOUND);
this.removeSelf();
if(GameMain.mode === GameMode.Normal){
if (!GameMain.gameView) {
GameMain.gameView = new GameView();
}
GameMain.gameView.startGame();
Laya.stage.addChild(GameMain.gameView);
}
else if(GameMain.mode === GameMode.Color){
if (!GameMain.gameColorMode) {
GameMain.gameColorMode = new GameColorMode();
}
GameMain.gameColorMode.startGame();
Laya.stage.addChild(GameMain.gameColorMode);
Laya.SoundManager.playSound(Const.GAME_START_SOUND);
}
}
public createTitle(): void {
let Text = Laya.Text;
let txt1 = new Text();
txt1.text = "Snake";
txt1.width = 300;
txt1.font = "SimSun";
txt1.fontSize = 50;
txt1.color = "white";
txt1.x = Laya.stage.width - txt1.textWidth >> 1;
txt1.y = Laya.stage.height * 0.08;
this.addChild(txt1);
let txt2 = "VS";
let w = 300;
let offsetX = Laya.stage.width >> 1;
let letter;
for (let i = 0, len = txt2.length; i < len; ++i) {
letter = this.createLetter(txt2.charAt(i));
letter.x = (i == 0 ? (Laya.stage.width >> 1) - 27 : (Laya.stage.width >> 1) + 5);
letter.y = 0;
//字符缓动动画
Laya.Tween.to(letter, {
y: Laya.stage.height * 0.16, update: new Laya.Handler(this, updateColor,
[letter])
}, 1500, Laya.Ease.bounceIn, Laya.Handler.create
(this, changeColor, [letter]), i * 200);
}
function updateColor(txt) {
let c = Math.floor(Math.random() * 3);
switch (c) {
case 0:
txt.color = "#eee000";
break;
case 1:
txt.color = "#ffffff";
break;
case 2:
txt.color = "#ff0000";
break;
default:
txt.color = "#eee000";
break;
}
}
function changeColor(txt) {
//将文本字体改变成红色
txt.color = "red";
}
let txt3 = new Text();
txt3.text = "Block";
txt3.width = 300;
txt3.fontSize = 50;
txt3.font = "SimSun";
txt3.color = "white";
txt3.x = Laya.stage.width - txt3.textWidth >> 1;
txt3.y = Laya.stage.height * 0.24;
this.addChild(txt3);
}
private createLetter(char) {
let letter = new Laya.Text();
letter.text = char;
letter.color = "white";
letter.fontSize = 50;
letter.font = "SimSun";
letter.bold = true;
this.addChild(letter);
return letter;
}
}
}
|
ce825db8b2dd5791342d87778ead9d6d9c2eb4e5
|
TypeScript
|
emqx/MQTTX
|
/src/utils/topicMatch.ts
| 3.265625
| 3
|
/**
* Topic matching algorithm
* @return Return matched result, true or false
* @param filter - type: topic string, subscription list topics
* @param topic - type: topic string, real send-receive topics
*/
export const matchTopicMethod = (filter: string, topic: string): boolean => {
let _filter = filter
let _topic = topic
if (filter.includes('$share')) {
// shared subscription format: $share/{ShareName}/{filter}
_filter = filter.split('/').slice(2).join('/')
}
const filterArray: string[] = _filter.split('/')
const length: number = filterArray.length
const topicArray: string[] = _topic.split('/')
for (let i = 0; i < length; i += 1) {
const left: string = filterArray[i]
const right: string = topicArray[i]
if (left === '#') {
return topicArray.length >= length - 1
}
if (left !== right && left !== '+') {
return false
}
}
return length === topicArray.length
}
const topicMatch = (data: MessageModel[], currentTopic: string): Promise<MessageModel[]> =>
new Promise((resolve, reject) => {
try {
const filterData = data.filter((item) => matchTopicMethod(currentTopic, item.topic))
return resolve(filterData)
} catch (error) {
return reject(error)
}
})
export default topicMatch
|
b8213343e5c2494e019a1af6a5cc9be6baffb41b
|
TypeScript
|
hfleischer/vector-tile-analysis
|
/synergis/protobuf/base/source/SubSourceMessage.ts
| 3.03125
| 3
|
import { CodedInputStream } from "./CodedInputStream";
import { ISubSource } from "./ISubSource";
/**
* implementation of ISubSource wrapping a single message as defined in the protocol-buffer standard<br>
*
* @author h.fleischer
* @since 26.07.2019
*/
export class SubSourceMessage implements ISubSource {
/**
* the input that is being read from
*/
input: ISubSource;
constructor(input: ISubSource) {
this.input = input;
let messageLength = input.readMessageLength();
input.pushLimit(messageLength);
}
pushLimit(messageLength: number): void {
this.input.pushLimit(messageLength);
}
peekLimit(): number {
return this.input.peekLimit();
}
popLimit(): void {
this.input.popLimit();
}
hasReachedLimit(): boolean {
return this.input.hasReachedLimit();
}
readRawVarint32(): number {
return this.input.readRawVarint32();
}
readRawVarint64(): number {
return this.input.readRawVarint64();
}
readDouble(): number {
return this.input.readDouble();
}
readString(): string {
return this.input.readString();
}
getBytesUntilLimit(): number {
return this.input.getBytesUntilLimit();
}
readMessageLength(): number {
return this.readRawVarint32();
}
}
|
3e4b8901ff6ed6f08050a1c6d044df5564bcca37
|
TypeScript
|
jankaspar/virtual-roads
|
/src/game/game.ts
| 2.625
| 3
|
import THREE = require('three');
import Input = require('./input');
import Level = require('./level');
import GameState = require('./gameState');
class Game {
element: HTMLElement;
state = GameState.Welcome;
onStateChange: () => void;
private levels = ['level1', 'level2'];
private currentLevel = 0;
private renderer: THREE.WebGLRenderer;
private clock: THREE.Clock;
private level: Level;
private input: Input;
constructor() {
this.renderer = new THREE.WebGLRenderer({
precision: 'highp',
devicePixelRatio: window.devicePixelRatio || 1
});
this.renderer.shadowMapEnabled = true;
this.renderer.shadowMapCullFace = THREE.CullFaceBack;
this.renderer.shadowMapType = THREE.PCFSoftShadowMap;
this.element = this.renderer.domElement;
window.onresize = () => this.resize();
this.resize();
this.reload();
this.loop();
}
private loop(){
if(this.level) {
this.renderer.render(this.level.scene, this.level.camera);
if(this.state != GameState.Welcome) {
this.level.update(this.clock.getDelta(), this.input);
}
}
requestAnimationFrame( () => this.loop() );
}
private resize() {
this.renderer.setSize( window.innerWidth, window.innerHeight);
if(this.level) {
this.level.camera.aspect = window.innerWidth / window.innerHeight;
this.level.camera.updateProjectionMatrix();
}
}
loadLevel(name:string) {
this.level = new Level(name);
this.level.load();
this.level.onFail = () => this.onFail();
this.level.onSuccess = () => this.onSuccess();
this.resize();
}
reload (){
var level = this.levels[this.currentLevel];
if (level) {
this.loadLevel(level);
} else {
this.changeState(GameState.Finished);
}
}
start() {
this.changeState(GameState.Playing);
this.input = new Input(document.body);
this.clock = new THREE.Clock();
this.level.paused = false;
}
onFail() {
this.changeState(GameState.Failed);
}
onSuccess() {
this.currentLevel++;
this.reload();
if(this.state != GameState.Finished){
this.start();
}
}
changeState( state: GameState) {
this.state = state;
this.onStateChange && this.onStateChange();
}
}
export = Game;
|
a60fe9e2a2d73467bf5123e08019074b5bad168a
|
TypeScript
|
Moseyza/BatisAutomationWeb
|
/src/store/models.d.ts
| 2.53125
| 3
|
export interface LetterDto {
id: string;
title: string;
from: string;
date: string;
summary: string;
number: string;
footNote?: string | null;
}
export interface LetterList{
letters:LetterDto[];
}
|
48c5756e47b5a9c73d52dc0fcf62bc7291f934ed
|
TypeScript
|
vova557/desktop
|
/app/test/unit/git/rebase/progress-test.ts
| 2.59375
| 3
|
import { IStatusResult } from '../../../../src/lib/git'
import {
rebase,
RebaseResult,
getRebaseSnapshot,
} from '../../../../src/lib/git'
import { createRepository as createShortRebaseTest } from '../../../helpers/repository-builder-rebase-test'
import { createRepository as createLongRebaseTest } from '../../../helpers/repository-builder-long-rebase-test'
import { getStatusOrThrow } from '../../../helpers/status'
import { GitRebaseSnapshot } from '../../../../src/models/rebase'
import { setupEmptyDirectory } from '../../../helpers/repositories'
import { getBranchOrError } from '../../../helpers/git'
const baseBranchName = 'base-branch'
const featureBranchName = 'this-is-a-feature'
describe('git/rebase', () => {
describe('skips a normal repository', () => {
it('returns null for rebase progress', async () => {
const repository = await setupEmptyDirectory()
const progress = await getRebaseSnapshot(repository)
expect(progress).toEqual(null)
})
})
describe('can parse progress', () => {
let result: RebaseResult
let snapshot: GitRebaseSnapshot | null
let status: IStatusResult
beforeEach(async () => {
const repository = await createShortRebaseTest(
baseBranchName,
featureBranchName
)
const featureBranch = await getBranchOrError(
repository,
featureBranchName
)
const baseBranch = await getBranchOrError(repository, baseBranchName)
result = await rebase(repository, baseBranch, featureBranch)
snapshot = await getRebaseSnapshot(repository)
status = await getStatusOrThrow(repository)
})
it('returns a value indicating conflicts were encountered', () => {
expect(result).toBe(RebaseResult.ConflictsEncountered)
})
it('status detects REBASE_HEAD', () => {
expect(snapshot).not.toEqual(null)
const s = snapshot!
expect(s.commits.length).toEqual(1)
expect(s.commits[0].summary).toEqual('Feature Branch!')
expect(s.progress.rebasedCommitCount).toEqual(1)
expect(s.progress.totalCommitCount).toEqual(1)
expect(s.progress.currentCommitSummary).toEqual('Feature Branch!')
expect(s.progress.value).toEqual(1)
})
it('is a detached HEAD state', () => {
expect(status.currentBranch).toBeUndefined()
})
})
describe('can parse progress for long rebase', () => {
let result: RebaseResult
let snapshot: GitRebaseSnapshot | null
let status: IStatusResult
beforeEach(async () => {
const repository = await createLongRebaseTest(
baseBranchName,
featureBranchName
)
const featureBranch = await getBranchOrError(
repository,
featureBranchName
)
const baseBranch = await getBranchOrError(repository, baseBranchName)
result = await rebase(repository, baseBranch, featureBranch)
snapshot = await getRebaseSnapshot(repository)
status = await getStatusOrThrow(repository)
})
it('returns a value indicating conflicts were encountered', () => {
expect(result).toBe(RebaseResult.ConflictsEncountered)
})
it('status detects REBASE_HEAD', () => {
expect(snapshot).not.toEqual(null)
const s = snapshot!
expect(s.commits.length).toEqual(10)
expect(s.commits[0].summary).toEqual('Feature Branch First Commit!')
expect(s.progress.rebasedCommitCount).toEqual(1)
expect(s.progress.totalCommitCount).toEqual(10)
expect(s.progress.currentCommitSummary).toEqual(
'Feature Branch First Commit!'
)
expect(s.progress.value).toEqual(0.1)
})
it('is a detached HEAD state', () => {
expect(status.currentBranch).toBeUndefined()
})
})
})
|
8d6abc896d70fa53a85dc9b987d49ef40988356c
|
TypeScript
|
redemma71/cs701-finalProject
|
/src/app/pipes/telephone.pipe.ts
| 2.703125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'telephone',
pure: false
})
export class TelephonePipe implements PipeTransform {
transform(phoneNumber: number): string {
let phoneNumberNormal = (phoneNumber.toString()).replace(/\D/g, '');
return '(' + phoneNumberNormal.substr(0, 3) + ')'
+ phoneNumberNormal.substr(3, 3) + '-'
+ phoneNumberNormal.substr(6, 4);
}
}
|
45dbbe9743bc13bdd6b121716aa3431b010cf10a
|
TypeScript
|
dtassone/material-ui-x
|
/packages/grid/_modules_/grid/utils/keyboardUtils.ts
| 2.65625
| 3
|
import * as React from 'react';
export const isEscapeKey = (key: string): boolean => key === 'Escape';
export const isEnterKey = (key: string): boolean => key === 'Enter';
export const isTabKey = (key: string): boolean => key === 'Tab';
export const isSpaceKey = (key: string): boolean => key === ' ';
export const isArrowKeys = (key: string): boolean => key.indexOf('Arrow') === 0;
export const isHomeOrEndKeys = (key: string): boolean => key === 'Home' || key === 'End';
export const isPageKeys = (key: string): boolean => key.indexOf('Page') === 0;
export const isDeleteKeys = (key: string) => key === 'Delete' || key === 'Backspace';
const printableCharRegex = /^(\p{L}|\p{M}\p{L}|\p{M}|\p{N}|\p{Z}|\p{S}|\p{P})$/iu;
export const isPrintableKey = (key: string) => printableCharRegex.test(key);
export const GRID_MULTIPLE_SELECTION_KEYS = ['Meta', 'Control', 'Shift'];
export const GRID_CELL_EXIT_EDIT_MODE_KEYS = ['Enter', 'Escape', 'Tab'];
export const GRID_CELL_EDIT_COMMIT_KEYS = ['Enter', 'Tab'];
export const isMultipleKey = (key: string): boolean =>
GRID_MULTIPLE_SELECTION_KEYS.indexOf(key) > -1;
export const isCellEnterEditModeKeys = (key: string): boolean =>
isEnterKey(key) || isDeleteKeys(key) || isPrintableKey(key);
export const isCellExitEditModeKeys = (key: string): boolean =>
GRID_CELL_EXIT_EDIT_MODE_KEYS.indexOf(key) > -1;
export const isCellEditCommitKeys = (key: string): boolean =>
GRID_CELL_EDIT_COMMIT_KEYS.indexOf(key) > -1;
export const isNavigationKey = (key: string) =>
isHomeOrEndKeys(key) || isArrowKeys(key) || isPageKeys(key) || isSpaceKey(key);
export const isKeyboardEvent = (event: any): event is React.KeyboardEvent => !!event.key;
export const isHideMenuKey = (key) => isTabKey(key) || isEscapeKey(key);
|
161b0866b5add605b1a7dba588194f86545e44bc
|
TypeScript
|
maximeleroylaval/ugram
|
/client/src/reducers/Notification/Notification.ts
| 2.765625
| 3
|
import {Action, ActionTypes} from "../../actions/Notifications/notifications";
import {Notification} from "../../models/Notification";
export interface IStateNotifications {
notifications: Notification[],
}
export const initialState: IStateNotifications = {
notifications: []
};
export function reducer(state: IStateNotifications = initialState, action: Action) : IStateNotifications {
switch (action.type) {
case ActionTypes.UPDATE_NOTIF:
return {
...state,
notifications: action.payload.notifications,
};
default:
return state
}
}
|
ee83ffa58ff9bdc309861e846eb2d22aabeadcb5
|
TypeScript
|
wix-incubator/raw-http-response
|
/index.spec.ts
| 2.53125
| 3
|
import buildHttpResponse from "./index";
test("builds an empty http response", () => {
const response = buildHttpResponse({
status: 200,
headers: { "X-My-Header": "Hello world!" },
body: Buffer.from("")
}).toString("utf8");
expect(response).toMatchSnapshot();
});
test("builds a simple string response", () => {
const response = buildHttpResponse({
status: 500,
headers: { "Content-Type": "text/plain" },
body: Buffer.from("Internal Server Error or whatevers!")
}).toString("utf8");
expect(response).toMatchSnapshot()
});
|
81ac4be17953120578758853e25f9be9b5b4851d
|
TypeScript
|
Rigii/mystery-chat
|
/src/user/schemas/user.schema.ts
| 2.796875
| 3
|
import * as mongoose from 'mongoose';
import { USER_GENDER, USER_ROLE } from '../constants';
import { statusEnum } from '../enums/status.enum';
export const UserSchema = new mongoose.Schema({
email: { type: String, required: true }, // necessary field
status: {
type: String,
enum: Object.values(statusEnum),
default: statusEnum.pending,
}, // is Object.values needed?
avatar: { type: String, default: null }, // unnecessary field
avatarId: { type: String, default: null }, //id файла для операций с удалением/обновлением...
firstName: { type: String, required: true },
lastName: { type: String, required: true },
gender: { type: String, required: true }, //, enum: Object.values(USER_GENDER)
address: {
country: { type: String, default: null },
city: { type: String, default: null },
addressLine1: { type: String, default: null },
addressLine2: { type: String, default: null },
},
profession: { type: String, default: null },
phone: { type: String, default: null },
roles: { type: [String], required: true, enum: Object.values(USER_ROLE) },
password: { type: String, required: true },
});
UserSchema.index({ email: 1 }, { unique: true });
// индекс под которым хранится эта коллекция в базе (индекс - это кеширование).
// Нужен для оптимизации поиска в коллекции. Под капотом вызывает метод монго, createIndex.
// Вместо того, чтобы просматривать все документы, mongo сохраняет отдельный индекс
// для быстрого доступа, например. здесь, чтобы проверить, существуют ли уже такие же значения,
// если вставлен новый документ. Индексирование в целом имеет ту же идею
|
f7763fefea3b5955fbf72bdc7bf536b8cc3f136f
|
TypeScript
|
cintiaribeiro/code-micro-videos
|
/frontend/src/util/helper /index.ts
| 2.765625
| 3
|
const members: string[] = ["Diretor", "Ator"];
export const member = (member:number) => {
return members[member];
}
|
4d8435736006acc5cb8a3c2baed61e66766f5b9d
|
TypeScript
|
frjjkil2009/najs-eloquent
|
/lib/relations/HasOneOrMany.ts
| 3.09375
| 3
|
export type RelationInfo = {
model: string
table: string
key: string
}
export class HasOneOrMany {
/**
* Store local RelationInfo, it always has 1 record
*/
protected local: RelationInfo
/**
* Store foreign RelationInfo, it can has 1 or many depends on "isHasOne"
*/
protected foreign: RelationInfo
/**
* If it is true the relation is OneToOne otherwise is OneToMany
*/
protected is1v1: boolean
constructor(oneToOne: boolean, local: RelationInfo, foreign: RelationInfo) {
this.is1v1 = oneToOne
this.local = local
this.foreign = foreign
}
load(model: any): any {
if (model.getModelName() === this.local.model) {
return this.loadByLocal(model)
}
return this.loadByForeign(model)
}
loadByLocal(localModel: any) {
const foreignModel = <any>{}
const query = foreignModel.newQuery().where(this.foreign.key, localModel.getAttribute(this.local.key))
if (this.is1v1) {
return query.first()
}
return query.get()
}
loadByForeign(foreignModel: any) {
const localModel = <any>{}
const query = localModel.newQuery().where(this.local.key, foreignModel.getAttribute(this.foreign.key))
return query.first()
}
}
|
487dd0d0f01a62dac2b6b1471c1d7ee201c2da38
|
TypeScript
|
AsimAlmshni/BankSystem
|
/Bank/ClientApp/src/app/customers-list/customers-list.component.ts
| 2.515625
| 3
|
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { CustomerService } from '../core/services/customer.service';
import { CustomerModel } from '../models/customer.model';
@Component({
selector: 'app-customers-list',
templateUrl: './customers-list.component.html',
styleUrls: ['./customers-list.component.css']
})
export class CustomersListComponent implements OnInit {
displayedColumns: string[] = ['name', 'mainCurrency', 'accId', 'totalBalance'];
dataSource: MatTableDataSource<CustomerModel>;// = new MatTableDataSource(ELEMENT_DATA);
constructor(private customerService: CustomerService) {
this.dataSource = new MatTableDataSource<CustomerModel>([]);
}
ngOnInit() {
this.dataSource.data = [
// {name: 'Kanaan', mainCurrency: 'Dollar', accId : '1', totalBalance : 900},
// {name: 'Asim', mainCurrency: 'Nis', accId : '2', totalBalance : 12900},
// {name: 'Fliz', mainCurrency: 'MG', accId : '3', totalBalance : 1900}
];
this.customerService.getCustomersList().subscribe((data: CustomerModel[]) => {
this.dataSource.data = data;
});
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
|
89aa40681fd1f101554bc111af5c0eb7003093d9
|
TypeScript
|
PirateSeal/PongBabylonJs
|
/src/components/objects/ball.ts
| 2.546875
| 3
|
import {
Color3,
Mesh,
MeshBuilder,
Scene,
StandardMaterial,
Vector3,
} from "babylonjs";
import { BallDirection, PaddleDirection } from "../enums/enums";
import Game from "../../game";
export default class Ball {
_body: Mesh;
_speed: number;
_direction: BallDirection;
_ctx: Game;
constructor(scene: Scene, context: Game) {
this._ctx = context;
this._body = MeshBuilder.CreateSphere(
"ball",
{
diameter: 6,
updatable: true,
},
scene
);
let mat = new StandardMaterial("ballMaterial", scene);
mat.diffuseColor = new Color3(1, 0, 0);
this._body.position = new Vector3(0, 0, 0);
this._body.material = mat;
this._speed = 0.5;
this._direction = 1;
this._body.checkCollisions = true;
}
update() {
this._move();
this._checkCollision();
}
_move() {
switch (this._direction) {
case BallDirection.DOWN:
this._body.position.x += this._speed;
break;
case BallDirection.UP:
this._body.position.x -= this._speed;
break;
case BallDirection.L_DOWN:
this._body.position.x += this._speed;
this._body.position.z -= this._speed;
break;
case BallDirection.R_DOWN:
this._body.position.x += this._speed;
this._body.position.z += this._speed;
break;
case BallDirection.L_UP:
this._body.position.x -= this._speed;
this._body.position.z -= this._speed;
break;
case BallDirection.R_UP:
this._body.position.x -= this._speed;
this._body.position.z += this._speed;
break;
}
}
_checkCollision() {
this._speed += 0.0001;
if (this._body.intersectsMesh(this._ctx._paddle1._body, false)) {
if (this._ctx._paddle1.getDirection() == PaddleDirection.NONE) {
this._direction = BallDirection.UP;
} else if (this._ctx._paddle1.getDirection() == PaddleDirection.LEFT) {
this._direction = BallDirection.L_UP;
} else if (this._ctx._paddle1.getDirection() == PaddleDirection.RIGHT) {
this._direction = BallDirection.R_UP;
}
}
if (this._body.intersectsMesh(this._ctx._paddle2._body, false)) {
if (this._ctx._paddle2.getDirection() == PaddleDirection.NONE) {
this._direction = BallDirection.DOWN;
} else if (this._ctx._paddle2.getDirection() == PaddleDirection.LEFT) {
this._direction = BallDirection.L_DOWN;
} else if (this._ctx._paddle2.getDirection() == PaddleDirection.RIGHT) {
this._direction = BallDirection.R_DOWN;
}
}
if (this._body.intersectsMesh(this._ctx._leftWall._body, false)) {
if (this._direction == BallDirection.L_DOWN) {
this._direction = BallDirection.R_DOWN;
} else if (this._direction == BallDirection.L_UP) {
this._direction = BallDirection.R_UP;
}
}
if (this._body.intersectsMesh(this._ctx._rightWall._body, false)) {
if (this._direction == BallDirection.R_DOWN) {
this._direction = BallDirection.L_DOWN;
} else if (this._direction == BallDirection.R_UP) {
this._direction = BallDirection.L_UP;
}
}
if (this._body.intersectsMesh(this._ctx._lowerWall._body, false)) {
this._body.position = new Vector3(0, 0, 0);
this._ctx._paddle1._score++;
this._ctx._paddle1._label.text.text =
"score : " + this._ctx._paddle1._score;
}
if (this._body.intersectsMesh(this._ctx._upperWall._body, false)) {
this._body.position = new Vector3(0, 0, 0);
this._ctx._paddle2._score++;
this._ctx._paddle2._label.text.text =
"score : " + this._ctx._paddle2._score;
}
}
}
|
3aea67f14baa91d9ab093985016203bf3a1db98d
|
TypeScript
|
flux627/abstract-factory-factory
|
/index.ts
| 2.96875
| 3
|
import 'reflect-metadata'
type Ctor<T> = Function & { prototype: T }
type FactoryCtor<T> = { create(): T }
type RegisteredFactoryMap<T> = Map<Ctor<T>, FactoryCtor<T>>
export class AbstractFactoryFactory {
static createAbstractFactory<B extends Object>(baseClass: Ctor<B>) {
return class AbstractFactory {
public static create<S extends B>(subCtor: Ctor<S>): B {
let registeredFactoryMap: RegisteredFactoryMap<B> | undefined = Reflect.getMetadata(
'registeredFactoryMap',
baseClass,
)
if (!registeredFactoryMap) {
registeredFactoryMap = new Map()
}
const factory = registeredFactoryMap.get(subCtor)
if (!factory) {
throw Error(`No factory was registered for class '${subCtor.name}'.`)
}
return factory.create()
}
}
}
static createRegisterFactoryDecorator<B extends Object>(baseClass: Ctor<B>) {
return <S extends B>(subCtor: Ctor<S>) => {
return (factoryCtor: FactoryCtor<S>) => {
let registeredFactoryMap: RegisteredFactoryMap<S> | undefined = Reflect.getMetadata(
'registeredFactoryMap',
baseClass,
)
if (!registeredFactoryMap) {
registeredFactoryMap = new Map()
}
registeredFactoryMap.set(subCtor, factoryCtor)
Reflect.defineMetadata('registeredFactoryMap', registeredFactoryMap, baseClass)
}
}
}
}
|
719484d3cdca20840762e5eaffd26ebb01c4717d
|
TypeScript
|
dmforaname/cobain_ts
|
/inheritance.ts
| 3.34375
| 3
|
class Pekerja{
bonus : number;
constructor(private noPekerja:string , private nama: string, private gaji:number){
this.bonus = this.gaji * 0.1 ;
}
getDetail(){
return "Nomor pekerja " + this.noPekerja + " dengan nama " + this.nama;
}
}
class Manajer extends Pekerja {
constructor (noPekerja:string, nama:string,gaji : number, private noLaporan:number){
super(noPekerja,nama,gaji);
}
getDetail(){
let detail = super.getDetail();
return detail + " Memiliki " + this.noLaporan + " laporan";
}
}
var emp = new Manajer("DM001" , "Daffa Mahendra", 10000000, 10);
console.log(emp.getDetail());
console.log(emp.bonus);
|
e20522421bf5789529d4158614db7d7770958686
|
TypeScript
|
rcauler/node-edi-stream
|
/lib/EdiLinePositional.d.ts
| 2.546875
| 3
|
import { EdiColumnSchema } from "./EdiColumnSchema";
export declare class EdiLinePositional {
line: string;
constructor(line: string);
read(column: EdiColumnSchema): string | number | Date;
readDate(startPosition: number, endPosition: number, dateFormat: string): Date;
readDateTime(datePos: number, dateLength: number, timePos: number, timeLength: number, dateFormat: string): Date;
readInt(startPosition: number, endPosition: number): number;
readFloat(startPosition: number, endPosition: number, decimals: number): number;
readFloatSigned(startPosition: number, endPosition: number, decimals: number, signPosition: number): number;
readString(startPosition: number, endPosition: number, rejectSameChars?: boolean): string;
static checkIfAllCharactersAreSame(str: string): boolean;
}
|
aaac3f1f276167fb659b670e1ab740cb1538c710
|
TypeScript
|
iyegoroff/typed-graphqlify
|
/dist/types.d.ts
| 2.671875
| 3
|
declare type ValueOf<T> = T[keyof T];
export declare function optional<T>(obj: T): T | undefined;
export declare function on<T extends {}>(typeName: string, internal: T): Partial<T>;
export declare function onUnion<T>(types: Record<string, T>): T;
export declare class types {
static readonly number: number;
static readonly string: string;
static readonly boolean: boolean;
static constant<T extends string>(_c: T): T;
static oneOf<T extends {}>(_e: T): ValueOf<T>;
static custom<T>(): T;
static or<T, U>(_t: T, _u: U): T | U;
static nonScalar<T>(_t: T): T;
static optional: {
number?: number;
string?: string;
boolean?: boolean;
constant: <T extends string>(_c: T) => T | undefined;
oneOf: <T extends {}>(_e: T) => (ValueOf<T>) | undefined;
custom: <T>() => T | undefined;
or: <T, U>(_t: T, _u: U) => T | U | undefined;
};
}
export {};
|
6986f52ff80a90ae56b1275d35d8ac0cb28ceccd
|
TypeScript
|
MegafonWebLab/megafon-ui
|
/packages/ui-shared/src/components/AudioPlayer/hooks/useTrackDuration.ts
| 2.796875
| 3
|
import React from 'react';
const useTrackDuration = (audioRef: React.RefObject<HTMLAudioElement>): number => {
const [trackDuration, setTrackDuration] = React.useState(0);
React.useEffect(() => {
const audioNode = audioRef.current;
if (!audioNode) {
return;
}
const { readyState, duration } = audioNode;
if (readyState > 0) {
setTrackDuration(Math.round(duration));
} else {
audioNode.onloadedmetadata = e => {
const el = e.target as HTMLAudioElement;
setTrackDuration(Math.round(el.duration));
};
}
}, [audioRef]);
return trackDuration;
};
export default useTrackDuration;
|
36a34d14b0aacf207692e006d40dfb6e88833141
|
TypeScript
|
AvinaLakshmi/sp-dev-fx-controls-react
|
/lib/controls/fileTypeIcon/FileTypeIcon.d.ts
| 2.609375
| 3
|
/// <reference types="react" />
import * as React from 'react';
import { IFileTypeIconProps } from './IFileTypeIcon';
/**
* File type icon component
*/
export declare class FileTypeIcon extends React.Component<IFileTypeIconProps, {}> {
constructor(props: IFileTypeIconProps);
/**
* Function which returns the font icon
*/
private _getIconClassName();
/**
* Function which returns the image icon
*/
private _getIconImageName();
/**
* Function to retrieve the file extension from the path
*
* @param value File path
*/
private _getFileExtension(value);
/**
* Find the icon name for the provided extension
*
* @param extension File extension
*/
private _getIconByExtension(extension, iconType);
/**
* Find the icon name for the application
*
* @param application
*/
private _getIconByApplicationType(application, iconType);
/**
* Return the right image size for the provided value
*
* @param value Image size value
*/
private _getFileSizeName(value);
/**
* Default React component render method
*/
render(): React.ReactElement<IFileTypeIconProps>;
}
|
ae036ef00d627cf3b44d0bd56065ef7bf5d769d5
|
TypeScript
|
mobitel-ltd/jira-to-matrix
|
/src/modules/log.ts
| 2.890625
| 3
|
import * as path from 'path';
import * as winston from 'winston';
import { config } from '../config';
/**
* Customize logger timestamp format to locale datetime with milliseconds
*
* @returns {string} Formatted datetime string
*/
const timestamp = () => {
const datetime = new Date();
const ms = String(datetime.getMilliseconds() % 1000);
return `${datetime.toLocaleString()},${ms.padEnd(3)}`;
};
const getLabel = mod => {
if (typeof mod === 'string') {
return mod;
}
const label = mod.filename
.replace(process.cwd(), '')
.split(path.sep)
.slice(-2)
.join(path.sep);
return label[0] === path.sep ? label : path.sep + label;
};
const getTransports = data => {
const baseTransport = { label: getLabel(data), timestamp };
const fileTransport = new winston.transports.File({
...baseTransport,
filename: config.log.filePath,
level: config.log.fileLevel,
json: true,
});
const consoleTransport = new winston.transports.Console({
...baseTransport,
colorize: true,
level: config.log.consoleLevel,
json: false,
prettyPrint: true,
silent: Boolean(process.env.TEST_WATCH),
});
const levels = {
file: [fileTransport],
console: [consoleTransport],
both: [fileTransport, consoleTransport],
};
return levels[config.log.type];
};
/**
* Customized settings for logger module "winston".
*
* @module log
* @param {object} data Current application module.
* @returns {{error: Function, warn: Function, info: Function, verbose: Function, debug: Function, silly: Function}}
* Configured logger object.
*/
export const getLogger = data => {
const transports = getTransports(data);
return new winston.Logger({
exitOnError: false,
transports,
});
};
|
5b59ed3afed3714b549e443df2ecc99e164f7bf9
|
TypeScript
|
jithyan/iag-challenge
|
/frontend/src/data/sagas.ts
| 2.71875
| 3
|
import { all, takeLatest, call, put } from "redux-saga/effects";
import axios, { AxiosResponse } from "axios";
import {
setHint,
setError,
START_NEW_GAME,
IVerifyAttemptAction,
setCorrect,
addAttempt,
VERIFY_ATTEMPT,
} from "./actions";
export interface INewPasswordResponse {
hint: string;
}
export interface IVerifyPasswordResponse {
correct: boolean;
highlight?: string[];
hint: string;
answer: string;
}
export const API_FAIL_MSG = "Sorry! The API failed on us.";
export function* startNewGameSagaWorker() {
try {
const response: AxiosResponse<INewPasswordResponse> = yield call(
axios.get,
"http://localhost:5000/new-password"
);
yield put(setHint(response.data.hint));
} catch (error) {
yield put(setError(API_FAIL_MSG));
}
}
export function* verifyAttemptSagaWorker(action: IVerifyAttemptAction) {
const { hint, guess } = action.payload;
if (guess.length === 0) {
yield put(setError("Attempt cannot be empty!"));
return;
}
try {
const response: AxiosResponse<IVerifyPasswordResponse> = yield call(
axios.post,
"http://localhost:5000/verify-password",
{
hint,
answer: guess,
}
);
const { correct, highlight = [], answer = "" } = response.data;
yield put(setError(""));
if (correct === true) {
yield put(setCorrect(true));
} else {
yield put(addAttempt({ highlight, answer }));
}
} catch (error) {
yield put(setError(API_FAIL_MSG));
}
}
export function* verifyAttemptSagaWatcher() {
yield takeLatest(VERIFY_ATTEMPT, verifyAttemptSagaWorker);
}
export function* startNewGameSagaWatcher() {
yield takeLatest(START_NEW_GAME, startNewGameSagaWorker);
}
export function* rootSaga() {
yield all([startNewGameSagaWatcher(), verifyAttemptSagaWatcher()]);
}
|
79032c957496b499d4d06cde64ddb39ef1a57e46
|
TypeScript
|
nprisament/OpenCircuits
|
/tests/app/digital/ts/models/CircuitDesigner.test.ts
| 2.828125
| 3
|
import "jest";
import {DigitalCircuitDesigner} from "digital/models/DigitalCircuitDesigner";
import {Switch} from "digital/models/ioobjects/inputs/Switch";
import {LED} from "digital/models/ioobjects/outputs/LED";
import {Place, Connect, Remove} from "test/helpers/Helpers";
describe("CircuitDesigner", () => {
describe("Empty Circuit", () => {
const designer = new DigitalCircuitDesigner(0);
expect(designer.getObjects().length).toBe(0);
expect(designer.getWires().length).toBe(0);
});
describe("Add", () => {
test("Add Object", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a]);
Place(designer, [o]);
expect(designer.getObjects().length).toBe(2);
expect(() => Place(designer, [a])).toThrowError();
expect(designer.getObjects().length).toBe(2);
expect(() => Place(designer, [o])).toThrowError();
expect(designer.getObjects().length).toBe(2);
});
test("Add Objects", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a, o]);
expect(designer.getObjects().length).toBe(2);
expect(() => Place(designer, [a])).toThrowError();
expect(designer.getObjects().length).toBe(2);
expect(() => Place(designer, [o])).toThrowError();
expect(designer.getObjects().length).toBe(2);
});
});
describe("Basic Circuit", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a, o]);
Connect(a, 0, o, 0);
const objects = designer.getObjects();
expect(objects.length).toBe(2);
expect(objects[0]).toBe(a);
expect(objects[1]).toBe(o);
const wires = designer.getWires();
expect(wires.length).toBe(1);
expect(wires[0].getInputComponent()).toBe(a);
expect(wires[0].getOutputComponent()).toBe(o);
test("Initial State", () => {
expect(o.isOn()).toBe(false);
});
test("Turn On", () => {
a.activate(true);
expect(o.isOn()).toBe(true);
});
});
describe("Remove Object", () => {
test("Add Remove No Connection", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a, o]);
expect(designer.getObjects().length).toBe(2);
Remove([a]);
Remove([o]);
expect(designer.getObjects().length).toBe(0);
expect(a.getDesigner()).toBe(undefined);
expect(o.getDesigner()).toBe(undefined);
expect(() => Remove([a])).toThrowError();
expect(() => Remove([o])).toThrowError();
});
test("Add Remove Connected 1", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a, o]);
Connect(a, 0, o, 0);
expect(designer.getObjects().length).toBe(2);
expect(designer.getWires().length).toBe(1);
expect(a.getOutputs().length).toBe(1);
expect(o.getInputs().length).toBe(1);
Remove([a]);
expect(designer.getObjects().length).toBe(1);
expect(designer.getWires().length).toBe(0);
expect(a.getOutputs().length).toBe(0);
expect(o.getInputs().length).toBe(0);
expect(() => Remove([a])).toThrowError();
});
});
describe("Reset Circuit", () => {
const designer = new DigitalCircuitDesigner(0);
const a = new Switch(), o = new LED();
Place(designer, [a, o]);
Connect(a, 0, o, 0);
});
});
|
c1c04dc99594cd3304a76a181212c4ab8566e723
|
TypeScript
|
RileyMShea/mui-next-ts
|
/__tests__/services/register.spec.ts
| 2.59375
| 3
|
import { STATUS_CODES } from 'http';
import register from 'services/register';
/* global fetchMock */
describe('login', () => {
it('should allow to send credentials', async () => {
fetchMock.mockResponseOnce(`{
"id": "760add88-0a2b-4358-bc3f-7d82245c5dea",
"username": "kristen.williams@example.com",
"name": "Kristen Williams",
"picture": "https://i.pravatar.cc/200",
"bio": "Lorem ipsum dolorem"
}`);
const body = {
firstName: 'Kristen',
lastName: 'Williams',
email: 'kristen.williams@example.com',
password: 'Pa$$w0rd!',
};
await expect(register(body)).resolves.toMatchObject({
id: expect.any(String),
username: body.email,
name: `${body.firstName} ${body.lastName}`,
picture: expect.any(String),
bio: expect.any(String),
});
});
it('should fail for duplicate user', async () => {
fetchMock.mockResponse(
`{
"statusCode": 409,
"error": "Conflict",
"message": "Username or Email already registered"
}`,
{ status: 409 },
);
const body = {
firstName: 'Jane',
lastName: 'Doe',
email: 'jane@doe.me',
password: 'Pa$$w0rd!',
};
await expect(register(body)).rejects.toThrow(
'Username or Email already registered',
);
});
it('should fail for validation error', async () => {
fetchMock.mockResponseOnce(
`{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": [
{
"children": [],
"constraints": {
"isString": "firstName must be a string",
"minLength": "firstName must be longer than or equal to 1 characters"
},
"property": "firstName",
"value": ""
},
{
"children": [],
"constraints": {
"isDefined": "lastName should not be null or undefined",
"isString": "lastName must be a string",
"minLength": "lastName must be longer than or equal to 1 characters"
},
"property": "lastName",
"value": null
},
{
"children": [],
"constraints": {
"isEmail": "email must be an email"
},
"property": "email",
"value": "jane_doe"
},
{
"children": [],
"constraints": {
"minLength": "password must be longer than or equal to 8 characters"
},
"property": "password",
"value": "pwd"
}
]
}`,
{ status: 422 },
);
const body = {
firstName: '',
lastName: null,
email: 'jane_doe',
password: 'pwd',
};
await expect(register(body)).rejects.toThrow(/must be an email/);
});
it('should fail for server error', async () => {
fetchMock.mockResponseOnce(
`{
"statusCode": 500,
"error": "Server Error"
}`,
{ status: 500 },
);
const body = {
firstName: 'Jane',
lastName: 'Doe',
email: 'jane@doe.me',
password: 'Pa$$w0rd!',
};
await expect(register(body)).rejects.toThrow(STATUS_CODES[500]);
});
});
|
88413f674f2c92687e783ea592247e56d322aa32
|
TypeScript
|
artyomsv/bootcamp-assessment
|
/src/services/Routing.service.ts
| 2.546875
| 3
|
import {AppView} from '../store/reducers/Navigation.reducer';
export interface PathParams {
id: number;
}
export interface AppRoutingData {
path: (id?: number | string) => string;
view: AppView;
}
export const AppRouting: { [id: string]: AppRoutingData } = {
root: {
path: () => '/',
view: 'home' as AppView,
},
actors: {
path: () => '/actors',
view: 'actors' as AppView,
},
actorsById: {
path: (id?: number | string): string => `${AppRouting.actors.path()}/${!!id ? id : ':id'}`,
view: 'actors' as AppView,
},
movies: {
path: () => '/movies',
view: 'movies' as AppView,
},
moviesById: {
path: (id?: number | string): string => `${AppRouting.movies.path()}/${!!id ? id : ':id'}`,
view: 'movies' as AppView,
}
};
|
710eac14e213e2b1b257d6c5ce3780fcb7669542
|
TypeScript
|
janderson-souza/CRUD-ANGULAR-FIREBASE
|
/src/app/shared/models/find.ts
| 2.96875
| 3
|
export class Filter<T> {
numberOfResult: number;
obj: T;
constructor(numberOfResult: number, obj: T) {
this.numberOfResult = numberOfResult;
this.obj = obj;
}
}
|
9041d008f97641b0872458d469307e8ffa70d3ec
|
TypeScript
|
bcherny/json-schema-to-typescript
|
/src/normalizer.ts
| 2.65625
| 3
|
import {JSONSchemaTypeName, LinkedJSONSchema, NormalizedJSONSchema, Parent} from './types/JSONSchema'
import {appendToDescription, escapeBlockComment, isSchemaLike, justName, toSafeString, traverse} from './utils'
import {Options} from './'
import {DereferencedPaths} from './resolver'
import {isDeepStrictEqual} from 'util'
type Rule = (
schema: LinkedJSONSchema,
fileName: string,
options: Options,
key: string | null,
dereferencedPaths: DereferencedPaths,
) => void
const rules = new Map<string, Rule>()
function hasType(schema: LinkedJSONSchema, type: JSONSchemaTypeName) {
return schema.type === type || (Array.isArray(schema.type) && schema.type.includes(type))
}
function isObjectType(schema: LinkedJSONSchema) {
return schema.properties !== undefined || hasType(schema, 'object') || hasType(schema, 'any')
}
function isArrayType(schema: LinkedJSONSchema) {
return schema.items !== undefined || hasType(schema, 'array') || hasType(schema, 'any')
}
rules.set('Remove `type=["null"]` if `enum=[null]`', schema => {
if (
Array.isArray(schema.enum) &&
schema.enum.some(e => e === null) &&
Array.isArray(schema.type) &&
schema.type.includes('null')
) {
schema.type = schema.type.filter(type => type !== 'null')
}
})
rules.set('Destructure unary types', schema => {
if (schema.type && Array.isArray(schema.type) && schema.type.length === 1) {
schema.type = schema.type[0]
}
})
rules.set('Add empty `required` property if none is defined', schema => {
if (isObjectType(schema) && !('required' in schema)) {
schema.required = []
}
})
rules.set('Transform `required`=false to `required`=[]', schema => {
if (schema.required === false) {
schema.required = []
}
})
rules.set('Default additionalProperties', (schema, _, options) => {
if (isObjectType(schema) && !('additionalProperties' in schema) && schema.patternProperties === undefined) {
schema.additionalProperties = options.additionalProperties
}
})
rules.set('Transform id to $id', (schema, fileName) => {
if (!isSchemaLike(schema)) {
return
}
if (schema.id && schema.$id && schema.id !== schema.$id) {
throw ReferenceError(
`Schema must define either id or $id, not both. Given id=${schema.id}, $id=${schema.$id} in ${fileName}`,
)
}
if (schema.id) {
schema.$id = schema.id
delete schema.id
}
})
rules.set('Add an $id to anything that needs it', (schema, fileName, _options, _key, dereferencedPaths) => {
if (!isSchemaLike(schema)) {
return
}
// Top-level schema
if (!schema.$id && !schema[Parent]) {
schema.$id = toSafeString(justName(fileName))
return
}
// Sub-schemas with references
if (!isArrayType(schema) && !isObjectType(schema)) {
return
}
// We'll infer from $id and title downstream
// TODO: Normalize upstream
const dereferencedName = dereferencedPaths.get(schema)
if (!schema.$id && !schema.title && dereferencedName) {
schema.$id = toSafeString(justName(dereferencedName))
}
if (dereferencedName) {
dereferencedPaths.delete(schema)
}
})
rules.set('Escape closing JSDoc comment', schema => {
escapeBlockComment(schema)
})
rules.set('Add JSDoc comments for minItems and maxItems', schema => {
if (!isArrayType(schema)) {
return
}
const commentsToAppend = [
'minItems' in schema ? `@minItems ${schema.minItems}` : '',
'maxItems' in schema ? `@maxItems ${schema.maxItems}` : '',
].filter(Boolean)
if (commentsToAppend.length) {
schema.description = appendToDescription(schema.description, ...commentsToAppend)
}
})
rules.set('Optionally remove maxItems and minItems', (schema, _fileName, options) => {
if (!isArrayType(schema)) {
return
}
if ('minItems' in schema && options.ignoreMinAndMaxItems) {
delete schema.minItems
}
if ('maxItems' in schema && (options.ignoreMinAndMaxItems || options.maxItems === -1)) {
delete schema.maxItems
}
})
rules.set('Normalize schema.minItems', (schema, _fileName, options) => {
if (options.ignoreMinAndMaxItems) {
return
}
// make sure we only add the props onto array types
if (!isArrayType(schema)) {
return
}
const {minItems} = schema
schema.minItems = typeof minItems === 'number' ? minItems : 0
// cannot normalize maxItems because maxItems = 0 has an actual meaning
})
rules.set('Remove maxItems if it is big enough to likely cause OOMs', (schema, _fileName, options) => {
if (options.ignoreMinAndMaxItems || options.maxItems === -1) {
return
}
if (!isArrayType(schema)) {
return
}
const {maxItems, minItems} = schema
// minItems is guaranteed to be a number after the previous rule runs
if (maxItems !== undefined && maxItems - (minItems as number) > options.maxItems) {
delete schema.maxItems
}
})
rules.set('Normalize schema.items', (schema, _fileName, options) => {
if (options.ignoreMinAndMaxItems) {
return
}
const {maxItems, minItems} = schema
const hasMaxItems = typeof maxItems === 'number' && maxItems >= 0
const hasMinItems = typeof minItems === 'number' && minItems > 0
if (schema.items && !Array.isArray(schema.items) && (hasMaxItems || hasMinItems)) {
const items = schema.items
// create a tuple of length N
const newItems = Array(maxItems || minItems || 0).fill(items)
if (!hasMaxItems) {
// if there is no maximum, then add a spread item to collect the rest
schema.additionalItems = items
}
schema.items = newItems
}
if (Array.isArray(schema.items) && hasMaxItems && maxItems! < schema.items.length) {
// it's perfectly valid to provide 5 item defs but require maxItems 1
// obviously we shouldn't emit a type for items that aren't expected
schema.items = schema.items.slice(0, maxItems)
}
return schema
})
rules.set('Remove extends, if it is empty', schema => {
if (!schema.hasOwnProperty('extends')) {
return
}
if (schema.extends == null || (Array.isArray(schema.extends) && schema.extends.length === 0)) {
delete schema.extends
}
})
rules.set('Make extends always an array, if it is defined', schema => {
if (schema.extends == null) {
return
}
if (!Array.isArray(schema.extends)) {
schema.extends = [schema.extends]
}
})
rules.set('Transform definitions to $defs', (schema, fileName) => {
if (schema.definitions && schema.$defs && !isDeepStrictEqual(schema.definitions, schema.$defs)) {
throw ReferenceError(
`Schema must define either definitions or $defs, not both. Given id=${schema.id} in ${fileName}`,
)
}
if (schema.definitions) {
schema.$defs = schema.definitions
delete schema.definitions
}
})
rules.set('Transform const to singleton enum', schema => {
if (schema.const !== undefined) {
schema.enum = [schema.const]
delete schema.const
}
})
export function normalize(
rootSchema: LinkedJSONSchema,
dereferencedPaths: DereferencedPaths,
filename: string,
options: Options,
): NormalizedJSONSchema {
rules.forEach(rule => traverse(rootSchema, (schema, key) => rule(schema, filename, options, key, dereferencedPaths)))
return rootSchema as NormalizedJSONSchema
}
|
ecb4b8ea0a9bda7b27479c73c28190df0df02ae9
|
TypeScript
|
PremierLangage/Amphi
|
/amphi_angular/src/app/interface/exercice/chart-ngx/chart-ngx.service.ts
| 2.734375
| 3
|
import { Injectable } from '@angular/core';
import { ChartKind, Type, Exercice, Data } from '../../../models/amphi.models';
@Injectable({ providedIn: 'root' })
export class ChartService {
step : number = 5;
kind : ChartKind = ChartKind.GRADER;
exercice : Exercice = { name: "", type: Type.FREE_ANSWER, question: "", rightAnswer: "", choices: {} }; // cleaner initializer;
grader: Data[] = [];
answers: Data[] = [];
percents: Data[] = [];
database : any[] = [];
customColors : { name: string, value : string }[] = [];
constructor() {
this.resetChart(this.exercice);
this.updateOthers();
this.updateCustomColors();
}
intToKind(serial: number) : ChartKind {
switch (serial) {
case 0:
return ChartKind.ANSWERS;
case 1:
return ChartKind.GRADER;
case 2:
return ChartKind.PERCENTS;
}
}
// getters
public getAnswers() : any[] {
return this.database;
}
public getChartData() : any[] {
switch (this.kind) {
case ChartKind.ANSWERS:
return this.answers;
case ChartKind.GRADER:
return this.grader;
case ChartKind.PERCENTS:
return this.percents;
}
}
private getRightAnswer() : string {
return this.exercice.rightAnswer;
}
private wantedResult() {
switch (this.kind) {
case ChartKind.ANSWERS:
return String(this.getRightAnswer());
case ChartKind.GRADER:
return "100";
case ChartKind.PERCENTS:
return "bonnes réponses";
}
}
// setters
public setKind(kind : ChartKind) {
this.kind = kind;
this.updateCustomColors();
}
public setStep(step : number) {
if (100 / step == Math.floor(100 / step)) {
this.step = step;
this.updateOthers();
}
}
public resetChart(exercice : Exercice) {
this.grader = [];
this.answers = [];
this.percents = [];
this.database = [];
this.exercice = exercice;
this.addRandomData();
}
// utils
private randint(min : number, max : number) : number {
return min + Math.round(Math.random() * (max - min))
}
private formatString(string : string) {
if (string.length > 10) return string.substring(0,10) + '...';
return string;
}
private sortData(data1 : Data, data2 : Data) {
var a : number = +data1.name;
var b : number = +data2.name;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
private sortCode(data1 : Data, data2 : Data) {
var a : number = +data1.name.split(" ")[0];
var b : number = +data2.name.split(" ")[0];
if (Number.isNaN(a)) return -1;
if (Number.isNaN(b)) return 1;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
private stepped(grade : number) : number {
return grade == 100 ? 100 : Math.floor(grade / this.step) * this.step;
}
// modify
private addValue(answer : any, array : any[]) {
var quit = false;
// format answer
switch (this.exercice.type) {
case Type.QCM:
case Type.CONTROLLED_INPUT:
answer = this.formatString(answer);
}
// if exists, add 1
array.forEach((data: Data) => {
if (data.name == answer) {
data.value += 1;
quit = true;
}
});
// if not, add a bar
if (!quit) array.push( { name: answer, value: 1 } );
}
public addRandomData() {
// adds 1000 random value with 30% chance of good answer
for (let i = 0; i < 100; i++) {
// 30% odd
if (this.randint(0, 100) == 0) {
this.addValue(this.getRightAnswer(), this.database);
} else {
var randomAnswer : any;
switch (this.exercice.type) {
case Type.TRUE_FALSE:
randomAnswer = this.randint(0, 1) == 1 ? this.getRightAnswer() : "non";
break;
case Type.CONTROLLED_INPUT:
case Type.QCU:
randomAnswer = Object.keys(this.exercice.choices)[this.randint(0, Object.keys(this.exercice.choices).length -1)];
break;
case Type.QCM:
randomAnswer = [];
Object.keys(this.exercice.choices).forEach((key : string) => {
if (this.randint(0, 1) == 0) randomAnswer.push(key);
});
break;
case Type.CODE:
var compile : boolean = this.randint(1, 25) != 1;
randomAnswer = {
'compile': compile,
'warnings': this.randint(1, 5) == 1 ? 0 : this.randint(1, 10),
'return': !compile ? false : this.randint(1, 2) == 1
};
break;
case Type.NUMERCIC_ANSWER:
default:
randomAnswer = this.getRightAnswer() + this.randint(-25, 25);
break;
}
this.addValue(randomAnswer, this.database);
}
}
};
// update
private updateOthers() {
this.updateAnswers();
this.updateGrader();
this.updatePercents();
}
private updateAnswers() {
this.answers = [];
switch (this.exercice.type) {
case Type.QCM:
this.database.forEach((data: any) => {
data.name.forEach((answer: string) => {
this.addValue(answer, this.answers);
});
});
break;
case Type.CODE:
this.database.forEach((data: any) => {
var answer = data.name;
if (answer.compile) {
this.addValue(
answer.return ? 'Bon return' : answer.warnings + ' warning' + (answer.warnings == 1 ? '' : 's'),
this.answers
);
} else {
this.addValue('Ne compile pas', this.answers);
}
});
this.answers.sort(this.sortCode);
break;
default:
this.answers = this.database;
}
}
private updateGrader() {
var quit = false;
this.grader = [];
// set values to 0
for (let grade = 100; grade >= 0; grade -= this.step) {
this.grader.push( { name: String(grade), value: 0 } );
}
this.database.forEach((data: any) => {
var newGrade : number;
switch (this.exercice.type) {
case Type.NUMERCIC_ANSWER:
newGrade = this.stepped(100 - Math.abs( (+this.getRightAnswer()) - (+data.name) ));
break;
case Type.QCM:
var nbChoices = Object.keys(this.exercice.choices).length
var nbRightAnswers = Object.keys(this.exercice.rightAnswer).length
newGrade = 0;
// among given answers
data.name.forEach((answer : string) => {
var points : number;
// check if answer is part of the right answers
points = (this.exercice.rightAnswer.includes(answer))
? (100 / nbRightAnswers)
: - (100 / nbChoices);
newGrade += points;
});
// if negative grade, set to 0
if (newGrade < 0) newGrade = 0;
else newGrade = this.stepped(newGrade);
break;
case Type.CODE:
var answer = data.name;
newGrade = answer.return ? 100 : (answer.compile ? 25 : 0);
newGrade -= answer.warnings * 10;
// if negative grade, set to 0
if (newGrade < 0) newGrade = 0;
else newGrade = this.stepped(newGrade);
break;
default:
newGrade = data.name == this.getRightAnswer() ? 100 : 0;
}
// if grade exists, add value, else create new {}
for (let i = 0; i < data.value; i++) {
this.addValue(newGrade, this.grader);
}
});
}
private updatePercents() {
this.percents = [ { name: "autres réponses", value: 0 } ];
this.database.forEach((data: Data) => {
if (data.name != this.getRightAnswer()) {
this.percents[0].value += data.value;
} else {
this.percents.push( { name: "bonnes réponses", value: data.value } );
}
});
// QCM : 1 percentage for each answer
}
private updateCustomColors() {
this.customColors = [];
if (this.kind == ChartKind.ANSWERS) {
switch (this.exercice.type) {
case Type.QCM:
this.exercice.rightAnswer.forEach((answer : string) => {
this.customColors.push({
name: this.formatString(answer),
value: 'rgb(175, 150, 250)'
})
});
break;
case Type.CODE:
this.customColors.push({
name: 'Bon return',
value: 'rgb(175, 150, 250)'
});
break;
default:
this.customColors.push({
name: this.wantedResult(),
value: 'rgb(175, 150, 250)'
});
}
} else {
this.customColors.push({
name: this.wantedResult(),
value: 'rgb(175, 150, 250)'
});
}
}
public reload() {
this.addRandomData();
this.database = [...this.database];
this.database.sort(this.sortData);
this.updateOthers();
this.updateCustomColors();
}
}
|
ae430d3520b9f54caab0155ee7b451b1c8214c4d
|
TypeScript
|
astuanax/fun-monads
|
/test/applicativelaws.test.ts
| 3.34375
| 3
|
import { Option } from '../src/Option'
import { Try } from '../src/Try'
import { Reader } from '../src/Reader'
const aValue: any = 1
const monads: any[] = [Option, Reader, Try]
describe('Applicative laws', () => {
test.each(monads)('Identity', m => {
const a = m.of(aValue)
const b = m.of((x: any) => x)
expect(m.ap(b, a).get()).toEqual(aValue)
})
test.each(monads)('Applicative laws: composition', m => {
const compose = (a: any) => (b: any) => (c: any) => a(b(c))
const fn = (x: string) => x + 'a'
const u = m.of(fn)
const v = m.of(fn)
const w = m.of('a')
const actual = m.ap(m.ap(m.ap(m.of(compose), u), v), w)
const expected = m.ap(u, m.ap(v, w))
expect(expected.get()).toEqual(actual.get())
})
test.each(monads)('Interchange', m => {
const u = m.of((x: string) => x)
const actual = m.ap(u, m.of(aValue))
const expected = m.ap(
m.of((f: any) => f(aValue)),
u
)
expect(expected.get()).toEqual(actual.get())
})
})
|
1676bb9728795df28c7ff3c260b474d20295ddd9
|
TypeScript
|
iamr0b0tx/scalabel
|
/app/src/js/common/track/track.ts
| 2.765625
| 3
|
import _ from 'lodash'
import Label2D from '../../drawable/2d/label2d'
import Label3D from '../../drawable/3d/label3d'
import { makeIndexedShape, makeTrack } from '../../functional/states'
import { IndexedShapeType, Label2DTemplateType, LabelType, State, TrackType } from '../../functional/types'
import { LabelTypeName, TrackPolicyType } from '../types'
import { Box2DLinearInterpolationPolicy } from './policy/linear_interpolation/box2d_linear_interpolation'
import { Box3DLinearInterpolationPolicy } from './policy/linear_interpolation/box3d_linear_interpolation'
import { CustomLabel2DLinearInterpolationPolicy } from './policy/linear_interpolation/custom_label2d_linear_interpolation'
import { Plane3DLinearInterpolationPolicy } from './policy/linear_interpolation/plane3d_linear_interpolation'
import { PolygonLinearInterpolationPolicy } from './policy/linear_interpolation/polygon_linear_interpolation'
import { TrackPolicy } from './policy/policy'
export type Label = Label2D | Label3D
/** Convert policy type name to enum */
export function policyFromString (
typeName: string
): TrackPolicyType {
switch (typeName) {
case TrackPolicyType.LINEAR_INTERPOLATION:
return TrackPolicyType.LINEAR_INTERPOLATION
case TrackPolicyType.NONE:
return TrackPolicyType.NONE
}
throw new Error(`Unrecognized policy type: ${typeName}`)
}
/** Returns a function for creating a policy object based on the track type */
export function policyFactoryMaker (policyType: TrackPolicyType): (
track: Track,
type: string,
label2DTemplates: {[name: string]: Label2DTemplateType}
) => TrackPolicy {
switch (policyType) {
case TrackPolicyType.NONE:
return (track: Track) => new TrackPolicy(track)
case TrackPolicyType.LINEAR_INTERPOLATION:
return linearInterpolationPolicyFactory
}
throw new Error(`Invalid policy type ${policyType}`)
}
/** Factory for linear interpolation policies */
export function linearInterpolationPolicyFactory (
track: Track,
type: string,
label2DTemplates: {[name: string]: Label2DTemplateType}
): TrackPolicy {
switch (type) {
case LabelTypeName.BOX_2D:
return new Box2DLinearInterpolationPolicy(track)
case LabelTypeName.BOX_3D:
return new Box3DLinearInterpolationPolicy(track)
case LabelTypeName.PLANE_3D:
return new Plane3DLinearInterpolationPolicy(track)
case LabelTypeName.POLYGON_2D:
case LabelTypeName.POLYLINE_2D:
return new PolygonLinearInterpolationPolicy(track)
}
if (type in label2DTemplates) {
return new CustomLabel2DLinearInterpolationPolicy(track)
}
throw new Error(
`Linear interpolation is not supported for track type ${type}`
)
}
/**
* Object representation of track
*/
export class Track {
/** policy */
protected _policy: TrackPolicy
/** track state */
protected _track: TrackType
/** shape map */
protected _shapes: { [index: number]: IndexedShapeType[] }
/** label map */
protected _labels: { [index: number]: LabelType }
/** updated indices */
protected _updatedIndices: Set<number>
/** type */
protected _type: string
constructor () {
this._track = makeTrack(-1, LabelTypeName.EMPTY)
this._policy = new TrackPolicy(this)
this._shapes = {}
this._labels = {}
this._updatedIndices = new Set()
this._type = ''
}
/**
* Run when state is updated
* @param state
*/
public updateState (state: State, id: number) {
this._track = state.task.tracks[id]
const policyType = policyFromString(
state.task.config.policyTypes[state.user.select.policyType]
)
if (policyType !== this.policyType) {
this._policy = policyFactoryMaker(policyType)(
this,
this._track.type,
state.task.config.label2DTemplates
)
}
const items = Object.keys(this._track.labels).map((key) => Number(key))
this._labels = Object.assign({}, _.pick(this._labels, items))
this._shapes = Object.assign({}, _.pick(this._shapes, items))
for (const item of items) {
const labelId = this._track.labels[item]
const label = state.task.items[item].labels[labelId]
this._labels[item] = label
this._shapes[item] = []
for (const shapeId of label.shapes) {
this._shapes[item].push(state.task.items[item].shapes[shapeId])
}
}
}
/**
* Get track policy
*/
public get policyType (): TrackPolicyType {
return this._policy.type
}
/**
* Get track id
*/
public get id () {
return this._track.id
}
/** Get track type */
public get type () {
return this._type
}
/** Get indices where the track has labels */
public get indices (): number[] {
return Object.keys(this._labels).map(
(key) => Number(key)
).sort(
(a, b) => a - b
)
}
/** Get label at index */
public getLabel (index: number): Readonly<LabelType> | null {
if (index in this._labels) {
return this._labels[index]
}
return null
}
/** Get shapes at item index */
public getShapes (
index: number
): Readonly<Array<Readonly<IndexedShapeType>>> {
if (index in this._shapes) {
return this._shapes[index]
}
return []
}
/** Set shapes at item index */
public setShapes (
index: number,
shapes: IndexedShapeType[]
) {
this._updatedIndices.add(index)
this._shapes[index] = shapes
}
/** Add updated index */
public addUpdatedIndex (index: number) {
this._updatedIndices.add(index)
}
/** Get updated indices */
public get updatedIndices (): Readonly<number[]> {
return Array.from(this._updatedIndices)
}
/** Clear updated indices */
public clearUpdatedIndices () {
this._updatedIndices.clear()
}
/**
* Get newly created labels when creating track
* @param itemIndex
* @param label
*/
public init (
itemIndex: number,
label: Readonly<Label>,
numItems: number,
parentTrack?: Track
): void {
this._shapes = {}
this._labels = {}
this._type = label.type
const labelState = label.label
const [,shapeTypes, shapeStates] = label.shapeStates()
for (let index = itemIndex; index < itemIndex + numItems; index ++) {
const cloned = _.cloneDeep(labelState) as LabelType
cloned.item = -1
if (index > itemIndex) {
cloned.manual = false
}
if (parentTrack) {
const parentLabel = parentTrack.getLabel(index)
if (parentLabel) {
cloned.item = index
cloned.parent = parentLabel.id
}
} else {
cloned.item = index
}
if (cloned.item === index) {
this._labels[index] = cloned
this._shapes[index] = []
for (let i = 0; i < shapeTypes.length; i++) {
this._shapes[index].push(makeIndexedShape(
-1, [-1], shapeTypes[i], _.cloneDeep(shapeStates[i])
))
}
this._updatedIndices.add(index)
}
}
}
/**
* Callback for when a label in the track is updated
* @param itemIndex
* @param newShapes
*/
public update (itemIndex: number, label: Readonly<Label>): void {
const [ids, shapeTypes, newShapes] = label.shapeStates()
if (
itemIndex in this._shapes &&
newShapes.length === this._shapes[itemIndex].length
) {
this._updatedIndices.add(itemIndex)
this._shapes[itemIndex].length = ids.length
for (let i = 0; i < newShapes.length; i++) {
this._shapes[itemIndex][i].id = ids[i]
this._shapes[itemIndex][i].type = shapeTypes[i]
this._shapes[itemIndex][i].shape = newShapes[i]
}
this._labels[itemIndex] = {
...this._labels[itemIndex],
...label.label
}
this._policy.update(itemIndex, this._track.id)
}
}
}
|
f978f6d9f305f55dbc249aae6a723de6b4a453d0
|
TypeScript
|
SivaCse/AngularUnitTestingShowcase
|
/src/app/services/auth.service.ts
| 2.75
| 3
|
import { Injectable } from '@angular/core';
import { AuthApiService } from './auth-api.service';
@Injectable()
export class AuthService {
private _isLoggedIn = false;
public get isLoggedIn() {
return this._isLoggedIn;
}
private _username = "";
public get username() {
return this._username;
}
constructor(
private _authApi: AuthApiService
) { }
// Synchronous calls, they do not use a remote service, used to show sync testing features
public login(username: string, password: string): boolean {
this._username = username;
this._isLoggedIn = true;
return true;
}
public logout(): boolean {
this._username = "";
this._isLoggedIn = false;
return true;
}
public getLoggedUser(): string {
return this.username;
}
// Asynchronous calls, they use a remote service, used to show stubs and async testing features
/* with Promise, less readable than async/await
public loginAsync(username: string, password: string): Promise<boolean> {
return this._authApi.login(username, password)
.then(result => {
if (result === true) {
this._isLoggedIn = true;
this._username = username;
}
return result;
});
}
public logoutAsync(): Promise<boolean> {
return this._authApi.logout()
.then(result => {
if (result === true) {
this._username = "";
this._isLoggedIn = false;
}
return result;
});
}
public getLoggedUserAsync(): Promise<string> {
return this._authApi.getLoggedUser()
.then(result => {
this._username = result;
this._isLoggedIn = result != null && result !== "";
return result;
});
}
*/
public async loginAsync(username: string, password: string): Promise<boolean> {
const result = await this._authApi.login(username, password);
if (result === true) {
this._isLoggedIn = true;
this._username = username;
}
return result;
}
public async logoutAsync(): Promise<boolean> {
const result = await this._authApi.logout();
if (result === true) {
this._username = "";
this._isLoggedIn = false;
}
return result;
}
public async getLoggedUserAsync(): Promise<string> {
const result = await this._authApi.getLoggedUser();
this._username = result;
this._isLoggedIn = result != null && result !== "";
return result;
}
}
|