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
|
|---|---|---|---|---|---|---|
d3e87c4ea4f8efe7cdee6335e776019e8e29de00
|
TypeScript
|
Blackdread/lens
|
/packages/core/src/renderer/search-store/search-store.ts
| 3.046875
| 3
|
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { action, computed, observable, makeObservable } from "mobx";
import autoBind from "auto-bind";
export class SearchStore {
/**
* An utility methods escaping user string to safely pass it into new Regex(variable)
* @param value Unescaped string
*/
public static escapeRegex(value?: string): string {
return value ? value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") : "";
}
constructor() {
makeObservable(this);
autoBind(this);
}
/**
* Text in the search input
*
* @observable
*/
@observable searchQuery = "";
/**
* Array with line numbers, eg [0, 0, 10, 21, 21, 40...]
*
* @observable
*/
@observable occurrences: number[] = [];
/**
* Index within the occurrences array. Showing where is activeOverlay currently located
*
* @observable
*/
@observable activeOverlayIndex = -1;
/**
* Sets default activeOverlayIndex
* @param text An array of any textual data (logs, for example)
* @param query Search query from input
*/
@action
public onSearch(text?: string[] | null, query = this.searchQuery): void {
this.searchQuery = query;
if (!query) {
return this.reset();
}
this.occurrences = this.findOccurrences(text ?? [], query);
if (!this.occurrences.length) {
return;
}
// If new highlighted keyword in exact same place as previous one, then no changing in active overlay
if (this.occurrences[this.activeOverlayIndex] === undefined) {
this.activeOverlayIndex = this.getNextOverlay(true);
}
}
/**
* Does searching within text array, create a list of search keyword occurrences.
* Each keyword "occurrence" is saved as index of the line where keyword was found
* @param lines An array of any textual data (logs, for example)
* @param query Search query from input
* @returns Array of line indexes [0, 0, 14, 17, 17, 17, 20...]
*/
private findOccurrences(lines: string[], query?: string): number[] {
const regex = new RegExp(SearchStore.escapeRegex(query), "gi");
return lines
.flatMap((line, index) => Array.from(line.matchAll(regex), () => index));
}
/**
* Getting next overlay index within the occurrences array
* @param loopOver Allows to jump from last element to first
* @returns next overlay index
*/
private getNextOverlay(loopOver = false): number {
const next = this.activeOverlayIndex + 1;
if (next > this.occurrences.length - 1) {
return loopOver ? 0 : this.activeOverlayIndex;
}
return next;
}
/**
* Getting previous overlay index within the occurrences array of occurrences
* @param loopOver Allows to jump from first element to last one
* @returns previous overlay index
*/
private getPrevOverlay(loopOver = false): number {
const prev = this.activeOverlayIndex - 1;
if (prev < 0) {
return loopOver ? this.occurrences.length - 1 : this.activeOverlayIndex;
}
return prev;
}
public setNextOverlayActive(): void {
this.activeOverlayIndex = this.getNextOverlay(true);
}
public setPrevOverlayActive(): void {
this.activeOverlayIndex = this.getPrevOverlay(true);
}
/**
* Gets line index of where active overlay is located
* @returns A line index within the text/logs array
*/
@computed get activeOverlayLine(): number {
return this.occurrences[this.activeOverlayIndex];
}
@computed get activeFind(): number {
return this.activeOverlayIndex + 1;
}
@computed get totalFinds(): number {
return this.occurrences.length;
}
/**
* Checks if overlay is active (to highlight it with orange background usually)
* @param line Index of the line where overlay is located
* @param occurrence Number of the overlay within one line
*/
public isActiveOverlay(line: number, occurrence: number): boolean {
const firstLineIndex = this.occurrences.findIndex(item => item === line);
return firstLineIndex + occurrence === this.activeOverlayIndex;
}
@action
private reset(): void {
this.searchQuery = "";
this.activeOverlayIndex = -1;
this.occurrences = [];
}
}
|
14bde59ebd14cce24b6e7056fbf2b4f89bac62e5
|
TypeScript
|
eduardovecino/bs-assistant
|
/src/rest/routes/cards.ts
| 2.546875
| 3
|
import { Request, Response } from "express";
import { CardService } from "../../services/card.service";
import { CardManager } from "../../managers/card.manager";
export class CardRoutes {
private cardService: CardService;
constructor() {
this.cardService = new CardService();
}
public routes(app): void {
app.route('/cards')
.get((req: Request, res: Response) => {
this.cardService.getCards().then(cards => {
if(cards){
const carouselOfCards = CardManager.cardsCarousel(cards);
res.status(200).send(carouselOfCards);
} else {
res.status(400).send('No se ha encontrado las tarjetas');
}
})
})
app.route('/cards/:last4/movements')
.get((req: Request, res: Response) => {
this.cardService.getCard(req.params.last4).then(card => {
if (card) {
const movementsTable = CardManager.generateMovementsTable(card);
res.status(200).send(movementsTable);
} else {
res.status(400).send('No se ha encontrado la tarjeta');
}
})
})
}
}
|
8282206ee41e3faac76d5a482779bdc134dfa504
|
TypeScript
|
francoisgeorgy/react-svg-knob
|
/src/knobConfig.ts
| 2.828125
| 3
|
export const TRACE = false;
export const VIEWBOX_WIDTH = 100;
export const VIEWBOX_HEIGHT = 100;
export const HALF_WIDTH = 50; // viewBox/2
export const HALF_HEIGHT = 50; // viewBox/2
export const NS = "http://www.w3.org/2000/svg";
export const CW = true; // clock-wise
export const CCW = !CW; // counter clock-wise
export type PublicKnobConfigType = {
angle_max?: number;
angle_min?: number;
center_value?: null;
center_zero?: boolean;
default_value?: number;
display_raw?: boolean;
format?: (v: any) => any;
format_raw?: (v: number) => number;
initial_value?: number;
mouse_wheel_acceleration?: number;
rotation?: boolean;
snap_to_steps?: boolean;
value_max?: number;
value_min?: number;
value_position?: number
value_resolution?: number;
value_text?: boolean;
zero_at?: number;
}
export type KnobConfigType = {
angle_max: number;
angle_min: number;
center_value: null;
center_zero: boolean;
default_value: number;
display_raw: boolean;
format: (v: any) => any;
format_raw: (v: number) => number;
initial_value: number;
mouse_wheel_acceleration: number;
rotation: boolean;
snap_to_steps: boolean;
value_max: number;
value_min: number;
value_position: number
value_resolution: number;
value_text: boolean;
zero_at: number;
}
export const DEFAULT_CONFIG: KnobConfigType = {
rotation: CW,
default_value: 0,
initial_value: 0,
value_min: 0.0,
value_max: 100.0,
value_resolution: 1, // null means ignore
// split knob:
center_zero: false,
center_value: null, // if null, the value will be computed from the min and max in the init() method
// position:
zero_at: 270.0, // [deg] (polar) the 0 degree will be at 270 polar degrees (6 o'clock).
angle_min: 30.0, // [deg] Angle in knob coordinates (0 at 6 0'clock)
angle_max: 330.0, // [deg] Angle in knob coordinates (0 at 6 0'clock)
// text displayed in the middle of the knob:
value_text: true,
value_position: HALF_HEIGHT + 8, // empirical value: HALF_HEIGHT + config.font_size / 3
// callback to get the text to display from the current value
display_raw: false, // if true, format callback is ignored
format_raw: (v: number) => Math.round(v),
format: (v: number) => v.toFixed(0), // formatting of the displayed value
// off_text: null, // text to display when raw_value = min
// out_of_range_text: null, // text to display when raw_value is out of range
snap_to_steps: false, // TODO
// mouse wheel support:
mouse_wheel_acceleration: 1
}
|
d08f59d500d3a2e6b7bef7ac714f2ddf1fb79cb1
|
TypeScript
|
concord-consortium/collaborative-learning
|
/src/models/tiles/geometry/geometry-model.ts
| 2.53125
| 3
|
import { difference, intersection } from "lodash";
import { applySnapshot, getSnapshot, getType, Instance, SnapshotIn, types } from "mobx-state-tree";
import { kDefaultBoardModelInputProps, kGeometryTileType } from "./geometry-types";
import { uniqueId } from "../../../utilities/js-utils";
import { typeField } from "../../../utilities/mst-utils";
import { TileContentModel } from "../tile-content";
import { ESegmentLabelOption, JXGChange, JXGPositionProperty } from "./jxg-changes";
import { imageChangeAgent } from "./jxg-image";
import { movableLineChangeAgent } from "./jxg-movable-line";
import { createPoint } from "./jxg-point";
import { polygonChangeAgent } from "./jxg-polygon";
import { vertexAngleChangeAgent } from "./jxg-vertex-angle";
import { kGeometryDefaultPixelsPerUnit } from "./jxg-types";
export interface IDependsUponResult {
depends: boolean;
dependencies: string[];
required: boolean;
}
export interface IAxisProperties {
name?: string;
label?: string;
min?: number;
unit?: number;
range?: number;
}
export const AxisModel = types.model("AxisModel", {
name: types.maybe(types.string),
label: types.maybe(types.string),
min: types.number,
unit: kGeometryDefaultPixelsPerUnit,
range: types.maybe(types.number)
})
.actions(self => ({
setName(name: string) {
self.name = name;
},
setLabel(label: string) {
self.label = label;
},
setMin(min: number) {
self.min = min;
},
setUnit(unit: number) {
self.unit = unit;
},
setRange(range: number) {
self.range = range;
}
}));
export interface AxisModelType extends Instance<typeof AxisModel> {}
export interface AxisModelSnapshot extends SnapshotIn<typeof AxisModel> {}
export const BoardModel = types.model("BoardModel", {
xAxis: AxisModel,
yAxis: AxisModel
});
export interface BoardModelType extends Instance<typeof BoardModel> {}
export const defaultBoard = () => BoardModel.create(kDefaultBoardModelInputProps);
export const GeometryObjectModel = types.model("GeometryObject", {
type: types.optional(types.string, () => {throw "Type must be overridden";}),
id: types.optional(types.identifier, () => uniqueId())
})
.views(self => ({
get dependencies(): string[] {
return [];
}
}))
.views(self => ({
dependsUpon(ids: string[]): IDependsUponResult {
const dependencies = intersection(ids, self.dependencies);
// by default all dependencies are required, i.e. object should be deleted if dependent is deleted
const depCount = dependencies.length;
return { depends: depCount > 0, dependencies, required: depCount > 0 };
}
}))
.actions(self => ({
setPosition(position: JXGPositionProperty) {
// ignored by base model
},
setText(text: string) {
// ignored by base model
},
removeDependencies(ids: string[]) {
// ignored by base model
}
}));
export interface GeometryObjectModelType extends Instance<typeof GeometryObjectModel> {}
// JSON.stringify converts undefined to null, which is invalid for position values.
// This function, suitable for use as a preProcessSnapshot handler, converts null
// position values back to undefined. One might think that one could handle this with a
// single preProcessSnapshot handler on the PositionedObjectModel, but that changes the
// types of the models in ways that breaks the build. ¯\_(ツ)_/¯ Therefore, we reuse
// this function in each final model that "derives" from PositionedObjectModel.
function preProcessPositionInSnapshot(snap: any) {
return snap?.x === null || snap?.y === null
? {
...snap,
// convert nulls to undefined
x: snap.x ?? undefined,
y: snap.y ?? undefined
}
: snap;
}
export const PositionedObjectModel = GeometryObjectModel
.named("PositionedObject")
.props({
x: types.maybe(types.number),
y: types.maybe(types.number)
})
.actions(self => ({
setPosition(position: JXGPositionProperty) {
const x = position[position.length - 2];
const y = position[position.length - 1];
(x != null) && (self.x = x);
(y != null) && (self.y = y);
}
}));
export interface PositionedObjectModelType extends Instance<typeof PositionedObjectModel> {}
export const isPositionedObjectModel = (o: GeometryObjectModelType): o is PositionedObjectModelType =>
Object.hasOwn(o, "x") && Object.hasOwn(o, "y");
export const CommentModel = PositionedObjectModel
.named("CommentModel")
.props({
type: typeField("comment"),
// multiple anchors to support polygon line segment comments, for instance
anchors: types.array(types.string), // ids of anchor objects
text: types.maybe(types.string)
})
.preProcessSnapshot(preProcessPositionInSnapshot)
.views(self => ({
get dependencies(): string[] {
return self.anchors;
}
}))
.actions(self => ({
setText(text: string) {
self.text = text;
}
}));
export interface CommentModelType extends Instance<typeof CommentModel> {}
export const isCommentModel = (o?: GeometryObjectModelType): o is CommentModelType => o?.type === "comment";
export const PointModel = PositionedObjectModel
.named("PointModel")
.props({
type: typeField("point"),
name: types.maybe(types.string),
fillColor: types.maybe(types.string),
strokeColor: types.maybe(types.string),
snapToGrid: types.maybe(types.boolean),
snapSizeX: types.maybe(types.number),
snapSizeY: types.maybe(types.number)
})
.preProcessSnapshot(preProcessPositionInSnapshot);
export interface PointModelType extends Instance<typeof PointModel> {}
export const isPointModel = (o?: GeometryObjectModelType): o is PointModelType => o?.type === "point";
export const segmentIdFromPointIds = (ptIds: [string, string]) => `${ptIds[0]}:${ptIds[1]}`;
export const pointIdsFromSegmentId = (segmentId: string) => segmentId.split(":");
export const PolygonSegmentLabelModel = types.model("PolygonSegmentLabel", {
id: types.identifier, // {pt1Id}:{pt2Id}
option: types.enumeration<ESegmentLabelOption>("LabelOption", Object.values(ESegmentLabelOption))
});
export interface PolygonSegmentLabelModelType extends Instance<typeof PolygonSegmentLabelModel> {}
export interface PolygonSegmentLabelModelSnapshot extends SnapshotIn<typeof PolygonSegmentLabelModel> {}
export const PolygonModel = GeometryObjectModel
.named("PolygonModel")
.props({
type: typeField("polygon"),
points: types.array(types.string),
labels: types.maybe(types.array(PolygonSegmentLabelModel))
})
.views(self => ({
get dependencies(): string[] {
return self.points;
},
hasSegmentLabel(ptIds: [string, string]) {
return !!self.labels?.find(label => label.id === segmentIdFromPointIds(ptIds));
},
getSegmentLabel(ptIds: [string, string]) {
const found = self.labels?.find(label => label.id === segmentIdFromPointIds(ptIds));
return found ? found.option : undefined;
}
}))
.views(self => ({
dependsUpon(ids: string[]): IDependsUponResult {
const dependencies = intersection(ids, self.dependencies);
// points can be removed from polygons until there are at least two vertices remaining
const depCount = dependencies.length;
return { depends: depCount > 0, dependencies, required: depCount > self.points.length - 2 };
}
}))
.actions(self => ({
removeDependencies(ids: string[]) {
self.points.replace(difference(self.points, ids));
},
replacePoints(ids: string[]) {
self.points.replace(ids);
},
setSegmentLabel(ptIds: [string, string], option: ESegmentLabelOption) {
const id = segmentIdFromPointIds(ptIds);
const value = { id, option };
const foundIndex = self.labels?.findIndex(label => label.id === id);
// remove any existing label if setting label to "none"
if (option === ESegmentLabelOption.kNone) {
if (self.labels && foundIndex != null && foundIndex >= 0) {
self.labels.splice(foundIndex, 1);
}
}
// replace the label if the segment is already labeled
else if (self.labels && foundIndex != null && foundIndex >= 0) {
self.labels[foundIndex] = value;
}
else if (!self.labels) {
// TODO: there must be a more efficient way to initialize an MST array
applySnapshot(self, { ...getSnapshot(self), labels: [value] });
}
else {
self.labels.push(value);
}
}
}));
export interface PolygonModelType extends Instance<typeof PolygonModel> {}
export const isPolygonModel = (o?: GeometryObjectModelType): o is PolygonModelType => o?.type === "polygon";
export const VertexAngleModel = GeometryObjectModel
.named("VertexAngleModel")
.props({
type: typeField("vertexAngle"),
points: types.refinement(types.array(types.string), v => v?.length === 3),
radius: types.maybe(types.number)
})
.views(self => ({
get dependencies(): string[] {
return self.points;
}
}))
.actions(self => ({
replacePoints(ids: string[]) {
self.points.replace(ids);
}
}));
export interface VertexAngleModelType extends Instance<typeof VertexAngleModel> {}
export const isVertexAngleModel = (o?: GeometryObjectModelType): o is VertexAngleModelType =>
o?.type === "vertexAngle";
export const MovableLineModel = GeometryObjectModel
.named("MovableLineModel")
.props({
type: typeField("movableLine"),
p1: PointModel,
p2: PointModel
});
export interface MovableLineModelType extends Instance<typeof MovableLineModel> {}
export const isMovableLineModel = (o?: GeometryObjectModelType): o is MovableLineModelType =>
o?.type === "movableLine";
export const isMovableLinePointId = (id: string) => /.*-point[12]/.test(id);
export const ImageModel = PositionedObjectModel
.named("ImageModel")
.props({
type: typeField("image"),
url: types.string,
filename: types.maybe(types.string),
width: types.number, // coordinate system size (not pixels)
height: types.number // coordinate system size (not pixels)
})
.preProcessSnapshot(preProcessPositionInSnapshot)
.actions(self => ({
setUrl(url: string) {
self.url = url;
}
}));
export interface ImageModelType extends Instance<typeof ImageModel> {}
export const isImageModel = (o: GeometryObjectModelType): o is ImageModelType => o.type === "image";
export function createObject(board: JXG.Board, obj: GeometryObjectModelType) {
const objType = getType(obj);
switch(objType.name) {
case ImageModel.name: {
const image = obj as ImageModelType;
const { x, y, url, width, height, ...properties } = image;
const change: JXGChange = {
operation: "create",
target: "image",
parents: [url, [x, y], [width, height]],
properties
};
imageChangeAgent.create(board, change);
break;
}
case MovableLineModel.name: {
const line = obj as MovableLineModelType;
const { p1, p2, ...properties } = line;
const change: JXGChange = {
operation: "create",
target: "movableLine",
parents: [[p1.x, p1.y], [p2.x, p2.y]],
properties
};
movableLineChangeAgent.create(board, change);
break;
}
case PointModel.name: {
const pt = obj as PointModelType;
const { x, y, ...props } = pt;
createPoint(board, [pt.x, pt.y], props);
break;
}
case PolygonModel.name: {
const poly = obj as PolygonModelType;
const { points, ...properties } = poly;
const change: JXGChange = {
operation: "create",
target: "polygon",
parents: poly.points.filter(id => !!id) as string[],
properties
};
polygonChangeAgent.create(board, change);
break;
}
case VertexAngleModel.name: {
const angle = obj as VertexAngleModelType;
const { points, ...properties } = angle;
const change: JXGChange = {
operation: "create",
target: "vertexAngle",
parents: angle.points.filter(id => !!id) as string[],
properties
};
vertexAngleChangeAgent.create(board, change);
break;
}
}
}
export type GeometryObjectModelUnion = CommentModelType | ImageModelType | MovableLineModelType | PointModelType |
PolygonModelType | VertexAngleModelType;
// Define the shape of the geometry content without the views/actions, etc. to avoid circular references
export const GeometryBaseContentModel = TileContentModel
.named("GeometryBaseContent")
.props({
type: types.optional(types.literal(kGeometryTileType), kGeometryTileType),
board: types.maybe(BoardModel),
bgImage: types.maybe(ImageModel),
objects: types.map(types.union(CommentModel, MovableLineModel, PointModel, PolygonModel, VertexAngleModel)),
// Used for importing table links from legacy documents
links: types.array(types.string) // table tile ids
})
.preProcessSnapshot(snapshot => {
// fix null table links ¯\_(ツ)_/¯
if (snapshot.links?.some(link => link == null)) {
snapshot = { ...snapshot, links: snapshot.links.filter(link => link != null) };
}
if (!snapshot.board) {
return { ...snapshot, board: defaultBoard() };
}
return snapshot;
})
.postProcessSnapshot(snapshot => {
// Remove links from snapshot
const { links, ...rest } = snapshot;
return { ...rest };
})
.actions(self => ({
replaceLinks(newLinks: string[]) {
self.links.replace(newLinks);
}
}));
export interface GeometryBaseContentModelType extends Instance<typeof GeometryBaseContentModel> {}
export interface GeometryBaseContentSnapshotType extends Instance<typeof GeometryBaseContentModel> {}
export const MigratedExtrasModel = types.model("MigratedExtras", {
extras: types.maybe(types.model("Extras", { title: types.maybe(types.string) }))
});
// Allow additional information to be returned from imports
export const GeometryExtrasContentModel = types.compose(
"GeometryExtraContent", GeometryBaseContentModel, MigratedExtrasModel);
export interface GeometryExtrasContentModelType extends Instance<typeof GeometryExtrasContentModel> {}
export interface GeometryExtrasContentSnapshotType extends SnapshotIn<typeof GeometryExtrasContentModel> {}
interface ICloneGeometryObjectOptions {
idMap: Record<string, string>;
offset?: {
x: number;
y: number;
};
}
export function cloneGeometryObject(
obj: GeometryObjectModelType, options: ICloneGeometryObjectOptions
): GeometryObjectModelType | undefined {
const { idMap, offset } = options || {};
const id = idMap[obj.id] || uniqueId();
function offsetPos(o: GeometryObjectModelType) {
return isPositionedObjectModel(o) && o.x != null && o.y != null && offset
? { x: o.x + offset.x, y: o.y + offset.y }
: undefined;
}
if (isPointModel(obj)) {
return PointModel.create({ ...obj, id, ...offsetPos(obj) });
}
if (isPolygonModel(obj)) {
const points = obj.points.map(ptId => idMap[ptId]);
const _labels = obj.labels?.map(label => {
const [p1Id, p2Id] = pointIdsFromSegmentId(label.id);
return { ...label, id: `${segmentIdFromPointIds([idMap[p1Id], idMap[p2Id]])}`, };
});
const labels = _labels ? { labels: _labels } : undefined;
// all vertices must be selected/copied to copy a polygon
if (points.every(ptId => !!ptId)) {
return PolygonModel.create({ ...obj, id, points, ...labels });
}
}
if (isVertexAngleModel(obj)) {
const points = obj.points.map(ptId => idMap[ptId]);
// all vertices must be selected/copied to copy a vertexAngle
if (points.every(ptId => !!ptId)) {
return VertexAngleModel.create({ ...obj, id, points });
}
}
if (isMovableLineModel(obj)) {
const { id: _id, p1, p2, ...others } = obj;
const _p1 = PointModel.create({ ...p1, id: `${id}-point1`, ...offsetPos(p1) });
const _p2 = PointModel.create({ ...p2, id: `${id}-point2`, ...offsetPos(p2) });
return MovableLineModel.create({ ...others, id, p1: _p1, p2: _p2 });
}
if (isCommentModel(obj)) {
const anchors = obj.anchors.map(anchorId => idMap[anchorId]);
if (anchors.every(srcId => !!srcId)) {
return CommentModel.create({ ...obj, id, anchors });
}
}
}
|
6faa219ecd81e2473723cb1e04c1739097f9052f
|
TypeScript
|
AuHau/sequelize-store
|
/test/index.spec.ts
| 2.625
| 3
|
import chai from 'chai'
import dirtyChai from 'dirty-chai'
import chaiAsPromised from 'chai-as-promised'
import { QueryTypes, Sequelize } from 'sequelize'
import { init, getObject, reset, purge, getEndPromise } from '../src'
chai.use(chaiAsPromised)
chai.use(dirtyChai)
const expect = chai.expect
function sleep<T> (ms: number, ...args: T[]): Promise<T> {
return new Promise(resolve => setTimeout(() => resolve(...args), ms))
}
describe('SequelizeStore', function () {
let sequelize: Sequelize
async function getDbEntries (): Promise<object> {
// noinspection SqlDialectInspection,SqlNoDataSourceInspection,ES6RedundantAwait
const results = await sequelize.query('SELECT * FROM `data-store`', {
type: QueryTypes.SELECT
})
return results.reduce((previous: object, current: object) => {
// @ts-ignore
previous[current.key] = current.value
return previous
}, {})
}
beforeEach(async () => {
sequelize = new Sequelize('sqlite://:memory:')
await sequelize.sync()
reset()
})
it('should create model in Sequelize', async () => {
await init(sequelize, { key: 'string' })
expect(sequelize.isDefined('sequelizeStore-dbstore')).to.be.true()
})
it('should set and get data', async () => {
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.string = 'hey'
obj.int = 1
obj.float = 2.3
obj.object = { some: 'object' }
expect(obj.bool).to.eql(false)
expect(obj.string).to.eql('hey')
expect(obj.int).to.eql(1)
expect(obj.float).to.eql(2.3)
expect(obj.object).to.eql({ some: 'object' })
await sleep(100)
const dbEntries = await getDbEntries()
expect(dbEntries).to.eql({
bool: 'false',
string: 'hey',
int: '1',
float: '2.3',
object: '{"some":"object"}'
})
})
it('should load data on init from db', async () => {
await init(sequelize, { key: 'string' })
sequelize.query('INSERT INTO `data-store` (`key`,`value`) VALUES (\'bool\',\'false\'), (\'string\',\'hey\'), (\'int\',\'1\'), (\'float\',\'2.3\'), (\'object\',\'{"some":"object"}\')', {
type: QueryTypes.INSERT
})
reset()
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const dbEntries = await getDbEntries()
expect(dbEntries).to.eql({
bool: 'false',
string: 'hey',
int: '1',
float: '2.3',
object: '{"some":"object"}'
})
const obj = getObject()
expect(obj.bool).to.eql(false)
expect(obj.string).to.eql('hey')
expect(obj.int).to.eql(1)
expect(obj.float).to.eql(2.3)
expect(obj.object).to.eql({ some: 'object' })
})
it('should delete from the object', async () => {
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.string = 'hey'
obj.int = 1
obj.float = 2.3
obj.object = { some: 'object' }
delete obj.string
expect(obj.int).to.eql(1)
expect(obj.float).to.eql(2.3)
expect(obj.object).to.eql({ some: 'object' })
await sleep(100)
const dbEntries = await getDbEntries()
expect(dbEntries).to.eql({
bool: 'false',
int: '1',
float: '2.3',
object: '{"some":"object"}'
})
})
it('should give defaults if set', async () => {
await init(sequelize, {
string: { type: 'string', default: 'ahoj' },
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
expect(obj.string).to.eql('ahoj')
expect(obj.bool).to.be.undefined()
})
it('should list values', async () => {
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.string = 'hey'
obj.int = 1
expect(Object.entries(obj)).to.eql([['bool', false], ['string', 'hey'], ['int', 1]])
})
describe('purge', function () {
it('should remove data from database and local store', async () => {
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.string = 'hey'
obj.int = 1
obj.float = 2.3
obj.object = { some: 'object' }
await sleep(100)
expect(obj.string).to.eql('hey')
let dbEntries = await getDbEntries()
expect(dbEntries).to.eql({
bool: 'false',
string: 'hey',
int: '1',
float: '2.3',
object: '{"some":"object"}'
})
await purge()
await sleep(100)
dbEntries = await getDbEntries()
expect(dbEntries).to.eql({})
expect(obj.string).to.be.undefined()
})
})
describe('scope', function () {
it('should scope get operation', async () => {
await init(sequelize, {
prefixString: 'string',
bool: 'bool',
prefixInt: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.prefixString = 'hey'
obj.prefixInt = 1
obj.float = 2.3
obj.object = { some: 'object' }
const prefixedObj = getObject('prefix')
expect(prefixedObj.String).to.eql('hey')
expect(prefixedObj.Int).to.eql(1)
expect(() => prefixedObj.bool).to.throw('Property prefixbool was not defined in Store\'s schema!')
})
it('should scope set operation', async () => {
await init(sequelize, {
prefixString: 'string',
bool: 'bool',
prefixInt: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.prefixString = 'hey'
obj.prefixInt = 1
obj.float = 2.3
obj.object = { some: 'object' }
const prefixedObj = getObject('prefix')
prefixedObj.String = 'hola'
expect(prefixedObj.String).to.eql('hola')
expect(obj.prefixString).to.eql('hola')
})
it('should scope delete operation', async () => {
await init(sequelize, {
prefixString: 'string',
bool: 'bool',
prefixInt: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.prefixString = 'hey'
obj.prefixInt = 1
obj.float = 2.3
obj.object = { some: 'object' }
const prefixedObj = getObject('prefix')
delete prefixedObj.String
expect(prefixedObj.String).to.be.undefined()
expect(obj.prefixString).to.be.undefined()
})
})
describe('getEndPromise', function () {
it('should wait for the db modifications to finish', async () => {
await init(sequelize, {
string: 'string',
bool: 'bool',
int: 'int',
float: 'float',
object: 'json'
})
const obj = getObject()
obj.bool = false
obj.string = 'hey'
obj.int = 1
obj.float = 2.3
obj.object = { some: 'object' }
expect(obj.bool).to.eql(false)
expect(obj.string).to.eql('hey')
expect(obj.int).to.eql(1)
expect(obj.float).to.eql(2.3)
expect(obj.object).to.eql({ some: 'object' })
expect(getEndPromise()).to.be.fulfilled()
})
})
})
|
4f08d3ab6a24a54eb3b3a5a00186e15cef9e953d
|
TypeScript
|
joshfeinsilber/word-chain-server
|
/src/Challenges.ts
| 3.625
| 4
|
import { shuffle } from "lodash"
export enum ChallengeCategory {
letterCount = "letterCount",
partOfSpeech = "partOfSpeech",
containsLetter = "containsLetter",
endsWithLetter = "endsWithLetter",
doesNotContainLetter = "doesNotContainLetter"
}
export interface Challenge {
category: ChallengeCategory
values: any[]
textDescription: string
}
const categories = [
ChallengeCategory.letterCount,
ChallengeCategory.partOfSpeech,
ChallengeCategory.containsLetter,
ChallengeCategory.endsWithLetter,
ChallengeCategory.doesNotContainLetter
]
export const validLetterCounts = [3, 4, 5, 6]
export const validPartsOfSpeech = ["verb", "adjective"]
export const validContainsLetter = ["s", "t", "l", "m", "n", "p"]
export const validEndsWithLetter = ["s", "t", "l", "m", "n", "p"]
export const validDoesNotContainLetter = ["a", "e", "i", "o", "u"]
export const getChallenge = (existingChallenge?: Challenge) => {
let challenge: Challenge = {
category: null,
values: [],
textDescription: ""
}
const category = shuffle(
categories.filter(c => {
if (!existingChallenge) {
return true
}
return existingChallenge.category !== c
})
)[0]
challenge.category = category
if (category === ChallengeCategory.letterCount) {
const letterCount = shuffle(validLetterCounts)[0]
challenge.values.push(letterCount)
challenge.textDescription = `at least ${letterCount} letters`
}
if (category === ChallengeCategory.partOfSpeech) {
const partOfSpeech = shuffle(validPartsOfSpeech)[0]
challenge.values.push(partOfSpeech)
challenge.textDescription = `${partOfSpeech}`
}
if (category === ChallengeCategory.containsLetter) {
const containingLetter = shuffle(validContainsLetter)[0]
challenge.values.push(containingLetter)
challenge.textDescription = `contains "${containingLetter}"`
}
if (category === ChallengeCategory.endsWithLetter) {
const endsWithLetter = shuffle(validEndsWithLetter)[0]
challenge.values.push(endsWithLetter)
challenge.textDescription = `ends with "${endsWithLetter}"`
}
if (category === ChallengeCategory.doesNotContainLetter) {
const doesNotContainLetter = shuffle(validDoesNotContainLetter)[0]
challenge.values.push(doesNotContainLetter)
challenge.textDescription = `does not contain "${doesNotContainLetter}"`
}
return challenge
}
|
20ff8f2777a202d323c91f4c1f36e406ba0b1287
|
TypeScript
|
dejvids/Angular-Material-playground
|
/src/app/contacts/contacts.component.ts
| 2.53125
| 3
|
import { Component, OnInit } from '@angular/core';
import { Contact } from './Contact';
@Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.css']
})
export class ContactsComponent implements OnInit {
contacts: Contact[];
constructor() {
}
ngOnInit() {
this.contacts = this.getSampleContacts();
}
getSampleContacts():Contact[] {
let contacts = [
new Contact("Dawid", "Suryś", "dsurys"),
new Contact("Piotr", "Szłapa", "pszlapa"),
new Contact("Tomasz", "Grabowski", "graba"),
new Contact("Marta", "Okoń", "mokon")]
return contacts;
}
}
|
37c9ddccb68b07394f3145312f0afa34d9656c28
|
TypeScript
|
alexghr/node-stats
|
/src/tracker.test.ts
| 2.953125
| 3
|
import 'jest';
import { createStatsTracker, StatsTracker } from './tracker';
import { StatsEventName } from './stats';
const TIMEOUT = 100;
describe('tracker', () => {
let tracker: StatsTracker;
beforeEach(() => {
jest.clearAllMocks();
tracker = createStatsTracker();
});
describe('can track functions', () => {
const sync = jest.fn().mockName('sync').mockReturnValue(undefined);
const async = jest.fn().mockName('async').mockResolvedValue(undefined)
it.each([sync, async])('emits a `Call` event whenever the target function is called', (func: jest.Mock, done) => {
expect.assertions(2);
const CALL_NUM = 10;
const callback = jest.fn();
const proxy = tracker.trackStats({ target: func });
tracker.stats.on(StatsEventName.Call, callback);
for (let i = 0; i < CALL_NUM; ++i) {
proxy();
}
setTimeout(() => {
expect(callback).toHaveBeenCalledTimes(CALL_NUM);
expect(callback).toHaveBeenCalledWith(func.name);
done();
}, TIMEOUT);
});
it('emits a `CallResolved` event after the function finished (sync)', (done) => {
expect.assertions(1);
// track when `sync` returns
let time: number;
const proxy = tracker.trackStats({ target: sync });
tracker.stats.on(StatsEventName.CallResolved, () => {
// CallResolved needs to be called after `time` (or at the very least on the same millisecond)
expect(Date.now()).toBeGreaterThanOrEqual(time);
});
proxy();
time = Date.now();
setTimeout(done, TIMEOUT);
});
it('emits a `CallResolved` event after the function\'s return promise is resolved (async)', (done) => {
expect.assertions(1);
// track when `func`'s return value is resolved
let time: number;
const proxy = tracker.trackStats({ target: async });
tracker.stats.on(StatsEventName.CallResolved, () => {
// CallResolved needs to be called after `time` (or at the very least on the same millisecond)
expect(Date.now()).toBeGreaterThanOrEqual(time);
});
const result = proxy();
result.then(() => time = Date.now());
setTimeout(done, TIMEOUT);
});
it.each([sync, async])('tracks how long the target function takes to run', (func: jest.Mock, done) => {
testTime(func, StatsEventName.CallResolved, done);
});
it.each([sync, async])('emits a `CallRejected` event if the function throws an error', (func: jest.Mock, done) => {
expect.assertions(1);
const callback = jest.fn();
func.mockImplementationOnce(() => { throw new Error() });
const proxy = tracker.trackStats({ target: func });
tracker.stats.on(StatsEventName.CallRejected, callback);
try {
proxy();
} catch { }
setTimeout(() => {
expect(callback).toHaveBeenCalled();
done();
}, TIMEOUT);
});
it('emits a `CallRejected` event if the function\'s returned Promise is rejected', (done) => {
expect.assertions(1);
const callback = jest.fn();
async.mockRejectedValueOnce(new Error('test'));
const proxy = tracker.trackStats({ target: async });
tracker.stats.on(StatsEventName.CallRejected, callback);
proxy();
setTimeout(() => {
expect(callback).toHaveBeenCalled();
done();
}, TIMEOUT);
});
it.each([sync, async])('tracks how long the target function before it throws', (func: jest.Mock, done) => {
func.mockImplementationOnce(() => { throw new Error('foo') })
testTime(func, StatsEventName.CallRejected, done);
});
it('tracks how long the target function before it\'s promise is rejected', (done) => {
async.mockRejectedValueOnce(new Error('test'));
testTime(async, StatsEventName.CallRejected, done);
});
function testTime(func: (...args: any[]) => any, eventName: StatsEventName, done: Function) {
expect.assertions(1);
const callback = jest.fn();
const proxy = tracker.trackStats({ target: func });
tracker.stats.on(eventName, callback);
try {
proxy();
} catch { }
setTimeout(() => {
expect(callback.mock.calls[0][1]).toBeGreaterThan(0);
done();
}, TIMEOUT);
}
});
describe('can track function properties on objects', () => {
it('does not change properties which are not functions', (done) => {
expect.assertions(4);
const callCb = jest.fn();
const resolvedCb = jest.fn();
const rejectedCb = jest.fn();
tracker.stats.on(StatsEventName.Call, callCb);
tracker.stats.on(StatsEventName.CallResolved, resolvedCb);
tracker.stats.on(StatsEventName.CallRejected, rejectedCb);
const proxy = tracker.trackStats({ target: { foo: 'foo prop' }, name: 'test' });
expect(proxy.foo).toBe('foo prop');
setTimeout(() => {
expect(callCb).not.toHaveBeenCalled();
expect(resolvedCb).not.toHaveBeenCalled();
expect(rejectedCb).not.toHaveBeenCalled();
done();
}, TIMEOUT);
});
it('does create proxies for properties which are functions', (done) => {
expect.assertions(4);
const callCb = jest.fn();
const resolvedCb = jest.fn();
const rejectedCb = jest.fn();
tracker.stats.on(StatsEventName.Call, callCb);
tracker.stats.on(StatsEventName.CallResolved, resolvedCb);
tracker.stats.on(StatsEventName.CallRejected, rejectedCb);
const proxy = tracker.trackStats({ target: { foo() { return 'foo'; }, }, name: 'test' });
expect(typeof proxy.foo).toBe('function');
proxy.foo();
setTimeout(() => {
expect(callCb).toHaveBeenCalledWith('test.foo');
expect(resolvedCb).toHaveBeenCalledWith('test.foo', expect.any(Number));
expect(rejectedCb).not.toHaveBeenCalled();
done();
}, TIMEOUT);
});
});
});
|
618ac159d12ff28625030fd50eca158ddab0c679
|
TypeScript
|
hyperskill/hs-test-web
|
/hstest/handler/eventHandler.ts
| 2.703125
| 3
|
import puppeteer from "puppeteer";
class EventHandler {
static async waitForEvent(eventName: string, pageInstance: puppeteer.Page,
elementHandle: puppeteer.ElementHandle | null,
timeout = 10000): Promise<any> {
async function pageFunction (event: string, elementHandle: HTMLElement,
timeout: number): Promise<boolean> {
const element = elementHandle || window;
let isEventHappened = false;
function listener () {
isEventHappened = true;
}
function sleep (ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
const sleepTimeout = 200;
element.addEventListener(event, listener);
try {
const startTime = performance.now();
const checkTimeout = (): boolean => {
return (performance.now() - startTime) < (timeout - sleepTimeout);
};
while (!isEventHappened) {
if (!checkTimeout()) {
return false;
}
await sleep(sleepTimeout);
}
return true;
} finally {
element.removeEventListener(event, listener);
}
}
return pageInstance.evaluate(pageFunction, eventName, elementHandle, timeout);
}
}
export default EventHandler;
|
f7a93fbc2f736c07c2c0630b33c4405e5a2f8790
|
TypeScript
|
rstedman/tfs-pullrequest-dashboard
|
/test/pullRequestFilter.pipe.spec.ts
| 2.546875
| 3
|
import {PullRequestAsyncStatus, User} from "../src/app/model";
import {PullRequestFilterPipe} from "../src/app/pullRequestFilter.pipe";
import {PullRequestViewModel} from "../src/app/pullRequestViewModel";
import {TestUtils} from "./testHelpers";
describe("PullRequestFilterPipe", () => {
function createPRViewModel(createdBy: string, reviewers: string[]): PullRequestViewModel {
const user: User = {
id: "user1",
displayName: "test user",
uniqueName: "testuser1",
memberOf: [
TestUtils.createIdentity("team1"),
TestUtils.createIdentity("team2")
]
};
const repo: GitRepository = {
_links: {
web: {
href: "http://git/repo"
}
},
defaultBranch: "master",
url: `http://git/repo`,
id: "repo",
name: "repo",
project: null,
remoteUrl: `http://git/repo`
};
const pr = TestUtils.createPullRequest({
created: new Date(),
createdById: createdBy,
id: 1,
mergeStatus: PullRequestAsyncStatus.Succeeded,
sourceBranch: "testbranch",
targetBranch: "master",
title: "test123",
reviewers: reviewers.map( (x) => {
return {
id: x,
required: false,
vote: 0
};
})
});
return new PullRequestViewModel(pr, repo, user);
}
let subject: PullRequestFilterPipe = null;
beforeEach(() => {
subject = new PullRequestFilterPipe();
});
it("returns an emtpy list if given an empty list", () => {
const result = subject.transform([], "requestedByMe");
expect(result).toBeDefined();
expect(result.length).toEqual(0);
});
it("returns only PRs requested by me when filtered", () => {
const pr1 = createPRViewModel("user2", []);
const pr2 = createPRViewModel("user1", ["user2"]);
const pr3 = createPRViewModel("user3", ["user2", "user1"]);
const pr4 = createPRViewModel("user1", ["user2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "requestedByMe");
expect(result).toBeDefined();
expect(result.length).toEqual(2);
expect(result[0]).toEqual(pr2);
expect(result[1]).toEqual(pr4);
});
it("returns returns an empty list if no prs requested by me when filtered", () => {
const pr1 = createPRViewModel("user2", []);
const pr2 = createPRViewModel("user4", ["user2"]);
const pr3 = createPRViewModel("user3", ["user2", "user1"]);
const pr4 = createPRViewModel("user2", ["user1"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "requestedByMe");
expect(result).toBeDefined();
expect(result.length).toEqual(0);
});
it("returns PRs assignedToMe when filtered", () => {
const pr1 = createPRViewModel("user2", ["user3", "user5", "user1", "user10"]);
const pr2 = createPRViewModel("user1", ["user2"]);
const pr3 = createPRViewModel("user3", ["user2", "user1"]);
const pr4 = createPRViewModel("user1", ["user2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMe");
expect(result).toBeDefined();
expect(result.length).toEqual(2);
expect(result[0]).toEqual(pr1);
expect(result[1]).toEqual(pr3);
});
it("doesn't return PRs assignedToMe if also createdByMe", () => {
const pr1 = createPRViewModel("user1", ["user3", "user5", "user1", "user10"]);
const pr2 = createPRViewModel("user1", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user1"]);
const pr4 = createPRViewModel("user1", ["user2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMe");
expect(result).toBeDefined();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(pr3);
});
it("returns an empty list if no PRs assignedtoMe", () => {
const pr1 = createPRViewModel("user2", ["user3", "user5", "user4", "user10"]);
const pr2 = createPRViewModel("user3", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user5"]);
const pr4 = createPRViewModel("user5", ["user2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMe");
expect(result).toBeDefined();
expect(result.length).toEqual(0);
});
it("returns PRs assignedToMyTeam when filtered", () => {
const pr1 = createPRViewModel("user2", ["user3", "team1", "user4", "user10"]);
const pr2 = createPRViewModel("user3", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user5"]);
const pr4 = createPRViewModel("user5", ["team2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMyTeam");
expect(result).toBeDefined();
expect(result.length).toEqual(2);
expect(result[0]).toEqual(pr1);
expect(result[1]).toEqual(pr4);
});
it("doesn't return PRs assignedToMyTeam if also requestedByMe", () => {
const pr1 = createPRViewModel("user1", ["user3", "team1", "user4", "user10"]);
const pr2 = createPRViewModel("user3", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user5"]);
const pr4 = createPRViewModel("user5", ["team2"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMyTeam");
expect(result).toBeDefined();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(pr4);
});
it("returns an empty list if no PRs assignedToMyTeam", () => {
const pr1 = createPRViewModel("user3", ["user3", "team4", "user4", "user10"]);
const pr2 = createPRViewModel("user3", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user5"]);
const pr4 = createPRViewModel("user5", ["team3"]);
const result = subject.transform([pr1, pr2, pr3, pr4], "assignedToMyTeam");
expect(result).toBeDefined();
expect(result.length).toEqual(0);
});
it("returns all other PRs if filtering for other", () => {
const pr1 = createPRViewModel("user1", []); // matches requestedByMe
const pr2 = createPRViewModel("user3", ["user2"]);
const pr3 = createPRViewModel("user2", ["user2", "user1"]); // matches assignedToMe
const pr4 = createPRViewModel("user5", ["team3"]);
const pr5 = createPRViewModel("user5", ["team1"]); // matches assignedToMyTeam
const result = subject.transform([pr1, pr2, pr3, pr4, pr5], "other");
expect(result).toBeDefined();
expect(result.length).toEqual(2);
expect(result[0]).toEqual(pr2);
expect(result[1]).toEqual(pr4);
});
it("doesn't return PRs assignedToMyTeam if also assignedToMe", () => {
const pr1 = createPRViewModel("user3", ["user1", "team1", "user4", "user10"]);
const pr2 = createPRViewModel("user2", ["team1", "user5"]);
const result = subject.transform([pr1, pr2], "assignedToMyTeam");
expect(result).toBeDefined();
expect(result.length).toEqual(1);
expect(result[0]).toEqual(pr2);
const result2 = subject.transform([pr1, pr2], "assignedToMe");
expect(result2).toBeDefined();
expect(result2.length).toEqual(1);
expect(result2[0]).toEqual(pr1);
});
});
|
d0ec118a8d4b64623358bd29c506c9e4e653677e
|
TypeScript
|
seatsio/seatsio-js
|
/tests/events/createEvents.test.ts
| 2.5625
| 3
|
import { TestUtils } from '../testUtils'
import { TableBookingConfig } from '../../src/Events/TableBookingConfig'
import { Category } from '../../src/Charts/Category'
import { LocalDate } from '../../src/LocalDate'
import { CreateEventParams } from '../../src/Events/CreateEventParams'
test('should check that a minimum of one event is required', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
try {
await client.events.createMultiple(chartKey)
} catch (e: any) {
expect(e.errors.length).toEqual(1)
expect(e.errors[0].code).toBe('GENERAL_ERROR')
expect(e.errors[0].message).toBe('#/events: expected minimum item count: 1, found: 0')
}
})
test('should check that an empty object is a valid event definition', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
const events = await client.events.createMultiple(chartKey, [new CreateEventParams()])
expect(events).toHaveLength(1)
expect(events[0].key).toBeTruthy()
})
test('should create a single event', async () => {
const { client } = await TestUtils.createTestUserAndClient()
const chart = await client.charts.create()
const events = await client.events.createMultiple(chart.key, [
new CreateEventParams().withKey('eventKey')
])
expect(events).toHaveLength(1)
expect(events[0].key).toEqual('eventKey')
const retrievedEvent = await client.events.retrieve('eventKey')
expect(retrievedEvent.key).toEqual('eventKey')
})
test('should create multiple events', async () => {
const { client } = await TestUtils.createTestUserAndClient()
const chart = await client.charts.create()
const events = [
new CreateEventParams().withKey('eventKey1'),
new CreateEventParams().withKey('eventKey2')
]
const createdEvents = await client.events.createMultiple(chart.key, events)
expect(createdEvents).toHaveLength(2)
expect(createdEvents[0].key).toEqual('eventKey1')
expect(createdEvents[1].key).toEqual('eventKey2')
})
test('supports tableBookingConfig custom', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChartWithTables(chartKey, user.secretKey)
const tableBookingConfig = TableBookingConfig.custom({ T1: 'BY_TABLE', T2: 'BY_SEAT' })
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withTableBookingConfig(tableBookingConfig)
])
expect(events[0].key).toBeTruthy()
expect(events[0].tableBookingConfig).toEqual(tableBookingConfig)
})
test('supports tableBookingConfig inherit', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChartWithTables(chartKey, user.secretKey)
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withTableBookingConfig(TableBookingConfig.inherit())
])
expect(events[0].key).toBeTruthy()
expect(events[0].tableBookingConfig).toEqual(TableBookingConfig.inherit())
})
test('it supports object categories', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withObjectCategories({ 'A-1': 10 })
])
expect(events[0].objectCategories).toEqual({ 'A-1': 10 })
})
test('it supports categories', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
const eventCategory = new Category('eventCat1', 'Event Level Category', '#AAABBB', false)
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withCategories([eventCategory])
])
expect(events[0].categories!.length).toEqual(4) // 3 from sampleChart.json, 1 event level category
expect(events[0].categories!.filter((cat: Category) => cat.key === 'eventCat1').length).toEqual(1)
expect(events[0].categories!.filter((cat: Category) => cat.key === 'eventCat1')[0].label).toEqual('Event Level Category')
expect(events[0].categories!.filter((cat: Category) => cat.key === 'eventCat1')[0].color).toEqual('#AAABBB')
})
test('it supports name', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withName('My event')
])
expect(events[0].name).toBe('My event')
})
test('it supports date', async () => {
const { client, user } = await TestUtils.createTestUserAndClient()
const chartKey = TestUtils.getChartKey()
await TestUtils.createTestChart(chartKey, user.secretKey)
const events = await client.events.createMultiple(chartKey, [
new CreateEventParams().withDate(new LocalDate(2020, 1, 8))
])
expect(events[0].date).toEqual(new LocalDate(2020, 1, 8))
})
|
f59daa2dda4d98224b51007f6845144115faea4a
|
TypeScript
|
oleg-prikhodko/AdventOfCode2020
|
/25/solution.ts
| 3.171875
| 3
|
function transform(subject: number, loopSize: number) {
let value = subject;
let loop = 1;
while (loop < loopSize) {
value = value * subject;
value = value % 20201227;
loop++;
}
return value;
}
function* getValueStream(subject: number) {
let value = 1;
while (true) {
value = value * subject;
value = value % 20201227;
yield value;
}
}
function getLoopValue(pk: number, subject: number) {
const valueStream = getValueStream(subject);
let loop = 1;
for (const value of valueStream) {
if (value === pk) break;
loop++;
}
return loop;
}
const subject = 7;
const cardsPk = 8252394;
const doorsPk = 6269621;
const cardsLoopSize = getLoopValue(cardsPk, subject);
const encryptionKey = transform(doorsPk, cardsLoopSize);
console.log(encryptionKey);
|
b66a555e5654e25550158588349aaba4e676afc5
|
TypeScript
|
benedicteb/country-visualizer
|
/src/utils.ts
| 2.640625
| 3
|
const ALL_COUNTRIES_URL = "https://restcountries.eu/rest/v2/all";
const kilometerSquaredToMilSquared = (kilometer: number): number => {
return kilometer * 0.3861;
};
const downloadListOfCountries = (
fields = ["name", "area", "population", "region", "languages"]
): Promise<Country[]> => {
return fetch(`${ALL_COUNTRIES_URL}?fields=${fields.join(";")}`)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(json => json as Country[]);
};
export { kilometerSquaredToMilSquared, downloadListOfCountries };
|
6d09fd4534f74135463f4497dd4e186444264681
|
TypeScript
|
StoneT2000/brain.js
|
/src/activation/tanh.ts
| 3.40625
| 3
|
/**
* Hyperbolic tan
*/
export function activate(weight: number): number {
return Math.tanh(weight);
}
/**
* @description grad for z = tanh(x) is (1 - z^2)
*/
export function measure(weight: number, error: number): number {
return (1 - weight * weight) * error;
}
|
8ffc32ef4ca3dbe7dac83352b5a87243f9a1f0d2
|
TypeScript
|
siva253/AKAN-Devices
|
/src/app/shared/Directives/count-to-counter.directive.ts
| 2.546875
| 3
|
import { Directive, OnInit, Input, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';
import { interval } from 'rxjs';
@Directive({
selector: '[appCountToCounter]'
})
export class CountToCounterDirective implements OnInit {
@Input('toValue') toValue:number;
@Output('onCount') onCount:EventEmitter<number> = new EventEmitter<number>();
isShown:boolean = false;
constructor(private el: ElementRef) {
}
ngOnInit(){
}
@HostListener('window:scroll', ['$event']) checkElementVisible(){
var top =this.el.nativeElement.offsetTop;
var parentElement = this.el.nativeElement.offsetParent;
while(parentElement) {
top += parentElement.offsetTop;
parentElement = parentElement.offsetParent;
}
if(window.innerHeight >= (top - window.scrollY) && !this.isShown)
{
this.isShown = true;
const mynumbers = interval(50);
mynumbers.subscribe(
n =>{
if(n > this.toValue)
return;
this.onCount.emit(n);
});
}
}
}
|
ca0a177ea6a7785cb35093d802ca33ba35337fb6
|
TypeScript
|
oooookk7/bust-it
|
/api/src/handlers/actionHandler.ts
| 2.5625
| 3
|
import { GameStateEnum, ActionTypeEnum, SocketInEventEnum, GameErrorTypeEnum, SocketOutEventEnum } from '../globals/enums'
import { SocketActionEventPayload, GameStatusInfo, ErrorInfo } from '../globals/types';
import { Sessions } from '../sessions';
import { Socket } from '../socket';
import { actionHelper } from '../helpers/actionHelper';
import { logger } from '../utils';
export const actionHandler = (socket: Socket, sessions: Sessions) => {
const onErrorFn = (gameId: string, errorInfo: ErrorInfo) => {
if (errorInfo.type === GameErrorTypeEnum.GAME_INVALID_STATE) {
return socket.send(SocketOutEventEnum.ERROR, errorInfo);
}
socket.broadcast(SocketOutEventEnum.ERROR, errorInfo);
};
const onActionEvent = (payload: SocketActionEventPayload) => {
switch (payload.type) {
case ActionTypeEnum.SHUFFLE:
case ActionTypeEnum.DRAW:
actionHelper(sessions, socket.room(), socket.id, payload.type).then((gameInfo: any | GameStatusInfo) => {
socket.broadcastP2P(payload.type === ActionTypeEnum.SHUFFLE ? SocketOutEventEnum.SHUFFLED : SocketOutEventEnum.DRAWN, gameInfo);
}).catch((errorInfo: ErrorInfo) => {
onErrorFn(socket.room(), errorInfo);
});
break;
case ActionTypeEnum.NEXT:
actionHelper(sessions, socket.room(), socket.id, payload.type).then((gameInfo: any | GameStatusInfo) => {
if (gameInfo.state === GameStateEnum.ENDED) {
// Game will be auto removed. Players disconnect on their end.
socket.broadcast(SocketOutEventEnum.ENDED, gameInfo);
}
else if (gameInfo.round_result) {
socket.broadcast(SocketOutEventEnum.RESULT, gameInfo);
}
else {
socket.broadcastP2P(SocketOutEventEnum.PLAYER_TURN, gameInfo);
}
}).catch((errorInfo: ErrorInfo) => {
onErrorFn(socket.room(), errorInfo);
});
}
};
socket.on(SocketInEventEnum.ACTION, onActionEvent);
};
|
a44f235ce3bcdfebf302b5090e4e36638082a0e6
|
TypeScript
|
nikhilrwadekar/deno
|
/basics/server.ts
| 2.734375
| 3
|
// Server (http module)
import { serve } from "https://deno.land/std/http/server.ts";
const server = serve({port: 3000})
console.log('Listening for requests on Port 3000')
// For loop for await (No limitter)
for await (const req of server) {
const url = req.url;
req.respond({body: `Hello Again! You visited ${url}`})
}
|
3259d2184bc10eebe6d020102110e0b5be54f70e
|
TypeScript
|
RayMa1n/clovermon-showdown
|
/data/mods/clover/rulesets.ts
| 3.046875
| 3
|
export const Rulesets: {[k: string]: ModdedFormatData} = {
blobbosclause: {
effectType: 'ValidatorRule',
name: 'Blobbos Clause',
desc: "Blobbos cannot use Eviolite. It does not need Eviolite.",
onValidateSet(set) {
if (this.toID(set.item) === 'eviolite' && this.toID(set.species || set.name) === 'blobbos') {
return ['Blobbos cannot use Eviolite. It is far too powerful for such an item.'];
}
},
},
cloveronly: {
effectType: 'ValidatorRule',
name: 'Clover Only',
desc: "Only allows Pokémon, items, and moves available in Pokémon Clover.",
onValidateSet(set) {
const errors = [];
const species = this.dex.species.get(set.species || set.name);
if (!species.availability?.clover) {
errors.push(`${species.baseSpecies} is not in Pokémon Clover.`);
}
const item = this.dex.items.get(set.item);
if (item && item.id && item.id !== '' && !item.availability?.clover) {
errors.push(`${set.name || set.species} has ${item.name}, which is unavailable in Pokémon Clover.`);
}
const ability = this.dex.abilities.get(set.ability);
if (ability && !ability.availability?.clover) {
errors.push(`${set.name || set.species} has ${ability.name}, which is unavailable in Pokémon Clover.`);
}
set.moves.forEach((moveName) => {
const move = this.dex.moves.get(this.toID(moveName));
if (!this.toID(moveName).startsWith('hiddenpower') && !move.availability?.clover) {
errors.push(`${set.name || set.species} has ${move}, which is unavailable in Pokémon Clover.`);
}
});
if (errors.length > 0) {
return errors;
}
},
},
originalityclause: {
effectType: 'ValidatorRule',
name: 'Originality Clause',
desc: "Requires 3 Clovermons and 3 non-Clovermons.",
onValidateTeam(team) {
const totalClovermons = team.reduce((total, set) => {
const species = this.dex.species.get(set.species || set.name);
return total + (species.availability?.clover ? 1 : 0);
}, 0);
if (Math.floor(team.length / 2) !== totalClovermons) {
return ['Your team requires equal number of Clovermons and non-Clovermons.'];
}
},
},
multitier: {
effectType: 'ValidatorRule',
name: 'Multi-Tier',
desc: "Requires 1 Uber, 1 OU mon, 2 UU mons, and 2 RU mons.",
onValidateTeam(team) {
let uber = 0;
let ou = 0;
let uu = 0;
let ru = 0;
team.forEach((set) => {
const species = this.dex.species.get(set.species || set.name);
if (species.tier === 'Uber') {
uber++;
} else if (species.tier === 'OU') {
ou++;
} else if ((species.tier === 'UU') || (species.tier === 'RUBL')) {
uu++;
} else if ((species.tier === 'RU') || (species.tier === 'LC') || (species.tier === 'NFE')) {
ru++;
}
});
const errors = [];
if (uber + ou + uu + ru !== 6) {
errors.push('This format requires teams of 6.');
}
if (uber !== 1) {
errors.push('This format requires exactly 1 Uber per team.');
}
if (ou !== 1) {
errors.push('This format requires exactly 1 OU mon per team.');
}
if (uu !== 2) {
errors.push('This format requires exactly 2 UU mons per team.');
}
if (ru !== 2) {
errors.push('This format requires exactly 2 RU (or equivalent) mons per team.');
}
return errors;
},
},
};
|
b761382e5a00c7f278522d4bcbc985ecf975e87a
|
TypeScript
|
krsepp/wallester-test
|
/src/services/reqres.ts
| 2.5625
| 3
|
import IListUsers from '../interfaces/IListUsers';
import ISingleUser from '../interfaces/ISingleUser';
const API_ENDPOINT = 'https://reqres.in/api/';
export async function getListUsers(page: number): Promise<IListUsers> {
const response = await fetch(`${API_ENDPOINT}users?page=${page}`);
return await response.json();
}
export async function getSingleUser(id: number): Promise<ISingleUser> {
const response = await fetch(`${API_ENDPOINT}users/${id}`);
return await response.json();
}
export async function createUser(name: string, job: string) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = JSON.stringify({
'name': name,
'job': job
});
let requestOptions: object = {
method: 'POST',
headers: headers,
body: body,
};
const response = await fetch(`${API_ENDPOINT}users`, requestOptions);
return await response.json();
}
|
0cb67a4efaf8fbff8ed01bc26a3d3774c99186c3
|
TypeScript
|
MaddyKilmurray/adoptapetFron
|
/src/app/adopt/adopt.component.ts
| 2.515625
| 3
|
import { Adopter } from './../models/adopter.model';
import { AnimalAdoptionAPIServiceService } from './../animal-adoption-apiservice.service';
import { Animal } from './../models/animal.model';
import { Component, OnInit } from '@angular/core';
import { Adopted } from '../models/adopted.model';
@Component({
selector: 'adopt',
templateUrl: './adopt.component.html',
styleUrls: ['./adopt.component.css']
})
export class AdoptComponent implements OnInit {
startAge: number;
endAge: number;
type:string;
adopterName:string;
petId:number;
showAdoptionPage=false;
animal: Animal | undefined;
animalsAvailable:Array<Animal>;
adoptableAnimals:Array<Animal>;
adopted:Adopted;
constructor(private animalAdoptionService: AnimalAdoptionAPIServiceService) {
this.animalsAvailable = new Array(new Animal(1,"Freckles","Dog",7,true),
new Animal(2,"Lua","Dog",1,false),
new Animal(3,"Baby","Cat",14,false),
new Animal(4,"Vinnie","Dog",7,true));
this.adoptableAnimals = new Array();
this.startAge = 1;
this.endAge = 100;
this.type = '';
this.adopterName='';
this.petId=0;
this.adopted=new Adopted("",0,"");
}
ngOnInit(): void {
}
searchAnimals():void {
this.animalAdoptionService.searchAnimals(this.startAge,this.endAge,this.type.toUpperCase()).subscribe(apiResponse => {
this.adoptableAnimals = apiResponse;
})
}
switchView(): void {
if(this.showAdoptionPage) {
this.showAdoptionPage = false;
} else {
this.showAdoptionPage = true;
}
}
adopt():void {
this.animalAdoptionService.adoptAnimal(new Adopter(this.adopterName,this.petId)).subscribe(apiResponse => {
this.adopted = apiResponse;
});
}
}
|
f9c53aebceb98d4f7e9293fb38b6ed63f0af9327
|
TypeScript
|
kingsley-einstein/Event-Manager-Frontend
|
/src/app/management/reducers/auth.reducer.ts
| 2.65625
| 3
|
import { AuthActionType, AuthConstants } from "../actions";
import { AuthState, initialAuthState } from "../states";
export default (state: AuthState = initialAuthState, action: AuthActionType): AuthState => {
switch (action.type) {
case AuthConstants.GET_AUTH_SUCCESS:
return { ...state, data: action.payload };
case AuthConstants.GET_AUTH_FAILURE:
return { data: null, error: action.payload };
default:
return state;
}
};
|
06114b26435b0f0d69691a339fe36dfa03ede5f4
|
TypeScript
|
broslukasz/wez-parasol
|
/src/app/weather/weather.service.ts
| 2.515625
| 3
|
import { ChangeDetectorRef, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { from, Observable } from 'rxjs';
import { first, mergeMap } from 'rxjs/operators';
import { WeatherbitHourlyForecast } from '../models/forecast';
interface Coordinates {
readonly accuracy: number;
readonly altitude: number | null;
readonly altitudeAccuracy: number | null;
readonly heading: number | null;
readonly latitude: number;
readonly longitude: number;
readonly speed: number | null;
}
interface Position {
readonly coords: Coordinates;
readonly timestamp: number;
}
@Injectable({
providedIn: 'root'
})
export class WeatherService {
constructor(
private http: HttpClient,
) { }
getForecastForCurrentLocation(): Observable<WeatherbitHourlyForecast> {
return from(new Promise<any>((resolve) => {
navigator.geolocation.getCurrentPosition((position: Position) => {
resolve(position);
});
})).pipe(
mergeMap((position: Position) => {
const hours = this.calculateHours();
return this.http.get<WeatherbitHourlyForecast>(`https://api.weatherbit.io/v2.0/forecast/hourly?lat=${position.coords.latitude}&lon=${position.coords.longitude}&lang=pl&key=635bf53034854830b7f6935482fed58f&hours=${hours}`);
}),
first(),
);
}
private calculateHours(): number {
return 24 - new Date().getHours();
}
}
|
a8d82e844c0b97eda2e17b434798499642483436
|
TypeScript
|
chenxsa/ngx-dynamic-form-builder
|
/apps/demo/src/app/shared/models/exp-user.ts
| 2.640625
| 3
|
import { IsEmail, IsNotEmpty, IsOptional, Validate, ValidateIf, ValidateNested } from 'class-validator-multi-lang';
import { EqualsTo } from '../utils/custom-validators';
import { ExpDepartment } from './exp-department';
export class ExpUser {
id: number;
@IsNotEmpty({
groups: ['user', 'guest', 'new'],
})
username: string;
@IsNotEmpty({
groups: ['guest', 'new'],
})
password: string;
@ValidateIf((o) => o.password, {
groups: ['new'],
})
@IsNotEmpty({
groups: ['new'],
})
@Validate(EqualsTo, ['password'], {
groups: ['new'],
})
rePassword: string;
@IsEmail(undefined, {
groups: ['user'],
})
@IsNotEmpty({
groups: ['user'],
})
email: string;
isSuperuser: boolean;
isStaff: boolean;
@ValidateNested({
groups: ['user'],
})
@IsOptional({
groups: ['user'],
})
department: ExpDepartment;
dateOfBirth?: Date;
constructor(data?: any) {
if (data === undefined) {
data = {};
}
this.username = data.username;
this.password = data.password;
this.rePassword = data.rePassword;
this.email = data.email;
this.isSuperuser = data.isSuperuser;
this.isStaff = data.isStaff;
this.department = new ExpDepartment(data.department);
if (data.dateOfBirth) {
const dateOfBirth = new Date(data.dateOfBirth);
const userTimezoneOffset = dateOfBirth.getTimezoneOffset() * 60000;
this.dateOfBirth = new Date(dateOfBirth.getTime() - userTimezoneOffset);
} else {
this.dateOfBirth = undefined;
}
}
toJSON() {
return {
...this,
department: this.department instanceof ExpDepartment ? this.department.toJSON() : this.department,
dateOfBirth: this.dateOfBirth ? this.dateOfBirth.toISOString() : undefined,
};
}
}
|
31efc2c86dfc64f946e33f8f089ae2ac325ce9b5
|
TypeScript
|
ashish8833/ReactiveAngularNgRx
|
/src/app/store/reducers/book.reducers.ts
| 2.875
| 3
|
import * as fromBookAction from '../actions/';
import { Book } from '../../model/book.model';
export interface BookState {
data : Book[];
loading : boolean;
loadedSucceess : boolean;
loadedFail : boolean;
searchTerms : string;
}
export const intialBookState : BookState = {
data : [],
loading : false,
loadedSucceess : false,
loadedFail : false,
searchTerms : ''
}
export function reducer (
state = intialBookState,
action: fromBookAction.BookActions
) : BookState {
switch(action.type){
case fromBookAction.LOAD_BOOK : {
return {
...state,
loading: true,
loadedSucceess: false,
loadedFail: false
}
}
case fromBookAction.LOAD_BOOK_SUCCESS : {
const data = action.payLoad;
return {
...state,
loading: false,
loadedSucceess: true,
loadedFail : false,
data
}
}
case fromBookAction.LOAD_BOOK_FAIL : {
const data = action.payLoad;
return {
...state,
loading: false,
loadedSucceess: false,
loadedFail : true,
data
}
}
case fromBookAction.SEARCH_BOOK : {
const searchTerms = action.payLoad;
return {
...state,
loading: true,
loadedSucceess: false,
loadedFail : false,
searchTerms
}
}
}
return state;
}
export const getBookLoading = (state:BookState) => state.loading;
export const getBookLodedSuccess = (state:BookState) => state.loadedSucceess;
export const getBookLoadFail = (state:BookState) => state.loadedFail;
export const getBook = (state: BookState) => state.data;
|
9bf3be8c0bbbf435d2c453d32c05384b07a822e9
|
TypeScript
|
z4444a/AIM
|
/frontend/src/redux/reducers/project-suggestion-reducers.ts
| 2.546875
| 3
|
import { ProjectModel } from '../../model/get/project-model';
import { getType, RootAction } from 'typesafe-actions';
import { clearProjectPage, fetchProjectPage } from '../actions/project-actions';
const projectPageReducer = (
state: ProjectModel[] | [] = [],
action: RootAction
): ProjectModel[] | [] => {
switch (action.type) {
case getType(fetchProjectPage.request):
return state;
case getType(fetchProjectPage.success):
return action.payload.content;
case getType(clearProjectPage):
return [];
case getType(fetchProjectPage.failure):
default:
return state;
}
};
export default projectPageReducer;
|
f2c75c33642729d20d1f3c196ace779e6dfd527e
|
TypeScript
|
LittleIronMan/Match2_SanAndreas
|
/Match2_SanAndreas/assets/src/BasePlayField.ts
| 2.984375
| 3
|
import gameConfig from "./GameConfig";
import { LEFT, RIGHT, DOWN, UP, OK } from "./Constants";
import * as C from "./Constants";
import BaseTile from "./BaseTile";
import TileType, { TileTag } from "./TileType";
import Pos from "./Pos";
type Dir = (typeof RIGHT | typeof LEFT);
export interface FieldProps {
/** ширина поля(в тайлах) */
width: number;
/** высота поля(в тайлах) */
height: number;
/** максимальное количество различных цветов тайлов на поле */
countColors: number;
}
export interface SetOnFieldOptions {
/**
* Флаг того, что функция применяется при инициализации поля,
* это означает что тайл нужно сразу поместить на целевую позицию
*/
onInit?: true,
/**
* Тайл размещается на поле после "выпадения" сверху, например.
* Его нужно разместить чуть выше самого верхнего ряда.
*/
onDrop?: true,
/**
* Тайл размещается при его создании по ходу игры,
* как, например, супер-тайлы.
*/
onGenerating?: true
}
type PosHashMap<T> = { [posHash: number]: T };
type TilesSet = PosHashMap<BaseTile>;
const FOUR_SIDES = [{ x: LEFT, y: 0 }, { x: RIGHT, y: 0 }, { x: 0, y: DOWN }, { x: 0, y: UP }];
const DEFAULT_TRIGGER = LEFT;
const DENY_FALL_TO_SIDE = 0;
const MISMATCH_TRIGGER = 1;
const TRIGGER_MATCH = 2;
enum TriggersMatchValue { DENY_FALL_TO_SIDE = 0, MISMATCH_TRIGGER = 1, TRIGGER_MATCH = 1 };
/**
* @class
* @classdesc Базовый класс для игрового поля
*/
export default class BasePlayField {
/** Ширина поля(в тайлах) */
width: number;
/** Высота поля(в тайлах) */
height: number;
/** Максимальное количество различных цветов тайлов на поле */
countColors: number;
/**
* Двумерный массив тайлов(width * height).
* Визуально индексация начинается с верхней-левой ячейки поля.
*/
field: (BaseTile | null)[][];
/** Множество предустановленных тайлов, выпадающих из точек рождения */
dropDownTiles: { [posHash: number]: number[] } = {};
/** Множество заблокированных клеток поля */
blockedCells: PosHashMap<1> = {};
/**
* Для заданной ячейки возвращает рекомендуемое направление движения вниз-вбок В эту ячейку.
* Например, для если для ячейки (3,3) триггер == -1,
* то это означает что рекомендуется падение в эту ячейку ИЗ ЛЕВОГО столбца, при прочих равных.
* Используется для чередования падений вбок в некоторые ячейки.
*/
fallToSideTriggers: { [posHash: number]: Dir } = {};
constructor({ width, height, countColors }: FieldProps) {
this.width = width;
this.height = height;
this.countColors = countColors;
this.field = Array(width);
for (let x = 0; x < width; x++) {
this.field[x] = Array(height);
for (let y = 0; y < height; y++) {
this.field[x][y] = null;
}
}
}
/**
* Функция создания нового тайла на поле,
* Может быть перегружена в классах-наследниках
*/
createTile(type: TileType, color: number = TileTag.ANY_COLOR): BaseTile {
const newTile = new BaseTile(type, color);
return newTile;
}
protected _setTileOnField(tile: BaseTile | null, x: number, y: number) {
const oldTile = this.field[x][y]; // старый тайл на том месте, на которое мы хотим поставить новый тайл
if (oldTile) {
oldTile.onField = false;
}
if (tile && tile.onField && !tile.pos.equals(x, y)) {
// убираем новый тайл с его предыдущего места
this.field[tile.pos.x][tile.pos.y] = null;
}
// устанавливаем тайл на новое место
this.field[x][y] = tile;
if (tile) {
tile.prevPos.set(tile.pos.x, tile.pos.y);
tile.pos.set(x, y);
tile.onField = true;
}
}
/** Ставит(переставляет) тайл на поле, обновляя соответствующие переменные */
setTileOnField(tile: BaseTile | null, x: number, y: number, opts: SetOnFieldOptions = {}) {
this._setTileOnField(tile, x, y);
}
/**
* Инициализация поля с помощью предустановленных чисел.
* Каждому числу соответствует цвет тайла, 0 - пустая клетка.
* Обрати внимание, что матрица arr транспонирована относительно field,
* это сделано для удобного задния поля в коде.
* Вероятно, основное применение этой функции - тестирование.
*/
initWith(arr: number[][]) {
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
let tag = arr[y][x];
if (tag == TileTag.ANY_COLOR) {
tag = this.getRandomColor();
}
if (tag > 0) {
const newTile = this.createTile(TileType.SIMPLE, tag);
this.setTileOnField(newTile, x, y, { onInit: true });
}
else if (tag === TileTag.BLOCKED_CELL) {
const posHash = this.getPosHash(x, y);
this.blockedCells[posHash] = OK;
const newTile = this.createTile(TileType.BLOCK, tag);
this.setTileOnField(newTile, x, y, { onInit: true });
this.setTileOnField(null, x, y);
}
else if (tag === TileTag.BOMB_TAG) {
const bomb = this.createTile(TileType.BOMB, tag);
this.setTileOnField(bomb, x, y, { onInit: true });
}
}
}
}
/**
* (Для тестов) Сравнивает цвета тайлов на поле с соответствующими числами массива.
*/
equals(arr: number[][]) {
let mismatchFound = false;
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
const tag = arr[y][x];
if (tag === TileTag.ANY_COLOR) {
continue;
}
const tile = this.field[x][y];
if (!tile) {
if (tag === TileTag.EMPTY_CELL) {
continue;
}
const posHash = this.getPosHash(x, y);
if (tag === TileTag.BLOCKED_CELL && this.blockedCells[posHash]) {
continue;
}
mismatchFound = true; break;
}
if (tile.color !== tag) {
mismatchFound = true; break;
}
}
if (mismatchFound) {
break;
}
}
return !mismatchFound;
}
getRandomColor(): number {
return Math.floor(Math.random() * this.countColors) + 1;
}
/** Инициализация поля случайным образом */
randomInit() {
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
const color = this.getRandomColor();
const newTile = this.createTile(TileType.SIMPLE, color);
this.setTileOnField(newTile, x, y, { onInit: true });
}
}
}
canTileFallDown(tile: BaseTile): boolean {
const tileDown = this.field[tile.pos.x][tile.pos.y + 1];
if (tileDown) {
// не двигаемся, если под тайлом другой тайл
return false;
}
const downPosHash = this.getPosHash(tile.pos.x, tile.pos.y + 1);
if (this.blockedCells[downPosHash]) {
// не двигаемся, если ячейка снизу заблокирована
return false;
}
return true;
}
canTileFallToSide(tile: BaseTile, dir: Dir, movedTiles: TilesSet): boolean {
const x = tile.pos.x + dir;
const y = tile.pos.y + 1;
if (!this.isValidPos(x, y)) {
return false;
}
const tileDown = this.field[x][y];
if (tileDown) {
// не двигаемся, если под тайлом другой тайл
return false;
}
const downPosHash = this.getPosHash(x, y);
if (this.blockedCells[downPosHash]) {
// не двигаемся, если ячейка снизу заблокирована
return false;
}
let denyFall = true;
for (let yTop = tile.pos.y; yTop >= 0; yTop--) {
const topPosHash = this.getPosHash(x, yTop);
if (this.blockedCells[topPosHash]) {
// если в нише, в которую хотим падать, сверху наткнулись на блокиратор - значит в эту нишу падать МОЖНО
denyFall = false;
break;
}
const topTile = this.field[x][yTop];
if (topTile) {
break;
}
}
if (denyFall) {
return false;
}
// за один вызов фукнции дискретного падения тайлов,
// в столбце из тайлов(без пустот и блокираторов) может упасть вбок только один тайл(самый верхний)
// код ниже проверяет это условие
for (const movedTile of Object.values(movedTiles)) {
if ((movedTile.prevPos.x === tile.pos.x) && (movedTile.prevPos.x !== movedTile.pos.x)) {
// нашелся сдвинутый вниз-вбок тайл из этого-же столбца
if (movedTile.prevPos.y < tile.pos.y) {
// этот тайл был расположен выше текущего тайла
denyFall = true;
for (let yTop = tile.pos.y - 1; yTop > movedTile.prevPos.y; yTop--) {
// если между этими тайлами есть пустые клетки - снимаем запрет
let midTile = this.field[tile.pos.x][yTop];
if (!midTile) {
denyFall = false;
break;
}
// также снимаем запрет, если между этими тайлами есть блокиратор
const topPosHash = this.getPosHash(x, yTop);
if (this.blockedCells[topPosHash]) {
denyFall = false;
break;
}
}
if (denyFall) {
break;
}
}
}
}
if (denyFall) {
return false;
}
return true;
}
/** Функция дискретного перемещения тайлов на единицу СТРОГО ВНИЗ, с учетом других тайлов и особенностей поля. */
oneMoveStrictDownTiles(movedTiles: TilesSet): TilesSet {
/** Множество тайлов, сдвинутых вертикально вниз */
const tilesMovedDown: TilesSet = {};
for (let y = this.height - 2; y >= 0; y--) {
for (let x = 0; x < this.width; x++) {
const posHash = this.getPosHash(x, y);
if (movedTiles[posHash]) {
continue;
}
const tile = this.field[x][y];
if (!tile) {
// тайл не найден в ячейке
continue;
}
if (!this.canTileFallDown(tile)) {
continue;
}
this.setTileOnField(tile, x, y + 1);
const downPosHash = this.getPosHash(x, y + 1);
tilesMovedDown[downPosHash] = tile;
movedTiles[downPosHash] = tile;
}
}
return tilesMovedDown;
}
private moveTileToSide(tile: BaseTile, dir: Dir, movedTiles: TilesSet, lastMovedTiles: TilesSet) {
const x = tile.pos.x + dir;
const y = tile.pos.y + 1;
this.setTileOnField(tile, x, y);
const downPosHash = this.getPosHash(x, y);
this.fallToSideTriggers[downPosHash] = dir;
movedTiles[downPosHash] = tile;
lastMovedTiles[downPosHash] = tile;
}
getTriggersMatchValue(x: number, y: number, dir: Dir, trgrUp: Dir, movedTiles: TilesSet): TriggersMatchValue {
let result: TriggersMatchValue = DENY_FALL_TO_SIDE;
if (!this.isValidPos(x, y)) {
return result;
}
const posHash = this.getPosHash(x, y);
if (movedTiles[posHash]) {
return result;
}
const tile = this.field[x][y];
if (!tile) {
return result;
}
if (this.canTileFallDown(tile)) {
// не трогаем те тайлы, которые могут падать вниз
return result;
}
if (!this.canTileFallToSide(tile, dir, movedTiles)) {
return result;
}
if (trgrUp === -dir) {
result = TRIGGER_MATCH;
}
else {
result = MISMATCH_TRIGGER;
}
return result;
}
/** Функция дискретного перемещения тайлов на единицу ВНИЗ И В БОК, с учетом других тайлов и особенностей поля. */
oneMoveDownAndSideTiles(movedTiles: TilesSet): TilesSet {
/** Множество тайлов, сдвинутых вниз-вбок */
const tilesMovedToSide: TilesSet = {};
for (let y = 0; y <= this.height - 2; y++) {
for (let x = 0; x < this.width; x++) {
let dirToFall: Dir | 0 = 0;
const posHash = this.getPosHash(x, y);
let leftDirTriggerMatch = DENY_FALL_TO_SIDE;
// для каждого тайла проверяем возможность падать вниз-вбок слева направо
for (const dir of [LEFT, RIGHT] as Dir[]) {
let trgrUp = this.fallToSideTriggers[this.getPosHash(x + dir, y + 1)];
if (!trgrUp) {
trgrUp = DEFAULT_TRIGGER;
}
let triggerMatch = this.getTriggersMatchValue(x, y, dir, trgrUp, movedTiles);
if (triggerMatch === TRIGGER_MATCH) {
// тайл может упасть по заданному направлению, и триггер совпадает
dirToFall = dir;
break;
}
if (triggerMatch === DENY_FALL_TO_SIDE) {
if (dir === LEFT) {
// тайл не может падать влево, проверяем правое направление
leftDirTriggerMatch = DENY_FALL_TO_SIDE;
continue;
}
else if (leftDirTriggerMatch === MISMATCH_TRIGGER) {
// тайл не может падать направо, но может налево(но триггер не сопадает),
// значит тайл упадет налево, игнорируя триггер
dirToFall = LEFT;
break;
}
else {
// тайл не может падать ни влево, ни направо
break;
}
}
// далее по коду подразумевается что triggerMatch === MISMATCH_TRIGGER
// проверяем тайл, расположенный на той-же строке, но через один столбец(x + 2 * dir, y)
// который тоже может хотеть упасть в ячейку (x + dir, y + 1)
// будем называть этот тайл "соперником"(rival)
const rivalX = x + 2 * dir;
const rivalDir = -dir as Dir;
let rivalTriggersMatch = this.getTriggersMatchValue(rivalX, y, rivalDir, trgrUp, movedTiles);
if (rivalTriggersMatch === TRIGGER_MATCH) {
// если тайл-соперник тоже хочет падать в эту ячейку(x + dir, y + 1),
// и триггер указывает на него,
// значит соперник будет сдвинут.
this.moveTileToSide(this.field[rivalX][y] as BaseTile, rivalDir, movedTiles, tilesMovedToSide);
if (dir === LEFT) {
leftDirTriggerMatch = DENY_FALL_TO_SIDE;
}
continue;
}
else if (rivalTriggersMatch === DENY_FALL_TO_SIDE) {
if (dir === LEFT) {
// если еще не проверили второе направление падения(направо),
// то проверяем
leftDirTriggerMatch = MISMATCH_TRIGGER;
continue;
}
else if (leftDirTriggerMatch === DENY_FALL_TO_SIDE) {
// тайл не может падать влево, но может направо(но триггер не сопадает),
// значит тайл упадет направо, игнорируя триггер
dirToFall = RIGHT;
break;
}
else if (leftDirTriggerMatch === MISMATCH_TRIGGER) {
// Если тайл имеет возможность падать в оба направления(соперников нет),
// но для обоих направлений не соостветствуют триггеры в ячейках,
// значит тайл будет падать влево, игнорируя триггер в левой ячейке.
dirToFall = LEFT;
break;
}
}
}
if (dirToFall !== 0) {
this.moveTileToSide(this.field[x][y] as BaseTile, dirToFall, movedTiles, tilesMovedToSide);
}
}
}
return tilesMovedToSide;
}
/** Функция дискретного перемещения тайлов на единицу вниз(в т.ч. и вниз-вбок), с учетом других тайлов и особенностей поля. */
oneMoveDownTiles() {
let movedTiles: TilesSet = {}
let needRepeat;
do {
needRepeat = false;
/** Сначала двигаем тайлы вертикально вниз */
const movedStrictDown = this.oneMoveStrictDownTiles(movedTiles);
/** Двигаем вниз-вбок те тайлы, которые не могут падать вертикально вниз */
const movedToSide = this.oneMoveDownAndSideTiles(movedTiles);
if (Object.keys(movedToSide).length > 0) {
needRepeat = true;
}
} while (needRepeat);
let hasNewTiles = false;
// рождаем новые тайлы, если в этом есть необходимость
const y = 0;
for (let x = 0; x < this.width; x++) {
const tile = this.field[x][y];
if (tile) {
// тайлы не рождаются в ячейках, если в них уже есть другие тайлы
continue;
}
const posHash = this.getPosHash(x, y);
if (this.blockedCells[posHash]) {
// запрещаем рождение тайлов в заблокированные клетки поля
continue;
}
let color: number;
const presetColors: number[] | undefined = this.dropDownTiles[posHash];
if (presetColors && presetColors.length > 0) {
color = presetColors.pop() as number;
}
else {
color = this.getRandomColor();
}
const newTile = this.createTile(TileType.SIMPLE, color);
this.setTileOnField(newTile, x, 0, { onDrop: true });
hasNewTiles = true;
}
const hasDownMove = ((Object.keys(movedTiles).length > 0) || hasNewTiles);
return hasDownMove;
}
/** Проверяет что позиция валидна для текущих размеров поля */
isValidPos(x: number, y: number): boolean {
if (x < 0 || x >= this.width) return false;
if (y < 0 || y >= this.height) return false;
return true;
}
/**
* @param x Координата X выбранной ячейки
* @param y Координата Y выбранной ячейки
* @param targetColor Цвет выбранной ячейки
* @returns Группа смежных тайлов того-же цвета, что и в выбранной ячейке.
*/
findGroup(x: number, y: number, targetColor: number): Pos[] {
const result: Pos[] = [];
if (!this.isValidPos(x, y)) {
return result;
}
/** Кэш для ячеек, отмеченных при вычислении группы */
const fieldMask: { [posHash: number]: 1 } = {};
const W = this.width;
fieldMask[this.getPosHash(x, y)] = OK;
let groupToCheck = [new Pos(x, y)];
while (groupToCheck.length > 0) {
const nextGroup: Pos[] = [];
for (const pos of groupToCheck) {
result.push(pos);
for (const delta of FOUR_SIDES) {
const newX = pos.x + delta.x;
const newY = pos.y + delta.y;
if (!this.isValidPos(newX, newY)) {
continue;
}
const newPosHash = this.getPosHash(newX, newY);
if (fieldMask[newPosHash]) {
continue;
}
fieldMask[newPosHash] = OK; // Запоминаем, что эту ячейку мы уже проверили
const tile = this.field[newX][newY];
if (!tile || (tile.color != targetColor)) {
continue;
}
nextGroup.push(new Pos(newX, newY));
}
}
result.concat(groupToCheck);
groupToCheck = nextGroup;
}
return result;
}
/**
* Для выбранного тайла находится группа смежных с ним тайлов того-же цвета.
* Эта группа уничтожается с поля.
*/
strikeTo(x: number, y: number) {
if (!this.isValidPos(x, y)) {
return;
}
const tile = this.field[x][y];
if (!tile) {
return;
}
const group = this.findGroup(x, y, tile.color);
if (group.length < gameConfig.K) {
return;
}
// уничтожаем группу тайлов на поле
group.forEach(pos => {
this.field[pos.x][pos.y] = null;
})
}
/** Хэширует двумерный целочисленный вектор в скаляр. */
getPosHash(x: number, y: number): number {
return y * this.width + x;
}
/** Возвращает зону поражения от взрыва бомбы */
getExplAreaForBomb(x: number, y: number): Pos[] {
const explosion: Pos[] = [];
const R = C.BOMB_EXPLOSION_RADIUS;
for (let dx = -R; dx <= R; dx++) {
for (let dy = -R; dy <= R; dy++) {
if (Math.abs(dx) + Math.abs(dy) > R) {
continue;
}
const xx = x + dx;
const yy = y + dy;
if (!this.isValidPos(xx, yy)) {
continue;
}
const victim = this.field[xx][yy];
if (!victim) {
continue;
}
explosion.push(victim.pos);
}
}
return explosion;
}
}
|
a1f9f03249bb6b199d9b7d9dc5579ac4a1eda29e
|
TypeScript
|
gauravmahto/simple-websocket-server
|
/src/app/run-cmd.ts
| 2.671875
| 3
|
/*
* Copyright 2019 - Author gauravm.git@gmail.com
*/
import { spawn } from 'child_process';
import process from 'process';
import { createLogger } from 'libs/utils';
const logger = createLogger('run-cmd');
const isWinPlatform = (process.platform === 'win32');
export function runCommand({
cmd = '',
onError = logger.error,
onExit = logger.info,
onResponse = logger.info
}: {
cmd: string;
onError: (...args: string[]) => void;
onExit: (code: any) => void;
onResponse: (...args: string[]) => void;
}, ...args: string[]) {
try {
let spawnedChild;
const cmdWithArgs = cmd + ' ' + args.join(' ');
logger.info('Cmd:', cmdWithArgs);
if (isWinPlatform) {
spawnedChild = spawn('cmd.exe', [ '/c', cmdWithArgs ]);
} else {
spawnedChild = spawn(cmdWithArgs, [], { shell: true });
}
if (spawnedChild) {
spawnedChild.stdout.on('data', (data) => {
logger.info(data.toString());
onResponse(data.toString());
});
spawnedChild.stderr.on('data', (data) => {
logger.error(data.toString());
onError(data.toString());
});
spawnedChild.on('exit', (code) => {
logger.info(`Child exited with code ${code}`);
onExit(code);
});
}
} catch (err) {
logger.error(err);
}
}
|
c7ac0f96df96ed5135b5fe0835afd625a22cba68
|
TypeScript
|
jopika/Resumemon
|
/src/App.ts
| 2.765625
| 3
|
import express from "express";
import {parse} from "./parse";
import { generatePowerLevel } from "./powerLevel";
import {generateMoveSet} from "./MoveSetGenerator";
import {getType, PokeType} from "./typeGenerator";
import {Pokemon} from "./Pokemon";
import {Move} from "./Move";
import {getPokemonByType} from "./pokemonGenerator";
import {getPokemonImageString} from "./pokemonSpriteGenerator";
import {BattleSimulator} from "./BattleSimulator";
const fs = require('fs');
const multer = require('multer');
const upload = multer({
dest: 'uploads/' // this saves your file into a directory called "uploads"
});
const app = express();
app.set("port", process.env.PORT || 3000);
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/../src/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/../src/public/index.html');
});
app.post('/', upload.array('file-to-upload', 2), (req, res) => {
const pokemons: Promise<Pokemon>[] = [];
for (const file of (req.files as Express.Multer.File[])) {
let pdfData = fs.readFileSync('uploads/' + file.filename);
let buzzwordsData = fs.readFileSync('buzzwords.txt').toString().trim().toLowerCase();
// Delete uploaded resume from our uploads folder once we're done reading it
if (fs.existsSync('uploads/' + file.filename)) {
fs.unlinkSync('uploads/' + file.filename);
}
let globalBuzzwords = buzzwordsData.split('\n');
// Parse the resume and do stuff with the returned Buzzwords object
pokemons.push(parse(pdfData, globalBuzzwords).then(function (buzzwords: any) {
let powerLevel: number = generatePowerLevel(buzzwords);
let moveSet: Set<Move> = generateMoveSet(buzzwords);
let type: string = getType(buzzwords);
let name: string = getPokemonByType(type as string);
let imgUrl: string = getPokemonImageString(name);
let pokemon: Pokemon = new Pokemon(name, powerLevel, type, moveSet, imgUrl);
return pokemon;
//console.log(buzzwords);
//console.log(generatePowerLevel(buzzwords));
//console.log(generateMoveSet(buzzwords));
//console.log(getType());
}));
}
Promise.all(pokemons).then((pokemons) => {
if (pokemons.length > 1) {
// simulate a battle
let simulator: BattleSimulator = new BattleSimulator();
let eventLog: Array<string> = simulator.battle(pokemons[0], pokemons[1]);
res.render('pkmn', {
pokemons: pokemons,
eventLog: eventLog,
})
} else {
res.render('pkmn', {
pokemons: pokemons,
eventLog: [],
});
}
})
});
app.post('/', upload.single('second-file-to-upload'), (req, res) => {
});
app.listen(3000);
export function run() {
}
|
2a4ac2d9a1121e544bcbc50ffa2bbac43954b673
|
TypeScript
|
bloom-housing/bloom
|
/sites/public/cypress/support/helpers.ts
| 2.828125
| 3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Listing } from "@bloom-housing/backend-core/types"
export const listingsUrl = "http://localhost:3100/listings?limit=all"
type GetIncomeReturn = {
monthlyMin: number
monthlyMax: number
annualMin: number
annualMax: number
} | null
type ApplyConfigUpdatesProps = {
config: Record<string, any>
listing: Listing
}
type UpdatePreferredUnitsProps = ApplyConfigUpdatesProps
export const setProperty = (
obj: Record<string, any>,
replacePath: string | string[],
value: any
) => {
if (Object(obj) !== obj) return obj
let path: string[] = []
if (!Array.isArray(replacePath)) path = replacePath.toString().match(/[^.[\]]+/g) || []
path
.slice(0, -1)
.reduce(
(a, c, i) =>
Object(a[c]) === a[c]
? a[c]
: (a[c] = Math.abs(+path[i + 1]) >> 0 === +path[i + 1] ? [] : {}),
obj
)[path[path.length - 1]] = value
return obj
}
export const getListingIncome = (): GetIncomeReturn => {
const listing = sessionStorage.getItem("bloom-app-listing")
if (!listing) return null
const listingObj: Listing = JSON.parse(listing)
const { units } = listingObj
const [annualMin, annualMax, monthlyMin] =
units &&
units.reduce(
([aMin, aMax, mMin], unit) => [
Math.min(aMin, parseFloat(unit.annualIncomeMin || "0.0")),
Math.max(aMax, parseFloat(unit.annualIncomeMax || "0.0")),
Math.min(mMin, parseFloat(unit.monthlyIncomeMin || "0.0")),
],
[Infinity, 0, Infinity]
)
const monthlyMax = annualMax / 12.0
return {
monthlyMin: parseFloat(monthlyMin.toFixed(2)),
monthlyMax: parseFloat(monthlyMax.toFixed(2)),
annualMin: parseFloat(annualMin.toFixed(2)),
annualMax: parseFloat(annualMax.toFixed(2)),
}
}
export const updatePreferredUnits = ({ config, listing }: UpdatePreferredUnitsProps) => {
const firstUnitType = listing.units[0].unitType
config.preferredUnit = [{ id: firstUnitType?.id }]
return config
}
export const applyConfigUpdates = ({ config, listing }: ApplyConfigUpdatesProps) => {
// unit types are related to the listing preferred_unit using Id, to test submission it needs to be updated
updatePreferredUnits({
config,
listing,
})
}
|
57c32ca343f1d5195989f478ea7c262d284a308f
|
TypeScript
|
strass/sigereth
|
/src/types/Generic.ts
| 2.90625
| 3
|
import { firestore } from 'firebase';
export type Action<Type extends string | number | symbol, I extends object = {}> = {
type: Type;
} & I;
export type InterfaceValueAction<T extends object> = {
[K in keyof T]: Action<K, { value: T[K] }>
}[keyof T];
export enum MoteType {
PERSONAL = 'personal',
PERIPHERAL = 'peripheral',
}
export enum DamageType {
BASHING = 'bashing',
LETHAL = 'lethal',
AGGRAVATED = 'aggravated',
}
export const damageLevelKeys: (string | number)[] = [0, 1, 2, 4, 'I'];
export enum Attribute {
STRENGTH = 'strength',
DEXTERITY = 'dexterity',
STAMINA = 'stamina',
PERCEPTION = 'perception',
INTELLIGENCE = 'intelligence',
WITS = 'wits',
CHARISMA = 'charisma',
MANIPULATION = 'manipulation',
APPEARANCE = 'appearance',
}
export enum Ability {
ARCHERY = 'archery',
ATHLETICS = 'athletics',
AWARENESS = 'awareness',
BRAWL = 'brawl',
BUREAUCRACY = 'bureaucracy',
CRAFT = 'craft',
DODGE = 'dodge',
INTEGRITY = 'integrity',
INVESTIGATION = 'investigation',
LARCENY = 'larceny',
LINGUISTICS = 'linguistics',
LORE = 'lore',
MARTIAL_ARTS = 'martialArts',
MEDICINE = 'medicine',
MELEE = 'melee',
OCCULT = 'occult',
PERFORMANCE = 'performance',
PRESENCE = 'presence',
RESISTANCE = 'resistance',
RIDE = 'ride',
SAIL = 'sail',
SOCIALIZE = 'socialize',
STEALTH = 'stealth',
SURVIVAL = 'survival',
THROWN = 'thrown',
WAR = 'war',
}
export interface Merit {
name: string;
description: string;
dots: 1 | 2 | 3 | 4 | 5 | 'N/A';
}
export type WithDates<T> = T & {
createdAt: firestore.Timestamp | firestore.FieldValue;
updatedAt: firestore.Timestamp | firestore.FieldValue;
};
export interface StaticValue {
value: number;
excellency?: {
maxExcellency: number;
unit: 'SUCCESSES';
motesPerUnit: number;
};
}
|
7a2288a96c94d2f70a15a17998204ff8e97a9707
|
TypeScript
|
EYHN/crypto
|
/src/aes/convertToInt32.ts
| 2.8125
| 3
|
export default function convertToInt32(data: ArrayBuffer) {
const bytes = new Uint8Array(data);
var result = [];
for (var i = 0; i < bytes.length; i += 4) {
result.push(
(bytes[i ] << 24) |
(bytes[i + 1] << 16) |
(bytes[i + 2] << 8) |
bytes[i + 3]
);
}
return result;
}
|
c70d1d3ad33d60f9c9568bf5d2c06eaa745b500e
|
TypeScript
|
MukulGupta005/Nosir_website
|
/src/app/services/auth.service.ts
| 2.53125
| 3
|
import { Injectable } from "@angular/core";
import { rejects } from "assert";
import * as firebase from "firebase";
import { Subject } from "rxjs";
@Injectable({
providedIn: "root",
})
export class AuthService {
currentUser;
isLoggedIn = new Subject<boolean>();
constructor() {}
signInwithGoogle() {
var provider = new firebase.default.auth.GoogleAuthProvider();
firebase.default
.auth()
.signInWithPopup(provider)
.then((result) => {
/** @type {firebase.auth.OAuthCredential} */
var credential = result.credential;
// This gives you a Google Access Token. You can use it to access the Google API.
var token = credential["accessToken"];
// The signed-in user info.
var user = result.user;
// ...
this.fetchCurrentSignedInUser();
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
}
fetchCurrentSignedInUser() {
firebase.default.auth().onAuthStateChanged((user) => {
if (user) {
this.setCurrentUser(user);
this.isLoggedIn.next(true);
console.log("Singed In");
} else {
console.log("Not signed In");
}
});
}
setCurrentUser(user) {
this.currentUser = user;
}
getCurrentUser() {
return this.currentUser;
}
}
|
576d789f7417e15ff2c4865b4f2037400372d96f
|
TypeScript
|
penkong/js-plain
|
/100algo/1.absoluteValMinimization.ts
| 3.3125
| 3
|
function absoluteValMinimization(a: number[]): number {
const isEven = a.length % 2 === 0;
return isEven ? a[a.length / 2 - 1] : a[Math.floor(a.length / 2)];
}
absoluteValMinimization([1, 2, 3, 4, 5, 6, 7]);
//
console.log(absoluteValMinimization([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));
|
129e3c756d4e1d3f3e0e2ad935e1a9f1d2dfbc5e
|
TypeScript
|
brunobispo/weather-app
|
/front/src/reducers/cities.ts
| 2.875
| 3
|
import { CitiesAction, CitiesActionTypes, UserAction, UserActionTypes } from '../actions'
import { City } from '../types'
interface CitiesState {
editing: boolean
selected: City
searchTerm: string | null
searchCities: City[] | null
loading: boolean
userCities: City[],
changed: boolean
}
const initialState: CitiesState = {
editing: false,
selected: {
id: 4932,
name: 'São Paulo',
state: 'SP'
},
searchTerm: null,
searchCities: null,
loading: false,
userCities: [],
changed: false,
}
export default function cities(
state: CitiesState = initialState,
action: CitiesAction | UserAction
): CitiesState {
switch (action.type) {
case CitiesActionTypes.REQUEST_SEARCH_CITY:
return { ...state, searchTerm: action.term }
case CitiesActionTypes.RECEIVE_SEARCH_CITY:
if (state.searchTerm === action.term)
return {
...state,
loading: state.searchTerm === action.term,
searchCities: action.cities
}
break
case CitiesActionTypes.START_EDITING_CITY:
return { ...state, loading: true, editing: true }
case CitiesActionTypes.STOP_EDITING_CITY:
return {
...state,
loading: false,
editing: false,
searchTerm: null,
searchCities: null
}
case CitiesActionTypes.SELECT_CITY:
return {
...state,
selected: action.city,
editing: false,
loading: false,
searchTerm: null,
searchCities: null
}
case CitiesActionTypes.REQUEST_ADD_USER_CITY:
return {
...state,
userCities: [action.city, ...state.userCities]
}
case UserActionTypes.RECEIVE_SIGN_IN:
case UserActionTypes.RECEIVE_CHECK_SESSION:
if (action.user)
return {
...state,
userCities: action.user.cities
}
break
case UserActionTypes.RECEIVE_SIGN_OUT:
return { ...state, userCities: [] }
}
return state
}
|
cb7ba75daa1a6287010e4c9a6e10e75f060f6304
|
TypeScript
|
AkshayRana92/ionic_tutorial
|
/src/models/task.ts
| 2.515625
| 3
|
export interface Task {
description: string;
creationDate: Date;
completionDate: Date;
isComplete: boolean
}
|
be4cf055ea4a9006f77683938c42d5beb2e1d8ef
|
TypeScript
|
alanszp/microservices-workshop
|
/calculator/edge-api/src/services/executorService.ts
| 2.796875
| 3
|
import {Operand} from "../models/operand";
import {Executor} from "../models/executor";
import {Expression} from "../models/expression";
import logger from "../logger";
import NoAvailableExecutorError from "../errors/no_available_executor_error";
const executorsMap: Map<Operand, Set<Executor>> = new Map();
export function registerExecutor(executor: Executor): void {
const operand = executor.operand;
const executorList = getExecutors(operand);
executorList.add(executor);
executorsMap.set(operand, executorList);
logger.info('executor_service.register.success', {
operand,
executorLength: executorList.size,
});
}
export function unregisterExecutor(executor: Executor): void {
const operand = executor.operand;
const executorList = getExecutors(operand);
executorList.delete(executor);
logger.info('executor_service.unregister.success', {
operand,
executorLength: executorList.size,
});
}
export function getExecutors(operand: Operand): Set<Executor> {
logger.info('elems', {
values: [...executorsMap.get(operand) || new Set()],
operand
});
return executorsMap.get(operand) || new Set();
}
export function getRandomExecutor(operand: Operand): Executor {
const executors = getExecutors(operand);
const random = Math.floor(Math.random() * executors.size);
return [...executors][random];
}
export function executeExpression(exp: Expression): Promise<number> {
const executor = getRandomExecutor(exp.operand);
if (!executor) {
throw new NoAvailableExecutorError(exp.operand);
}
logger.info('executor_service.execute.starting', {
executor: executor.name,
expression: exp.serialize(),
});
return exp.callExecutor(executor)
.then((res) => {
logger.info('executor_service.execute.done', {
executor: executor.name,
expression: exp.serialize(),
result: res
});
return res;
})
.catch((error) => {
unregisterExecutor(executor);
logger.info('executor_service.execute.error', {
executor: executor.name,
expression: exp.serialize(),
error,
});
throw error;
})
}
|
5ea3f14facb2950e580e66f52ea919c56cf625c0
|
TypeScript
|
abdallanayer/ng-bcomponents
|
/bcomponents/button/button.bcomponent.ts
| 2.546875
| 3
|
import {Component, Directive, Input, Output, EventEmitter, ElementRef} from '@angular/core';
import {BComponent, BComponentInputs, DisplayType} from '../bcomponent';
export class ButtonBase extends BComponent {
@Input() text: string;
@Input() type: DisplayType = "default";
@Input() click: () => void;
@Output() onClick: EventEmitter<this> = new EventEmitter<this>();
constructor(el: ElementRef = void 0) {
super("btn btn-default", el);
}
public Initialize = (text: string = "", type: DisplayType = "default", click: () => void = (() => {})): this => {
this.text = text;
this.type = type;
this.click = click;
if(this.ngOnChildChanges != null) this.ngOnChildChanges();
return this;
}
ngOnChildChanges = () => {
this.baseClass = "btn btn-" + this.type;
}
public clickEvent = () => {
if(this.click != null) {this.click();}
this.onClick.emit(this);
}
}
@Component({
selector: "bc-button",
templateUrl: "button.bcomponent.html",
inputs: BComponentInputs
})
export class ButtonBComponent extends ButtonBase {
constructor() { super(); }
}
@Directive({
selector: "[bc-button]",
inputs: BComponentInputs
})
export class ButtonBDirective extends ButtonBase {
constructor(el: ElementRef) { super(el); }
}
|
754b8de2c659be77e9f940a13e81b194f0e2132c
|
TypeScript
|
DystopianProgrammer/emilena
|
/src/person/common-actions.ts
| 2.734375
| 3
|
import { Person, Staff, Client, Address, Availability } from '../model/model';
export abstract class CommonActions {
_person: Person;
constructor(person: Person) {
this._person = person;
this._person.address = new Address();
}
showAvailabilityForm: boolean = false;
active = true;
// Availability
addAvailability() {
this.showAvailabilityForm = true;
}
availabilityUpdated(availabilities: Availability[]) {
this.showAvailabilityForm = false;
this._person.availabilities = availabilities;
}
removeAvailability(index: number) {
this._person.availabilities.splice(index, 1);
}
setPerson(person: Person) {
this._person = person;
}
person(): Person {
return this._person;
}
// this includes general availability as well as custom availability
cancelAvailability(cancel: boolean) {
this.showAvailabilityForm = false;
}
clear(): void {
if (this._person instanceof Staff) {
this._person = new Staff();
this._person.address = new Address();
} else if (this._person instanceof Client) {
this._person = new Client();
this._person.address = new Address();
} else {
console.error('common-actions: Unknown person type: ' + this._person);
}
}
}
|
c8e534b040dbfa945e4153bac83597a6a067d7b6
|
TypeScript
|
mkinfrared/click-the-fox
|
/src/ui/Heading/Heading.type.ts
| 2.546875
| 3
|
export type HeadingProps = {
className?: string;
children?: React.ReactNode;
/**
* h1 - 36px, h2 - 30px, h3 - 26px, h4 - 20px, h5 - 16px, h6 - 14px
*/
variant?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
};
|
f2f324613f4fae3154c086a90416a15a59d56df2
|
TypeScript
|
mogo062/portfolio
|
/src/app/services/account.service.ts
| 2.8125
| 3
|
import { Injectable } from '@angular/core';
import { Stock } from './stocks.model';
import { LocalStorageService } from './local-storage.service';
import { AlertService } from './alert.service';
import { CurrencyPipe } from '@angular/common';
const defaultBalance: number = 10000;
@Injectable({
providedIn: 'root'
})
export class AccountService {
private _balance: number = defaultBalance;
private _cost: number = 0;
private _value: number = 0;
private _stocks: Stock[]=[];
get balance(): number { return this._balance;}
get cost(): number { return this._cost;}
get value(): number { return this._value;}
get stocks(): Stock[] { return this._stocks; }
constructor(private localStorageService : LocalStorageService, private alertService : AlertService, private currencyPipe :CurrencyPipe) {
// this.init();
}
purchase(stock : Stock): void {
stock = Object.assign({}, stock);
if(stock.price < this._balance){
this._balance=this.debit(stock.price, this.balance);
stock.cost = stock.price;
this._cost = this.credit(stock.price, this.cost);
stock.change = 0;
this.stocks.push(stock);
this.calculateValue();
this.cacheValues(); // add to cach values after purchase and sell
this.alertService.alert(true, 5000, 'S','You bought ${stock.symbol} for '+this.currencyPipe.transform(stock.price, 'USD', true, '.2'));
}else{
this.alertService.alert(true, 5000, 'D','You have insufficient funds to buy ${stock.symbol}');
}
}
sell(index : number):void {
let stock = this._stocks[index];
if(stock){
this._balance = this.credit(stock.price, this.balance);
this._stocks.splice(index, 1);
this._cost = this.debit(stock.cost, this.cost);
this.calculateValue();
this.cacheValues(); // add to cach values after purchase & sell
this.alertService.alert(true, 5000, 'S','You sold ${stock.symbol} for '+this.currencyPipe.transform(stock.price, 'USD', true, '.2'));
}else{
this.alertService.alert(true, 5000, 'D','You do not own the ${stock.symbol} stock.');
}
}
init(){
//this._cost=1500;
//this._value = 3000;
this._stocks = this.localStorageService.get('stocks', []); // add to recovery data from cache
this._balance = this.localStorageService.get('balance', defaultBalance); // add to recovery data from cache
this._cost = this.localStorageService.get('cost', 0); // add to recovery data from cache
}
reset(){
this._stocks = [];
this._balance = defaultBalance;
this._cost = 0;
this._value = 0;
this.cacheValues(); // add to cach values after purchase & sell
}
calculateValue(): void{
/*
map func : create an array by stock.price only (a verctor by stock.price values)
reduce func : sum all array value in this case
*/
this._value = this._stocks.map(stock => stock.price).reduce((a,b) => { return a + b }, 0);
}
private credit(amount: number, balance: number): number{
return (balance*100+amount*100)/100;
}
private debit(amount: number, balance: number): number{
return (balance*100-amount*100)/100;
}
private cacheValues(){
this.localStorageService.set('stocks', this.stocks);
this.localStorageService.set('balance', this.balance);
this.localStorageService.set('cost', this.cost);
}
}
|
65668580c39360668904db63002719b75e44efec
|
TypeScript
|
pixelfactoryio/synthetic-exporter
|
/src/metrics/PerformanceMetric.spec.ts
| 2.546875
| 3
|
import { Registry, Gauge } from 'prom-client';
import { PerformanceMetric } from './PerformanceMetric';
let registry: Registry;
let pm: PerformanceMetric<Gauge<string>>;
beforeAll(() => {
registry = new Registry();
pm = new PerformanceMetric(
new Gauge({
name: 'test_probe_seconds',
help: 'Test probe for testing.',
labelNames: ['target'],
}),
'duration',
);
registry.registerMetric(pm.metric);
pm.set({ target: 'foo' }, 1);
});
afterAll(() => {
registry.clear();
});
describe('PerformanceMetric', () => {
it('Should create a gauge and add value', async () => {
pm.set({ target: 'foo' }, 10);
const metrics = await registry.metrics();
const output =
'# HELP test_probe_seconds Test probe for testing.\n# TYPE test_probe_seconds gauge\ntest_probe_seconds{target="foo"} 0.01\n';
expect(pm).toBeInstanceOf(PerformanceMetric);
expect(pm.metric).toBeInstanceOf(Gauge);
expect(pm.metric).toEqual(registry.getSingleMetric('test_probe_seconds'));
expect(metrics).toEqual(output);
});
it('Should create a gauge and reset its value', async () => {
pm.reset();
const metrics = await registry.metrics();
const output = '# HELP test_probe_seconds Test probe for testing.\n# TYPE test_probe_seconds gauge\n';
expect(pm).toBeInstanceOf(PerformanceMetric);
expect(pm.metric).toBeInstanceOf(Gauge);
expect(pm.metric).toEqual(registry.getSingleMetric('test_probe_seconds'));
expect(metrics).toEqual(output);
});
});
|
b00b3a1203d72ebeae8ffe3f983c60ee143c29bb
|
TypeScript
|
erkiesken/advent-of-code
|
/2019/day-10/solution.ts
| 2.953125
| 3
|
import { readFileStrSync } from 'https://deno.land/std@v0.25.0/fs/read_file_str.ts';
import { vec2 } from 'https://unpkg.com/gl-matrix@3.1.0/esm/index.js';
type vec2 = Float32Array;
function parse(s:string) {
return s.trim().split('\n').map((val) => val.split(''));
}
const input = readFileStrSync('input.txt');
type Sight = { xy: string, len: number };
function getAsteroidViews(data):Map<string, Map<string, Sight[]>> {
const w = data[0].length;
const h = data.length;
const asteroids = new Map<string, Map<string, Sight[]>>();
for (let yo = 0; yo < h; yo += 1) {
for (let xo = 0; xo < w; xo += 1) {
if (data[yo][xo] !== '#') {
continue;
}
const views = new Map<string, Sight[]>();
asteroids.set(`${xo}:${yo}`, views);
for (let yi = 0; yi < h; yi += 1) {
for (let xi = 0; xi < w; xi += 1) {
if (yo === yi && xo === xi) {
// skip self
continue;
}
if (data[yi][xi] === '#') {
const vec: vec2 = vec2.fromValues(xi - xo, yo - yi);
const xy = `${xi}:${yi}`;
let angle: number = vec2.angle(vec, vec2.fromValues(0, 1));
if (vec[0] < 0) {
angle = 2 * Math.PI - angle;
}
const key = `${angle.toFixed(8)}`;
const vals: Sight[] = views.get(key) || [];
views.set(key, [...vals, { xy, len: vec2.length(vec) }]);
}
}
}
}
}
return asteroids;
}
function findBestViews(data): { best: string, max: number, asteroids: Map<string, Map<string, Sight[]>>} {
let max = -Infinity;
let best = '';
const asteroids = getAsteroidViews(data);
for (let [key, value] of asteroids.entries()) {
if (value.size > max) {
max = value.size;
best = key;
}
}
return { best, max, asteroids };
}
function part1(data) {
let { best, max } = findBestViews(data);
console.log(`Best location ${best} max asteroids: ${max}`);
}
function part2(data) {
let { best, max, asteroids } = findBestViews(data);
type Target = [string, Sight[]];
const targets: Target[] = Array.from(asteroids.get(best).entries());
targets.sort((a, b) => {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return 1;
}
return 0;
});
for (let t of targets) {
const s = t[1];
s.sort((a, b) => {
if (a.len < b.len) {
return -1;
} else if (a.len > b.len) {
return 1;
}
return 0;
})
}
let idx = 0;
let i = 0;
let match: Sight;
while (true) {
match = targets[i][1].shift();
if (match) {
idx += 1;
// console.log(`${idx} targetted ${match.xy} toward ${targets[i][0]}`);
}
if (idx === 200) {
break;
}
i = (i + 1) % targets.length;
}
function getValue(s) {
const parts = s.split(':');
return parseInt(parts[0], 10) * 100 + parseInt(parts[1]);
}
console.log(`200th match is at ${match.xy}, result ${getValue(match.xy)}`);
}
part1(parse(`
.#..#
.....
#####
....#
...##
`));
part1(parse(`
......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####
`));
part1(parse(`
#.#...#.#.
.###....#.
.#....#...
##.#.#.#.#
....#.#.#.
.##..###.#
..#...##..
..##....##
......#...
.####.###.
`));
part1(parse(`
.#..#..###
####.###.#
....###.#.
..###.##.#
##.##.#.#.
....###..#
..#.#..#.#
#..#.#.###
.##...##.#
.....#.#..
`));
part1(parse(`
.#..##.###...#######
##.############..##.
.#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.###.###.#.##
....##.##.###..#####
.#.#.###########.###
#.#.#.#####.####.###
###.##.####.##.#..##
`));
part2(parse(`
.#..##.###...#######
##.############..##.
.#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.###.###.#.##
....##.##.###..#####
.#.#.###########.###
#.#.#.#####.####.###
###.##.####.##.#..##
`));
part1(parse(input));
part2(parse(input));
|
a8b94d974f94730913b884786fd61cb916ca5c3a
|
TypeScript
|
AldiPrayogi/frontend-learning-angular
|
/src/app/hero.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { Observable, of } from 'rxjs';
import { MessageService } from './message.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class HeroService {
private HERO_URL = 'http://localhost:3000/api/v1/heroes';
private log(response: any){
this.messageService.add(`HeroService: ${response.message}`);
}
private handleError<T>(operation = 'operation', result?: T){
return (error: any): Observable<T> => {
console.log(error);
this.log(`${operation} failed: ${error.message}`);
return of(result as T);
};
};
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
getHeroes(offset: number): Observable<any> {
return this.http.get<Hero[]>(`${this.HERO_URL}?offset=${offset}`)
.pipe(
tap(() => {
const messageResponse = {
message: 'Fetched Heroes',
};
this.log(messageResponse);
}),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
getHero(id: string): Observable<Hero> {
return this.http.get<Hero>(`${this.HERO_URL}/${id}`)
.pipe(
tap(() => {
const messageResponse = {
message: `fetched hero by ID=${id}`,
};
this.log(messageResponse);
}),
catchError(this.handleError<Hero>('getHero'))
);
}
updateHero(hero: Hero): Observable<any> {
return this.http.put(`${this.HERO_URL}/${hero.id}`, hero, this.httpOptions)
.pipe(
tap((response) => this.log(response)),
catchError(this.handleError<any>('updateHero'))
);
};
addHero(hero: Hero): Observable<Hero> {
return this.http.post(this.HERO_URL, hero, this.httpOptions)
.pipe(
tap((response: any) => {
const messageResponse = {
message: `added hero with hero name=${response.createdHero.name}`,
};
this.log(messageResponse);
}),
catchError(this.handleError<Hero>('addHero'))
);
};
deleteHero(id: string): Observable<any> {
const url = `${this.HERO_URL}/${id}`;
return this.http.delete<any>(url, this.httpOptions)
.pipe(
tap((response) => this.log(response)),
catchError(this.handleError<Hero>('deletedHero'))
);
}
constructor(
private messageService: MessageService,
private http: HttpClient,
) { }
}
|
1f450cbbaeae881204202d1b1af00c9710ade2ef
|
TypeScript
|
carl-eis/dnd-roller
|
/src/core/constants/index.ts
| 2.890625
| 3
|
export interface IDiceRuleset {
name: string;
dice: number;
discardDice: number;
discardSets: number;
sets: number;
}
export interface IRulesets {
[x: string]: IDiceRuleset;
}
export const RULESETS: IRulesets = {
ROLL_3: {
name: 'Roll 6x3',
dice: 3,
sets: 6,
discardDice: 0,
discardSets: 0,
},
ROLL_3_DISCARD_SET: {
name: 'Roll 7x3, discard lowest set',
dice: 3,
sets: 7,
discardDice: 0,
discardSets: 1,
},
ROLL_4_DISCARD_1: {
name: 'Roll 6x4, discard lowest dice',
dice: 4,
sets: 6,
discardDice: 1,
discardSets: 0,
},
};
export const UTILITIES = {
numericSort: (a, b) => (b - a),
addNumbers: (acc: number, item: number) => (acc + item),
};
|
6ddc4c49f4b8e4bd50cc15b4729dbaf4e8ba397b
|
TypeScript
|
mscheetz/CryptoBits
|
/src/app/classes/cryptoBits/transaction.ts
| 2.84375
| 3
|
import { TrxType } from "./trxType";
import { Location } from "./location";
import { Address } from "./address";
/**
* Represents a transaction.
*/
export class Transaction {
private _symbol: string;
private _name: string;
private _pair: string;
private _type: string;
private _date: Date;
private _quantity: number;
private _price: number;
private _fee: number;
private _feeSymbol: string;
private _source: string;
private _destination: string;
private _trxType: TrxType;
private _sourceLocation: Location;
private _sourceAddress: Address;
private _destinationLocation: Location;
private _destinationAddress: Address;
private _trxId: string;
private _trxSource: string;
get symbol(): string {
return this._symbol;
}
set symbol(value: string) {
this._symbol = value;
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
get pair(): string {
return this._pair;
}
set pair(value: string) {
this._pair = value;
}
get type(): string {
return this._type;
}
set type(value: string) {
this._type = value;
}
get date(): Date {
return this._date;
}
set date(value: Date) {
this._date = value;
}
get quantity(): number {
return this._quantity;
}
set quantity(value: number) {
this._quantity = value;
}
get price(): number {
return this._price;
}
set price(value: number) {
this._price = value;
}
get fee(): number {
return this._fee;
}
set fee(value: number) {
this._fee = value;
}
get feeSymbol(): string {
return this._feeSymbol;
}
set feeSymbol(value: string) {
this._feeSymbol = value;
}
get source(): string {
return this._source;
}
set source(value: string) {
this._source = value;
}
get destination(): string {
return this._destination;
}
set destination(value: string) {
this._destination = value;
}
get trxId(): string {
return this._trxId;
}
set trxId(value: string) {
this._trxId = value;
}
get trxSource(): string {
return this._trxSource;
}
set trxSource(value: string) {
this._trxSource = value;
}
get trxType(): TrxType {
return this._trxType;
}
set trxType(value: TrxType) {
this._trxType = value;
}
get sourceLocation(): Location {
return this._sourceLocation;
}
set sourceLocation(value: Location) {
this._sourceLocation = value;
}
get sourceAddress(): Address {
return this._sourceAddress;
}
set sourceAddress(value: Address) {
this._sourceAddress = value;
}
get destinationAddress(): Address {
return this._destinationAddress;
}
set destinationAddress(value: Address) {
this._destinationAddress = value;
}
get destinationLocation(): Location {
return this._destinationLocation;
}
set destinationLocation(value: Location) {
this._destinationLocation = value;
}
}
|
1ddcfc3eebf150d7d1eb19c8569c9a6da0b81090
|
TypeScript
|
Blackdread/lens
|
/packages/core/src/common/__tests__/catalog-category-registry.test.ts
| 2.765625
| 3
|
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { CatalogCategorySpec } from "../catalog";
import { CatalogCategory, CatalogCategoryRegistry } from "../catalog";
class TestCatalogCategoryRegistry extends CatalogCategoryRegistry { }
class TestCatalogCategory extends CatalogCategory {
public readonly apiVersion = "catalog.k8slens.dev/v1alpha1";
public readonly kind = "CatalogCategory";
public metadata = {
name: "Test Category",
icon: "",
};
public spec: CatalogCategorySpec = {
group: "entity.k8slens.dev",
versions: [],
names: {
kind: "Test",
},
};
}
class TestCatalogCategory2 extends CatalogCategory {
public readonly apiVersion = "catalog.k8slens.dev/v1alpha1";
public readonly kind = "CatalogCategory";
public metadata = {
name: "Test Category 2",
icon: "",
};
public spec: CatalogCategorySpec = {
group: "entity.k8slens.dev",
versions: [],
names: {
kind: "Test2",
},
};
}
describe("CatalogCategoryRegistry", () => {
it("should remove only the category registered when running the disposer", () => {
const registry = new TestCatalogCategoryRegistry();
expect(registry.items.length).toBe(0);
const d1 = registry.add(new TestCatalogCategory());
const d2 = registry.add(new TestCatalogCategory2());
expect(registry.items.length).toBe(2);
d1();
expect(registry.items.length).toBe(1);
d2();
expect(registry.items.length).toBe(0);
});
it("doesn't return items that are filtered out", () => {
const registry = new TestCatalogCategoryRegistry();
registry.add(new TestCatalogCategory());
registry.add(new TestCatalogCategory2());
expect(registry.items.length).toBe(2);
expect(registry.filteredItems.length).toBe(2);
const disposer = registry.addCatalogCategoryFilter(category => category.metadata.name === "Test Category");
expect(registry.items.length).toBe(2);
expect(registry.filteredItems.length).toBe(1);
const disposer2 = registry.addCatalogCategoryFilter(category => category.metadata.name === "foo");
expect(registry.items.length).toBe(2);
expect(registry.filteredItems.length).toBe(0);
disposer();
expect(registry.items.length).toBe(2);
expect(registry.filteredItems.length).toBe(0);
disposer2();
expect(registry.items.length).toBe(2);
expect(registry.filteredItems.length).toBe(2);
});
});
|
4020008e2d6cbbc8e17264ce99ad8eea37d82339
|
TypeScript
|
Loeka1234/express-res-errors
|
/lib/errorHandlerMiddleware.ts
| 3.265625
| 3
|
import { NextFunction, Request, Response } from "express";
import { CustomError } from "./CustomError";
import { DefaultError } from "./errors/DefaultError";
const defaultConfig: ErrorHandlerMiddlewareConfig = {
defaultResponse: {
errors: [{ message: "Something went wrong" }],
},
logCustomErrors: false,
logUnknownErrors: true,
};
export interface ErrorHandlerMiddlewareConfig {
/** The default response that the middleware should send if the error was not a custom error. */
defaultResponse?: object;
/** If true, the middleware will log custom errors and default errors. Default: **false** */
logCustomErrors?: boolean;
/** If true, the middleware will log uknown errors. Default: **true** */
logUnknownErrors?: boolean;
}
/**
* Error handler for handling custom errors.
* @param config config for the error handler middleware.
*/
export const errorHandlerMiddleware = (
config?: ErrorHandlerMiddlewareConfig
) => {
config = { ...defaultConfig, ...config };
const { defaultResponse, logCustomErrors, logUnknownErrors } = config;
return (err: Error, _req: Request, res: Response, _next: NextFunction) => {
if (err instanceof CustomError || err instanceof DefaultError) {
if (logCustomErrors) console.error(err);
return res.status(err.statusCode).json({ errors: err.serializeErrors() });
}
if (logUnknownErrors) console.error(err);
return res.status(500).json(defaultResponse);
};
};
|
42a9b059cb9acdf616aac1c656650dceca0db8b9
|
TypeScript
|
RosenborgSupporterSoftware/RUSK
|
/src/Utility/ChunkHandler.ts
| 3.03125
| 3
|
/**
* ChunkHandler.ts
* Experimental class that provides chunking functionality.
* This will hopefully result in stable code that can help RUSK store larger amounts of configuration data.
*
*/
/** A simple class that represents a single chunk of data */
export class Chunk {
private _name: string;
/**
* Gets the name given to this chunk
*/
public get Name(): string {
return this._name;
}
private _seq: number;
/**
* Gets the sequence number of this chunk
*/
public get Sequence(): number {
return this._seq;
}
private _csum: number;
/**
* Gets the checksum for the data
*/
public get Checksum(): number {
return this._csum;
}
private _data: string;
/**
* Gets the actual data represented by this Chunk object
*/
public get Data(): string {
return this._data;
}
constructor(name: string, sequence: number, checksum: number, data: string) {
this._name = name;
this._seq = sequence;
this._csum = checksum;
this._data = data;
}
/** Gets a pure JSON string representation of this chunk */
public ToJSON(): string {
return JSON.stringify({
name: this.Name,
seq: this.Sequence,
checksum: this.Checksum,
data: this.Data
});
}
/** Gets a Chunk object from a JSON string */
public static FromJSON(json: string): Chunk {
let obj = JSON.parse(json);
return new Chunk(obj.name, obj.seq, obj.checksum, obj.data);
}
}
/** A class for splitting data into chunks and reassembling it again */
export class ChunkHandler {
public Chunkify(input: any, chunkName: string, chunkSize: number = 8000): Array<Chunk> {
if (typeof input != "string") {
input = JSON.stringify(input);
}
let encoded = this.EncodeString(input);
let chunks = new Array<Chunk>();
let seq = 0;
for (let idx = 0; idx < encoded.length; idx += chunkSize) {
let data = encoded.substr(idx, chunkSize);
let csum = this.Checksum(data);
chunks.push(new Chunk(chunkName, seq, csum, data));
}
return chunks;
}
public Dechunkify(chunks: Array<Chunk>): string {
if (chunks == null || chunks.length == 0) return '';
let ordered = chunks.sort((a, b) => { return b.Sequence - a.Sequence });
let encoded = "";
ordered.forEach(ch => {
if (this.Checksum(ch.Data) != ch.Checksum) {
throw new Error('Corrupt input data in chunk ' + ch.Name + ' sequence #' + ch.Sequence + '!');
}
encoded += ch.Data;
});
return this.DecodeString(encoded);
}
/**
* Encode a string as base 64, handling UTF-8 and other stuff that atob() bombs on.
* @param inputString - The string to encode
*/
public EncodeString(inputString: string): string {
return this.Base64.encode(inputString);
}
/**
* Decode a string that has been encoded using EncodeString
* @param inputString - The string to decode
*/
public DecodeString(inputString: string): string {
return this.Base64.decode(inputString);
}
/**
* Create a simple checksum value from an input string to verify uncorrupt data
* @param inputString - The input string to create a checksum for
*/
public Checksum(inputString: string): number {
return this.checksum(inputString);
}
// Borrowed from www.webtoolkit.info
// Ref: https://stackoverflow.com/questions/23223718/failed-to-execute-btoa-on-window-the-string-to-be-encoded-contains-characte
private Base64 = {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
// public method for encoding
, encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = this._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
} // Whend
return output;
} // End Function encode
// public method for decoding
, decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
} // Whend
output = this._utf8_decode(output);
return output;
} // End Function decode
// private method for UTF-8 encoding
, _utf8_encode: function (string) {
var utftext = "";
string = string.replace(/\r\n/g, "\n");
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
} // Next n
return utftext;
} // End Function _utf8_encode
// private method for UTF-8 decoding
, _utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c, c1, c2, c3;
c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
} // Whend
return string;
} // End Function _utf8_decode
}
// Stolen from https://gist.github.com/Facel3ss1/6e36392ff5b2603ee3f514ae6744cd1a
checksum(s: string): number {
var hash = 0, strlen = s.length, i, c;
if (strlen === 0) {
return hash;
}
for (i = 0; i < strlen; i++) {
c = s.charCodeAt(i);
hash = ((hash << 5) - hash) + c;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
}
|
0fcd591295008023a4233384b2e226a8368688ed
|
TypeScript
|
kunalashar25/learn-typescript
|
/language_fundamentals/generics/utility_types/partial_types/app.ts
| 3.953125
| 4
|
interface CourseGoal {
title: string;
description: string;
completeUntil: Date;
}
function createCourseGoal(
title: string,
description: string,
completeUntil: Date
): CourseGoal {
// let courseGoal:CourseGoal = {}; Type '{}' is missing the following properties from type 'CourseGoal': title, description, completeUntil
// we cannot assign empty object as it'll directly throw error
// if our requirement is to validate all input data and then set it to interface then we need to use Partial Types
// Partial Type will mark all interface proeprties as optional and while returning the object, we can return all the keys
let courseGoal: Partial<CourseGoal> = {};
courseGoal.title = title;
courseGoal.description = description;
courseGoal.completeUntil = completeUntil;
// cannot return is directly as it is still type of partial courseGoal
// return courseGoal; Type 'Partial<CourseGoal>' is not assignable to type 'CourseGoal'
// so we need to convert it to CourseGoal type using type casting
return courseGoal as CourseGoal;
}
|
80af0abdac0ec2e083d6e2cc9c928c3eda413e96
|
TypeScript
|
johnnywale/labs
|
/src/problem4/retrieve-service.ts
| 2.765625
| 3
|
import {ethers} from "ethers";
import {Event} from "@ethersproject/contracts/src.ts/index";
export class ContractInfo {
public static readonly BSS_PROVIDER_URL: string = "https://bsc-dataseed.binance.org/"
constructor(
public readonly contactAddress: string,
public readonly abi: string,
) {
}
}
export class RetrieveAllHoldersClient {
private readonly provider: ethers.providers.JsonRpcProvider
private readonly contract: ethers.Contract
private readonly processedAddress: Set<string>
constructor(
public readonly contractInfo: ContractInfo
) {
this.provider = new ethers.providers.JsonRpcProvider(ContractInfo.BSS_PROVIDER_URL);
this.contract = new ethers.Contract(contractInfo.contactAddress, contractInfo.abi, this.provider)
this.processedAddress = new Set<string>();
}
/**
* get max block number , then iterate all block to get all transfer event , to get holders address and then call balanceOf method from contract to get balance.
*/
async retrieve(): Promise<void> {
const max = await this.provider.getBlockNumber();
const batchSize = 1000;
console.log(`current block ${max} , max block size ${batchSize} `)
/**
* retrieve start from current block , make it faster to see the result
*/
for (let value = max; value > 0; value -= batchSize) {
try {
await this.retrieveBlock(value - batchSize, value)
} catch (e) {
/**
* skip for now , I added some retry logic issue not pass
*/
console.error(e);
}
}
}
async getFromLatestBlocks() {
const max = await this.provider.getBlockNumber();
await this.retrieveBlock(max - 2000, max);
}
async retrieveByEvent(event: Event) {
if (event.args) {
const addressFrm = event.args[0]
/**
* only print once
*/
if (!this.processedAddress.has(addressFrm)) {
const balanceFrom = await this.contract.balanceOf(addressFrm);
console.log(`${addressFrm} ${balanceFrom}`)
this.processedAddress.add(addressFrm)
}
const addressTo = event.args[1]
if (!this.processedAddress.has(addressTo)) {
const balanceTo = await this.contract.balanceOf(addressTo);
console.log(`${addressTo} ${balanceTo}`)
this.processedAddress.add(addressTo)
}
}
}
async retrieveBlock(from: number, to: number) {
console.log(`from ${from} to ${to} `);
if (from < 0) {
from = 0;
}
let eventFilter = this.contract.filters.Transfer()
return this.contract.queryFilter(eventFilter, from, to).then(async value => {
if (value.length > 0) {
for (const event of value) {
await this.retrieveByEvent(event);
}
} else {
// console.log("not result");
}
})
}
}
|
eb10d5e1e43e2df46d4de29cc85f3d3f3a0c9e19
|
TypeScript
|
everdimension/draggable-list
|
/src/dataSources/statements/Source.ts
| 3.046875
| 3
|
import NanoEvents from 'nanoevents';
import nanoid from 'nanoid';
import { createReorderedArray } from './createReorderedArray';
interface ItemBase {
name: string;
description: string;
}
interface Item extends ItemBase {
id: string;
}
interface State {
items: {
[id: string]: Item;
};
order: string[];
}
export class Source {
state: State;
emitter: NanoEvents<any>;
constructor() {
this.emitter = new NanoEvents();
this.state = {
items: {},
order: [],
};
this.setItems = this.setItems.bind(this);
this.createNewItem = this.createNewItem.bind(this);
this.reorder = this.reorder.bind(this);
}
subscribe(listener: (state: any) => any) {
return this.emitter.on('update', listener);
}
emit() {
this.emitter.emit('update', this.state);
}
getState() {
return this.state;
}
setItems(items: State['items']) {
this.state.items = items;
this.state.order = Object.keys(items);
this.emit();
}
createNewItem(item: ItemBase) {
const id = nanoid();
const { items, order } = this.state;
this.state.items = {
...items,
[id]: {
...item,
id,
},
};
this.state.order = [...order, id];
this.emit();
}
reorder(sourceIndex: number, destinationIndex: number) {
const { order } = this.state;
this.state.order = createReorderedArray(
order,
sourceIndex,
destinationIndex,
);
this.emit();
}
}
|
1c089e09516c93ae96a05b3a91fb19616c962aa9
|
TypeScript
|
vaibhsir1991/WeatherApp
|
/src/redux/reducers/reducer-location.ts
| 3.4375
| 3
|
interface State {
latitude: number;
longitude: number;
city: string;
}
const initialState: State = {
latitude: 0,
longitude: 0,
city: ''
};
const locationReducer = (
state: State = initialState,
action: { type: any; payload: any }
) => {
switch (action.type) {
case 'SET_LOCATION':
return {
...state,
latitude: action.payload.location.lat,
longitude: action.payload.location.long
};
case 'SET_CITY':
return { ...state, city: action.payload.city };
case 'RESET':
return { ...initialState };
default:
return state;
}
};
export default locationReducer;
|
ff062f164656ad21f86f7724c5b937ad2cebfe5a
|
TypeScript
|
Polycapa/angular-migration-tool
|
/src/utils/lint/rules/TripleEqualsRule.ts
| 2.578125
| 3
|
import { Fix } from '../models/fix';
import { LintRule } from './../models/lint-rule';
import { SimplifiedRuleFailure } from './../models/simplified-rule-failure';
export class TripleEqualsRule implements LintRule {
fix(failure: SimplifiedRuleFailure): Fix {
const text = failure.failure.indexOf('!=') !== -1 ? '!==' : '===';
return {
fileName: failure.fileName,
start: failure.startPosition.position,
length: failure.endPosition.position - failure.startPosition.position,
text: text
}
}
}
|
fc0dbb783ac3b50cc59e465b464d49ee9d9c7865
|
TypeScript
|
tonyonodi/Observatory
|
/src/index.test.ts
| 3.203125
| 3
|
import { Access } from "./index";
// Messing about
import { Lens, fromTraversable } from "monocle-ts";
import { array } from "fp-ts/lib/Array";
import * as L from "monocle-ts/lib/Lens";
import * as T from "monocle-ts/lib/Traversal";
import { pipe } from "fp-ts/lib/function";
// Not messing about
type Address = {
number: number;
street: string;
city: string;
};
type Person = {
first_name: string;
surname: string;
address: Address;
tweets: Tweet[];
};
const person: Person = {
first_name: "Tony",
surname: "Onodi",
address: {
number: 1,
street: "Glentrammon Road",
city: "London",
},
tweets: [
{ text: "blah", id: 1 },
{ text: "blah 2", id: 2 },
],
};
type Tweet = {
text: string;
id: number;
};
const _Person = Access<Person>();
const _Tweet = Access<Tweet>();
// More messsing about
// const p = L.id<Person>();
// const ad = L.prop<Person, "address">("address");
// const pt = L.prop<Person, "tweets">("tweets");
// const st = L.prop<Address, "street">("street");
// const _fn: L.Lens<Person, string> = Lens.fromProp<Person>()("first_name");
// // var fromLens = function (lens) { return new Lens(lens.get, lens.set); };
// const l = new Lens(p.get, p.set);
// st(ad(p)).get(person);
// const arrayTraversal = fromTraversable(array)<string>();
// Optic<Person>().tweets.__each;
// const capitalise = (s: string) => s.toUpperCase();
// const pets = Lens.fromProp<Person>()("tweets");
// it("quick test", () => {
// const optic = l
// .composeLens(Lens.fromProp<Person>()("tweets"))
// .composeTraversal(fromTraversable(array)<Tweet>())
// .composeLens(Lens.fromProp<Tweet>()("text"));
// expect(optic.asFold().getAll(person)).toEqual(["blah", "blah 2"]);
// });
// const trav = fromTraversable(array)<Person>();
// const mytrav = T.id<string>();
// const blah = trav
// .composeLens(Lens.fromProp<Person>()("first_name"))
// .set("blah")([person]);
it("should be able to get a prop value", () => {
expect(Access<Person>().first_name.__getFrom(person)).toEqual("Tony");
});
it("should be able to get an array from a value", () => {
expect(Access<Person>().tweets.__getFrom(person)).toEqual(person.tweets);
});
it("should be able to get a nested value", () => {
expect(Access<Person>().address.number.__getFrom(person)).toEqual(1);
});
it("should be able to get props from an array", () => {
expect(Access<Person>().tweets.__each.text.__getFrom(person)).toEqual([
"blah",
"blah 2",
]);
});
const capitalise = (s: string) => s.toUpperCase();
const updateFirstTweet = (t: Tweet) =>
t.id === 1 ? { ...t, text: "updated" } : t;
const _l = L.id<Person>();
const l = new Lens(_l.get, _l.set);
const updatedPerson = l
.composeLens(Lens.fromProp<Person>()("tweets"))
.composeTraversal(fromTraversable(array)<Tweet>())
.filter((t) => t.id === 1);
// _Person.tweets.__filter((t) => t.id === 1).text.__getFrom(person);
// it("quick", () => {
// expect(updatedPerson).toEqual({
// ...person,
// tweets: [
// { text: "updated", id: 1 },
// { text: "blah 2", id: 2 },
// ],
// });
// });
it("should be able to modify values in an array", () => {
expect(
Access<Person>().tweets.__each.__setWith(updateFirstTweet)(person)
).toEqual({
...person,
tweets: [
{ text: "updated", id: 1 },
{ text: "blah 2", id: 2 },
],
});
});
it("should be able to filter an array and get a value from it", () => {
expect(
_Person.tweets.__filter((t) => t.id === 1).text.__getFrom(person)
).toEqual(["blah"]);
});
it("should be able to filter an array and modify a value", () => {
expect(
_Person.tweets.__filter((t) => t.id === 1).text.__setTo("updated")(person)
).toEqual({
...person,
tweets: [
{ text: "updated", id: 1 },
{ text: "blah 2", id: 2 },
],
});
});
it("should be able to set a nested value", () => {
expect(Access<Person>().address.number.__setTo(11)(person)).toEqual({
first_name: "Tony",
surname: "Onodi",
address: {
number: 11,
street: "Glentrammon Road",
city: "London",
},
tweets: person.tweets,
});
});
|
b795e66dae77a1a23e726225a17af9797e17f3fa
|
TypeScript
|
phenomLi/Matrix4
|
/src/matrix4.ts
| 3.15625
| 3
|
import { Mat4, Vec3, Quat, _tempMatrix4, _tempMatrix3 } from "./matrix";
import { Vector3 } from "./vector3";
/**
* 4 * 4 矩阵
*/
export const Matrix4 = {
/**
* 创建 4 * 4 矩阵
* @param value
*/
create(value?: Mat4): Mat4 {
let mat4: Mat4 = new Float32Array(16);
mat4[0] = 1;
mat4[5] = 1;
mat4[10] = 1;
mat4[15] = 1;
if(value !== undefined && Array.isArray(value)) {
this.set(mat4, value);
}
return mat4;
},
/**
* 设置矩阵值
* @param m
* @param value
*/
set(m: Mat4, value: Mat4): Mat4 {
m[0] = value[0];
m[1] = value[1];
m[2] = value[2];
m[3] = value[3];
m[4] = value[4];
m[5] = value[5];
m[6] = value[6];
m[7] = value[7];
m[8] = value[8];
m[9] = value[9];
m[10] = value[10];
m[11] = value[11];
m[12] = value[12];
m[13] = value[13];
m[14] = value[14];
m[15] = value[15];
return m;
},
/**
* 矩阵相加
* @param m1
* @param m2
* @param mOut
*/
add(m1: Mat4, m2: Mat4, mOut?: Mat4): Mat4 {
let dest: Mat4;
if(mOut !== undefined) {
dest = mOut;
}
else {
dest = this.create();
}
dest[0] = m1[0] + m2[0];
dest[1] = m1[1] + m2[1];
dest[2] = m1[2] + m2[2];
dest[3] = m1[3] + m2[3];
dest[4] = m1[4] + m2[4];
dest[5] = m1[5] + m2[5];
dest[6] = m1[6] + m2[6];
dest[7] = m1[7] + m2[7];
dest[8] = m1[8] + m2[8];
dest[9] = m1[9] + m2[9];
dest[10] = m1[10] + m2[10];
dest[11] = m1[11] + m2[11];
dest[12] = m1[12] + m2[12];
dest[13] = m1[13] + m2[13];
dest[14] = m1[14] + m2[14];
dest[15] = m1[15] + m2[15];
return dest;
},
/**
* 矩阵相减
* @param m1
* @param m2
* @param mOut
*/
subtract(m1: Mat4, m2: Mat4, mOut?: Mat4): Mat4 {
let dest: Mat4;
if(mOut !== undefined) {
dest = mOut;
}
else {
dest = this.create();
}
dest[0] = m1[0] - m2[0];
dest[1] = m1[1] - m2[1];
dest[2] = m1[2] - m2[2];
dest[3] = m1[3] - m2[3];
dest[4] = m1[4] - m2[4];
dest[5] = m1[5] - m2[5];
dest[6] = m1[6] - m2[6];
dest[7] = m1[7] - m2[7];
dest[8] = m1[8] - m2[8];
dest[9] = m1[9] - m2[9];
dest[10] = m1[10] - m2[10];
dest[11] = m1[11] - m2[11];
dest[12] = m1[12] - m2[12];
dest[13] = m1[13] - m2[13];
dest[14] = m1[14] - m2[14];
dest[15] = m1[15] - m2[15];
return dest;
},
/**
* 矩阵相乘
* @param mOut
*/
multiply(m1: Mat4, m2: Mat4, mOut?: Mat4): Mat4 {
let dest: Mat4;
if(mOut !== undefined) {
dest = mOut;
}
else {
dest = this.create();
}
let d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33;
d00 = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12];
d01 = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13];
d02 = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14];
d03 = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15];
d10 = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12];
d11 = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13];
d12 = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14];
d13 = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15];
d20 = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12];
d21 = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13];
d22 = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14];
d23 = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15];
d30 = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12];
d31 = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13];
d32 = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14];
d33 = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15];
dest[0] = d00; dest[1] = d01; dest[2] = d02; dest[3] = d03;
dest[4] = d10; dest[5] = d11; dest[6] = d12; dest[7] = d13;
dest[8] = d20; dest[9] = d21; dest[10] = d22; dest[11] = d23;
dest[12] = d30; dest[13] = d31; dest[14] = d32; dest[15] = d33;
return dest;
},
/**
* 矩阵与 3 维向量相乘
* @param m
* @param v
* @param vOut
*/
multiplyVec3(m: Mat4, v: Vec3, vOut?: Vec3): Vec3 {
let dest: Vec3;
if(vOut !== undefined) {
dest = vOut;
}
else {
dest = Vector3.create();
}
let v0, v1, v2;
v0 = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];
v1 = m[4] * v[0] + m[5] * v[1] + m[6] * v[2] + m[7];
v2 = m[8] * v[0] + m[9] * v[1] + m[10] * v[2] + m[11];
dest[0] = v0;
dest[1] = v1;
dest[2] = v2;
return dest;
},
/**
* 矩阵乘上一个数
* @param m
* @param n
*/
multiplyNum(m: Mat4, n: number): Mat4 {
m[0] = m[0] * n;
m[1] = m[1] * n;
m[2] = m[2] * n;
m[3] = m[3] * n;
m[4] = m[4] * n;
m[5] = m[5] * n;
m[6] = m[6] * n;
m[7] = m[7] * n;
m[8] = m[8] * n;
m[9] = m[9] * n;
m[10] = m[10] * n;
m[11] = m[11] * n;
m[12] = m[12] * n;
m[13] = m[13] * n;
m[14] = m[14] * n;
m[15] = m[15] * n;
return m;
},
/**
* 矩阵转置
* @param m
*/
transpose(m: Mat4): Mat4 {
let m00 = m[0],
m01 = m[1],
m02 = m[2],
m03 = m[3],
m10 = m[4],
m11 = m[5],
m12 = m[6],
m13 = m[7],
m20 = m[8],
m21 = m[9],
m22 = m[10],
m23 = m[11],
m30 = m[12],
m31 = m[13],
m32 = m[14],
m33 = m[15];
m[0] = m00;
m[1] = m10;
m[2] = m20;
m[3] = m30;
m[4] = m01;
m[5] = m11;
m[6] = m21;
m[7] = m31;
m[8] = m02;
m[9] = m12;
m[10] = m22;
m[11] = m32;
m[12] = m03;
m[13] = m13;
m[14] = m23;
m[15] = m33;
return m;
},
/**
* 转换为单位矩阵
* @param m
*/
identity(m: Mat4): Mat4 {
m[0] = m[5] = m[10] = m[15] = 1;
m[1] = m[2] = m[3] = 0;
m[4] = m[6] = m[7] = 0;
m[8] = m[9] = m[11] = 0;
m[12] = m[13] = m[14] = 0;
return m;
},
/**
* 求矩阵的某个元素的代数余子式
* @param m
* @param i
*/
factor(m: Mat4, i: number): number {
let d = new Float32Array(9),
k , n = 0;
for(k = 0; k < m.length; k++) {
if(Math.abs(k - i) >= 4 && i % 4 !== k % 4) {
d[n] = m[k];
n++;
}
}
let a11 = d[0], a12 = d[1], a13 = d[2],
a21 = d[3], a22 = d[4], a23 = d[5],
a31 = d[6], a32 = d[7], a33 = d[8],
det = a11 * a22 * a33 + a12 * a23 * a31 + a13 * a21 * a32 - a13 * a22 * a31 - a12 * a21 * a33 - a11 * a23 * a32;
return (-1)**(Math.floor(i / 4) + 1 + i % 4 + 1) * det;
},
/**
* 求矩阵行列式
* @param m
*/
determinant(m: Mat4): number {
let det = 0;
for(let i = 0; i < m.length; i++) {
det += m[i] * Matrix4.factor(m, i);
}
return det;
},
/**
* 矩阵求逆
* @param m
* @param mOut
*/
invert(m: Mat4, mOut?: Mat4): Mat4 {
let dest: Mat4;
if(mOut !== undefined) {
dest = mOut;
}
else {
dest = this.create();
}
const det = Matrix4.determinant(m);
dest[0] = Matrix4.factor(m, 0);
dest[4] = Matrix4.factor(m, 1);
dest[8] = Matrix4.factor(m, 2);
dest[12] = Matrix4.factor(m, 3);
dest[1] = Matrix4.factor(m, 4);
dest[5] = Matrix4.factor(m, 5);
dest[9] = Matrix4.factor(m, 6);
dest[13] = Matrix4.factor(m, 7);
dest[2] = Matrix4.factor(m, 8);
dest[6] = Matrix4.factor(m, 9);
dest[10] = Matrix4.factor(m, 10);
dest[14] = Matrix4.factor(m, 11);
dest[3] = Matrix4.factor(m, 12);
dest[7] = Matrix4.factor(m, 13);
dest[11] = Matrix4.factor(m, 14);
dest[15] = Matrix4.factor(m, 15);
return Matrix4.multiplyNum(dest, 1 / det);
},
/**
* (TODO)
* 从四元数构建矩阵
* @param m
* @param quat
*/
fromQuaternion(m: Mat4, quat: Quat): Mat4 {
return m;
},
/**
* 设置位移矩阵
* @param m
* @param v
*/
translate(m: Mat4, v: Vec3): Mat4 {
_tempMatrix4[0] = 1;
_tempMatrix4[1] = 0;
_tempMatrix4[2] = 0;
_tempMatrix4[3] = v[0];
_tempMatrix4[4] = 0;
_tempMatrix4[5] = 1;
_tempMatrix4[6] = 0;
_tempMatrix4[7] = v[1];
_tempMatrix4[8] = 0;
_tempMatrix4[9] = 0;
_tempMatrix4[10] = 1;
_tempMatrix4[11] = v[2];
_tempMatrix4[12] = 0;
_tempMatrix4[13] = 0;
_tempMatrix4[14] = 0;
_tempMatrix4[15] = 1;
return Matrix4.multiply(_tempMatrix4, m, m);
},
/**
* 设置缩放矩阵
* @param m
* @param v
*/
scale(m: Mat4, v: Vec3): Mat4 {
_tempMatrix4[0] = v[0];
_tempMatrix4[1] = 0;
_tempMatrix4[2] = 0;
_tempMatrix4[3] = 0;
_tempMatrix4[4] = 0;
_tempMatrix4[5] = v[1];
_tempMatrix4[6] = 0;
_tempMatrix4[7] = 0;
_tempMatrix4[8] = 0;
_tempMatrix4[9] = 0;
_tempMatrix4[10] = v[2];
_tempMatrix4[11] = 0;
_tempMatrix4[12] = 0;
_tempMatrix4[13] = 0;
_tempMatrix4[14] = 0;
_tempMatrix4[15] = 1;
return Matrix4.multiply(_tempMatrix4, m, m);
},
/**
* 设置旋转矩阵
* @param m
* @param rad
* @param axis
*/
rotate(m: Mat4, rad: number, axis: Vec3): Mat4 {
let sin = Math.sin(rad),
cos = Math.cos(rad),
ncos = 1 - cos,
[x, y, z] = axis;
_tempMatrix4[0] = cos * (1 - cos) * x**2;
_tempMatrix4[1] = ncos * x * y - sin * z;
_tempMatrix4[2] = ncos * x * z - sin * y;
_tempMatrix4[3] = 0;
_tempMatrix4[4] = ncos * x * y + sin * z;
_tempMatrix4[5] = cos + ncos * y**2;
_tempMatrix4[6] = ncos * y * z - sin * x;
_tempMatrix4[7] = 0;
_tempMatrix4[8] = ncos * x * z - sin * y;
_tempMatrix4[9] = ncos * y * z + sin * x;
_tempMatrix4[10] = cos + ncos * z**2;
_tempMatrix4[11] = 0;
_tempMatrix4[12] = 0;
_tempMatrix4[13] = 0;
_tempMatrix4[14] = 0;
_tempMatrix4[15] = 1;
return Matrix4.multiply(_tempMatrix4, m, m);
},
/**
* 设置视图矩阵
* @param m
* @param ex
* @param ey
* @param ez
* @param dx
* @param dy
* @param dz
* @param ux
* @param uy
* @param uz
*/
setViewer(m: Mat4, ex: number, ey: number, ez: number, dx: number, dy: number, dz: number, ux: number, uy: number, uz: number): Mat4 {
let Nx, Ny, Nz, Ux, Uy, Uz, Vx, Vy, Vz, Nlen, Ulen;
Matrix4.translate(m, new Float32Array([-ex, -ey, -ez]));
Nlen = 1 / Math.hypot(dx, dy, dz);
Nx = dx * Nlen;
Ny = dy * Nlen;
Nz = dz * Nlen;
Ux = Ny * uz - Nz * uy;
Uy = Nz * ux - Nx * uz;
Uz = Nx * uy - Ny * ux;
Ulen = 1 / Math.hypot(Ux, Uy, Uz);
Ux *= Ulen;
Uy *= Ulen;
Uz *= Ulen;
Vx = Uy * Nz - Uz * Ny;
Vy = Uz * Nx - Ux * Nz;
Vz = Ux * Ny - Uy * Nx;
_tempMatrix4[0] = Ux;
_tempMatrix4[1] = Uy;
_tempMatrix4[2] = Uz;
_tempMatrix4[3] = 0;
_tempMatrix4[4] = Vx;
_tempMatrix4[5] = Vy;
_tempMatrix4[6] = Vz;
_tempMatrix4[7] = 0;
_tempMatrix4[8] = -Nx;
_tempMatrix4[9] = -Ny;
_tempMatrix4[10] = -Nz;
_tempMatrix4[11] = 0;
_tempMatrix4[12] = 0;
_tempMatrix4[13] = 0;
_tempMatrix4[14] = 0;
_tempMatrix4[15] = 1;
return Matrix4.multiply(_tempMatrix4, m, m);
},
/**
* 设置正交投影矩阵
* @param m
* @param width
* @param height
* @param depth
*/
setOrthogonal(m: Mat4, left: number, right: number, bottom: number, top: number, near: number, far: number): Mat4 {
let rw = 1 / (right - left),
rh = 1 / (top - bottom),
rd = 1 / (far - near);
m[0] = 2 * rw;
m[1] = 0;
m[2] = 0;
m[3] = -(left + right) * rw;
m[4] = 0;
m[5] = 2 * rh;
m[6] = 0;
m[7] = -(top + bottom) * rh;
m[8] = 0;
m[9] = 0;
m[10] = -2 * rd;
m[11] = -(far + near) * rd;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
return m;
},
/**
* 设置透视投影矩阵
* @param m
* @param width
* @param height
* @param depth
*/
setPerspective(m: Mat4, fovy: number, aspect: number, near: number, far: number): Mat4 {
let f = Math.cos(fovy / 2) / Math.sin(fovy / 2),
rd = 1 / (far - near);
m[0] = f / aspect;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = f;
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = -(far + near) * rd;
m[11] = -2 * far * near * rd;
m[12] = 0;
m[13] = 0;
m[14] = -1;
m[15] = 0;
return m;
}
};
|
a1dac51643a958a36236ba7fc8e710fe34b42520
|
TypeScript
|
MrAbalogu/kcd-discord-bot
|
/src/admin/deduping-channel-posts.ts
| 2.828125
| 3
|
import type * as TDiscord from 'discord.js'
import {
commandPrefix,
isWelcomeChannel,
getMember,
getMessageLink,
sendBotMessageReply,
isTextChannel,
} from './utils'
const sixHours = 1000 * 60 * 60 * 6
function isLink(text: string) {
try {
// eslint-disable-next-line no-new
new URL(text.trim())
return true
} catch {
return false
}
}
async function dedupeMessages(message: TDiscord.Message) {
const {guild} = message
if (!guild) return
if (message.author.id === message.client.user?.id) return // ignore the bot
if (!isTextChannel(message.channel)) return // ignore non-text channels
if (isWelcomeChannel(message.channel)) return // ignore onboarding channels
if (message.content.startsWith(commandPrefix)) return // ignore commands
if (message.content.length < 50) return // ignore short messages
if (isLink(message.content)) return // ignore links, gifs/blog posts/etc.
const member = getMember(guild, message.author.id)
if (!member) return
const channels = Array.from(
guild.channels.cache
.filter(ch => isTextChannel(ch) && !isWelcomeChannel(ch))
.values(),
) as Array<TDiscord.TextChannel>
function msgFilter(msg: TDiscord.Message) {
return (
msg.id !== message.id && // not the EXACT same message
msg.author.id !== msg.client.user?.id && // not from the bot
msg.author.id === message.author.id && // from the same user
!msg.content.startsWith(commandPrefix) && // not a command
new Date().getTime() - msg.createdAt.getTime() < sixHours && // within the last six hours
msg.content.length > 50 && // longer than 50 characters
msg.content.toLowerCase() === message.content.toLowerCase() // same content
)
}
let duplicateMessage
for (const channel of channels) {
duplicateMessage = Array.from(channel.messages.cache.values()).find(
msgFilter,
)
if (duplicateMessage) break
}
if (duplicateMessage) {
await message.delete({reason: `Duplicate message: ${duplicateMessage.id}`})
const duplicateMessageLink = getMessageLink(duplicateMessage)
await sendBotMessageReply(
message,
`
Hi ${member.user}, I deleted a message you just posted because it's a duplicate of this one: <${duplicateMessageLink}>. Please give it time for users to respond to your first post.
If you think your message is better suited in another channel please delete the first one then repost. Thank you.
`.trim(),
)
}
}
function setup(client: TDiscord.Client) {
// prime the message cache for relevant channels
const guild = client.guilds.cache.find(({name}) => name === 'KCD')
if (!guild) return
const channels = Array.from(
guild.channels.cache
.filter(ch => isTextChannel(ch) && !isWelcomeChannel(ch))
.values(),
) as Array<TDiscord.TextChannel>
for (const channel of channels) {
// ignore the returned promise. Fire and forget.
void channel.messages.fetch({limit: 30})
}
}
export {dedupeMessages as handleNewMessage, setup}
|
49d5df6c7ac32bf4d7037b7f683d89b55bf74a19
|
TypeScript
|
buyforgirl/clibuilder
|
/src/util.ts
| 2.84375
| 3
|
import { Command } from './Command'
export function getCommand(nameOrAlias, commands: Command[]) {
return commands.find(cmd => {
return cmd.name === nameOrAlias ||
(!!cmd.alias && cmd.alias.indexOf(nameOrAlias) !== -1)
})
}
export function getCommandAndAliasNames(commands: { name: string, alias?: string[] }[]) {
const names: string[] = []
commands.forEach(cmd => {
names.push(cmd.name)
if (cmd.alias) {
names.push(...cmd.alias)
}
})
return names.sort()
}
|
c50f531cbdec2506c1d69c22763dc690808e180d
|
TypeScript
|
ekmixon/smartthings-cli
|
/packages/lib/src/io-util.ts
| 2.984375
| 3
|
import fs from 'fs'
import path from 'path'
import util from 'util'
import yaml from 'js-yaml'
import { logManager } from './logger'
export const readFile = util.promisify(fs.readFile)
export const writeFile = util.promisify(fs.writeFile)
export enum IOFormat {
YAML = 'yaml',
JSON = 'json',
// for input, this is Q & A or command line, for output, it's a human-readable table format
COMMON = 'common',
}
export function formatFromFilename(filename: string): IOFormat {
const ext = path.extname(filename).toLowerCase()
if (ext === '.yaml' || ext === '.yml') {
return IOFormat.YAML
}
if (ext === '.json') {
return IOFormat.JSON
}
logManager.getLogger('cli').warn(`could not determine file type from filename "${filename}, assuming YAML`)
return IOFormat.YAML
}
export function parseJSONOrYAML<T>(rawInputData: string, source: string): T {
const data = yaml.safeLoad(rawInputData)
if (!data) {
throw Error(`did not get any data from ${source}`)
}
if (typeof data === 'string') {
throw Error(`got simple string from ${source}`)
}
return data as unknown as T
}
export function readDataFromStdin(): Promise<string> {
return new Promise((resolve, reject) => {
try {
const stdin = process.stdin
const inputChunks: string[] = []
stdin.resume()
stdin.on('data', chunk => {
inputChunks.push(chunk.toString())
})
stdin.on('end', () => {
resolve(inputChunks.join(''))
})
} catch (error) {
reject(error)
}
})
}
/**
* Simple function to test for TTY input. Use this instead of directly calling `process` if you want
* to mock in unit tests.
*/
export function stdinIsTTY(): boolean {
return process.stdin.isTTY
}
/**
* Simple function to test for TTY output. Use this instead of directly calling `process` if you want
* to mock in unit tests.
*/
export function stdoutIsTTY(): boolean {
return process.stdout.isTTY
}
|
704476698477fda611ce44a65881495e54434263
|
TypeScript
|
RomanMitrodorv/TherapyAPI_frontend
|
/src/app/common/pipes/filter-articles.pipe.ts
| 2.53125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Article } from '../models';
@Pipe({
name: 'filterArticles',
pure: false
})
export class FilterArticlesPipe implements PipeTransform {
transform(articles: Article[], activeIndex: number) {
if (!articles || !articles.length || activeIndex === -1) {
return articles;
}
let result = [...articles];
if (activeIndex === 0) {
result.splice(0, 1);
return result;
}
//result.splice(activeIndex - 1, 2);
result.splice(0, activeIndex + 1);
return result;
}
}
|
703ac4b3af050c24051cb69ed7f2b01b58015912
|
TypeScript
|
8coon/next
|
/src/Error/InterceptorNotFound.ts
| 2.515625
| 3
|
import {JSWorksError} from './ErrorDecorator';
@JSWorksError
export class InterceptorNotFoundError extends Error {
constructor(typeOrName: string) {
super(`Interceptor not found :"${typeOrName}"`);
}
}
|
4a50cd52b420acf7b4d888c727ede9fda797912f
|
TypeScript
|
tcgdex/cards-database
|
/data/Sun & Moon/Burning Shadows/82.ts
| 2.515625
| 3
|
import { Card } from '../../../interfaces'
import Set from '../Burning Shadows'
const card: Card = {
name: {
en: "Alolan Raticate",
fr: "Rattatac d’Alola",
es: "Raticate de Alola",
it: "Raticate di Alola",
pt: "Raticate de Alola",
de: "Alola-Rattikarl"
},
illustrator: "Kouki Saitou",
rarity: "Rare",
category: "Pokemon",
set: Set,
dexId: [
20,
],
hp: 120,
types: [
"Darkness",
],
evolveFrom: {
en: "Alolan Rattata",
fr: "Rattata d’Alola",
},
stage: "Stage1",
attacks: [
{
name: {
en: "Enhanced Fang",
fr: "Croc Amélioré",
es: "Incisivos Mejorados",
it: "Zanne Super",
pt: "Presa Acentuada",
de: "Spezial-Zahn"
},
effect: {
en: "If this Pokémon has a Pokémon Tool card attached to it, this attack does 50 more damage.",
fr: "Si une carte Outil Pokémon est attachée à ce Pokémon, cette attaque inflige 50 dégâts supplémentaires.",
es: "Si este Pokémon tiene 1 carta de Herramienta Pokémon unida a él, este ataque hace 50 puntos de daño más.",
it: "Se questo Pokémon ha una carta Oggetto Pokémon assegnata, questo attacco infligge 50 danni in più.",
pt: "Se este Pokémon tiver uma carta de Ferramenta Pokémon ligada a ele, este ataque causará 50 pontos de dano a mais.",
de: "Wenn an dieses Pokémon eine Pokémon-Ausrüstung angelegt ist, fügt diese Attacke 50 Schadenspunkte mehr zu."
},
damage: "10+",
},
{
cost: [
"Darkness",
],
name: {
en: "Hyper Fang",
fr: "Croc de Mort",
es: "Hipercolmillo",
it: "Iperzanna",
pt: "Hiperpresa",
de: "Hyperzahn"
},
effect: {
en: "Flip a coin. If tails, this attack does nothing.",
fr: "Lancez une pièce. Si c’est pile, cette attaque ne fait rien.",
es: "Lanza 1 moneda. Si sale cruz, este ataque no hace nada.",
it: "Lancia una moneta. Se esce croce, questo attacco non ha effetto.",
pt: "Jogue 1 moeda. Se sair coroa, este ataque não fará nada.",
de: "Wirf 1 Münze. Bei Zahl hat diese Attacke keine Auswirkungen."
},
damage: 60,
},
],
weaknesses: [
{
type: "Fighting",
value: "×2"
},
],
resistances: [
{
type: "Psychic",
value: "-20"
},
],
retreat: 3,
}
export default card
|
921cfbf661ba111c47630839988da1da9a8a4727
|
TypeScript
|
CuriosBasant/shadyantra-mono
|
/packages/jugaad/src/new-engine/Utils.ts
| 2.765625
| 3
|
export const BOARD_SIZE = 10
export const ONE_LESS = BOARD_SIZE - 1
export const TOTAL_SQUARES = BOARD_SIZE ** 2
export const _DEFAULT_FEN = '0c1ia1c0/cmhgrsghmc/cppppppppc/9/9/9/9/CPPPPPPPPC/CMHGSRGHMC/0C1AI1C0'
export const DEFAULT_FEN = '.c..ia..c.cmhgrsghmccppppppppc........................................CPPPPPPPPCCMHGSRGHM..C..AI..C.'
export const ORTHOGONAL_DIRECTION = Object.freeze([BOARD_SIZE, 1, -1, -BOARD_SIZE])
export const DIAGNAL_DIRECTION = Object.freeze([BOARD_SIZE - 1, BOARD_SIZE + 1, -BOARD_SIZE - 1, -BOARD_SIZE + 1])
export const ADJACENT_DIRECTION = Object.freeze(DIAGNAL_DIRECTION.concat(ORTHOGONAL_DIRECTION))
export const BOARD_LAYOUT = Array<string>((BOARD_SIZE + 1) ** 2).fill('·')
.map((val, i) => i % (BOARD_SIZE + 1) ? val : `│\n${ 9 - (i / BOARD_SIZE | 0) } │`)
BOARD_LAYOUT[1] = BOARD_LAYOUT[10] = BOARD_LAYOUT[100] = BOARD_LAYOUT[109] = '#'
const temp = ' ' + '-'.repeat(32)
BOARD_LAYOUT[110] = `│\n${ temp }\n `
BOARD_LAYOUT[0] = temp + BOARD_LAYOUT[0].slice(1)
for (let i = 111, str = 'xabcdefghy'; i < 121; i++) {
BOARD_LAYOUT[i] = str[i - 111]
}
export enum SQUARE_FLAGS {
x9, a9, b9, c9, d9, e9, f9, g9, h9, y9,
x8, a8, b8, c8, d8, e8, f8, g8, h8, y8,
x7, a7, b7, c7, d7, e7, f7, g7, h7, y7,
x6, a6, b6, c6, d6, e6, f6, g6, h6, y6,
x5, a5, b5, c5, d5, e5, f5, g5, h5, y5,
x4, a4, b4, c4, d4, e4, f4, g4, h4, y4,
x3, a3, b3, c3, d3, e3, f3, g3, h3, y3,
x2, a2, b2, c2, d2, e2, f2, g2, h2, y2,
x1, a1, b1, c1, d1, e1, f1, g1, h1, y1,
x0, a0, b0, c0, d0, e0, f0, g0, h0, y0,
}
// type valueof<T> = typeof T[keyof typeof T]
export const SYMBOL = {
INDRA: 'I', SHASTRI: 'A', CHARAN: 'C', RISHI: 'R',
SENAPATI: 'S', RATHA: 'M', ASHVA: 'H', GAJA: 'G',
PYADA: 'P'
} as const
export type PieceSymbol = typeof SYMBOL[keyof typeof SYMBOL]
|
70607b5e815eb4e408f2aa1e944b40386d96d45f
|
TypeScript
|
25juan/react-study
|
/vanilla-inspector/src/constructor/Stack.ts
| 2.9375
| 3
|
class Stack<T> {
constructor(private stack:Array<T>) {
}
push(item:T) {
this.stack.push(item);
}
back() {
this.stack.pop();
}
length() {
return this.stack.length;
}
}
const routes = new Stack<string>([]);
routes.push('hello');
|
aa89a0cf5a4d25a9796e0ef5704e111c263746e8
|
TypeScript
|
tomekrozalski/landofhop-gatsby
|
/src/components/Stats/TopBrands/utils/normalizeData.ts
| 2.65625
| 3
|
import { add, format, isBefore, max, min } from 'date-fns';
import { TopBrandsData, RawData } from '../types';
type Props = {
limit: number;
values: RawData;
};
const getTopBrands = ({ limit, values }: Props) => {
type AccType = {
[name: string]: {
amount: number;
badge: string;
id: string;
name: {
language?: string;
value: string;
}[];
};
};
const accumulator = values.allBeverage.edges.reduce(
(acc: AccType, { node }) => {
const { brand } = node;
return {
...acc,
[brand.id]: {
...brand,
amount: acc[brand.id] ? acc[brand.id].amount + 1 : 1,
},
};
},
{},
);
return Object.values(accumulator)
.sort((a, b) => (a.amount < b.amount ? 1 : -1))
.slice(0, limit);
};
const normalizeData = ({ limit, values }: Props): TopBrandsData[] => {
const domain: TopBrandsData[] = [];
const dates = values.allBeverage.edges.map(
({ node }) => new Date(node.added),
);
const earliest = min(dates);
const latest = max(dates);
const endpoint = new Date(
`${format(add(latest, { months: 1 }), 'yyyy-MM')}-01`,
);
let current = earliest;
const topBrands = getTopBrands({ limit, values });
do {
domain.push({
date: format(current, 'yyyy-MM'),
brands: topBrands.map(props => ({
...props,
amount: 0,
})),
});
current = add(current, { months: 1 });
} while (isBefore(current, endpoint));
values.allBeverage.edges.forEach(({ node }) => {
const { brand } = node;
if (!topBrands.map(({ id }) => id).includes(brand.id)) {
return false;
}
const index = domain.findIndex(
({ date }) => date === format(new Date(node.added), 'yyyy-MM'),
);
for (let i = index; i < domain.length; i += 1) {
const selectedBrand = domain[i].brands.find(({ id }) => id === brand.id);
selectedBrand!.amount += 1;
}
return true;
});
return domain;
};
export default normalizeData;
|
6911bc201a2f679712608337d1b3e6eff57ec5bd
|
TypeScript
|
ondaa/common
|
/lib/string/pascalCase.ts
| 2.984375
| 3
|
import toHeadUpperCase from "./toHeaUpperCase";
import onlyString from "./onlyString";
import rmSpace from "./rmSpace";
/**
* @method pascalCase
* @param str 문자열
* @description
* * 파스칼 문법 ex) BigRabbit
*/
const pascalCase = (str: string) =>
onlyString(str, " ")
.split(" ")
.map(v => toHeadUpperCase(rmSpace(v, "all")))
.join("");
export default pascalCase;
|
fb1e707be82519562965505835847f549933fd15
|
TypeScript
|
danielcornock/habi-ui
|
/src/app/core/services/storage/storage.service.ts
| 2.6875
| 3
|
import { Injectable } from '@angular/core';
import { StorageKeys } from '../../constants/storage-keys.constant';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() {}
public set(key: StorageKeys, payload: string): void {
localStorage.setItem(key, payload);
}
public get(key: StorageKeys): string {
return localStorage.getItem(key);
}
public remove(key: StorageKeys): void {
localStorage.removeItem(key);
}
public setObject<T>(key: StorageKeys, payload: T): void {
const stringPayload = JSON.stringify(payload);
this.set(key, stringPayload);
}
public getObject<T>(key: StorageKeys): T {
const payload = this.get(key);
return JSON.parse(payload);
}
}
|
cf335294c0952ed8421ee7c1429c7eff6aa37757
|
TypeScript
|
the-djmaze/Squire
|
/source/node/Block.ts
| 2.5625
| 3
|
import { TreeIterator, SHOW_ELEMENT } from './TreeIterator';
import { isBlock } from './Category';
// ---
const getBlockWalker = (
node: Node,
root: Element | DocumentFragment,
): TreeIterator<HTMLElement> => {
const walker = new TreeIterator<HTMLElement>(root, SHOW_ELEMENT, isBlock);
walker.currentNode = node;
return walker;
};
const getPreviousBlock = (
node: Node,
root: Element | DocumentFragment,
): HTMLElement | null => {
const block = getBlockWalker(node, root).previousNode();
return block !== root ? block : null;
};
const getNextBlock = (
node: Node,
root: Element | DocumentFragment,
): HTMLElement | null => {
const block = getBlockWalker(node, root).nextNode();
return block !== root ? block : null;
};
const isEmptyBlock = (block: Element): boolean => {
return !block.textContent && !block.querySelector('IMG');
};
// ---
export { getBlockWalker, getPreviousBlock, getNextBlock, isEmptyBlock };
|
20f64edb37b446fc6800d355dcaa60521f23cd26
|
TypeScript
|
dnikomon/fhirform-vue
|
/src/fhirform-vue.ts
| 2.65625
| 3
|
/**
* @fileoverview
*
* @author Bell Eapen
*
*/
import { R4 } from '@ahryman40k/ts-fhir-types';
import VueFormGeneratorSchema from 'schema';
import VueFormGeneratorField from 'field';
import Fform from 'fform';
import VueFormGeneratorGroup from 'group';
export const FhirFormVue: any = (fhirjson: any) => {
// validation succeeded
const schemaValidationResult = R4.RTTI_Questionnaire.decode(fhirjson); // => Right if good, Left if not
const fhirq: R4.IQuestionnaire = <R4.IQuestionnaire>(
schemaValidationResult.value
);
let ffvue_qresp: R4.IQuestionnaireResponse = {
resourceType: 'QuestionnaireResponse',
item: [],
status: R4.QuestionnaireResponseStatusKind._inProgress,
};
let ffvue_schema: VueFormGeneratorSchema = {
fields: [],
groups: [],
};
let index = 0;
fhirq.item?.forEach(function(item, _) {
// _ is the ignored index
// If the item is a group
if (item.type == R4.Questionnaire_ItemTypeKind._group) {
// Add legend to the group
let ffvue_group: VueFormGeneratorGroup = {
legend: item.text?.toString(),
fields: [],
};
// Get group items from outer item
let groupitems: Array<R4.IQuestionnaire_Item> = [];
if (item.item) groupitems = item.item;
groupitems.forEach(function(groupitem, _) {
ffvue_group.fields?.push(Fprocess(groupitem, index));
index++;
ffvue_qresp.item?.push(Rprocess(groupitem));
});
ffvue_schema.groups?.push(ffvue_group);
// Just push the fields if not a group
} else {
ffvue_schema.fields?.push(Fprocess(item, index));
index++;
ffvue_qresp.item?.push(Rprocess(item));
}
});
let fform: Fform = {
model: ffvue_qresp,
schema: ffvue_schema,
};
return JSON.stringify(fform);
};
/**
* Takes a R4.IQuestionnaire_Item and returns the VueFormGeneratorField
* @param {R4.IQuestionnaire_Item} item
*
* @returns {VueFormGeneratorField}
*/
const Fprocess = (item: R4.IQuestionnaire_Item, index: number) => {
let ffvue_field: VueFormGeneratorField = {
type: GetControlType(item),
inputType: 'text',
label: item.text?.toString(),
id: item.linkId?.toString(),
textOn: 'on',
textOff: 'off',
dateTimePickerOptions: {
format: 'YYYY-MM-DD HH:mm:ss',
},
model: AddIndexToItems(GetValueType(item), index),
};
return ffvue_field;
};
const Rprocess = (item: R4.IQuestionnaire_Item) => {
let qresp_item: R4.IQuestionnaireResponse_Item = {
linkId: item.linkId,
text: item.text,
answer: [],
};
var key = GetOnlyValueType(GetValueType(item));
let ans: R4.IQuestionnaireResponse_Answer = {};
ans[key] = '';
qresp_item.answer?.push(ans);
return qresp_item;
};
const GetControlType = (item: R4.IQuestionnaire_Item) => {
if (
item.type == R4.Questionnaire_ItemTypeKind._date ||
item.type == R4.Questionnaire_ItemTypeKind._dateTime ||
item.type == R4.Questionnaire_ItemTypeKind._time
) {
return 'dateTimePicker';
}
if (
item.type == R4.Questionnaire_ItemTypeKind._choice ||
item.type == R4.Questionnaire_ItemTypeKind._openChoice
) {
return 'select';
}
if (item.type == R4.Questionnaire_ItemTypeKind._boolean) {
return 'switch';
}
return 'input';
};
const GetValueType = (item: R4.IQuestionnaire_Item) => {
if (item.type == R4.Questionnaire_ItemTypeKind._date) {
return 'item.answer[0].valueDate';
}
if (item.type == R4.Questionnaire_ItemTypeKind._time) {
return 'item.answer[0].valueTime';
}
if (item.type == R4.Questionnaire_ItemTypeKind._dateTime) {
return 'item.answer[0].valueDateTime';
}
if (item.type == R4.Questionnaire_ItemTypeKind._integer) {
return 'item.answer[0].valueInteger';
}
if (item.type == R4.Questionnaire_ItemTypeKind._decimal) {
return 'item.answer[0].valueDecimal';
}
if (item.type == R4.Questionnaire_ItemTypeKind._boolean) {
return 'item.answer[0].valueBoolean';
}
return 'item.answer[0].valueString';
};
/**
*
* @param valueType {string} full model path
*
* @returns {sting} just the type
*/
const GetOnlyValueType = (valueType: string) => {
var pieces = valueType.split(/[\s.]+/); // Split on .
return pieces[pieces.length - 1];
};
const AddIndexToItems = (fullString: string, index: number) => {
return fullString.replace(
'item.answer[0]',
'item[' + index.toString() + '].answer[0]'
);
};
|
c7f731905599ae0eb60d64c0b31b31140f3541d0
|
TypeScript
|
galyniayaroshenko/Resume
|
/src/app/form-validators/phone-number/phone-number.validator.ts
| 2.75
| 3
|
import { AbstractControl } from '@angular/forms';
import { IValidatorResult } from '../validator-result.interface';
export function phoneNumberValidator(control: AbstractControl): IValidatorResult { // tslint:disable-line
const phoneNumberPattern: RegExp = /^([0-9()+ -]*)$/;
if (control.value && !phoneNumberPattern.test(control.value)) {
return { phoneNumber: 'Value should be valid phone number' };
}
return null;
}
|
c9034bd0ca1ddb3599f76e08a09b473abf25f5f5
|
TypeScript
|
ionic-team/stencil
|
/src/sys/node/node-lazy-require.ts
| 2.75
| 3
|
import { buildError } from '@utils';
import fs from 'graceful-fs';
import path from 'path';
import semverLte from 'semver/functions/lte';
import major from 'semver/functions/major';
import satisfies from 'semver/functions/satisfies';
import type * as d from '../../declarations';
import { NodeResolveModule } from './node-resolve-module';
/**
* The version range that we support for a given package. The strings should be
* standard semver strings.
*/
interface DepVersionRange {
minVersion: string;
recommendedVersion: string;
/**
* Max version is optional because we aren't always worried about upgrades.
* This should be set for packages where major version upgrades have
* historically caused problems, or when we've identified a specific issue
* that requires us to stay at or below a certain version. Note that
* `NodeLazyRequire.ensure` only checks the major version.
*/
maxVersion?: string;
}
/**
* A manifest for lazily-loaded dependencies, mapping dependency names to
* version ranges.
*/
export type LazyDependencies = Record<string, DepVersionRange>;
/**
* Lazy requirer for Node, with functionality for specifying version ranges and
* returning diagnostic errors if requirements aren't met.
*/
export class NodeLazyRequire implements d.LazyRequire {
private ensured = new Set<string>();
/**
* Create a NodeLazyRequire instance
*
* @param nodeResolveModule an object which wraps up module resolution functionality
* @param lazyDependencies the dependency requirements we want to enforce here
*/
constructor(
private nodeResolveModule: NodeResolveModule,
private lazyDependencies: LazyDependencies,
) {}
/**
* Ensure that a dependency within our supported range is installed in the
* current environment. This function will check all the dependency
* requirements passed in when the class is instantiated and return
* diagnostics if there are any issues.
*
* @param fromDir the directory from which we'll attempt to resolve the
* dependencies, typically this will be project's root directory.
* @param ensureModuleIds an array of module names whose versions we're going
* to check
* @returns a Promise holding diagnostics if any of the dependencies either
* were not resolved _or_ did not meet our version requirements.
*/
async ensure(fromDir: string, ensureModuleIds: string[]): Promise<d.Diagnostic[]> {
const diagnostics: d.Diagnostic[] = [];
const problemDeps: string[] = [];
ensureModuleIds.forEach((ensureModuleId) => {
if (!this.ensured.has(ensureModuleId)) {
const { minVersion, recommendedVersion, maxVersion } = this.lazyDependencies[ensureModuleId];
try {
const pkgJsonPath = this.nodeResolveModule.resolveModule(fromDir, ensureModuleId);
const installedPkgJson: d.PackageJsonData = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
const installedVersionIsGood = maxVersion
? // if maxVersion, check that `minVersion <= installedVersion <= maxVersion`
satisfies(installedPkgJson.version, `${minVersion} - ${major(maxVersion)}.x`)
: // else, just check that `minVersion <= installedVersion`
semverLte(minVersion, installedPkgJson.version);
if (installedVersionIsGood) {
this.ensured.add(ensureModuleId);
return;
}
} catch (e) {}
// if we get here we didn't get to the `return` above, so either 1) there was some error
// reading the package.json or 2) the version wasn't in our specified version range.
problemDeps.push(`${ensureModuleId}@${recommendedVersion}`);
}
});
if (problemDeps.length > 0) {
const err = buildError(diagnostics);
err.header = `Please install supported versions of dev dependencies with either npm or yarn.`;
err.messageText = `npm install --save-dev ${problemDeps.join(' ')}`;
}
return diagnostics;
}
require(fromDir: string, moduleId: string) {
const modulePath = this.getModulePath(fromDir, moduleId);
return require(modulePath);
}
getModulePath(fromDir: string, moduleId: string) {
const modulePath = this.nodeResolveModule.resolveModule(fromDir, moduleId);
return path.dirname(modulePath);
}
}
|
047e999d75eef5fde81a0c386533d9fd85642ba8
|
TypeScript
|
duydao/vscode-mockthis
|
/src/switcher/SpecFileSwitcher.ts
| 2.71875
| 3
|
import * as path from 'path';
import * as vscode from 'vscode';
export interface SpecFileSwitcherBehavior {
findFiles(include: string, exclude: string): Thenable<vscode.Uri[]>;
showWarningMessage(message: string, ...items: string[]): void;
}
class DefaultSpecFileSwitcherBehavior implements SpecFileSwitcherBehavior {
findFiles(include: string, exclude: string): Thenable<vscode.Uri[]> {
return vscode.workspace.findFiles(include, exclude, 100);
}
showWarningMessage(message: string, ...items: string[]) {
vscode.window.showWarningMessage(message, ...items);
}
}
export class SpecFileSwitcher {
private editorFileName: string;
private fileSuffixes: string[];
private excludePattern: string;
private behavior: SpecFileSwitcherBehavior;
private currentIndex: number;
public matchingFiles: string[];
public callback: (name: string) => void;
public constructor(behavior?: SpecFileSwitcherBehavior) {
this.behavior = behavior ? behavior : new DefaultSpecFileSwitcherBehavior;
this.currentIndex = -1;
}
public readFiles(callsNext?: boolean): Thenable<void> {
let name: string = path.parse(this.editorFileName).name;
let ext: string = path.parse(this.editorFileName).ext;
let unitTestBase: string = name;
this.fileSuffixes.some(suffix => name.endsWith(suffix));
this.matchingFiles = [];
let self = this;
let promise: Thenable<vscode.Uri[]> = this.behavior.findFiles('**/' + unitTestBase + '{,' + this.fileSuffixes.join(',') + '}' + ext, self.excludePattern);
return promise.then(uris => {
if (!uris) {
return;
}
uris.forEach(uri => {
self.matchingFiles.push(uri.fsPath);
});
self.matchingFiles.sort();
self.currentIndex = self.matchingFiles.indexOf(self.editorFileName);
if (callsNext) {
self.callNext();
}
});
}
public next() {
if (this.currentIndex < 0) {
this.readFiles(true);
} else {
this.callNext();
}
}
public isFirstTime() {
return !this.matchingFiles;
}
public hasNext() {
return this.matchingFiles && 1 < this.matchingFiles.length;
}
private callNext() {
if (!this.hasNext()) {
this.behavior.showWarningMessage('Not found match files...');
return;
}
this.currentIndex = (this.currentIndex + 1) % this.matchingFiles.length;
this.callback(this.matchingFiles[this.currentIndex]);
}
public readFilesBy(editorFileName: string, fileSuffixes: string[], excludePatterns: string[]): Thenable<void> {
this.editorFileName = editorFileName;
this.fileSuffixes = fileSuffixes;
this.excludePattern = this.resolveExcludePatterns(excludePatterns);
return this.readFiles();
}
private resolveExcludePatterns(excludePatterns: string[]): string {
return excludePatterns ? '{' + excludePatterns.join(',') + '}' : null;
}
public currentFileOfToggle(): string {
return this.isFirstTime() ? null : this.matchingFiles[this.currentIndex];
}
public outputMatchingFiles() {
if (!this.matchingFiles) {
console.log('null');
return;
}
else if (this.matchingFiles.length === 0) {
console.log('[]');
return;
}
console.log(this.matchingFiles.join('\n'));
}
}
|
e47723d3b61824a42cfe20b644fa45a96bacecf3
|
TypeScript
|
seek-oss/playroom
|
/src/utils/formatting.spec.ts
| 2.921875
| 3
|
import {
positionToCursorOffset,
cursorOffsetToPosition,
formatCode,
formatAndInsert,
} from './formatting';
describe('cursor offset to position', () => {
it('should work for one line', () => {
const code = `<h1>Title</h1>`;
const position = 4; // Before the capital T
expect(cursorOffsetToPosition(code, position)).toEqual({ line: 0, ch: 4 });
});
it('should work across multiple lines', () => {
const code = `<div>\n<h1>Title</h1>\n</div>`;
const position = 10; // Before the capital T
expect(cursorOffsetToPosition(code, position)).toEqual({ line: 1, ch: 4 });
});
});
describe('position to cursor offset', () => {
it('should work for one line', () => {
const code = `<h1>Title</h1>`;
const offset = {
line: 0,
ch: 4,
}; // Before the capital T
expect(positionToCursorOffset(code, offset)).toEqual(4);
});
it('should work across multiple lines', () => {
const code = `<div>\n<h1>Title</h1>\n</div>`;
const offset = {
line: 1,
ch: 4,
};
expect(positionToCursorOffset(code, offset)).toEqual(10);
});
});
describe('formatting code', () => {
it('should handle one line', () => {
const code = `<div><h1>Title</h1></div>`;
expect(formatCode({ code, cursor: { line: 0, ch: 9 } })).toEqual({
cursor: { line: 1, ch: 6 },
code: `<div>\n <h1>Title</h1>\n</div>\n`,
});
});
it('should handle multiple lines', () => {
const code = `<div>\n<h1>Title</h1>\n</div>`;
expect(formatCode({ code, cursor: { line: 1, ch: 4 } })).toEqual({
cursor: { line: 1, ch: 6 },
code: `<div>\n <h1>Title</h1>\n</div>\n`,
});
});
it('should handle multiple lines with cursor at start of line', () => {
const code = `<div>\n<h1>Title</h1>\n</div>`;
expect(formatCode({ code, cursor: { line: 1, ch: 0 } })).toEqual({
cursor: { line: 1, ch: 0 },
code: `<div>\n <h1>Title</h1>\n</div>\n`,
});
});
it('should handle multiple root level jsx elements', () => {
const code = `<div><h1>Title</h1></div><div><h1>Title Two</h1></div>`;
expect(formatCode({ code, cursor: { line: 0, ch: 34 } })).toEqual({
cursor: { line: 4, ch: 6 },
code: `<div>\n <h1>Title</h1>\n</div>\n<div>\n <h1>Title Two</h1>\n</div>\n`,
});
});
});
describe('format and insert', () => {
it('should handle inserting one line into one line', () => {
const snippet = '<span>added</span>';
const code = `<div><h1>Title</h1></div>`;
expect(
formatAndInsert({ code, cursor: { line: 0, ch: 9 }, snippet })
).toEqual({
cursor: { line: 2, ch: 22 },
code: `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n`,
});
});
it('should handle inserting multiple lines into multiple lines', () => {
const snippet = '<span>\n <strong>second</strong>\n</span>';
const code = `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n`;
expect(
formatAndInsert({ code, cursor: { line: 2, ch: 15 }, snippet })
).toEqual({
cursor: { line: 6, ch: 13 },
code: `<div>\n <h1>\n <span>\n added\n <span>\n <strong>second</strong>\n </span>\n </span>\n Title\n </h1>\n</div>\n`,
});
});
it('should handle inserting at the start', () => {
const snippet = '<span>\n <strong>second</strong>\n</span>';
const code = `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n`;
expect(
formatAndInsert({ code, cursor: { line: 0, ch: 0 }, snippet })
).toEqual({
cursor: { line: 2, ch: 7 },
code: `<span>\n <strong>second</strong>\n</span>\n<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n`,
});
});
it('should handle inserting at the end', () => {
const snippet = '<span>\n <strong>second</strong>\n</span>';
const code = `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n`;
expect(
formatAndInsert({ code, cursor: { line: 5, ch: 0 }, snippet })
).toEqual({
cursor: { line: 7, ch: 7 },
code: `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n<span>\n <strong>second</strong>\n</span>\n`,
});
});
it('should handle inserting at the end after multiple new lines', () => {
const snippet = '<span>\n <strong>second</strong>\n</span>\n';
const code = `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n\n\n\n`;
expect(
formatAndInsert({ code, cursor: { line: 8, ch: 0 }, snippet })
).toEqual({
cursor: { line: 9, ch: 0 },
code: `<div>\n <h1>\n <span>added</span>Title\n </h1>\n</div>\n\n<span>\n <strong>second</strong>\n</span>\n`,
});
});
});
|
22b59d92daee6d07a73fbf914464d22793e3e459
|
TypeScript
|
Sersph/chaos-forum
|
/frontend/front/src/util/ajax.ts
| 2.703125
| 3
|
import axios from 'axios';
// 携带 cookie
axios.defaults.withCredentials = true;
type Method =
| 'get'
| 'GET'
| 'post'
| 'POST'
| 'put'
| 'PUT'
| 'delete'
| 'DELETE'
| 'options'
| 'OPTIONS'
| 'head'
| 'HEAD'
| 'patch'
| 'PATCH'
| 'POST_FILE';
// ajax 请求封装模块
export default function ajax(method: Method, url: string, data = {}): object {
return new Promise(async (resolve, reject) => {
// axios response 对象
let response = {
data: {}
};
try {
switch (method) {
case 'GET':
// 发送 get
response = await axios({
method,
url,
params: data,
withCredentials: true
});
break;
case 'POST':
// 发送 post
response = await axios({
method,
url,
data,
transformRequest: [
function (oldData) {
let newStr = '';
for (let item in oldData) {
newStr += encodeURIComponent(item) + '=' + encodeURIComponent(oldData[item]) + '&';
}
newStr = newStr.slice(0, -1);
return newStr;
}
],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
break;
case 'POST_FILE':
// 发送 post
response = await axios({
method: 'POST',
url,
data
});
break;
case 'PUT':
// 发送 delete
response = await axios({
method,
url,
data,
transformRequest: [
function (oldData) {
let newStr = '';
for (let item in oldData) {
newStr += encodeURIComponent(item) + '=' + encodeURIComponent(oldData[item]) + '&';
}
newStr = newStr.slice(0, -1);
return newStr;
}
],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
break;
case 'DELETE':
// 发送 delete
response = await axios({
method,
url,
data,
transformRequest: [
function (oldData) {
let newStr = '';
for (let item in oldData) {
newStr += encodeURIComponent(item) + '=' + encodeURIComponent(oldData[item]) + '&';
}
newStr = newStr.slice(0, -1);
return newStr;
}
],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
break;
default:
console.log(`ajax request method error: ${method}`);
}
resolve(response.data);
} catch (e) {
reject(e);
}
});
}
|
91e3cdb84d7b231b2a7dc71b91b8474ac48f82ee
|
TypeScript
|
ptp28/spl
|
/src/parsers/block-parsers/variable-statements-parser/variable-modification-parser.ts
| 2.859375
| 3
|
import { Scope } from "src/models/Scope";
import { LineOfCode } from "src/models/LineOfCode";
import { BlockParser } from "src/parsers/block-parsers/block-parser";
import { Block } from "src/blocks/Block";
import { VariableBlock, VariableBlockType } from "src/blocks/variable-blocks/variable-block";
import { ExpressionEvaluator } from "src/expression-evaluators/expression-evaluator";
import { ArithmeticExpressionEvaluator } from "src/expression-evaluators/arithmetic-expressions/arithmetic-expression-evaluator";
import { BooleanExpressionEvaluator } from "src/expression-evaluators/boolean-expressions/boolean-expression-evaluator";
import { StringExpressionEvaluator } from "src/expression-evaluators/string-expression-evaluator";
import { ArrayExpressionEvaluator } from "src/expression-evaluators/array-expression-evaluator";
export class VariableModificationParser extends BlockParser {
private readonly expressionEvaluators: { [key: string]: ExpressionEvaluator } = {};
private readonly primitiveExpressionEvaluators: ExpressionEvaluator[] = [];
private readonly mapping: string[] = [
'number',
'boolean',
'string'
];
private static regex =
/^set\s* (\S*)\s* to\s* (.*)\s*$/;
constructor(public scope: Scope,
public lineOfCodes: LineOfCode[]) {
super();
this.expressionEvaluators.number = new ArithmeticExpressionEvaluator(this.scope);
this.expressionEvaluators.boolean = new BooleanExpressionEvaluator(this.scope);
this.expressionEvaluators.string = new StringExpressionEvaluator(this.scope);
this.expressionEvaluators.array = new ArrayExpressionEvaluator(this.scope);
// If order changes, change the order of this.mapping
this.primitiveExpressionEvaluators.push(new ArithmeticExpressionEvaluator(this.scope));
this.primitiveExpressionEvaluators.push(new BooleanExpressionEvaluator(this.scope));
this.primitiveExpressionEvaluators.push(new StringExpressionEvaluator(this.scope));
}
tryParse(): boolean {
const lineUnderTest = this.lineOfCodes[this.lineOfCodes.length - 1];
return VariableModificationParser.regex.test(lineUnderTest.value);
}
private modifyingArray(identifier: string, value: string): Block {
const regexMatchResult = identifier.trim().match(/^([_a-zA-Z][_a-zA-Z0-9]*)\[(.+)]$/);
if (regexMatchResult) {
const arrayName = regexMatchResult[1];
if (arrayName === "") {
throw new Error('Invalid array name at line: ' +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
const indexOfArrayAsString = regexMatchResult[2];
let index: any;
try {
index = new ArithmeticExpressionEvaluator(this.scope).evaluate(indexOfArrayAsString);
} catch (e) {
throw new Error('Invalid index expression of array at line: ' +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
if (this.scope.hasVariable(arrayName) === false) {
throw new Error(`Array: ${arrayName} not found at line: ` +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
const array = this.scope.getVariable(arrayName);
if (array.type !== 'array') {
throw new Error(`Variable: ${arrayName} is not an array at line: ` +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
if (index < 0 || index >= array.value.length) {
throw new Error(`Index out of bounds exception at line: ` +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
let type: string = 'NULL';
for (let i = 0; i < this.primitiveExpressionEvaluators.length; i++) {
const evaluator = this.primitiveExpressionEvaluators[i];
if (evaluator.tryEvaluate(value)) {
value = evaluator.evaluate(value)
type = this.mapping[i];
break;
}
}
if (type === 'NULL') {
throw new Error(`Invalid value being assigned at line: ` +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
if (type !== array.arrayType) {
throw new Error(`Inconsistent types at line: ` +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
const newValues = [...array.value];
newValues[index] = value;
// Remove the line as it is done parsing.
this.lineOfCodes.pop();
return new VariableBlock(
VariableBlockType.set,
arrayName,
array.type,
newValues,
false,
this.scope
);
}
throw new Error('Invalid modification of array at line: ' +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
parse(): Block {
if (this.tryParse()) {
const lineUnderTest = this.lineOfCodes[this.lineOfCodes.length - 1];
const result = lineUnderTest.value.match(VariableModificationParser.regex);
if (result) {
const variableName = result[1];
const value = result[2];
if (/\[.*]$/.test(variableName)) {
return this.modifyingArray(variableName, value);
}
if (this.scope.hasVariable(variableName.trim()) === false) {
throw new Error('Invalid identifier: ' + variableName.trim() +
' at line: ' + lineUnderTest.number);
}
const variable = this.scope.getVariable(variableName.trim());
const valueEvaluator = this.expressionEvaluators[variable.type];
if (valueEvaluator.tryEvaluate(value) === false) {
throw new Error('Invalid value assigned to variable at line: ' + lineUnderTest.number);
}
if (variable.type === 'array') {
const valueType = (valueEvaluator as ArrayExpressionEvaluator).getType(value);
if (valueType !== 'any' && valueType !== variable.arrayType) {
throw new Error("Variable's type is different from value's type")
}
}
// Remove the line as it is done parsing.
this.lineOfCodes.pop();
return new VariableBlock(
VariableBlockType.set,
variableName,
variable.type,
valueEvaluator.evaluate(value),
false,
this.scope
);
}
}
throw new Error('Invalid variable modification statement at line: ' +
this.lineOfCodes[this.lineOfCodes.length - 1].number);
}
}
|
4a4f8af5318c31596d4548e84b955dc0fb04f3e5
|
TypeScript
|
cybermizrach/sqlite-wasm
|
/src/ts/module.ts
| 2.6875
| 3
|
namespace Module {
export type stack = number & { __type__: "stack" }
export type i8 = number & { __type__: "i8", __size__: 1 }
export type i32 = number & { __type__: "i32", __size__: 4 }
export type ptr<T> = number & { __type__: "ptr", __deref__: T, __size__: 4 }
export type arr<T extends sized> = number & { __type__: "arr", __deref__: Array<T>, __size__: 4 }
export type sized = { __size__: number }
export declare function getValue<T extends ptr<any>>(ptr: ptr<T>, type: "*", noSafe?: boolean): T | 0;
export declare function getValue(ptr: ptr<i32>, type: "i32", noSafe?: boolean): i32;
export declare function getValue(ptr: ptr<number>, type: "double", noSafe?: boolean): number;
export declare function UTF8ToString(ptr: ptr<string>): string
export declare function stringToUTF8(str: string, outPtr: ptr<string>, maxBytesToWrite: number): void
export const stackSave
: () => stack
= Module["Runtime"].stackSave
export const stackRestore
: (stack: stack) => void
= Module["Runtime"].stackRestore
export const stackAlloc
: <T extends sized>(size: number & T["__size__"]) => ptr<T>
= Module["Runtime"].stackAlloc
export const addFunction
: <T extends Function>(func: T) => ptr<T>
= Module["Runtime"].addFunction
export const removeFunction
: <T extends Function>(ptr: ptr<T>) => void
= Module["Runtime"].removeFunction
}
|
c1860d9c7dbfdcae7aefbf12d3f89eab18eff2c8
|
TypeScript
|
tiagomota79/check-it-off-frontend
|
/src/type.d.ts
| 2.828125
| 3
|
interface ITask {
id: string;
text: string;
active: boolean;
listTitle: string;
listId: string;
}
interface IList {
id: string;
title: string;
description: string;
active: boolean;
}
interface IListsState {
lists: IList[];
}
interface ITasksState {
tasks: ITask[];
}
interface IThemeState {
theme: string;
}
|
cb8038fa0cd9429fb8aba6368eaf160ff12d464a
|
TypeScript
|
rehael/testcafe-config-example
|
/config.ts
| 2.71875
| 3
|
const environmentVariableName = 'env';
const defaultEnvironmentName = 'dev';
const environmentConfigurationFileName = 'environments.json';
const getArgOrEnv = (argName, defaultValue) => {
let arg = process.argv.find(arg => arg.startsWith(`--${argName}=`));
return arg?.split('=')[1] ?? process.env[environmentVariableName] ?? defaultValue;
};
export const getEnv = () => getArgOrEnv(environmentVariableName, defaultEnvironmentName);
export const getConfig = () => {
const fs = require('fs');
const env = getEnv();
return JSON.parse(fs.readFileSync(environmentConfigurationFileName, 'utf8'))[env];
};
|
be7a7c8fe9b545c857804121603b02a8a8c5617f
|
TypeScript
|
petermirithu/Angular-Goal_app
|
/src/app/goal/goal.component.ts
| 2.59375
| 3
|
import { Component, OnInit } from '@angular/core';
import {Goal} from '../goal'
@Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.css']
})
export class GoalComponent implements OnInit {
ngOnInit(): void {
throw new Error("Method not implemented.");
}
goals:Goal[] = [
new Goal( 1, 'Become a PRO at Software Development.', 'Find all ways of being a PRO'),
new Goal( 2, 'Learn how to find loop holes in a machine.', 'Get all metasploit tools'),
new Goal( 3, 'Get equipped in ICT security.', 'learn how to use metasploit'),
];
toggleDetails(index){
this.goals[index].showDescription = !this.goals[index].showDescription;
}
deleteGoal(isComplete, index){
if(isComplete){
let toDelete = confirm(`Are you sure you wanna delete ${this.goals[index].name}?`)
if (toDelete) {
this.goals.splice(index,1);
}
}
GoalComponent.constructor(); { }
this.ngOnInit(); {
}
}
addNewGoal(goal){
let goalLength = this.goals.length;
goal.id = goalLength+1;
goal.completeDate = new Date(goal.completeDate)
this.goals.push(goal)
}
}
|
89d73168163586db5295a9ee48ef10d5e5013ea8
|
TypeScript
|
DreamLarva/js-ts-Algorithms
|
/leetcode/961.重复N次的元素.ts
| 4.40625
| 4
|
/*
961. 重复 N 次的元素
在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。
返回重复了 N 次的那个元素。
示例 1:
输入:[1,2,3,3]
输出:3
示例 2:
输入:[2,1,2,5,3,2]
输出:2
示例 3:
输入:[5,1,5,2,5,3,5,4]
输出:5
提示:
4 <= A.length <= 10000
0 <= A[i] < 10000
A.length 为偶数
* */
function repeatedNTimes(A: number[]): number {
// 正常的做法 使用map 计数 一旦等于一半就是结果
// 根据题意
// 除了那个 重复的元素 则 其他的元素都 是不等的
// 取巧的做法 在满足上面的原则 下 一定会出现 3个连续元素中至少有2个相同的情况
// 除了等于数组长度 为 4 的情况 可能出爱心 [1,2,3,1] 刚好不满足
for (let i = 0; i < A.length - 2; i++) {
const a = A[i];
const b = A[i + 1];
const c = A[i + 2];
if (a === b || a === c) {
return a;
}
if (b === c) {
return b;
}
}
return A[A.length - 1];
}
import assert from "assert";
assert.strictEqual(repeatedNTimes([1, 2, 3, 3]), 3);
assert.strictEqual(repeatedNTimes([2, 1, 2, 5, 3, 2]), 2);
assert.strictEqual(repeatedNTimes([5, 1, 5, 2, 5, 3, 5, 4]), 5);
|
8aa9bba2c4be2b309abc407f29937846c3b97667
|
TypeScript
|
supabase/supabase
|
/packages/ui/src/lib/utils/mergeDeep.ts
| 3.578125
| 4
|
/**
* Check if item is Object
*/
export function isObject(item: any): boolean {
return item && typeof item === 'object' && !Array.isArray(item)
}
/**
* Deep merge two objects.
* @return merged object
*/
export function mergeDeep(target: any, ...sources: any[]): any {
if (sources.length === 0) return target
const source = sources.shift()
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
mergeDeep(target[key], source[key])
} else {
Object.assign(target, { [key]: source[key] })
}
}
}
return mergeDeep(target, ...sources)
}
|
a06b57a4146ee166819bd6caf6f02eda3c3edced
|
TypeScript
|
angelbeltran/mobile-landscape
|
/src/canvas/entities/shapes/circle.ts
| 3.25
| 3
|
import Shape from './shape';
interface Props {
radius: number;
[key: string]: any;
}
/*
* x, y, radius,
*/
export default class Circle extends Shape {
radius: number;
constructor(props: Props) {
super(props);
this.radius = props.radius;
}
draw() {
this.ctx.beginPath();
this.ctx.arc(0, 0, this.radius, 0, 2 * Math.PI);
if (this.fillStyle) {
this.ctx.fill();
}
if (this.strokeStyle) {
this.ctx.stroke();
}
}
}
|
85a1fe671d6272a23b2283fb17fd411fd3fd4894
|
TypeScript
|
openluck/demoCollection-
|
/project/reactComponent/CatMovies-master/server/src/entities/Movie.ts
| 3.234375
| 3
|
import { MinLength, MaxLength, IsNotEmpty, ArrayMinSize, Min, Max, IsArray, validate, ValidationOptions, ValidatorOptions } from "class-validator"
import { Type, plainToClass } from "class-transformer"
import { BaseEntites } from "./BaseEntites"
/**
* 电影类, 记录一个电影实例的成员
*/
export class Movie extends BaseEntites{
/**
* 电影名称
*/
@IsNotEmpty({ message: "电影名称不能为空" })
@MinLength(4, { message: "电影名称长度不能小于4" })
@MaxLength(12, { message: "电影名称的长度不能超过12" })
@Type(() => String)
public name: string
/**
* 电影类型
*/
@IsNotEmpty({ message: "电影的类型不能为空" })
@IsArray({ message: "电影的类型必须是数组" })
@ArrayMinSize(1, { message: "电影的类型不能小于1" })
@Type(() => String)
public types: string[]
/**
* 电影上映地区
*/
@IsNotEmpty({ message: "电影的上映地区不能为空" })
@IsArray({ message: "电影的上映地区必须是数组" })
@ArrayMinSize(1, { message: "电影的上映地区不能小于1" })
@Type(() => String)
public area: string[]
/**
* 电影播放时长(分钟为单位)
*/
@IsNotEmpty({ message: "电影时长不能为空" })
@Min(1, { message: "电影时长不足一分钟, 请检查时长是否有误" })
@Max(99999, { message: "电影时长超过99999分钟, 请检查时长是否有误" })
@Type(() => Number)
public timeLong: number
/**
* 电影是否热映
*/
@IsNotEmpty({ message: "是否热映不能为空" })
@Type(() => Boolean)
public isHot: boolean
/**
* 电影是否为经典电影
*/
@IsNotEmpty({ message: "是否是经典电影不能为空" })
@Type(() => Boolean)
public isClassic: boolean
/**
* 电影是否即将上映
*/
@IsNotEmpty({ message: "是否即将上映不能为空" })
@Type(() => Boolean)
public isComming: boolean
/**
* 电影的描述
*/
@Type(() => String)
public description?: string
/**
* 电影的海报: 图片
*/
@Type(() => String)
public poster?: string
/**
* 将piainObject转换为Movie类的实例
* @param plainObject 平面对象
*/
public static transform(plainObject: object): Movie {
return super.baseTransform(this, plainObject);
}
public async validateThis(validatorOptions?: ValidatorOptions): Promise<string[]> {
return super.validateThis(validatorOptions);
}
}
|
d6de34c3b5e9dd05576a63877ead16d8c0bc2ee0
|
TypeScript
|
vochabular/admin-frontend
|
/src/helper/Diff.ts
| 3.5
| 4
|
import odiff from "odiff";
/**
* TODO(df): Create PR and export this in the odiff lib
*/
type odiffResultType = "set" | "unset" | "add" | "rm";
/**
* TODO(df): Create PR and export this in the odiff lib
*/
interface odiffResult {
type: odiffResultType;
path: Array<string | number>;
val: any;
index: number;
vals: any[];
num: number;
}
/**
* A (wrapper) class for deep comparison of two objects.
* Once instantiated with an "old" and "new" object, the public CRUD properties can be accessed
* Based on / Credits: https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects
*/
export default class Diff {
/**
* Input object 1 - The results of the comparison are relative to this object
*/
oldObj: any;
/**
* Input object 2 - Will be compared to the "old" object
*/
newObj: any;
/**
* The difference of the two constructor objects
*/
diff: odiffResult[];
constructor(oldObj: any, newObj: any) {
this.oldObj = oldObj;
this.newObj = newObj;
this.diff = odiff(oldObj, newObj);
}
get created() {
return this.filter(this.diff, "add");
}
get deleted() {
return this.filter(this.diff, "rm");
}
get updated() {
return this.filter(this.diff, "set");
}
get isEqual() {
return (
this.created.length + this.updated.length + this.deleted.length === 0
);
}
private filter(input: odiffResult[], filter: odiffResultType) {
return input.filter(e => e.type === filter);
}
}
|
69ae243c99b012193542732ccc3df38cde3d39f3
|
TypeScript
|
YangSeungWook/ts-inflearn
|
/.history/class-note/5_operator_20210404232841.ts
| 4.09375
| 4
|
// function logMessage(value:any){
// console.log(value);
// }
// logMessage('hello');
// logMessage(100);
// Union Type ( 파이프 연산자를 이용하여 추가로 사용가능)
var seho : string | number | boolean;
function logMessage(value : string | number){
if(typeof value == 'number'){
value.toLocaleString();
}
if(typeof value == 'string'){
value.toString();
}
throw new TypeError('value must be string or number';)
}
logMessage('hello');
logMessage(100);
|
155fff9a002cf54903e166b77ac89edc2b792eae
|
TypeScript
|
mertsev/react-test-project
|
/frontend/src/api/btc-data.api.ts
| 2.75
| 3
|
import axios from "axios";
export function fetchFromApi() {
return axios({
method: 'get',
url: 'https://blockchain.info/ticker',
responseType: 'json'
})
}
let btcPrice = 0;
export const getBtcData = (): Promise<number> => {
const promise = new Promise<number>(resolve => {
fetchFromApi().then((response) => {
console.log(response.data["USD"]["last"]);
btcPrice = response.data["USD"]["last"];
resolve(btcPrice);
}, (error) => {
console.log(error);
});
});
return promise;
};
|
ee53364deb4390c11864db73091036be8c44ce79
|
TypeScript
|
ondfavourmachine/egora_treasury
|
/src/app/utilities/utility-functions.ts
| 2.53125
| 3
|
export class UtilityFunctions{
static toggleSidebar(event: Event, remove?: string){
if(remove){
const icons: NodeListOf<HTMLElement> = document.querySelectorAll('.targetted_icon');
const spanWithText: NodeListOf<HTMLElement> = document.querySelectorAll('.targetted');
const header: HTMLElement = document.querySelector('.offcanvas-header');
const sideBar: HTMLElement = document.getElementById('offcanvasExample');
const majorSide: HTMLElement = document.querySelector('.major_side');
majorSide.classList.remove('increaseSize');
sideBar.classList.remove('reduceSize');
header.classList.remove('hide');
icons.forEach(elem => elem.classList.remove('hide'));
spanWithText.forEach(elem => elem.classList.remove('hide'));
const showWhenTogglerIsOff = document.querySelector('.showWhenTogglerIsOff');
showWhenTogglerIsOff.classList.add('hide')
showWhenTogglerIsOff.classList.remove('show');
return;
}
const icons: NodeListOf<HTMLElement> = document.querySelectorAll('.targetted_icon');
const spanWithText: NodeListOf<HTMLElement> = document.querySelectorAll('.targetted');
const header: HTMLElement = document.querySelector('.offcanvas-header');
const sideBar: HTMLElement = document.getElementById('offcanvasExample');
const majorSide: HTMLElement = document.querySelector('.major_side');
majorSide.classList.add('increaseSize');
sideBar.classList.add('reduceSize');
header.classList.add('hide');
icons.forEach(elem => elem.classList.add('hide'));
spanWithText.forEach(elem => elem.classList.add('hide'));
const showWhenTogglerIsOff = document.querySelector('.showWhenTogglerIsOff');
showWhenTogglerIsOff.classList.remove('hide')
showWhenTogglerIsOff.classList.add('show');
}
}
|
4ed63490c01f7b87fafacccda1aed1da0340a783
|
TypeScript
|
TwinsMaj/exbanking
|
/src/account.ts
| 2.828125
| 3
|
/* eslint-disable require-jsdoc */
import { add, subtract } from './utils/currency';
import { Currency } from 'dinero.js';
export class Account {
private static ACCOUNT_PREFIX = 'ACCT';
private accounts = {
[`${Account.ACCOUNT_PREFIX}_USD`]: 0.0,
[`${Account.ACCOUNT_PREFIX}_EUR`]: 0.0,
};
public credit(amount: number, currency: string): number {
const balance = this.getAccountBalance(currency);
const total = add(amount, balance, currency as Currency);
this.setAccountBalance(total, currency);
return total;
}
public debit(amount: number, currency: string): number {
const balance = this.getAccountBalance(currency);
const result = subtract(amount, balance, currency as Currency);
this.setAccountBalance(result, currency);
return result;
}
public addAccountFor(currency: string): void {
const accountKey = `${Account.ACCOUNT_PREFIX}_${currency}`;
this.accounts[accountKey] = 0.0;
}
public getAccountBalance(currency: string): number {
const accountKey = `${Account.ACCOUNT_PREFIX}_${currency}`;
return this.accounts[accountKey];
}
private setAccountBalance(amount: number, currency: string): void {
const accountKey = `${Account.ACCOUNT_PREFIX}_${currency}`;
amount = amount <= 0 ? 0.0 : amount;
this.accounts[accountKey] = amount;
}
public isAccountExist(currency: string): boolean {
const accountKey = `${Account.ACCOUNT_PREFIX}_${currency}`;
return accountKey in this.accounts;
}
public isFundSufficient(amount: number, currency: string): boolean {
const accountKey = `${Account.ACCOUNT_PREFIX}_${currency}`;
return this.accounts[accountKey] > amount;
}
}
|
cdbe5672bc9e5bb8aa343229610075aa860f8033
|
TypeScript
|
Gidaio/food-tracker-gui
|
/src/createIngredientComponent.ts
| 3.15625
| 3
|
import { element } from "./app.js"
import { Component } from "./component.js"
interface CreateIngredientRequest {
amount: number
unit: string
}
export class CreateIngredientComponent extends Component {
protected buildTemplate(): HTMLElement {
const template = element([
"form", undefined,
element(["input", { id: "ingredient-name", type: "text", placeholder: "Ingredient Name" }]),
element(["br"]),
element(["input", { id: "ingredient-amount", type: "number" }]),
element(["br"]),
element([
"select", { id: "ingredient-unit" },
element(["option", { value: "cup" }, "cup"]),
element(["option", { value: "fl oz" }, "fl oz"])
]),
element(["br"]),
element(["button", { type: "submit" }, "Create"])
])
template.addEventListener("submit", this.submitForm.bind(this))
return template
}
public submitForm(event: Event): void {
event.stopPropagation()
event.preventDefault()
const ingredientName = this.getElementByID("ingredient-name").value
const ingredientAmount = this.getElementByID("ingredient-amount").valueAsNumber
const ingredientUnit = this.getElementByID("ingredient-unit").value
this.createIngredient(ingredientName, ingredientAmount, ingredientUnit).then(() => {
console.log(`Created ingredient ${ingredientName}`)
}).catch((error) => {
console.log(error)
})
}
public async createIngredient(name: string, amount: number, unit: string): Promise<void> {
const encodedName = encodeURIComponent(name)
const endpoint = `/ingredients/${encodedName}`
return this.request<CreateIngredientRequest, void>("POST", endpoint, { amount, unit })
}
}
|
3ba774f80d62a6338e502ec672838ef4084cba47
|
TypeScript
|
JavCordero/frontendDGE
|
/reducers/authReducer.ts
| 3
| 3
|
import { AuthState } from "../context/AuthContext";
type AuthAction =
| { type: "signIn"; payload: string; id: string }
| { type: "signOut" }
| { type: "checkLogin"; payload: string };
export const authReducer = (
state: AuthState,
action: AuthAction
): AuthState => {
switch (action.type) {
case "signIn":
return { ...state, isLoggedIn: true, rol: action.payload, id: action.id };
case "signOut":
return { ...state, isLoggedIn: false, rol: undefined };
case "checkLogin":
return { ...state, isLoggedIn: true, rol: action.payload };
default:
return state;
}
};
|
a446edbbe4b5eb2722d2df5aae024b06d63220b7
|
TypeScript
|
denyskorolkov/typescript-samples
|
/src/missing.ts
| 4.4375
| 4
|
/**
* Takes an unsorted array of unique numbers (ie. no repeats) from 1 through some number n,
* and returns the missing number in the sequence
* (there are either no missing numbers, or exactly one missing number).
*
* @example
* missing([]) // undefined
* missing([1, 4, 3]) // 2
* missing([2, 3, 4]) // 1
* missing([5, 1, 4, 2]) // 3
* missing([1, 2, 3, 4]) // undefined
*
* @export
* @template T
* @param {Array<number>} arr Unsorted array of unique numbers (ie. no repeats)
* @returns {number} The missing number in the sequence
*/
export function missing(arr: Array<number>): number | undefined {
let full: number = 1;
let partly: number = 1;
let i: number = 0;
while (i < arr.length) {
partly *= arr[i];
full *= ++i;
}
if (full === partly) {
return;
}
return full * (arr.length + 1) / partly;
}
|
d394ac3052b24cefa71cd3fc6160f9ecf2ccef1c
|
TypeScript
|
acburdine/denali-cli
|
/lib/builder.ts
| 2.78125
| 3
|
import {
upperFirst
} from 'lodash';
import * as fs from 'fs';
import * as path from 'path';
import * as Funnel from 'broccoli-funnel';
import * as MergeTree from 'broccoli-merge-trees';
import PackageTree from './package-tree';
import Project from './project';
import * as createDebug from 'debug';
import findPlugins, { PluginSummary } from 'find-plugins';
const debug = createDebug('denali-cli:builder');
// Because it's nice to have a named type for this
// tslint:disable-next-line:no-empty-interface
export interface Tree {}
/**
* The Builder class is responsible for taking a Denali package (an app or an addon), and performing
* any build steps necessary to produce the final, compiled output. Often times this includes
* transpiling, precompiling template files, etc. The base Builder class also performs some basic
* copying of package files (package.json, Readme, etc).
*
* Projects can define their own Builder in `/denali-build.js`, which can customize how the package
* is built via the `processSelf` hook. Addon Builders can also contribute to their parent package's
* build via the processParent() hook, allowing for purely build-related addons like denali-babel or
* denali-typescript
*
* @export
* @class Builder
* @module denali-cli
*/
export default class Builder {
[key: string]: any;
/**
* An internal cache that maps real disk locations to Builder instances. This lets us accurately
* model the deeply nested and even circular dependencies of an app's addon graph, but take
* advantage of npm/yarn flattening by only using one Builder instance per disk location.
*/
public static buildersCache: { [dir: string]: Builder } = {};
/**
* A factory method that checks for a local Builder class in `/denali-build.js`, and instantiates
* that if present.
*/
public static createFor(dir: string, project: Project, preseededAddons?: string[]): Builder {
if (!this.buildersCache[dir]) {
// Use the local denali-build.js if present
let denaliBuildPath = path.join(dir, 'denali-build');
if (fs.existsSync(`${ denaliBuildPath }.js`)) {
let LocalBuilder = require(denaliBuildPath);
LocalBuilder = LocalBuilder.default || LocalBuilder;
this.buildersCache[dir] = new LocalBuilder(dir, project, preseededAddons);
} else {
this.buildersCache[dir] = new this(dir, project, preseededAddons);
}
}
return this.buildersCache[dir];
}
/**
* Denali automatically checks the Node Security Project for any vulnerabilities in your app's
* dependencies. Sometimes it will pick up vulnerabilities that you want to ignore, i.e. a
* vulnerability in a package that is only used at build time.
*
* This array defines a blacklist of vulnerabilities to ignore. Each entry is an array that
* describes the path through the dependency graph. Any vulnerabilities from that point and
* farther down the graph will be ignored.
*
* So for example, if your dependencies include:
*
* foo@1.2.3
* bar@4.5.6
* buzz@7.8.9
*
* Then adding `[ 'foo', 'bar@~4.2.1' ]` would ignore any vulnerabilities from the "bar" package
* (as long as the version of "bar" satisfied "~4.2.1"), as well as any vulnerabilities from
* "buzz"
*/
public ignoreVulnerabilities: string[][] = [
[ 'broccoli@*' ],
[ 'jscodeshift@*' ]
];
/**
* A list of files that should be copied as-is into the final build
*/
public packageFiles: string[] = [
'package.json',
'README.md',
'CHANGELOG.md',
'LICENSE',
'denali-build.js',
'yarn.lock'
];
/**
* A list of directories that should be copied as-is into the final build
*/
public packageDirs: string[] = [];
/**
* The directory containing the package that should be built.
*/
public dir: string;
/**
* The package.json for this package
*/
public pkg: any;
/**
* The Project instance that represents the root package being built
*/
public project: Project;
/**
* A list of directories containing addons that are children to this package
*/
public addons: PluginSummary[];
/**
* An array of builder instances for child addons of this package
*/
public childBuilders: Builder[];
/**
* If true, when the root Project is built, it will create a child Project for this package,
* which will watch for changes and trigger a rebuild of this package as well as the root Project.
*
* Warning: experimental and highly unstable
*/
public isDevelopingAddon = false;
/**
* Modify the build of the parent package that is consuming this addon.
*
* @param tree the tree representing the parent package
* @param dir the absolute path to the parent package source
*/
public processParent: (tree: Tree, dir: string) => Tree;
/**
* Modify this package's build
*
* @param tree the tree representing the package
* @param dir the absolute path to the package source
*/
public processSelf: (tree: Tree, dir: string) => Tree;
/**
* Creates an instance of Builder for the given directory, as a child of the given Project. If
* preseededAddons are supplied, they will be included as child addons of this Builder instance.
*/
constructor(dir: string, project: Project, preseededAddons?: string[]) {
debug(`creating builder for ./${ path.relative(project.dir, dir) }`);
this.dir = dir;
this.pkg = require(path.join(this.dir, 'package.json'));
this.project = project;
this.addons = findPlugins({
dir: this.dir,
keyword: 'denali-addon',
sort: true,
includeDev: true,
configName: 'denali',
include: preseededAddons
});
}
/**
* Return a single broccoli tree that represents the completed build output for this package
*/
public toTree(): Tree {
let tree = this._prepareSelf();
// Find child addons
this.childBuilders = this.addons.map((addon) => Builder.createFor(addon.dir, this.project));
// Run processParent hooks
this.childBuilders.forEach((builder) => {
if (builder.processParent) {
tree = builder.processParent(tree, this.dir);
}
});
// Run processSelf hooks
if (this.processSelf) {
tree = this.processSelf(tree, this.dir);
}
let unbuiltTrees: Tree[] = [];
this.packageDirs.forEach((dir) => {
if (fs.existsSync(path.join(this.dir, dir))) {
unbuiltTrees.push(new Funnel(path.join(this.dir, dir), { destDir: dir }));
}
});
if (unbuiltTrees.length > 0) {
tree = new MergeTree(unbuiltTrees.concat(tree), { overwrite: true });
}
return tree;
}
/**
* Returns an array of top-level directories within this package that should go through the build
* process. Note that top-level files cannot be built. You can include them (unbuilt) in the final
* output via the `packageFiles` property; see https://github.com/broccolijs/broccoli/issues/173#issuecomment-47584836
*/
public sourceDirs(): string[] {
let dirs = [ 'app', 'blueprints', 'commands', 'config', 'lib' ];
if (this.project.environment === 'test') {
dirs.push('test');
}
return dirs;
}
/**
* Generic treeFor method that simply returns the supplied directory as is. You could override
* this to customize the build process for all files.
*/
public treeFor(dir: string): string | Tree {
return dir;
}
/**
* Compiles the base build tree which will be passed to the user-defined build hooks. Grabs all
* the top-level directories to be built, runs the treeFor hooks on each, adds package files
*/
private _prepareSelf(): Tree {
// Get the various source dirs we'll use. This is important because broccoli
// cannot pick files at the root of the project directory.
let dirs = this.sourceDirs();
// Give any subclasses a chance to override the source directories by defining
// a treeFor* method
let sourceTrees = dirs.map((dir) => {
let treeFor = this[`treeFor${ upperFirst(dir) }`] || this.treeFor;
let tree = treeFor.call(this, path.join(this.dir, dir));
if (typeof tree !== 'string' || fs.existsSync(tree)) {
return new Funnel(tree, { annotation: dir, destDir: dir });
}
return false;
}).filter(Boolean);
// Copy top level files into our build output (this special tree is
// necessary because broccoli can't pick a file from the root dir).
sourceTrees.push(new PackageTree(this, { files: this.packageFiles }));
// Combine everything into our unified source tree, ready for building
return new MergeTree(sourceTrees, { overwrite: true });
}
}
|
f26cef2def8100b0229f7c5d3fc01e312c612b4d
|
TypeScript
|
cslogan-red/free_weather_project
|
/functions/src/WeatherService.ts
| 2.796875
| 3
|
import * as request from 'request-promise-native';
/**
* @abstract Weather API service handling weather provider requests
*
* @author Chase
*/
export default class WeatherService {
// lookup local weather information based on lat & lng
_getWeatherResultAsync = async (lat, lng) => {
const WEATHER_API_PREFIX = 'https://api.darksky.net/forecast/<YOUR_API_KEY_HERE>',
WEATHER_API_SUFFIX = '?exclude=minutely',
URI = WEATHER_API_PREFIX + lat + ',' + lng + WEATHER_API_SUFFIX,
OPTIONS = { uri : URI, json : true },
EXP_PREFIX = ':::WeatherService._getWeatherResultAsync(), exception message: ';
const retObj = { currently : {}, daily : [], hourly : [], alerts : [] };
try {
const TEMP_UNIT = 'F',
RESOLVE = await request.get(OPTIONS);
// build currently
retObj.currently = {
temp : Math.round(RESOLVE.currently.temperature) + TEMP_UNIT,
feelsLikeTemp : Math.round(RESOLVE.currently.apparentTemperature) + TEMP_UNIT,
icon : RESOLVE.currently.icon,
summary : RESOLVE.currently.summary,
humidity : Math.round(RESOLVE.currently.humidity * 100),
windSpeed : Math.round(RESOLVE.currently.windGust),
sunriseTime : RESOLVE.daily.data ? RESOLVE.daily.data[0].sunriseTime : '',
sunsetTime : RESOLVE.daily.data ? RESOLVE.daily.data[0].sunsetTime : '',
timezone : RESOLVE.timezone
};
// build daily
RESOLVE.daily.data.map((item) => {
const day = {
...item,
date : item.time,
tempHigh : Math.round(item.temperatureHigh) + TEMP_UNIT,
tempLow : Math.round(item.temperatureLow) + TEMP_UNIT,
};
retObj.daily.push(day);
});
// build hourly
RESOLVE.hourly.data.map((item) => {
const hour = {
temp : Math.round(item.temperature) + TEMP_UNIT,
time : item.time,
icon : item.icon,
precip : Math.round(item.precipProbability * 100)
};
retObj.hourly.push(hour);
});
// build alerts, if present
if (RESOLVE.alerts) {
RESOLVE.alerts.map((item) => {
const alert = { ...item, dateIssued: item.time };
retObj.alerts.push(alert);
});
}
} catch (e) {
// log it on server side debug console
console.log(EXP_PREFIX + e);
}
return retObj;
};
}
|
73fcc6eae9e0a5757fa7ffabcac5ae2cecd99b9a
|
TypeScript
|
FullScreenShenanigans/SpriteMakr-Neue
|
/Source/References/RequireAll.d.ts
| 2.84375
| 3
|
/// <reference path="require.d.ts" />
/// <reference path="RequireAll.ts" />
declare module RequireAll {
/**
* Optional settings for loading a file.
*/
export interface IRequireSettings {
/**
* The name of the file to load (by default, the path).
*/
alias?: string;
/**
* The full path to the file.
*/
path: string;
/**
* Any additional files to load before this one.
*/
requires?: string[];
}
/**
* Summary of requirement information and load status for a file.
*/
export interface IRequirement {
/**
* How to identify the file (by default, the path).
*/
alias: string;
/**
* The full path to the file.
*/
path: string;
/**
* Any additional files to load before this one.
*/
requires: IRequirements;
/**
* Loading status for the file.
*/
status: Status;
}
/**
* Requirements, keyed by alias.
*/
export interface IRequirements {
[i: string]: IRequirement;
}
/**
* A handler callback for when loading completes.
*
* @param requirement The loaded (or errored) requirement.
*/
export interface ICallback {
(requirement: IRequirement): void;
}
}
|
7abe51c54c6200dbe9f258678a6008ccbae1a83d
|
TypeScript
|
xujif/node_mmap_mio
|
/typing.d.ts
| 3.03125
| 3
|
export declare class MappedFile {
/**
* Creates an instance of MappedFile.
* @param {(string | number)} path_or_fd
* @param {number} [offset]
* @param {number} [size_to_map]
* @memberof MappedFile
*/
constructor(path_or_fd: string | number, offset?: number, size_to_map?: number);
readonly writable: boolean
/**
* mapped length
*
* @type {number}
* @memberof MappedFile
*/
readonly length: number
readonly offset: number
/**
* get the buffer of mapped data
*
* @param {number} [offset]
* @param {number} [length]
* @returns {Buffer}
* @memberof MappedFile
*/
buffer(offset?: number, length?: number): Buffer
/**
* mapped length
*
* @returns {number}
* @memberof MappedFile
*/
size(): number
isMapped(): boolean
unmap(): void
sync(): void
}
export declare class ReadOnlyMappedFile extends MappedFile { }
/**
* Creates an instance of MappedFile.
*
* @export
* @param {(string | number)} path_or_fd
* @param {number} [offset]
* @param {number} [size_to_map]
* @returns {MappedFile}
*/
export declare function mmap(path_or_fd: string | number, offset?: number, size_to_map?: number): MappedFile
/**
* Creates an instance of ReadOnlyMappedFile.
*
* @export
* @param {(string | number)} path_or_fd
* @param {number} [offset]
* @param {number} [size_to_map]
* @returns {ReadOnlyMappedFile}
*/
export declare function mmap_ro(path_or_fd: string | number, offset?: number, size_to_map?: number): ReadOnlyMappedFile
export default mmap
|
ecbe4901e6772bb3c977bfbc513be25c5a1c0388
|
TypeScript
|
charlyee/typescript-tutorials
|
/7 - Code From Video/video7/classExport.ts
| 3.375
| 3
|
//Generally speaking: One class should be in one file.
//(Yes nested classes are a thing, but that's for later!!!)
export class Square {
//Properties
private width: number;
private height: number;
//Constructor
public constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
//Methods
getWidth(): number {
return this.width;
}
getHeight(): number {
return this.height;
}
getArea(): number {
return this.height * this.width;
}
};
|
938d7036b092d53659a5324219e549c7dba458be
|
TypeScript
|
rajhub/algo-ds
|
/src/bits/BitMan.ts
| 3.6875
| 4
|
export class BitMan {
public static invertBits(num: number) {
let bitCount = Math.trunc(Math.log2(num)) + 1;
for (let i = 0; i < bitCount; i++) {
num = num ^ (1 << i);
}
return num;
}
public static printBits(num: number) {
let bitString: string = '';
while(num) {
bitString = (num & 1) + bitString;
num = num >> 1;
}
return bitString;
}
public static test() {
// console.log(BitMan.printBits(3));
console.log(BitMan.printBits(BitMan.invertBits(5)));
}
}
|
4bc79a51310a672212efde9095fc2284ff192117
|
TypeScript
|
ildede/toss-the-toast
|
/src/ext/OutlinePipeline.ts
| 2.5625
| 3
|
export default class OutlinePipeline extends Phaser.Renderer.WebGL.Pipelines.TextureTintPipeline {
// the unique id of this pipeline
public static readonly KEY = 'Outline';
/**
* @param {Phaser.Game} game - the controller of the game instance
*/
constructor(game: Phaser.Game) {
super({
game: game,
renderer: game.renderer,
fragShader: `
precision mediump float;
uniform sampler2D uMainSampler;
uniform vec2 uTextureSize;
varying vec2 outTexCoord;
varying float outTintEffect;
varying vec4 outTint;
void main(void)
{
vec4 texture = texture2D(uMainSampler, outTexCoord);
vec4 texel = vec4(outTint.rgb * outTint.a, outTint.a);
vec4 color = texture;
if (outTintEffect == 0.0)
{
color = texture * texel;
}
else if (outTintEffect == 1.0)
{
color.rgb = mix(texture.rgb, outTint.rgb * outTint.a, texture.a);
color.a = texture.a * texel.a;
}
else if (outTintEffect == 2.0)
{
color = texel;
}
vec2 onePixel = vec2(1.2, 1.2) / uTextureSize;
float upAlpha = texture2D(uMainSampler, outTexCoord + vec2(0.0, onePixel.y)).a;
float leftAlpha = texture2D(uMainSampler, outTexCoord + vec2(-onePixel.x, 0.0)).a;
float downAlpha = texture2D(uMainSampler, outTexCoord + vec2(0.0, -onePixel.y)).a;
float rightAlpha = texture2D(uMainSampler, outTexCoord + vec2(onePixel.x, 0.0)).a;
if (texture.a == 0.0 && max(max(upAlpha, downAlpha), max(leftAlpha, rightAlpha)) == 1.0)
{
color = vec4(1.0, 0.0, 0.0, 1.0);
}
gl_FragColor = color;
}
`
});
}
}
|
1ef37dd45fa990184b0362ccf43e5292731019af
|
TypeScript
|
WuertzMariia/SocialNetwork-Typescript-React-Redux
|
/src/redux/profileReducer.test.ts
| 2.609375
| 3
|
import profileReducer, {actions} from './profileReducer';
it('new post should be added', () => {
// 1. test data
let action = actions.actioncreatorAddPost('new post');
let state = {
posts: [
{post: 'Hello', id: 1},
{post: 'how are you', id: 2},
{post: 'i am fine', id: 3},
{post: 'i am fine', id: 3},
{post: 'i am fine', id: 4},
{post: 'i am fine', id: 4},
{post: 'i am fine', id: 5}
],
profile: null,
isFetching: false,
status: 'My dream is to become a good Frontend Developer'
}
// 2. action
let newState = profileReducer(state, action);
// 3. expectation
expect(newState.posts.length).toBe(8);
})
it('to delete', () => {
let action = actions.deletePost(1);
let state = {
posts: [
{post: 'Hello', id: 1},
{post: 'how are you', id: 2},
{post: 'i am fine', id: 3},
{post: 'i am fine', id: 3},
{post: 'i am fine', id: 4},
{post: 'i am fine', id: 4},
{post: 'i am fine', id: 5}
],
profile: null,
isFetching: false,
status: 'My dream is to become a good Frontend Developer'
}
let newState = profileReducer(state, action);
expect(newState.posts.length).toBe(6);
})
|
ae1062c976ac0928810a381041c0c55cf4bd5a68
|
TypeScript
|
jstarry/solana
|
/explorer/src/utils/program-logs.ts
| 2.59375
| 3
|
import { TransactionError } from "@solana/web3.js";
import { Cluster } from "providers/cluster";
import { programLabel } from "utils/tx";
import { getTransactionInstructionError } from "utils/program-err";
export type LogMessage = {
text: string;
prefix: string;
style: "muted" | "info" | "success" | "warning";
};
export type InstructionLogs = {
logs: LogMessage[];
failed: boolean;
};
export function prettyProgramLogs(
logs: string[],
error: TransactionError | null,
cluster: Cluster
): InstructionLogs[] {
let depth = 0;
let prettyLogs: InstructionLogs[] = [];
const prefixBuilder = (depth: number) => {
const prefix = new Array(depth - 1).fill("\u00A0\u00A0").join("");
return prefix + "> ";
};
let prettyError;
if (error) {
prettyError = getTransactionInstructionError(error);
}
logs.forEach((log) => {
if (log.startsWith("Program log:")) {
prettyLogs[prettyLogs.length - 1].logs.push({
prefix: prefixBuilder(depth),
text: log,
style: "muted",
});
} else {
const regex = /Program (\w*) invoke \[(\d)\]/g;
const matches = [...log.matchAll(regex)];
if (matches.length > 0) {
const programAddress = matches[0][1];
const programName =
programLabel(programAddress, cluster) ||
`Unknown (${programAddress}) Program`;
if (depth === 0) {
prettyLogs.push({
logs: [],
failed: false,
});
} else {
prettyLogs[prettyLogs.length - 1].logs.push({
prefix: prefixBuilder(depth),
style: "info",
text: `Invoking ${programName}`,
});
}
depth++;
} else if (log.includes("success")) {
prettyLogs[prettyLogs.length - 1].logs.push({
prefix: prefixBuilder(depth),
style: "success",
text: `Program returned success`,
});
depth--;
} else if (log.includes("failed")) {
const instructionLog = prettyLogs[prettyLogs.length - 1];
if (!instructionLog.failed) {
instructionLog.failed = true;
instructionLog.logs.push({
prefix: prefixBuilder(depth),
style: "warning",
text: `Program returned error: ${log.slice(log.indexOf(": ") + 2)}`,
});
}
depth--;
} else {
if (depth === 0) {
prettyLogs.push({
logs: [],
failed: false,
});
depth++;
}
// system transactions don't start with "Program log:"
prettyLogs[prettyLogs.length - 1].logs.push({
prefix: prefixBuilder(depth),
text: log,
style: "muted",
});
}
}
});
// If the instruction's simulation returned an error without any logs then add an empty log entry for Runtime error
// For example BpfUpgradableLoader fails without returning any logs for Upgrade instruction with buffer that doesn't exist
if (prettyError && prettyLogs.length === 0) {
prettyLogs.push({
logs: [],
failed: true,
});
}
if (prettyError && prettyError.index === prettyLogs.length - 1) {
const failedIx = prettyLogs[prettyError.index];
failedIx.failed = true;
failedIx.logs.push({
prefix: prefixBuilder(1),
text: `Runtime error: ${prettyError.message}`,
style: "warning",
});
}
return prettyLogs;
}
|
a5f338245f2a9d8272dc47a3bd95d199fdf7a981
|
TypeScript
|
bluestone029/Canvas-Renderer
|
/src/shape/DrawTool.ts
| 2.921875
| 3
|
import { TranslateMatrix, Matrix } from '../math/matrix';
// 绘制工具
class DrawTool {
path: Path2D;
tPath: Path2D;
oX: number;
oY: number;
endX: number;
endY: number;
constructor() {}
init(path: Path2D, pin: Array<number>): DrawTool {
this.path = path;
this.oX = pin[0];
this.oY = pin[1];
this.endX = this.oX;
this.endY = this.oY;
this.tPath = new Path2D();
Matrix.set(
TranslateMatrix,
[[1, 0, this.oX],
[0, 1, this.oY]]
);
this.tPath.moveTo(0, 0);
return this;
}
// 直线
bee(path: Array<Array<number>>): DrawTool {
for(let i = 0; i < path.length; i ++) {
this.tPath.lineTo(path[i][0], path[i][1]);
}
this.endX = path[path.length - 1][0];
this.endY = path[path.length - 1][1];
return this;
}
// 贝塞尔曲线
bez(ctrlPoint1: Array<number>, ctrlPoint2: Array<number>, endPoint: Array<number>) {
this.tPath.moveTo(this.endX, this.endY);
this.tPath.bezierCurveTo(ctrlPoint1[0], ctrlPoint1[1], ctrlPoint2[0], ctrlPoint2[1], endPoint[0], endPoint[1]);
this.endX = endPoint[0]; this.endY = endPoint[1];
}
// 弧线
arc(radius: number, startDeg: number, endDeg: number, clockWise: boolean = true): DrawTool {
let xCenter: number, yCenter: number;
// 将弧的圆心进行位移,确保直线的末尾端点跟弧的开始端点可以衔接
xCenter = this.endX - radius*Math.cos((360 - startDeg)/180*Math.PI);
yCenter = this.endY + radius*Math.sin((360 - startDeg)/180*Math.PI);
this.tPath.arc(xCenter, yCenter, radius, (startDeg)/180*Math.PI, endDeg/180*Math.PI, clockWise);
// 将弧的圆心进行位移,确保弧的末尾端点和下一段直线的开端可以衔接
this.endX = xCenter - radius*Math.cos((360 - endDeg)/180*Math.PI);
this.endY = yCenter + radius*Math.sin((360 - endDeg)/180*Math.PI);
return this;
}
move(x: number, y: number) {
this.tPath.moveTo(x, y);
this.endX = x;
this.endY = y;
}
end(closePath: boolean = true) {
closePath && this.tPath.closePath();
this.path.addPath(this.tPath, TranslateMatrix);
Matrix.init(TranslateMatrix);
}
}
export const drawTool = new DrawTool();
|