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
|
|---|---|---|---|---|---|---|
518bb3748f7108b62322be86f0a88817e703858c
|
TypeScript
|
JaredBrown138/CROS
|
/src/app/components/messages/messages.component.ts
| 2.59375
| 3
|
import { Component, OnInit } from '@angular/core';
import { APIService } from '../../services/api.service';
import { MatSnackBar } from '@angular/material';
import * as moment from 'moment';
@Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
readMessages: any = [];
unreadMessages: any = [];
constructor(public api: APIService, public snackBar: MatSnackBar) {
this.getMessages();
}
ngOnInit() { }
/**
* Tells the serve a user has read a message and
* then adds the message to the read array in the
* front end.
* @param message
*/
read(message) {
if (message['read']) {
this.unreadMessages = this.unreadMessages.filter(msg => msg['id'] != message['id']);
this.readMessages.unshift(message);
} else {
this.api.markMessageRead({ id: message['id'] }).subscribe(
res => {
message['read'] = true;
},
err => {
console.log(err.error.message);
}
);
}
}
/**
* Retrieves messages using the api service
*/
getMessages() {
this.api.getMessages().subscribe(
res => {
this.readMessages = res.filter(msg => msg['read'] == true);
this.readMessages.reverse();
this.unreadMessages = res.filter(msg => msg['read'] == false);
},
err => {
this.snackBar.open(err.error['message'], '', {
panelClass: ['bad', 'snack'],
duration: 5000
});
}
);
}
/**
* Helper function which formats the date.
* @param date
*/
dateClean(date) {
return moment(date).fromNow();
}
}
|
78f5d674bb6125c6e04fb026bed740970a687df4
|
TypeScript
|
n8rzz/othello
|
/src/public/script/gameBoard/GameBoardController.ts
| 2.859375
| 3
|
import { positionToIdTranslator } from '../translator/stageCellTranslators';
import { VECTOR_FROM_POSITION } from '../constants/gameBoardConstants';
import { PLAYER } from '../constants/playerConstants';
class GameBoardController {
public gameBoard: number[][] = [];
public capturedPieces: number[][] = [];
private _vectorsToOpponentCache: number[][] = [];
constructor() {
this.gameBoard = this._buildGameBoardInitialState();
}
public collectAvailableMovesForPlayer(player: PLAYER): number[][] {
const availableMoveList: number[][] = [];
for (let i = 0; i < this.gameBoard.length; i++) {
for (let j = 0; j < this.gameBoard[i].length; j++) {
const position = [i, j];
if (this._getPlayerAtPosition(position) !== PLAYER.INVALID_PLAYER) {
continue;
}
if (this._isCapturablePosition(position, player)) {
availableMoveList.push(position);
}
}
}
return availableMoveList;
}
public collectPositionsAlongVectorUntilPlayer(vector: number[], position: number[], player: PLAYER, sum: number[][]): number[][] {
const comparisonPosition: number[] = this._calculateComparisonPositionFromPositionWithVector(position, vector);
const comparisonPlayer: PLAYER = this._getPlayerAtPosition(comparisonPosition);
if (!this.isValidPosition(comparisonPosition)) {
return [];
}
if (comparisonPlayer === this._getOpposingPlayerNumber(player)) {
sum.push(comparisonPosition);
return this.collectPositionsAlongVectorUntilPlayer(vector, comparisonPosition, player, sum);
} else if (comparisonPlayer === PLAYER.INVALID_PLAYER) {
return [];
}
return sum;
}
public countPiecesForPlayer(player: PLAYER): number {
let sum = 0;
for (let i = 0; i < this.gameBoard.length; i++) {
for (let j = 0; j < this.gameBoard[i].length; j++) {
const position = [i, j];
if (this._getPlayerAtPosition(position) !== player) {
continue;
}
sum++;
}
}
return sum;
}
public doesCaptureOpposingPlayerPiece(position: number[], player: PLAYER): boolean {
this._vectorsToOpponentCache = this.findVectorsToOpposingPlayerPiece(position, player);
if (this._vectorsToOpponentCache.length === 0) {
return false;
}
for (let i = 0; i < this._vectorsToOpponentCache.length; i++) {
const vector = this._vectorsToOpponentCache[i];
// returns true on the first capture formation, there may be several
if (this.isCapturePieceAlongVector(vector, position, player)) {
return true;
}
}
return false;
}
public findVectorsToOpposingPlayerPiece(position: number[], player: PLAYER): number[][] {
const foundVectors: any[] = [];
for (let i = 0; i < VECTOR_FROM_POSITION.length; i++) {
const vector: number[] = VECTOR_FROM_POSITION[i];
const comparePosition: number[] = this._calculateComparisonPositionFromPositionWithVector(position, vector);
const comparePlayer: PLAYER = this._getPlayerAtPosition(comparePosition);
if (comparePlayer === player || comparePlayer === PLAYER.INVALID_PLAYER) {
continue;
}
foundVectors.push(vector);
}
return foundVectors;
}
public playerCanMoveToPosition(position: number[], player: PLAYER): boolean {
return this.isLegalMove(position) && this.doesCaptureOpposingPlayerPiece(position, player);
}
// TODO: split this up
public isCapturePieceAlongVector(vector: number[], position: number[], player: PLAYER): boolean {
const comparisonPosition: number[] = this._calculateComparisonPositionFromPositionWithVector(position, vector);
const comparisonPlayer: PLAYER = this._getPlayerAtPosition(comparisonPosition);
if (!this.isValidPosition(comparisonPosition)) {
return false;
}
if (comparisonPlayer === this._getOpposingPlayerNumber(player)) {
return this.isCapturePieceAlongVector(vector, comparisonPosition, player);
}
return comparisonPlayer === player;
}
public isGameComplete(): boolean {
let sum: number = 0;
const pieceCount: number = this.gameBoard.length * this.gameBoard[0].length;
for (let i = 0; i < this.gameBoard.length; i++) {
for (let j = 0; j < this.gameBoard[0].length; j++) {
const position: number[] = [i, j];
const playerAtPosition: PLAYER = this._getPlayerAtPosition(position);
if (playerAtPosition !== PLAYER.INVALID_PLAYER) {
continue;
}
sum++;
}
}
return sum <= 1;
}
public isLegalMove(position: number[]): boolean {
return this._getPlayerAtPosition(position) === PLAYER.INVALID_PLAYER;
}
public isValidPosition(position: number[]): boolean {
return position[0] >= 0 &&
position[0] < this.gameBoard.length &&
position[1] >= 0 &&
position[1] < this.gameBoard[0].length;
}
public reset(): void {
this.gameBoard = this._buildGameBoardInitialState();
}
public resetCacheAfterTurn(): void {
this._vectorsToOpponentCache = [];
this.capturedPieces = [];
}
public updatePlayerAtPosition(player: PLAYER, position: number[]): void {
this.gameBoard[position[0]][position[1]] = player;
}
public updateGameBoardStateForPendingMove(player: PLAYER, position: number[]): void {
let capturedPieces: number[][] = [];
for (let i = 0; i < this._vectorsToOpponentCache.length; i++) {
const vector: number[] = this._vectorsToOpponentCache[i];
const positionsAlongVectorToPlayer: number[][] = this.collectPositionsAlongVectorUntilPlayer(vector, position, player, []);
capturedPieces = capturedPieces.concat(positionsAlongVectorToPlayer);
}
this._updateGameBoardWithCapturedPieces(player, capturedPieces);
}
private _buildGameBoardInitialState(): number[][] {
return [
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.ONE, PLAYER.TWO, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.TWO, PLAYER.ONE, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
[PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER, PLAYER.INVALID_PLAYER],
];
}
private _calculateComparisonPositionFromPositionWithVector(position: number[], vector: number[]): number[] {
return [
position[0] + vector[0],
position[1] + vector[1],
];
}
private _getPlayerAtPosition(position: number[]): PLAYER {
if (!this.isValidPosition(position)) {
return PLAYER.INVALID_PLAYER;
}
return this.gameBoard[position[0]][position[1]];
}
private _getOpposingPlayerNumber(currentPlayer: PLAYER): PLAYER {
const opposingPlayer: PLAYER = currentPlayer === PLAYER.ONE
? PLAYER.TWO
: PLAYER.ONE;
if (currentPlayer === PLAYER.INVALID_PLAYER) {
return PLAYER.INVALID_PLAYER;
}
return opposingPlayer;
}
private _isCapturablePosition(position: number[], player: PLAYER): boolean {
const availableMoveList: number[][] = [];
for (let v = 0; v < VECTOR_FROM_POSITION.length; v++) {
const vector = VECTOR_FROM_POSITION[v];
const foundPositionsForVector: number[][] = this.collectPositionsAlongVectorUntilPlayer(vector, position, player, []);
if (foundPositionsForVector.length === 0) {
continue;
}
return true;
}
}
private _updateGameBoardWithCapturedPieces(player: PLAYER, capturedPieces: number[][]): void {
this.capturedPieces = capturedPieces;
for (let i = 0; i < capturedPieces.length; i++) {
const position: number[] = capturedPieces[i];
this.updatePlayerAtPosition(player, position);
}
}
}
export default GameBoardController;
|
b6ae93be9234eaf15b2790efab95dda16d3ef7f6
|
TypeScript
|
raghav-kukreti/myBlog
|
/old/lib/routes/crm_routes.ts
| 2.515625
| 3
|
import {Request, Response} from "express";
import {ContactController} from "../controllers/crm_controller";
export class Routes {
public contactController : ContactController = new ContactController();
public routes(app): void {
app.route('/').get((req: Request, res: Response) => res.json({name : "hello, check check 123"}));
app.route('/contact').get((req: Request, res: Response) => this.contactController.get_contacts);
app.route('/contact').post((req: Request, res: Response) => this.contactController.add_contact);
app.route('/contact/:contactId')
.get(this.contactController.get_contact_id)
.put(this.contactController.updateContact)
.delete(this.contactController.deleteContact)
}
}
|
181d5aaeda42ba160f76c1974aa3f5e06f9a6ca5
|
TypeScript
|
Reggino/adventofcode
|
/src/2020/06/index.ts
| 2.796875
| 3
|
import { readFileSync } from "fs";
import { join } from "path";
const groupsLines = readFileSync(join(__dirname, "./input.txt"), {
encoding: "utf-8"
})
.trim()
.split("\n\n");
console.log(
groupsLines
.map(groupLines =>
groupLines
.trim()
.split("\n")
.reduce<{ [answer: string]: true }>(
(groupPrev, personLine) =>
personLine.split("").reduce((personPrev, personAnswer) => {
groupPrev[personAnswer] = true;
return groupPrev;
}, groupPrev),
{}
)
)
.reduce((prev, groupAnswers) => prev + Object.keys(groupAnswers).length, 0)
);
console.log(
groupsLines
.map(groupLines => {
const personLines = groupLines.trim().split("\n");
const answers = personLines.reduce<{ [answer: string]: number }>(
(groupPrev, personLine) =>
personLine.split("").reduce((personPrev, personAnswer) => {
groupPrev[personAnswer] = (groupPrev[personAnswer] || 0) + 1;
return groupPrev;
}, groupPrev),
{}
);
return Object.keys(answers).filter(
answer => answers[answer] === personLines.length
).length;
})
.reduce((prev, answerCount) => prev + answerCount, 0)
);
|
6228cf7fe52aad27d1ca73bebf62041ce8f31778
|
TypeScript
|
teves-castro/ddd-ts
|
/classes.ts
| 3.390625
| 3
|
import { Either, right, left } from "fp-ts/lib/Either"
import { match, match2 } from "./functions"
// --------- Implementation ---------- //
export abstract class Tagged {
protected readonly tag = "Tagged"
}
export class UnvalidatedWidgetCode extends Tagged {
public readonly kind = "UnvalidatedWidgetCode"
private constructor(public readonly code: string) {
super()
}
public static create = (code: string): UnvalidatedWidgetCode => new UnvalidatedWidgetCode(code)
}
export class ValidatedWidgetCode extends Tagged {
public readonly kind = "ValidatedWidgetCode"
private constructor(public readonly code: string, public readonly type: number) {
super()
}
public static create = (code: string, type: number): Either<string, ValidatedWidgetCode> =>
/W-.+/i.test(code)
? right<never, ValidatedWidgetCode>(new ValidatedWidgetCode(code, type))
: left<string, never>("Invalid product code")
}
export type WidgetCode = UnvalidatedWidgetCode | ValidatedWidgetCode
export type ValidateWidget = (w: UnvalidatedWidgetCode) => Either<string, ValidatedWidgetCode>
export const validateWidget: ValidateWidget = code => ValidatedWidgetCode.create(code.code, 5)
// --------- Usage ---------- //
const unvalidated = UnvalidatedWidgetCode.create("W-other")
const validated = validateWidget(unvalidated)
console.log(unvalidated)
validated.fold(console.log, console.log)
const code = unvalidated as WidgetCode
const result = match(code)({
ValidatedWidgetCode: 0,
UnvalidatedWidgetCode: 1,
})
console.log(result)
const validatedFake1: WidgetCode = {
kind: "ValidatedWidgetCode",
code: "XPTO",
type: 5,
}
const validatedFake2: WidgetCode = {
tag: "Tagged",
kind: "ValidatedWidgetCode",
code: "XPTO",
type: 5,
}
const result2 = match2(unvalidated as WidgetCode)({
ValidatedWidgetCode: c => c.kind === "ValidatedWidgetCode" && `${c.code}-${c.type}`,
UnvalidatedWidgetCode: ({ code }) => code,
})
console.log(result2)
|
1bbd02ad3760bab4cb44a3bf44737477fdd30a07
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/jsforce/api/chatter.d.ts
| 2.625
| 3
|
import { Connection, Callback } from '../connection';
import { Query } from '../query';
import { Stream } from 'stream';
interface BatchRequestParams extends RequestParams {
method: string;
url: string;
richInput?: string | undefined;
}
interface BatchRequestResult {
statusCode: string;
result: RequestResult;
}
interface BatchRequestResults {
hasError: boolean;
results: BatchRequestResult[];
}
interface RequestParams {
method: string;
url: string;
body?: string | undefined;
}
export class RequestResult {}
export class Request<T> implements PromiseLike<T> {
constructor(chatter: Chatter, params: RequestParams);
batchParams(): BatchRequestParams;
promise(): Promise<T>;
stream(): Stream;
then<TResult1, TResult2>(
onfulfilled?: ((value: T) => PromiseLike<TResult1> | TResult1) | null,
onrejected?: ((reason: any) => PromiseLike<TResult2> | TResult2) | null,
): Promise<TResult1 | TResult2>;
finally(onfinally?: () => void): Promise<T>;
thenCall(callback?: (err: Error, records: T) => void): Query<T>;
}
export class Resource<T> extends Request<T> {
constructor(chatter: Chatter, url: string, queryParams?: object);
create(data: object | string, callback?: Callback<T>): Request<T>;
del(callback?: Callback<T>): Request<T>;
delete(callback?: Callback<T>): Request<T>;
retrieve(callback?: Callback<T>): Request<T>;
update(data: object, callback?: Callback<T>): Request<T>;
}
export class Chatter {
constructor(conn: Connection);
batch(callback?: Callback<BatchRequestResults>): Promise<BatchRequestResults>;
request(params: RequestParams, callback?: Callback<Request<RequestResult>>): Request<RequestResult>;
resource(url: string, queryParams?: object): Resource<RequestResult>;
}
|
916f93274cd8f32e8abe6b01b51b1be17f5820b9
|
TypeScript
|
reichert621/transcribe
|
/server/db/models/recording.ts
| 2.65625
| 3
|
import { first, last } from 'lodash';
import knex from '../knex';
import M from './types';
type RecordingParams = {
id?: number;
name?: string;
timestamp?: any;
transcription?: any;
userId?: number;
status?: 'IN_PROGRESS' | 'COMPLETED' | 'FAILED';
paid?: boolean;
};
const Recording = () => knex('recordings');
const fetch = (where: any = {}) => {
return Recording()
.select()
.where(where)
.orderBy('timestamp', 'desc');
};
const findOne = (where: any = {}) => {
return fetch(where).first();
};
const findById = (id: number, where: any = {}) => {
return findOne({ ...where, id });
};
const create = (params: RecordingParams) => {
return Recording()
.returning('id')
.insert(params)
.then(first)
.then((id: number) => findById(id));
};
const update = (id: number, params: RecordingParams) => {
return findById(id)
.update(params)
.then(count => count > 0)
.then(() => findById(id));
};
const findByName = (name: string, where: any = {}) => {
return findOne({ ...where, name });
};
const updateByName = (name: string, params: RecordingParams) => {
return findByName(name)
.update(params)
.then(count => count > 0)
.then(() => findByName(name));
};
const destroy = (id: number) => {
return findById(id).delete();
};
const calculateDuration = (recording: M.Recording) => {
if (!recording || !recording.transcription) {
return 0;
}
const { transcription } = recording;
const { textByTime } = transcription;
const times = textByTime
.map(({ endTime }) => Number(endTime))
.sort((a, b) => a - b);
return last(times);
};
export default {
fetch,
findById,
create,
update,
destroy,
findOne,
updateByName,
calculateDuration
};
|
f5b8183a69e5283b36d72012538bce150c5be718
|
TypeScript
|
goldylucks/payment-gateway
|
/src/services/declined-charges/declined-charges.ts
| 2.984375
| 3
|
export interface Declined {
[merchant: string]: { reason: string; count: number }[]
}
export interface AddDeclinedArgs {
merchant: string
reason: string
}
export default function makeDeclinedCharges() {
return (function declinedCharges() {
const declined = {} as Declined
return {
add,
getByMerchant,
}
function add({ merchant, reason }: AddDeclinedArgs) {
declined[merchant] = declined[merchant] || []
const reasonObj = declined[merchant].find(obj => obj.reason === reason)
if (reasonObj) {
reasonObj.count++
} else {
declined[merchant].push({ reason, count: 1 })
}
}
function getByMerchant(merchant: string) {
return declined[merchant]
}
})()
}
|
9069ab317eea51aa5b3210927103d4bdeb93c091
|
TypeScript
|
vrtnev/hometask7
|
/src/app/app.component.ts
| 2.734375
| 3
|
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from "@angular/forms";
interface MyUser {
name?: string;
surname?: string;
emails?: string[];
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm: FormGroup;
users: MyUser[] = [];
constructor() {
this.userForm = new FormGroup({
name: new FormControl(null, [Validators.required]),
surname: new FormControl(null, [Validators.required]),
emails: new FormArray([
new FormControl(null, [Validators.required])
])
});
}
onUserFormSubmit() {
this.users.push(this.userForm.value);
this.userForm.reset();
}
onAddEmail() {
(<FormArray>this.userForm.controls['emails']).push(new FormControl(null, [Validators.required]));
}
onDelEmail(index) {
(<FormArray>this.userForm.controls['emails']).removeAt(index);
}
}
|
e49944b68562ceec4cff352cef03e2de5764eb52
|
TypeScript
|
AYaki-coder/node-js-RS2021Q2
|
/src/resources/users/user.router.ts
| 2.53125
| 3
|
import { Router } from 'express';
import User from '../../entities/user';
import * as usersService from './user.service';
const router = Router();
router.route('/').get(async (_, res, next) => {
try {
const users = await usersService.getAll();
// map user fields to exclude secret fields like "password"
res.json(users.map(User.toResponse));
} catch (error) {
next(error);
}
});
router.route('/:id').get(async (req, res, next) => {
try {
const user = await usersService.get(req.params.id);
res.json(User.toResponse(user));
} catch (e) {
next(e);
}
});
router.route('/').post(async (req, res, next) => {
try {
const user = await usersService.create(req.body);
res.status(201).json(User.toResponse(user));
} catch (error) {
next(error);
}
});
router.route('/:id').put(async (req, res, next) => {
try {
const user = await usersService.update(req.params.id, req.body);
res.json(User.toResponse(user));
} catch (e) {
next(e);
}
});
router.route('/:id').delete(async (req, res, next) => {
try {
await usersService.remove(req.params.id);
res.status(204).send('The user has been deleted');
} catch (e) {
next(e);
}
});
export default router;
|
a34c5b8574b6d6d87c460c041a742bc6e43ed164
|
TypeScript
|
nivinjoseph/n-ject
|
/src/child-scope.ts
| 2.6875
| 3
|
import { BaseScope } from "./base-scope";
import { given } from "@nivinjoseph/n-defensive";
import { ScopeType } from "./scope-type";
import { ComponentRegistry } from "./component-registry";
import { Scope } from "./scope";
import { ObjectDisposedException } from "@nivinjoseph/n-exception";
// internal
export class ChildScope extends BaseScope
{
public constructor(componentRegistry: ComponentRegistry, parentScope: Scope)
{
given(componentRegistry, "componentRegistry").ensureHasValue().ensureIsType(ComponentRegistry);
given(parentScope, "parentScope").ensureHasValue().ensureIsObject();
super(ScopeType.Child, componentRegistry, parentScope);
this.bootstrap();
}
// cannot put this method in the base class due to circular reference issue
public createScope(): Scope
{
if (this.isDisposed)
throw new ObjectDisposedException(this);
given(this, "this").ensure(t => t.isBootstrapped, "not bootstrapped");
return new ChildScope(this.componentRegistry, this);
}
}
|
876306dc2eb0ad57a2c00b06abc26e8c3b948676
|
TypeScript
|
hellocustomer/HC.WebsiteSDK
|
/src/lib/core/utils/flatten-object.util.ts
| 3.390625
| 3
|
/**
* @ignore
*/
export function flattenObject<T>(
inputObject: T
): Record<string, string | number | boolean> {
if (!inputObject || typeof inputObject !== 'object') return {};
return Object.entries(inputObject).reduce((result, current) => {
const [key, value] = current;
let partialResult: Record<string, string>;
if (typeof value === 'object' && value != null)
partialResult = Object.entries(flattenObject(value)).reduce(
(total, current) => ({
...total,
[key +
(current[0].startsWith('[') ? '' : '.') +
current[0]]: current[1],
}),
{}
);
else partialResult = { [key]: value };
return {
...result,
...partialResult,
};
}, {});
}
|
3c07be89fd8f5f0966f3cee565418ffd1ea0bf15
|
TypeScript
|
donedgardo/tic-tac-toe
|
/packages/game-state/src/AiPlayer.ts
| 2.828125
| 3
|
import { Player } from './Player';
import { Board } from './Board';
import { PlayerMark } from './PlayerMark';
import {corners, get_random, oppositeCornerMap, weakPoints} from "./winningPlaysByPositionMap";
export class AiPlayer extends Player {
constructor(mark: PlayerMark) {
super(mark);
}
getPlayIndex(board: Board): number {
const randomCorner = this.getRandomAvailableCorner(board);
if (board.isEmpty() && randomCorner !== null) return randomCorner;
const nextWinningPlays = this.getNextWinningPlayIndexes(board);
if (nextWinningPlays.length > 0) return nextWinningPlays[0];
const myCrossWinningPlay = this.getCrossWinPlayForPlayer(board, this.mark);
if (myCrossWinningPlay !== null) return myCrossWinningPlay;
const opponentCrossWinningPlay = this.getCrossWinPlayForPlayer(board, this.getOpponentMark());
if (opponentCrossWinningPlay !== null) return this.getOpponentCrossPlayCounter(opponentCrossWinningPlay, board);
if(this.shouldPlayOppositeCorner(board)) {
const cornersTaken = board.getPlayerMarkIndexes(this.mark)
return oppositeCornerMap[cornersTaken[0]]
}
if (this.shouldPlayMiddle(board)) return 4;
const trapIndex = this.getTrap(board);
if (trapIndex !== null) return trapIndex;
return randomCorner || get_random(board.getEmptyIndexes());
}
getCornersAvailable(board: Board): number[] {
return corners.filter((i) => board.isBoardIndexEmpty(i));
}
getRandomAvailableCorner(board: Board): number | null {
const availableCorners = this.getCornersAvailable(board);
if (availableCorners.length === 0) return null;
const randomCorner = get_random(availableCorners);
return randomCorner;
}
private wentFirst(board: Board): boolean {
return board.getEmptyIndexes().length % 2 !== 0;
}
private getTrap(board: Board): number | null {
let trapIndex: number | null = null;
const availableCorners = this.getCornersAvailable(board);
availableCorners.forEach((corner) => {
if (trapIndex !== null) return;
const predictionBoard = new Board(board.getState());
predictionBoard.play(corner, this.mark);
let winningIndexes = this.getNextWinningPlayIndexes(predictionBoard);
if (winningIndexes.length === 0) return;
if (weakPoints.some((weakPoint) => winningIndexes.includes(weakPoint))) {
trapIndex = corner;
return;
}
});
return trapIndex;
}
getOpponentMark(): PlayerMark {
return this.mark === PlayerMark.X ? PlayerMark.O : PlayerMark.X;
}
getNextWinningPlayIndexes(board: Board): number[] {
const myNextWinningPlays = this.getNextWinningPlaysForPlayer(board, this.mark)
if (myNextWinningPlays.length > 0) return myNextWinningPlays;
const opponentNextWinningPlays = this.getNextWinningPlaysForPlayer(board, this.getOpponentMark())
return opponentNextWinningPlays
}
private getNextWinningPlaysForPlayer(board:Board, mark: PlayerMark): number[] {
return this.getPlayerWinningPlays(board, mark);
}
private shouldPlayMiddle(board: Board) {
return !this.wentFirst(board) && board.isBoardIndexEmpty(4);
}
private shouldPlayOppositeCorner(board: Board) {
return this.wentFirst(board) && board.getEmptyIndexes().length === 7 && !board.isBoardIndexEmpty(4);
}
private getPlayerWinningPlays(board: Board, mark: PlayerMark) {
let myNextWinningPlays: number[] = [];
const availablePlayIndexes = board.getEmptyIndexes();
availablePlayIndexes.forEach((boardIndex) => {
const myWinningPlay = board.isWinningIndexForPlayer(
mark,
boardIndex,
);
if (myWinningPlay) myNextWinningPlays.push(boardIndex);
});
return myNextWinningPlays
}
private getOpponentCrossPlayCounter(opponentCrossWinningPlay: number, board: Board): number {
const availablePlayIndexes = board.getEmptyIndexes();
let counterPlay: number | null = null;
availablePlayIndexes.filter(i=> i !== opponentCrossWinningPlay).some(possibleCounter => {
const predictionBoard = new Board(board.getState());
predictionBoard.play(possibleCounter, this.mark);
predictionBoard.play(opponentCrossWinningPlay, this.getOpponentMark());
const opponentWinningPlays = this.getNextWinningPlaysForPlayer(predictionBoard, this.getOpponentMark())
if(opponentWinningPlays.length < 2){
counterPlay = possibleCounter
return true
}
})
if(counterPlay !== null) return counterPlay;
return availablePlayIndexes[0]
}
private getCrossWinPlayForPlayer(board: Board, mark: PlayerMark): number | null {
let crossWinPlay: number | null = null;
const availablePlays = board.getEmptyIndexes();
availablePlays.forEach((play) => {
const predictionBoard = new Board(board.getState());
predictionBoard.play(play, mark);
const winningIndexes = this.getNextWinningPlaysForPlayer(predictionBoard, mark);
if (winningIndexes.length < 2) return;
crossWinPlay = play;
});
return crossWinPlay;
}
}
|
33806553f5c4eed6a79321aea71196fe59c941f2
|
TypeScript
|
MannimMond86/gaen-mobile-develop
|
/src/gaen/dataConverter.spec.ts
| 2.921875
| 3
|
import dayjs from "dayjs"
import { DateTimeUtils } from "../utils"
import { ExposureDatum } from "../exposure"
import { toExposureInfo, RawExposure } from "./dataConverters"
describe("toExposureInfo", () => {
describe("when there are no exposure notifications", () => {
it("returns an empty ExposureInfo", () => {
const rawExposures: RawExposure[] = []
const result = toExposureInfo(rawExposures)
expect(result).toEqual([])
})
})
describe("when there was a possible exposure two days ago", () => {
it("returns an ExposureInfo with a PossibleExposure at the correct date", () => {
const today = Date.now()
const twoDaysAgo = dayjs(today).subtract(2, "day").valueOf()
const duration = 30 * 60 * 1000
const rawExposures: RawExposure[] = [
{
id: "ABCD-EFGH",
date: twoDaysAgo,
duration,
},
]
const expected: ExposureDatum = {
date: DateTimeUtils.beginningOfDay(twoDaysAgo),
duration: duration,
id: "ABCD-EFGH",
}
const result = toExposureInfo(rawExposures)
expect(result.length).toEqual(1)
expect(result).toEqual([expected])
})
})
describe("when there are multiple raw exposures on the same day", () => {
it("combines the raw exposure into a single possible exposure with the sum of duration and max of risk", () => {
const today = Date.now()
const beginningOfDay = DateTimeUtils.beginningOfDay(today)
const duration1 = 30 * 60 * 1000
const duration2 = 10 * 60 * 1000
const duration3 = 25 * 60 * 1000
const rawExposures: RawExposure[] = [
{
id: "raw-exposure-1",
date: beginningOfDay + 1000,
duration: duration1,
},
{
id: "raw-exposure-2",
date: beginningOfDay + 18000,
duration: duration2,
},
{
id: "raw-exposure-3",
date: beginningOfDay + 36000,
duration: duration3,
},
]
const expected: ExposureDatum = {
date: DateTimeUtils.beginningOfDay(today),
duration: duration1 + duration2 + duration3,
id: "raw-exposure-1",
}
const result = toExposureInfo(rawExposures)
expect(result).toEqual([expected])
})
})
})
|
dc715a646093d0a629bf31125d474d216ad48f0a
|
TypeScript
|
minus9d/programming_contest_archive
|
/abc/105/b/b.ts
| 2.921875
| 3
|
declare var require: (x: string) => any;
function Main(input: string[]) {
const N = parseInt(input[0]);
let flag: boolean = false;
for (var a = 0; a <= N / 4; a++) {
if ((N - a * 4) % 7 == 0) {
flag = true;
}
}
if(flag) {
console.log('Yes')
} else {
console.log('No')
}
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));
|
ddf022a2b43cf9fc1449a8f6dcaa2e9234123438
|
TypeScript
|
original001/magicgame
|
/src/phisics.ts
| 2.59375
| 3
|
import {Creature} from './index'
import { onGround } from './collide';
import {Box, Vector} from 'sat'
const G = 9.8;
export const moveCreature = (
creature: Creature,
timeDelta,
{ x: speedX, y: speedY },
terrains
): Creature => {
const { speed, box } = creature;
const { x, y } = box.pos;
const isOnGround = onGround(creature.box, terrains.map(t => t.box));
const newSpeedX = speedX;
const newSpeedY = isOnGround ? speedY : speed.y + G;
const newCreature = {
...creature,
box: new Box(
new Vector(x + newSpeedX * timeDelta, y + newSpeedY * timeDelta),
box.w,
box.h
),
speed: new Vector(newSpeedX, newSpeedY)
};
return newCreature;
};
|
4c60e21feb883c2f4fa6bbd6e11408cdc77192f8
|
TypeScript
|
AkshatKumar-is-built-different/Car-Game
|
/main.ts
| 2.84375
| 3
|
input.onButtonPressed(Button.A, function () {
bird.change(LedSpriteProperty.Y, -1)
})
input.onButtonPressed(Button.B, function () {
bird.change(LedSpriteProperty.Y, 1)
})
input.onLogoEvent(TouchButtonEvent.Pressed, function () {
speed += -500
music.playTone(131, music.beat(BeatFraction.Quarter))
music.playTone(262, music.beat(BeatFraction.Quarter))
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(147, music.beat(BeatFraction.Quarter))
music.playTone(294, music.beat(BeatFraction.Quarter))
music.playTone(587, music.beat(BeatFraction.Quarter))
music.playTone(247, music.beat(BeatFraction.Quarter))
music.playTone(988, music.beat(BeatFraction.Quarter))
})
let emptyObstacleY = 0
let ticks = 0
let bird: game.LedSprite = null
music.setVolume(255)
music.setTempo(135)
music.playTone(494, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Quarter))
music.playTone(587, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Quarter))
music.playTone(988, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Quarter))
music.playTone(880, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Half))
music.playTone(740, music.beat(BeatFraction.Quarter))
let index = 0
let obstacles: game.LedSprite[] = []
bird = game.createSprite(0, 2)
bird.set(LedSpriteProperty.Blink, 300)
let speed = 1000
game.setScore(0)
game.setLife(1)
basic.forever(function () {
while (obstacles.length > 0 && obstacles[0].get(LedSpriteProperty.X) == 0) {
obstacles.removeAt(0).delete()
}
for (let obstacle2 of obstacles) {
obstacle2.change(LedSpriteProperty.X, -1)
}
if (ticks % 3 == 0) {
emptyObstacleY = randint(0, 4)
for (let index2 = 0; index2 <= 4; index2++) {
if (index2 != emptyObstacleY) {
obstacles.push(game.createSprite(4, index2))
}
}
}
for (let obstacle3 of obstacles) {
if (obstacle3.get(LedSpriteProperty.X) == bird.get(LedSpriteProperty.X) && obstacle3.get(LedSpriteProperty.Y) == bird.get(LedSpriteProperty.Y)) {
music.setVolume(255)
music.setTempo(160)
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(311, music.beat(BeatFraction.Quarter))
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(311, music.beat(BeatFraction.Eighth))
game.removeLife(1)
game.addScore(-1)
}
}
ticks += 1
basic.pause(speed)
})
loops.everyInterval(29999, function () {
music.rest(music.beat(BeatFraction.Breve))
game.addScore(10)
game.addLife(1)
music.playTone(262, music.beat(BeatFraction.Quarter))
music.rest(music.beat(BeatFraction.Half))
music.playTone(659, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Eighth))
music.playTone(523, music.beat(BeatFraction.Eighth))
music.rest(music.beat(BeatFraction.Quarter))
music.playTone(659, music.beat(BeatFraction.Eighth))
})
loops.everyInterval(5000, function () {
speed += -50
music.rest(music.beat(BeatFraction.Double))
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(587, music.beat(BeatFraction.Quarter))
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(659, music.beat(BeatFraction.Quarter))
music.playTone(523, music.beat(BeatFraction.Quarter))
music.playTone(698, music.beat(BeatFraction.Quarter))
})
|
845b1cbf030ddf3aa4fc9826b98c55874a8b3d35
|
TypeScript
|
dejavvu/tsd
|
/test/assert/tsd/DefBlob.ts
| 2.5625
| 3
|
/// <reference path="../../tsdHelper.ts" />
module helper {
'use strict';
var assert:Chai.Assert = require('chai').assert;
export function serialiseDefBlob(blob:tsd.DefBlob, recursive:number = 0):any {
xm.assertVar(blob, tsd.DefBlob, 'blob');
recursive -= 1;
var json:any = {};
json.sha = blob.sha;
if (blob.content && recursive >= 0) {
json.content = blob.content.toString('base64');
}
return json;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
export function assertDefBlob(blob:tsd.DefBlob, values:any, message:string) {
assert.ok(blob, message + ': blob');
assert.ok(values, message + ': values');
assert.instanceOf(blob, tsd.DefBlob, message + ': author');
helper.propStrictEqual(blob, values, 'sha', message);
if (values.lines) {
assert.strictEqual(blob.content.toString('base64'), values.lines, message + ': content');
}
}
}
|
e2dad39eee8dc1b393af285958e37cca963302c9
|
TypeScript
|
rhfoods/rehuo
|
/src/map/modules/point/modules/sort/dtos/point.sort.dto.ts
| 2.53125
| 3
|
import { ApiProperty } from '@nestjs/swagger';
import { BaseDTO } from '@rehuo/common/dtos/base.response.dto';
import { PageResponseDTO } from '@rehuo/common/dtos/page.response.dto';
import { Exclude, Expose, Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
/**
* 点位分类信息
*/
@Exclude()
export class PointSortInternalDTO {
@Expose()
@ApiProperty({
type: Number,
description: '分类ID',
})
sortId: number;
@Expose()
@ApiProperty({
type: String,
description: '分类信息',
})
name: string;
@Expose()
@ApiProperty({
type: String,
description: '分类显示的LOGO',
})
logo: string;
@Expose()
@ApiProperty({
type: Number,
description: '对应点位数',
})
points: number;
}
/**
* 点位分类列表DTO
*/
export class PointSortDTO extends BaseDTO {
constructor() {
super();
}
@ValidateNested({ each: true })
@Type(() => PointSortInternalDTO)
@ApiProperty({
type: PointSortInternalDTO,
description: '点位分类信息',
})
sort: PointSortInternalDTO;
}
/**
* 点位分类列表DTO
*/
export class PointSortsDTO extends PageResponseDTO {
constructor() {
super();
}
@ValidateNested({ each: true })
@Type(() => PointSortInternalDTO)
@ApiProperty({
type: [PointSortInternalDTO],
description: '点位分类列表',
})
sorts: PointSortInternalDTO[];
@ApiProperty({
type: Number,
description: '所有点位数量',
})
totalPoints: number;
@ApiProperty({
type: Number,
description: '不属于分类的点位数量',
})
defaultPoints: number;
}
/**
* 返回极简的点位信息
*/
@Exclude()
export class MapPointLittleInternalDTO {
@Expose()
@ApiProperty({
type: Number,
description: '点位收藏ID',
})
psaveId: number;
@Expose()
@ApiProperty({
type: String,
description: '点位收藏标签',
})
tag: string;
@Expose()
@ApiProperty({
type: String,
description: '点位名称',
})
name: string;
@Expose()
@ApiProperty({
type: String,
description: '点位地址',
})
address: string;
@Expose()
@ApiProperty({
type: String,
description: '点位收藏LOGO',
})
logo: string;
@Expose()
@ApiProperty({
type: Number,
description: '点位收藏价格',
})
price: number;
@Expose()
@ApiProperty({
type: Number,
description: '点位经度',
})
longitude: number;
@Expose()
@ApiProperty({
type: Number,
description: '点位纬度',
})
latitude: number;
@Expose()
@ApiProperty({
type: Number,
description: '分类ID',
})
sortId: number;
@Expose()
@ApiProperty({
type: Number,
description: '文章ID',
})
noteId: number;
@Expose()
@ApiProperty({
type: Date,
description: '创建时间',
})
createdAt: Date;
}
/**
* 点位DTO数据
*/
export class MapPointLittlesDTO extends PageResponseDTO {
constructor() {
super();
}
@ApiProperty({
type: [MapPointLittleInternalDTO],
description: '点位极简信息列表',
})
points: MapPointLittleInternalDTO[];
}
|
450b4084f8655f3d0c53798093ab57db339f62e4
|
TypeScript
|
AlCalzone/node-dtls-client
|
/src/lib/AEADCrypto.ts
| 3.078125
| 3
|
import * as crypto from "crypto";
import * as semver from "semver";
/**
* Starting with NodeJS 10, we can use the official crypto API to do AEAD encryption
* because authTagLength is now configurable. This module is a wrapper around either
* node-aead-crypto or the native methods
*/
export interface EncryptionResult {
ciphertext: Buffer;
auth_tag: Buffer;
}
export interface DecryptionResult {
plaintext: Buffer;
auth_ok: boolean;
}
export interface AEADEncryptionInterface {
encrypt: (
key: Buffer,
iv: Buffer,
plaintext: Buffer,
additionalData: Buffer,
authTagLength?: number,
) => EncryptionResult;
decrypt: (
key: Buffer,
iv: Buffer,
ciphertext: Buffer,
additionalData: Buffer,
authTag: Buffer,
) => DecryptionResult;
}
function encryptNative(
mode: "ccm" | "gcm",
key: Buffer,
iv: Buffer,
plaintext: Buffer,
additionalData: Buffer,
authTagLength: number,
): EncryptionResult {
// prepare encryption
const algorithm = `aes-${key.length * 8}-${mode}`;
// @ts-ignore The 4th parameter is available starting in NodeJS 10+
const cipher = crypto.createCipheriv(algorithm, key, iv, { authTagLength });
// @ts-ignore The 2nd parameter is available starting in NodeJS 10+
cipher.setAAD(additionalData, { plaintextLength: plaintext.length });
// do encryption
const ciphertext = cipher.update(plaintext);
cipher.final();
const auth_tag = cipher.getAuthTag();
return { ciphertext, auth_tag };
}
function decryptNative(
mode: "ccm" | "gcm",
key: Buffer,
iv: Buffer,
ciphertext: Buffer,
additionalData: Buffer,
authTag: Buffer,
): DecryptionResult {
// prepare decryption
const algorithm = `aes-${key.length * 8}-${mode}`;
// @ts-ignore The 4th parameter is available starting in NodeJS 10+
const decipher = crypto.createDecipheriv(algorithm, key, iv, { authTagLength: authTag.length });
decipher.setAuthTag(authTag);
// @ts-ignore The 2nd parameter is available starting in NodeJS 10+
decipher.setAAD(additionalData, { plaintextLength: ciphertext.length });
// do decryption
const plaintext = decipher.update(ciphertext);
// verify decryption
let auth_ok: boolean = false;
try {
decipher.final();
auth_ok = true;
} catch (e) {/* nothing to do */ }
return { plaintext, auth_ok };
}
let importedCCM: AEADEncryptionInterface;
let importedGCM: AEADEncryptionInterface;
let nativeCCM: AEADEncryptionInterface;
let nativeGCM: AEADEncryptionInterface;
if (
!process.versions.electron &&
semver.satisfies(process.versions.node, ">=10")
) {
// We can use the native methods
nativeCCM = {
encrypt: encryptNative.bind(undefined, "ccm"),
decrypt: decryptNative.bind(undefined, "ccm"),
};
nativeGCM = {
encrypt: encryptNative.bind(undefined, "gcm"),
decrypt: decryptNative.bind(undefined, "gcm"),
};
} else {
// import from the node-aead-crypto module
({ ccm: importedCCM, gcm: importedGCM } = require("node-aead-crypto"));
}
export const ccm = importedCCM || nativeCCM;
export const gcm = importedGCM || nativeGCM;
|
f7a67ae7050a3c2e593af74483979c26f78d7e4b
|
TypeScript
|
chengdonghaipu/supine
|
/projects/dy-form/src/lib/type.ts
| 2.515625
| 3
|
export type ModelPartial<T> = {
[P in keyof T]?: T[P];
};
export type BreakpointType = 'xm' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
|
7b486103b731f6acd75242393e0e3055e7787390
|
TypeScript
|
Friends-of-Groot-Society/groot-material
|
/src/app/services/auth/auth-store.service.ts
| 2.578125
| 3
|
import { Injectable } from "@angular/core";
import { throwError, BehaviorSubject, Observable } from "rxjs";
import { User } from '../../models/User';
import { Router } from '@angular/router';
import { map, shareReplay, catchError, tap } from 'rxjs/operators'
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { environment } from "src/environments/environment";
import { Address } from "src/app/models/Address";
export const AUTH_DATA = "AUTH_DATA";
export const ID_TOKEN = 'idToken'
// https://firebase.google.com/docs/reference/rest/auth#section-create-email-password
export interface FireBaseAuthResponseData {
kind?: string;
idToken?: string;
email?: string;
refreshToken?: string;
expiresIn?: string;
localId?: string;
registered?: boolean;
}
/*
*displayName email : "thomasm1.maestas@gmail.com"
expiresIn : "3600"
idToken : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOTczZWUwZTE2ZjdlZWY0ZjkyMWQ1MGRjNjFkNzBiMmVmZWZjMTkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vZnJpZW5kcy1vZi1ncm9vdCIsImF1ZCI6ImZyaWVuZHMtb2YtZ3Jvb3QiLCJhdXRoX3RpbWUiOjE2NzkyNjUxNjksInVzZXJfaWQiOiJKU2pzNzFLWGtvT0ZBSWN2YkVEUDN0Q0JjZDcyIiwic3ViIjoiSlNqczcxS1hrb09GQUljdmJFRFAzdENCY2Q3MiIsImlhdCI6MTY3OTI2NTE2OSwiZXhwIjoxNjc5MjY4NzY5LCJlbWFpbCI6InRob21hc20xLm1hZXN0YXNAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7ImVtYWlsIjpbInRob21hc20xLm1hZXN0YXNAZ21haWwuY29tIl19LCJzaWduX2luX3Byb3ZpZGVyIjoicGFzc3dvcmQifX0.swtfv1IyLhqWPh_sVTlQUy09PGYnn9vtObttPhq0ts31pmC_UUsXPI0ROu6U988FN3Zfcudwia9NBXMUImNy2oXrQspocRXhdkhX2joKLejwA3IBw-Wv4roZvt7NJjbslzbcfJZBhQG_R5C4zwXAPSeq52Bkte81DqKQeZeJ5vONEKvyTdRCLIhm6ajkV2PlpheG4XXXelaBQSgKdkroSkA7h4m7BDFpm66UboXa1TCpSBY1G4dupauxL_i0sWa39twOpADWfKYKzSI8btL1ihFcILlKAetX_BupSLUpwQZqW9cxRHcHsfBYQJJblo2NLwcmv_eorWE1tM-7MtEfmA"
kind : "identitytoolkit#VerifyPasswordResponse"
localId : "JSjs71KXkoOFAIcvbEDP3tCBcd72"
refreshToken : "APJWN8dCHcFTdGRJIUVrhr3i8qlPYpAI_NGKATFhoI42AOEJXcMaGJl8rJk6G66kbIqTH-OnlLtbKfblDbQXFIi4twZAJ_NQzOnjCr9RNt8EpduUySu7b_s8dcQSZCTLwr54Xni_BlJEau4Q82OZ6A--cWQXcSzWLs6YgVJ9nZdn09RPaguFbpZLXL_O-qpxd840ndCSQmcrG7aj6kdARSTttnIenmHG-b5DHFL6fUF1HxTxpzDv9nc"
registered : true
*/
export interface GrootAuth extends FireBaseAuthResponseData {
idToken?: string;
userId?:string;
username: string;
lastName?: string;
firstName?: string;
groups?:number;
userType?: number;
email?: string;
phone?: string;
cusUrl?: string;
photoPath?: string;
userGroup?: string;
isActive?: number; // 0 = inactive, 1 = active
groupType?: string;
id?: number;
addresses?: Address[];
}
@Injectable({
providedIn: 'root'
})
export class AuthStore {
setUser(user: GrootAuth) {
throw new Error('Method not implemented.');
}
private uSubject$ = new BehaviorSubject<User>(null);
user$: Observable<User> = this.uSubject$.asObservable();
email:string = localStorage.getItem('email');
isLoggedIn$: Observable<boolean>
isLoggedOut$: Observable<boolean>
constructor(private router: Router, private httpClient: HttpClient) {
this.isLoggedIn$ = this.user$.pipe(map(user => !!user));
this.isLoggedOut$ = this.isLoggedIn$.pipe(map(loggedIn => !loggedIn));
const user = localStorage.getItem(AUTH_DATA);
if (user) {
this.uSubject$.next(JSON.parse(user));
}
}
register({ email, password, firstName, lastName }) {
localStorage.setItem('email', email );
localStorage.setItem('firstName', firstName );
localStorage.setItem('lastName', lastName );
return this.httpClient
.post<GrootAuth>( // AuthResponseData
`${environment.nft_url}/users/register`, {
email: email,
password: password,
firstName: firstName,
lastName: lastName
}
)
.pipe(
tap(resData => {
this.executeAuthenticationService(
resData.email,
resData.localId,
resData.idToken
);
})
)
}
login(email: string, password: string): Observable<GrootAuth> {
localStorage.setItem('email', email );
return this.httpClient
.post<GrootAuth>(
`${environment.nft_url}/users/login`,
{
email: email,
password: password,
returnSecureToken: true
})
.pipe(
catchError(this.handleError),
tap(resData => {
this.executeAuthenticationService(
resData.email,
resData.localId,
resData.idToken
);
})
// tap(user => {
// this.uSubject.next(user);
// user.password = "********";
// localStorage.setItem(AUTH_DATA, JSON.stringify(user));
// }),
// shareReplay()
);
}
executeAuthenticationService(
email: string,
userId: string,
token: string
) {
const user = new User();
user.email = email;
user.userId = userId;
user.idToken = token;
this.uSubject$.next(user);
user.firstName = localStorage.getItem('firstName');
user.lastName = localStorage.getItem('lastName');
localStorage.setItem('AUTH_DATA', JSON.stringify(user));
localStorage.setItem('idToken', token);
localStorage.setItem('userId', userId);
}
private handleError(errorRes: HttpErrorResponse) {
let errorMessage = 'An unknown error occurred!';
if (!errorRes.error || !errorRes.error.error) {
return throwError(errorMessage);
}
switch (errorRes.error.error.message) {
case 'EMAIL_EXISTS':
errorMessage = 'This email exists already';
break;
case 'EMAIL_NOT_FOUND':
errorMessage = 'This email does not exist.';
break;
case 'INVALID_PASSWORD':
errorMessage = 'This password is not correct.';
break;
}
return throwError(errorMessage);
}
getEmailId(){
let email = localStorage.getItem('email');
return this.email;
}
logout() {
this.uSubject$.next(null);
localStorage.removeItem(AUTH_DATA);
}
public get currentUserValue(): User {
console.log(this.uSubject$.value)
return this.uSubject$.value;
}
}
|
78a3e09154282104e0da381222b941b9bafb05aa
|
TypeScript
|
leonkj/vet-clinic-demo
|
/client/src/entity/doctor/model.ts
| 2.5625
| 3
|
import { iDoctor } from './interfaces';
import { store } from '../../store';
import { getDoctors, getDoctorsArray } from './selectors';
import { ClinicModel } from '../clinic/model';
export class DoctorModel {
private doctor: iDoctor;
constructor(doctor: iDoctor) {
this.doctor = JSON.parse(JSON.stringify(doctor));
}
getName() {
return this.doctor.firstName + ' ' + this.doctor.lastName;
}
getClinicId() {
return this.doctor.clinic;
}
getClinic() {
return ClinicModel.findById(this.doctor.clinic);
}
getId() {
return this.doctor.id;
}
getSpecialization() {
return this.doctor.specialization;
}
toJSON() {
return this.doctor;
}
static findAll() {
let state = store.getState();
return getDoctorsArray(state).map(rawDoctor => new DoctorModel(rawDoctor));
}
static findById(id: any) {
let state = store.getState();
let rawDoctor = getDoctors(state)[id];
if (rawDoctor) {
return new DoctorModel(rawDoctor);
}
}
static fromArray(doctors: iDoctor[]) {
return doctors.map(rawDoctor => new DoctorModel(rawDoctor));
}
}
|
9f23c2e2c9131adcb210b5846c22b92bcdb35a67
|
TypeScript
|
marcomontalbano/figma-export
|
/packages/core/src/lib/figmaStyles/paintStyle.ts
| 2.875
| 3
|
import * as Figma from 'figma-js';
import * as FigmaExport from '@figma-export/types';
import { notEmpty } from '../utils';
const extractColor = ({ color, opacity = 1 }: FigmaExport.ExtractableColor): (FigmaExport.Color | undefined) => {
if (!color) {
return undefined;
}
const toFixed = (number: number, fractionDigits: number) => parseFloat((number).toFixed(fractionDigits));
const convert = (figmaColor: number) => toFixed(figmaColor * 255, 0);
// eslint-disable-next-line object-curly-newline
let { r = 0, g = 0, b = 0, a = 1 } = color;
r = convert(r);
g = convert(g);
b = convert(b);
a = toFixed(opacity * a, 2);
return {
r,
g,
b,
a,
rgba: `rgba(${r}, ${g}, ${b}, ${a})`,
};
};
const extractGradientLinear = (paint: Figma.Paint): (FigmaExport.LinearGradient | undefined) => {
if (!paint.gradientStops || !paint.gradientHandlePositions) {
return undefined;
}
const getAngle = (figmaGradientHandlePositions: readonly Figma.Vector2[]): string => {
const [startPoint, endPoint] = figmaGradientHandlePositions;
const deltaY = (endPoint.y - startPoint.y);
const deltaX = (endPoint.x - startPoint.x);
const deg = ((Math.atan2(deltaY, deltaX) * 180) / Math.PI) + 90;
return `${parseFloat(deg.toFixed(2))}deg`;
};
const getGradientStops = (figmaGradientStops: readonly Figma.ColorStop[], opacity?: number): FigmaExport.LinearColorStop[] => {
const gradientStops: FigmaExport.LinearColorStop[] = [];
figmaGradientStops.forEach((stop) => {
const color = extractColor({ ...stop, opacity });
const position = parseFloat((stop.position * 100).toFixed(3));
if (color) {
gradientStops.push({ color, position });
}
});
return gradientStops;
};
return {
angle: getAngle(paint.gradientHandlePositions),
gradientStops: getGradientStops(paint.gradientStops, paint.opacity),
};
};
const createFillStyles = (fill: Figma.Paint): FigmaExport.FillStyle | undefined => {
// eslint-disable-next-line default-case
switch (fill.type) {
case 'SOLID': {
const color = extractColor(fill);
if (color) {
return {
type: 'SOLID',
visible: fill.visible !== false,
color,
value: color.rgba,
};
}
break;
}
case 'GRADIENT_LINEAR': {
const gradient = extractGradientLinear(fill);
if (gradient) {
return {
type: 'GRADIENT_LINEAR',
visible: fill.visible !== false,
...gradient,
value: `linear-gradient(${gradient.angle}, ${gradient.gradientStops.map((stop) => {
return `${stop.color.rgba} ${stop.position}%`;
}).join(', ')})`,
};
}
break;
}
}
return undefined;
};
const parse = (node: FigmaExport.StyleNode): FigmaExport.StyleTypeFill | undefined => {
if (node.styleType === 'FILL' && node.type === 'RECTANGLE') {
return {
styleType: 'FILL',
fills: Array.from(node.fills)
.reverse()
.map(createFillStyles)
.filter(notEmpty),
};
}
return undefined;
};
export {
parse,
extractColor,
};
|
33d0cc5f4d649229e397bf948d473bdf672ee733
|
TypeScript
|
jweissman/reflex
|
/src/reflex/ReflexString.spec.ts
| 3.375
| 3
|
import { evaluate } from "./SpecHelper"
describe('String', () => {
it('is the class of words', () => {
expect(evaluate("'hello'.class")).toEqual('Class(String)')
expect(evaluate("'world'.class")).toEqual('Class(String)')
})
describe('instance methods', () => {
it('concat', () => {
expect(evaluate("'hello'.concat(' world')")).toEqual("hello world")
})
it('length', () => {
expect(evaluate("'hello'.length()")).toEqual(5)
})
it('eq', () => {
expect(evaluate("'hello'.eq('hello')")).toEqual(true)
expect(evaluate("'hello'.eq('world')")).toEqual(false)
expect(evaluate("'world'.eq('world')")).toEqual(true)
})
it('reverse', () => {
expect(evaluate("'hello'.reverse().eq('olleh')")).toEqual(true)
expect(evaluate("'hello'.eq('olleh'.reverse())")).toEqual(true)
expect(evaluate("'hello'.reverse().reverse().eq('hello')")).toEqual(true)
expect(evaluate("'hello'.eq('hello'.reverse().reverse())")).toEqual(true)
})
it('multiply', () => {
expect(evaluate("'hi'.multiply(5)")).toEqual('hihihihihi')
})
it('subtract', () => {
expect(evaluate("'abstract'.subtract('algebra')")).toEqual('stct')
})
xit('call', () => {
expect(evaluate("'add'.call(1,2)")).toEqual(3)
})
xit('add calls concat with correct args', () => {
expect(evaluate("'add'.call('hello', 'world')")).toEqual('hello world')
})
})
describe('operators', () => {
it('add is concat', () => {
expect(evaluate("'hello' + ' world'")).toEqual("hello world")
})
it('multiply is replicate', () => {
expect(evaluate("'hello' * 3")).toEqual("hellohellohello")
})
})
describe('escapes', () => {
it('unicode escapes', () => {
evaluate(`code(value) { "\\u001b[" + value + "m" }`)
expect(evaluate("code('123')")).toEqual("\u001b[123m")
expect(evaluate("code('31')+'town'+code('0')")).toEqual("\u001b[31mtown\u001b[0m");
})
})
})
|
f9cd3506ea6078b14df05d4eeb0dd0899435e542
|
TypeScript
|
latotty/snake
|
/lib/manual-snake.hook.ts
| 2.875
| 3
|
import { useState, useEffect } from 'react';
import { SnakeConfig } from '../game/snake-config';
import * as snakeGame from '../game/snake';
import { coordEq } from '../lib/coord';
const snakeLoop = (
gameTick: (
state: snakeGame.State | undefined,
newDirection?: snakeGame.Direction,
) => snakeGame.State,
timeout: number,
setSnakeState: ((cb: (state: snakeGame.State) => snakeGame.State) => void),
): { startLoop: Function; resetLoop: Function; stopLoop: Function } => {
let tid: number;
let stop = false;
const loop = () => {
if (stop) {
return;
}
setSnakeState(state => gameTick(state));
resetLoop();
};
const resetLoop = () => {
window.clearTimeout(tid);
tid = window.setTimeout(loop, timeout);
};
return {
resetLoop,
startLoop: () => resetLoop(),
stopLoop: () => {
stop = true;
window.clearTimeout(tid);
},
};
};
const keyMap: { [key: string]: snakeGame.Direction } = {
ArrowUp: snakeGame.Directions.Up,
ArrowRight: snakeGame.Directions.Right,
ArrowDown: snakeGame.Directions.Down,
ArrowLeft: snakeGame.Directions.Left,
w: snakeGame.Directions.Up,
d: snakeGame.Directions.Right,
s: snakeGame.Directions.Down,
a: snakeGame.Directions.Left,
};
const keyListener = (
config: SnakeConfig,
gameTick: (
state: snakeGame.State | undefined,
newDirection?: snakeGame.Direction,
) => snakeGame.State,
setSnakeState: ((cb: (state: snakeGame.State) => snakeGame.State) => void),
resetLoop: Function,
resetGame: Function,
): { startListen: Function; stopListen: Function } => {
const keydown = (event: KeyboardEvent) => {
switch (event.key) {
case ' ':
resetGame();
return event.preventDefault();
}
if (event.key in keyMap) {
const direction = keyMap[event.key];
setSnakeState(state => {
if (
(state.snakeParts.length > 2 &&
coordEq(
snakeGame.moveOnBoard(config, state.snakeParts[0], direction),
state.snakeParts[1],
)) ||
coordEq(state.direction, direction)
) {
return state;
}
resetLoop();
return gameTick(gameTick(state, direction));
});
return event.preventDefault();
}
};
return {
startListen: () => window.addEventListener('keydown', keydown),
stopListen: () => window.removeEventListener('keydown', keydown),
};
};
export const useManualSnake = (
config: SnakeConfig,
speed: number,
baseTimeout: number,
): {
snakeState: snakeGame.State;
loopTimeout: number;
} => {
const [gameTick, setGameTick] = useState(() => snakeGame.createGame(config));
const [snakeState, setSnakeState] = useState(() => gameTick(undefined));
const resetGame = () => {
const newGameTick = snakeGame.createGame(config);
const newState = newGameTick(undefined);
setGameTick(() => newGameTick);
setSnakeState(() => newState);
};
useEffect(() => resetGame(), [config]); // RESET EFFECT
const loopTimeout =
baseTimeout *
Math.min(1, 0.99 ** (snakeState.snakeParts.length / 8)) *
0.5 ** (speed - 1);
useEffect(
() => {
const { resetLoop, startLoop, stopLoop } = snakeLoop(
gameTick,
loopTimeout,
setSnakeState,
);
const { startListen, stopListen } = keyListener(
config,
gameTick,
setSnakeState,
resetLoop,
resetGame,
);
startLoop();
startListen();
return () => {
stopLoop();
stopListen();
};
},
[config, loopTimeout],
);
return { snakeState, loopTimeout };
};
|
45da8a7a01362bfe9560d8188bbe73197cb5df86
|
TypeScript
|
easylaneof/password-sharing
|
/app/frontend/src/lib/vaidation/email.ts
| 2.609375
| 3
|
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
export const validateEmail = (email: string) => {
const result = re.test(email.toLocaleLowerCase());
if (!result) {
return 'Not a valid email';
}
return true;
};
|
04a260b55248b6ba3e72c0fc2b763e1d244adb4b
|
TypeScript
|
Navachethan-Murugeppa/lens
|
/src/common/utils/camelCase.ts
| 3.40625
| 3
|
// Convert object's keys to camelCase format
import { camelCase, isPlainObject } from "lodash";
export function toCamelCase(obj: Record<string, any>): any {
if (Array.isArray(obj)) {
return obj.map(toCamelCase);
}
else if (isPlainObject(obj)) {
return Object.keys(obj).reduce((result, key) => {
const value = obj[key];
result[camelCase(key)] = typeof value === "object" ? toCamelCase(value) : value;
return result;
}, {} as any);
}
else {
return obj;
}
}
|
1e3e08e072b5a7a36d3241961504985c366b6667
|
TypeScript
|
Koushik95/usc-csci-571
|
/hw8/client/src/app/pipes/group/group.pipe.ts
| 2.734375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'group'
})
export class GroupPipe implements PipeTransform {
transform<T>(value: T[], perGroup: number): T[][] {
const groups: T[][] = [];
for (let i = 0; i < value.length; i += perGroup) {
groups.push(value.slice(i, i + perGroup));
}
return groups;
}
}
|
1aa38b789ba5ee55a7afe00ab24567d30ff46f6b
|
TypeScript
|
skrylnikov/Phoronis-tg-bot
|
/src/controllers/me.ts
| 2.53125
| 3
|
import { Context } from 'telegraf';
export const meController = (ctx: Context) => {
try {
if(ctx.message?.text && ctx.from){
const text = ctx.message.text.replace('/me', '').trim();
const username = `[${ctx.from.first_name || ctx.from.last_name || ctx.from.username || 'Неопознаный космонавт'}](tg://user?id=${ctx.from.id})`
const result = `${username} *${text}*`;
ctx.reply(result, { parse_mode: 'Markdown'});
ctx.deleteMessage(ctx.message.message_id);
}
} catch (e) {
console.error(e);
}
}
|
5d648a41ac428bd42e94b3fb1a1f47c799397bf4
|
TypeScript
|
itsdino/discord-bot-base
|
/src/commands/general/Ping.ts
| 2.796875
| 3
|
import { command } from "../../decorators/command";
import { Command, CommandExecuteArgs } from "../../structures/Command";
@command("ping")
export class PingCommand extends Command {
constructor() {
super({
description: "Checks if I am still online",
category: "General",
});
}
execute({ message }: CommandExecuteArgs) {
message.channel.send("🏓️ Pong!");
}
}
|
264a3434ec305a3813e4fc1998ad2adaa6d4a2e7
|
TypeScript
|
rvilela/node-cookbook
|
/ts/FSUtil.ts
| 2.8125
| 3
|
declare var require;
class FSUtil {
private static myself = null;
private path: string;
private regExp: RegExp;
private myMvMethod: any;
private fs: any;
private FILENAME_REGEXP;
constructor(path: string, regExp: RegExp) {
this.path = path;
this.regExp = regExp;
this.myMvMethod = require('mv');
this.fs = require('fs');
this.FILENAME_REGEXP = regExp;
}
static getinstance(path: string, regExp: RegExp) {
if (FSUtil.myself == null) {
FSUtil.myself = new FSUtil(path, regExp);
}
return FSUtil.myself;
}
// console.log('path string : "' + pathStr + '"');
getFilesName() {
// console.log('regExp : "' + this.FILENAME_REGEXP + '"');
var myArray = this.fs.readdirSync(this.path);
var retArray = [];
for ( var i = 0; i < myArray.length; i++) {
var elem = myArray[i];
var epochDate = this.filter(this.FILENAME_REGEXP, elem);
if (epochDate) {
retArray.push(elem);
}
}
return retArray.sort();
}
filter(regExp, nArq) {
// console.log('filter : ' + regExp + ' - ' + nArq);
if (this.regExp == undefined) {
return false;
}
if (this.regExp.test(nArq)) {
var myArray = regExp.exec(nArq);
return myArray[1]; // A variavel que guarda o Epoch
} else {
return false;
}
}
mv(source, destination) {
console.log('movendo ' + source + ' >>> ' + destination);
// console.log(myMvMethod);
this.myMvMethod(source, destination, function(err) {
if (err != undefined) {
console.log('%s'.red.bold, err);
}
});
}
processInFile(nArq) {
var msg = 'arquivo : ' + nArq + ' movido para diretorio tmp';
// movendo os arquivos
this.mv('./in/' + nArq, './tmp/' + nArq);
console.log(msg);
}
callbackIn(e, i) {
var epochDate = this.filter(this.FILENAME_REGEXP, e);
if (epochDate) {
var myDate = new Date(epochDate * 1000);
var dateStr = myDate.toLocaleString();
console.log('[' + i + '] : ' + 'Processando o arquivo relativo a ['
+ dateStr + ']');
this.processInFile(e);
}
}
// fs.writeFileSync(fileName, str, 'utf8');
processIn() {
var fileNames = this.getFilesName();
if (fileNames.length > 0) {
// processo apenas o primeiro da lista
this.callbackIn(fileNames[0], 0);
return [ fileNames[0], (fileNames[0].split('.'))[0] + '.out' ];
}
// TODO: verificar se devo retornar [] nestas situações.
return [];
}
write(fileName, msg) {
// arquivo pode ser novo ou já existir
// Se já existir limpa e atualiza com o novo valor
this.fs.writeFileSync(fileName, msg); // encoding utf-8
console.log('msg = ' + msg + ' foi salva em ' + fileName);
}
}
export function fsUtil(path: string, regExp: RegExp) {
return FSUtil.getinstance(path, regExp);
};
|
1c9db0a6a3ac6c3fc2f35069993a7bdac220b375
|
TypeScript
|
MdSazzadIslam/paragraph-service
|
/src/schemas/contentSchema.ts
| 2.828125
| 3
|
import { Model, model, Schema } from "mongoose";
export interface IParagraph {
id?: string;
paragraph: string;
numberOfSentence: number;
sentence: Array<string>;
}
const ContentSchema: Schema = new Schema(
{
paragraph: {
type: String,
required: [true, "Paragraph is required"],
unique: true,
},
numberOfSentence: {
type: Number,
},
sentence: [
{
type: String,
},
],
complete: {
type: Boolean,
default: false,
},
},
{ timestamps: true },
);
export const Content: Model<IParagraph> = model("Content", ContentSchema);
|
0db59288be762774250ac7e02b760454cc456611
|
TypeScript
|
jest-community/eslint-plugin-jest
|
/src/rules/no-commented-out-tests.ts
| 2.765625
| 3
|
import type { TSESTree } from '@typescript-eslint/utils';
import { createRule } from './utils';
function hasTests(node: TSESTree.Comment) {
return /^\s*[xf]?(test|it|describe)(\.\w+|\[['"]\w+['"]\])?\s*\(/mu.test(
node.value,
);
}
export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Disallow commented out tests',
recommended: 'warn',
},
messages: {
commentedTests: 'Some tests seem to be commented',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
const sourceCode = context.getSourceCode();
function checkNode(node: TSESTree.Comment) {
if (!hasTests(node)) {
return;
}
context.report({ messageId: 'commentedTests', node });
}
return {
Program() {
const comments = sourceCode.getAllComments();
comments.forEach(checkNode);
},
};
},
});
|
5a802640912f45d5b03746b5f00f5303dcbc9e68
|
TypeScript
|
Podlipny/Courses
|
/Youtube/Picking From 20 React State Managers/examples/atomic-agilets/src/store.ts
| 2.65625
| 3
|
import {createState, globalBind} from '@agile-ts/core';
export const NAMES = createState<string[] | null>(null);
export const SECONDS = createState(0);
export const IS_RUNNING = createState(false);
export const incrementSeconds = async (amount = 0.1) => {
const seconds = SECONDS.value;
const todos = NAMES.value;
// Increment Seconds
SECONDS.set((v) => v + amount);
// Fetch dummy Data
if (seconds > 2 && todos == null) {
const response = await fetch('/names.json');
const parsedJson = await response.json();
NAMES.set(parsedJson.names);
}
};
export const { toggleTimer } = (() => {
let timerRef: null | number = null;
const toggleTimer = () => {
const isRunning = !IS_RUNNING.value;
IS_RUNNING.set(isRunning);
// Clear Interval
if (timerRef != null) {
clearInterval(timerRef);
timerRef = null;
}
// Start Interval
if (isRunning) timerRef = setInterval(incrementSeconds, 100);
};
return { toggleTimer };
})();
// For better debugging in Browser console
globalBind('__store__', {NAMES, SECONDS, IS_RUNNING});
|
544824e06cacbc86f93ff33ef7da9f7d8495ae99
|
TypeScript
|
jordivid/exercici-vehicles
|
/nivell1/models/wheel.ts
| 3.109375
| 3
|
export class Wheel{
public diameter:number;
public brand:string;
constructor(diameter:number, brand:string){
this.diameter=diameter;
this.brand=brand;
}
public htmlCode(numero: number): string {
let code: string = `
<div class="col-6 col-md-3 mb-1">
<div class="d-flex flex-column p-1 wheelData">
<h6 class="font-weight-bold">Roda ${ numero }</h6>
<div class="d-flex">
<span class="font-weight-bold mr-1">Marca:</span>
<span class="text-break">${ this.brand }</span>
</div>
<div class="d-flex">
<span class="font-weight-bold mr-1">Diàmetre:</span>
<span>${ this.diameter }</span>
</div>
</div>
</div>
`;
return code;
}
public validate(numero: number) : boolean | string {
let errorText: string = "";
let success: boolean = true;
if (this.brand === "") {
errorText = `Introdueix marca de la roda ${ numero }`;
success = false;
}
if ((isNaN(this.diameter)) || (this.diameter < 0.4 || this.diameter > 2)) {
if (errorText !== "") {
errorText +="\n";
}
errorText += `El diàmetre de la roda ${ numero } és incorrecte`;
success = false;
}
if(success) {
return success;
} else {
return errorText;
}
}
}
|
9541202fd3916330375d13a70e5fcbf72ccdea6e
|
TypeScript
|
clinyong/fake-mobx
|
/mobx/utils/reactive.ts
| 2.75
| 3
|
export interface IObservers {
[index: string]: IDerivation;
}
export interface IObservable {
observers: IObservers;
}
export interface IDerivation {
name: string;
observing: IObservable[];
schedule: () => void;
}
|
b308a86d7b7cb93c28271b9757abe75522d4245e
|
TypeScript
|
phuhgh/js-util
|
/src/array/typed-array/mat3/mat3-factory.ts
| 2.890625
| 3
|
import { ITypedArrayTupleFactory } from "../i-typed-array-tuple-factory.js";
import { ATypedTupleFactory } from "../a-typed-tuple-factory.js";
import { TTypedArray } from "../t-typed-array.js";
import { IMat3Ctor, Mat3, TMat3CtorArgs } from "./mat3.js";
import { INormalizedDataView } from "../normalized-data-view/i-normalized-data-view.js";
export class Mat3Factory<T extends Mat3<TTypedArray>>
extends ATypedTupleFactory<T, TMat3CtorArgs>
implements ITypedArrayTupleFactory<T, TMat3CtorArgs>
{
public constructor
(
private ctor: IMat3Ctor<TTypedArray>,
dataView: INormalizedDataView,
)
{
super(9, ctor.BYTES_PER_ELEMENT, dataView);
}
public createOneEmpty(): T
{
return new this.ctor() as T;
}
public createOne
(
c1r1: number,
c2r1: number,
c3r1: number,
c1r2: number,
c2r2: number,
c3r2: number,
c1r3: number,
c2r3: number,
c3r3: number,
)
: T
{
const a = this.createOneEmpty();
a[0] = c1r1;
a[1] = c2r1;
a[2] = c3r1;
a[3] = c1r2;
a[4] = c2r2;
a[5] = c3r2;
a[6] = c1r3;
a[7] = c2r3;
a[8] = c3r3;
return a;
}
}
|
6f6f1086a48652d2ebd0b07386923fa98b953d14
|
TypeScript
|
ai-FarazKhan/gettickets
|
/tickets/src/events/publishers/ticket-created-publisher.ts
| 3.09375
| 3
|
// publisher is going to emit an event to NATS streaming server.
import { Publisher, Subjects, TicketCreatedEvent } from "@gettickets/common";
// Publisher base class that is a generic class, which means we need to put on those brackets and provide the Type of event that we are going to try to emit with this Publisher. So in this Case it is TicketCreatedEvent.
export class TicketCreatedPublisher extends Publisher<TicketCreatedEvent>{
subject: Subjects.TicketCreated = Subjects.TicketCreated; // we have to do both the type annotation and value assignment, the reason that we have both on here is to make sure that we never try to change the value of subject.
}
|
6f2bad66833d372397d8466d0050b20f2ba43966
|
TypeScript
|
DjonnyX/ng-router-parser
|
/src/helpers/normalize-path.ts
| 3.046875
| 3
|
import { parsePath } from "./path-parser";
import path from "path";
const UP_PATH_PATTERN = /\.\.(?:[\\/]|$)/g;
const RESOLVE_PATH_PATTERN = /(?:^|[\\/])\.(?:[\\/]|$)/;
/**
* Нормализация пути
* @param {string} currentPath
* @param {string} observedPath
* @return {string}
*/
export const normalizePath = (currentPath: string, observedPath: string): string => {
const cpSegments = parsePath(currentPath);
const obsSegments = parsePath(observedPath);
if (UP_PATH_PATTERN.test(observedPath)) {
const entryCount = observedPath.match(UP_PATH_PATTERN).length;
return cpSegments.slice(0, cpSegments.length - entryCount).concat(obsSegments.slice(entryCount)).join(path.sep);
} else if (RESOLVE_PATH_PATTERN.test(observedPath)) {
const entryCount = observedPath.match(RESOLVE_PATH_PATTERN).length;
return cpSegments.concat(obsSegments.slice(entryCount)).join(path.sep);
}
return obsSegments.join(path.sep);
}
|
7f849aa162f1c87bd99f2318b382dc20e8ad35ab
|
TypeScript
|
Sicphy/iba-winter-2019
|
/Angular tasks/src/app/models/status-code.ts
| 2.53125
| 3
|
import {ObjectType} from './object-type';
export class StatusCode {
id: number;
code: string;
description: string;
objectType: ObjectType;
objectTypeName: string;
issueGrouping: boolean;
createIncidents: boolean;
status: string;
constructor() {
this.id = 0;
this.code = '';
this.description = '';
this.objectType = new ObjectType();
this.objectTypeName = '';
this.issueGrouping = false;
this.createIncidents = false;
this.status = '';
}
}
|
90f8673fe19c56d125fad73ed899d4816bdd0f4f
|
TypeScript
|
loglife-dev/transporte-biologico_v3
|
/src/modules/shipping/infra/typeorm/repositories/ShippingRepository.ts
| 2.546875
| 3
|
import { BaseRepository } from "../../../../../shared/infra/repositories/BaseRepositories";
import { IShippingRepository } from "../../../repositories/IShippingRepository";
import { Shipping } from "../entities/Shipping";
class ShippingRepository extends BaseRepository<Shipping> implements IShippingRepository {
constructor() {
super(Shipping)
}
async Get(): Promise<Shipping[]> {
return this.repository.find({
order: {
company_name: 'ASC'
}
});
}
async findById(id: string): Promise<Shipping> {
return this.repository.findOne({
where: { id },
order: {
company_name: 'ASC'
}
})
}
async findByCnpj(cnpj: string): Promise<Shipping> {
return this.repository.findOne({ cnpj })
}
}
export { ShippingRepository }
|
a61d17713b081198650066dcaa9b91408fd883d0
|
TypeScript
|
xJA10x/ToDoAppWithAngular
|
/src/app/components/todos/todos.component.ts
| 2.796875
| 3
|
import { Component, OnInit } from '@angular/core';
// Imports service to bring our todos data.
import {TodoService} from '../../services/todo.service';
// Imports Todo model to work with todo data.
import {Todo} from '../../models/Todo'
@Component({
selector: 'app-todos',
templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css']
})
// Builds class.
// Inherits from Onnit.
export class TodosComponent implements OnInit {
// Loops from all of our todos that
// come from json place holders and fetch them
// through a service.
// Builds property.
todos:Todo[];
// Constructor is used initialize services.
// The name can be anything we want
// and then bind it to the services we import.
constructor(private todoService:TodoService) { }
// Life cycle method.
// Runs right away.
ngOnInit() {
// Method call
// using service.
// Subscribe to the oservable
this.todoService.getTodos().subscribe(todos => {
// Sets todos
// to the todos that are return.
this.todos = todos;
});
}
// Builds method.
// Takes one parameter,
// a todo.
// When we click the delete button sends
// an event to the todo-item component.
deleteTodo(todo:Todo) {
// Remove From UI.
// Deletes todos from the front end.
// Returns all the todos that dont have that id.
this.todos = this.todos.filter(t => t.id !== todo.id);
// Deleted todos from the server.
this.todoService.deleteTodo(todo).subscribe();
}
// Builds method.
addTodo(todo:Todo) {
// Makes post request to the server through the service.
this.todoService.addTodo(todo).subscribe(todo => {
// Pushes to the array.
this.todos.push(todo);
});
}
}
|
9162ebec5609f28a7135cf965dd623ad517ed44c
|
TypeScript
|
murage-poc/angular-pipe-recursion
|
/src/app/object-value.pipe.ts
| 2.8125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'objectValue'})
export class ObjectValuePipe implements PipeTransform {
dynamicValues;
transform(obj:{}): string[] {
this.dynamicValues=[];
return this.getValueFromObject(obj);
}
getValueFromObject(dataObj) {
for (const prop in dataObj) {
if (typeof dataObj[prop] === "object") {
this.getValueFromObject(dataObj[prop]);
} else {
this.dynamicValues.push( " |=> " + dataObj[prop]);
}
}
return this.dynamicValues;
}
}
|
b615c98b30f016a1f44dd77e342749658c1d27b9
|
TypeScript
|
dczwx5/learngit
|
/note/erget/MergeTheCards3/MergeTheCards/MiniGame_OpenDataContext/src/lib/contextEvent/IEventDispatcher.ts
| 2.578125
| 3
|
interface IEventDispatcher{
addEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number): void ;
once(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number): void ;
removeEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean): void ;
hasEventListener(type: string): boolean ;
dispatchEvent(event: egret.Event): boolean ;
willTrigger(type: string): boolean ;
}
|
be7161f39ff097ab575218a44295a34f6e3211f4
|
TypeScript
|
swissglider/homeOverviewIonic
|
/src/app/oldapp/store/error/error-msg.model.ts
| 2.9375
| 3
|
/** Specifies an errorMsg used within the Error Msg Store */
export interface ErrorMsg {
/** id */
id: string;
/** severity of the error (can be: info, warning, success, danger) */
type: 'info' | 'warning' | 'success' | 'danger';
/** text for the error */
text: string;
/** action the user should take */
action: string;
/** scope the error belongs to */
scope: 'local' | 'global' | 'debug' | 'info';
}
/** @ignore */
export function createErrorMsg(params: Partial<ErrorMsg>) {
return {
} as ErrorMsg;
}
|
cb4a47f0bea137d2949e59c5774685587d9c590e
|
TypeScript
|
obniz/obniz
|
/src/parts/Grove/Grove_RotaryAngleSensor/index.ts
| 2.625
| 3
|
/**
* @packageDocumentation
* @module Parts.Grove_RotaryAngleSensorOptionsA
*/
import Obniz from '../../../obniz';
import { PeripheralAD } from '../../../obniz/libs/io_peripherals/ad';
import { DriveType } from '../../../obniz/libs/io_peripherals/common';
import { PeripheralGrove } from '../../../obniz/libs/io_peripherals/grove';
import {
ObnizPartsInterface,
ObnizPartsInfo,
} from '../../../obniz/ObnizPartsInterface';
interface Grove_RotaryAngleSensorOptionsA {
signal: number;
vcc?: number;
gnd?: number;
}
interface Grove_RotaryAngleSensorOptionsB {
grove: PeripheralGrove;
}
export type Grove_RotaryAngleSensorOptions =
| Grove_RotaryAngleSensorOptionsA
| Grove_RotaryAngleSensorOptionsB;
export default class Grove_RotaryAngleSensor implements ObnizPartsInterface {
public static info(): ObnizPartsInfo {
return {
name: 'Grove_RotaryAngleSensor',
};
}
public keys: string[];
public requiredKeys: string[];
public params: any;
public drive: DriveType;
// public vcc_voltage = 5.0;
public position = 0;
public ad!: PeripheralAD;
public value: any;
public onchange?: (position: number) => void;
protected obniz!: Obniz;
constructor() {
this.keys = ['vcc', 'gnd', 'signal', 'grove'];
this.requiredKeys = [];
this.drive = '5v';
}
public wired(obniz: Obniz) {
if (this.params.grove) {
const groveAd = this.params.grove.getAnalog();
this.ad = groveAd.primary;
} else {
this.obniz.setVccGnd(this.params.vcc, this.params.gnd, this.drive);
this.ad = obniz.getAD(this.params.signal);
}
this.ad.start((value: number) => {
this.value = value;
if (this.onchange) {
this.onchange(this.value);
}
});
}
}
|
fa9b73b8f6076898617a3b0fe937f4690ea26ded
|
TypeScript
|
zanachka/noderdom-detached
|
/base/classes/XMLSerializer.ts
| 2.609375
| 3
|
import InternalHandler, { initializeConstantsAndPrototypes } from '../InternalHandler';
import StateMachine from '../StateMachine';
import { INode, IXMLSerializer } from '../interfaces';
export const { getState, setState, setHiddenState, setReadonlyOfXMLSerializer } = StateMachine<
IXMLSerializer,
IXMLSerializerProperties,
IXMLSerializerReadonlyProperties
>('XMLSerializer');
export const internalHandler = new InternalHandler<IXMLSerializer>('XMLSerializer', getState, setState);
export default class XMLSerializer implements IXMLSerializer {
constructor() {
initializeConstantsAndPrototypes<XMLSerializer>(XMLSerializer, this, internalHandler, XMLSerializerConstantKeys, XMLSerializerPropertyKeys);
}
// methods
public serializeToString(root: INode): string {
return internalHandler.run<string>(this, 'serializeToString', [root]);
}
}
// INTERFACES RELATED TO STATE MACHINE PROPERTIES //////////////////////////////
export interface IXMLSerializerProperties {}
export interface IXMLSerializerReadonlyProperties {}
// tslint:disable-next-line:variable-name
export const XMLSerializerPropertyKeys = [];
// tslint:disable-next-line:variable-name
export const XMLSerializerConstantKeys = [];
|
c4443e4b84dcca581ce0c8319b338e239efc30f4
|
TypeScript
|
maranite/Keylab-Viper
|
/ts-stubs/Action.d.ts
| 3.46875
| 3
|
/**
* Instances of this interface represent actions in Bitwig Studio, such as commands that can be launched from
* the main menu or via keyboard shortcuts.
*
* To receive the list of all actions provided by Bitwig Studio call {Application#getActions()}. The
* list of actions that belong to a certain category can be queried by calling
* {ActionCategory#getActions()}. Access to specific actions is provided in
* {Application#getAction(String)}.
*/
interface Action {
/** Returns a string the identifies this action uniquely.
* @returnType {string} the identifier string */
getId(): string;
/** Returns the name of this action.
* @returnType {string} the name string */
getName(): string;
/** Returns the category of this action.
* @returnType {ActionCategory} the category string */
getCategory(): ActionCategory;
/** Returns the text that is displayed in menu items associated with this action.
* @returnType {string} the menu item text */
getMenuItemText(): string;
/** Invokes the action.
* */
invoke(): void;
}
|
19ae9253b40dec5c659962c98e040c5f7264d0c0
|
TypeScript
|
hota1024/lifegame-core
|
/src/Types/Copyable.ts
| 3.140625
| 3
|
/**
* Copyable interface.
*/
export interface Copyable<Type> {
/**
* Copy.
*/
copy(): Type
}
|
7643f4cd3f73efb557e0b7eabd744abaef3dfe70
|
TypeScript
|
kavehsajjadi/app-wordy
|
/src/util/debounce.ts
| 2.703125
| 3
|
export function debounce(func, wait, immediate = false) {
var timeout
return function() {
var context = this,
args = arguments
var later = function() {
timeout = null
if (!immediate) func.apply(context, args)
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
export function callWithDelay(fn, delay) {
let timeout = null
return (...params) => {
clearTimeout(timeout)
return new Promise(resolve => {
timeout = setTimeout(() => resolve(fn(...params)), delay)
})
}
}
|
45561312be5ab83bfe5afa4d3b791f0950e7aba0
|
TypeScript
|
LucasGomes9/employee_backend
|
/src/app/controllers/LikeController.ts
| 2.828125
| 3
|
import { getRepository } from 'typeorm';
import Employees from '../models/Employees';
class LikeController {
async like(id: string): Promise<number> {
const employeeRepository = getRepository(Employees);
const employee = await employeeRepository.findOne({where: { id }});
if (!employee) {
throw new Error('Doesn\'t exists employee with this id');
}
employee.likes += 1;
employeeRepository.save(employee);
return employee.likes;
}
async dislike(id: string): Promise<number> {
const employeeRepository = getRepository(Employees);
const employee = await employeeRepository.findOne({where: { id }});
if (!employee) {
throw new Error('Doesn\'t exists employee with this id');
}
employee.dislikes -= 1;
employeeRepository.save(employee);
return employee.dislikes;
}
}
export default LikeController;
|
419426b2420a0e266372ed65d332afd5ff19b20b
|
TypeScript
|
lmenezes/x
|
/packages/search-types/src/facet/facet.model.ts
| 2.734375
| 3
|
import { Identifiable } from '../identifiable.model';
import { FacetModelName, NamedModel } from '../named-model.model';
import { Filter } from './filter/filter.model';
/**
* Facet is a trait for filtering results. It uses {@link Filter} as filters.
*
* @public
*/
export interface Facet extends NamedModel<FacetModelName>, Identifiable {
/** Filters available for the facet. */
filters: Filter[];
/** Label that represents the facet text. */
label: string;
}
|
cab920dd664eb304a39ad9e326bc6d7387cbd506
|
TypeScript
|
xyy277/hikaru-angular
|
/src/app/business/common/service/localstorage.service.ts
| 2.78125
| 3
|
import {Injectable} from '@angular/core';
@Injectable()
export class LocalStorageService {
constructor() {
}
read(key: string): string {
const text: string = localStorage.getItem(key);
if (text === null || typeof (text) === undefined || text === 'undefined') {
return null;
} else {
return text;
}
}
readObject<T>(key: string): T {
const text = this.read(key);
let data: T;
try {
data = <T> JSON.parse(text);
} catch (e) {
data = null;
}
return data;
}
write(key: string, data: string): void {
localStorage.setItem(key, data);
}
writeObject(key: string, data: any): void {
const text = JSON.parse(data);
this.write(key, data);
}
remove(key: string): void {
localStorage.removeItem(key);
}
clear(): void {
localStorage.clear();
}
}
|
cd7cc69f75f9c906fe48ba2c3980c1b215f661fb
|
TypeScript
|
kaiwensun/leetcode
|
/2001-2500/2172.Maximum AND Sum of Array.ts
| 3.015625
| 3
|
function maximumANDSum(nums: number[], numSlots: number): number {
const DP = [];
function dfs(i, slotSetting) {
if (i === nums.length) {
return 0;
}
if (i == DP.length) {
DP.push({});
}
if (DP[i].hasOwnProperty(slotSetting)) {
return DP[i][slotSetting];
}
let slotIter = slotSetting;
let slotId = 0;
let res = -Infinity;
while (slotIter !== 0) {
const space = slotIter & 3;
if (space !== 0) {
res = Math.max(res, ((slotId + 1) & nums[i]) + dfs (i + 1, slotSetting - (1 << (slotId * 2))));
}
slotId++;
slotIter >>= 2;
}
DP[i][slotSetting] = res;
return res;
}
let slotSettings = 0;
for (let i = 0; i < numSlots; i++) {
slotSettings <<= 2;
slotSettings += 2;
}
return dfs(0, slotSettings);
};
|
e1550702d6ab8900ea92a3efd5e6b3a578f646bb
|
TypeScript
|
whjvenyl/Valetudo
|
/src/api/mock/Command.ts
| 2.765625
| 3
|
import { IValetudoCommandApi } from "@/api";
import { MockApi } from "@/api/mock";
import {
chargingResponse,
cleaningResponse,
idleResponse,
pausedResponse,
returnHomeResponse,
sleepingResponse,
spotCleaningResponse
} from "@/api/mock/fakeResponses";
export class MockCommandApi implements IValetudoCommandApi {
private parent: MockApi;
constructor(parent: MockApi) {
this.parent = parent;
}
public StartCleaning(): Promise<any> {
this.parent.currentResponse = cleaningResponse;
this.parent.inCleaning = true;
this.parent.fakeArea = 0;
const start = performance.now();
setInterval(() => {
if (this.parent.currentResponse.state === cleaningResponse.state) {
this.parent.fakeTime = Math.round((performance.now() - start) / 1000);
this.parent.fakeArea +=
1000 + Math.floor(Math.random() * Math.floor(8000));
}
}, 1000);
return Promise.resolve();
}
public Pause(): Promise<any> {
this.parent.currentResponse = pausedResponse;
setTimeout(() => {
if (this.parent.currentResponse.state === pausedResponse.state) {
this.parent.currentResponse = { ...sleepingResponse };
}
}, 4000);
return Promise.resolve();
}
public Stop(): Promise<any> {
this.parent.currentResponse = idleResponse;
this.parent.inCleaning = false;
setTimeout(() => {
if (this.parent.currentResponse.state === idleResponse.state) {
this.parent.currentResponse = { ...sleepingResponse };
}
}, 4000);
return Promise.resolve();
}
public Home(): Promise<any> {
this.parent.currentResponse = returnHomeResponse;
this.parent.inCleaning = false;
setTimeout(() => {
if (this.parent.currentResponse.state === returnHomeResponse.state) {
this.parent.currentResponse = { ...chargingResponse };
}
}, 4000);
return Promise.resolve();
}
public Find(): Promise<any> {
alert("Hey...I'm here!");
return Promise.resolve();
}
public SpotClean(): Promise<any> {
this.parent.currentResponse = spotCleaningResponse;
setTimeout(() => {
this.parent.currentResponse = chargingResponse;
}, 4000);
return Promise.resolve();
}
public setFanSpeed(speed: number): Promise<any> {
// tslint:disable-next-line:no-console
console.log("Setting fan speed", speed);
this.parent.fanSpeed = speed;
return Promise.resolve();
}
}
|
5b88cb283b44401adccc136d4ae83660f7f79552
|
TypeScript
|
bionicgym/react-native-blemulator
|
/src/internal/internal-types.ts
| 2.75
| 3
|
import { UUID, Base64 } from "../types";
import { SimulatedService, SimulatedCharacteristic, SimulatedDescriptor } from "../..";
export interface TransferService {
peripheralId: string,
id: number,
uuid: UUID,
characteristics: Array<TransferCharacteristic>
}
export interface TransferCharacteristic {
peripheralId: string,
id: number,
uuid: UUID,
serviceId: number,
serviceUuid: UUID,
isReadable: boolean,
isWritableWithResponse: boolean,
isWritableWithoutResponse: boolean,
isNotifiable: boolean,
isIndicatable: boolean,
isNotifying: boolean,
value: Base64 | null,
descriptors: Array<TransferDescriptor> | null
}
export interface TransferDescriptor {
peripheralId: string,
id: number,
uuid: UUID,
characteristicId: number,
characteristicUuid: UUID,
serviceId: number,
serviceUuid: UUID,
value: Base64 | null
}
export function mapToTransferService(service: SimulatedService, peripheralId: string): TransferService {
return {
peripheralId: peripheralId,
id: service.id,
uuid: service.uuid,
characteristics: service.getCharacteristics().map(
(charateristic) => mapToTransferCharacteristic(
charateristic, peripheralId, undefined, charateristic.getDescriptors()
)
)
}
}
export function mapToTransferCharacteristic(characteristic: SimulatedCharacteristic, peripheralId: string,
value?: Base64, descriptors?: Array<SimulatedDescriptor>): TransferCharacteristic {
return {
peripheralId: peripheralId,
id: characteristic.id,
uuid: characteristic.uuid,
serviceId: characteristic.service!.id,
serviceUuid: characteristic.service!.uuid,
isReadable: characteristic.isReadable,
isIndicatable: characteristic.isIndicatable,
isNotifiable: characteristic.isNotifiable,
isNotifying: characteristic.isNotifying,
isWritableWithResponse: characteristic.isWritableWithResponse,
isWritableWithoutResponse: characteristic.isWritableWithoutResponse,
descriptors: descriptors ? descriptors?.map((descriptor) => mapToTransferDescriptor(descriptor, peripheralId)) : null,
value: value ? value : null
}
}
export function mapToTransferDescriptor(descriptor: SimulatedDescriptor, peripheralId: string, value?: Base64): TransferDescriptor {
return {
peripheralId: peripheralId,
id: descriptor.id,
uuid: descriptor.uuid,
characteristicId: descriptor.characteristic!.id,
characteristicUuid: descriptor.characteristic!.uuid,
serviceId: descriptor.characteristic!.service!.id,
serviceUuid: descriptor.characteristic!.service!.uuid,
value: value ? value : null
}
}
|
84a64e0c1479137053074470770b6ad4fe27fef3
|
TypeScript
|
viry3d/viry3d.github.io
|
/viry3d/web/lib/graphics/BufferGL.ts
| 3.046875
| 3
|
import { Graphics } from "./Graphics"
export enum BufferType {
None,
Vertex,
Index,
Uniform,
Image,
};
export type FillFunc = (param: any, buffer: DataView) => void;
export class BufferGL {
Fill(param: any, fill: FillFunc) {
let gl = Graphics.GetDisplay().GetGL();
let buffer = new ArrayBuffer(this.m_size);
fill(param, new DataView(buffer));
gl.bindBuffer(this.m_type, this.m_buffer);
if(this.m_usage == gl.DYNAMIC_DRAW) {
gl.bufferSubData(this.m_type, 0, buffer);
} else {
gl.bufferData(this.m_type, buffer, this.m_usage);
}
gl.bindBuffer(this.m_type, null);
}
GetBuffer(): WebGLBuffer {
return this.m_buffer;
}
GetSize(): number {
return this.m_size;
}
protected CreateInternal(type: BufferType, dynamic = false) {
let gl = Graphics.GetDisplay().GetGL();
switch(type) {
case BufferType.Vertex:
this.m_type = gl.ARRAY_BUFFER;
break;
case BufferType.Index:
this.m_type = gl.ELEMENT_ARRAY_BUFFER;
break;
default:
this.m_type = 0;
this.m_usage = 0;
break;
}
if(dynamic) {
this.m_usage = gl.DYNAMIC_DRAW;
} else {
this.m_usage = gl.STATIC_DRAW;
}
this.m_buffer = gl.createBuffer();
if(this.m_usage == gl.DYNAMIC_DRAW) {
gl.bindBuffer(this.m_type, this.m_buffer);
gl.bufferData(this.m_type, this.m_size, this.m_usage);
gl.bindBuffer(this.m_type, null);
}
}
private m_buffer: WebGLBuffer;
private m_type = 0;
private m_usage = 0;
protected m_size = 0;
}
|
1abc2eae2b06689039ff8542f4dc530f8325b690
|
TypeScript
|
Drischdaan/mooncake
|
/src/injection/injector.ts
| 2.953125
| 3
|
import { IInjectableMetadata, IInjector } from "../api/injection/injector.interfaces";
import { Class, ProviderKey } from "../types";
export class Injector implements IInjector {
public createInstance<T>(value: Class<T>, ...args: any[]): T {
if(value === undefined)
throw new Error(`Invalid class provided!`);
return new value(...args);
}
public generateKey(value: ProviderKey<any>): string {
if(typeof(value) === "string")
return value;
else if(typeof(value) === "symbol")
return value.toString().replace('Symbol(', '').replace(')', '');
else if(typeof(value) === "function") {
const metadata: IInjectableMetadata = Reflect.getMetadata('injectable:metadata', value);
if(metadata === undefined)
throw new Error(`Couldn't retrieve injectable metadata from provider: ${String(value)}`);
return metadata.name;
}
return undefined;
}
}
|
0a682ed10603847a84bad2b73bfe7b199d9ca722
|
TypeScript
|
dalfiannur/absensi
|
/src/store/user-role/reducers.ts
| 2.8125
| 3
|
import {
UserRoleTypes,
UserRoleState,
SET_ROLE,
SET_ROLES
} from './types'
const initialState: UserRoleState = {
role: {
id: 0,
name: ''
},
roles: []
}
export const userRoleReducer = (state = initialState, action: UserRoleTypes) => {
switch (action.type) {
case SET_ROLE:
return {
...state,
role: action.payload
}
case SET_ROLES:
return {
...state,
roles: action.payload
}
default:
return state
}
}
|
72da0024c8e287bb3c753ab5c00e1ea99eb5a051
|
TypeScript
|
Vatsalshah8200/Summer_Internship
|
/snake game/js/index.ts
| 3.03125
| 3
|
//constnats
let inputDir = { x: 0, y: 0 };
const foodSound = new Audio('./music/food.mp3');
const gameOverSound = new Audio('./music/gameover.mp3');
const moveSound = new Audio('./music/move.mp3');
const musicSound = new Audio('./music/music.mp3');
const speed = 9;
let lastPaintTime = 0;
let score = 0;
let snakeArr = [
{ x: 15, y: 15 }
]
let food = { x: 2, y: 15 };
let board = document.getElementById('board')!;
let score2 = document.getElementById('score')!;
let highscore2 = document.getElementById('highscore')!;
let highscoreval;
//game function
const main = (ctime) => {
window.requestAnimationFrame(main);
// console.log(ctime);
if ((ctime - lastPaintTime) / 1000 < 1 / speed) {
return;
}
lastPaintTime = ctime;
gameEngine();
}
function isCollide(snake) {
// If you bump into yourself
for (let i = 1; i < snakeArr.length; i++) {
if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
return true;
}
}
// If you bump into the wall
if (snake[0].x >= 18 || snake[0].x <= 0 || snake[0].y >= 18 || snake[0].y <= 0) {
return true;
}
return false;
}
function gameEngine() {
//snake array and food
if (isCollide(snakeArr)) {
gameOverSound.play();
musicSound.pause();
inputDir = { x: 0, y: 0 };
alert("game Over. press any key ");
snakeArr = [{ x: 15, y: 15 }];
musicSound.play();
score = 0;
}
//random food increment score
if (snakeArr[0].y === food.y && snakeArr[0].x === food.x) {
score += 1;
if (score > highscoreval) {
highscoreval = score;
localStorage.setItem("highscore", JSON.stringify(highscoreval));
highscore2.innerHTML = "HiScore :" + highscoreval;
}
score2.innerHTML = "Score: " + score;
foodSound.play();
snakeArr.unshift({ x: snakeArr[0].x + inputDir.x, y: snakeArr[0].y + inputDir.y });
let a = 2, b = 16;
food = { x: Math.round(a + (b - a) * Math.random()), y: Math.round(a + (b - a) * Math.random()) };
}
//snake movement
for (let i = snakeArr.length - 2; i >= 0; i--) {
//const element = array[i];
snakeArr[i + 1] = { ...snakeArr[i] };
}
snakeArr[0].x += inputDir.x;
snakeArr[0].y += inputDir.y;
// snake display
board.innerHTML = "";
snakeArr.forEach((e, index) => {
let snakeElement: string | number | HTMLDivElement;
snakeElement = document.createElement('div');
//snakeElement.style.setProperty("gridRowStart",e.y);
//snakeElement.setAttribute("style","gridRowStart:${e.y};");
//snakeElement.setAttribute("style","gridColumnStart:e.x;")
snakeElement.style.gridRowStart = e.y.toString();
snakeElement.style.gridColumnStart = e.x.toString();
if (index == 0) {
snakeElement.classList.add('head');
}
else {
snakeElement.classList.add('snake');
}
board.appendChild(snakeElement);
//foood display
let foodElement: string | number | HTMLDivElement;
foodElement = document.createElement('div');
foodElement.style.gridRowStart = food.y.toString();
foodElement.style.gridColumnStart = food.x.toString();
foodElement.classList.add('food');
board.appendChild(foodElement);
})
}
//main logic
let highscore = localStorage.getItem("highScore");
if (highscore === null) {
highscoreval = 0;
localStorage.setItem("highscore", JSON.stringify(highscoreval));
}
else {
highscoreval = JSON.parse(highscore);
highscore2.innerHTML = "HiScore :" + highscore;
}
window.requestAnimationFrame(main);
window.addEventListener('keydown', e => {
inputDir = { x: 0, y: 1 };
moveSound.play();
switch (e.key) {
case "ArrowUp":
console.log("Arrow up");
inputDir.x = 0;
inputDir.y = -1;
break;
case "ArrowDown":
console.log("Arrow Down");
inputDir.x = 0;
inputDir.y = 1;
break;
case "ArrowLeft":
console.log("Arrow Left");
inputDir.x = -1;
inputDir.y = 0;
break;
case "ArrowRight":
console.log("Arrow Right");
inputDir.x = 1;
inputDir.y = 0;
break;
default:
break;
}
})
|
3e75b14b404d58c89253ed374f8f3eed45694de3
|
TypeScript
|
Mondei1/DocSort
|
/backend/src/dummyData.ts
| 2.734375
| 3
|
import { Document } from "./entity/document";
import { Tag } from "./entity/tag";
import { User } from "./entity/user";
import { createRandomString } from "./libs/createRandomString";
import { createPasswordHash } from "./libs/createPasswordHash";
export async function insertDummyData() {
const dummyUsers: Array<any> = [
{
username: "Mondei1",
password: "pass"
},
{
username: "spYro",
password: "PASS"
}
]
// Write dummy users into database
for(let dummyUser of dummyUsers) {
const salt: string = createRandomString(16);
const hashedPW: string = await createPasswordHash(dummyUser.password, salt);
await User.create({
username: dummyUser.username,
password: hashedPW,
salt: salt
}).save();
}
const user: User = await User.findOne({where: {username: "Mondei1"}});
// 1. save document
let highestDoc = await Document.findOne({
select: ["primaryNumber"],
order: { primaryNumber: "DESC" }
})
let doc1 = new Document();
if(highestDoc == null) {
doc1.primaryNumber = 1;
} else {
doc1.primaryNumber = highestDoc.primaryNumber + 1;
}
doc1.secondaryNumber = 1;
doc1.user = user;
doc1.fileExtension = "png";
doc1.title = "Rechnung TUI Flitterwochen 2019";
doc1.note = "Rechnung von den Flitterwochen zu den Malediven (Fushifaru) Ende 2019";
// CRYPT: doc1.iv = "0A2wp3fgzhWquOlz";
let tagRechnung = await Tag.create({name: "Rechnung"}).save();
let tagReise = await Tag.create({name: "Reise"}).save();
let tagMahnung = await Tag.create({name: "Mahnung"}).save();
let doc1Tags = [];
doc1Tags.push(tagRechnung, tagReise);
let tags1 = await doc1.tags;
tags1 = doc1Tags;
doc1.mimeType = "image/png";
await doc1.save();
// 2. Document speichern
let doc2 = new Document();
doc2.primaryNumber = doc1.primaryNumber;
doc2.secondaryNumber = doc1.secondaryNumber + 1;
doc2.fileExtension = "png";
doc2.title = "Mahnung TUI";
doc2.note = "Mahnung von TUI von den Flitterwochen zu den Malediven (Fushifaru) Ende 2019";
doc2.user = user;
// CRYPT: doc2.iv = "yUlW6tqGiIG4Ms1K";
let doc2Tags = [];
doc2Tags.push(tagRechnung);
doc2Tags.push(tagMahnung);
let tags2 = await doc2.tags;
tags2 = doc2Tags;
doc2.mimeType = "image/png";
await doc2.save();
}
|
3738021efda01451ddd87dba3b00833cb01177ef
|
TypeScript
|
rikusv/amena-wedding
|
/src/app/manage/sort.pipe.ts
| 2.796875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(items: any[], sorter: {property: string, ascending?: boolean}): any {
function score(invitation: any, eventId: string) {
return invitation.rsvp[eventId] === '' || typeof invitation.rsvp[eventId] === 'undefined' ?
0 : (invitation.rsvp[eventId] < invitation.events[eventId] ? 2 : 1);
}
if (!items || !sorter || !sorter.property) {
return items;
}
const parts = sorter.property.split('/');
if (parts.length === 1) { // direct field sort
const type = typeof items[0][sorter.property];
switch (type) {
case 'boolean':
return items.sort((a, b) => a[sorter.property] ?
(sorter.ascending ? 1 : -1) : (sorter.ascending ? -1 : 1));
case 'string':
return items.sort((a, b) => a[sorter.property] < b[sorter.property] ?
(sorter.ascending ? -1 : 1) : (sorter.ascending ? 1 : -1));
default:
return items;
}
} else if (parts[0] === 'rsvp') {
const eventId = parts[1];
return items.sort((a, b) => {
const aScore = score(a, eventId);
const bScore = score(b, eventId);
return sorter.ascending ?
(aScore >= bScore ? -1 : 1) : (aScore >= bScore ? 1 : -1);
});
} else { // don't know how to sort
return items;
}
}
}
|
f945260305af482b78ccbb403fb4c256207c84f1
|
TypeScript
|
rocketbase-io/rollup-plugin-sequential
|
/src/combine-sync-functions.ts
| 2.515625
| 3
|
export function combineSyncFunctions(name: string, plugins: any[], once: boolean) {
let ranBefore = false;
let lastResult: any = undefined;
return function(this: any, ...params: any) {
if (once && ranBefore) return lastResult;
ranBefore = true;
plugins.forEach(plugin => (lastResult = plugin[name].call(this, ...params)));
return lastResult;
};
}
|
48366f9406b5126ad8d987bc4e4b9bc461dd4e01
|
TypeScript
|
Coffeekraken/coffeekraken
|
/packages/postcss/s-postcss-sugar-plugin/src/node/mixins/float/classes.ts
| 2.796875
| 3
|
import __SInterface from '@coffeekraken/s-interface';
/**
* @name classes
* @as @sugar.float.classes
* @namespace node.mixin.float
* @type PostcssMixin
* @platform postcss
* @status beta
*
* This mixin generate all the float helper classes like ```.s-float:left```, ```.s-float:right```, etc...
*
* @return {Css} The generated css
*
* @snippet @sugar.float.classes
*
* @example css
* \@sugar.float.classes;
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
class postcssSugarPluginFloatClassesInterface extends __SInterface {
static get _definition() {
return {};
}
}
export interface IPostcssSugarPluginFloatClassesParams {}
export { postcssSugarPluginFloatClassesInterface as interface };
export default function ({
params,
atRule,
CssVars,
replaceWith,
}: {
params: Partial<IPostcssSugarPluginFloatClassesParams>;
atRule: any;
CssVars: any;
replaceWith: Function;
}) {
const finalParams: IPostcssSugarPluginFloatClassesParams = {
...params,
};
const vars = new CssVars();
vars.comment(
() => `
/**
* @name Float
* @namespace sugar.style.helpers.float
* @type Styleguide
* @menu Styleguide / Helpers /styleguide/helpers/float
* @platform css
* @status beta
*
* These classes allows you to apply some float styling into your html.
*
* @support chromium
* @support firefox
* @support safari
* @support edge
*
* @install css
* \\@sugar.float.classes;
*
* @cssClass s-float:left Apply the left float style
* @cssClass s-float:right Apply the right float style
* @cssClass s-float:none Apply the none float style
*
* @example html Left
* <div class="s-bg:accent s-clearfix s-p:30 s-radius">
* <div class="s-float:left">I'm a cool float left element</div>
* </div>
*
* @example html Right
* <div class="s-bg:complementary s-clearfix s-p:30 s-radius">
* <div class="s-float:right">I'm a cool float right element</div>
* </div>
*
* @example html None
* <div class="s-bg:error s-p:30 s-radius">
* <div class="s-float:none">I'm a cool float none element</div>
* </div>
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
`,
);
vars.comment(
() => `/**
* @name s-float:left
* @namespace sugar.style.helpers.float
* @type CssClass
* @platform css
* @status beta
*
* This class allows you to apply a "<yellow>left</yellow>" float style to any HTMLElement
*
* @example html
* <div class="s-bg:accent">
* <div class="s-float:left">I'm a cool float left element</div>
* </div>
*/
`,
).code(
`
.s-float-left {
float: left;
}`,
{ type: 'CssClass' },
);
vars.comment(
() => `/**
* @name s-float:right
* @namespace sugar.style.helpers.float
* @type CssClass
* @platform css
* @status beta
*
* This class allows you to apply a "<yellow>right</yellow>" float style to any HTMLElement
*
* @example html
* <div class="s-bg:accent">
* <div class="s-float:right">I'm a cool float right element</div>
* </div>
*/
`,
).code(
`
.s-float-right {
float: right;
}`,
{ type: 'CssClass' },
);
vars.comment(
() => `/**
* @name s-float:none
* @namespace sugar.style.helpers.float
* @type CssClass
* @platform css
* @status beta
*
* This class allows you to apply a "<yellow>none</yellow>" float style to any HTMLElement
*
* @example html
* <div class="s-bg:accent">
* <div class="s-float:none">I'm a cool float none element</div>
* </div>
*/
`,
).code(
`
.s-float-none {
float: none;
}`,
{ type: 'CssClass' },
);
return vars;
}
|
53142aebc94036a3f3b169e41215e4dedc065170
|
TypeScript
|
rudani-c/bank
|
/src/app/pipes/sort.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { CommonUtil } from '../utils/common.util';
@Pipe({
name: 'sort',
})
export class SortPipe implements PipeTransform {
transform(array: any, field: string, order: string): any[] {
if (order == 'asc' || order == 'desc') {
switch (field) {
case 'date':
array.sort((a: any, b: any) =>
CommonUtil.compare(a.dates.valueDate, b.dates.valueDate)
);
break;
case 'name':
array.sort((a: any, b: any) =>
CommonUtil.compare(a.merchant.name, b.merchant.name)
);
break;
case 'amount':
array.sort((a: any, b: any) =>
CommonUtil.compare(
+a.transaction.amountCurrency.amount,
+b.transaction.amountCurrency.amount
)
);
break;
}
}
if (order == 'desc') {
array.reverse();
}
return array;
}
}
|
bd8ac5d449076715ecbe774cb4e611d5382902f4
|
TypeScript
|
motss/jsmodern
|
/src/map/entry.ts
| 2.921875
| 3
|
import type { PrototypeStruct } from '../index.js';
interface Entry<K, V> {
entry(key: K): [K, V];
}
export const entry: PrototypeStruct = {
label: 'entry',
fn: function mapEntry<K, V>(key: K): [] | [K, undefined | V] {
const ctx = this as unknown as Map<K, V>;
const val = !ctx.size ? undefined : ctx.get(key);
return [key, val];
},
};
declare global {
interface Map<K, V> extends Entry<K, V> {}
}
|
0586d36bbb161d3c484e77a66893c9dc6f28a385
|
TypeScript
|
microsoft/PowerBI-visuals-AttributeSlicer
|
/packages/attribute-slicer/src/selection/SelectionManager.ts
| 2.703125
| 3
|
/*
* Copyright (c) Microsoft
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class SelectionManager<T extends ISelectableItem<any>> {
/**
* The current selection
*/
protected internalSelectionDontUseDirectly: T[] = [];
/**
* The brushing selection, the selection that is occuring while the brushing is happening
*/
protected internalBrushingSelection: T[] = [];
/**
* The current key state
*/
protected keyState: IKeyState = {};
/**
* Whether or not the user is currently dragging
*/
protected internalDragging: boolean = false;
/**
* Whether or not we are currently in brush mode
*/
protected internalBrushMode: boolean = false;
/**
* The list of all items
*/
protected internalItems: T[];
private selectionListener: (items: T[]) => unknown;
/**
* The item (pivot point) which the user started shift selecting
*/
private shiftPivot: T;
/**
* The most recent item selected via brush selection
*/
private internalPreviousBrushedItem: T;
private internalSingleSelectDontUse: boolean = false;
/**
* Constructor
*/
constructor(onSelectionChanged?: (items: T[]) => unknown) {
this.selectionListener = onSelectionChanged;
}
/**
* Gets the set of items associated with this manager
*/
public get items(): T[] {
return this.internalItems;
}
/**
* Sets the current set of items
*/
public set items(value: T[]) {
this.internalItems = value || [];
}
/**
* Returns the current selection
*/
public get selection(): T[] {
return this.internalSelectionDontUseDirectly;
}
/**
* Setter for selection
*/
public set selection(value: T[]) {
this.setSelection(value);
}
/**
* Setter for single select mode
*/
public get singleSelect(): boolean {
return this.internalSingleSelectDontUse;
}
/**
* Setter for single select mode
*/
public set singleSelect(value: boolean) {
this.internalSingleSelectDontUse = value;
// Cheat, reset it, this forces a single item to be selected
this.selection = this.selection.slice(0);
}
/**
* Returns the brushing selection
*/
public get brushingSelection(): T[] {
return this.internalBrushingSelection;
}
/**
* Returns true if we are current dragging
*/
public get dragging(): boolean {
return this.internalDragging;
}
/**
* Getter for brushMode
*/
public get brushMode(): boolean {
return this.internalBrushMode;
}
/**
* Setter for brush mode
*/
public set brushMode(value: boolean) {
this.internalBrushMode = value;
}
/**
* Indicates that an item was hovered over
* @returns IBrushSelectionDelta
*/
public itemHovered(item: T): IBrushSelectionDelta<T> {
const delta: IBrushSelectionDelta<T> = { added: [], removed: [] };
if (this.internalDragging && this.internalBrushMode) {
if (
this.internalBrushingSelection.length >= 1 &&
this.items &&
this.items.length
) {
let lowIndex: number;
let highIndex: number;
const newSel: T[] = this.internalBrushingSelection.slice(0);
if (this.findIndex(item, newSel) > -1) {
// remove item if dragging back
newSel.splice(newSel.indexOf(this.internalPreviousBrushedItem), 1);
delta.removed.push(this.internalPreviousBrushedItem);
} else {
// add the item to selection list
newSel.push(item);
delta.added.push(item);
}
newSel.forEach((n: T) => {
const currIndex: number = this.internalItems.indexOf(n);
if (lowIndex === undefined || currIndex < lowIndex) {
lowIndex = currIndex;
}
if (highIndex === undefined || currIndex > highIndex) {
highIndex = currIndex;
}
});
this.internalBrushingSelection = this.items.slice(
lowIndex,
highIndex + 1,
);
} else if (this.findIndex(item, this.internalBrushingSelection) < 0) {
this.internalBrushingSelection.push(item);
delta.added.push(item);
}
this.internalPreviousBrushedItem = item;
}
return delta;
}
/**
* Indicates that an item was clicked
*/
public itemClicked(item: T): void {
// Toggles the selected item out of the selection
const toggleItem: Function = (): void => {
const idx: number = this.findIndex(item);
const newSel: T[] = this.selection.slice(0);
if (idx < 0) {
newSel.push(item);
} else {
newSel.splice(idx, 1);
}
this.selection = newSel;
};
if (!this.keyState.ctrl) {
// If the user just selected the first item
if (this.keyState.shift && !this.shiftPivot) {
this.shiftPivot = item;
}
if (this.keyState.shift && this.items && this.items.length) {
const idx: number = this.findIndex(this.shiftPivot, this.items);
const lastIdx: number = this.findIndex(item, this.items);
// The selection is the range between the first and second indexes
this.selection = this.items.slice(
idx < lastIdx ? idx : lastIdx,
(idx < lastIdx ? lastIdx : idx) + 1,
);
} else if (this.internalBrushMode) {
// If the user is in "brush" mode, but just single clicks an item,
// then just deselect it, otherwise set the item
this.selection =
this.selection.length === 1 && this.selection[0].id === item.id
? []
: [item];
} else {
toggleItem();
}
} else {
toggleItem();
}
}
/**
* Lets the selection manager that a key was pressed
*/
public keyPressed(state: IKeyState): void {
this.keyState.ctrl = state.ctrl;
if (this.keyState.shift !== state.shift) {
// User started pressing shift
if (state.shift) {
this.shiftPivot = this.selection[this.selection.length - 1];
} else {
delete this.shiftPivot;
}
this.keyState.shift = state.shift;
}
}
/**
* Indicates that we are starting to drag
*/
public startDrag(): void {
this.internalDragging = true;
this.internalBrushingSelection = [];
}
/**
* Indicates that we are ending a drag operation
*/
public endDrag(): void {
if (this.internalDragging) {
this.internalDragging = false;
if (this.brushMode) {
if (this.keyState.ctrl) {
this.internalBrushingSelection = [
...this.internalBrushingSelection,
...this.selection,
];
}
this.selection = this.internalBrushingSelection.slice(0);
}
this.internalBrushingSelection = [];
}
}
/**
* Finds the given item in the list of selections
*/
protected findIndex(item: T, list?: T[]): number {
if (!list) {
list = this.selection;
}
for (let i: number = 0; i < list.length; i += 1) {
const toCompare: T = list[i];
if (toCompare.id === item.id) {
return i;
}
}
return -1;
}
/**
* Internal method for setting the selection
*/
protected setSelection(value: T[]): boolean {
value = value || [];
// We are single select, limit to one
if (this.singleSelect && value.length) {
value = [value[value.length - 1]];
}
const oldSelection: T[] = this.selection || [];
const newSelection: T[] = value;
// Are there any selected items which do not appear in the new selection
let hasChanged: boolean =
oldSelection.filter(
(n: T) => newSelection.filter((m: T) => n.id === m.id).length === 0,
).length > 0;
// Are there any selected items which do not appear in the old selection
hasChanged =
hasChanged ||
newSelection.filter(
(n: T) => oldSelection.filter((m: T) => n.id === m.id).length === 0,
).length > 0;
if (hasChanged) {
this.internalSelectionDontUseDirectly = value;
if (this.selectionListener) {
this.selectionListener(value);
}
return true;
}
return false;
}
}
/**
* Represents an item that can be used with the selection manager
*/
export interface ISelectableItem<T> {
id: string;
}
export interface IKeyState {
/**
* If ctrl is being held down
*/
ctrl?: boolean;
/**
* If shift is being pressed
*/
shift?: boolean;
}
export interface IBrushSelectionDelta<T> {
/**
* Items added to the brush selection
*/
added: T[];
/**
* Items removed from the brush selection
*/
removed: T[];
}
|
becac011e16994afe331264dfc69b0a26eb58f26
|
TypeScript
|
vocodes/audio-sample-abtest
|
/frontend/src/audio/Experiment.ts
| 2.84375
| 3
|
export class FileDescriptor {
name: string;
relative_path: string;
constructor(name: string, relative_path: string) {
this.name = name;
this.relative_path = relative_path;
}
static fromJson(json: any) : FileDescriptor {
return new FileDescriptor(json.name, json.relative_path);
}
getWavUrl() : string {
return `http://localhost:5000/wav/${this.relative_path}`
}
}
export class Experiment {
file_a: FileDescriptor;
file_b: FileDescriptor;
constructor(file_a: FileDescriptor, file_b: FileDescriptor) {
this.file_a = file_a;
this.file_b = file_b;
}
static fromJson(json: any) : Experiment {
const fd_a = FileDescriptor.fromJson(json.file_a);
const fd_b = FileDescriptor.fromJson(json.file_b);
return new Experiment(fd_a, fd_b);
}
}
export enum ExperimentOption {
A,
B,
}
|
591a60a096283ceeda96f80bd289a2778d2870be
|
TypeScript
|
lbwa/docs-server
|
/src/generator/static.ts
| 2.515625
| 3
|
import BaseGenerator = require('./base')
import path = require('path')
const Mtj = require('mark-to-json')
const formatDate = require('../utils/format-date')
type normalize = (path: string) => string
class StaticGenerator extends BaseGenerator {
private __normalize: normalize
constructor () {
super()
}
async run ({cwd, normalize}: {cwd: string, normalize: normalize}) {
this.cwd = cwd
this.__normalize = normalize
try {
await this.parser()
} catch (e) {
console.error(e)
}
}
async iterator (paths: string[]) {
// read every markdown
paths.map(async (singlePath: string) => {
let content: string
let origin: string
try {
// 防止将 {} 解析为代码块,应该解析为对象
({ origin, content } = await this.getContent(singlePath))
} catch (err) {
console.error(err)
}
const normalized = this.normalizeRoute(origin)
new Mtj({
token: content,
dest: path.resolve(process.cwd(), `./${normalized}.json`),
extraHeader: {
errno: 0,
to: normalized
},
contentKey: 'content',
filter (schema: {[key: string]: any}) {
schema.date = formatDate(schema.date)
}
})
})
}
normalizeRoute (origin: string) {
return this.__normalize ? this.__normalize(origin) : defaultNormalize(origin)
}
}
export = new StaticGenerator()
function defaultNormalize (origin: string) {
return origin.replace(/\.md$/, '')
}
|
f19fe9e58139b23983077849ccb3da6c0d6594a2
|
TypeScript
|
desktop/desktop
|
/app/test/unit/find-forked-remotes-to-prune-test.ts
| 2.578125
| 3
|
import { findForkedRemotesToPrune } from '../../src/lib/stores/helpers/find-forked-remotes-to-prune'
import { Branch, BranchType } from '../../src/models/branch'
import { CommitIdentity } from '../../src/models/commit-identity'
import { GitHubRepository } from '../../src/models/github-repository'
import { PullRequest } from '../../src/models/pull-request'
import { IRemote } from '../../src/models/remote'
import { gitHubRepoFixture } from '../helpers/github-repo-builder'
function createSamplePullRequest(
gitHubRepository: GitHubRepository,
userName: string,
baseBranchName: string
) {
return new PullRequest(
new Date(),
'desktop',
1,
{
ref: 'main',
sha: 'deadbeef',
gitHubRepository,
},
{
ref: baseBranchName,
sha: 'deadbeef',
gitHubRepository,
},
userName,
false,
'sample body'
)
}
function createSampleBranch(name: string, upstream: string | null) {
const author = new CommitIdentity(
'someone',
'someone@somewhere.com',
new Date()
)
const branchTip = {
sha: '300acef',
author,
}
return new Branch(name, upstream, branchTip, BranchType.Local, '')
}
describe('findForkedRemotesToPrune', () => {
const TestUserName = 'sergiou87'
const OriginRemote = 'origin'
const NonGitHubDesktopRemote = 'non-github-desktop-remote'
const GitHubDesktopRemoteWithLocalBranch = 'github-desktop-niik'
const GitHubDesktopRemoteWithPullRequest = `github-desktop-${TestUserName}`
const remotes = [
{
name: OriginRemote,
url: 'https://github.com/desktop/desktop.git',
},
{
name: NonGitHubDesktopRemote,
url: 'https://github.com/fakeuser/desktop.git',
},
{
name: GitHubDesktopRemoteWithLocalBranch,
url: 'https://github.com/niik/desktop.git',
},
{
name: GitHubDesktopRemoteWithPullRequest,
url: `https://github.com/${TestUserName}/desktop.git`,
},
]
function getNamesFromRemotes(remotes: readonly IRemote[]) {
return remotes.map(r => r.name)
}
it('never prunes remotes not created by the app', () => {
const remotesToPrune = findForkedRemotesToPrune(remotes, [], [])
const names = getNamesFromRemotes(remotesToPrune)
expect(names).not.toBeEmpty()
expect(names).not.toContain(OriginRemote)
expect(names).not.toContain(NonGitHubDesktopRemote)
})
it('never prunes remotes with local branches', () => {
const allBranches = [
createSampleBranch(
'app-store-refactor',
`${GitHubDesktopRemoteWithLocalBranch}/app-store-refactor`
),
]
const remotesToPrune = findForkedRemotesToPrune(remotes, [], allBranches)
expect(getNamesFromRemotes(remotesToPrune)).not.toContain(
GitHubDesktopRemoteWithLocalBranch
)
})
it('never prunes remotes with pull requests', () => {
const forkRepository = gitHubRepoFixture({
name: 'desktop',
owner: TestUserName,
})
const openPRs = [
createSamplePullRequest(forkRepository, TestUserName, 'my-cool-feature'),
]
const remotesToPrune = findForkedRemotesToPrune(remotes, openPRs, [])
expect(getNamesFromRemotes(remotesToPrune)).not.toContain(
GitHubDesktopRemoteWithPullRequest
)
})
it('prunes remotes without pull requests or local branches', () => {
const remotesToPrune = findForkedRemotesToPrune(remotes, [], [])
const remoteNames = getNamesFromRemotes(remotesToPrune)
expect(remoteNames).toContain(GitHubDesktopRemoteWithPullRequest)
expect(remoteNames).toContain(GitHubDesktopRemoteWithLocalBranch)
})
})
|
83e6f6a389f588c18147825b8dccfe0b55481bea
|
TypeScript
|
Ragini-1004/Angular
|
/Assignment 2/1_Ass2.ts
| 3.59375
| 4
|
function Maximum(num:number[]):number
{
var iMax:number=0;
for(var i=0; i< num.length; i++)
{
if(num[i]> iMax)
{
iMax=num[i];
}
}
return iMax;
}
var arr:number[]= new Array(8);
arr = [23,89,6,29,56,45,77,32 ] ;
var iret=Maximum(arr);
console.log("Maximum number from array is "+iret);
|
8a02cdc3f36d81cb4013fd356f2a05afbf024b24
|
TypeScript
|
enliberte/patterns
|
/behavioral/mediator/src/scheme/mediator/Mediator.ts
| 2.75
| 3
|
import IMediator from "./IMediator";
import SenderA from "../senders/SenderA";
import SenderB from "../senders/SenderB";
import SenderC from "../senders/SenderC";
import SenderD from "../senders/SenderD";
export default class Mediator implements IMediator {
senderA: SenderA;
senderB: SenderB;
senderC: SenderC;
senderD: SenderD;
constructor(senderA: SenderA, senderB: SenderB, senderC: SenderC, senderD: SenderD) {
this.senderA = senderA;
this.senderB = senderB;
this.senderC = senderC;
this.senderD = senderD;
this.senderA.setMediator(this);
this.senderB.setMediator(this);
this.senderC.setMediator(this);
this.senderD.setMediator(this);
}
notify(event: string): void {
switch (event) {
case 'A':
this.reactOnA();
break;
case 'B':
this.reactOnB();
break;
case 'C':
this.reactOnC();
break;
case 'D':
this.reactOnD();
break;
}
}
reactOnA(): void {
console.log('Notification from A');
this.senderB.methodB();
this.senderC.methodC();
this.senderD.methodD();
}
reactOnB(): void {
console.log('Notification from B');
this.senderA.methodA();
this.senderC.methodC();
this.senderD.methodD();
}
reactOnC(): void {
console.log('Notification from C');
this.senderA.methodA();
this.senderB.methodB();
this.senderD.methodD();
}
reactOnD(): void {
console.log('Notification from D');
this.senderA.methodA();
this.senderB.methodB();
this.senderC.methodC();
}
}
|
a4be43e768efc4cb667d33dff2792a2875cd6ad5
|
TypeScript
|
blinker-iot/blinker-js
|
/example/aligenie/example_aligenie_sensor.ts
| 2.671875
| 3
|
import { BlinkerDevice } from '../../lib/blinker';
import { AliGenie, VA_TYPE } from '../../lib/voice-assistant';
let device = new BlinkerDevice('');
let aliGenie = device.addVoiceAssistant(new AliGenie(VA_TYPE.SENSOR));
device.ready().then(() => {
// 查询传感器状态
aliGenie.stateQuery.subscribe(message => {
// console.log(message.data);
message.humi(10).temp(10).pm25(10).update();
})
device.dataRead.subscribe(message => {
console.log('otherData:', message);
})
device.builtinSwitch.change.subscribe(message => {
console.log('builtinSwitch:', message);
device.builtinSwitch.setState(turnSwitch()).update();
})
})
/*
以下为测试用函数
*/
let switchState = false
function turnSwitch() {
switchState = !switchState
device.log("切换设备状态为" + (switchState ? 'on' : 'off'))
return switchState ? 'on' : 'off'
}
|
8ec1305b6c48f7cf256abc1acb41d437cc35817f
|
TypeScript
|
royaltm/node-murmurhash-native
|
/test/types/tap.d.ts
| 2.625
| 3
|
/* a small restrictive subset declaration for tap */
declare module 'tap' {
export interface Test {
end(): void;
error(error: Error, message?: string, extra?: any): void;
ok(obj: any, message?: string, extra?: any): void;
plan(count: number): void;
strictEqual<T>(found: T, wanted: T, message?: string, extra?: any): void;
deepEqual<T>(found: T, wanted: T, message?: string, extra?: any): void;
test(label: string, f: (t: Test) => void): void;
test(label: string, opt: Object, f: (t: Test) => PromiseLike<any>): void;
test(label: string, opt: Object, f: (t: Test) => void): void;
threw(error: any): any;
type(object: any, type: string|Function, message?: string, extra?: any): void;
}
export function test(label: string, f: (t: Test) => void): void;
export function test(label: string, opt: Object, f: (t: Test) => void): void;
export function test(label: string, opt: Object, f: (t: Test) => PromiseLike<any>): void;
}
|
dea86f8a3f5529e73fee281b477f310417a364c2
|
TypeScript
|
ctx-core/function
|
/src/slice_arg_a_/index.d.ts
| 2.578125
| 3
|
import type { a_nowrap_T } from '../_types'
/**
* Returns a function where the arguments to the wrapped function are sliced with begin_idx & end_idx.
*/
export declare function slice_arg_a_<
In extends unknown = unknown,
Out extends unknown[] = unknown[]
>(
fn:slice_arg_a_fn_T<In, Out>, begin_idx?:number, end_idx?:number
):slice_arg_a_T<In, Out>
export declare type slice_arg_a_fn_T<
In extends unknown = unknown,
Out extends unknown[] = unknown[]
> = (
arg_a:a_nowrap_T<In>
)=>Out
export declare type slice_arg_a_T<
In extends unknown = unknown,
Out extends unknown[] = unknown[]
> = (
arg_a:a_nowrap_T<In>
)=>Out
export {
slice_arg_a_ as slice_arg_a1_fn,
slice_arg_a_ as _slice_arg_a1,
slice_arg_a_ as _arg_a1__slice,
slice_arg_a_ as _a1__arg__slice,
}
|
a976c1e656253fc49595252b20e7aee15f22d379
|
TypeScript
|
DBetta/cloud-service-discovery
|
/src/cloud/consul/utils/consul-utils.ts
| 2.578125
| 3
|
export class ConsulUtils {
static getMetadata(tags: string[]): Map<string, string> {
const metadata = new Map<string, string>();
for (const tag of tags) {
const parts = tag.split('=');
metadata.set(parts[0], parts[1]);
}
return metadata;
}
}
|
14ee02051527416175feedf4ede1cd2f681e60cc
|
TypeScript
|
ourcade/coronavirus-pop-phaser
|
/src/game/BallGrid.ts
| 2.828125
| 3
|
import Phaser from 'phaser'
import BallLayoutData, {
Red, Gre, Blu, Yel
} from './BallLayoutData'
import BallColor, { colorIsMatch } from './BallColor'
import { Subject } from 'rxjs'
import BallState from '~/consts/BallState'
interface IGridPosition
{
row: number
col: number
}
type IBallOrNone = IBall | undefined
class RowList extends Array<IBallOrNone>
{
isStaggered = false
}
export default class BallGrid
{
private scene: Phaser.Scene
private pool: IStaticBallPool
private layoutData?: BallLayoutData
private size: Phaser.Structs.Size
private grid: IBallOrNone[][] = []
private ballsCount = 0
private ballsDestroyedSubject = new Subject<number>()
private ballWillBeDestroyed = new Subject<IBall>()
private orphanWillBeDestroyed = new Subject<IBall>()
private ballsAddedSubject = new Subject<number>()
private ballAttachedSubject = new Subject<IBall>()
get totalBalls()
{
return this.ballsCount
}
get height()
{
this.cleanUpEmptyRows()
return this.grid.length * this.ballInterval
}
get ballInterval()
{
return this.size.height * 0.8
}
get bottom()
{
if (this.grid.length <= 0)
{
return 0
}
const idx = this.grid.length - 1
const ball = this.grid[idx].find(n => n)
if (!ball)
{
return 0
}
return ball.y + ball.radius
}
constructor(scene: Phaser.Scene, pool: IStaticBallPool)
{
this.scene = scene
this.pool = pool
const sample = this.pool.spawn(0, 0)
this.size = new Phaser.Structs.Size(sample.width, sample.height)
this.pool.despawn(sample)
}
destroy()
{
this.ballsDestroyedSubject.complete()
this.ballWillBeDestroyed.complete()
}
setLayoutData(layout: BallLayoutData)
{
this.layoutData = layout
return this
}
onBallsDestroyed()
{
return this.ballsDestroyedSubject.asObservable()
}
onBallWillBeDestroyed()
{
return this.ballWillBeDestroyed.asObservable()
}
onOrphanWillBeDestroyed()
{
return this.orphanWillBeDestroyed.asObservable()
}
onBallsAdded()
{
return this.ballsAddedSubject.asObservable()
}
onBallAttached()
{
return this.ballAttachedSubject.asObservable()
}
/**
*
* @param x x position at collision with grid
* @param y y position at collision with grid
* @param color color ball
* @param gridBall ball in grid that was collided with
* @param bvx x velocity of ball at collision
* @param bvy y velocity of ball at collision
*/
async attachBall(x: number, y: number, color: BallColor, gridBall: IBall, bvx: number, bvy: number)
{
const width = this.size.width
const radius = width * 0.5
const vel = new Phaser.Math.Vector2(bvx, bvy)
vel.normalize()
// the position on the ball in the direction it was heading
const hx = x + (vel.x * radius)
const cellX = gridBall.x
const cellY = gridBall.y
const dx = hx - cellX
let tx = dx <= 0 ? cellX - radius : cellX + radius
// offset by vertical interval
const interval = this.ballInterval
const dy = y - cellY
let ty = dy >= 0 ? cellY + interval : cellY - interval
// place on same row
const sameRow = Math.abs(dy) <= radius
if (sameRow)
{
ty = cellY
// adjust x to be next to
tx = dx <= 0 ? tx - radius : tx + radius
}
const newBall = this.pool.spawn(x, y)
.setColor(color)
const { row, col } = this.findRowAndColumns(gridBall)
let bRow = -1
if (sameRow)
{
bRow = row
}
else
{
if (ty < cellY)
{
bRow = row - 1
}
else
{
bRow = row + 1
}
}
let bCol = -1
if (sameRow)
{
bCol = tx < cellX ? col - 1 : col + 1
}
else
{
const isStaggered = this.isRowStaggered(bRow)
if (isStaggered)
{
bCol = tx < cellX ? col : col + 1
}
else
{
bCol = tx < cellX ? col - 1 : col
}
}
this.insertAt(bRow, bCol, newBall)
const matches = this.findMatchesAt(bRow, bCol, color)
// minimum 3 matches required
if (matches.length < 3)
{
this.ballsCount += 1
this.ballsAddedSubject.next(1)
this.ballAttachedSubject.next(newBall)
this.animateAttachBounceAt(bRow, bCol, tx, ty, newBall)
return
}
// remove them from grid immediately but not visually...
// remove visually after animation below
// we want to remove from grid immediately so that other
// processes that add new rows can run normally
const matchedBalls = this.removeFromGrid(matches)
const orphanPositions = this.findOrphanedBalls()
const orphans = this.removeFromGrid(orphanPositions)
.map(ball => {
ball.setActive(false)
this.scene.physics.world.remove(ball.body)
return ball
})
this.cleanUpEmptyRows()
await new Promise(resolve => {
this.scene.tweens.add({
targets: newBall,
y: ty,
x: tx,
duration: 50,
ease: 'Back.easeOut',
onComplete: function () {
resolve()
}
})
})
const body = newBall.body as Phaser.Physics.Arcade.StaticBody
body.updateFromGameObject()
// remove matched balls
matchedBalls.forEach(ball => {
this.ballWillBeDestroyed.next(ball)
this.pool.despawn(ball)
})
const destroyedCount = matches.length + orphans.length
this.ballsDestroyedSubject.next(destroyedCount)
this.ballsCount -= destroyedCount
if (orphans.length > 0)
{
await this.animateOrphans(orphans)
}
}
generate(rows = 6)
{
if (!this.layoutData)
{
return this
}
for (let i = 0; i < rows; ++i)
{
this.spawnRow()
}
return this
}
moveBy(dy: number)
{
if (this.pool.countActive() === 0)
{
return this
}
const balls = this.pool.getChildren()
const count = balls.length
for (let i = 0; i < count; ++i)
{
const b = balls[i] as IBall
b.y += dy
const body = b.body as Phaser.Physics.Arcade.StaticBody
body.updateFromGameObject()
}
return this
}
spawnRow()
{
if (!this.layoutData)
{
return -1
}
const row = this.layoutData.getNextRow()
const count = row.length
if (count <= 0)
{
return 0
}
this.addRowToFront(row)
this.ballsCount += count
this.ballsAddedSubject.next(count)
return row.length
}
private addRowToFront(row: string[])
{
const middle = this.scene.scale.width * 0.5
const width = this.size.width
const radius = width * 0.5
const verticalInterval = this.ballInterval
const count = row.length
const gridRow = new RowList()
this.grid.unshift(gridRow)
const halfCount = count * 0.5
let x = middle - (halfCount * width) + (radius * 0.5)
let y = 0
if (this.grid.length <= 1)
{
gridRow.isStaggered = true
}
else
{
const rowList = this.grid[1] as RowList
gridRow.isStaggered = !rowList.isStaggered
const anyItem = rowList.find(n => n)
if (anyItem)
{
y = anyItem.y - verticalInterval
}
}
if (gridRow.isStaggered)
{
x += radius
// to handle the offset
gridRow.push(undefined)
}
row.forEach(colorCode => {
const b = this.pool.spawn(x, y)
gridRow.push(b)
switch (colorCode)
{
default:
case undefined:
break
case Red:
b!.setColor(BallColor.Red)
break
case Blu:
b!.setColor(BallColor.Blue)
break
case Gre:
b!.setColor(BallColor.Green)
break
case Yel:
b!.setColor(BallColor.Yellow)
break
}
x += width
})
if (!gridRow.isStaggered)
{
// pad end with space for offset
gridRow.push(undefined)
}
}
private removeFromGrid(matches: IGridPosition[])
{
const balls: IBall[] = []
const size = matches.length
for (let i = 0; i < size; ++i)
{
const { row, col } = matches[i]
const ball = this.getAt(row, col)
if (!ball)
{
// should never be the case..
console.warn(`detroyMatches: match not found...`)
continue
}
this.grid[row][col] = undefined
balls.push(ball)
}
return balls
}
private async animateOrphans(orphans: IBall[])
{
// move down and fade out
const timeline = this.scene.tweens.timeline()
const bottom = this.scene.scale.height * 0.9
const tasks = orphans.map(orphan => {
const y = orphan.y
const dy = bottom - y
const duration = dy * 0.75
return new Promise(resolve => {
timeline.add({
targets: orphan,
y: y + dy,
offset: 0,
duration,
onComplete: function () {
// @ts-ignore
this.ballWillBeDestroyed.next(orphan)
// @ts-ignore
this.orphanWillBeDestroyed.next(orphan)
// @ts-ignore
this.pool.despawn(orphan)
resolve()
},
onCompleteScope: this
})
})
})
timeline.play()
await Promise.all(tasks)
}
private animateAttachBounceAt(row: number, col: number, tx: number, ty: number, newBall: IBall)
{
// https://github.com/photonstorm/phaser/blob/v3.22.0/src/math/easing/EaseMap.js
const timeline = this.scene.tweens.createTimeline()
timeline.add({
targets: newBall,
y: ty - 5,
duration: 50
})
timeline.add({
targets: newBall,
x: tx,
duration: 100,
offset: 0
})
timeline.add({
targets: newBall,
y: ty,
duration: 50,
ease: 'Back.easeOut',
onComplete: () => {
const body = newBall.body as Phaser.Physics.Arcade.StaticBody
body.updateFromGameObject()
}
})
timeline.play()
this.jiggleNeighbors(row, col)
}
private findRowAndColumns(ball: IBall)
{
// search from the bottom
const size = this.grid.length
for (let i = size - 1; i >= 0; --i)
{
const row = this.grid[i]
const colIdx = row.findIndex(b => b === ball)
if (colIdx < 0)
{
continue
}
return {
row: i,
col: colIdx
}
}
return {
row: -1,
col: -1
}
}
private insertAt(row: number, col: number, ball: IBall)
{
if (row >= this.grid.length)
{
const count = row - (this.grid.length - 1)
for (let i = 0; i < count; ++i)
{
const rowList = new RowList()
const prevRow = this.grid[row + i - 1] as RowList
rowList.isStaggered = !prevRow.isStaggered
this.grid.push(rowList)
}
}
const rowList = this.grid[row]
for (let i = 0; i <= col; ++i)
{
if (rowList.length <= i)
{
rowList[i] = undefined
}
}
rowList[col] = ball
}
private getAt(row: number, col: number)
{
if (row < 0)
{
return null
}
if (row > this.grid.length - 1)
{
return null
}
const rowList = this.grid[row]
return rowList[col]
}
private findOrphanedBalls()
{
// find all connected balls starting from the top row
const connected = new Set<IBall>()
const rootPositions = this.grid[0]
.map((n, idx) => {
if (!n)
{
return undefined
}
connected.add(n)
return { row: 0, col: idx }
})
.filter(n => n) as IGridPosition[]
rootPositions.forEach(({ row, col }) => {
this.findMatchesAt(row, col, BallColor.Any, connected)
})
// any balls that are NOT in the connected set are orphaned
// ignore the root row at index 0; they can never be "orphaned"
const orphans: IGridPosition[] = []
const count = this.grid.length
for (let row = 1; row < count; ++row)
{
const list = this.grid[row]
for (let col = 0; col < list.length; ++col)
{
const ball = list[col]
if (!ball)
{
continue
}
if (connected.has(ball))
{
continue
}
orphans.push({
row, col
})
}
}
return orphans
}
private findMatchesAt(row: number, col: number, color: BallColor, found: Set<IBall> = new Set())
{
// breadth-first search method
const isStaggered = this.isRowStaggered(row)
const adjacentMatches: IGridPosition[] = []
// top left
if (isStaggered)
{
const tl = this.getAt(row - 1, col - 1)
if (tl && colorIsMatch(tl.color, color) && !found.has(tl))
{
adjacentMatches.push({
row: row - 1,
col: col - 1
})
found.add(tl)
}
}
// top
const t = this.getAt(row - 1, col)
if (t && colorIsMatch(t.color, color) && !found.has(t))
{
adjacentMatches.push({
row: row - 1,
col
})
found.add(t)
}
// top right
if (!isStaggered)
{
const tr = this.getAt(row - 1, col + 1)
if (tr && colorIsMatch(tr.color, color) && !found.has(tr))
{
adjacentMatches.push({
row: row - 1,
col: col + 1
})
found.add(tr)
}
}
// right
const r = this.getAt(row, col + 1)
if (r && colorIsMatch(r.color, color) && !found.has(r))
{
adjacentMatches.push({
row,
col: col + 1
})
found.add(r)
}
// bottom right
if (!isStaggered)
{
const br = this.getAt(row + 1, col + 1)
if (br && colorIsMatch(br.color, color) && !found.has(br))
{
adjacentMatches.push({
row: row + 1,
col: col + 1
})
found.add(br)
}
}
// bottom
const b = this.getAt(row + 1, col)
if (b && colorIsMatch(b.color, color) && !found.has(b))
{
adjacentMatches.push({
row: row + 1,
col
})
found.add(b)
}
// bottom left
if (isStaggered)
{
const bl = this.getAt(row + 1, col - 1)
if (bl && colorIsMatch(bl.color, color) && !found.has(bl))
{
adjacentMatches.push({
row: row + 1,
col: col - 1
})
found.add(bl)
}
}
// left
const l = this.getAt(row, col - 1)
if (l && colorIsMatch(l.color, color) && !found.has(l))
{
adjacentMatches.push({
row,
col: col - 1
})
found.add(l)
}
adjacentMatches.forEach(pos => {
this.findMatchesAt(pos.row, pos.col, color, found)
.forEach(obj => adjacentMatches.push(obj))
})
const missing = adjacentMatches.find(({ row, col }) => {
return !this.getAt(row, col)
})
if (missing)
{
console.dir(missing)
}
return adjacentMatches
}
private jiggleNeighbors(sourceRow: number, sourceCol: number)
{
const sourceBall = this.getAt(sourceRow, sourceCol)
const firstNeightbors = this.getNeighbors(sourceRow, sourceCol)
const secondTop = sourceRow - 1
const secondNeighbors = firstNeightbors.find(({ row }) => row === secondTop)
? this.getNeighbors(secondTop, sourceCol)
: []
const degrees = [
firstNeightbors,
secondNeighbors
]
const size = degrees.length
for (let i = 0; i < size; ++i)
{
const deg = degrees[i]
for (let j = 0; j < deg.length; ++j)
{
const { row, col } = deg[j]
const ball = this.getAt(row, col)
if (!ball || ball === sourceBall)
{
continue
}
const factor = (size - i) / size
const movement = 10 * factor
const timeline = this.scene.tweens.createTimeline()
const y = ball.y
timeline.add({
targets: ball,
y: y - movement,
duration: 50
})
timeline.add({
targets: ball,
y,
duration: 50,
ease: 'Back.easeOut'
})
timeline.play()
}
}
}
private getNeighbors(row: number, col: number, includeBottom = false)
{
const positions = this.getNeighborPositions(row, col, 1, includeBottom)
const neighbors = positions.map(({ row, col }) => {
const n = this.getAt(row, col)
if (!n)
{
return undefined
}
return { row, col }
})
.filter(n => n)
return neighbors as { row: number, col: number }[]
}
private getNeighborPositions(row: number, col: number, degrees = 1, includeBottom = false)
{
const positions = [
{ row: row, col: col - degrees }, // left
{ row: row, col: col + degrees }, // right
{ row: row - degrees, col: col }, // top
{ row: row - degrees, col: col - degrees }, // top left
{ row: row - degrees, col: col + degrees}, // top right
]
if (includeBottom)
{
positions.push({ row: row + degrees, col: col }) // bottom
positions.push({ row: row + degrees, col: col - degrees }) // bottom left
positions.push({ row: row + degrees, col: col + degrees }) // bottom right
}
return positions
}
private isRowStaggered(row: number)
{
if (row >= this.grid.length - 1)
{
// if asking about a row that has not been created yet
// check row above and invert
const rowList = this.grid[row - 1] as RowList
return !rowList.isStaggered
}
const rowList = this.grid[row] as RowList
return rowList.isStaggered
}
private cleanUpEmptyRows()
{
const size = this.grid.length
for (let i = size - 1; i >= 0; --i)
{
const row = this.grid[i]
if (row.find(n => n))
{
return
}
this.grid.pop()
}
}
}
|
5d6a4ea3e7e1f2ba7f31bf48b41bbd198155e054
|
TypeScript
|
theirish81/dbsheets
|
/src/actions/SetVarAction.ts
| 2.671875
| 3
|
import { AbstractAction } from "./AbstractAction";
import { Op } from "../Op";
/**
* Sets a variable
*/
export class SetVarAction extends AbstractAction {
evaluate(params : any) : Promise<AbstractAction> {
return new Promise((resolve,reject)=> {
if(params.first){
this.scope[params.var] = Op.fetchValue(params.ds.getData()[0],params.first)
}
if(params.multiple){
this.scope[params.var] = params.ds.getData().map((it : any) => Op.fetchValue(it,params.multiple))
}
return resolve(this)
})
}
}
|
c3bcf1bfd9f032b6f9ff8c16fc5efb6709727cff
|
TypeScript
|
FlorianJansen1337/ScrimBuxBot
|
/src/cronjobs/monthly.ts
| 2.546875
| 3
|
import { CronJob } from 'cron';
import { Balance, Contract } from "../helper/types";
import * as fs from 'fs';
const contracts = require('../../data/contracts.json') as Contract[];
const balances = require('../../data/balances.json') as Balance[];
export const monthly = new CronJob('0 0 1 * *', function () {
payOutWage();
}, null, true, 'Europe/Berlin');
const payOutWage = () => {
fs.writeFileSync('./data/backup/balances.json.backup', JSON.stringify(balances, null, 2));
contracts.forEach((contract: Contract) => {
let balanceIndex = balances.findIndex((item: Balance) => item.userID === contract.userID)
if (balanceIndex > -1)
balances.find((item: Balance) => item.userID === contract.userID)!.amount += contract.paycheck.wage;
else
balances.push({ userID: contract.userID, amount: contract.paycheck.wage } as Balance)
});
fs.writeFileSync('./data/balances.json', JSON.stringify(balances, null, 2));
console.log("distributed monthly wage")
};
|
74bd95fdca20fbc372679ceec5ad5885bf7576b6
|
TypeScript
|
Jhonnyc/jaebook-server
|
/src/services/PostCommentService.ts
| 2.515625
| 3
|
import { Service } from "typedi";
import { InjectRepository } from "typeorm-typedi-extensions";
import { PostComment } from "../entities/PostComment";
import { PostCommentRepository } from "../repositories/PostCommentRepository";
import {
CreatePostCommentDto,
UpdatePostCommentDto,
} from "../dtos/PostCommentDto";
@Service()
export class PostCommentService {
constructor(
@InjectRepository()
private postCommentRepository: PostCommentRepository,
) {}
public async createPostComment(
postId: string,
createPostCommentDto: CreatePostCommentDto,
userId: string,
): Promise<PostComment> {
const postComment = createPostCommentDto.toEntity();
postComment.postId = postId;
postComment.userId = userId;
return await this.postCommentRepository.save(postComment);
}
public async getCommentByPostId(postId: string): Promise<PostComment[]> {
return this.postCommentRepository.getCommentsByPostId(postId);
}
public async updatePostComment(
postId: string,
commentId: string,
updatePostCommentDto: UpdatePostCommentDto,
userId: string,
): Promise<PostComment> {
const postCommentToUpdate = await this.postCommentRepository.getCommentById(
postId,
commentId,
);
if (postCommentToUpdate?.userId === userId) {
postCommentToUpdate.text = updatePostCommentDto.text;
return await this.postCommentRepository.save(postCommentToUpdate);
}
return null;
}
public async deletePostComment(
postId: string,
commentId: string,
userId: string,
): Promise<boolean> {
const postCommentToDelete = await this.postCommentRepository.getCommentById(
postId,
commentId,
);
if (postCommentToDelete?.userId === userId) {
await this.postCommentRepository.delete({ id: commentId });
return true;
}
return false;
}
}
|
5c98c9315a4b71e0baf4b4be470ee0afa888a597
|
TypeScript
|
angelgadea/pw-component-frontend
|
/pw-cp-frontend/src/app/shared/pipes/capitalize-first-letter.pipe.ts
| 2.609375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalizeFirstLetter'
})
export class CapitalizeFirstLetterPipe implements PipeTransform {
transform(text: string): any {
text = text.toLowerCase();
return text[0].toUpperCase() + text.substr(1).toLowerCase();
}
}
|
2d7628ec905cbf899055057aca169821e0e0e602
|
TypeScript
|
angular/angular
|
/packages/compiler-cli/src/ngtsc/annotations/common/src/api.ts
| 3.09375
| 3
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Resolves and loads resource files that are referenced in Angular metadata.
*
* Note that `preload()` and `load()` take a `resolvedUrl`, which can be found
* by calling `resolve()`. These two steps are separated because sometimes the
* resolved URL to the resource is needed as well as its contents.
*/
export interface ResourceLoader {
/**
* True if this resource loader can preload resources.
*
* Sometimes a `ResourceLoader` is not able to do asynchronous pre-loading of resources.
*/
canPreload: boolean;
/**
* If true, the resource loader is able to preprocess inline resources.
*/
canPreprocess: boolean;
/**
* Resolve the url of a resource relative to the file that contains the reference to it.
* The return value of this method can be used in the `load()` and `preload()` methods.
*
* @param url The, possibly relative, url of the resource.
* @param fromFile The path to the file that contains the URL of the resource.
* @returns A resolved url of resource.
* @throws An error if the resource cannot be resolved.
*/
resolve(file: string, basePath: string): string;
/**
* Preload the specified resource, asynchronously. Once the resource is loaded, its value
* should be cached so it can be accessed synchronously via the `load()` method.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to preload.
* @param context Information regarding the resource such as the type and containing file.
* @returns A Promise that is resolved once the resource has been loaded or `undefined`
* if the file has already been loaded.
* @throws An Error if pre-loading is not available.
*/
preload(resolvedUrl: string, context: ResourceLoaderContext): Promise<void>|undefined;
/**
* Preprocess the content data of an inline resource, asynchronously.
*
* @param data The existing content data from the inline resource.
* @param context Information regarding the resource such as the type and containing file.
* @returns A Promise that resolves to the processed data. If no processing occurs, the
* same data string that was passed to the function will be resolved.
*/
preprocessInline(data: string, context: ResourceLoaderContext): Promise<string>;
/**
* Load the resource at the given url, synchronously.
*
* The contents of the resource may have been cached by a previous call to `preload()`.
*
* @param resolvedUrl The url (resolved by a call to `resolve()`) of the resource to load.
* @returns The contents of the resource.
*/
load(resolvedUrl: string): string;
}
/**
* Contextual information used by members of the ResourceLoader interface.
*/
export interface ResourceLoaderContext {
/**
* The type of the component resource.
* * Resources referenced via a component's `styles` or `styleUrls` properties are of
* type `style`.
* * Resources referenced via a component's `template` or `templateUrl` properties are of type
* `template`.
*/
type: 'style'|'template';
/**
* The absolute path to the file that contains the resource or reference to the resource.
*/
containingFile: string;
}
|
6c4a171ce54a552b7e3c91ce6db52dda394934b1
|
TypeScript
|
trash/ripple
|
/app/src/ItemRequirementsMap.ts
| 3.40625
| 3
|
import * as Immutable from 'immutable';
import {
IItemRequirementsMapEntry,
RequiredItems,
IItemSearchResult
} from './interfaces';
import {EventEmitter2} from 'eventemitter2';
import {Item} from './data/Item';
type ForEachCallback = (
itemType: string,
itemEntry: IItemRequirementsMapEntry
) => void;
/**
* An object that represents all the required items for a given task/item.
* This is for non persistent item tracking.
*
* @constructor
* @param {object} items An map of item names and the amount required
* i.e. { wood: 10, stone: 5 }
*/
export class ItemRequirementsMap extends EventEmitter2 {
protected map: Map<Item, IItemRequirementsMapEntry>;
constructor (items: RequiredItems) {
super();
this.map = new Map();
items.forEach(item => {
this.map.set(item.enum, {
gathered: 0,
required: item.count
});
});
}
/**
* Updates the map based on the given item list. This is useful for temporary
* calculating of item requirements that don't need persistence.
* @param itemList
*/
setItemList(itemList: Immutable.Map<Item, number>): void {
itemList.forEach((count, item) => {
const entry = this.map.get(item);
if (entry) {
entry.gathered = Math.min(count, entry.required);
this.map.set(item, entry);
}
});
}
getRequiredCountMap(): Map<Item, number> {
const countMap = new Map<Item, number>();
Array.from(this.map).forEach(([itemType, itemEntry]) => {
countMap.set(itemType, itemEntry.required);
});
return countMap;
}
/**
* Checks whether or not the given item list contains the amount of items
* necessary to complete the ResourceRequirements object.
* @param itemList Map of items to count of that item
*/
itemListContainsRequiredResources(itemList: Immutable.Map<Item, number>): boolean {
return Array.from(this.map).every(([itemType, itemEntry]) => {
return itemList.get(itemType) + itemEntry.gathered >= itemEntry.required;
});
}
isCompleted(): boolean {
// There doesn't exist some entry where the gathered amount is not the
// required amount
return !Array.from(this.map).some(([itemType, itemEntry]) => {
return itemEntry.gathered < itemEntry.required;
});
}
toString(): string {
let string = '';
this.map.forEach((itemEntry, itemType) => {
const itemName = Item[itemType];
string += `${itemName}:[${itemEntry.gathered}/${itemEntry.required}] `;
});
return string;
}
/**
* Method to set all items as collected. For use when a building is
* spawned as already completed.
*/
markAsCompleted(): void {
this.map.forEach(itemEntry => {
itemEntry.gathered = itemEntry.required;
});
}
/**
* Adds a item to the list of gathered items of the given item type
*
* @param {Item} item A item item that has been gathered for the requirements
* and needs to be removed from the game (used).
*/
addToRequirements (itemSearchResult: IItemSearchResult) {
// Update our gathered amount
this.map.get(itemSearchResult.state.enum).gathered += 1;
}
/**
* Returns the total required items left to be gathered across all types.
*
* @return {Number} The number of items left to be gathered.
*/
totalRequiredResources () {
let total = 0;
this.map.forEach((itemEntry) => {
total += itemEntry.required - itemEntry.gathered;
});
return total;
}
/**
* The total amount of items that are required to have this be built.
* Compared with `totalRequiredResources` to tell if you're done.
*/
totalNeededResources () {
let total = 0;
this.map.forEach((itemEntry) => {
total += itemEntry.required;
});
return total;
}
/**
* Returns the count of different types of items. I.e. if wood and stone then 2
*
* @return {Number} Number of different ttypes of items required
*/
itemTypeCount () {
return Object.keys(this.map).length;
}
}
|
3e87ca153b4368e6f14fadba544907157092ae59
|
TypeScript
|
geraldyeo/restyled
|
/src/mixins/compose.test.ts
| 2.625
| 3
|
import defaultTheme from '../index';
import * as StyledSystem from '../system';
import compose from './compose';
const theme = {
...defaultTheme,
colors: { white: '#fff', black: '#000', grey: '#333' },
};
describe('compose', () => {
it('should compose a style function', () => {
const fn = compose(
StyledSystem.backgroundColor('white'),
StyledSystem.color('black'),
StyledSystem.fontFamily('Arial'),
StyledSystem.fontSize([0, 2, 4]),
StyledSystem.fontWeight(['light', 'normal', 'medium']),
);
const style = fn({ theme });
expect(style).toEqual({
backgroundColor: '#fff',
color: '#000',
fontFamily: 'Arial',
fontSize: 12,
fontWeight: 300,
'@media screen and (min-width: 40em)': {
fontSize: 16,
fontWeight: 400,
},
'@media screen and (min-width: 52em)': {
fontSize: 22,
fontWeight: 500,
},
});
});
});
|
d06cbcaad63f7d7e44f666b32a128831871cd9ef
|
TypeScript
|
garyng/Wimm
|
/src/api/ts/rating.ts
| 2.671875
| 3
|
import { ModelFilter } from './model-filter';
export class Rating extends ModelFilter {
constructor(
public id: number = 0,
public userId: number = 0,
public bookId: number = 0,
public rating: number = 0,
public createdAt: Date = new Date(),
public updatedAt: Date = new Date(),
) {
super();
}
public static create(rawObj: Rating): Rating {
return new Rating(
rawObj.id,
rawObj.userId,
rawObj.bookId,
rawObj.rating,
rawObj.createdAt,
rawObj.updatedAt,
);
}
}
|
e5f09e96e827911f5cb8fa89ddb18512033e1eef
|
TypeScript
|
ellisonbg/phosphor
|
/src/layout/SpacerItem.ts
| 2.9375
| 3
|
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
module phosphor.layout {
import Alignment = enums.Alignment;
import SizePolicy = enums.SizePolicy;
import Size = geometry.Size;
import Widget = widgets.Widget;
/**
* A concrete implementation of ILayoutItem which manages empty space.
*
* User code will not typically create instances of this class directly.
*/
export
class SpacerItem implements ILayoutItem {
/**
* Construct a new spacer item.
*/
constructor(width: number, height: number, hPolicy: SizePolicy, vPolicy: SizePolicy) {
this.setSize(width, height, hPolicy, vPolicy);
}
/**
* Test whether the item manages a widget.
*/
get isWidget(): boolean {
return false;
}
/**
* Test whether the item manages empty space.
*/
get isSpacer(): boolean {
return true;
}
/**
* Test whether the item should be treated as hidden.
*/
get isHidden(): boolean {
return false;
}
/**
* The widget the item manages, if any.
*/
get widget(): Widget {
return null;
}
/**
* Test whether the item should be expanded horizontally.
*/
get expandHorizontal(): boolean {
return (this._m_hPolicy & SizePolicy.ExpandFlag) !== 0;
}
/**
* Test Whether the item should be expanded vertically.
*/
get expandVertical(): boolean {
return (this._m_vPolicy & SizePolicy.ExpandFlag) !== 0;
}
/**
* The alignment of the item in its layout cell.
*/
get alignment(): Alignment {
return 0;
}
/**
* Change the size of the spacer item.
*
* The owner layout must be invalidated to reflect the change.
*/
setSize(width: number, height: number, hPolicy: SizePolicy, vPolicy: SizePolicy): void {
var w = Math.max(0, width);
var h = Math.max(0, height);
this._m_size = new Size(w, h);
this._m_hPolicy = hPolicy;
this._m_vPolicy = vPolicy;
}
/**
* Transpose the effective orientation of the spacer item.
*/
transpose(): void {
var size = this._m_size;
var hPolicy = this._m_hPolicy;
var vPolicy = this._m_vPolicy;
this._m_size = new Size(size.height, size.width);
this._m_vPolicy = hPolicy;
this._m_hPolicy = vPolicy;
}
/**
* Invalidate the cached data for the item.
*/
invalidate(): void { }
/**
* Compute the preferred size of the item.
*/
sizeHint(): Size {
return this._m_size;
}
/**
* Compute the minimum size of the item.
*/
minSize(): Size {
var size = this._m_size;
var w = this._m_hPolicy & SizePolicy.ShrinkFlag ? 0 : size.width;
var h = this._m_vPolicy & SizePolicy.ShrinkFlag ? 0 : size.height;
return new Size(w, h);
}
/**
* Compute the maximum size of the item.
*/
maxSize(): Size {
var size = this._m_size;
var w = this._m_hPolicy & SizePolicy.GrowFlag ? Infinity : size.width;
var h = this._m_vPolicy & SizePolicy.GrowFlag ? Infinity : size.height;
return new Size(w, h);
}
/**
* Set the geometry of the item.
*/
setGeometry(x: number, y: number, width: number, height: number): void { }
private _m_size: Size;
private _m_hPolicy: SizePolicy;
private _m_vPolicy: SizePolicy;
}
} // module phosphor.layout
|
0f6c48a28c9b91881bb2ea6e0855b0c436ff815a
|
TypeScript
|
github/vscode-codeql
|
/extensions/ql-vscode/src/model-editor/library.ts
| 3.078125
| 3
|
import { basename, extname } from "../common/path";
// From the semver package using
// const { re, t } = require("semver/internal/re");
// console.log(re[t.LOOSE]);
// Modifications:
// - Added version named group which does not capture the v prefix
// - Removed the ^ and $ anchors
// - Made the minor and patch versions optional
// - Added a hyphen to the start of the version
// - Added a dot as a valid separator between the version and the label
// - Made the patch version optional even if a label is given
// This will match any semver string at the end of a larger string
const semverRegex =
/-[v=\s]*(?<version>([0-9]+)(\.([0-9]+)(?:(\.([0-9]+))?(?:[-.]?((?:[0-9]+|\d*[a-zA-Z-][a-zA-Z0-9-]*)(?:\.(?:[0-9]+|\d*[a-zA-Z-][a-zA-Z0-9-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?)?)?)/g;
interface Library {
name: string;
version?: string;
}
export function parseLibraryFilename(filename: string): Library {
let libraryName = basename(filename);
const extension = extname(libraryName);
libraryName = libraryName.slice(0, -extension.length);
let libraryVersion: string | undefined;
let match: RegExpMatchArray | null = null;
// Reset the regex
semverRegex.lastIndex = 0;
// Find the last occurence of the regex within the library name
// eslint-disable-next-line no-constant-condition
while (true) {
const currentMatch = semverRegex.exec(libraryName);
if (currentMatch === null) {
break;
}
match = currentMatch;
}
if (match?.groups) {
libraryVersion = match.groups?.version;
// Remove everything after the start of the match
libraryName = libraryName.slice(0, match.index);
}
// Remove any leading or trailing hyphens or dots
libraryName = libraryName.replaceAll(/^[.-]+|[.-]+$/g, "");
return {
name: libraryName,
version: libraryVersion,
};
}
|
5879fea336ae21a175e6d33bfe380a12f03c747b
|
TypeScript
|
vitoraa/clean-node
|
/src/presentation/controllers/ship/add-ship/add-ship-controller.ts
| 2.578125
| 3
|
import { AddShip } from '@/domain/usecases/ship/add-ship'
import { FieldInUseError } from '@/presentation/errors/field-in-use-error'
import { badRequest, forbidden, ok, serverError } from '@/presentation/helpers/http/http-helper'
import { Controller, HttpResponse } from '@/presentation/protocols'
import { Validation } from '../../login/login-controller-protocols'
export class AddShipController implements Controller {
constructor (
private readonly addShip: AddShip,
private readonly validation: Validation
) { }
async handle (request: AddShipController.Request): Promise<HttpResponse> {
try {
const error = this.validation.validate(request)
if (error) {
return badRequest(error)
}
// const { name, ab } = request.body
const ship = await this.addShip.add(request)
if (!ship) {
return forbidden(new FieldInUseError('Imo'))
}
return ok(ship)
} catch (error) {
return serverError(error)
}
}
}
export namespace AddShipController {
export type Request = {
name: string
ab: number
imo: string
}
}
|
39dc8cd893c23ae94d7bab711e1a83c86ccdd9bc
|
TypeScript
|
dimunozp/curso-rxjs-inicio
|
/src/observables/07-interval-timer.ts
| 2.75
| 3
|
import {Observable, Observer, interval, timer} from 'rxjs';
const observer: Observer<any> = {
next: (value: any) => console.log('next: ', value),
error: null,
complete: () => console.info('complete')
};
const hoyEn5: Date = new Date();
hoyEn5.setSeconds(hoyEn5.getSeconds() + 5);
const interval$: Observable<any> = interval(1000);
// const timer$:Observable<any> = timer(2000);
// const timer$:Observable<any> = timer(2000, 1000);
const timer$: Observable<any> = timer(hoyEn5);
console.log('Inicio');
interval$.subscribe(observer);
timer$.subscribe(observer);
console.log('Fin');
|
70d2f43b6fcaae51341f0b0ddb81cbe071b7b5d0
|
TypeScript
|
cholnhial/deco2500
|
/src/app/components/photos/photos.ts
| 2.65625
| 3
|
import {Component} from "@angular/core";
@Component({
selector: 'component-photos',
templateUrl: 'photos.html',
styleUrls: ['./photos.scss'],
})
export class PhotosComponent {
images = [];
constructor() {
}
onRemoveImage(imageIndex) {
this.images.splice(imageIndex, 1);
}
onAddImage() {
this.images.push("https://source.unsplash.com/900x583/?nature,water&version=" + this.getRandomString(5));
}
getRandomString(length) {
let result = [];
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++ ) {
result.push(characters.charAt(Math.floor(Math.random() *
charactersLength)));
}
return result.join('');
}
getImages() {
return this.images;
}
setImages(images) {
this.images = images;
}
}
|
78ab7b9aecc7db6ed3e15146f018db7523f6ebd8
|
TypeScript
|
ryabv/learn-ts
|
/src/store/fileContent/reducers.ts
| 2.8125
| 3
|
import { GET_FILE_CONTENT_FROM_SERVER_SUCCESS } from './actions';
const defaultState = ['Hello world'];
type Action = {
type: string,
payload: {}
}
export const fileContentReducer = (state = defaultState, action: Action) => {
switch (action.type) {
case GET_FILE_CONTENT_FROM_SERVER_SUCCESS:
console.log('REDUCER', state);
return action.payload
default:
return state;
}
}
|
c997f9579ef2db5c0eb35a7337f648acfe019c34
|
TypeScript
|
anujshah108/mt-sinai-chat-prototype
|
/app/src/socket/index.ts
| 2.671875
| 3
|
import { Message } from "../components/MessageContainer.tsx/MessageContainer";
// api/index.js
const socket = new WebSocket("ws://localhost:8080/ws");
const connect = (callback: (msg: MessageEvent) => void) => {
socket.onopen = () => {
console.log("Successfully Connected");
};
socket.onmessage = (msg: MessageEvent) => {
callback(msg);
};
socket.onclose = (event: CloseEvent) => {
console.log("Socket Closed Connection: ", event);
};
socket.onerror = (error: Event) => {
console.log("Socket Error: ", error);
};
};
let sendMsg = (msg: Message) => {
socket.send(JSON.stringify(msg));
};
let closeSocket = () => {
socket.close();
};
export { connect, sendMsg, closeSocket };
|
bee4a382c49d419971386c5115734062144814f6
|
TypeScript
|
cloudify-cosmo/cloudify-stage
|
/widgets/userGroups/src/actions.ts
| 2.546875
| 3
|
import { map, concat, includes, filter, size, isUndefined, isEmpty } from 'lodash';
import type { SystemRole } from '../../../app/widgets/common/roles/types';
import type { Toolbox } from '../../../app/utils/StageAPI';
import type { RolesAssignment } from '../../../app/widgets/common/tenants/utils';
import type { UserGroup } from './widget.types';
function isAdminGroup(group: UserGroup) {
return group.role === Stage.Common.Consts.sysAdminRole;
}
export type NamedResourceResponse = Stage.Types.PaginatedResponse<{ name: string }>;
export default class Actions {
toolbox: Toolbox;
currentUsername: string;
currentUserRole: SystemRole;
constructor(toolbox: Toolbox) {
this.toolbox = toolbox;
this.currentUsername = toolbox.getManager().getCurrentUsername();
this.currentUserRole = toolbox.getManager().getCurrentUserRole();
}
doCreate(groupName: string, ldapGroup: string, role: SystemRole) {
const body =
isUndefined(ldapGroup) || isEmpty(ldapGroup)
? { group_name: groupName, role }
: { group_name: groupName, ldap_group_dn: ldapGroup, role };
return this.toolbox.getManager().doPost('/user-groups', { body });
}
doDelete(groupName: string) {
return this.toolbox.getManager().doDelete(`/user-groups/${groupName}`);
}
doSetRole(groupName: string, role: SystemRole) {
return this.toolbox.getManager().doPost(`/user-groups/${groupName}`, { body: { role } });
}
doGetUsers() {
return this.toolbox.getManager().doGet('/users?_include=username');
}
doGetTenants() {
return this.toolbox.getManager().doGet('/tenants?_get_all_results=true&_include=name');
}
doAddUserToGroup(username: string, groupName: string) {
return this.toolbox.getManager().doPut('/user-groups/users', { body: { username, group_name: groupName } });
}
doRemoveUserFromGroup(username: string, groupName: string) {
return this.toolbox.getManager().doDelete('/user-groups/users', { body: { username, group_name: groupName } });
}
doAddTenantToGroup(tenantName: string, groupName: string, role: string) {
return this.toolbox
.getManager()
.doPut('/tenants/user-groups', { body: { tenant_name: tenantName, group_name: groupName, role } });
}
doRemoveTenantFromGroup(tenantName: string, groupName: string) {
return this.toolbox
.getManager()
.doDelete('/tenants/user-groups', { body: { tenant_name: tenantName, group_name: groupName } });
}
doUpdateTenant(tenantName: string, groupName: string, role: string) {
return this.toolbox
.getManager()
.doPatch('/tenants/user-groups', { body: { tenant_name: tenantName, group_name: groupName, role } });
}
doHandleUsers(groupName: string, usersToAdd: string[], usersToDelete: string[]) {
const addActions = map(usersToAdd, username => this.doAddUserToGroup(username, groupName));
const deleteActions = map(usersToDelete, username => this.doRemoveUserFromGroup(username, groupName));
return Promise.all(concat(addActions, deleteActions));
}
doHandleTenants(
groupName: string,
tenantsToAdd: RolesAssignment,
tenantsToDelete: string[],
tenantsToUpdate: RolesAssignment
) {
const addActions = map(tenantsToAdd, (role, tenant) => this.doAddTenantToGroup(tenant, groupName, role));
const deleteActions = map(tenantsToDelete, tenant => this.doRemoveTenantFromGroup(tenant, groupName));
const updateActions = map(tenantsToUpdate, (role, tenant) => this.doUpdateTenant(tenant, groupName, role));
return Promise.all(concat(addActions, deleteActions, updateActions));
}
isUserIn(users: string[], username = this.currentUsername) {
return includes(users, username);
}
hasCurrentUserAdminRole() {
return this.currentUserRole === Stage.Common.Consts.sysAdminRole;
}
// Check if user <username> belongs to group <group> and it is the only admin group he belongs to
isUserGroupTheOnlyAdminGroup(group: UserGroup, groups: UserGroup[], username = this.currentUsername) {
if (includes(group.users, username)) {
const currentUserAdminGroups = filter(
groups,
userGroup => includes(userGroup.users, username) && userGroup.role === Stage.Common.Consts.sysAdminRole
);
return size(currentUserAdminGroups) === 1;
}
return false;
}
// Check if user <username> is in <users>
// user <username> does not have admin role
// group <group> has admin rights
// user <username> belongs to group <group> as the only admin group
isLogoutToBePerformed(group: UserGroup, groups: UserGroup[], users: string[], username = this.currentUsername) {
return (
this.isUserIn(users, username) &&
!this.hasCurrentUserAdminRole() &&
isAdminGroup(group) &&
this.isUserGroupTheOnlyAdminGroup(group, groups, username)
);
}
}
|
2edb3b5b105a17729b10a32874c60638cceda19e
|
TypeScript
|
MoonG25/wangwang
|
/src/utils/index.ts
| 2.703125
| 3
|
export const getPlayYMD = () => {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const day = today.getDate();
return `${year}${addZero(month)}${addZero(day)}`;
};
export const addZero = (value: number) => {
return ('0' + value).slice(-2);
};
|
4d50e3f3ab8b43798d21077e5fdf3ed66a241927
|
TypeScript
|
andreimaurina/acic
|
/src/models/Associado.ts
| 2.734375
| 3
|
export class Associado {
nome: string;
tipo: string;
email: string;
telefone: string;
cep: string;
cidade: string;
rua: string;
numEndereco: number;
bairro: string;
constructor(tipo: string) {
this.tipo = tipo;
}
}
export class PessoaFisica extends Associado {
cpf: string;
sexo: string;
dataNasc: string;
facebook: string;
instagram: string;
twitter: string;
linkedin: string;
constructor() {
super('pessoaFisica');
}
}
export class PessoaJuridica extends Associado {
cnpj: string;
razaoSocial: string;
nomeFantasia: string;
site: string;
constructor() {
super('pessoaJuridica')
}
}
|
745698fc796f8df86ad23a96bcd454ad5db74d28
|
TypeScript
|
DreamLarva/js-ts-Algorithms
|
/leetcode/599.两个列表的最小索引总和.ts
| 3.65625
| 4
|
/*
假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。
示例 1:
输入:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
输出: ["Shogun"]
解释: 他们唯一共同喜爱的餐厅是“Shogun”。
示例 2:
输入:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
输出: ["Shogun"]
解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。
提示:
1. 两个列表的长度范围都在 [1, 1000]内。
2. 两个列表中的字符串的长度将在[1,30]的范围内。
3. 下标从0开始,到列表的长度减1。
4. 两个列表都没有重复的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* */
/**
* @param {string[]} list1
* @param {string[]} list2
* @return {string[]}
*/
var findRestaurant = function (list1: string[], list2: string[]): string[] {
// 哈希表 解决
// 其实 判断数组大小好像没毛线 区别 只是 让用的哈希表的内存小一点 时间复杂度还是 O(n + m)的样子
// 现将 较小的一个数组 放入哈希表
if (list1.length > list2.length) return findRestaurant(list2, list1);
const map: { [key: string]: number } = {};
for (let i = 0; i < list1.length; i++) {
map[list1[i]] = i;
}
let max = Infinity;
let result: string[] = [];
// 扫描较大的数组
// 老夫写的更屌 添加这个 判断之后 i <= max 可以排除一部分不可能的情况
for (let i = 0; i < list2.length && i <= max; i++) {
const str = list2[i];
if (map[str] != null) {
if (map[str] + i < max) {
max = map[str] + i;
result = [str];
} else if (map[str] + i === max) {
result.push(str);
}
}
}
return result;
};
import assert from "assert";
assert.deepStrictEqual(
findRestaurant(
["Shogun", "Tapioca Express", "Burger King", "KFC"],
[
"Piatti",
"The Grill at Torrey Pines",
"Hungry Hunter Steakhouse",
"Shogun",
]
),
["Shogun"]
);
assert.deepStrictEqual(
findRestaurant(
["Shogun", "Tapioca Express", "Burger King", "KFC"],
["KFC", "Shogun", "Burger King"]
),
["Shogun"]
);
assert.deepStrictEqual(
findRestaurant(
["Shogun", "Tapioca Express", "Burger King", "KFC"],
["KFC", "Burger King", "Tapioca Express", "Shogun"]
),
["KFC", "Burger King", "Tapioca Express", "Shogun"]
);
|
62a61bb207aafe4765c58c999482c4dc23e7190d
|
TypeScript
|
darwinpsunny/fsdlibappangular-frontend
|
/src/app/signup/signup.component.ts
| 2.953125
| 3
|
import { Component, OnInit } from '@angular/core';
import{AuthService} from "../auth.service";
import{Router} from '@angular/router';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
constructor(private authservice:AuthService,private _router:Router) { }
ngOnInit(): void {
}
eColor : string = '';
pColor: string = '';
p2color: string="";
ncolor:string="";
ebool:boolean=false;
pbool:boolean=false;
nbool:boolean=false;
p2bool:boolean=false;
strength="";
text:string ="";
password1:string="";
password2:string="";
ntext:string="";
user={
email:"",
password:"",
phonenumber:""
}
useradd()
{
this.authservice.adduser(this.user).subscribe();
this._router.navigate(['login']);
}
emailvalidate(event) {
let regexp=/^([a-zA-Z0-9\.\-]+)@([a-zA-Z0-9\-]+)\.([a-z]{2,3})(\.[a-z]{2,3})?$/;
if(regexp.test(event.target.value))
{
this.eColor=" blue";
this.ebool=true;
}
else{
this.eColor="red";
this.ebool=false;
}
}
numbervalidate(event)
{
let regxp2=/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(regxp2.test(event.target.value))
{
this.ncolor="blue";
this.ntext="";
this.nbool=true;
}
else{
this.ncolor="red";
this.ntext="please enter a valid number";
this.nbool=false;
}
}
password1validate(event){
// Create an array and push all possible values that you want in password
var matchedCase = new Array();
matchedCase.push("[$@$!%*#?&]"); // Special Charector
matchedCase.push("[A-Z]"); // Uppercase Alpabates
matchedCase.push("[0-9]"); // Numbers
matchedCase.push("[a-z]"); // Lowercase Alphabates
// Check the conditions
var ctr = 0;
for (var i = 0; i < matchedCase.length; i++) {
if (new RegExp(matchedCase[i]).test(this.user.password)) {
ctr++;
}
}
// Display it
var color = "";
var strength = "";
switch (ctr) {
case 0:
case 1:
case 2:
strength = " password Very Weak";
color = "red";
break;
case 3:
strength = "password strength is Medium";
color = "orange";
break;
case 4:
if(this.user.password.length>=8){
strength = "Strong password";
color = "green";}
else{
strength = "password strength is Medium minuinum 8 characters required";
color = "orange";
}
break;
}
this.pColor=color;
this.strength=strength;
// Password1help.innerText=strength;
// Password1help.style.color=color;
if(color=="green" )
{
this.pbool=true;
}
else{
this.pbool=false;
}
}
password2validate(event)
{ //alert(this.password1+this.password2)
if(this.user.password == this.password2)
{
this.p2color="green";
this.text="passwords match"
}
else{
this.p2color="red";
this.text="passwords doesnt match";
}
if(this.p2color=="green")
{
this.p2bool=true;
}
else
{ this.p2bool=false;
}
}
}
|
df1b2063a6497152f526bfadb154b23c74c49021
|
TypeScript
|
beaumontjonathan/mev
|
/lib/rule/NumberRule.ts
| 3.15625
| 3
|
import { ValidationRuleResult } from '../types';
import { defaultRuleOptions, Rule, RuleOptions } from './Rule';
export interface NumberRuleOptions extends RuleOptions {}
export const defaultNumberRuleOptions: NumberRuleOptions = {
...defaultRuleOptions,
initialTypeTestType: 'number',
};
export class NumberRule extends Rule<number> {
constructor(opts: NumberRuleOptions = defaultNumberRuleOptions) {
super(opts);
}
public min(min: number): this {
this.addNonRequiredInternalTestFunction((n) => n >= min, {
title: 'less than minimum',
description: `must be greater than the minimum value of ${min}`,
});
return this;
}
public closedMin(min: number): this {
this.min(min);
return this;
}
public openMin(min: number): this {
this.addNonRequiredInternalTestFunction((n) => n > min, {
title: 'less than or equal to minimum',
description: `must be greater than the open minimum value of ${min}`,
});
return this;
}
public max(max: number): this {
this.addNonRequiredInternalTestFunction((n) => n <= max, {
title: 'greater than maximum',
description: `must be less than the maximum value of ${max}`,
});
return this;
}
public closedMax(max: number): this {
this.max(max);
return this;
}
public openMax(max: number): this {
this.addNonRequiredInternalTestFunction((n) => n < max, {
title: 'greater than or equal to maximum',
description: `must be less than the open maximum value of ${max}`,
});
return this;
}
public closedInterval(min: number, max: number): this {
this.addNonRequiredInternalTestFunction((n) => n >= min && n <= max, {
title: 'outside closed interval',
description: `outside of the closed interval of [${min},${max}]`,
});
return this;
}
public openInterval(min: number, max: number): this {
this.addNonRequiredInternalTestFunction((n) => n > min && n < max, {
title: 'outside open interval',
description: `outside of the open interval of (${min},${max})`,
});
return this;
}
public test(n: number): ValidationRuleResult {
return super.test(n);
}
}
|
17d21eba267bc8b7269144eccd71458a84d90c20
|
TypeScript
|
denisugiarto/audiophile
|
/redux/slices/cartSlice.ts
| 3.046875
| 3
|
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { ProductType } from "data/types/productType";
import { toast } from "react-toastify";
import { toastAction } from "helpers/toastify";
import { RootState } from "redux/store";
//TODO: cartSlice interface
interface CartSliceType {
cartItems: ProductType[];
}
//TODO: Declare the initial state of the cartSlice (Get cartItems data from the localStorage)
const initialState: CartSliceType = {
cartItems:
typeof window !== "undefined" &&
(localStorage.getItem("cartItems")
? JSON.parse(localStorage.getItem("cartItems"))
: []),
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
//TODO: Reducer => Add products to the cart and update localStorage (with toastify alerts)
addItemToCart(state, action: PayloadAction<ProductType>) {
const itemIndex = state.cartItems.findIndex(
(item) => item.id === action.payload.id
);
if (itemIndex >= 0) {
state.cartItems[itemIndex].cartQuantity += 1;
//Calculate the subtotal price of each "multiple" product
const subTotal =
state.cartItems[itemIndex].price *
state.cartItems[itemIndex].cartQuantity;
state.cartItems[itemIndex].subTotal = subTotal;
//Notification: Alert an increase in product quantity
toast.success(`${action.payload.name} added to cart`, toastAction);
} else {
const tempProduct = {
...action.payload,
cartQuantity: 1,
};
state.cartItems.push(tempProduct);
toast.success(`${action.payload.name} added to cart`, toastAction);
}
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
},
//TODO: Reducer => Increase the number of products in the cart (with toastify alerts)
increaseQuantity(state, action) {
const itemIndex = state.cartItems.findIndex(
(cartItem) => cartItem.id === action.payload.id
);
if (state.cartItems[itemIndex]) {
if (state.cartItems[itemIndex].cartQuantity >= 1) {
state.cartItems[itemIndex].cartQuantity += 1;
//Calculate the subtotal price of each "multiple" product
const subTotal =
state.cartItems[itemIndex].price *
state.cartItems[itemIndex].cartQuantity;
state.cartItems[itemIndex].subTotal = subTotal;
}
//localStorage: Update state and push to localStorage
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
} else {
toast.error(`Click on "ADD TO CART"!`, toastAction);
}
},
//TODO: Reducer => Decrease the number of products in the cart (with toastify alerts)
decreaseQuantity(state, action) {
const itemIndex = state.cartItems.findIndex(
(cartItem) => cartItem.id === action.payload.id
);
if (state.cartItems[itemIndex]) {
if (state.cartItems[itemIndex].cartQuantity > 1) {
state.cartItems[itemIndex].cartQuantity -= 1;
//Calculate the subtotal price of each "multiple" product
const subTotal =
state.cartItems[itemIndex].price *
state.cartItems[itemIndex].cartQuantity;
state.cartItems[itemIndex].subTotal = subTotal;
//localStorage: Update state and push to localStorage
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
}
//!: Delete the product from cart if the count is below 1
else if (state.cartItems[itemIndex].cartQuantity === 1) {
const nextCartItems = state.cartItems.filter(
(cartItem) => cartItem.id !== action.payload.id
);
state.cartItems = nextCartItems;
//localStorage: Update state and push to localStorage
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
//Notification: Alert a product remove in product quantity
toast.error(`Removed ${action.payload.name} form cart`, toastAction);
}
} else {
toast.error(`This product CANNOT BE FOUND in the cart!`, toastAction);
}
},
//TODO: Reducer => Decrease the number of products in the cart (with toastify alerts)
//!: This reducer will prevent the item from deleting when the value is lesser that 1. This is used in the product page counter only!
customDecreaseQuantity(state, action) {
const itemIndex = state.cartItems.findIndex(
(cartItem) => cartItem.id === action.payload.id
);
if (state.cartItems[itemIndex]) {
if (state.cartItems[itemIndex].cartQuantity > 1) {
state.cartItems[itemIndex].cartQuantity -= 1;
//Calculate the subtotal price of each "multiple" product
const subTotal =
state.cartItems[itemIndex].price *
state.cartItems[itemIndex].cartQuantity;
state.cartItems[itemIndex].subTotal = subTotal;
//localStorage: Update state and push to localStorage
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
}
} else {
toast.error(`This product CANNOT BE FOUND in the cart!`, toastAction);
}
},
//TODO: Reducer => Clear all products in the cart and localStorage (with toastify alerts)
clearCart(state, action) {
if (action.payload === true) {
state.cartItems = [];
}
//localStorage: Clear localStorage
localStorage.removeItem("cartItems");
//Notification: Alert an all-cleared product cart
toast.error(`Your cart is cleared`, toastAction);
},
},
});
//TODO: Calculate the total number of item(s) in the cart
export const totalCartQuantity = (state: RootState) => {
const total = (state.cart.cartItems || [])
.map((cartItem) => cartItem.cartQuantity)
.reduce((acc, curr) => acc + curr, 0);
return total;
};
//TODO: Calculate the total number price of products in the cart
export const productTotal = (state: RootState) => {
const total = (state.cart.cartItems || [])
.map((cartItem) => cartItem.subTotal)
.reduce((acc, curr) => acc + curr, 0);
return total;
};
export const {
addItemToCart,
increaseQuantity,
decreaseQuantity,
customDecreaseQuantity,
clearCart,
} = cartSlice.actions;
export default cartSlice.reducer;
|