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
|
|---|---|---|---|---|---|---|
43af5fcdbe8f8fe07d34ee13d25c29ac9ee5a9b3
|
TypeScript
|
bogdandan/adventofcode2020
|
/packages/day6/src/index.ts
| 3.15625
| 3
|
import path from 'path';
import fs from 'fs';
import { Group } from './model';
function readInput(filename: string): Group[] {
const filePath = path.join(__dirname, '../data', filename);
const input = fs.readFileSync(filePath, 'utf-8');
const groups: Group[] = [];
input.split('\n\n').forEach((groupInput) => {
const group: Group = {
persons: [],
};
groupInput.split('\n').forEach((personAnswer) => {
group.persons.push({ answers: personAnswer.split('') });
});
groups.push(group);
});
return groups;
}
function computeChallenge1(groups: Group[]): number {
return groups.reduce((acc, group) => {
const uniqAnswers = new Set();
group.persons.forEach((p) => {
p.answers.forEach((answer) => uniqAnswers.add(answer));
});
return acc + uniqAnswers.size;
}, 0);
}
function computeChallenge2(groups: Group[]): number {
return groups.reduce((acc, group) => {
const answersPerQuestion: Record<string, number> = {};
group.persons.forEach((person) => {
person.answers.forEach((answer) => {
if (typeof answersPerQuestion[answer] === 'undefined') {
answersPerQuestion[answer] = 0;
}
answersPerQuestion[answer] += 1;
});
});
const answers = Object.values(answersPerQuestion).filter(
(answerPerQuestion) => answerPerQuestion === group.persons.length,
).length;
return acc + answers;
}, 0);
}
async function main(): Promise<number[]> {
const fileName = typeof process.env.FILE === 'string' ? process.env.FILE : 'test';
const result = readInput(fileName);
const challenge1 = computeChallenge1(result);
const challenge2 = computeChallenge2(result);
return [challenge1, challenge2];
}
main().then(console.log).catch(console.error);
|
889638311142ff6224e0e4ab99d1c9f8fa0f8705
|
TypeScript
|
DavidTorresM/ing-software-backend
|
/src/publicacion/controller/publicacion.controller.ts
| 2.53125
| 3
|
import {
Body,
Controller,
Get,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuardDocente } from '../../auth/guards/jwt-aut.docente.guard';
import { JwtAuthGuardAlumno } from '../../auth/guards/jwt-auth.alumno.guard';
import { Publicacion } from '../publicacion.entity';
import { PublicacionDTO } from '../interface/publicacion.interface';
import { PublicacionService } from '../service/publicacion.service';
import { ArchivoService } from '../../archivo/service/archivo.service';
@Controller('api/publicacion')
export class PublicacionController {
constructor(
private servicioPublicacion: PublicacionService,
private servicioArchivo: ArchivoService,
){}
//curl 'http://localhost:3000/api/publicacion/crear' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0' -H 'Accept: application/json, text/plain, */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/json;charset=utf-8' -H 'Origin: http://localhost:3001' -H 'Connection: keep-alive' -H 'Referer: http://localhost:3001/' --data-raw $'{"idSala":"3","titulo":"Publicaicon nueva ","descripcion":"jkslafddjska\xf1fjksdl","fechaPublicacion":"2021-01-19T02:18:58.523Z","archivo":{"nombre":"cal-Escolarizada-20-21.pdf","tamanio":1296956,"tipo":"application/pdf","url":"https://archivos-polimeet.s3.us-east-2.amazonaws.com/1611022730930%20-%20cal-Escolarizada-20-21.pdf"}}'
@UseGuards(JwtAuthGuardDocente)
@Post('crear')
async crearPublicacion(@Body() publicacion: PublicacionDTO): Promise< Publicacion|null >{
let publicacionNueva: Publicacion;
if(publicacion.archivo && Object.keys(publicacion.archivo).length > 0 ){//con archivo
console.log("con archivo");
//Primero creamos en archivo
let archivo = await this.servicioArchivo.crear(publicacion.archivo);
console.log("Archivo creado", archivo);
publicacion["archivoUrl"] = archivo.url;
//borramos el archivo
delete publicacion.archivo;
}else{//sin archivo
console.log("sin archivo");
(publicacion.archivo)?delete publicacion.archivo:null;
}
publicacionNueva = await this.servicioPublicacion.crear(publicacion);
console.log("Publicacion nueva", publicacionNueva);
return publicacionNueva;
}
@UseGuards(JwtAuthGuardAlumno)
@Get('buscar/id/:id')
async buscarPublicacion(@Param('id') id:number): Promise< Publicacion | null >{
const publicacion = await this.servicioPublicacion.obtenerPublicacion(id);
return publicacion;
}
@UseGuards(JwtAuthGuardAlumno)
@Get('listar')
async obtenerPublicaciones(): Promise< Publicacion[] >{
const publicaciones = await this.servicioPublicacion.obtenerPublicaciones();
return publicaciones;
}
@Get('buscar/sala/:id')
async buscarPublicacionSala(@Param('id') id:number): Promise< Publicacion[] | null >{
const publicacion = await this.servicioPublicacion.obtenerPublicacionPorCampo("idSala",""+id);
return publicacion;
}
}
|
7cf5d788b7375c8a3e5d838eaf1006c1ef52a6c4
|
TypeScript
|
lineCode/redis-om-node
|
/lib/search/where-array.ts
| 3.125
| 3
|
import Entity from "../entity/entity";
import Search from "./search";
import WhereField from "./where-field";
export default class WhereArray<TEntity extends Entity> extends WhereField<TEntity> {
private value!: string[];
contain(value: string): Search<TEntity> {
this.value = [value];
return this.search;
}
contains(value: string): Search<TEntity> { return this.contain(value); }
containsOneOf(...value: string[]): Search<TEntity> {
this.value = value;
return this.search;
}
containOneOf(...value: string[]): Search<TEntity> { return this.containsOneOf(...value); }
toString(): string {
let matchPunctuation = /[,.<>{}[\]"':;!@#$%^&*()\-+=~| ]/g;
let escapedValue = this.value.map(s => s.replace(matchPunctuation, '\\$&')).join('|');
return this.buildQuery(`{${escapedValue}}`);
}
}
|
c11d7af96d4490803eeb86a559c72886a7443b1c
|
TypeScript
|
dgp-web/dgp-ng-app
|
/projects/dgp-ng-charts/src/lib/shared/functions/normal/create-normal-interpolator.function.ts
| 2.671875
| 3
|
import * as d3 from "d3";
import { Many } from "data-modeling";
import { getProbabilityChartPMax } from "../probability-chart/get-probability-chart-p-max.function";
import { getProbabilityChartPMin } from "../probability-chart/get-probability-chart-p-min.function";
import { getNormalYCoordinate } from "./get-normal-y-coordinate.function";
import { computeDistance } from "../compute-distance.function";
import { reverseTComputation } from "../reverse-t-computation.function";
export function createNormalInterpolator(payload: {
readonly P?: Many<number>;
} = {}): d3.InterpolatorFactory<number, number> {
const P = payload.P;
const pMin = getProbabilityChartPMin({P});
const pMax = getProbabilityChartPMax({P});
const pMinY = getNormalYCoordinate({p: pMin});
const pMaxY = getNormalYCoordinate({p: pMax});
const referenceDistance = computeDistance({target: pMaxY, start: pMinY});
return (rangeStart: number, rangeTarget: number) => {
/**
* a and b are the range boundaries
*
* We compute the visual middle between them which is where our median value should be placed.
*/
const yPxDistance = computeDistance({target: rangeTarget, start: rangeStart});
return (t: number) => {
/**
* Note that the value t already gets transformed by d3.
*
* It's the computed distance of an input value between the domain boundaries.
*
* For us, this means that values between 0 and 100 are transformed back into values between 0 and 1.
*/
const p = reverseTComputation({value: t, min: pMin, max: pMax});
if (p === pMin) return rangeTarget;
if (p === pMax) return rangeStart;
const pY = getNormalYCoordinate({p});
const pYDistance = computeDistance({
target: pMaxY,
start: pY
});
const share = pYDistance / referenceDistance;
return share * yPxDistance;
};
};
}
|
ebf6a54a83a4ed719da1b0a8303bfbe5ac5117e0
|
TypeScript
|
Teaplus-S-Srisuwan-Dii-G-2/Typescript_WS
|
/src/employee.ts
| 3.625
| 4
|
interface configemployee {
name?: string
surnane?:string
employeeID?:number
age?:number
salary?:number
Bonus?:boolean
}
function C_employee(config:configemployee): {name:string;surnane:string;employeeID:number;age:number;salary:number;bonus:boolean}{
let newemployee = {name:"Default",surnane:"Default",employeeID:999999,age:99,salary:999999,bonus: false,bonus_out:99999}
if(config.name){
newemployee.name = config.name
}
if(config.surnane){
newemployee.surnane = config.surnane
}
if(config.employeeID){
newemployee.employeeID = config.employeeID
}
if(config.age){
newemployee.age = config.age
}
if(config.salary){
newemployee.salary = config.salary
}
if(config.Bonus){
newemployee.bonus = config.Bonus
if(newemployee.bonus == true){
newemployee.bonus_out = newemployee.salary*2.5
}
}
return newemployee
}
let My_employee =C_employee({name:"Dev-Dew",surnane:"dewathiwat",employeeID:632110,age:20,salary:21000,Bonus:true})
console.log('Output:',My_employee)
|
fbb5f7801f0ca40fda18018cc443d07a397154bd
|
TypeScript
|
VolodymyrRudeychuk/d3v4Angular4_chart
|
/src/app/shared/data.ts
| 2.921875
| 3
|
import { Component, OnInit } from '@angular/core';
export interface Frequency {
letter: string,
frequency: number,
}
export const letterStart = ["CN", "NG", "QA", "EG", "CZ", "HU", "HR", "SI", "IT", "PN"];
function getPositiveRandomArbitrary() {
return Math.floor(Math.random() * 100) + 17
}
function getNegativeRandomArbitrary() {
return Math.random() * (-100 - 0) + 0
}
setInterval(function () {
updateStatistic ()
}, 1000);
export const STATISTICS: Frequency[] =[{letter: "", frequency: 0}];
function updateStatistic () {
for(var i = 0; i < 5; i++) {
STATISTICS[i] = ({letter: letterStart[i], frequency: getPositiveRandomArbitrary()});
}
for(var i = 5; i < 10; i++) {
STATISTICS[i] = ({letter: letterStart[i], frequency: getNegativeRandomArbitrary()});
}
}
|
6f25081af6fa7f9ab807f82c1112c33a0f936a41
|
TypeScript
|
taokexia/ts-study
|
/src/base/enum.ts
| 4
| 4
|
// 数字枚举
enum Num {
One,
Two,
Three
}
console.log(Num.One === 0) // true
// 字符串枚举
enum Str {
Up = 'up',
Down = 'down'
}
console.log(Str.Up, Str.Down) // up down
// 异构枚举
enum Enum {
Num = 1,
Str = 'test'
}
// 反向映射
enum BackReflect {
Up,
Down,
Left,
Right = 'right'
}
console.log(BackReflect[0]) // Up
console.log(BackReflect['Right'])
// 常量枚举
const enum Enu {
Up = 'up',
Down = 'down'
}
const down = Enu.Down
// 枚举成员类型
enum Direction {
Up,
Down,
Left,
Right
}
const a = 0
console.log(a === Direction.Up) // true
type c = 0
declare let b: c
// b = 1 // 不能将类型“1”分配给类型“0”
b = Direction.Up // ok
declare let c:Direction
c = Direction.Down
// 给枚举添加方法
enum Week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
namespace Week {
export function isWork(day: Week) {
switch (day) {
case Week.Monday:
case Week.Tuesday:
case Week.Wednesday:
case Week.Thursday:
case Week.Friday:
return true;
default:
return false
}
}
}
|
604383c0c05ce1ed2f72798247fa1d7e40873ff4
|
TypeScript
|
avdeev1/tinkoff-social-network
|
/backend/src/auth/auth.service.ts
| 2.65625
| 3
|
import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Auth } from '../models/auth';
import { Repository } from 'typeorm';
import { User } from '../models/user';
import { RegisterUseDto } from './dto/registerUse.dto';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(Auth) private readonly authRepo: Repository<Auth>,
@InjectRepository(User) private readonly userRepo: Repository<User>,
) {}
async getUserByToken(token: string): Promise<User | null> {
const auth = await this.authRepo.findOne(
{ token },
{ relations: ['user'] },
);
if (auth) {
return auth.user;
}
return null;
}
async authUser(login: string, password: string): Promise<User | undefined> {
return await this.userRepo.findOne({ login, password });
}
async createToken(user: User): Promise<string> {
const auth = this.authRepo.create();
auth.user = user;
await this.authRepo.save(auth);
return auth.token;
}
async register(userDto: RegisterUseDto) {
if (userDto.password !== userDto.confirmPassword) {
throw new HttpException('Password does not match!', 400);
}
const user = this.userRepo.create({
login: userDto.login,
password: userDto.password,
});
await this.userRepo.save(user);
return this.createToken(user);
}
}
|
aeefa24fc6f470edbf17fe8bf200cf43afcc8b7d
|
TypeScript
|
commonlyjs/commonly
|
/packages/transducer/xhead/xhead.ts
| 2.828125
| 3
|
import Transducer from "../../type/Transducer/Transducer"
import xslice from "../xslice/xslice"
/**
* [Not yet documented]
*
* @since 1.0.0
*
* @returns
*/
const xhead = <TValue>(): Transducer<TValue> => {
return xslice(0, 1)
}
export default xhead
|
c2bdd12b8e3952afa151cd0a21df29e17786dfb2
|
TypeScript
|
perzeuss/LurkerBot
|
/bot/tools/stats/game_tracker.ts
| 2.65625
| 3
|
import { GuildMember } from "discord.js";
import * as UserMethods from "../user_methods";
import stats from "../stats/stats";
import { getMongoRepository } from "typeorm";
import { GameTime } from "../../../typeorm/models/game-time";
import { DiscordDBUser } from "../../../typeorm/models/discord-db-user";
import { GameType } from "../../../helpers/discord-js-enums";
import { DiscordDBUserHelper } from "../../../typeorm/helpers/discord-db-user-helper";
/**
* When the user starts playing a game, call this function.
* @param user
*/
function beginLogging(user: GuildMember, game: string) {
if (!user.presence.game.streaming && user.presence.game.type === GameType.PLAYING) {
stats.addGame(user, game);
}
}
/**
* When the user stops playing a game, call this function.
* @param user
*/
async function endLogging(user: GuildMember, game: string) {
const timeBegan: Date = stats.startedAt(user, game);
const timeEnded: Date = new Date();
stats.removeGame(user, game);
if (timeBegan === null || ((timeEnded.getTime() - timeBegan.getTime()) / 1000) < 1) {
return;
}
const match = await DiscordDBUserHelper.getUser(user.id);
if (!match) {
return;
}
console.log(`Processing gametime ${user.displayName} for ${game}`);
let newEntry = new GameTime();
newEntry.sessionBegin = timeBegan;
newEntry.sessionEnd = timeEnded;
newEntry.gameName = game;
newEntry.userId = match.userId;
newEntry.gameDetail = user.presence.game.details ? user.presence.game.details : null;
newEntry.gameState = user.presence.game.state;
if (game === "League of Legends") {
newEntry.gameType = user.presence.game.assets ? user.presence.game.assets.largeText : null;
}
const gameTimeRepository = getMongoRepository(GameTime);
gameTimeRepository.insertOne(newEntry);
console.log(`Logged ${(timeEnded.getTime() - timeBegan.getTime()) / 1000} seconds for ${match.username} playing ${newEntry.gameName}`);
// If a valid number of seconds, be sure to add it to the database.
// writeNewTimeRow(user, seconds);
}
export default function (before: GuildMember, after: GuildMember) {
const beforeGameName = UserMethods.getGameName(before);
const afterGameName = UserMethods.getGameName(after);
const userQuitGame = beforeGameName && beforeGameName !== afterGameName;
const presenceChanged = beforeGameName === afterGameName && JSON.stringify(before.presence.game) !== JSON.stringify(after.presence.game);
// If the user has a game on before, that means they quit that game.
if (userQuitGame || presenceChanged) {
endLogging(before, beforeGameName);
}
// If the user has a game on after, that means they began playing the game
if (afterGameName) {
beginLogging(after, afterGameName);
}
}
|
035283d7f1f937e2816cea47969e3cdfe747e8ad
|
TypeScript
|
rickyhopkins/spyfalling
|
/src/context/authentication.ts
| 2.703125
| 3
|
import React from "react";
export interface User {
_id: string;
name: string;
avatar: string;
}
export interface UserProfile {
displayName?: User["name"];
avatar?: User["avatar"];
}
interface Authentication {
user?: User;
addUser?(name: string): Promise<boolean>;
}
const AuthenticationContext = React.createContext<Authentication>({});
export default AuthenticationContext;
|
6233450a2585e883310bf47f6e9b8d9e9a33d81d
|
TypeScript
|
gumiranda/ts-api-devdoidobackup
|
/projetoAntigo/controller-base.ts
| 2.59375
| 3
|
const post = async (repository, validationContract, res, modelData) => {
try {
if (!validationContract.isValid()) {
res
.status(400)
.send({
message: 'Existem dados inválidos na sua requisição',
validation: validationContract.errors(),
})
.end();
return;
}
const resultado = await repository.create(modelData);
res.status(201).send(resultado);
} catch (e) {
res.status(500).send({ message: 'Internal server error', error: e });
}
};
const put = async (repository, validationContract, req, res) => {
try {
const data = req.body;
if (!validationContract.isValid()) {
res
.status(400)
.send({
message: 'Existem dados inválidos na sua requisição',
validation: validationContract.errors(),
})
.end();
return;
}
const resultado = await repository.update(
req.params.id,
data,
req.usuarioLogado.user,
);
res.status(202).send(resultado);
} catch (e) {
res.status(500).send({ message: 'Internal server error', error: e });
}
};
const get = async (repository, req, res) => {
try {
const resultado = await repository.getAll();
res.status(200).send(resultado);
} catch (erro) {
res.status(500).send({ message: 'Erro no processamento', error: erro });
}
};
const getById = async (repository, req, res) => {
try {
const resultado = await repository.getById(req.params.id);
res.status(200).send(resultado);
} catch (erro) {
res.status(500).send({ message: 'Erro no processamento', error: erro });
}
};
const getMyAll = async (repository, req, res) => {
try {
const resultado = await repository.getMyAll(req.usuarioLogado.user);
res.status(200).send(resultado);
} catch (erro) {
res.status(500).send({ message: 'Erro no processamento', error: erro });
}
};
const getMy = async (repository, validationContract, req, res) => {
try {
if (!validationContract.isValid()) {
res
.status(400)
.send({
message: 'Existem dados inválidos na sua requisição',
validation: validationContract.errors(),
})
.end();
return;
}
const resultado = await repository.getMy(
req.params.page,
req.usuarioLogado.user,
);
res.status(200).send(resultado);
} catch (erro) {
res.status(500).send({ message: 'Erro no processamento', error: erro });
}
};
const remove = async (repository, req, res) => {
try {
const { id } = req.params;
if (id) {
const resultado = await repository.delete(id, req.usuarioLogado);
if (resultado !== 'Operação Inválida') {
res.status(200).send({ message: 'Registro excluído com sucesso' });
} else {
res.status(401).send({ message: 'Operação inválida' });
}
} else {
res.status(500).send({ message: 'O parametro id precisa ser informado' });
}
} catch (e) {
res.status(500).send({ message: 'Internal server error', error: e });
}
};
export default {
post,
put,
remove,
getById,
get,
getMy,
getMyAll,
};
|
6e40222ce5da10457f289e8b36e1aff1a44241f8
|
TypeScript
|
thomicdk/relinq
|
/src/deferred-iterable.ts
| 3.140625
| 3
|
/** @internal */
export type DeferredIterable<TSource> = () => IterableIterator<TSource>;
/** @internal */
export function createDeferredIterable<TSource>(source: Iterable<TSource>): DeferredIterable<TSource> {
return function*() {
for (let item of source) {
yield item;
}
}
}
|
8d16c1d0c4b6a0a4ec964336a240093eb68afb80
|
TypeScript
|
jackzoom/JMLotto_Node
|
/src/config/ticket.config.ts
| 3.0625
| 3
|
interface RankRulesType {
[key: string]: {
name: string;
bonus: string | number;
bonusUnit: string;
rules: any;
};
}
/**
* 奖项级别信息
* @see https://www.lottery.gov.cn/dlt/ltjsq/index.html
*/
export const LottoRankRules: RankRulesType = {
0: {
name: "未中奖",
bonus: "",
bonusUnit: "",
rules: [],
},
1: {
name: "一等奖",
bonus: 33, //TODO:暂时按照最低标准
bonusUnit: "%",
rules: [
{
blue: 2,
red: 5,
},
],
},
2: {
name: "二等奖",
bonus: 18,
bonusUnit: "%",
rules: [
{
blue: 1,
red: 5,
},
],
},
3: {
name: "三等奖",
bonus: 10000,
bonusUnit: "¥",
rules: [
{
blue: 0,
red: 5,
},
],
},
4: {
name: "四等奖",
bonus: 3000,
bonusUnit: "¥",
rules: [
{
blue: 2,
red: 4,
},
],
},
5: {
name: "五等奖",
bonus: 300,
bonusUnit: "¥",
rules: [
{
blue: 1,
red: 4,
},
],
},
6: {
name: "六等奖",
bonus: 200,
bonusUnit: "¥",
rules: [
{
blue: 2,
red: 3,
},
],
},
7: {
name: "七等奖",
bonus: 100,
bonusUnit: "¥",
rules: [
{
blue: 0,
red: 4,
},
],
},
8: {
name: "八等奖",
bonus: 15,
bonusUnit: "¥",
rules: [
{
blue: 1,
red: 3,
},
{
blue: 2,
red: 2,
},
],
},
9: {
name: "九等奖",
bonus: 5,
bonusUnit: "¥",
rules: [
{
blue: 0,
red: 3,
},
{
blue: 1,
red: 2,
},
{
blue: 2,
red: 1,
},
{
blue: 2,
red: 0,
},
],
},
};
|
b2c911ed39fba5bd370ae38b5c82525715bf2fc5
|
TypeScript
|
Kiranmaii/RecipeBook
|
/src/app/recipe-list/recipe-filter.pipe.ts
| 2.734375
| 3
|
import { PipeTransform, Pipe } from '@angular/core';
import { Recipes } from '../shared/recipes.model';
@Pipe({
name: 'Filter'
})
export class RecipeFilterPipe implements PipeTransform {
transform(recipe: Recipes[], search: string): Recipes[] {
if (!recipe || !search){
return recipe;
}
return recipe.filter(recipes=>
recipes.name.toLowerCase().indexOf(search.toLowerCase()) !== -1);
}
}
|
f444b9554f63b802a10166bae404d62ea8dd5c4c
|
TypeScript
|
zhougz520/draft-ts
|
/src/component/selection/isSelectionAtLeafStart.ts
| 2.59375
| 3
|
import { EditorState } from '../model/immutable/EditorState';
import { SelectionState } from '../model/immutable/SelectionState';
import { List } from 'immutable';
export function isSelectionAtLeafStart(editorState: EditorState): boolean {
const selection: SelectionState = editorState.getSelection();
const anchorKey: string = selection.getAnchorKey();
const blockTree: List<any> = editorState.getBlockTree(anchorKey);
const offset: number = selection.getStartOffset();
let isAtStart: boolean = false;
blockTree.some(
(leafSet: any) => {
if (offset === leafSet.get('start')) {
isAtStart = true;
return true;
}
if (offset < leafSet.get('end')) {
return leafSet.get('leaves').some(
(leaf: any) => {
const leafStart: number = leaf.get('start');
if (offset === leafStart) {
isAtStart = true;
return true;
}
return false;
});
}
return false;
}
);
return isAtStart;
}
|
65ce6c446c347e95193f7d43e9a508533d74010f
|
TypeScript
|
kyen99/next.js
|
/packages/font/src/local/utils.ts
| 2.78125
| 3
|
import { AdjustFontFallback } from 'next/font'
const allowedDisplayValues = ['auto', 'block', 'swap', 'fallback', 'optional']
const formatValues = (values: string[]) =>
values.map((val) => `\`${val}\``).join(', ')
const extToFormat = {
woff: 'woff',
woff2: 'woff2',
ttf: 'truetype',
otf: 'opentype',
eot: 'embedded-opentype',
}
type FontOptions = {
family: string
files: Array<{
file: string
ext: string
format: string
unicodeRange?: string
}>
display: string
weight?: number
style?: string
fallback?: string[]
preload: boolean
variable?: string
ascentOverride?: string
descentOverride?: string
fontStretch?: string
fontVariant?: string
fontFeatureSettings?: string
fontVariationSettings?: string
lineGapOverride?: string
sizeAdjust?: string
adjustFontFallback?: AdjustFontFallback
}
export function validateData(functionName: string, data: any): FontOptions {
if (functionName) {
throw new Error(`@next/font/local has no named exports`)
}
let {
src,
display = 'optional',
weight,
style,
fallback,
preload = true,
variable,
ascentOverride,
descentOverride,
fontStretch,
fontVariant,
fontFeatureSettings,
fontVariationSettings,
lineGapOverride,
sizeAdjust,
adjustFontFallback,
} = data[0] || ({} as any)
if (!allowedDisplayValues.includes(display)) {
throw new Error(
`Invalid display value \`${display}\`.\nAvailable display values: ${formatValues(
allowedDisplayValues
)}`
)
}
const srcArray = Array.isArray(src) ? src : [{ file: src }]
if (srcArray.length === 0) {
throw new Error('Src must contain one or more files')
}
const files = srcArray.map(({ file, unicodeRange }) => {
if (!file) {
throw new Error('Src array objects must have a `file` property')
}
if (srcArray.length > 1 && !unicodeRange) {
throw new Error(
"Files must have a unicode-range if there's more than one"
)
}
const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(file)?.[1]
if (!ext) {
throw new Error(`Unexpected file \`${file}\``)
}
return {
file,
unicodeRange,
ext,
format: extToFormat[ext as 'woff' | 'woff2' | 'eot' | 'ttf' | 'otf'],
}
})
const family = /.+\/(.+?)\./.exec(files[0].file)![1]
return {
family,
files,
display,
weight,
style,
fallback,
preload,
variable,
ascentOverride,
descentOverride,
fontStretch,
fontVariant,
fontFeatureSettings,
fontVariationSettings,
lineGapOverride,
sizeAdjust,
adjustFontFallback,
}
}
|
b161473d532bc8dfe034e1bf99aff4fadceab30d
|
TypeScript
|
JVH31/up-goe
|
/src/app/student/general/pages/gen-profile/gen-profile.component.ts
| 2.796875
| 3
|
//Core Imports
import {
Component,
OnInit
} from '@angular/core';
import {
NgModel
} from '@angular/forms';
//Application Imports
import {
Course,
Quest,
User
} from 'shared/models';
import {
PageService,
UserService
} from 'shared/services';
/* AHJ: Remove once the services are implemented properly */
const SECTIONS: any[] = [
{
course_name: "CMSC 128",
section_name: "A",
week_total_exp: [10, 30, 70, 300, 500],
max_exp: 700
},
{
course_name: "CMSC 128",
section_name: "B",
week_total_exp: [120, 40, 80, 321, 700],
max_exp: 1200
},
{
course_name: "CMSC 141",
section_name: "J",
week_total_exp: [10, 30, 70, 300, 500],
max_exp: 1000
},
];
//TOTXP - total accumulative weekly experience points of current student
const TOTXP: number[] = [1000, 2123, 3439, 4655, 6053, 6104];
//MAXXP - the max experience points to obtain a 1.0 grade
const MAXXP: number = 10000;
@Component({
selector: 'app-gen-profile',
templateUrl: './gen-profile.component.html',
styleUrls: ['./gen-profile.component.css']
})
export class GenProfileComponent implements OnInit {
user: User;
// lineChart
lineChartColors: Array<any>;
lineChartData: Array<any> = [];
lineChartLabels: Array<any> = ['Week 0', 'Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9', 'Week 10', 'Week 11', 'Week 12', 'Week 13', 'Week 14', 'Week 15', 'Week 16'];
lineChartOptions: any = {
responsive: true,
scales: {
yAxes: [{ id: 'y-axis-1', type: 'linear', position: 'left', ticks: { min: 0, max: 100 } }]
}
};
/**
* @constructor
*
* @param pageService: used to identify that the profile page is currently navigated on
* @param userService used to obtains data needed for user
*/
constructor(
private pageService: PageService,
private userService: UserService
) {
}
ngOnInit() {
this.pageService.isProfilePage(true);
this.getUser();
this.getGrades();
this.setPerformanceGraph();
}
/**
* Stores the current user
* @description Stores the current user to the 'user' variable from the user.service function
*/
getUser(): void {
//ced make curUser in userService or use localStorage
this.user = this.userService.getCurrentUser()
}
/**
* Display the user's grades in the performance graph
* @description Obtains the current user's array of weekly grades (or experience points) in an accumulative manner (e.g [1, 20, 200...]),
* computes its relative percentage based on the section's max experience points and sets the performance graph's value with this
* computed array of percentage.
*/
getGrades(): void {
let grades = TOTXP ? TOTXP : [];
let max: number = MAXXP ? MAXXP : 10;
//AHJ: unimplemented
//replace SECTIONS with this.getUserSectionExp(user_id) [section.service] function if the function is working
SECTIONS.forEach(section => {
let dataGrade: number[] = [];
//convert the user's section weekly accumulative exp into dataset readable by performance graph
section.week_total_exp.forEach(grade => {
// get the decimal percentage
let percentage: number = (grade / section.max_exp) * 100;
// round the decimal up to two decimal points
dataGrade.push(Math.round((percentage + 0.00001) * 100) / 100);
});
let className = section.course_name + " - " + section.section_name;
let dataLine: any = {
data: dataGrade,
label: className
};
this.lineChartData.push(dataLine);
})
}
/* Below are the helper functions */
/**
* Sets the performance graph's display and design in the profile page
*/
setPerformanceGraph() {
this.lineChartColors = this.pageService.lineChartColors;
this.lineChartLabels = ['Week 0', 'Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9', 'Week 10', 'Week 11', 'Week 12', 'Week 13', 'Week 14', 'Week 15', 'Week 16'];
this.lineChartOptions = {
responsive: true,
scales: {
yAxes: [{ id: 'y-axis-1', type: 'linear', position: 'left', ticks: { min: 0, max: 100 } }]
}
};
}
/**
* @public
*
* @summary Triggers when chart is clicked
* @param e
*/
public chartClicked(e: any): void {
console.log(e);
}
/**
* @public
*
* @summary Triggers when chart is hovered
* @param e
*/
public chartHovered(e: any): void {
console.log(e);
}
}
|
8db523f7e7b7cdf46404af299ba9aee60caa039a
|
TypeScript
|
jacob-ebey/gremlin-helper
|
/src/Schema.ts
| 3.046875
| 3
|
export type SchemaType = 'string' | 'number' | string;
export interface IPropDef {
type: SchemaType;
required?: boolean;
}
// type Required<T> = {
// [P in Purify<keyof T>]: NonNullable<T[P]>;
// };
export type NonNullable<T> = T & {};
export type Purify<T extends string> = {[P in T]: T; }[T];
export type PropDef = SchemaType | IPropDef;
export interface IVertexSchema<T = void> {
label: string;
props?: {
[P in Purify<keyof T>]: NonNullable<PropDef>;
}
}
export interface IEdgeSchema<T = void> {
label: string;
props?: {
[P in Purify<keyof T>]: NonNullable<PropDef>;
}
}
|
edb00aab05f067ddb89949dc11b8724555647fcf
|
TypeScript
|
muzea/aliyun-sdk-node
|
/dist/ecs/ModifyAutoSnapshotPolicyEx/req.d.ts
| 2.625
| 3
|
interface ModifyAutoSnapshotPolicyExRequest {
"RegionId"?: string;
/**
* 自动快照策略所在的地域 ID。您可以调用 [DescribeRegions](~~25609~~) 查看最新的阿里云地域列表。
* @example `cn-hangzhou`
*/ "regionId": string;
/**
* 目标自动快照策略 ID。您可以调用 [DescribeAutoSnapshotPolicyEx](~~25530~~) 查看您可用的自动快照策略。
* @example `p-autopolicyid1`
*/ "autoSnapshotPolicyId": string;
"SourceRegionId"?: string;
/**
* RAM用户的虚拟账号ID。
* @example `155780923770`
*/ "OwnerId"?: number;
/**
* 自动快照策略的名称。如果参数为空则代表不修改。
* @example `FinanceJoshua`
*/ "autoSnapshotPolicyName"?: string;
/**
* 自动快照的创建时间点,单位为小时。取值范围:0~23,代表 00:00 至 23:00 共 24 个时间点,如 1 表示 01:00。当一天内需要创建多次自动快照时,可以传入多个时间点:
* - 最多传入 24 个时间点。
* - 多个时间点用一个格式类似 "0", "1", … "23" 的 JSON 数组表示,时间点之间用半角逗号(,)隔开。
* @example `["0", "1"]`
*/ "timePoints"?: string;
/**
* 自动快照的重复日期,单位为天,周期为星期。取值范围:1~7,如 1 表示周一。当一星期内需要创建多次自动快照时,可以传入多个时间点:
* - 最多传入 7 个时间点。
* - 多个时间点用一个格式类似 "1", "2", … "7" 的 JSON 数组表示,时间点之间用半角逗号(,)隔开。
* @example `["1", "7"]`
*/ "repeatWeekdays"?: string;
/**
* 自动快照的保留时间,单位为天。取值范围:
* - -1(默认):永久保存。
* - 1~65536:指定保存天数。
* @example `30`
*/ "retentionDays"?: number;
}
export { ModifyAutoSnapshotPolicyExRequest };
|
e9ac6873fb52c23861e397892ab495cda1d74c3a
|
TypeScript
|
pchevilley/2020-onboarding-project
|
/core/src/Classes/Movies.test.ts
| 2.671875
| 3
|
import axios from "axios";
import Movies from "./Movies";
import Genres from "./Genres";
import Sorting from "./Sorting";
const genres = new Genres();
const movies = new Movies();
const sorting = new Sorting();
jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;
it("should return a valid TMDb url", () => {
genres.toggleGenre({ id: 27, name: "Horror" });
sorting.setSortingOption("releaseDate");
expect(movies.getFetchUrl()).toBeDefined();
});
it("should change the current page number", () => {
movies.setCurrentPage(2);
expect(movies.currentPage).toBe(2);
});
it("should fetch a movie list", async () => {
mockedAxios.get.mockResolvedValue({
data: {
results: [
{
id: 1,
voteAverage: 45,
posterPath:
"https://image.tmdb.org/t/p/w220_and_h330_face/jsMVRjLwKWN3gaiGd9pJUrxezsp.jpg",
releaseDate: "12/03/2020",
title: "Blade Runner 2049",
url: "https://www.themoviedb.org/movie/335984",
},
],
},
});
const list = await movies.fetchMovies(true);
expect(list.length).toBeGreaterThan(0);
expect(list[0].title).toBe("Blade Runner 2049");
});
|
6673c141696d4b17cd376cce6c9e5191a50e4142
|
TypeScript
|
diggitus/stock-analyzer
|
/src/app/model/cashFlowRatios.ts
| 2.6875
| 3
|
/**
* Cash Flow Ratios Class
*/
export class CashFlowRatios {
operatingCashFlowGrowth: Array<number> | null;
freeCashFlowGrowth: Array<number> | null;
capExAOfSales: Array<number> | null;
freeCashFlowSales: Array<number> | null;
freeCashFlowNetIncome: Array<number> | null;
/**
* Constructor.
*/
constructor() {
this.operatingCashFlowGrowth = null;
this.freeCashFlowGrowth = null;
this.capExAOfSales = null;
this.freeCashFlowSales = null;
this.freeCashFlowNetIncome = null;
}
}
|
b6c30d0fd3f2d986ea1718740a3a838dbfd77729
|
TypeScript
|
NichijouCC/ToyGL
|
/src/webgl/pixelFormatEnum.ts
| 2.75
| 3
|
/* eslint-disable no-redeclare */
/* eslint-disable import/export */
import { TypedArray } from "../core/typedArray";
import { GlConstants } from "./glConstant";
import { PixelDatatypeEnum } from "./pixelDatatype";
export enum PixelFormatEnum {
DEPTH_COMPONENT16 = GlConstants.DEPTH_COMPONENT16,
/**
* A pixel format containing a depth value.
*/
DEPTH_COMPONENT = GlConstants.DEPTH_COMPONENT,
/**
* A pixel format containing a depth and stencil value, most often used with {@link PixelDatatype.UNSIGNED_INT_24_8}.
*/
DEPTH_STENCIL = GlConstants.DEPTH_STENCIL,
/**
* A pixel format containing an alpha channel.
*/
ALPHA = GlConstants.ALPHA,
/**
* A pixel format containing red, green, and blue channels.
*/
RGB = GlConstants.RGB,
/**
* A pixel format containing red, green, blue, and alpha channels.
*/
RGBA = GlConstants.RGBA,
/**
* A pixel format containing a luminance (intensity) channel.
*/
LUMINANCE = GlConstants.LUMINANCE,
/**
* A pixel format containing luminance (intensity) and alpha channels.
*/
LUMINANCE_ALPHA = GlConstants.LUMINANCE_ALPHA,
/**
* A pixel format containing red, green, and blue channels that is DXT1 compressed.
*/
RGB_DXT1 = GlConstants.COMPRESSED_RGB_S3TC_DXT1_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT1 compressed.
*/
RGBA_DXT1 = GlConstants.COMPRESSED_RGBA_S3TC_DXT1_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT3 compressed.
*/
RGBA_DXT3 = GlConstants.COMPRESSED_RGBA_S3TC_DXT3_EXT,
/**
* A pixel format containing red, green, blue, and alpha channels that is DXT5 compressed.
*/
RGBA_DXT5 = GlConstants.COMPRESSED_RGBA_S3TC_DXT5_EXT,
/**
* A pixel format containing red, green, and blue channels that is PVR 4bpp compressed.
*/
RGB_PVRTC_4BPPV1 = GlConstants.COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
/**
* A pixel format containing red, green, and blue channels that is PVR 2bpp compressed.
*/
RGB_PVRTC_2BPPV1 = GlConstants.COMPRESSED_RGB_PVRTC_2BPPV1_IMG,
/**
* A pixel format containing red, green, blue, and alpha channels that is PVR 4bpp compressed.
*/
RGBA_PVRTC_4BPPV1 = GlConstants.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,
/**
* A pixel format containing red, green, blue, and alpha channels that is PVR 2bpp compressed.
*/
RGBA_PVRTC_2BPPV1 = GlConstants.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG,
/**
* A pixel format containing red, green, and blue channels that is ETC1 compressed.
*/
RGB_ETC1 = GlConstants.COMPRESSED_RGB_ETC1_WEBGL,
}
export namespace PixelFormatEnum {
/**
* @private
*/
export function componentsLength(pixelFormat: PixelFormatEnum) {
switch (pixelFormat) {
case PixelFormatEnum.RGB:
return 3;
case PixelFormatEnum.RGBA:
return 4;
case PixelFormatEnum.LUMINANCE_ALPHA:
return 2;
case PixelFormatEnum.ALPHA:
case PixelFormatEnum.LUMINANCE:
return 1;
default:
return 1;
}
}
export function validate(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.DEPTH_COMPONENT ||
pixelFormat === PixelFormatEnum.DEPTH_STENCIL ||
pixelFormat === PixelFormatEnum.ALPHA ||
pixelFormat === PixelFormatEnum.RGB ||
pixelFormat === PixelFormatEnum.RGBA ||
pixelFormat === PixelFormatEnum.LUMINANCE ||
pixelFormat === PixelFormatEnum.LUMINANCE_ALPHA ||
pixelFormat === PixelFormatEnum.RGB_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT3 ||
pixelFormat === PixelFormatEnum.RGBA_DXT5 ||
pixelFormat === PixelFormatEnum.RGB_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGB_PVRTC_2BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_2BPPV1 ||
pixelFormat === PixelFormatEnum.RGB_ETC1;
}
export function isColorFormat(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.ALPHA ||
pixelFormat === PixelFormatEnum.RGB ||
pixelFormat === PixelFormatEnum.RGBA ||
pixelFormat === PixelFormatEnum.LUMINANCE ||
pixelFormat === PixelFormatEnum.LUMINANCE_ALPHA;
}
export function isDepthFormat(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.DEPTH_COMPONENT ||
pixelFormat === PixelFormatEnum.DEPTH_STENCIL;
}
export function isCompressedFormat(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.RGB_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT3 ||
pixelFormat === PixelFormatEnum.RGBA_DXT5 ||
pixelFormat === PixelFormatEnum.RGB_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGB_PVRTC_2BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_2BPPV1 ||
pixelFormat === PixelFormatEnum.RGB_ETC1;
}
export function isDXTFormat(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.RGB_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT1 ||
pixelFormat === PixelFormatEnum.RGBA_DXT3 ||
pixelFormat === PixelFormatEnum.RGBA_DXT5;
}
export function isPVRTCFormat(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.RGB_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGB_PVRTC_2BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_4BPPV1 ||
pixelFormat === PixelFormatEnum.RGBA_PVRTC_2BPPV1;
}
export function isETC1Format(pixelFormat: PixelFormatEnum) {
return pixelFormat === PixelFormatEnum.RGB_ETC1;
}
;
export function compressedTextureSizeInBytes(pixelFormat: PixelFormatEnum, width: number, height: number) {
switch (pixelFormat) {
case PixelFormatEnum.RGB_DXT1:
case PixelFormatEnum.RGBA_DXT1:
case PixelFormatEnum.RGB_ETC1:
return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8;
case PixelFormatEnum.RGBA_DXT3:
case PixelFormatEnum.RGBA_DXT5:
return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16;
case PixelFormatEnum.RGB_PVRTC_4BPPV1:
case PixelFormatEnum.RGBA_PVRTC_4BPPV1:
return Math.floor((Math.max(width, 8) * Math.max(height, 8) * 4 + 7) / 8);
case PixelFormatEnum.RGB_PVRTC_2BPPV1:
case PixelFormatEnum.RGBA_PVRTC_2BPPV1:
return Math.floor((Math.max(width, 16) * Math.max(height, 8) * 2 + 7) / 8);
default:
return 0;
}
}
export function textureSizeInBytes(pixelFormat: PixelFormatEnum, pixelDatatype: PixelDatatypeEnum, width: number, height: number) {
var componentsLength = PixelFormatEnum.componentsLength(pixelFormat);
if (PixelDatatypeEnum.isPacked(pixelDatatype)) {
componentsLength = 1;
}
return componentsLength * PixelDatatypeEnum.sizeInBytes(pixelDatatype) * width * height;
}
export function alignmentInBytes(pixelFormat: PixelFormatEnum, pixelDatatype: PixelDatatypeEnum, width: number) {
var mod = PixelFormatEnum.textureSizeInBytes(pixelFormat, pixelDatatype, width, 1) % 4;
return mod === 0 ? 4 : (mod === 2 ? 2 : 1);
}
export function createTypedArray(pixelFormat: PixelFormatEnum, pixelDatatype: PixelDatatypeEnum, width: number, height: number) {
var constructor;
var sizeInBytes = PixelDatatypeEnum.sizeInBytes(pixelDatatype);
if (sizeInBytes === Uint8Array.BYTES_PER_ELEMENT) {
constructor = Uint8Array;
} else if (sizeInBytes === Uint16Array.BYTES_PER_ELEMENT) {
constructor = Uint16Array;
} else if (sizeInBytes === Float32Array.BYTES_PER_ELEMENT && pixelDatatype === PixelDatatypeEnum.FLOAT) {
constructor = Float32Array;
} else {
constructor = Uint32Array;
}
var size = PixelFormatEnum.componentsLength(pixelFormat) * width * height;
return new constructor(size);
}
export function flipY(bufferView: TypedArray, pixelFormat: PixelFormatEnum, pixelDatatype: PixelDatatypeEnum, width: number, height: number) {
if (height === 1) {
return bufferView;
}
var flipped = PixelFormatEnum.createTypedArray(pixelFormat, pixelDatatype, width, height);
var numberOfComponents = PixelFormatEnum.componentsLength(pixelFormat);
var textureWidth = width * numberOfComponents;
for (var i = 0; i < height; ++i) {
var row = i * height * numberOfComponents;
var flippedRow = (height - i - 1) * height * numberOfComponents;
for (var j = 0; j < textureWidth; ++j) {
flipped[flippedRow + j] = bufferView[row + j];
}
}
return flipped;
}
}
|
dd61154bbc09d59ec27140af55ed1b8a697b2cd1
|
TypeScript
|
yami-beta/nextjs-todo-sample-template
|
/src/modules/todoSlice.ts
| 2.8125
| 3
|
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { v4 as uuidv4 } from "uuid";
export type Todo = {
id: string;
text: string;
completed: boolean;
};
type TodoState = {
todos: Todo[];
};
export const todoInitialState: TodoState = {
todos: [
{ id: uuidv4(), text: "todo0", completed: false },
{ id: uuidv4(), text: "todo1", completed: false },
{ id: uuidv4(), text: "todo2", completed: false },
],
};
const todoSlice = createSlice({
name: "todo",
initialState: todoInitialState,
reducers: {
addTodo: (state, action: PayloadAction<Todo>) => {
return {
...state,
todos: [...state.todos, action.payload],
};
},
},
});
export const { addTodo } = todoSlice.actions;
export const todoReducer = todoSlice.reducer;
|
6eeb53ea9cfc0f1dd63f0e472294f7e127852b61
|
TypeScript
|
mdbobskiy777/social_network
|
/src/redux/users-reducer.ts
| 2.671875
| 3
|
import {DeleteFollowType, PostFollowType, usersAPI} from "../api/api"
import {updateObjectInArray} from "../utils/object-helpers"
import {PhotosType} from "./profile-reducer";
import {Dispatch} from "redux";
const FOLLOW = 'users-reducer/FOLLOW'
const UNFOLLOW = 'users-reducer/UNFOLLOW'
const SET_USERS = 'users-reducer/SET_USERS'
const SET_CURRENT_PAGE = 'users-reducer/SET_CURRENT_PAGE'
const SET_TOTAL_USERS_COUNT = 'users-reducer/SET_TOTAL_USERS_COUNT'
const TOGGLE_IS_FETCHING = 'users-reducer/TOGGLE_IS_FETCHING';
const TOGGLE_IS_FOLLOWING_PROGRESS = 'users-reducer/TOGGLE_IS_FOLLOWING_PROGRESS'
export type UserType = {
name: string
id: number
uniqueUrlName: null | string
photos: PhotosType
status: string
followed: boolean
}
type AcceptFollowActionType = {
type: typeof FOLLOW
userId: number
}
type AcceptUnfollowActionType = {
type: typeof UNFOLLOW
userId: number
}
type ToggleFollowProgressActionType = {
type: typeof TOGGLE_IS_FOLLOWING_PROGRESS
isFetching: boolean
id: number
}
type SetUsersActionType = {
type: typeof SET_USERS
users: Array<UserType>
}
type SetCurrentPageActionType = {
type: typeof SET_CURRENT_PAGE
currentPage: number
}
type SetTotalUserCount = {
type: typeof SET_TOTAL_USERS_COUNT
count: number
}
type ToggleIsFetching = {
type: typeof TOGGLE_IS_FETCHING
isFetching: boolean
}
let initialState = {
users: [] as Array<UserType>,
pageSize: 5,
totalUsersCount: 0,
currentPage: 1,
isFetching: true,
followingInProgress: [] as Array<number>,
};
type InitialStateType = typeof initialState
const usersReducer = (state = initialState, action: any): InitialStateType => {
switch (action.type) {
case FOLLOW:
return {
...state,
users: updateObjectInArray(state.users,
action.userId,
"id",
{followed: true})
}
case UNFOLLOW:
return {
...state,
users: updateObjectInArray(state.users, action.userId,
"id",
{followed: false}
)
}
case SET_USERS: {
return {...state, users: action.users}
}
case SET_CURRENT_PAGE: {
return {...state, currentPage: action.currentPage}
}
case SET_TOTAL_USERS_COUNT: {
return {...state, totalUsersCount: action.count}
}
case TOGGLE_IS_FETCHING: {
return {...state, isFetching: action.isFetching}
}
case TOGGLE_IS_FOLLOWING_PROGRESS: {
return {
...state, followingInProgress: action.isFetching ? [...state.followingInProgress, action.id]
: state.followingInProgress.filter(id => id !== action.id)
}
}
default:
return state;
}
}
const acceptFollow = (userId: number): AcceptFollowActionType => ({type: FOLLOW, userId})
type AcceptFollowType = typeof acceptFollow
const acceptUnfollow = (userId: number): AcceptUnfollowActionType => ({type: UNFOLLOW, userId})
type AcceptUnfollowType = typeof acceptUnfollow
const toggleFollowingProgress = (isFetching: boolean, id: number): ToggleFollowProgressActionType =>
({type: TOGGLE_IS_FOLLOWING_PROGRESS, isFetching, id})
export const setUsers = (users: Array<UserType>): SetUsersActionType => ({type: SET_USERS, users})
export const setCurrentPage = (currentPage: number): SetCurrentPageActionType => ({type: SET_CURRENT_PAGE, currentPage})
export const setTotalUsersCount = (totalUsersCount: number): SetTotalUserCount => ({
type: SET_TOTAL_USERS_COUNT,
count: totalUsersCount
})
export const toggleIsFetching = (isFetching: boolean): ToggleIsFetching => ({type: TOGGLE_IS_FETCHING, isFetching})
export const getUsers = (currentPage: number, pageSize: number) => async (dispatch: (arg0: { type: "users-reducer/TOGGLE_IS_FETCHING" | "users-reducer/SET_USERS" | "users-reducer/SET_TOTAL_USERS_COUNT"; isFetching?: boolean; users?: UserType[]; count?: number; }) => void) => {
dispatch(toggleIsFetching(true));
let data = await usersAPI.getUsers(currentPage, pageSize)
dispatch(toggleIsFetching(false));
dispatch(setUsers(data.items));
dispatch(setTotalUsersCount(data.totalCount));
}
export const followUnfollowFlow = async (dispatch: Dispatch<AcceptFollowActionType |
AcceptUnfollowActionType |
ToggleFollowProgressActionType>,
id: number,
apiMethod: PostFollowType | DeleteFollowType,
actionCreator: AcceptFollowType |
AcceptUnfollowType) => {
dispatch(toggleFollowingProgress(true, id))
let data = await apiMethod(id)
if (data.resultCode === 0) {
dispatch(actionCreator(id))
}
dispatch(toggleFollowingProgress(false, id))
}
export const follow = (id: number) => async (dispatch: Dispatch<AcceptFollowActionType |
AcceptUnfollowActionType |
ToggleFollowProgressActionType>) => {
await followUnfollowFlow(dispatch, id, usersAPI.postFollow.bind(usersAPI), acceptFollow)
}
export const unfollow = (id: number) => async (dispatch: Dispatch<AcceptFollowActionType |
AcceptUnfollowActionType |
ToggleFollowProgressActionType>) => {
await followUnfollowFlow(dispatch, id, usersAPI.deleteFollow.bind(usersAPI), acceptUnfollow)
}
export default usersReducer;
|
5b673ab6db048f149ef64e61199b78d544ec13aa
|
TypeScript
|
bradenmacdonald/ratio
|
/frontend/budget/components/tab-transactions/parse-ofx.ts
| 2.75
| 3
|
import {parse as parseOFX} from 'ofx-js';
import {Currency, PDate, SUPPORTED_CURRENCIES} from 'prophecy-engine';
export interface ImportedTransaction {
date: PDate;
amount: number;
/** A unique ID for this transaction */
tid: string;
description: string;
}
export interface ParseResult {
uniqueAccountId: string;
currency: Currency;
transactions: ImportedTransaction[];
}
/**
* Given a string with OFX (Open Financial Exchange) data, parse it into usable
* transaction and account data.
* @param {string} ofxDataString The OFX data to parse.
* @returns {Promse} A promise that will resolve to {uniqueAccountId, currency, transactions}.
*/
export function parseOfxToTransactions(ofxDataString: string): Promise<ParseResult> {
return new Promise((resolve, reject) => {
// First parse the raw string data into structured OFX data:
parseOFX(ofxDataString).then((ofxData: any) => {
try {
const result = extractOfxTransactions(ofxData);
resolve(result);
} catch (e) {
reject(e);
}
}).catch(err => {
console.error(err);
reject(new Error("Unable to parse the file. It may not be a valid OFX or QFX file."));
});
});
}
/**
* Given structured OFX data as parsed by ofx-js, extract the actual list
* of transaction data in a format compatible with Prophecy.
* @param {object} ofxData The structured OFX data to use
*/
function extractOfxTransactions(ofxData: any): ParseResult {
// The OFX spec used for this was http://www.ofx.net/downloads/OFX%202.2.pdf
// The FI tag holds an ORG that defines the namespace and then an FID (ID) unique within that namespace, identifying the financial instiution:
const FI = ofxData.OFX.SIGNONMSGSRSV1.SONRS.FI;
if (!FI.ORG || !FI.FID) {
throw new Error("Could not determine financial institution ID.");
}
const uniqueFID = `${FI.ORG}>${FI.FID}`; // A string that uniquely identifies this financial institution
let statementResponse;
let accountId;
if (ofxData.OFX.BANKMSGSRSV1) {
// This is a bank transaction list
statementResponse = ofxData.OFX.BANKMSGSRSV1.STMTTRNRS.STMTRS;
accountId = statementResponse.BANKACCTFROM.ACCTID;
} else if (ofxData.OFX.CREDITCARDMSGSRSV1) {
// This is a credit card transaction list
statementResponse = ofxData.OFX.CREDITCARDMSGSRSV1.CCSTMTTRNRS.CCSTMTRS;
accountId = statementResponse.CCACCTFROM.ACCTID;
} else {
throw new Error("Expected a BANKMSGSRSV1 (Bank Message Set Response) or CREDITCARDMSGSRSV1 (Credit Card Message Set Response).");
}
const uniqueAccountId = `${uniqueFID}>${accountId}`;
const currencyCode = statementResponse.CURDEF && statementResponse.CURDEF.toUpperCase();
const currency = SUPPORTED_CURRENCIES[currencyCode];
if (currency === undefined) {
throw new Error(`Unknown or unsupported currency (${currencyCode}).`);
}
// Now iterate over the transaction list:
let transactionStatement = statementResponse.BANKTRANLIST.STMTTRN;
if (Array.isArray(transactionStatement)) {
// This is what we want - a list of transactions.
} else if (typeof transactionStatement === 'object') {
// There was only one transaction - wrap it in an array for consistency:
transactionStatement = [transactionStatement];
} else if (typeof transactionStatement === 'undefined') {
// There were no transactions at all.
transactionStatement = [];
}
const transactions: ImportedTransaction[] = [];
for (const txn of transactionStatement) {
// Parse the date. Prefer "date the user initiated the transaction" over "date posted", though only the latter is guaranteed
const fullDateTimeString: string = txn.DTUSER || txn.DTPOSTED;
const dateString = fullDateTimeString.substr(0, 4) + '-' + fullDateTimeString.substr(4, 2) + '-' + fullDateTimeString.substr(6, 2);
const date = PDate.fromString(dateString);
// Parse the amount
const amount = Math.round(parseFloat(txn.TRNAMT) * Math.pow(10, currency.decimals));
transactions.push({
date,
amount,
tid: txn.FITID, // A string uniquely identifying this transaction (but only unique to this particular financial institution and account)
description: txn.NAME || txn.PAYEE.NAME,
});
}
return {
uniqueAccountId,
currency,
transactions,
};
}
|
9736ebb85889e23c3a400f21137468443701eee8
|
TypeScript
|
expo/expo
|
/packages/expo-sensors/build/Pedometer.d.ts
| 2.5625
| 3
|
import { PermissionExpiration, PermissionResponse, PermissionStatus, Subscription } from 'expo-modules-core';
export type PedometerResult = {
/**
* Number of steps taken between the given dates.
*/
steps: number;
};
/**
* Callback function providing event result as an argument.
*/
export type PedometerUpdateCallback = (result: PedometerResult) => void;
/**
* Subscribe to pedometer updates.
* @param callback A callback that is invoked when new step count data is available. The callback is
* provided with a single argument that is [`PedometerResult`](#pedometerresult).
* @return Returns a [`Subscription`](#subscription) that enables you to call
* `remove()` when you would like to unsubscribe the listener.
*/
export declare function watchStepCount(callback: PedometerUpdateCallback): Subscription;
/**
* Get the step count between two dates.
* @param start A date indicating the start of the range over which to measure steps.
* @param end A date indicating the end of the range over which to measure steps.
* @return Returns a promise that fulfills with a [`PedometerResult`](#pedometerresult).
*
* As [Apple documentation states](https://developer.apple.com/documentation/coremotion/cmpedometer/1613946-querypedometerdatafromdate?language=objc):
* > Only the past seven days worth of data is stored and available for you to retrieve. Specifying
* > a start date that is more than seven days in the past returns only the available data.
* @platform ios
*/
export declare function getStepCountAsync(start: Date, end: Date): Promise<PedometerResult>;
/**
* Returns whether the pedometer is enabled on the device.
* @return Returns a promise that fulfills with a `boolean`, indicating whether the pedometer is
* available on this device.
*/
export declare function isAvailableAsync(): Promise<boolean>;
/**
* Checks user's permissions for accessing pedometer.
*/
export declare function getPermissionsAsync(): Promise<PermissionResponse>;
/**
* Asks the user to grant permissions for accessing pedometer.
*/
export declare function requestPermissionsAsync(): Promise<PermissionResponse>;
export { Subscription, PermissionResponse, PermissionStatus, PermissionExpiration };
//# sourceMappingURL=Pedometer.d.ts.map
|
5beb6e0f9fb39f145fbd602f1c203565e8bd25ea
|
TypeScript
|
OptimalBits/ground
|
/lib/container/collection-schema.ts
| 2.75
| 3
|
/// <reference path="../models/schema.ts" />
/// <reference path="./collection.ts" />
module Gnd {
/**
Collection Schema Type. This class can be used to define collection types
in schemas.
var ChatSchema = new Schema({
rooms: new ColectionSchemaType(Room, 'rooms');
});
@class CollectionSchemaType
@extends SchemaType
@constructor
@param mode {IModel} A model class defining the type of items to store in the
sequence.
@param bucket {String} Bucket where the items are stored in the server.
*/
export class CollectionSchemaType extends SchemaType
{
public static type = Collection;
constructor(model: IModel, bucket?: string)
{
super({type: Collection, ref:{model: model, bucket: bucket || model.__bucket}});
}
init(property: string)
{
this.definition.ref.bucket = property;
}
toObject(obj)
{
// undefined since a collection is never serialized.
}
fromObject(arg)
{
// undefined since a collection is never deserialized
}
get(model, args?, opts?)
{
var def = this.definition;
return model.all(def.ref.model, args || {}, def.ref.bucket);
}
}
}
|
0d1a92f7ba79ee21b51bd3a403c5f3bc10091836
|
TypeScript
|
lmachens/trophy-hunter-api
|
/src/routes/champs.ts
| 2.546875
| 3
|
import Champs, { Champ, ChampStats } from '../models/Champs';
import { Request, Response } from 'express';
import { sortWinRate } from '../utils/sort';
export async function getChamp(req: Request, res: Response) {
res.set('Cache-Control', 'public, max-age=1200');
const champId = parseInt(req.query.champId);
const mapId = parseInt(req.query.mapId);
if (isNaN(mapId) || isNaN(champId)) {
return res.status(403).end('Invalid mapId or champId');
}
const champ = await Champs().findOne(
{ champId, [`maps.${mapId}`]: { $exists: true } },
{
projection: {
_id: false,
champId: true,
[`maps.${mapId}`]: true
}
}
);
if (!champ) {
return res.status(404).end('Not found');
}
const filteredChamp = filterChamp(champ);
res.json(filteredChamp);
}
function filterChamp(champ: Champ) {
const [mapId, map] = Object.entries(champ.maps)[0];
const positions = Object.entries(map.positions).reduce((positions, [key, value]) => {
const position = {
...omitDates(value.stats),
spells: filterTop(value.spells, value.stats.matches, 2),
items: {
'2-12': filterTop(value.items['2-12'].items, value.items['2-12'].stats.matches, 5),
'12-22': filterTop(value.items['12-22'].items, value.items['12-22'].stats.matches, 5),
'22-32': filterTop(value.items['22-32'].items, value.items['22-32'].stats.matches, 5),
'32-42': filterTop(value.items['32-42'].items, value.items['32-42'].stats.matches, 5),
'42-52': filterTop(value.items['42-52'].items, value.items['42-52'].stats.matches, 5)
},
firstItems: filterTop(value.firstItems, value.stats.matches, 2),
perks: filterTop(value.perks, value.stats.matches, 2),
skillOrder: filterTop(value.skillOrder, value.stats.matches, 2),
averageStats: value.averageStats
};
return {
...positions,
[key]: position
};
}, {});
return {
champId: champ.champId,
mapId: parseInt(mapId),
matches: map.stats.matches,
winRate: map.stats.winRate,
banRate: map.stats.banRate,
pickRate: map.stats.pickRate,
positions
};
}
interface ChampStatsObj {
[key: string]: ChampStats;
}
function filterTop(obj: ChampStatsObj, matches: number, limit = 1, threshold = 0.1) {
return Object.values(obj)
.filter(stats => stats.matches / matches > threshold)
.sort(sortWinRate)
.slice(0, limit)
.map(omitDates);
}
function omitDates(obj?: ChampStats) {
if (!obj) {
return null;
}
const { createdAt, lastPlayedAt, ...other } = obj;
return other;
}
|
390c5965670698bef98de3d98a2a0dcb009084e0
|
TypeScript
|
fahadhussain2/Angular-2-Assignments
|
/Inventory Application/src/app/app.component.ts
| 2.53125
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'inventory-app',
styleUrls: ['./app.component.css'],
template:
`
<header></header>
<br/>
<div class="container">
<product-list
[productlist]="product">
</product-list>
</div>
`
})
export class AppComponent {
product:Product[];
constructor(){
this.product= [new Product(
'T-SHIRT' ,
'A nice blue T-shirt',
'http://i68.tinypic.com/2j5euqf.png',
['Men','Accessories','t-shirt'],
30),
new Product(
'NEATOJACKET' ,
'Grey Jacket' ,
'http://i63.tinypic.com/x6bpk3.png' ,
[ 'Men' , 'Apparel' , 'Jackets & Vests' ],
238.99),
new Product(
'Black Hat' ,
'A nice black hat' ,
'http://s.pictub.club/2016/11/08/HkVGM.jpg' ,
[ 'Men' , 'glasses' , 'Rayban glasses' ],
109.99),
new Product(
'Black Running Shoes' ,
'My Shoes' ,
'http://s.pictub.club/2016/11/08/HkUo5.jpg' ,
[ 'Men' , 'Shoes' , 'Running Shoes' ],
238.99)
]
}
}
export class Product{
constructor(
public sku:string,
public name:string,
public imageUrl:string,
public department:string[],
public price:number){
}
}
|
6d9cb5404f9d5b05d92aac01548d05c4eef9ad8f
|
TypeScript
|
organization-research-group/org-shell
|
/src/Route.ts
| 3.015625
| 3
|
"use strict";
import * as qs from 'querystring'
import { Params, Opts } from './types'
export default class Route {
resourceName: string;
params: Params;
opts: Opts<any>;
constructor(resourceName: string, params?: Params, opts?: Opts<any>) {
this.resourceName = resourceName;
this.params = params || {};
this.opts = opts || {};
}
_asURL(
serializeValue: (opt: any) => string
) {
const params = qs.encode(this.params)
, opts = qs.encode(mapObj(serializeValue, this.opts))
let url: string = '?page=' + this.resourceName
if (params) url += `&${params}`
if (opts) url += `#${opts}`
return url
}
static _fromPath(
path: string,
deserializeValue: (opt: string) => any
) {
if (path[0] === '?') path = path.slice(1)
const [ params, opts ] = path.split('#')
const { page='', ...parsedParams } = qs.parse(params)
, parsedOpts = mapObj(deserializeValue, qs.parse(opts))
if (typeof page !== 'string') {
throw new Error('Invalid value for `page` parameter: ' + page)
}
for (let key in parsedParams) {
const value = parsedParams[key]
if (!(typeof value === 'string' || typeof value === 'number')) {
throw new Error('Query parameters must either be strings or numbers')
}
}
return new Route(page, <Params>parsedParams, parsedOpts)
}
}
function mapObj<T>(
fn: (arg: any) => T,
obj: Record<string, any>
): Record<string, T> {
const mapped: Record<string, any> = {}
Object.entries(obj).forEach(([ k, v ]) => {
mapped[k] = fn(v)
})
return mapped
}
|
1272cfa88b481d6277a1e8bb3bd595435eccc024
|
TypeScript
|
AngelTezo/FinalProject
|
/src/app/rol/rol.service.ts
| 2.515625
| 3
|
import { Rol } from './rol';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class RolService {
constructor(private _http: Http) { }
// Get list of categories from database via api.
readrols(): Observable<Rol[]>{
return this._http
.get("http://localhost/Proyecto_Final/rol/read.php")
.map(res => res.json());
}
// Send product data to remote server to create it.
createrol(product): Observable<Rol>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(
"http://localhost/Proyecto_Final/rol/create.php",
product,
options
).map(res => res.json());
}
// Send product data to remote server to update it.
updaterol(product): Observable<Rol>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(
"http://localhost/Proyecto_Final/rol/update.php",
product,
options
).map(res => res.json());
}
// Send product ID to remote server to delete it.
deleterol(id_rol){
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post(
"http://localhost/Proyecto_Final/rol/delete.php",
{ id_rol: id_rol },
options
).map(res => res.json());
}
}
|
1bcfe60c0137be3e9143fc2db9e44d0d58f6f4b7
|
TypeScript
|
iFalcao/PrevisaoTempo
|
/SitePrevisaoTempo/src/app/_models/city.ts
| 2.5625
| 3
|
export interface City {
name: string;
customCode: number;
latitude?: number;
longitude?: number;
country?: string;
}
|
f2b05ae28f2cadeceb71ffd4628e513a20eaf0e4
|
TypeScript
|
lorceroth/speculo
|
/src/plugins/plugin-loader.ts
| 2.53125
| 3
|
import * as $script from 'scriptjs';
import { IConfig, IPluginConfig } from "../config/config";
import { IPlugin } from './plugin';
const PLUGINS_PATH = '/plugins';
export const PLUGINS_SCRIPT_ID = 'plugins';
export class PluginLoader {
constructor() {
console.log('Plugins loaded from:', PLUGINS_PATH);
}
load(config: IConfig): IPlugin[] {
let plugins: IPlugin[] = new Array<IPlugin>();
let paths = config.plugins
.map(pluginConfig => this.getPluginPath(pluginConfig));
$script(paths, PLUGINS_SCRIPT_ID, () => {
for (let pluginConfig of config.plugins) {
let plugin = this.createPlugin(pluginConfig);
if (plugin) {
plugins.push(plugin);
}
}
console.log('Loaded plugins:', plugins);
});
return plugins;
}
private getPluginPath(plugin: IPluginConfig): string {
return PLUGINS_PATH.concat(`/${plugin.name}/${plugin.name}.js`);
}
private createPlugin(pluginConfig: IPluginConfig): IPlugin | null {
try {
let component = (<any>window[pluginConfig.name]).default;
return {
path: this.getPluginPath(pluginConfig),
component: component,
props: Object.assign({
position: pluginConfig.position,
size: pluginConfig.size,
align: pluginConfig.align,
}, pluginConfig.props),
}
}
catch (err) {
console.error('Plugin component is not accessable:', pluginConfig);
return null;
}
}
}
|
7c4f414e90157a84de5a5bb9a0f7997bfcc4fbfc
|
TypeScript
|
yuebwang/create-figma-plugin
|
/packages/monetization/src/gumroad/validate-gumroad-license-key-ui-async.ts
| 2.53125
| 3
|
import { LicenseKeyValidationResult } from '../utilities/types.js'
const emptyLicense = {
email: null,
licenseKey: null,
purchaseTimestamp: null,
validationTimestamp: null
}
export async function validateGumroadLicenseKeyUiAsync(options: {
incrementUsesCount: boolean
licenseKey: string
productPermalink: string
}): Promise<LicenseKeyValidationResult> {
const { incrementUsesCount, licenseKey, productPermalink } = options
const trimmedLicenseKey = licenseKey.trim()
if (trimmedLicenseKey === '') {
return { ...emptyLicense, result: 'INVALID_EMPTY' }
}
if (trimmedLicenseKey.length !== 35) {
return { ...emptyLicense, result: 'INVALID' }
}
try {
const response = await window.fetch(
'https://api.gumroad.com/v2/licenses/verify',
{
body:
`increment_uses_count=${
incrementUsesCount === true ? 'true' : 'false'
}&license_key=` +
encodeURIComponent(trimmedLicenseKey) +
'&product_permalink=' +
encodeURIComponent(productPermalink),
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
method: 'POST'
}
)
const json = await response.json()
const { purchase, success } = json
if (
success === false ||
purchase.chargebacked === true ||
purchase.disputed === true ||
purchase.refunded === true
) {
return { ...emptyLicense, result: 'INVALID' }
}
return {
email: purchase.email,
licenseKey: trimmedLicenseKey,
purchaseTimestamp: purchase.sale_timestamp,
result: 'VALID',
validationTimestamp: new Date().toISOString()
}
} catch {
return { ...emptyLicense, result: 'ENDPOINT_DOWN' }
}
}
|
9e51436eceb7f9a4d8eea4cce1431844bfd07d32
|
TypeScript
|
BobNisco/ComBOBiler
|
/scripts/code_table.ts
| 3.40625
| 3
|
module Combobiler {
export class CodeTable {
// Set the expected size of the code table. This should match up with the
// program size on the OS. Since MS-BOS has a default program size of 256,
// we will match that for our compiler.
public static CODE_TABLE_SIZE = 256;
public entries: Array<string>;
// Keep track of what positions we are currently writing to
public currentPosition: number;
public currentHeapPosition: number;
constructor() {
this.entries = new Array<string>(CodeTable.CODE_TABLE_SIZE);
this.currentPosition = 0;
this.currentHeapPosition = this.entries.length - 1;
}
/**
* Finalizes the code table by putting 0x00 into each spot that isn't occupied.
* Should be run after back-patching is completed
*/
public finalizeCodeTable() {
for (var i = 0; i < CodeTable.CODE_TABLE_SIZE; i++) {
if (this.entries[i] === null || this.entries[i] === undefined) {
this.entries[i] = "00";
}
}
}
/**
* Generates a nicely formatted string version of the code table (8 x 32)
*
* @return string version of the code table
*/
public createStringForDisplay() {
var returnString = '';
for (var i = 0; i < CodeTable.CODE_TABLE_SIZE; i++) {
if (i % 8 === 0 && i !== 0) {
returnString += '\n';
}
returnString += this.entries[i] + ' ';
}
return returnString;
}
public addCode(data: string) {
this.add(data, this.currentPosition);
return this.currentPosition++;
}
public addHeapData(data: string) {
this.add(data, this.currentHeapPosition);
return this.currentHeapPosition--;
}
public findStringInHeap(data: string) {
var curString = '';
for (var i = CodeTable.CODE_TABLE_SIZE - 1; i >= this.currentHeapPosition - 1; i--) {
if (this.entries[i] === '00') {
if (curString === data) {
return i;
}
} else {
curString = String.fromCharCode(parseInt(this.entries[i], 16)) + curString;
}
}
return null;
}
public addRawString(str: string) {
var position;
if (str.length <= 0) {
position = this.addHeapData('00');
}
// Null terminated string
this.addHeapData('00');
for (var i = str.length - 1; i >= 0; i--) {
var hex = str.charCodeAt(i).toString(16);
position = this.addHeapData(hex);
}
return position;
}
public addString(str: string) {
// Strip the double quotes
var theString = str.value.value.replace(/\"/g, '');
return this.addRawString(theString);
}
/**
* Check to ensure that our heap/static/code sections haven't collided
* If they have collided, we'll throw an exception
*/
private checkForCollision() {
if (this.currentPosition >= this.currentHeapPosition) {
throw new Error('Ran out of space in our code table! Program too long!');
}
}
/**
* Internal handler for adding code to the table.
* Performs special checking to ensure code that is added is valid
*
* @param data the data (hex) to be added to the code table
* @param position the position (base-10, 0-indexed) in the codeTable to add the data to
*/
public add(data: string, position: number) {
// Uppercase all the letters so that it's uniform regardless
data = data.toUpperCase();
if (!(data.match(/^[0-9A-G]{2}/) || data.match(/^T[0-9]/) || data.match(/^J[0-9]/) || data.match(/^XX$/))) {
throw new Error('Tried to place the data string ' + data + ' in code table, but it is not 2 valid hex characters nor is it valid temp variable data');
}
if (position >= CodeTable.CODE_TABLE_SIZE || position < 0) {
throw new Error('Position ' + position + ' is invalid for our code table');
}
this.checkForCollision();
this.entries[position] = data;
return position;
}
}
}
|
a0b2175c89146cc7393634ab825e0766f657ad66
|
TypeScript
|
ericlee05/Busrode
|
/src/Busrode.ts
| 2.765625
| 3
|
import { CityClass, CityCode } from "./City/City"
import { Yangsan } from "./City/Yangsan/Yangsan"
import { BusArrival } from "./Models/BusArrival"
import { BusLine } from "./Models/BusLine"
import { BusStop } from "./Models/BusStop"
export class Busrode extends CityClass{
private readonly CityWrapper:CityClass
private Cities:Array<CityClass> = [
new Yangsan()
]
constructor(CityType:CityCode){
super()
this.CityWrapper = this.Cities.find(c => c.City == CityType)!
}
//이름으로 정류장을 찾아 반환
async findStop(name:string):Promise<Array<BusStop>>{
return await this.CityWrapper.findStop(name)
}
//이름으로 노선을 찾아 반환
async findLine(name:string){
return await this.CityWrapper.findLine(name)
}
//도착정보 얻기
async getArrivalInfo(stopID:string, lineID:string){
return await this.CityWrapper.getArrivalInfo(stopID, lineID)
}
}
|
59480ea1e4c714c61aeceafc9eb6e7e66a920b2a
|
TypeScript
|
PushTracker/EvalApp
|
/libs/core/services/analytics.service.ts
| 2.765625
| 3
|
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
export interface IAnalyticsProperties {
category?: string;
label?: string;
action?: string;
// https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitType
hitType?:
| 'pageview'
| 'screenview'
| 'event'
| 'transaction'
| 'item'
| 'social'
| 'exception'
| 'timing';
value?: number;
page?: string;
[key: string]: any;
}
/**
* Funnel for all analytics reporting data
*/
@Injectable()
export class AnalyticsService {
private _devMode = false;
constructor(private _router: Router) {
this.devMode(false);
}
/**
* Track actions, events, etc.
**/
track(action: string, properties: any | IAnalyticsProperties): void {
if (!this.devMode()) {
// send some analytics to db/service
}
}
/**
* Control whether analytics are tracked
* true: dev mode on, therefore do not track anything
* false: dev mode off, track everything
**/
devMode(enable?: boolean): boolean {
if (typeof enable !== 'undefined') {
this._devMode = enable;
}
return this._devMode;
}
}
/**
* Base class
* Standardizes tracking actions and categorization
*/
export class Analytics {
analytics: AnalyticsService;
// sub-classes should define their category
category: string;
/**
* Track actions, events, etc.
**/
track(action: string, properties: IAnalyticsProperties = {}): void {
this.analytics.track(
action,
Object.assign({}, properties, { category: this.category })
);
}
}
|
74b98cae2b6c05983da751bfcecd23fd4ec853ab
|
TypeScript
|
next-generation-web-translator/translation-api
|
/src/sentence-dict/sentence-dict.service.ts
| 2.734375
| 3
|
import { Injectable } from '@nestjs/common';
import { TranslationModel } from '../models/translation.model';
import { OriginalModel } from '../models/original.model';
import { SentenceDictEntryModel } from '../entities/sentence-dict-entry.model';
import * as leven from 'leven';
import { pick } from 'lodash';
@Injectable()
export class SentenceDict {
private dict: SentenceDictEntryModel[] = [];
query(fingerprints: string[]): TranslationModel[] {
return fingerprints
.map(fingerprint => this.dict.find(it => it.fingerprint === fingerprint))
.filter(entry => !!entry)
.map(toTranslationModel);
}
create(originals: OriginalModel[]): TranslationModel[] {
return originals
.map(it => this.fuzzyFind(it))
.map(entry => this.addEntry(entry))
.map(toTranslationModel);
}
load(dict: SentenceDictEntryModel[]): void {
this.dict = dict;
}
fuzzyFind(original: OriginalModel): SentenceDictEntryModel {
const sortedEntries = this.dict.map(value => ({ value, confidence: calculateConfidence(original, value) }))
.sort((v1, v2) => v2.confidence - v1.confidence);
const mostConfidentEntry = sortedEntries[0];
return {
...original,
translation: mostConfidentEntry.value.translation,
confidence: mostConfidentEntry.confidence,
};
}
private addEntry(entry: SentenceDictEntryModel): SentenceDictEntryModel {
this.dict.push(entry);
return entry;
}
}
function confidenceFromEditDistance(text1: string, text2: string): number {
const diff = leven(text1, text2);
const total = Math.max(text1.length, text2.length);
return 1 - diff / total;
}
function calculateConfidence(original: OriginalModel, dictEntry: SentenceDictEntryModel): number {
const confidenceOfPageUri = confidenceFromEditDistance(original.pageUri, dictEntry.pageUri);
const confidenceOfContent = confidenceFromEditDistance(original.original, dictEntry.original);
const confidenceOfPaths = confidenceFromEditDistance(original.paths.join('/'), dictEntry.paths.join('/'));
// TODO: Automatically adjust weights through machine learning
const weightOfPageUri = 0.25;
const weightOfPaths = 0.25;
const weightOfContent = 0.5;
const confidence = confidenceOfPageUri * weightOfPageUri + confidenceOfContent * weightOfContent + confidenceOfPaths * weightOfPaths;
return +confidence.toFixed(2);
}
export function toTranslationModel(entry: SentenceDictEntryModel) {
return pick(entry, ['fingerprint', 'confidence', 'translation']);
}
|
1634bc7d69a03b349185be52f575dd4a3917ba38
|
TypeScript
|
Sumeetrana/100-Algorithms-Challenge
|
/alphabeticSubSequence/alphabeticSubSequence.ts
| 3.546875
| 4
|
function alphabeticSubSequence(inputString: string): boolean {
let isSS = true;
for (let i = 0; i < inputString.length - 1; i++) {
if (inputString.charCodeAt(i) >= inputString.charCodeAt(i + 1)) {
isSS = false;
break;
}
}
return isSS;
}
console.log(alphabeticSubSequence("acf"));
|
6f721aa8e4bc05bdc1826f9d9eea956a8df60b8b
|
TypeScript
|
JuanKitu/ProyectoGIS
|
/server/src/services/jwt.services.ts
| 2.59375
| 3
|
import { OAuth2Client } from 'google-auth-library';
import jwt,{ Secret } from 'jsonwebtoken';
import { UsuarioInterface, UsuarioTokenInterface } from '../interfaces/interfaces';
const client = new OAuth2Client('1096762710491-c7d53lpa1n5uju66qi8md97gln49rv1d.apps.googleusercontent.com');
export function createToken(usuario: UsuarioInterface) {
const claveSecreta: Secret = 'elseed'
return jwt.sign({
usuario: usuario
}, claveSecreta, { expiresIn: 60 * 60 * 24 * 30 });
};
//esta funcion verifica que el token que envia google es valido
export async function verifyGoogle(token:string) {
console.log('EL TOKEN ESTA SIENDO VERIFICADO');
const ticket = await client.verifyIdToken({
idToken: token,
audience: '1096762710491-c7d53lpa1n5uju66qi8md97gln49rv1d.apps.googleusercontent.com', // Specify the CLIENT_ID of the app that accesses the backend
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
});
console.log(ticket.getPayload);
const payload = ticket.getPayload();
if(payload){
console.log('ENVIANDO PAYLOAD');
const userid = payload['sub'];
console.log(payload.name);
console.log(payload.email);
console.log(payload.picture);
const usuario:UsuarioTokenInterface={
nombreUsuario:payload.name,
email:payload.email,
img:payload.picture,
google:true
};
return usuario
}
}
|
a9c18791786c4430bdf32100571aa87da45b7b2e
|
TypeScript
|
ThomasSpeedy/Angular
|
/buch_ng4/internationalisierung/src/app/shared/user.ts
| 2.515625
| 3
|
export interface User {
firstName?: string;
lastName?: string;
sex?: string;
}
|
7639d9927c6b383be479672a119883ac6c71d3b9
|
TypeScript
|
thehig/turtleChallenge
|
/test/Turtle.spec.ts
| 3.640625
| 4
|
import { expect } from "chai";
import { Turtle, Direction, TurtleState, Action } from "../src/";
describe("Turtle", () => {
it("is not null or undefined", () => {
expect(Turtle).to.not.be.null;
expect(Turtle).to.not.be.undefined;
});
it("has a constructor that takes 3 parameters", () =>
expect(() => new Turtle(0, 0, Direction.North)).not.to.throw());
it("defaults direction to North if not provided", () =>
expect(new Turtle(0, 0)).to.have.property("dir", Direction.North));
it("sets a valid X and Y value from the constructor", () => {
const myTurtle = new Turtle(10, 10, Direction.North);
expect(myTurtle).to.have.property("x", 10);
expect(myTurtle).to.have.property("y", 10);
expect(myTurtle).to.have.property("dir", Direction.North);
});
it("floors incoming values", () => {
const myTurtle = new Turtle(9.1, 9.99, Direction.North);
expect(myTurtle).to.have.property("x", 9);
expect(myTurtle).to.have.property("y", 9);
});
it("throws an error for unknown actions", () => {
const myTurtle = new Turtle(9.1, 9.99, Direction.North);
expect(() => myTurtle.act(Action.Error)).to.throw(/Unknown Turtle action/);
});
describe("state", () => {
it("defaults to Initializing", () => {
const myTurtle = new Turtle(9.1, 9.99, Direction.North);
expect(myTurtle).to.have.property("state", TurtleState.Initializing);
});
it("can be specified in constructor", () => {
const myTurtle = new Turtle(
9.1,
9.99,
Direction.North,
TurtleState.InDanger
);
expect(myTurtle).to.have.property("state", TurtleState.InDanger);
});
});
describe("act(Action.Rotate)", () => {
var startingTurtle = null;
beforeEach(() => (startingTurtle = new Turtle(3, 3, Direction.North)));
afterEach(() => (startingTurtle = null));
it("returns a new instance", () => {
var oneRotation = startingTurtle.act(Action.Rotate);
expect(startingTurtle).to.have.property("dir", Direction.North);
expect(oneRotation).to.have.property("dir", Direction.East);
});
it("throws an error if Direction is invalid", () => {
const myTurtle = new Turtle(9.1, 9.99, Direction.Error);
expect(() => myTurtle.act(Action.Rotate)).to.throw(
/Unknown Turtle Rotate direction/
);
});
it("rotates through the directions properly", () => {
var oneRotation = startingTurtle.act(Action.Rotate);
var twoRotation = oneRotation.act(Action.Rotate);
var threeRotation = twoRotation.act(Action.Rotate);
var fourRotation = threeRotation.act(Action.Rotate);
expect(oneRotation).to.have.property("dir", Direction.East);
expect(twoRotation).to.have.property("dir", Direction.South);
expect(threeRotation).to.have.property("dir", Direction.West);
expect(fourRotation).to.have.property("dir", Direction.North);
});
});
describe("act(Action.Move)", () => {
var startingTurtle = null;
beforeEach(() => (startingTurtle = new Turtle(3, 3, Direction.North)));
afterEach(() => (startingTurtle = null));
it("returns a new instance", () => {
var oneRotation = startingTurtle.act(Action.Move);
expect(startingTurtle).to.have.property("y", 3);
expect(oneRotation).to.have.property("y", 2);
});
it("throws an error if Direction is invalid", () => {
const myTurtle = new Turtle(9.1, 9.99, Direction.Error);
expect(() => myTurtle.act(Action.Move)).to.throw(
/Unknown Turtle Move direction/
);
});
it("moves up when facing North", () => {
var movedTurtle = startingTurtle.act(Action.Move);
expect(movedTurtle).to.have.property("dir", Direction.North);
expect(movedTurtle).to.have.property("x", 3);
expect(movedTurtle).to.have.property("y", 2);
});
it("moves right when facing East", () => {
var movedTurtle = startingTurtle.act(Action.Rotate).act(Action.Move);
expect(movedTurtle).to.have.property("dir", Direction.East);
expect(movedTurtle).to.have.property("x", 4);
expect(movedTurtle).to.have.property("y", 3);
});
it("moves down when facing South", () => {
var movedTurtle = startingTurtle
.act(Action.Rotate)
.act(Action.Rotate)
.act(Action.Move);
expect(movedTurtle).to.have.property("dir", Direction.South);
expect(movedTurtle).to.have.property("x", 3);
expect(movedTurtle).to.have.property("y", 4);
});
it("moves left when facing West", () => {
var movedTurtle = startingTurtle
.act(Action.Rotate)
.act(Action.Rotate)
.act(Action.Rotate)
.act(Action.Move);
expect(movedTurtle).to.have.property("dir", Direction.West);
expect(movedTurtle).to.have.property("x", 2);
expect(movedTurtle).to.have.property("y", 3);
});
});
});
|
751c6382bae38ea57b2cb74e869ecc6a9003d5ef
|
TypeScript
|
green-fox-academy/IceAge-Reddit-Backend
|
/tests/services/UserValidationService.spec.ts
| 2.546875
| 3
|
/* eslint-disable @typescript-eslint/unbound-method */
import { Unauthorized } from '@tsed/exceptions';
import { assert, expect } from "chai";
import { beforeEach } from 'mocha';
import { UserCreation } from '../../src/models/auth.types';
import { UserValidationService } from '../../src/services/UserValidationService';
describe("UserValidationService", () => {
const service = new UserValidationService();
let userCreation: UserCreation;
beforeEach(() => {
userCreation = {
username: "Karhal",
email: "karhal@email.com",
password: "Str0ngPa55word"
};
});
describe("validateUserCreation()", () => {
it("should not fail", () => {
assert.doesNotThrow(() => {service.validateUserCreation(userCreation)});
});
describe("username property", () => {
it("should fail cause empty username", () => {
userCreation.username = "";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Missing credentials!");
});
it("should fail cause has whitespace", () => {
userCreation.username = "Baba Jaga";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Whitespaces in username!");
});
});
describe("email property", () => {
it("should fail cause empty email", () => {
userCreation.email = "";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Missing credentials!");
});
it("should fail cause no valid email format", () => {
userCreation.email = "email.com";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Invalid email format!");
});
});
describe("password property", () => {
it("should fail cause empty password", () => {
userCreation.password = "";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Missing credentials!");
});
it("should fail cause too short (less then 6 symbols)", () => {
userCreation.password = "fds";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Week password!");
});
it("should fail cause too long (more then 20 symbols)", () => {
userCreation.password = "sdfasdfdasfasdfdasffsgfhsgththrthggfhnn";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Week password!");
});
it("should fail cause no digits", () => {
userCreation.password = "jfdadfFFjdk";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Week password!");
});
it("should fail cause no lower-case symbols", () => {
userCreation.password = "464FDEDVA";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Week password!");
});
it("should fail cause no capital symbols", () => {
userCreation.password = "464dfsde";
expect(() => {service.validateUserCreation(userCreation)})
.to.throw(Unauthorized, "Week password!");
});
});
});
});
|
0fb0a11d5c9cd22e91576d34ddb28b4e1bb42110
|
TypeScript
|
companieshouse/promise-to-file-web
|
/src/client/axios.api.call.handler.ts
| 2.96875
| 3
|
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, Method } from "axios";
import logger from "../logger";
import PromiseError from "../utils/error";
export const HTTP_POST: Method = "post";
/**
* A base axios config that is common for API calls.
* @param token Bearer token for API call
*/
export const getBaseAxiosRequestConfig = (token: string): AxiosRequestConfig => {
return {
headers: {
Accept: "application/json",
Authorization: "Bearer " + token,
},
proxy: false,
validateStatus: (status) => {
return ((status >= 200 && status < 300) || status === 400);
},
};
};
/**
* Makes a call to whatever url is set in AxiosRequestConfig and returns the result of that
* call in AxiosResponse.
* Will throw error if unable to make call.
* Throws error if unable to make call
* @param config: AxiosRequestConfig
*/
export const makeAPICall = async (config: AxiosRequestConfig): Promise<AxiosResponse> => {
try {
return await axios.request<any>(config);
} catch (err) {
logger.error(`API ERROR ${JSON.stringify(err, null, 2)}`);
const axiosError = err as AxiosError;
const {response, message} = axiosError;
throw new PromiseError(
response ? response.data.errors : [],
message,
response ? response.status : -1
);
}};
|
3a38601d437ea990831c8033ef26aa35798865d4
|
TypeScript
|
cdnjs/cdnjs
|
/ajax/libs/amcharts4/4.9.34/.internal/plugins/bullets/PointedCircle.d.ts
| 3.03125
| 3
|
/**
* Pointed rectangle module.
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { PointedShape, IPointedShapeProperties, IPointedShapeAdapters, IPointedShapeEvents } from "../../core/elements/PointedShape";
/**
* ============================================================================
* REQUISITES
* ============================================================================
* @hidden
*/
/**
* Defines properties for [[PointedCircle]].
*/
export interface IPointedCircleProperties extends IPointedShapeProperties {
/**
* Radius of a pin, in pixels.
*
* @default 18
*/
radius?: number;
/**
* Angle of a pointer, in degrees.
*
* @default 90
*/
pointerAngle?: number;
}
/**
* Defines events for [[PointedCircle]].
*/
export interface IPointedCircleEvents extends IPointedShapeEvents {
}
/**
* Defines adapters for [[PointedCircle]].
*
* @see {@link Adapter}
*/
export interface IPointedCircleAdapters extends IPointedShapeAdapters, IPointedCircleProperties {
}
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* Draws a circle with a pointer.
*
* @since 4.5.7
* @see {@link https://www.amcharts.com/docs/v4/tutorials/plugin-bullets/} for usage instructions.
* @see {@link IPointedCircleEvents} for a list of available events
* @see {@link IPointedCircleAdapters} for a list of available Adapters
*/
export declare class PointedCircle extends PointedShape {
/**
* Defines available properties.
*/
_properties: IPointedCircleProperties;
/**
* Defines available adapters.
*/
_adapter: IPointedCircleAdapters;
/**
* Defines available events.
*/
_events: IPointedCircleEvents;
/**
* Constructor
*/
constructor();
/**
* Draws the element.
*
* @ignore Exclude from docs
*/
draw(): void;
/**
* Radius of a circle in pixels.
*
* @default 18
* @param value Radius (px)
*/
/**
* @return Radius (px)
*/
radius: number;
/**
* Angle of a pointer, in degrees.
*
* @default 90
* @param value Angle (degrees)
*/
/**
* @return Angle of a pointer, in degrees.
*/
pointerAngle: number;
getTooltipY(): number;
getTooltipX(): number;
}
|
086fd84a1809200b29579f1205fef3aa7628f9f5
|
TypeScript
|
cyberspacedk/RxJS
|
/rxjs_ts/src/swipe/index.ts
| 3.265625
| 3
|
import { fromEvent, Observable, zip, from, merge, iif, of } from "rxjs";
import { map, switchMap, pluck } from "rxjs/operators";
// create two streams
// click or touch start
const start$ = getClientX(fromEvent<TouchEvent>(document, 'touchstart'), fromEvent<MouseEvent>(document, 'mousedown'));
// click or touch end
const end$ = getClientX(fromEvent<TouchEvent>(document, 'touchend'), fromEvent<MouseEvent>(document, 'mouseup'));
// based on previous two streams create one stream
const dimensions$ = zip(start$, end$)
// call swipe function and pass stream
swipe(dimensions$).subscribe(direction => {
const dir = direction < 0 ? 'SWIPE LEFT' : 'SWIPE RIGHT';
console.log(dir)
})
// get clientX coordinate mobile or desktop
function getClientX(sourceMobile$: Observable<TouchEvent>, sourceDesktop$: Observable<MouseEvent>){
return merge(sourceMobile$, sourceDesktop$)
.pipe(
// Variant with switchMap - lets us switch on another stream
switchMap((event: TouchEvent | MouseEvent)=>{
return iif(
()=> event instanceof TouchEvent,
of(event as TouchEvent).pipe(pluck('changeTouches', '0', 'clientX')),
of(event as MouseEvent).pipe(pluck('clientX'))
)
}),
// Variant with map
// map((event: TouchEvent | MouseEvent) => {
// if(event instanceof TouchEvent){
// return event.changedTouches[0].clientX;
// }
// return event.clientX
// })
)
}
// get stream and calculate difference between values
function swipe(source$:Observable<[number, number]>){
return source$
.pipe(
map(([start, end]) => start - end)
)
}
|
a0753674e1ff75e8a949cce13f518e92e34be77e
|
TypeScript
|
wezzzyang/game
|
/app_server/src/utils/crypto.ts
| 2.953125
| 3
|
// @ts-ignore
function Base64(this: any) {
let _keyStr =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
this.encode = function (input: string) {
var output = '';
var chr1: number,
chr2: number,
chr3: number,
enc1: number,
enc2: number,
enc3: number,
enc4: number;
var i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output =
output +
_keyStr.charAt(enc1) +
_keyStr.charAt(enc2) +
_keyStr.charAt(enc3) +
_keyStr.charAt(enc4);
}
return output;
};
// 解密
this.decode = (input: string) => {
var output = '';
var chr1: number, chr2: number, chr3: number;
var enc1: number, enc2: number, enc3: number, enc4: number;
var i = 0;
if (input == undefined || input == null) {
} else {
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
};
// private method for UTF-8 encoding
let _utf8_encode = (string: string) => {
console.log('string', string);
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
// private method for UTF-8 decoding
let _utf8_decode = (utftext: string) => {
var string = '';
var i = 0;
var c = (c2 = 0);
var c2 = 0;
var c3 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(
((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
);
i += 3;
}
}
return string;
};
}
export default new Base64();
|
52aa4b4bae460a068f81cbafd9169180725eb5bf
|
TypeScript
|
B2bCashLimited/b2b-admin.b2b.cash
|
/src/app/core/models/pager.model.ts
| 2.546875
| 3
|
export class PagerModel {
currentPage: number;
perPage: number;
totalItems: number;
totalPages: number;
constructor(obj) {
this.currentPage = obj.page;
this.perPage = obj.page_size;
this.totalItems = obj.total_items;
this.totalPages = obj.page_count;
}
}
|
430dea2d33ebb4aa41c85cd87a7f716435cc4f6a
|
TypeScript
|
power-f-GOD/books-dir-API
|
/src/controllers/books.controller.ts
| 2.609375
| 3
|
import { Request } from 'express';
import debug from 'debug';
import { BooksDB } from 'src/db';
import { Book, BRequestBody } from 'src/types';
import { BResponseSuccess, BHttpHandler } from 'src/helpers';
import { HttpStatusCode } from 'src/constants';
const log = debug('books-dir:books-controller');
class BooksController {
@BHttpHandler
async getAll(_request: Request<any, any, BRequestBody>) {
return new BResponseSuccess((await BooksDB.getAll()) || []);
}
@BHttpHandler
async getById(request: Request<any, any, BRequestBody>) {
return new BResponseSuccess(await BooksDB.getById(request.body._id!));
}
@BHttpHandler
async getByTitle(request: Request<any, any, BRequestBody>) {
return new BResponseSuccess(await BooksDB.getByTitle(request.body.title!));
}
@BHttpHandler
async getByAuthor(request: Request<any, any, BRequestBody>) {
return new BResponseSuccess(
await BooksDB.getByAuthor(request.body.author!)
);
}
@BHttpHandler
async create(request: Request<any, any, Book>) {
request.body = {
...request.body,
created_at: Date.now()
};
log(await BooksDB.create(request.body));
return new BResponseSuccess(null, 'Book created!', HttpStatusCode.CREATED);
}
@BHttpHandler
async update(request: Request<any, any, BRequestBody>) {
const { _id, ...rest } = request.body;
request.body = {
...rest,
updated_at: Date.now()
};
log(await BooksDB.updateOne(_id!, request.body));
return new BResponseSuccess(null, 'Book updated!', HttpStatusCode.CREATED);
}
@BHttpHandler
async rateBook(request: Request<any, any, BRequestBody>) {
const { _id, rating } = request.body;
let book = (await BooksDB.getByIdWithRatings(_id!))?.toJSON() as Book;
const ratings = book!.ratings!.concat([rating!]);
book = {
...book,
ratings,
rating: ratings.reduce((a, b) => a + b, 0) / ratings.length,
ratings_count: ratings.length,
updated_at: Date.now()
};
log(await BooksDB.updateOne(_id!, book));
return new BResponseSuccess(book, 'Book rated!', HttpStatusCode.CREATED);
}
@BHttpHandler
async delete(request: Request<any, any, BRequestBody>) {
log(await BooksDB.deleteOne(request.body._id!));
return new BResponseSuccess(null, 'Book deleted!');
}
}
export default new BooksController();
|
bca0392302d583df989807ccd688e41b86c990fd
|
TypeScript
|
Auroratide/Dampfire
|
/game/tools/Positioning.ts
| 3.078125
| 3
|
import * as PIXI from 'pixi.js'
export default class Positioning {
private renderer: PIXI.Renderer
constructor(renderer: PIXI.Renderer) {
this.renderer = renderer
}
y = (obj: PIXI.DisplayObject, units: number) => {
obj.y = units
}
centerX = (obj: PIXI.DisplayObject) => {
obj.x = this.renderer.width / 2
}
center = (obj: PIXI.DisplayObject) => {
obj.position.set(this.renderer.width / 2, this.renderer.height / 2)
}
topRight = (obj: PIXI.DisplayObject, padding: number = 0) => {
obj.position.set(this.renderer.width - padding, 0)
}
bottomCenter = (obj: PIXI.DisplayObject) => {
obj.position.set(this.renderer.width / 2, this.renderer.height)
}
randomOffScreen = (obj: PIXI.DisplayObject) => {
const angle = Math.random() * Math.PI * 2
const distance = Math.max(this.renderer.width, this.renderer.height) * 0.70914 // sqrt(2) / 2
obj.position.set(Math.cos(angle) * distance + this.renderer.width / 2, Math.sin(angle) * distance + this.renderer.height / 2)
}
}
|
a500f353ac5d553e3ac2290e0622f71093b58815
|
TypeScript
|
binhapp/wakatime-cli
|
/src/utils/codingGoals.ts
| 2.703125
| 3
|
import fetch from 'node-fetch';
import { Spinner } from 'cli-spinner';
import { blueText, greenText, headText, purpleText, redText } from './color';
import asTable from 'as-table';
import { handleDate } from './handleDate';
const codingGoalsUrl = 'https://wakatime.com/api/v1/users/current/goals';
interface Goals {
range: any;
range_status: string;
actual_seconds_text: string
}
let finalArr: Array<any> = [];
export const codingGoals = (apikey: string) => {
let spin = new Spinner('Fetching Data .. %s');
spin.start();
const fetchRawData = async (): Promise<void> => {
const rawData = await fetch(`${codingGoalsUrl}?api_key=${apikey}`)
.then((res) => res.json())
.catch((err) => console.log(redText(err.message)));
rawData['data'][0]['chart_data'].forEach((el: any) => {
const { range, range_status , actual_seconds_text }: Goals = el;
let tempObj = {
Duration: `${handleDate(range['start'])}-${handleDate(range['end'])}`,
Status:
range_status === 'success' ? greenText('Success') : redText('Failed'),
'Coding Time': blueText(actual_seconds_text),
};
finalArr.push(tempObj);
});
spin.stop();
console.log(headText('\nCODING GOALS :\n'))
console.log(purpleText(`Goal : ${rawData['data'][0]['title']}\n`))
console.log(asTable(finalArr));
};
fetchRawData();
};
|
190e81c354fec0694b5fc9863a36798b23e6e59b
|
TypeScript
|
Frezc/leetcode-solutions
|
/leetcode-challenge/2021-06/Matchsticks to Square.ts
| 3.484375
| 3
|
// use DFS to check every case
function makesquare(matchsticks: number[]): boolean {
const sum = matchsticks.reduce((acc, cur) => acc + cur);
if (sum % 4 !== 0) {
return false;
}
const size = sum / 4;
return checkSquare(size, [0, 0, 0, 0], matchsticks, 0);
};
function checkSquare(size: number, lens: number[], rest: number[], restIndex: number) {
if (restIndex === rest.length) {
return true;
}
for (let i = 0; i < lens.length; i++) {
const lls = lens.slice();
lls[i] += rest[restIndex];
if (lls[i] <= size) {
if (checkSquare(size, lls, rest, restIndex + 1)) {
return true;
}
}
}
return false;
}
|
bae567b3f52fdde1132f44774ef7a46e60fb4df0
|
TypeScript
|
troyunverdruss/advent-of-code-2015
|
/src/utils.ts
| 2.796875
| 3
|
import fs from "fs";
export function formatDay(day: number): string {
return day.toString().padStart(2, "0");
}
export function loadInput(day: number): string[] {
const filename = "inputs/input" + formatDay(day) + ".txt";
const lines = fs.readFileSync(filename)
.toString()
.split(/\r?\n/);
return lines;
}
|
c680df28e5b3eddbfd44e59dbf0fb0991ec25257
|
TypeScript
|
matthu/Spatial-Temporal-Storyline-Visualization
|
/src/storyline.ts
| 2.875
| 3
|
// Generators
import { storyOrder } from './order/index'
import { storyAlign } from './align/index'
import { storyCompact } from './compact/index'
import { storyRender } from './render/index'
import { storyTransform } from './transform/index'
// Data structure
import { ConstraintStore, ConstraintStyle } from './data/constraint'
import { Graph } from './data/graph'
import { Story, StoryJson } from './data/story'
// Utils
import { logConstraintError } from './utils/logger'
export default class iStoryline {
_pipeline: any;
_story: Story;
_constraintStore: ConstraintStore;
orderGenerator: any;
alignGenerator: any;
compactGenerator: any;
renderGenerator: any;
transformGenerator: any;
/**
* Construct a iStoryline generator for a story.
* Once the story changed, the generator should be re-constructed.
*
* @param {Array} pipeline
* - ['GreedyOrder', 'GreedyAlign', 'GreedySlotCompact', 'SmoothRender', 'FreeTransform']
*/
constructor(
pipeline = [
'GreedyOrder',
'GreedyAlign',
'GreedySlotCompact',
'SmoothRender',
'FreeTransform',
]
) {
this._pipeline = pipeline
this._story = new Story()
this._constraintStore = new ConstraintStore()
}
/**
* Generate storyline visualizations from the input file.
*
* @param {String} fileUrl
* - "./data/JurassicPark.xml"
*/
async loadFile(fileUrl: string) {
await this._story.loadFile(fileUrl)
return this._layout()
}
/**
* Generate storyline visualizations from the input json.
*
* @param {Object} storyJson
* - https://github.com/tangtan/iStoryline.js/wiki/Story-Script
*/
load(storyJson: StoryJson) {
this._story.loadJson(storyJson)
return this._layout()
}
_layout() {
const { _story, _constraintStore, _pipeline } = this
const _constraints = _constraintStore.constraints
// Order
this.orderGenerator = _pipeline[0] || null
if (this.orderGenerator) {
storyOrder(this.orderGenerator, _story, _constraints)
}
// Align
this.alignGenerator = _pipeline[1] || null
if (this.alignGenerator) {
storyAlign(this.alignGenerator, _story, _constraints)
}
// Compact
this.compactGenerator = _pipeline[2] || null
if (this.compactGenerator) {
storyCompact(this.compactGenerator, _story, _constraints)
}
// Render
this.renderGenerator = _pipeline[3] || null
if (this.renderGenerator) {
storyRender(this.renderGenerator, _story, _constraints)
}
// Transform
this.transformGenerator = _pipeline[4] || null
if (this.transformGenerator) {
storyTransform(this.transformGenerator, _story, _constraints)
}
return new Graph(_story)
}
// Only enable download json file.
dump(fileName: string) {
this._story.dump(fileName, 'json')
}
addCharacter(character: string, timeRange: number[][]) {
this._story.addCharacter(character, timeRange)
return this._layout()
}
changeCharacter(character: string | number, timeRange: number[][]) {
this._story.changeCharacter(character, timeRange)
return this._layout()
}
deleteCharacter(character: string | number) {
this._story.deleteCharacter(character)
return this._layout()
}
addSession(characters: (string | number)[], timeSpan: number[]) {
const newSessionID = this._story.getNewSessionID()
this._story.changeSession(newSessionID, characters, timeSpan)
return this._layout()
}
// removeSession(sessionID) {
// this._story.deleteSession(sessionID)
// return this._layout()
// }
addLocation(location: string, characters: number[], timeRange: number[][]) {
this._story.changeLocation(location, characters, timeRange)
return this._layout()
}
removeLocation(location: string) {
this._story.changeLocation(location)
return this._layout()
}
/**
* Rearrange the order of characters
*
* @param {String[]} names
* @param {Number[]} timeSpan
*
* @example
* - constraint: {
* "names": ['upperName', 'lowerName'],
* "timeSpan": [t1, t2],
* "style": 'Sort',
* "param": {}
* }
*
* @return graph
*/
sort(names: string[], timeSpan: number[]) {
if (names.length > 1 && timeSpan.length === 2) {
this._constraintStore.add(names, timeSpan, 'Sort', {})
} else {
logConstraintError('Sort')
}
return this._layout()
}
/**
* Bend character lines
*
* @param {String[]} names
* @param {Number[]} timeSpan
*
* @example
* - constraint: {
* "names": ['name'],
* "timeSpan": [t1, t2],
* "style": 'Bend',
* "param": {}
* }
*
* @return graph
*/
bend(names: string[], timeSpan: number[]) {
if (
names.length === 1 &&
timeSpan.length === 2 &&
timeSpan[0] === timeSpan[1]
) {
this._constraintStore.add(names, timeSpan, 'Bend', {})
} else {
logConstraintError('Bend')
}
return this._layout()
}
/**
* Straighten character lines
*
* @param {String[]} names
* @param {Number[]} timeSpan
*
* @example
* - constraint: {
* "names": ['name'],
* "timeSpan": [t1, t2],
* "style": 'Straighten',
* "param": {}
* }
*
* @return graph
*/
straighten(names: string[], timeSpan: number[]) {
if (
names.length === 1 &&
timeSpan.length === 2 &&
timeSpan[0] !== timeSpan[1]
) {
this._constraintStore.add(names, timeSpan, 'Straighten', {})
} else {
logConstraintError('Straighten')
}
return this._layout()
}
/**
* Remove white space
*
* @param {String[]} names
* @param {Number[]} timepan
* @param {Number} scale
*
* @example
* - scale: 0<<1
* - constraint: {
* "names": ['name1', 'name2', ...],
* "timeSpan": [t1, t2],
* "style": 'Compact',
* "param": { 'scale': 0.5 }
* }
*
* @return graph
*/
compress(names: string[], timeSpan: number[], scale: number = 0.5) {
if (names.length === 2 && timeSpan.length === 2) {
this._constraintStore.add(names, timeSpan, 'Compress', { scale: scale })
} else {
logConstraintError('Compress')
}
return this._layout()
}
/**
* Expand white space
*
* @param {String[]} names
* @param {Number[]} timeSpan
* @param {Number} scale
*
* @example
* - scale: >1
* - constraint: {
* "names": ['name1', 'name2', ...],
* "timeSpan": [t1, t2],
* "style": 'Expand',
* "param": {}
* }
*
* @return graph
*/
expand(names: string[], timeSpan: number[], scale: number = 2) {
if (names.length === 2 && timeSpan.length === 2) {
this._constraintStore.add(names, timeSpan, 'Expand', { scale: scale })
} else {
logConstraintError('Expand')
}
return this._layout()
}
/**
* Control white space
*
* @param {Number} intraSep
* @param {Number} interSep
*
* @return graph
*/
space(intraSep: number, interSep: number) {
this._constraintStore.add([], [], 'Space', {
intraSep: intraSep,
interSep: interSep,
})
return this._layout()
}
/**
* Change line paths
*
* @param {String[]} names
* @param {Number[]} timeSpan
* @param {Point[]} path
* @param {Array} constraints
*
* @example
* - constraint: {
* "names": ['name'],
* "timeSpan": [t1, t2],
* "style": 'Adjust',
* "param": {'path': [x1, y1, x2, y2, ...]}
* }
*
* @return graph
*/
adjust(names: string[], timeSpan: number[], path: string[]) {
if (
names.length === 1 &&
timeSpan.length === 2 &&
timeSpan[1] > timeSpan[0]
) {
this._constraintStore.add(names, timeSpan, 'Adjust', { path: path })
} else {
logConstraintError('Adjust')
}
return this._layout()
}
/**
* Relate lines acccording to the semantic connections
*
* @param {String[]} names
* @param {Number[]} timeSpan
* @param {String} style
* @param {Array} constraints
*
* @example
* - constraint: {
* "names": ['name1', 'name2'],
* "timeSpan": [t1, t2],
* "style": 'Twine' | 'Knot' | 'Collide' | 'Merge' | 'Split',
* "param": {}
* }
*
* @return graph
*/
relate(names: string[], timeSpan: number[], style: ConstraintStyle) {
if (names.length === 2 && timeSpan.length === 2) {
this._constraintStore.add(names, timeSpan, style, {})
} else {
logConstraintError('Relate')
}
return this._layout()
}
/**
* Set the style of lines
*
* @param {String[]} names
* @param {Number[]} timeSpan
* @param {String} style
*
* @example
* - constraint: {
* "names": ['name'],
* "timeSpan": [t1, t2],
* "style": 'Color' | 'Width' | 'Dash' | 'Zigzag' | 'Wave' | 'Bump',
* "param": {}
* }
*
* @return graph
*/
stylish(names: string[], timeSpan: number[], style: ConstraintStyle) {
if (names.length === 1 && timeSpan.length === 2) {
this._constraintStore.add(names, timeSpan, style, {})
} else {
logConstraintError('Stylish')
}
return this._layout()
}
/**
* Reshape the layout.
*
* @param {Number[]} upperPath
* @param {Number[]} lowerPath
*
* @example
* - path: [x1, y1, x2, y2, ...]
*
* @return graph
*/
reshape(upperPath: string[] = [], lowerPath: string[] = []) {
this._constraintStore.add([], [], 'Reshape', {
upperPath: upperPath,
lowerPath: lowerPath,
})
return this._layout()
}
/**
* Change the size of storyline visualization
*
* @param {Number} x0
* @param {Number} y0
* @param {Number} width
* @param {Number} height
* @param {Boolean} reserveRatio
*
* @return graph
*/
scale(x0: number = 0, y0: number = 0, width: number = 1000, height: number = 372, reserveRatio: boolean = false) {
this._constraintStore.add([], [], 'Scale', {
x0: x0,
y0: y0,
width: width,
height: height,
reserveRatio: reserveRatio,
})
return this._layout()
}
}
|
ae2ef218b662fb2fffc16ef302c6b3fc95612913
|
TypeScript
|
min33sky/murmur
|
/Frontend/typings/posts.d.ts
| 2.75
| 3
|
export type CommentType = {
id: string;
content: string;
User: {
id: string;
nickname: string;
};
};
export interface IPost {
id: string;
content: string;
likes: number[]; //? 좋아요를 누른 사람들의 아이디
User: {
id: string;
nickname: string;
email: string;
}; // 포스트 작성자
Images: { src: string }[]; // 포스트에 포함된 이미지들
Comments: CommentType[];
}
|
738cf0b17a5679853fd332fe614efd87fe0cd219
|
TypeScript
|
soltrinox/ecos-design-system
|
/src/routes/guides/guides-list.ts
| 2.625
| 3
|
import { customElement, IRouteViewModel } from 'aurelia';
import template from './guides-list.html'
import guides from './guides.json';
@customElement({name: 'guides-list', template})
export class GuidesList implements IRouteViewModel {
public guidesList = guides;
public filteringTag = 'all';
public search = '';
public get tags(): string[] {
const tags = guides.reduce((previousValue, currentValue) => {
for (const badge of (currentValue as unknown as {badges: string[]}).badges) {
if (!previousValue.includes(badge)) {
previousValue.push(badge);
}
}
return previousValue;
}, []);
return tags;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public getGuidesList(search: string, tag: string): any[] {
return this.guidesList.filter((guide) => {
const foundWithSearch = search === ''
|| guide.name.toLowerCase().includes(search.toLowerCase())
|| guide.description.toLowerCase().includes(search.toLowerCase());
const foundWithTag = tag === '' || tag === 'all'
|| (guide as unknown as {badges: string[]}).badges.includes(tag);
return foundWithSearch && foundWithTag;
})
}
}
|
ef9c6a6e9637fde66c9899672a94f8a2fae3658b
|
TypeScript
|
avemike/flappy-bird.js
|
/client/utils/getBirdAssets.ts
| 2.53125
| 3
|
import sprites from "url:../../assets/birds/**/*.svg";
import { BIRD_COLORS } from "../../configs/game";
const birdColor = {
color: BIRD_COLORS.YELLOW,
};
function setBirdColor(color: BIRD_COLORS) {
birdColor.color = color;
}
function getBirdAssets(color: BIRD_COLORS): HTMLImageElement[] {
const wingsBot = new Image();
const wingsMid = new Image();
const wingsUp = new Image();
wingsBot.src = sprites[color].bottom;
wingsMid.src = sprites[color].mid;
wingsUp.src = sprites[color].top;
const bird_spr: HTMLImageElement[] = [wingsBot, wingsMid, wingsUp];
return bird_spr;
}
export { getBirdAssets, setBirdColor };
|
3655233651f670c17e48343c353b1010fffbdf50
|
TypeScript
|
ViV3RRa/sisl-client
|
/src/ui/reducers/all-questionnaires-reducer.ts
| 3.03125
| 3
|
interface IAllQuestionnairesFetching {
type: 'ALL_QUESTIONNAIRES_FETCHING';
payload: any;
}
interface IAllQuestionnairesFetched {
type: 'ALL_QUESTIONNAIRES_FETCHED';
payload: any;
}
export type AllQuestionnairesActions =
| IAllQuestionnairesFetching
| IAllQuestionnairesFetched;
export interface IUIStateAllQuestionnaires {
fetching: boolean;
data: {}[];
}
export const initialStateAllQuestionnaires: IUIStateAllQuestionnaires = {
fetching: false,
data: []
};
export function allQuestionnairesReducer(
state: IUIStateAllQuestionnaires = initialStateAllQuestionnaires,
action: AllQuestionnairesActions
) {
switch (action.type) {
case 'ALL_QUESTIONNAIRES_FETCHING':
return {
...state,
fetching: true,
data: []
};
case 'ALL_QUESTIONNAIRES_FETCHED':
return {
...state,
fetching: false,
data: action.payload
};
default:
return state;
}
}
|
1ad2920340145d3c8ccf465d0d5c6e2be91cab36
|
TypeScript
|
krawaller/algol5
|
/modules/content/commands/helpers/stubGame.ts
| 2.734375
| 3
|
import { GameId } from "../../../games/dist/list";
import meta from "../../../games/dist/meta";
import path from "path";
import fs, { writeFileSync } from "fs-extra";
export const stubGame = (gameId: GameId) => {
const out = path.join(__dirname, `../../material/games/${gameId}`);
if (!fs.existsSync(out)) {
fs.ensureDirSync(out);
writeFileSync(
path.join(out, `about.md`),
`---
updated: ${new Date().toISOString().slice(0, 10)}
---
{GAME}! ${meta[gameId].tagline}. More yabber about the game to come!`
);
writeFileSync(path.join(out, `links.ts`), `export const links = {};\n`);
writeFileSync(
path.join(out, `rules.md`),
`---
updated: ${new Date().toISOString().slice(0, 10)}
---
{GAME} is played on a {DIM} board with the following setup:
{SETUP}
Soon we will show the rules for {GAME} here! In the meantime you can read them {EXTLINK:url=${
meta[gameId].source
},text=here}.`
);
fs.ensureDirSync(path.join(out, `pics`));
const cap = gameId[0].toUpperCase() + gameId.slice(1);
writeFileSync(
path.join(out, "arrangements.ts"),
`// File created by the stubGame command
import { AlgolArrangements } from "../../../../types";
import { ${cap}Blob } from "../../../../games/dist/games/${gameId}";
// Add your arrangements in this object, and then you can refer to them
// from the markdown files. Those references will be replaced by a
// generated SVG when the content is written to html.
export const arrangements: AlgolArrangements<${cap}Blob> = {};`
);
} else {
throw new Error(
`Tried to stub content for ${gameId} but folder already existed!`
);
}
};
|
5afa86cf363cc390468506abf2cca90af2e9dfaa
|
TypeScript
|
xiriuxb/mecanica
|
/backend/api-mecanica/src/clases-genericas/clase-generica-component/clase-generica.controller.ts
| 2.59375
| 3
|
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
InternalServerErrorException,
Param,
Post,
Put,
Query,
} from '@nestjs/common';
import { ClaseGenericaService } from './clase-generica.service';
import { validate } from 'class-validator';
import { ConsultaInterface } from './consulta.interface';
@Controller()
export class ClaseGenericaController<Entity> {
crearDto: any;
editarDto: any;
constructor(
private readonly _claseGenericaService: ClaseGenericaService<Entity>,
) {}
@Post()
async crear(@Body() datos: Entity) {
const nuevoDato = new this.crearDto(datos);
const errores = await validate(nuevoDato);
const existeErrores = errores.length > 0;
if (!existeErrores) {
try {
const respuesta: any = await this._claseGenericaService.crear(datos);
return {
data: respuesta,
id: respuesta.id,
};
} catch (e) {
throw new InternalServerErrorException(e);
}
} else {
throw new BadRequestException(errores);
}
}
@Put(':id')
async editar(@Param('id') id: number, @Body() datos: Entity) {
const datosAActualizar = new this.editarDto(datos);
const errores = await validate(datosAActualizar);
const existeErrores = errores.length > 0;
if (!existeErrores) {
try {
return await this._claseGenericaService.editar(id, datos);
} catch (e) {
throw new InternalServerErrorException(e);
}
} else {
throw new BadRequestException(errores);
}
}
@Get()
async listarTodo(@Query() parametros: ConsultaInterface) {
parametros.skip = Number(parametros.skip);
parametros.take = Number(parametros.take);
try {
const resultado = await this._claseGenericaService.listarTodos(
parametros.skip,
parametros.take,
);
return {
data: resultado[0],
cantidad: resultado[1],
};
} catch (e) {
throw new InternalServerErrorException(e);
}
}
@Get(':id')
async listarPorId(@Param('id') id: number) {
try {
return await this._claseGenericaService.listarPorId(id);
} catch (e) {
throw new InternalServerErrorException(e);
}
}
@Delete(':id')
async eliminar(@Param('id') id: number) {
try {
return await this._claseGenericaService.eliminar(id);
} catch (e) {
throw new InternalServerErrorException(e);
}
}
}
|
acc4d5badb4724b9f786f96b82b4742ed6e6765f
|
TypeScript
|
maiyama18/ymark
|
/src/node/node.ts
| 3.3125
| 3
|
export type Node = Document | Line | Inline;
// Document node
export class Document {
public readonly nodeType = 'DOCUMENT';
public lines: Line[];
constructor(lines: Line[] = []) {
this.lines = lines;
}
public addLine(line: Line): void {
this.lines.push(line);
}
}
// Line nodes
export type Line = Paragraph | Header | List;
export class Paragraph {
public readonly nodeType = 'PARAGRAPH';
public inlines: Inline[];
constructor(inlines: Inline[] = []) {
this.inlines = inlines;
}
public addInline(inline: Inline): void {
this.inlines.push(inline);
}
}
export class Header {
public readonly nodeType = 'HEADER';
public numHashes: number;
public inlines: Inline[];
constructor(numHashes: number, inlines: Inline[] = []) {
this.numHashes = numHashes;
this.inlines = inlines;
}
public addInline(inline: Inline): void {
this.inlines.push(inline);
}
}
export class List {
public readonly nodeType = 'LIST';
public isFirst: boolean;
public isLast: boolean;
public inlines: Inline[];
constructor(isFirst: boolean = false, isLast: boolean = false, inlines: Inline[] = []) {
this.isFirst = isFirst;
this.isLast = isLast;
this.inlines = inlines;
}
public addInline(inline: Inline): void {
this.inlines.push(inline);
}
}
// Inline nodes
export type Inline = Text | Link;
export class Text {
public readonly nodeType = 'TEXT';
public text: string;
constructor(text: string = '') {
this.text = text;
}
public html(): string {
return `<span>${this.text}</span>`;
}
}
export class Link {
public readonly nodeType = 'LINK';
public text: string;
public href: string;
constructor(text: string = '', href: string = '') {
this.text = text;
this.href = href;
}
public html(): string {
return `<a href="${this.href}">${this.text}</a>`;
}
}
|
7d19aa997d4424fdb5a9f1594bcefbead6060863
|
TypeScript
|
dey600r/MTM
|
/app/src/app/core/services/common/calendar.service.ts
| 2.609375
| 3
|
import { Injectable } from '@angular/core';
// LIBRARY ANGULAR
import { TranslateService } from '@ngx-translate/core';
import * as Moment from 'moment';
// UTILS
import { Constants } from '@utils/index';
// MODELS
import { VehicleModel } from '@models/index';
@Injectable({
providedIn: 'root'
})
export class CalendarService {
constructor(private translator: TranslateService) {
}
// COMMON UTILS METHODS STRINGS
getDateString(date: Date): any {
return Moment(date).format(this.getFormatCalendar());
}
getDateStringToDB(date: Date): any {
return Moment(date).format(Constants.DATE_FORMAT_DB);
}
getDateTimeStringToDB(date: Date): any {
return Moment(date).format(Constants.DATE_TIME_FORMAT_DB);
}
getFormatCalendar() {
return this.translator.currentLang === 'es' ? Constants.DATE_FORMAT_ES : Constants.DATE_FORMAT_EN;
}
getFormatCalendarWeekStart() {
return this.translator.currentLang === 'es' ? 1 : 0;
}
getFormatCalendarWeek() {
return this.translator.currentLang === 'es' ?
['D', 'L', 'M', 'X', 'J', 'V', 'S'] : ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
}
getFormatCalendarMonth() {
return this.translator.currentLang === 'es' ?
['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SEP', 'OCT', 'NOV', 'DEC'] :
['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
}
// COMMON UTILS METHODS
monthDiff(dateIni: Date, dateFin: Date): number {
let months: number = (dateFin.getFullYear() - dateIni.getFullYear()) * 12;
months -= dateIni.getMonth() + 1;
months += dateFin.getMonth() + 1;
return months <= 0 ? 0 : months;
}
dayDiff(dateIni: Date, dateFin: Date): number {
const diffc: number = dateFin.getTime() - dateIni.getTime();
const days: number = Math.round(Math.abs(diffc / (1000 * 60 * 60 * 24)));
return days <= 0 ? 0 : days;
}
sumTimeToDate(date: Date, time: number): Date {
const dateResult: Date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
dateResult.setMonth(dateResult.getMonth() + time);
return dateResult;
}
// CALCULATE VEHICLE
calculateKmVehicleEstimated(vehicle: VehicleModel): number {
const kmPerM: number = this.calculateKmsPerMonth(vehicle);
const dateKm: Date = new Date(vehicle.dateKms);
return vehicle.km + (vehicle.active ? (Math.round((kmPerM / 30) * this.dayDiff(dateKm, new Date()))) : 0 );
}
calculateKmsPerMonth(vehicle: VehicleModel): number {
let kmPerM: number = vehicle.kmsPerMonth;
const dateKm: Date = new Date(vehicle.dateKms);
if (!kmPerM || kmPerM === 0) {
const diffMonts: number = this.monthDiff(new Date(vehicle.datePurchase), dateKm);
kmPerM = Math.round(vehicle.km / (diffMonts === 0 ? 1 : diffMonts));
}
return (kmPerM === 0 ? 1 : kmPerM);
}
}
|
0a08f7f9f981b316cd1138f05166c347a6eca585
|
TypeScript
|
microsoft/FluidFramework
|
/server/routerlicious/packages/services-core/src/clientManager.ts
| 2.5625
| 3
|
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { IClient, ISignalClient, ISignalMessage } from "@fluidframework/protocol-definitions";
/**
* Represents a client that has some sequence numbers attached
*/
export interface ISequencedSignalClient {
/**
* The client object
*/
client: IClient;
/**
* Counts the number of signals sent by the client
*/
clientConnectionNumber: number;
/**
* Sequence number that indicates when the signal was created in relation to the delta stream
*/
referenceSequenceNumber: number;
/**
* The time when the client will expire.
* The client will expire if Date.now() exceeds this value.
*/
exp: number;
}
/**
* Manages the list of clients connected to the websocket.
*/
export interface IClientManager {
/**
* Adds a client to the list.
*/
addClient(
tenantId: string,
documentId: string,
clientId: string,
details: IClient,
signalMessage?: ISignalMessage,
): Promise<void>;
/**
* Removes a client from the list.
*/
removeClient(
tenantId: string,
documentId: string,
clientId: string,
signalMessage?: ISignalMessage,
): Promise<void>;
/**
* Returns all clients currently connected.
*/
getClients(tenantId: string, documentId: string): Promise<ISignalClient[]>;
/**
* Returns all clients currently connected including a keep alive time.
* Should be used with delis read only client functionality.
*/
getSequencedClients(
tenantId: string,
documentId: string,
): Promise<Map<string, ISequencedSignalClient>>;
/**
* Called when the expiration time of clients should be extended.
* @param clientTimeout - Amount of time in milliseconds to add to the clients expiration time.
*/
extendSequencedClients(
tenantId: string,
documentId: string,
clients: Map<string, ISequencedSignalClient>,
clientTimeout: number,
): Promise<void>;
}
|
8105f083ed87327aa0e01c273f5177485524dd9b
|
TypeScript
|
Leko/darkdown
|
/parser-combinator/EOS.ts
| 2.953125
| 3
|
import { Parser } from './parser.ts'
// End of string
export const EOS = (): Parser<boolean> => (input: string, pos: number) => {
if (input.length === pos) {
return [true, true, pos]
}
return [false, null, pos]
}
|
5b1d0119fbf788b20f4e8c664ccfa99c8549da11
|
TypeScript
|
wso2/samples-is
|
/b2b-sample/libs/business-admin-app/data-access/data-access-controller/src/lib/controller/role/controllerPatchRole/controllerDecodePatchRole.ts
| 2.53125
| 3
|
/**
* Copyright (c) 2022, WSO2 LLC. (https://www.wso2.com). All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Role } from "@b2bsample/business-admin-app/data-access/data-access-common-models-util";
import { commonControllerDecode } from "@b2bsample/shared/data-access/data-access-common-api-util";
import { PatchBody } from "@b2bsample/shared/data-access/data-access-common-models-util";
import { PatchMethod } from "@b2bsample/shared/util/util-common";
import { Session } from "next-auth";
import { controllerCallPatchRole } from "./controllerCallPatchRole";
function getAddReplaceBody(patchMethod: PatchMethod, path: string, value: string[] | string): PatchBody {
return {
"operations": [
{
"op": patchMethod,
"path": path,
"value": value
}
]
};
}
function getRemoveBody(patchMethod: PatchMethod, path: string, value: string[] | string): PatchBody {
return {
"operations": [
{
"op": patchMethod,
"path": `${path}[value eq ${value}]`
}
]
};
}
function getPatchBody(patchMethod: PatchMethod, path: string, value: string[] | string) {
switch (patchMethod) {
case PatchMethod.ADD:
return getAddReplaceBody(patchMethod, path, value);
case PatchMethod.REPLACE:
return getAddReplaceBody(patchMethod, path, value);
case PatchMethod.REMOVE:
return getRemoveBody(patchMethod, path, value);
default:
return;
}
}
/**
* Decodes the response from the API call to patch a role.
*
* @param session - session object
* @param roleUri - uri of the role
* @param patchMethod - `PatchMethod.ADD`, `PatchMethod.REPLACE` or `PatchMethod.REMOVE`
* @param path - path
* @param value - edited value
*
* @returns - whehter the patch was successful or not.
*/
export async function controllerDecodePatchRole(
session: Session, roleUri: string, patchMethod: PatchMethod, path: string, value: string[] | string)
: Promise<Role | null> {
const patchBody: PatchBody = (getPatchBody(patchMethod, path, value) as PatchBody);
const res = (
await commonControllerDecode(() => controllerCallPatchRole(session, roleUri, patchBody), null) as Role | null);
return res;
}
export default controllerDecodePatchRole;
|
d60f52ccc20a44725d05ddba4aa743b59384229a
|
TypeScript
|
hostops/estech-challenge
|
/web-application/src/main/webapp/app/shared/model/system-device-type.model.ts
| 2.578125
| 3
|
import { ISystemDevice } from 'app/shared/model/system-device.model';
export const enum DeviceType {
CONTROLLER = 'CONTROLLER',
CONFIGURABLE = 'CONFIGURABLE',
PASSIVE = 'PASSIVE',
SENSOR = 'SENSOR'
}
export interface ISystemDeviceType {
id?: number;
name?: string;
description?: string;
deviceType?: DeviceType;
dataSheet?: string;
devices?: ISystemDevice[];
}
export class SystemDeviceType implements ISystemDeviceType {
constructor(
public id?: number,
public name?: string,
public description?: string,
public deviceType?: DeviceType,
public dataSheet?: string,
public devices?: ISystemDevice[]
) {}
}
|
b4fe54fc627800eb8e5c0b2754ac71535c92a281
|
TypeScript
|
pgnDataBase/pgnDB
|
/webclient/src/pipes/error-code.pipe.ts
| 2.90625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'errorCode'
})
export class ErrorCodePipe implements PipeTransform {
transform(value: any, args?: any): any {
return this.errorCodes(value) ? this.errorCodes(value) : "Unknown error";
}
errorCodes(value: string) {
if (value === 'required') {
return 'Field is required'
}
if (value === 'maxLength') {
return 'Max length exceeded';
}
if (value.startsWith('minValue')) {
let minValue = value.split(':')[1];
return 'Value is too low. Min is ' + minValue;
}
if (value.startsWith('maxValue')) {
let maxValue = value.split(':')[1];
return 'Value is too high. Max is ' + maxValue;
}
if (value === 'minLength') {
return 'Field too short';
}
if (value === 'usernameTaken') {
return 'Username already taken';
}
}
}
|
627c45d43153d2eb1a036b963d61b553f03d7cb0
|
TypeScript
|
nextools/metarepo
|
/packages/autoprops/src/check-child-perm.ts
| 2.75
| 3
|
import BigInt from 'big-integer'
import type { BigInteger } from 'big-integer'
import { getValidPermImpl } from './get-valid-perm'
import { skipToPerm } from './skip-to-perm'
import type { TCommonComponentConfig, TCheckPermFn } from './types'
const getValidChildPerm = (childConfig: TCommonComponentConfig, int: BigInteger, isChildRequired: boolean): BigInteger | null => {
if (isChildRequired) {
// no index offset needed
return getValidPermImpl(childConfig, int)
}
// Offset index back and forth
const perm = getValidPermImpl(childConfig, int.minus(BigInt.one))
if (perm === null) {
return perm
}
return perm.plus(BigInt.one)
}
export const checkChildPerm: TCheckPermFn = (values, permConfig, componentConfig) => {
const { propKeys, childrenKeys } = permConfig
// Have to check every child, because deps check get child into invalid state
for (let i = propKeys.length; i < values.length; ++i) {
const childKey = childrenKeys[i - propKeys.length]
const isChildRequired = Boolean(componentConfig.required?.includes(childKey))
// Skip if child is inactive
if (values[i].isZero() && !isChildRequired) {
continue
}
// Valid value guaranteed
const childConfig = componentConfig.children![childKey]!.config
// Validate Child Perm
const childInt = getValidChildPerm(childConfig, values[i], isChildRequired)
// check no valid index left
if (childInt === null) {
return skipToPerm(values, permConfig, i + 1)
}
// check no changes, perm is valid
if (childInt.equals(values[i])) {
continue
}
// perm was invalid, apply new perm
const nextValues = values.slice()
nextValues[i] = childInt
return nextValues
}
return values
}
|
1fc7c65cd7fd42a7cf88786e0575563590dd1f0a
|
TypeScript
|
techwebb/world
|
/src/app/models/Race.ts
| 2.640625
| 3
|
import { Human } from './Human';
export class Race{
name:string;
height:number;
fields;
constructor(){
this.fields = [
{name:'gender', type:'choice'},
{name:'height', type:'distribution'}
];
}
getName(){
return 'human';
}
toString(){
return this.name || 'not sure';
}
}
|
60cf604812e095624263951d2d9ef2a3604474ce
|
TypeScript
|
alxrgv/greendata-coding-assignment
|
/src/components/EmployeesList/config.ts
| 2.953125
| 3
|
import { format, isDate } from "date-fns";
import { ru } from "date-fns/locale";
import type { ReactNode } from "react";
import type { TableCellProps } from "@material-ui/core";
import type { Employee } from "store/models";
import type { PropTypeExtractor } from "types/global";
import { Gender } from "store/models";
export interface CellConfig {
key: string;
title: string;
cellAlign: TableCellProps["align"];
titleAlign: TableCellProps["align"];
selector: (emp: Employee) => PropTypeExtractor<Employee>;
render: (value: any) => ReactNode;
}
const undefinedStringifiedValue = "Не указано";
export const mainTableConfig: CellConfig[] = [
{
key: "fullname",
title: "ФИО",
cellAlign: "left",
titleAlign: "center",
selector: (emp) => emp.fullname,
render: (value: string) => value,
},
{
key: "gender",
title: "Пол",
cellAlign: "right",
titleAlign: "center",
selector: (emp) => emp.gender,
render: (value: Gender) => {
if (value === Gender.Unknown) {
return undefinedStringifiedValue;
} else if (value === Gender.Male) {
return "Мужской";
} else {
return "Женский";
}
},
},
{
key: "position",
title: "Должность",
cellAlign: "right",
titleAlign: "center",
selector: (emp) => emp.position,
render: (value: string) => value,
},
{
key: "birthday",
title: "Дата рождения",
cellAlign: "right",
titleAlign: "right",
selector: (emp) => emp.birthday,
render: (value: Date | null) => {
if (isDate(value)) {
return format(value as Date, "dd MMMM yyyy", { locale: ru });
}
return undefinedStringifiedValue;
},
},
{
key: "isFired",
title: "Уволен",
cellAlign: "center",
titleAlign: "right",
selector: (emp) => emp.isFired,
render: (value: boolean) => (value ? "Да" : "Нет"),
},
];
export const nestedTableConfig: CellConfig[] = [
{
key: "fullname",
title: "ФИО",
cellAlign: "center",
titleAlign: "center",
selector: (emp) => emp.fullname,
render: (value: string) => value,
},
{
key: "position",
title: "Должность",
cellAlign: "center",
titleAlign: "center",
selector: (emp) => emp.position,
render: (value: string) => value,
},
];
|
6d242d04ccefa757b7fbd11af44dd6ac0a452dd9
|
TypeScript
|
floorin/apaca-frontend
|
/src/modules/utils.ts
| 2.640625
| 3
|
import moment, {Moment} from 'moment';
import nomenclatoare from '@/store/nomenclatoare';
import {getModule} from 'vuex-module-decorators';
const storeNomenclatoare = getModule(nomenclatoare);
export function dateToStringDDMonYYYY(pDate: Moment) {
return moment(pDate).format('D MMM YYYY');
}
export function humanReadableBytes(bytes:number):string {
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
// @ts-ignore
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
}
export function denDepartamentFromOrg(pOrgId: number):string {
const departament = storeNomenclatoare.NomOrganizatii.find(organizatie=>{
return organizatie.appid==pOrgId;
})
if(departament){
return departament.divizie+' / '+departament.departament;
}else{
return 'nedefinit';
}
}
export function denPersoanaUtilizatorFromMarca(pMarca: number):string {
const persoana = storeNomenclatoare.NomPersoaneUtilizatoare.find(ppersoana=>{
return ppersoana.marca==pMarca;
})
if(persoana){
return persoana.firstName+' '+persoana.lastName;
}else{
return 'nedefinit';
}
}
export function ValidateEmail(mailString:string):boolean
{
var result=false;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(mailString) == false)
{
result=false;
}else{
result=true;
}
return result;
}
|
1f69027ed39a98fbda76b08b447cb1cdb4b28892
|
TypeScript
|
MichalLytek/type-graphql
|
/src/helpers/utils.ts
| 2.734375
| 3
|
export type ArrayElements<TArray extends readonly any[]> = TArray extends ReadonlyArray<
infer TElement
>
? TElement
: never;
export type UnionFromClasses<TClassesArray extends readonly any[]> = InstanceType<
ArrayElements<TClassesArray>
>;
|
0634af4ffa489fdb13a8b2c841894bedd45804f5
|
TypeScript
|
LimMem/cgyro
|
/app/src/utils/file.ts
| 2.921875
| 3
|
const fs = require("fs");
const path = require("path");
import handlebars from 'handlebars';
import inquirer from 'inquirer';
import {
warn,
} from './logger'
/**
* 从文件夹读取所有文件路径
* @param dir 文件路径
*/
const getFilesPathWithDir = (dirPath: string) => {
const fsSync = (dPath: string, paths: string[]) => {
fs.readdir(dPath, (err: any, files: string[]) => {
if (err) throw err;
files.forEach((file: string) => {
//拼接获取绝对路径,fs.stat(绝对路径,回调函数)
let fPath = path.join(dirPath, file);
fs.stat(fPath, (error: any, stat: { isFile: () => any; }) => {
if (!error) {
if (stat.isFile()) {
paths.push(fPath);
} else {
fsSync(fPath, paths);
}
}
});
});
});
};
let resultPath: string[] = [];
fsSync(dirPath, resultPath);
return resultPath;
}
export const tplFile = (filePath: string, options: any) => {
const packageContent = fs.readFileSync(filePath, 'utf-8')
//使用handlebars解析模板引擎
const packageResult = handlebars.compile(packageContent)(options)
//将解析后的结果重写到package.json文件中
fs.writeFileSync(filePath, packageResult)
};
export const tplDir = (dir: string, options: any) => {
if (!dir) {
return;
}
const paths = getFilesPathWithDir(dir);
paths.forEach(path => {
tplFile(path, options);
});
};
// 检查是否已经存在相同名字工程
export const checkProjectExist = async (targetDir: string) => {
if (fs.existsSync(targetDir)) {
const answer: any = await inquirer.prompt({
type: 'list',
name: 'checkExist',
message: `\n仓库路径${targetDir}已存在,请选择`,
choices: ['覆盖', '取消'],
})
if (answer?.checkExist === '覆盖') {
warn(`删除${targetDir}...`)
fs.removeSync(targetDir)
} else {
return true
}
}
return false
}
|
835c39853ebd083a84840c46847f94baec63baed
|
TypeScript
|
danielnguyen/mavis-bot
|
/src/skills/controllers/vj.ts
| 2.515625
| 3
|
import * as _ from "lodash";
import { Bot, Controller, Message, Conversation} from "botkit";
import { BotkitNLP, NLPMessage } from "../../middleware/botkit-nlp";
import { VideoRequestModel } from "../models/vj";
import { Config } from "../../config"
import { platform } from "os";
import { BaseSkill } from "./_skill";
import { MessageUtils } from "../helpers/messageutils";
import { VJServices } from "../services/vjServices";
/**
* Video Jockey skills.
*/
export class VJSkill extends BaseSkill {
/**
* List of video platforms
*/
private static VIDEO_PLATFORMS: string[] = ["youtube", "netflix", "anime", "vimeo", "hulu", "cbc", "dramafevor", "twice", "vevo"];
/**
* List of projection mediums
*/
private static PROJECTION_MEDIUMS: string[] = ["tv", "television", "projector"];
/**
* List of common strings to remove to make the search more accurate.
*/
private static COMMON_STRINGS: string[] = ["on", "the"]
private vjServices: VJServices = new VJServices();
constructor(controller: Controller<any, any, any>) {
super(controller);
}
protected init() {
this.controller.hears("video.play", "message_received", BotkitNLP.hear, this.handleVideoPlay);
}
public async handleVideoPlay(bot: Bot<any, any>, message: NLPMessage) {
let reply: string = "Not sure how to play this yet..."
let nlpParameters: any;
if (message.topIntent && message.topIntent.data && message.topIntent.data.parameters) {
nlpParameters = message.topIntent.data.parameters;
const videoInfo: VideoRequestModel = this.getVideoInformation(message.text, nlpParameters);
if (!videoInfo.medium || !videoInfo.service || !videoInfo.title) {
// Start conversation to retrieve missing information
await bot.startConversation(message,(err: Error, convo: Conversation<any>) => {
if (!videoInfo.title) {
convo.addQuestion("What did you want to watch?", (response,convo) => {
convo.next();
},{key: "videoTitle"},"default");
}
if (!videoInfo.service) {
convo.addQuestion("Which video service did you want to watch it on?", (response,convo) => {
convo.next();
},{key: "videoService"},"default");
}
if (!videoInfo.medium) {
convo.addQuestion("Where do you want to play it on?", (response,convo) => {
convo.next();
},{key: "videoMedium"},"default");
}
convo.on("end", (convo) => {
if (convo.status=="completed") {
if (!videoInfo.title) videoInfo.title = convo.extractResponse("videoTitle");
if (!videoInfo.service) videoInfo.service = convo.extractResponse("videoService");
if (!videoInfo.medium) videoInfo.medium = this.stringRemove(convo.extractResponse("videoMedium"), VJSkill.COMMON_STRINGS);
reply = this.vjServices.searchAndPlay(videoInfo);
}
});
convo.activate();
});
} else {
reply = this.vjServices.searchAndPlay(videoInfo);
}
}
bot.reply(message, reply, (err: Error) => {
console.error(err);
});
}
/**********************
* Helpers
*/
/**
* Retrieve video information from the spoken input.
*
* @param rawMessage the initial spoken message
* @param nlpParameters the parameters extracted by DialogFlow
*/
private getVideoInformation(rawMessage: string, nlpParameters: any): VideoRequestModel {
let videoInformation: VideoRequestModel = {
title: undefined,
service: undefined,
medium: undefined
};
// Find the Video Platform
if (nlpParameters.service && _.includes(VJSkill.PROJECTION_MEDIUMS, nlpParameters.service)) {
videoInformation.service = nlpParameters.service;
} else {
const platformsFound = MessageUtils.findMentions(rawMessage, VJSkill.VIDEO_PLATFORMS);
// Use the first found
if (platformsFound.length > 0) {
videoInformation.service = platformsFound[0];
}
}
// Find the Projection Medium. Use the first found
const projectionMediums = MessageUtils.findMentions(rawMessage, VJSkill.PROJECTION_MEDIUMS);
if (projectionMediums.length > 0) {
videoInformation.medium = projectionMediums[0];
}
// Find the video title
if (nlpParameters.movie) {
videoInformation.title = nlpParameters.movie.toLowerCase();
} else if (nlpParameters.video) {
videoInformation.title = nlpParameters.video.toLowerCase();
}
// Strip the platform and medium from the title to improve video search results
const toTrim: string[] = _.concat(VJSkill.COMMON_STRINGS, [videoInformation.service], [videoInformation.medium]);
videoInformation.title = this.stringRemove(videoInformation.title, toTrim);
console.log("Video title: " + videoInformation.title);
return videoInformation;
}
/**
* Remove specified strings from a string.
*
* @param srcStr the string to remove from.
* @param trimStrings the strings to remove.
*/
private stringRemove(srcStr: string, trimStrings: string[]): string {
trimStrings.forEach((trim) => {
srcStr = srcStr.replace(new RegExp(trim, "g"), "");
});
return srcStr.trim();
}
}
|
32240c780f1152fc2e4cfdbf418a6750a2fdc1a4
|
TypeScript
|
semagarcia/rxjs-t3chfest-reactividad
|
/01-async-datasources/async-rp-way.ts
| 2.671875
| 3
|
// T3chFest example
class UserAsync {
private backendUserSrv;
setName(name: string, cb: Function) {
const res = this.backendUserSrv.setUserName(name, cb);
cb(res);
}
setSurname(surname: string, cb: Function) {
const res = this.backendUserSrv.setUserSurname(surname, cb);
cb(res);
}
setAge(age: number, cb: Function) {
const res = this.backendUserSrv.setUserAge(age, cb);
cb(res);
}
}
|
152154a4ad8a57c843d959f35df49a96d3aa2e7c
|
TypeScript
|
DerrickF/giphyApp
|
/giphy-app/src/app/components/search/search.reducer.ts
| 2.90625
| 3
|
import * as SearchActions from './search.actions';
import { Search } from './search.model';
export type Action = SearchActions.All;
// Default state
const defaultState: Search = {
searchTerm: "",
loading: false,
searchResults: []
}
// Reducer
export function searchReducer(state: Search = defaultState, action: Action) {
switch (action.type) {
case SearchActions.SET_VALUE:
return { ...state, searchTerm: action.payload }
case SearchActions.GET_SEARCH_RESULTS:
return { ...state, loading: true };
case SearchActions.GET_SEARCH_RESULTS_SUCCESS:
return { ...state, searchResults: action.payload, loading: false };
case SearchActions.GET_SEARCH_RESULTS_FAIL:
return { ...state, ...action.payload, loading: false };
case SearchActions.TOGGLE_PLAY_ALL:
console.log('flipping all actives:', );
//loop through current results and set the active property
let results = [];
state.searchResults.forEach(function (item, index) {
let result = state.searchResults[index];
result.active = action.payload;
results.push(result);
});
//push results into new state obj
return { ...state, searchResults: results, loading: false };
default:
return state;
}
}
|
4edd90c60df7b3dc91fe5e8dfc2d524eefc847eb
|
TypeScript
|
windeko/trg-test
|
/car-service/src/car/index.ts
| 2.609375
| 3
|
import {ICar} from "./interfaces";
import {random} from "../helpers";
import {DriverModel} from "../driver/model";
import {Driver} from "../driver";
import {CarModel} from "./model";
export class Car {
private readonly car: ICar;
private constructor(car: ICar) {
this.car = car
}
public static async factory(): Promise<Car> {
const car: ICar = {
carID: (await Car.getRandom())._id,
latitude: random(-90, 90),
longitude: random(-90, 90),
speed: random(parseInt(process.env.MINSPEED), parseInt(process.env.MAXSPEED)),
userID: (await Driver.getRandom())._id
};
return new Car(car)
}
static async getRandom() {
const count = await CarModel.find({}).countDocuments();
const random = Math.floor(Math.random() * count);
return CarModel.findOne().skip(random)
}
getCar() {
return this.car
}
}
|
d650280742bf87a30702bdc426e4d16194ed0580
|
TypeScript
|
JhnFbre/InterfacesPrueba
|
/server/src/controllers/espolControllers.ts
| 2.59375
| 3
|
import { Request, Response } from 'express';
import pool from '../database'
class EspolControllers{
public async list (req:Request, res:Response){
const espol= await pool.query('select usuario.id_persona, usuario.identificacion, persona.cedula, persona.nombres, persona.apellidos from usuario inner join persona on usuario.id_persona=persona.id_persona');
res.json(espol);
console.log("leyendo");
}
public async getOne(req: Request, res: Response): Promise<any> {
const { id } = req.params;
const games = await pool.query('select usuario.identificacion, persona.cedula, persona.nombres, persona.apellidos from usuario inner join persona on usuario.id_persona=persona.id_persona WHERE persona.cedula = ?', [id]);
console.log(games.length);
if (games.length > 0) {
return res.json(games[0]);
}
res.status(404).json({ text: "La persona no existe" });
}
public async create(req: Request, res: Response): Promise<void> {
const result = await pool.query('INSERT INTO persona set ?', [req.body]);
res.json({ message: 'Person Saved' });
}
public async update (req:Request, res:Response): Promise<void>{
const { id } = req.params;
const oldGame = req.body;
await pool.query('UPDATE persona set ? WHERE id_persona = ?', [req.body, id]);
res.json({ message: "La persona fue actualizado" });
}
}
const espolControllers= new EspolControllers();
export default espolControllers;
//ecto, lo he hecho y funciona. ;) Por si ha alguien le puede servir: "npm i promise-mysql@3.3.2"
//getone por list, se puede filtrar
|
51178f71d5b1fe6c8869fc0184b0b0d3f961342d
|
TypeScript
|
riverfeya/lume
|
/tests/module.test.ts
| 2.609375
| 3
|
import { assertStrictEquals as equals } from "../deps/assert.ts";
import { getSite, testPage } from "./utils.ts";
Deno.test("build a site with js/ts modules", async () => {
const site = getSite({
test: true,
src: "module",
location: new URL("https://example.com/blog"),
});
await site.build();
testPage(site, "/simple", (page) => {
equals(page.document?.querySelectorAll("h1").length, 1);
equals(page.document?.querySelector("h1")?.innerText, page.data.title);
equals(
page.document?.querySelector(".home")?.getAttribute("href"),
"https://example.com/blog/",
);
equals(
page.document?.querySelector(".link-1")?.getAttribute("href"),
"/blog/",
);
equals(
page.document?.querySelector(".link-2")?.getAttribute("href"),
"/blog/simple-page-new-permalink.html",
);
});
testPage(site, "/multiple[0]", (page) => {
equals(page.data.url, "/multiple/1.html");
equals(page.data.tags?.[0], "multiple");
equals(page.document?.querySelector("title")?.innerText, "Page 1");
});
testPage(site, "/multiple[1]", (page) => {
equals(page.data.url, "/multiple/2.html");
equals(page.data.tags?.[0], "multiple");
equals(page.document?.querySelector("title")?.innerText, "Default title");
});
testPage(site, "/multiple[2]", (page) => {
equals(page.data.url, "/multiple/3.html");
equals(page.data.tags?.[0], "multiple");
equals(page.document?.querySelector("title")?.innerText, "Default title");
});
testPage(site, "/multiple-async[0]", (page) => {
equals(page.data.url, "/async/1/");
equals(page.dest.path, "/async/1/index");
equals(page.dest.ext, ".html");
equals(page.data.tags?.[0], "autogenerated");
equals(page.data.title, "Multiple page 1");
equals(page.document?.querySelector("title")?.innerText, page.data.title);
});
testPage(site, "/multiple-async[1]", (page) => {
equals(page.data.url, "/async/2/");
equals(page.dest.path, "/async/2/index");
equals(page.dest.ext, ".html");
equals(page.data.tags?.[0], "autogenerated");
equals(page.data.title, "Multiple page 2");
equals(page.document?.querySelector("title")?.innerText, page.data.title);
});
});
|
0f544a0aac8332f82869a9ad2898b2d69179f04c
|
TypeScript
|
freddybotteri/nestjs-IoC
|
/src/domain/vo/UserName.ts
| 3.25
| 3
|
import { InvalidArgument } from '../errors/InvalidArgument';
export class UserName {
readonly value: string;
constructor(value: string) {
this.value = value;
this.ensureLengthIsLessThan30Characters(value);
}
private ensureLengthIsLessThan30Characters(value: string): void {
if (value.length < 2) {
throw new InvalidArgument(`The User Name <${value}> has less than 2 characters`);
}
}
toString(): string {
return this.value;
}
}
|
36afd58f8b729fb67ad6515095e485cd5d19f65f
|
TypeScript
|
Mellisah-lisah/Quotes
|
/src/app/app.component.ts
| 2.578125
| 3
|
import { Component } from '@angular/core';
import { Quote } from './quote';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
quotes:Quote[] = [
new Quote(1, 'No human is limited', 'Eliud Kipchoge',new Date(2020,3,14)),
new Quote(2,'Great minds discuss ideas; average minds discuss events; small minds discuss people.','Eleanor Roosevelt',new Date(2019,6,9)),
new Quote(3,'Do one thing every day that scares you','Eleanor Roosevelt',new Date(2022,1,12)),
new Quote(4,'If you always do what interests you, at least one person is pleased','Katharine Hepburn',new Date(2019,0,18)),
new Quote(5,'The difference between winning and losing is most often not quitting','Damn Math',new Date(2019,2,14)),
new Quote(6,'Things work out best for those who make the best of how things work out','John Wooden',new Date(2030,3,14)),
];
}
|
a61a3f35de3eed856ddd38dfeaf7cd6eab303ebb
|
TypeScript
|
lgomezs/Angular
|
/appEmpleado/src/app/pipes/conversor.pipe.ts
| 2.65625
| 3
|
import {Pipe,PipeTransform} from '@angular/core';
@Pipe({name : 'conversor' })
export class ConversorPipe implements PipeTransform{
transform(value,por){
let valor1= parseInt(value);
let valor2 = parseInt(por);
let resultado = "La multiplicacion de " + valor1 + " por " + valor2 + " = " + (valor1 * valor2) ;
return resultado;
}
}
|
b7fe40c3e8240e77c7c116c718ab49a9d84d94bd
|
TypeScript
|
bela333/melon-bread-event
|
/src/utils/temporary-set.ts
| 3.390625
| 3
|
export class TemporarySet<T> implements Set<T> {
private items: Map<T, number> = new Map();
readonly [Symbol.toStringTag] = "TemporarySet";
constructor(public timeout: number) { }
private prune() {
for (const [item, time] of this.items.entries()) {
if (Date.now() > time + this.timeout) {
this.items.delete(item);
}
}
}
add(item: T): this {
this.items.set(item, Date.now())
return this;
}
clear() {
this.items.clear();
}
delete(item: T): boolean {
return this.items.delete(item);
}
has(item: T): boolean {
this.prune();
return this.items.has(item);
}
get size(): number {
this.prune();
return this.items.size;
}
*entries() {
this.prune();
for (const item of this.items.keys()) {
yield [item, item] as [T, T];
}
}
*keys() {
this.prune();
for (const item of this.items.keys()) {
yield item;
}
}
values() {
return this.keys();
}
forEach(callback: (value: T, key: T, set: this) => void) {
for (const item of this.items.keys()) {
callback(item, item, this);
}
}
[Symbol.iterator]() {
return this.keys();
}
}
|
8d21b3f29d4fc11030dd7f7c37c0f7a6e0663936
|
TypeScript
|
liuxinqiong/react-template
|
/src/utils/url.ts
| 2.609375
| 3
|
/* eslint-disable no-useless-escape */
import { parse } from 'qs';
export class UrlUtil {
static isUrl(path: string): boolean {
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
return reg.test(path);
}
static isRelativeProtocolUrl(url: string) {
const newUrl = `https:${url}`;
return UrlUtil.isUrl(newUrl);
}
static getFullRequestUrl(url: string) {
const { protocol, origin } = window.location;
if (UrlUtil.isUrl(url)) {
return url;
}
if (UrlUtil.isRelativeProtocolUrl(url)) {
return protocol + url;
}
return origin + url;
}
static getPageQuery() {
return parse(window.location.href.split('?')[1]);
}
}
|
bb2cc53a287926ac1cdabf1da5cb6afcacd0982e
|
TypeScript
|
Pseudonian/Ipsum
|
/src/utility.ts
| 3.40625
| 3
|
import assert from "assert"
import { COPYFILE_FICLONE_FORCE } from "constants"
/**
*
* @param n : A positive integer.
* @returns The sum of the first n integers, according to Gauss' expression.
*/
export const sumLinear = (n:number):number => {
return n * (n + 1) / 2
}
/**
*
* @param n : A positive integer
* @returns The sum of the first n squares, according to the generalized
* formula
*/
export const sumQuadratic = (n: number):number => {
return n * (n + 1) * (2*n + 1) / 6
}
/**
*
* @param n : A positive integer
* @returns The sum of the first n cubes, which is the square of sumLinear for n.
*/
export const sumCubic = (n: number):number => {
return Math.pow(sumLinear(n), 2)
}
/**
*
* @param n : A number to be formatted
* @param accuracy : The amount of decimal digits to be displayed
* @returns a string of the number formatted to specific conditions.
*/
export const format = (n: number, accuracy = 0):string => {
if (n < 0)
return "-" + format(-n, accuracy)
const truncatedNumber = Math.floor(n);
const decimalValue = n - truncatedNumber
const stringedInteger = truncatedNumber.toLocaleString();
const decimalPoint = (accuracy > 0 && n !== 0);
let returnDecimalRaw = Math.pow(10, accuracy) * decimalValue;
// Fix Float Point Error!
const tolerance = 1e-6;
if (Math.ceil(returnDecimalRaw) - returnDecimalRaw < tolerance)
returnDecimalRaw = Math.ceil(returnDecimalRaw);
// End of Fix Float Point Error!
let returnDecimalValue = (decimalPoint)? Math.floor(returnDecimalRaw).toString() : ""
if (returnDecimalValue !== "") {
while (returnDecimalValue.length < accuracy) {
returnDecimalValue = "0" + returnDecimalValue;
}
returnDecimalValue = "." + returnDecimalValue
}
return stringedInteger + returnDecimalValue
}
/**
* Assert that two numbers are equal within a given error tolerance.
* @param expected answer expected by the test
* @param actual answer actually returned by the module being tested
* @param delta actual is considered equal to expected if it's within +/- delta
* @param message optional message with extra information about this test case, to display when the assertion fails
*/
export function assertAlmostEqual(expected:number, actual:number, delta:number, message?:string):void {
assert(Math.abs(expected - actual) <= delta,
(message ? message + ", " : "") + "expected <" + expected.toFixed(3) + "> but got <" + actual.toFixed(3) + ">");
}
|
bcc3b3c28d0e6c871a3f8e6dc2d2bff2d39d7cf4
|
TypeScript
|
Ricebal/GroteZwarteDriehoek
|
/src/classes/fuzzy/FuzzySetRightShoulder.ts
| 2.953125
| 3
|
import { FuzzySet } from "./FuzzySet";
export class FuzzySetRightShoulder extends FuzzySet {
private _peakPoint: number;
private _leftOffset: number;
private _rightOffset: number;
constructor(peak: number, leftOffset: number, rightOffset: number) {
super(((peak + rightOffset) + peak) / 2);
this._peakPoint = peak;
this._leftOffset = leftOffset;
this._rightOffset = rightOffset;
}
public clone(): FuzzySetRightShoulder {
return new FuzzySetRightShoulder(this._peakPoint, this._leftOffset, this._rightOffset);
}
public calculateDOM(val: number): number {
if ((this._rightOffset === 0.0 && this._peakPoint === val) || (this._leftOffset === 0.0 && this._peakPoint === val)) {
return 1.0;
} else if ((val <= this._peakPoint) && (val > (this._peakPoint - this._leftOffset))) {
let grad: number = 1.0 / this._leftOffset;
return grad * (val - (this._peakPoint - this._leftOffset));
} else if ((val > this._peakPoint) && (val <= this._peakPoint + this._rightOffset)) {
return 1.0;
} else {
return 0.0;
}
}
}
|
ef8d08260232a9ff5353f0da7f6e9d57393a22f9
|
TypeScript
|
tatiane-lab/sistema-de-cadastro-digitrack
|
/cadastro-front/src/app/models/endereco.model.ts
| 2.546875
| 3
|
export class Endereco {
id: number;
cidade: string;
endereco: string;
bairro: string;
numero: string;
coordenadas: string;
constructor(cidade: string, endereco: string, numero: string, bairro:string, coordenadas: string){
this.bairro= bairro;
this.cidade= cidade;
this.numero = numero;
this.coordenadas = coordenadas;
this.endereco = endereco;
}
}
|
9972b4fd4534dedc329decdb18c67b7e203b122d
|
TypeScript
|
zkochan/packages
|
/safe-promise-defer/src/index.ts
| 2.875
| 3
|
import pShare from 'promise-share'
export interface SafePromiseDefer<T> {
(): Promise<T>
resolve: (v: T) => void
reject: (err: Error) => void
}
export default function safeDeferredPromise<T> (): SafePromiseDefer<T> {
let _resolve!: (v: T) => void
let _reject!: (err: Error) => void
const promiseFn = pShare(new Promise<T>((resolve, reject) => {
_resolve = resolve
_reject = reject
}))
return Object.assign(promiseFn, { resolve: _resolve, reject: _reject })
}
|
2903f935e426be753f2ae77001551ddb2407c20d
|
TypeScript
|
medusajs/medusa
|
/packages/medusa/src/api/middlewares/with-default-sales-channel.ts
| 2.53125
| 3
|
import { FlagRouter } from "@medusajs/utils"
import { NextFunction, Request, Response } from "express"
import SalesChannelFeatureFlag from "../../loaders/feature-flags/sales-channels"
import { SalesChannelService } from "../../services"
/**
* Middleware that includes the default sales channel on the request, if no sales channels present
* @param context Object of options
* @param context.attachChannelAsArray Whether to attach the default sales channel as an array or just a string
*/
export function withDefaultSalesChannel({
attachChannelAsArray,
}: {
attachChannelAsArray?: boolean
}): (req: Request, res: Response, next: NextFunction) => Promise<void> {
return async (req: Request, _, next: NextFunction) => {
const featureFlagRouter = req.scope.resolve(
"featureFlagRouter"
) as FlagRouter
if (
!featureFlagRouter.isFeatureEnabled(SalesChannelFeatureFlag.key) ||
req.query.sales_channel_id?.length ||
req.get("x-publishable-api-key")
) {
return next()
}
const salesChannelService: SalesChannelService = req.scope.resolve(
"salesChannelService"
)
try {
const defaultSalesChannel = await salesChannelService.retrieveDefault()
if (defaultSalesChannel?.id) {
req.query.sales_channel_id = attachChannelAsArray
? [defaultSalesChannel.id]
: defaultSalesChannel.id
}
} catch {
} finally {
next()
}
}
}
|
846574b2ecce5137c624ea5f16c8bc6513d6df2f
|
TypeScript
|
wujiangu/baijiang0.1
|
/src/game/Buff/buffs/AddProperty.ts
| 2.84375
| 3
|
/**
* 增加人物的基础属性
*
*/
class AddProperty extends BuffBase {
public constructor() {
super();
// this.buffInit();
}
/**初始化 */
public buffInit(options:any) {
super.buffInit();
this.options = options;
this.buffData.className = "AddProperty";
this.buffData.superpositionType = SuperpositionType.SuperpositionType_Overlay;
this.buffData.buffType = BuffType.BuffType_DeBuff;
this.buffData.disperseType = DisperseType.DisperseType_NoClear;
this.buffData.controlType = ControlType.NO;
this.buffData.postionType = PostionType.PostionType_Body;
this.buffData.duration = options.duration;
this.buffData.id = options.id;
this._extraValue = 0;
this._extraSpeed = 0;
if (this.buffData.duration > 0) {
let count = 50 * this.buffData.duration;
if (!this._tempTimer) this._tempTimer = new egret.Timer(20, count);
this._tempTimer.stop();
this._tempTimer.addEventListener(egret.TimerEvent.TIMER, this._onUpdate, this);
this._tempTimer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this._onComplete, this);
}
}
/**开始 */
public buffStart(target:any) {
this.AddEffect(target);
let value:number;
if (this.buffData.id >= 20) value = this.getTalentValue();
switch (this.buffData.id) {
//梨花落雨
case 9:
this.target.attr.crt += 20;
break;
//狂怒
case 20:
this.target.attr.wsp *= (1 - value/100);
this.target.setWSPDelay();
break;
//巫术
case 21:
this.target.attr.skd = Math.floor(this.target.attr.skd*(1+value/100))
break;
//先天资质
case 23:
let level:number = HeroData.getHeroData(GameData.curHero).lv;
this.target.attr.atk += (value * (level - 1));
break;
//智谋
case 32:
let cd:number = this.target.getSkillCd();
this.target.setSkillCd(Math.floor(cd*(1-value/100)));
break;
//漫游者
case 38:
let speed:number = this.target.getSpeed() * (1 + value/100);
this.target.setSpeed(Math.floor(speed));
break;
}
}
/**结束 */
public buffEnd() {
}
/**刷新数据 */
public update(target:any, callBack:Function = null) {
this._isReset = true;
if (this._extraValue == 0 && this._extraSpeed == 0){
let speed:number = this.target.getSpeed();
Common.log("增加属性buff")
//增加的属性(后续扩展可以增加任何属性)
this._extraSpeed = speed * 0.5;
this.target.setSpeed(speed + this._extraSpeed);
this._extraValue = Math.floor(this.target.attr.atk * 0.15);
this.target.attr.atk += this._extraValue;
}
if (this.buffData.duration > 0) this._tempTimer.start();
}
/**
* 定时过程刷新数据
*/
private _onUpdate(event:egret.TimerEvent) {
if (this._isReset) {
this._tempTimer.reset();
this._tempTimer.start();
this._isReset = false;
}
}
/**
* 定时完成
*/
private _onComplete(event:egret.TimerEvent) {
this._isReset = false;
Common.log("buff 结束");
//恢复原来数值(后续扩展)
let speed:number = this.target.getSpeed();
this.target.setSpeed(speed - this._extraSpeed);
this.target.attr.atk -= this._extraValue;
this._extraSpeed = 0;
this._extraValue = 0;
this._tempTimer.reset();
}
/**作用点 */
private position(target:any):void {
switch (this.buffData.postionType) {
case PostionType.PostionType_Foot:
target.x = 0;
target.y = 0;
break;
case PostionType.PostionType_Head:
target.x = 0;
target.y = -90;
break;
case PostionType.PostionType_Body:
target.x = 0;
target.y = 0;
break;
}
}
/**增加特效 */
public AddEffect(target:any) {
this.target = target;
}
/**显示特效 */
public ShowEffect() {
this.target.skillArmature.visible = true;
}
/**隐藏特效 */
public HideEffect() {
this.target.skillArmature.visible = false;
}
/**回收buff */
public recycleBuff() {
super.recycleBuff();
if (this.buffData.duration > 0) this._tempTimer.reset();
}
private target:any;
/**附加的攻击值 */
private _extraValue:number;
/**附加的移动速度值 */
private _extraSpeed:number;
private _extraBuff:UnableMove;
private _tempTimer:egret.Timer;
private _isReset:boolean;
}
|
73ce5a0df0710db406a1993af77e3bf9d7b6e817
|
TypeScript
|
bumer7721/shop
|
/src/app/first/first.component.ts
| 2.53125
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
name: string;
description: string;
price: number;
isAvailable: boolean;
category: Categories;
colors: Array<string>;
constructor() {
}
ngOnInit() {
this.name = 'First component';
this.description = 'Descriprion component';
this.price = 7;
this.isAvailable = false;
this.category = Categories.Hardware;
this.colors = ['Green', 'Red', 'Black'];
}
}
enum Categories {
Hardware,
Computers,
Accessories
}
|
cbe177df1a86995dd4423e054ca42f34912e74d1
|
TypeScript
|
suprithagowda-D/accelerated-news
|
/src/services/AuthService.ts
| 2.609375
| 3
|
import { formatHttpError } from '@http-utils/core';
import axios from 'axios';
import { Credentials, User, SignUpInput } from '../models';
import { Storage } from '../utils';
const TOKEN_KEY = 'accessToken';
const SIGN_IN_REDIRECT_KEY = 'signInRedirect';
const getAccessToken = () => {
return Storage.get(TOKEN_KEY);
};
const setAccessToken = (accessToken: string) => {
return Storage.set(TOKEN_KEY, accessToken);
};
const removeAccessToken = () => {
return Storage.remove(TOKEN_KEY);
};
const getSignInRedirectPath = () => {
return Storage.get(SIGN_IN_REDIRECT_KEY, '/');
};
const setSignInRedirectPath = (path: string) => {
return Storage.set(SIGN_IN_REDIRECT_KEY, path);
};
const removeSignInRedirectPath = () => {
return Storage.remove(SIGN_IN_REDIRECT_KEY);
};
const fetchUser = async (): Promise<User | undefined> => {
const token = Storage.get(TOKEN_KEY);
if (!token) return;
try {
const resp = await axios.get('/auth/me');
return resp.data as User;
} catch (e) {
throw new Error(formatHttpError(e));
}
};
const signIn = async (credentials: Credentials): Promise<User> => {
try {
const resp = await axios.post('/auth/signin', credentials);
const { accessToken, user } = resp.data as {
accessToken: string;
user: User;
};
setAccessToken(accessToken);
return user;
} catch (e) {
throw new Error(formatHttpError(e));
}
};
const signOut = async (): Promise<Boolean> => {
try {
const resp = await axios.post('/auth/signout');
removeAccessToken();
return resp.data as boolean;
} catch (e) {
throw new Error(formatHttpError(e));
}
};
const signUp = async (signUpInput: SignUpInput): Promise<User> => {
try {
const resp = await axios.post('/auth/signup', signUpInput);
const { accessToken, user } = resp.data as {
accessToken: string;
user: User;
};
setAccessToken(accessToken);
return user;
} catch (e) {
throw new Error(formatHttpError(e));
}
};
export const AuthService = {
getAccessToken,
setAccessToken,
removeAccessToken,
getSignInRedirectPath,
setSignInRedirectPath,
removeSignInRedirectPath,
fetchUser,
signIn,
signOut,
signUp,
};
|
ec77cef62fade9f481baf3bac85d28e83dfadc62
|
TypeScript
|
IfyNdu/united-states-africa
|
/packages/server/src/domain/video/add-tag.spec.ts
| 2.59375
| 3
|
import { mockLogger } from 'usa-utils';
import addTag from './add-tag';
import DB from '../../db';
const dbAddTagMock = jest.spyOn(DB.video, 'addTag')
jest.mock('uuid/v1', () => {
return () => 'mock-id';
});
const mockTag = [{
id: 'test video tag'
}]
dbAddTagMock.mockReturnValue(null);
const data = ['test video tag']
const logger = mockLogger.init()
describe('addTag', () => {
it('accepts an array of tags and calls Sequelize', async () => {
await addTag(data, logger)
expect(dbAddTagMock).toHaveBeenCalledTimes(1);
expect(dbAddTagMock).toHaveBeenCalledWith(mockTag);
});
it('should throw an error if the tags are not passed in as an array', async () => {
expect.assertions(1)
return addTag({ name: 'test-1' } as any, logger)
.catch(err => { expect(err).toEqual(expect.any(Error)) })
});
it('should throw an error if incorrect data is passed', async () => {
expect.assertions(1)
return addTag([565] as any, logger)
.catch(err => { expect(err).toEqual(expect.any(Error)) })
});
it('should throw an error if tag name isnt alphabetical', async () => {
expect.assertions(1)
return addTag(['invalid0-98'] as any, logger)
.catch(err => { expect(err).toEqual(expect.any(Error)) })
});
})
|
8673bddaf2a963ca37e3c11e4007cdf99ae13671
|
TypeScript
|
pillaiashwin/mern-stack-template
|
/mern-stack/user-service/src/models/UserJwt.ts
| 2.578125
| 3
|
import jwt from "jsonwebtoken";
import UserJwtInterface from "../interfaces/UserJwt";
class UserJwt implements UserJwtInterface {
id: string;
role: string;
constructor(bearerToken: string, secret: string) {
const data = jwt.verify(bearerToken, secret);
this.id = data._id;
this.role = data.role;
}
}
export default UserJwt;
|
8d3a3482cde56c5bac8e500d1639e7dd542a9926
|
TypeScript
|
mlepecki/Angular6App
|
/testTS/basicType.ts
| 2.515625
| 3
|
class BasicType {
name: string = 'Reksio';
age: number = 12;
tablica: string[] = ['Ala', 'kasia'];
dates: Array<Date> = [new Date(), new Date()];
pair: [string, number] = ['PN', 1];
xyz: any = '12';
}
|
744a519382b98dd29f145d66ce93f82537802956
|
TypeScript
|
Studiosity/realm-js
|
/integration-tests/tests/src/tests/iterators.ts
| 2.921875
| 3
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import { expect } from "chai";
import Realm from "realm";
import { DogSchema, IDog, IPerson, PersonSchema } from "../schemas/person-and-dogs";
describe("Iterating", () => {
let realm: Realm;
beforeEach(() => {
Realm.clearTestState();
});
beforeEach(() => {
// Add linkingObjects to the PersonAndDogs schema
const PersonWithDogsSchema = {
...PersonSchema,
properties: {
...PersonSchema.properties,
dogs: {
type: "linkingObjects",
objectType: "Dog",
property: "owner",
},
},
};
realm = new Realm({ schema: [DogSchema, PersonWithDogsSchema] });
realm.write(() => {
const alice = realm.create<IPerson>("Person", {
name: "Alice",
age: 16,
});
const bob = realm.create<IPerson>("Person", {
name: "Bob",
age: 42,
});
const charlie = realm.create<IPerson>("Person", {
name: "Charlie",
age: 62,
});
realm.create<IDog>("Dog", {
age: 1,
name: "Max",
owner: alice,
});
realm.create<IDog>("Dog", {
age: 3,
name: "Rex",
owner: alice,
});
realm.create<IDog>("Dog", {
age: 5,
name: "Bobby",
owner: bob,
});
// Make Bob and Charlie mutural frieds
bob.friends.push(charlie);
charlie.friends.push(bob);
});
});
it("returns an instance of Results", () => {
const results = realm.objects("Person");
expect(results).instanceOf(Realm.Results);
});
it("throws if object schema doesn't exist", () => {
expect(() => {
realm.objects("SomeOtherClass");
}).throws("Object type 'SomeOtherClass' not found in schema.");
});
type CollectionCallback = () => Realm.Collection<IPerson | IDog>;
function itCanIterate(getCollection: CollectionCallback, expectedNames: string[]) {
it("iterates using forEach", () => {
const collection = getCollection();
const names: string[] = [];
collection.forEach((person) => {
names.push(person.name);
});
expect(names).deep.equals(expectedNames);
});
it("iterates using map", () => {
const collection = getCollection();
const names = collection.map((person) => person.name);
expect(names).deep.equals(expectedNames);
});
it("iterates using indexed for-loop", () => {
const collection = getCollection();
const names: string[] = [];
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < collection.length; i++) {
const person = collection[i];
names.push(person.name);
}
expect(names).deep.equals(expectedNames);
});
it("iterates using for-in-loop", () => {
const collection = getCollection();
const names: string[] = [];
for (const i in collection) {
if (Object.prototype.hasOwnProperty.call(collection, i)) {
const person = collection[i];
names.push(person.name);
}
}
expect(names).deep.equals(expectedNames);
});
it("iterates using for-of-loop", () => {
const collection = getCollection();
const names: string[] = [];
// tslint:disable-next-line:prefer-for-of
for (const person of collection) {
names.push(person.name);
}
expect(names).deep.equals(expectedNames);
});
it("iterates using values for-of-loop", () => {
const collection = getCollection();
const names: string[] = [];
// tslint:disable-next-line:prefer-for-of
for (const person of collection.values()) {
names.push(person.name);
}
expect(names).deep.equals(expectedNames);
});
it("iterates using for-of-loop entries", () => {
const collection = getCollection();
const names: string[] = [];
for (const [, person] of collection.entries()) {
names.push(person.name);
}
expect(names).deep.equals(expectedNames);
});
}
describe("unfiltered results", () => {
itCanIterate(() => realm.objects<IPerson>("Person"), ["Alice", "Bob", "Charlie"]);
});
describe("filtered results", () => {
itCanIterate(() => realm.objects<IPerson>("Person").filtered("age > 60"), ["Charlie"]);
});
describe("linkingObjects collections", () => {
itCanIterate(() => {
const result = realm.objectForPrimaryKey<IPerson>("Person", "Alice");
if (!result) throw new Error("Object not found");
return result.dogs;
}, ["Max", "Rex"]);
});
describe("lists", () => {
itCanIterate(() => {
const result = realm.objectForPrimaryKey<IPerson>("Person", "Bob");
if (!result) throw new Error("Object not found");
return result.friends;
}, ["Charlie"]);
});
});
|
4a6e9ec9880431f6098cb5074c760db32db705ed
|
TypeScript
|
alirezashahali/politlling_political_polling
|
/issue/src/services/solutionsChecker.ts
| 3.03125
| 3
|
import { RequestValidationError, ArtificialValidationError,
ArtificialRequestValidationError } from '@politling_common/common';
import validator from 'validator'
// returns zero for no error and returns a number for number of solutions that does not have all
// of their requirments
export interface Solution{
title: string,
description: string,
references?: Array<string>,
// origin?: {type: ModelTypes, id: string}
}
export function solutionsChecker(listOfSolutions: Solution[]): Array<ArtificialValidationError>{
let listOfErrors: ArtificialValidationError[] = [];
// let error;
for (const i in listOfSolutions) {
listOfErrors = errorThrower(listOfSolutions[i].title, 'title', listOfErrors, true, Number(i));
listOfErrors = errorThrower(listOfSolutions[i].description, 'description', listOfErrors, true, Number(i));
if(listOfSolutions[i].references){
for(const j in listOfSolutions[i].references){
// required is true beacause if there is a member
// then it should be string(url or reference of a...)
// or other kind of text
listOfErrors = errorThrower(listOfSolutions[i].references![Number(j)], 'references', listOfErrors,
true, Number(j))
}
}
}
// TODO implement origin as well if it is to be handled in this route
return listOfErrors
}
export function ndFixer (num: number): string {
switch(num) {
case 0: {
return '1st'
break;
}
case 1: {
return '2nd';
break;
}
case 2: {
return '3rd';
break;
}
default: {
return num.toString() + 'th';
break;
}
}
}
// returns true when it includes error and false otherwise
const TextIncludeError = (innie: string | undefined, required: boolean) => {
// for now all are some how required
if(!innie){
return true;
}
return !validator.isAlpha
}
function errorThrower(inward: string | undefined, field: string,
listOfErrors: Array<ArtificialValidationError>,
required: boolean, index: number): ArtificialValidationError[]{
// console.log('errorThrowerConsole',inward, field, listOfErrors, required, index)
if(TextIncludeError(inward, required)){
let newError: ArtificialValidationError;
switch(field) {
case 'references': {
newError= {msg: 'The ' +
ndFixer(Number(index)) + ' reference is empty or is not acceptable', param: field};
break;
}
default: {
newError= {msg: field + ' of the ' +
ndFixer(Number(index)) + ' solution is empty or is not acceptable', param: field};
break;
}
}
return [...listOfErrors, newError]
}else{
return listOfErrors
}
}
export function referencesChecker( references : Array<string> ) : Array<ArtificialValidationError> {
let listOfErrors : Array<ArtificialValidationError> = [];
for(const i in references){
listOfErrors = errorThrower(references[Number(i)], 'references', listOfErrors, true, Number(i));
}
return listOfErrors
}
|
5dbd40a33891d4fcdca0edf41f533a2069197929
|
TypeScript
|
kubikowski/Rabbit
|
/src/main/angular/src/app/services/web-socket-subscription.model.ts
| 2.828125
| 3
|
import { SubscriptionLike } from 'rxjs';
/**
* Equivalent to Map<String, Subscription or MultiSubscription>
*/
export interface Subscriptions {
[x: string]: Subscription | MultiSubscription;
}
export class Subscription {
constructor(public connection: SubscriptionLike,
public callback: () => any) {
}
}
/**
* Equivalent to Map<String, Subscription>
*/
export class MultiSubscription {
[x: string]: Subscription;
constructor() {
}
}
|
6778d39bbdc7ddeda0b441cc95c683385fe1dec2
|
TypeScript
|
cane4044/fast-dna
|
/packages/fast-tooling-react/src/navigation/navigation-tree-item.props.ts
| 2.890625
| 3
|
import { NavigationDataType } from "./navigation.props";
export enum VerticalDragDirection {
up,
down,
center,
}
export interface NavigationTreeItemProps
extends NavigationTreeItemDragSourceCollectedProps,
NavigationTreeItemDropTargetCollectedProps {
/**
* The React children
*/
children?: React.ReactNode;
/**
* The class
*/
className: (dragging: boolean) => string;
/**
* The class for the content
*/
contentClassName: string;
/**
* The class for the expand trigger
*/
expandTriggerClassName: string;
/**
* A string representing the data location in lodash notation
*/
dataLocation: string;
/**
* The expanded state
*/
expanded: boolean;
/**
* The click handler for expanding an item
*/
handleClick: React.MouseEventHandler<HTMLElement>;
/**
* The click handler for selecting an item
*/
handleSelectionClick: React.MouseEventHandler<HTMLElement>;
/**
* The keyDown handler
*/
handleKeyDown: React.KeyboardEventHandler<HTMLElement>;
/**
* The handler for closing dragging items
*/
handleCloseDraggingItem: (dataLocation: string, type: NavigationDataType) => void;
/**
* The text used for the tree item
*/
text: string;
/**
* The type of data this tree item represents
*/
type: NavigationDataType;
/**
* The drag hover state
*/
dragHover: boolean;
/**
* The drag hover before state
*/
dragHoverBefore: boolean;
/**
* The drag hover after state
*/
dragHoverAfter: boolean;
/**
* The onChange callback for updating the data
*/
onChange: (
sourceDataLocation: string,
targetDataLocation: string,
type?: NavigationDataType,
direction?: VerticalDragDirection
) => void;
/**
* The hover callback for dragging
*/
onDragHover: (dataLocation: string, direction?: VerticalDragDirection) => void;
/**
* The class for hovering when dragging
*/
getContentDragHoverClassName: (
type: NavigationDataType,
direction?: VerticalDragDirection
) => string;
}
export interface NavigationTreeItemDragSourceCollectedProps {
connectDragSource?: (el: JSX.Element) => JSX.Element;
isDragging?: boolean;
}
export interface NavigationTreeItemDropTargetCollectedProps {
connectDropTarget?: (el: JSX.Element) => JSX.Element;
canDrop?: boolean;
isOver?: boolean;
}
export interface NavigationTreeItemDragObject {
dataLocation: string;
}
|