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
|
|---|---|---|---|---|---|---|
672e754dd27ce40dae61edf7b0f1787d0d3daf2d
|
TypeScript
|
chickenLeobar/gymapp
|
/manzana/src/modules/comments/entitites/Interaction.ts
| 2.6875
| 3
|
import { User } from "./../../../entity/User";
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { ObjectType, Field, Int, ID } from "type-graphql";
import { InteractionType } from "../types/model";
import { Comment } from "../entitites/Comment";
/**
* Interactioin withm comments : LIKE - OTHERS
*/
@Entity()
@ObjectType()
export class Interaction extends BaseEntity {
@PrimaryGeneratedColumn()
@Field((type) => ID)
id!: number;
@CreateDateColumn()
@Field((type) => Date)
createInteraction!: Date;
@Column("varchar", { length: 120 })
@Field((type) => String)
typeInteraction!: InteractionType;
@ManyToOne((type) => User)
@JoinColumn({ name: "id_user" })
user!: Promise<User>;
@ManyToOne((type) => Comment)
@JoinColumn({ name: "id_comment" })
comment!: Comment;
// ids connectiom
@Column()
@Field((type) => Int)
id_user!: number;
@Column()
@Field((type) => String)
id_comment!: string;
}
|
5cd7f10c82042dc4935a9a03fbf9d84a6ca269b1
|
TypeScript
|
33mhz/beta
|
/__tests__/components/Avatar.spec.ts
| 2.5625
| 3
|
import { shallowMount } from '@vue/test-utils'
import Avatar from '~/components/atoms/Avatar.vue'
describe('Avatar', () => {
let opts: {
propsData: {
avatar:
| string
| {
link: string
}
size?: number
enablePlaceholder?: boolean
maxSize?: number | string
}
}
beforeEach(() => {
opts = {
propsData: {
avatar: 'foo.png',
},
}
})
describe('avatar props', () => {
test('pass string', () => {
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img[src="foo.png"]').exists()).toBe(true)
})
test('pass object', () => {
opts.propsData.avatar = {
link: 'foo.png',
}
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img[src="foo.png"]').exists()).toBe(true)
})
test('When pass the username, show icon using API', () => {
const wrapper = shallowMount(Avatar, {
propsData: {
avatar: '@test_user',
},
})
expect(wrapper.find('img').attributes().src).toBe(
'https://api.pnut.io/v0/users/@test_user/avatar'
)
})
})
test('Add w param when max-size is larger than 0', () => {
opts.propsData.maxSize = 16
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img').attributes().src).toContain('?w=16')
opts.propsData.maxSize = '24'
const wrapper2 = shallowMount(Avatar, opts)
expect(wrapper2.find('img').attributes().src).toContain('?w=24')
})
test('size attr equals width and height', async () => {
opts.propsData.size = 32
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.attributes().width).toBe('32')
expect(wrapper.attributes().height).toBe('32')
wrapper.setProps({
size: 64,
})
await wrapper.vm.$nextTick()
expect(wrapper.attributes().width).toBe('64')
expect(wrapper.attributes().height).toBe('64')
})
test('Default shape is rounded-circle', () => {
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img').classes()).toContain('rounded-circle')
})
test('Be square icon when square_avatars equals `true`', async () => {
localStorage.setItem('square_avatars', 'true')
const wrapper = shallowMount(Avatar, opts)
await wrapper.vm.$nextTick()
expect(wrapper.find('img').classes()).not.toContain('rounded-circle')
})
test('set srcset', () => {
opts.propsData.size = 32
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.attributes().srcset).toBe('foo.png?w=64 2x')
})
test('Show placeholder svg when avatar link is empty', () => {
opts.propsData.avatar = {
link: '',
}
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img').attributes().src).toContain('')
})
test('Show placeholder svg when enablePlaceholder prop is true', () => {
opts.propsData.enablePlaceholder = true
const wrapper = shallowMount(Avatar, opts)
expect(wrapper.find('img').attributes().src).toContain('')
})
})
|
13ccbd5364ab46d0ae658be57356665f17940f5a
|
TypeScript
|
ColquePaxi/nestJS
|
/src/modules/users/dto/user.dto.ts
| 2.59375
| 3
|
enum Gender {
MALE = 'male',
FEMALE = 'female',
}
export class UserDto {
readonly name: string;
readonly email: string;
readonly password: string;
readonly gender: Gender;
}
|
2a72a4affab4c70039a55f98a27fe34e81befee6
|
TypeScript
|
amacz13/4A-IPS-24hApp
|
/src/logic/game-flow.ts
| 2.640625
| 3
|
import {Injectable} from '@angular/core';
import 'rxjs/add/operator/map';
import {Question} from "./question";
import {HttpClient} from "@angular/common/http";
import {Quiz} from "./quiz";
@Injectable()
export class GameFlow {
quizInfo: Quiz;
questionsDone: Array<number>;
constructor(public http: HttpClient) {
/* get json quizz */
this.http.get('../assets/quiz/ComputerScienceHistory.json').map(res => res as Quiz).subscribe(data => {
this.quizInfo = data;
});
}
start() {
this.questionsDone = new Array<number>();
var randomIndex = Math.floor(Math.random() * this.quizInfo.questions.length);
this.questionsDone.push(randomIndex);
return this.quizInfo.questions[randomIndex];
}
next() {
var randomIndex;
do {
randomIndex = Math.floor(Math.random() * this.quizInfo.questions.length);
} while (this.questionsDone.indexOf(randomIndex) != -1);
this.questionsDone.push(randomIndex);
if (this.questionsDone.length >= 11) {
return 0;
} else {
return this.quizInfo.questions[randomIndex];
}
}
}
|
20c2a792bc7db5ff19125e9076e277760b5a6445
|
TypeScript
|
MattAgn/react-native-testing-library
|
/src/__tests__/config.test.ts
| 2.546875
| 3
|
import { getConfig, configure, resetToDefaults } from '../config';
beforeEach(() => {
resetToDefaults();
});
test('getConfig() returns existing configuration', () => {
expect(getConfig().asyncUtilTimeout).toEqual(1000);
});
test('configure() overrides existing config values', () => {
configure({ asyncUtilTimeout: 5000 });
configure({ defaultDebugOptions: { message: 'debug message' } });
expect(getConfig()).toEqual({
asyncUtilTimeout: 5000,
defaultDebugOptions: { message: 'debug message' },
defaultHidden: true,
});
});
test('resetToDefaults() resets config to defaults', () => {
configure({ asyncUtilTimeout: 5000 });
expect(getConfig().asyncUtilTimeout).toEqual(5000);
resetToDefaults();
expect(getConfig().asyncUtilTimeout).toEqual(1000);
});
|
9738836b624c64c2da1a9687ecfc08ab62bb8ebb
|
TypeScript
|
AlexShan2008/lerna-repo
|
/packages/object-helpers/src/object-helpers.ts
| 2.8125
| 3
|
export class ObjectHelpers {
// TODO
public static getKeys(obj) {
return Object.keys(obj);
}
public static getValues(obj) {
return Object.values(obj);
}
}
|
51761e15bab633d1da2f88a2808f8002baafbe11
|
TypeScript
|
csiszaralex/Lotto
|
/src/Content.ts
| 2.515625
| 3
|
import fs from "fs";
import http from "http";
import url from "url";
import Megoldas from "./Megoldas";
export default class Content {
public content(req: http.IncomingMessage, res: http.ServerResponse): void {
// favicon.ico kérés kiszolgálása:
if (req.url === "/favicon.ico") {
res.writeHead(200, { "Content-Type": "image/x-icon" });
fs.createReadStream("favicon.ico").pipe(res);
return;
}
// Weboldal inicializálása + head rész:
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.write("<!DOCTYPE html>");
res.write("<html lang='hu'>");
res.write("<head>");
res.write('<meta charset="UTF-8" />');
res.write("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
res.write("<title>Lottó</title>");
res.write(
'<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous">'
);
res.write(
'<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/js/bootstrap.bundle.min.js" integrity="sha384-BOsAfwzjNJHrJ8cZidOg56tcQWfp6y72vEJ8xQ9w6Quywb24iOsW913URv1IS4GD" crossorigin="anonymous"></script>'
);
res.write("</head>");
res.write('<body><div class="container-fluid m-3"><form>');
const params = url.parse(req.url as string, true).query;
// Kezd a kódolást innen -->
const div: string = '<div class="row align-items-center mb-3">';
const col4: string = '<div class="col-12 col-md-4">';
let Megold: Megoldas = new Megoldas("lottosz.dat");
//1. feladat
let be1: string = params.be1 as string;
if (!be1) be1 = "";
res.write(div);
res.write(col4);
res.write('<label for="fel1" class="col-form-label">1. feladat: Kérem az 52. hét lottó számait: </label></div>');
res.write(col4);
res.write(
`<input type='text' id="fel1" class="form-control" name='be1' value='${be1}' onChange='this.form.submit();' pattern='/^[0-9]+[ ][0-9]+[ ][0-9]+[ ][0-9]+[ ][0-9]+$/'></div>`
);
res.write(col4);
res.write('<span class="form-text">5 szám, szóközzel elválasztva 1-90-ig</span></div></div>');
//2. feladat
let szamok52: number[] = [];
if (be1.split(" ").length == 5) be1.split(" ").forEach(x => szamok52.push(parseInt(x)));
szamok52.sort((a, b) => a - b);
Megold.add = szamok52;
res.write(div);
res.write(col4+'2. feladat: Rendezett számok:</div>');
res.write(col4+`${szamok52.join(" ")}</div></div>`);
//3. feladat
let be3Het: number = parseInt(params.be3 as string);
if (isNaN(be3Het) || be3Het > 52 || be3Het < 1) be3Het = 1;
res.write(div);
res.write(col4);
res.write('<label for="fel3" class="col-form-label">3. feladat: Kérem egy hét sorszámát:</label></div>');
res.write(col4);
res.write(`<input type="text" id="fel3" class="form-control" name="be3" value="${be3Het}" onchange="this.form.submit();" /></div>`);
res.write(col4);
res.write('<span class="form-text">Egy hét száma 1-52-ig</span></div></div>');
//4. feladat
res.write(div);
res.write(`${col4}4. feladat: A(z) ${be3Het}. heti nyerőszámok:</div>`);
res.write(`${col4}${Megold.xHetiNyeroszamok(be3Het)}</div></div>`);
//5. feladat
res.write(div);
res.write(`<div class="col-12">5. feladat: ${Megold.voltENemKihzottSzam ? "Volt" : "Nem volt"} nem kihúzott szám a vizsgált időszakban.</div></div>`);
//6. feladat
res.write(div);
res.write(col4+'6. feladat: Páratlan számok a húzásokban:</div>');
res.write(`${col4}${Megold.paratlanCount} db</div></div>`);
//7. feladat
Megold.filebaIr();
//8. feladat
res.write(`<div class="row align-items-center mb-1">${col4}8. feladat: Lottószámok:</div></div>`);
res.write(`<div class="row mb-1">${col4}</div>${col4}`);
Megold.kihuzottSzamokStat.forEach((x, i) => {
res.write(` ${x}`);
if (i % 15 === 14) {
res.write("</div></div>");
if (i != 89) res.write(`<div class="row mb-1">${col4}</div>${col4}`);
}
});
//9. feladat
res.write(div);
res.write(col4+'9. feladat: Ki nem húzott prímek:</div>');
res.write(`${col4}${Megold.kiNemHuzottPrimek.join(", ")} db</div></div>`);
//GIT
res.write('<div class="row align-items-center mb-3 mt-5">');
res.write('<div class="col-12 col-sm-4"><a href="https://github.com/csiszaralex/Lotto"><button type="button" class="btn btn-info">GitHub</button></a></div>');
//Filek
let filek: string[] = ["lottosz.dat", "lotto52.ki"];
filek.forEach(x => {
res.write(`<div class="col-12 col-sm-4 mt-2 mt-0-sm">
<button type="button" class="btn btn-outline-info" data-toggle="modal" data-target="#${x.split(".")[0]}">${x}</button>
</div>`);
});
res.write("</div>");
filek.forEach(x => {
res.write(`<div class="modal fade" id="${x.split(".")[0]}" tabindex="-1">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">${x}</h5>
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">`);
res.write(`<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Lottószámok</th>
</tr>
</thead><tbody>`);
fs.readFileSync(x)
.toString()
.split("\n")
.forEach((y, i) => {
res.write(` <tr>
<th scope="row">${i + 1}</th>
<td>${y}</td>
</tr>`);
});
res.write(`</tbody></table></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Bezárás</button>
</div>
</div>
</div>
</div>`);
});
// <---- Fejezd be a kódolást
res.write("</pre></form>");
res.write("</body></html>");
res.end();
}
}
|
f58ba65f43066fdb1fdb1f33263be9e56199eaae
|
TypeScript
|
Chris3y/carbon
|
/src/components/flat-table/flat-table-header/flat-table-header.d.ts
| 2.671875
| 3
|
import * as React from "react";
import { PaddingProps } from "styled-system";
import { TableBorderSize } from "..";
export interface FlatTableHeaderProps extends PaddingProps {
/** Content alignment */
align?: "left" | "center" | "right";
/** If true sets alternative background color */
alternativeBgColor?: boolean;
children?: React.ReactNode | string;
/** Number of columns that a header cell should span */
colspan?: number | string;
/** Number of rows that a header cell should span */
rowspan?: number | string;
/** Sets a custom vertical right border */
verticalBorder?: TableBorderSize;
/** Sets the color of the right border */
verticalBorderColor?: string;
/** Column width, pass a number to set a fixed width in pixels */
width?: number;
}
declare function FlatTableHeader(props: FlatTableHeaderProps): JSX.Element;
export default FlatTableHeader;
|
71a9e306e3d08a9d4cc5d82e09987a5db14bc2c2
|
TypeScript
|
vijaysinghkadam/algo-viz
|
/runners/js/builtins/tests/btree.test.ts
| 2.953125
| 3
|
import 'mocha'
import expect from 'expect'
import instantiateViz from '../src';
const Viz = instantiateViz()
describe('Binary Tree', () => {
describe('create', () => {
it('breadth', () => {
const elems = [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
const btree = Viz.BTree.create(elems, 'inOrder')
const array: any[] = []
btree.traverse((val) => array.push(val), 'breadthFirst')
expect(array).toEqual(elems)
})
it('binary', () => {
const elems = [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
const btree = Viz.BTree.create(elems, 'binary')
const array: any[] = []
btree.traverse((val) => array.push(val), 'inOrder')
expect(array).toEqual(elems)
})
})
})
|
536051083245fcd1c8e95a23d6cbf7ab5039c1bf
|
TypeScript
|
dsasu1/prahsApp-Customers
|
/src/app/customers/stores/customer.reducer.ts
| 2.53125
| 3
|
import { createReducer, on } from '@ngrx/store';
import { Customer } from '../models/customer.model';
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { customerActionTypes, customersLoaded } from './customer.action';
export interface CustomerState extends EntityState<Customer> {
customersLoaded: boolean;
}
export const adapter: EntityAdapter<Customer> = createEntityAdapter<Customer>();
export const initialState = adapter.getInitialState({
customersLoaded: false,
});
export const customerReducer = createReducer(
initialState,
on(customerActionTypes.customersLoaded, (state, action) => {
return adapter.addMany(action.customers, {
...state,
customersLoaded: true,
});
}),
on(customerActionTypes.createCustomer, (state, action) => {
return adapter.addOne(action.customer, state);
}),
on(customerActionTypes.deleteCustomer, (state, action) => {
return adapter.removeOne(action.customerId, state);
}),
on(customerActionTypes.updateCustomer, (state, action) => {
return adapter.updateOne(action.update, state);
})
);
export const { selectAll, selectIds } = adapter.getSelectors();
/*
const customerReducer = createReducer(
initialState,
on(customerActions.add, state => ({ ...state, home: state.home + 1 })),
on(customerActions.deleteById, state => ({ ...state, away: state.away + 1 })),
on(customerActions.getAll, state => (state.)),
on(customerActions.getById, (state, { game }) => ({ home: game.home, away: game.away })),
on(customerActions.update, (state, { game }) => ({ home: game.home, away: game.away }))
);
export function reducer(state: State | undefined, action: Action) {
return scoreboardReducer(state, action);
} */
|
409e06933d0a7c0f7d18dc1aa80972cc2024d0ac
|
TypeScript
|
matudelatower/evenprom-ionic
|
/src/directives/comment-text.ts
| 2.546875
| 3
|
import { Component, Input } from '@angular/core';
@Component({
selector: 'comment-text',
template: '<p [ngClass]="clase" (click)="expandedText();">{{text}}</p>',
})
export class CommentText {
@Input() text: string ;
expanded = false;
clase = 'white-space-nowrap';
constructor() {
}
// ngOnInit() {
// this.empersa =
// }
expandedText (){
this.expanded = !this.expanded;
if (this.expanded){
this.clase = 'white-space-initial';
}else{
this.clase = 'white-space-nowrap';
}
}
}
|
1f2231b3cd84a0e87e8da3154f89749515ec37df
|
TypeScript
|
johngrantuk/sor-test
|
/src/utils/bignumber.ts
| 2.65625
| 3
|
import { BigNumber } from 'bignumber.js';
BigNumber.config({
EXPONENTIAL_AT: [-100, 100],
ROUNDING_MODE: 1,
DECIMAL_PLACES: 18,
});
export { BigNumber };
export function bnum(val: string | number | BigNumber): BigNumber {
return new BigNumber(val.toString());
}
export function scale(input: BigNumber, decimalPlaces: number): BigNumber {
const scalePow = new BigNumber(decimalPlaces.toString());
const scaleMul = new BigNumber(10).pow(scalePow);
return input.times(scaleMul);
}
|
b7657ca21ce956b510af8107e95ce3085492a009
|
TypeScript
|
clownShewz/Pomodoro
|
/src/app/task/models/task.ts
| 3.359375
| 3
|
export class task{
taskId : number;
taskName :string;
taskStartTime : any;
taskEndTime : any;
timeSpent : any;
completed : boolean;
constructor(name:string){
this.taskName = name;
this.completed = false;
this.setTaskTime('START');
}
setTaskTime(type : string){
if(type.toUpperCase() === "START"){
this.taskStartTime = new Date();
}else if (type.toUpperCase() === "END"){
this.taskEndTime = new Date();
}else{
alert('This is not a good state to be in right now');
}
}
setTimeSpent(){
this.setTaskTime('END');
let timeDiff = Math.abs(this.taskEndTime - this.taskStartTime);
this.timeSpent = this.formatTime(Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)));
}
getTimeSpent(){
return this.timeSpent;
}
formatTime(value:number){
if(value >= 10){
return value;
} else {
return "0" + value;
}
}
}
|
dd727de36c38b4b5f2459ca6db03466c6271228d
|
TypeScript
|
kimkanu/github-readme-solvedac
|
/src/types/index.ts
| 2.90625
| 3
|
interface Organization {
organizationId: number;
name: string;
type: 'community' | 'university' | 'company' | 'high_school';
rating: number;
userCount: number;
voteCount: number;
solvedCount: number;
color: string;
}
interface Badge {
badgeId: string;
badgeImageUrl: string;
displayName: string;
displayDescription: string;
}
interface Background {
backgroundId: string;
backgroundImageUrl: string;
author: string;
authorUrl: string;
displayName: string;
displayDescription: string;
}
export interface UserInformation {
handle: string;
bio: string;
organizations: Organization[];
badge?: Badge;
background: Background;
profileImageUrl: string;
solvedCount: number;
voteCount: number;
exp: number;
tier: number;
rating: number;
ratingByProblemSum: number;
ratingByClass: number;
ratingBySolvedCount: number;
ratingByVoteCount: number;
class: number;
classDecoration: 'none' | 'silver' | 'gold';
rivalCount: number;
reverseRivalCount: number;
maxStreak: number;
rank: number;
isRival?: boolean;
isReverseRival?: boolean;
}
export type TierRank =
| 'Unrated'
| 'Bronze'
| 'Silver'
| 'Gold'
| 'Platinum'
| 'Diamond'
| 'Ruby'
| 'Master';
export type TierDivision = 'I' | 'II' | 'III' | 'IV' | 'V';
|
3fee2168957091851dbed2914bd6de4c909a676e
|
TypeScript
|
AlexanderDLe/TypeScript_DataStructuresAndAlgorithms
|
/src/TreeDFS/PathSum3.ts
| 3.84375
| 4
|
/**
* 437. Path Sum 3
*
* targetSum = 8
*
* 2 > 10 > 3 > 5 > 4
*
* 2 > 12 > 15 > 20 > 24
*
* 2: 1 ^-- In this example, we should know there is a valid path (3 + 5 = 8)
* 12: 1 At value 20, a valid path sum exists if there exists on the outerpath,
* 15: 1 a sum of 20 - target.
* 20: 1
* So we check if a path exists. 20 - 8 = 12. We have encountered 12 before!
* So that previous path + target sum means we should be able to arrive at current.
*/
import { TreeNode } from '../DataStructures/TreeClass';;
type Node = TreeNode<number> | null;
const pathOfMaximumSum = (root: Node, targetSum: number): number => {
let map: any = {0:1};
let result = 0;
const DFS = (n:Node, sum:number) => {
if (!n) return;
let currSum = sum + n.val;
let desiredOuterSum = currSum - targetSum;
if (map[desiredOuterSum]) result += map[desiredOuterSum];
map[currSum] = (map[currSum] || 0) + 1;
DFS(n.left, currSum);
DFS(n.right, currSum);
map[currSum]--;
}
DFS(root, 0);
return result;
}
export default () => {
const t1 = new TreeNode(10);
t1.left = new TreeNode(5);
t1.right = new TreeNode(-3);
t1.right.right = new TreeNode(11);
t1.left.left = new TreeNode(3);
t1.left.right = new TreeNode(2);
t1.left.left.left = new TreeNode(3);
t1.left.left.right = new TreeNode(-2);
t1.left.right.right = new TreeNode(1);
console.log(pathOfMaximumSum(t1, 8))
console.log(pathOfMaximumSum(t1, 18))
console.log(pathOfMaximumSum(t1, 21))
console.log(pathOfMaximumSum(t1, 3))
};
|
43a3e59d19e887f80a312139895df4d7e5311afe
|
TypeScript
|
LeoYulinLi/match-making
|
/src/app.ts
| 2.84375
| 3
|
import * as io from "socket.io";
import mongoose from "mongoose";
import keys from "./keys/keys";
import User from "./models/User";
const server = io.listen(process.env.PORT || 3000)
if (keys.mongoURI) {
mongoose
.connect(keys.mongoURI, { useNewUrlParser: true })
.then(() => console.log("Connected to MongoDB successfully"))
.catch(err => console.log(err));
} else {
console.error("No mongo URL was found")
}
// const user = new User({
// username: "hi",
// password: "asdf",
// apiKey: "asdf"
// })
//
// user.save()
server.use((async (socket, next) => {
const apiKey = socket.handshake.query.apiKey
if (apiKey) {
const user = await User.findOne({ apiKey })
if (user) {
next()
}
}
next(new Error('authentication error'))
}))
interface Player {
id: string
level: number
}
interface Config {
threshold: number
}
server.on("connection", (socket) => {
let players: Player[] = []
let config: Config = {
threshold: 0.2
}
function matchPlayer(newPlayer: Player) {
console.log(`enqueued player with id ${ newPlayer.id } at level ${ newPlayer.level }`)
const matchingPlayerIndex = players.findIndex((player) => {
return player.level - config.threshold < newPlayer.level && player.level + config.threshold > newPlayer.level
})
if (matchingPlayerIndex != -1) {
socket.emit("match", [newPlayer, players[matchingPlayerIndex]])
console.log(`matched player ${ newPlayer.id } and ${ players[matchingPlayerIndex].id }`)
delete players[matchingPlayerIndex]
} else {
players.push(newPlayer)
}
}
socket.on("enqueue", matchPlayer)
socket.on("dequeue", (player: Player) => {
delete players[players.findIndex(it => it.id === player.id)]
})
socket.on("config", (newConfig: Config) => {
config = newConfig
const playersCopy = [...players]
players = []
playersCopy.forEach(player => matchPlayer(player))
})
})
|
3cebf35f677934982b980932f4836c5ae105a01d
|
TypeScript
|
RedBlazerFlame/hertzsprung-russell-diagram-WS22-exercise
|
/scripts/constants.ts
| 3.0625
| 3
|
import { RGBColor, SpectralLetterType, SpectralStringType, uint8 } from "./types";
// Returns an RGB color (copied and pasted from methods.ts to prevent a Reference Error from occuring)
const rgb = (r: uint8, g: uint8, b: uint8): RGBColor => ({
r: r,
g: g,
b: b
});
// Maps a spectral letter type to a number
export const LETTER_TYPE_TO_NUMERAL_MAP: Map<SpectralLetterType, number> = new Map(
[
["O", 0],
["B", 1],
["A", 2],
["F", 3],
["G", 4],
["K", 5],
["M", 6]
]
);
// Contains the maximum and minimum temperatures for each spectral type
export const TEMP_KEY_POINTS = [50000, 28000, 10000, 7500, 6000, 4900, 3500, 2000];
// Contains the colors of each spectral type (not including subtypes)
export const COLOR_KEY_POINTS = [rgb(101, 110, 251), rgb(140, 150, 255), rgb(202, 205, 255), rgb(255, 255, 255), rgb(255, 245, 104), rgb(255, 170, 81), rgb(254, 99, 68), rgb(254, 99, 68)];
// The sun's temperature in Kelvin
export const SUN_TEMPERATURE = 5823;
// Contains the luminosities of each spectral type (for main sequence stars)
export const LUMINOSITY_KEY_POINTS = [
[800000, 90000],
[52000, 95],
[55, 8],
[6.5, 2],
[1.5, 0.66],
[0.42, 0.1],
[0.08, 0.001]
];
// All possible spectral string types
export const SPECTRAL_STRING_VALUES: SpectralStringType[] = ["O0","O1","O2","O3","O4","O5","O6","O7","O8","O9","B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","G0","G1","G2","G3","G4","G5","G6","G7","G8","G9","K0","K1","K2","K3","K4","K5","K6","K7","K8","K9","M0","M1","M2","M3","M4","M5","M6","M7","M8","M9"];
|
4387b0be65d4f14f0d1f004d624ae112ab054499
|
TypeScript
|
Pedroh1510/encurtador-url
|
/src/repositories/implementations/TypeOrmUrlRepository.ts
| 2.546875
| 3
|
import { getConnection } from 'typeorm'
import { Urls } from './../../entities/implementations/TypeOrmUrl'
import { Url } from './../../entities/Url'
import { IUrlRepository } from './../IUrlRepository'
export class TypeOrmUrlRepository implements IUrlRepository {
async findUrl (smallUrl:string):Promise<Url> {
const connection = await getConnection()
const data = await connection.getRepository(Urls).findOne({ smallUrl })
return data
}
async save (data:Url):Promise<void> {
const connection = await getConnection()
const url = new Urls()
Object.assign(url, data)
await connection.manager.save(url)
}
}
|
744c31cf16300eb73ca86d334f355c7d8426f3f0
|
TypeScript
|
Basuchi/angualr
|
/basics.ts
| 3.765625
| 4
|
function test(){
var xx:number = 100;
var str:string = "ABC";
var b:boolean=false;
var x:any=123.4;
console.info(typeof(xx));
console.info(typeof(str));
console.info(typeof(b));
console.info(typeof(x));
}
//function with arguments
function display(aa:number,bb:number){
//return (x+y);
console.info(aa+bb);
}
//console.info(print(100,200));
test();
display(1,2);
|
e312659693819871609d7f5fbeabd40db9f77a12
|
TypeScript
|
tabithagabeau/PRSAngular
|
/src/app/model/purchaserequest.ts
| 2.546875
| 3
|
import { User } from './user';
export class PurchaseRequest {
Id: number;
User: User;
UserName: string;
Description: string;
Justification: string;
DateNeeded: Date;
DeliveryMode: string;
Status: string;
Total: number;
SubmittedDate: Date;
ReasonForRejection: string;
constructor( Id: number=0, user: User = null, dsc: string = '', jst: string = '', dneeded: Date = null, dlvmode: string = '', status: string='', total: number = 0, dsubmitted: Date = null, rfrejection: string=''){
this.Id=Id;
this.User= user;
this.Description = dsc;
this.Justification = jst;
this.DateNeeded = dneeded;
this.DeliveryMode = dlvmode;
this.Status = status;
this.Total=total;
this.SubmittedDate=dsubmitted;
this.ReasonForRejection=rfrejection;
}
about(): string{
return `PurchaseRequest: id=${this.Id}, user=${this.User}, description=${this.Description}, justification=${this.Justification}, dateNeeded=${this.DateNeeded}, deliveryMode=${this.DeliveryMode}, status=${this.Status}, total=${this.Total}, submittedDate=${this.SubmittedDate}, reasonForRejection=${this.ReasonForRejection}`}
}
|
645d2aa3a5317f1a6141e2034992ff4b3ba89a26
|
TypeScript
|
kritzware/monzo
|
/src/http.ts
| 2.71875
| 3
|
import https from "https"
import { OutgoingHttpHeaders } from "http"
import { ClientOptions } from "./types"
const MONZO_BASE_URL = "api.monzo.com"
interface QueryParams { [header: string]: string | number }
export default class HttpClient {
private readonly options: ClientOptions
constructor(options: ClientOptions) {
this.options = options
}
private request(method: "GET" | "POST", path: string, headers?: OutgoingHttpHeaders): Promise<Buffer> {
const options = {
hostname: MONZO_BASE_URL,
port: 443,
path,
method,
headers,
}
let data: Buffer
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
res.on("data", data => {
resolve(data)
})
})
req.on("error", err => {
reject(err)
})
req.end()
})
}
private _get(path: string) {
return this.request("GET", path, {
"Authorization": `Bearer ${this.options.accessToken}`
})
}
private _post(path: string) {
return this.request("POST", path, {
"Authorization": `Bearer ${this.options.accessToken}`
})
}
protected async getData<T>(path: string, params?: QueryParams): Promise<T> {
const response = await this._get(params ? this.buildPath(path, params) : path)
const data: T = JSON.parse(response.toString())
return data
}
buildPath(path: string, params: QueryParams): string {
let queryParams = []
for (const key in params) {
queryParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
}
return `${path}?${queryParams.join('&')}`
}
}
|
92997afe60b9070b8ca855c11287425b4efd2a69
|
TypeScript
|
ppjmpd/cyrilla
|
/src/rulesGenerator.ts
| 3.046875
| 3
|
import { Rules } from './lang/rules';
interface MultiplyOptions {
from: string;
to: string;
onStart?: boolean;
onEnd?: boolean;
before?: (string | Rules)[];
after?: (string | Rules)[];
}
interface CreateOptions {
onStart?: boolean;
onEnd?: boolean;
before?: (string | Rules)[];
beforeVowel?: boolean;
beforeConsonant?: boolean;
after?: (string | Rules)[];
afterVowel?: boolean;
afterConsonant?: boolean;
}
// Anchors
export const START = '^';
export const END = '$';
export class RulesGenerator {
private readonly rules: Rules;
private readonly vowels: string[];
private readonly consonants: string[];
constructor(rules: Rules, vowels: string[], consonants: string[]) {
this.rules = rules;
this.vowels = vowels;
this.consonants = consonants;
}
private normalize(arr: (string | Rules)[]): [string[], string[]] {
const fromArr: string[] = [];
const toArr: string[] = [];
arr.forEach((value) => {
if (typeof value === 'string') {
fromArr.push(value);
const to = this.rules[value];
if (typeof to !== 'undefined') {
toArr.push(to);
} else {
// Transliterate letter by letter
const str = [...value].reduce((str, fromLetter) => {
// Maybe we can use multiple string replacement algorithm here
const toLetter = this.rules[fromLetter];
return typeof toLetter !== 'undefined' ? str + toLetter : str;
}, '');
toArr.push(str);
}
} else {
Object.keys(value).forEach((deepValue) => {
const deepTo = value[deepValue];
fromArr.push(deepValue);
toArr.push(deepTo);
});
}
});
return [fromArr, toArr];
}
private multiply({ from, to, onStart = false, onEnd = false, before = [], after = [] }: MultiplyOptions): Rules {
const start = onStart ? START : '';
const end = onEnd ? END : '';
const rules: Rules = {};
const [afterFrom, afterTo] = this.normalize(after);
const [beforeFrom, beforeTo] = this.normalize(before);
function wrapFrom(str: string) {
return start + str + end;
}
function wrapTo(str: string) {
return str;
}
if (afterFrom.length === 0 && beforeFrom.length === 0) {
return <Rules>{
[wrapFrom(from)]: wrapTo(to),
};
}
// B > 0
if (afterFrom.length === 0) {
beforeFrom.forEach((beforeFromValue, b) => {
const beforeToValue = beforeTo[b];
const fromVal = wrapFrom(from + beforeFromValue);
rules[fromVal] = wrapTo(to + beforeToValue);
});
return rules;
}
// A > 0
if (beforeFrom.length === 0) {
afterFrom.forEach((afterFromValue, a) => {
const afterToValue = afterTo[a];
const fromVal = wrapFrom(afterFromValue + from);
rules[fromVal] = wrapTo(afterToValue + to);
});
return rules;
}
// A > 0 && B > 0
afterFrom.forEach((afterFromValue, a) => {
const afterToValue = afterTo[a];
beforeFrom.forEach((beforeFromValue, b) => {
const beforeToValue = beforeTo[b];
const fromVal = wrapFrom(afterFromValue + from + beforeFromValue);
rules[fromVal] = wrapTo(afterToValue + to + beforeToValue);
});
});
return rules;
}
create(
from: string,
to: string,
{
onStart = false,
onEnd = false,
before = [],
beforeVowel = false,
beforeConsonant = false,
after = [],
afterVowel = false,
afterConsonant = false,
}: CreateOptions = {},
): Rules {
if (beforeVowel) {
before.push(...this.vowels);
}
if (afterVowel) {
after.push(...this.vowels);
}
if (beforeConsonant) {
before.push(...this.consonants);
}
if (afterConsonant) {
after.push(...this.consonants);
}
return this.multiply({
from,
to,
onStart,
onEnd,
after,
before,
});
}
}
|
17c1ee738bd2460951e35310630046afd8dcaf05
|
TypeScript
|
alexh00/engine
|
/src/core/ScreenManager.ts
| 2.75
| 3
|
import { EngineEvents } from "./EngineEvents";
import { EventQueue } from "../utils";
import { Screen } from "./Screen";
import { ISize, Settings } from "./Settings";
import { Loader } from "./Loader";
import { Unloader } from "./Unloader";
export interface IScreenMap {
[id: string]: typeof Screen
}
export class ScreenManager {
public root: PIXI.Container;
private _size: ISize;
public currentScreen: Screen;
private _screenMap: IScreenMap
constructor(
private _events: EventQueue,
private _settings: Settings,
private _loader: Loader,
private _unloader: Unloader
) {
this._size = this._settings.size;
this.root = new PIXI.Container();
this.root.position.set(
this._size.width / 2,
this._size.height / 2
)
this._events.on(EngineEvents.SHOW_SCREEN, this.showScreen)
}
public set screenMap(map: IScreenMap) {
this._screenMap = map;
}
public update(delta: number): void {
if (this.currentScreen) {
this.currentScreen.update(delta);
}
}
public showScreen = (id: string): void => {
// - validate id
if (!this._screenMap.hasOwnProperty(id)) {
console.error('Screen type not found', id)
}
// - Unload first if necessary too
if (this.currentScreen) {
const assetsToUnLoad = this._settings.assets[this.currentScreen.id];
this._unloader.unload(assetsToUnLoad)
}
const ScreenType = this._screenMap[id];
// - preload first if necessary
const assetsToLoad = this._settings.assets[id];
if (assetsToLoad) {
this._loader.loadAssets(assetsToLoad).then(() => {
this.disposeScreen();
this.currentScreen = this._createScreen(ScreenType, id)
})
} else {
this.disposeScreen();
this.currentScreen = this._createScreen(ScreenType, id)
}
}
private _createScreen(ScreenType: typeof Screen, id: string): Screen {
const screen = <Screen>new ScreenType({
screenWidth: this._size.width,
screenHeight: this._size.height,
screenEvents: this._events,
id
});
this.root.addChild(screen);
return screen;
}
public resize(): void {
//TODO - keep root centered? Or maybe not needed...
}
public disposeScreen(): void {
if (this.currentScreen) {
this.currentScreen.dispose();
this.currentScreen = null;
}
}
}
|
509115e49648984b2833ad1b36bd4cc21934b595
|
TypeScript
|
mar-celohenrique/cdc-nestjs
|
/src/authors/dto/create-author.dto.ts
| 2.59375
| 3
|
import { IsEmail, IsNotEmpty, MaxLength } from 'class-validator';
import { UniqueValue } from '@/commons/validations/validations';
import { Author } from '../entities/author.entity';
export class CreateAuthorDto {
@IsNotEmpty()
name: string;
@IsNotEmpty()
@IsEmail()
@UniqueValue({ field: 'email', clazz: Author })
email: string;
@IsNotEmpty()
@MaxLength(400)
description: string;
}
|
d9a194d177481ae314b8309c64efbb94488b8a1b
|
TypeScript
|
hongjunshi/swagger-typescript
|
/src/generateHook.ts
| 2.640625
| 3
|
import {
getTsType,
isAscending,
getDefineParam,
getParamString,
getJsdoc,
toPascalCase,
getSchemaName,
isMatchWholeWord,
} from "./utils";
import { ApiAST, SwaggerConfig, TypeAST } from "./types";
import { HOOKS_BEGINNING, DEPRECATED_WARM_MESSAGE } from "./strings";
function generateHook(
apis: ApiAST[],
types: TypeAST[],
config: SwaggerConfig,
): string {
let code = HOOKS_BEGINNING;
try {
apis = apis.sort(({ serviceName }, { serviceName: _serviceName }) =>
isAscending(serviceName, _serviceName),
);
let apisCode =
apis.reduce((prev, { serviceName }) => {
return prev + ` ${serviceName},`;
}, "import {") + '} from "./services"\n';
apisCode += apis.reduce(
(
prev,
{
summary,
deprecated,
serviceName,
queryParamsTypeName,
pathParams,
requestBody,
headerParams,
isQueryParamsNullable,
isHeaderParamsNullable,
responses,
method,
queryParameters,
},
) => {
const hasPaging = queryParameters.find(
({ name }) => name.toLowerCase() === "page",
);
const isGet =
config.useQuery?.includes(serviceName) || method === "get";
const getParamsString = (override?: boolean) => ` ${
pathParams.length ? `${pathParams.map(({ name }) => name)},` : ""
}
${requestBody ? "requestBody," : ""}
${
queryParamsTypeName
? hasPaging && override
? `{
..._param,
...queryParams,
},`
: "queryParams,"
: ""
}`;
const TQueryFnData = `SwaggerResponse<${
responses ? getTsType(responses) : "any"
}>`;
const TError = "RequestError | Error";
const getQueryParamName = (
name: string,
nullable: boolean = isQueryParamsNullable,
) =>
queryParamsTypeName
? `${getParamString(name, !nullable, queryParamsTypeName)},`
: "";
const TVariables = `${
/** Path parameters */
pathParams
.map(({ name, required, schema, description }) =>
getDefineParam(name, required, schema, description),
)
.join(",")
}${pathParams.length > 0 ? "," : ""}${
/** Request Body */
requestBody
? `${getDefineParam("requestBody", true, requestBody)},`
: ""
}${
/** Query parameters */
getQueryParamName("queryParams")
}${
/** Header parameters */
headerParams
? `${getParamString(
"headerParams",
!isHeaderParamsNullable,
headerParams,
)},`
: ""
}`;
const hookName = `use${toPascalCase(serviceName)}`;
const deps = `[${serviceName}.key,${
pathParams.length ? `${pathParams.map(({ name }) => name)},` : ""
}
${queryParamsTypeName ? "queryParams," : ""}
${requestBody ? "requestBody," : ""}]`;
let result =
prev +
`
${getJsdoc({
description: summary,
tags: {
deprecated: {
value: Boolean(deprecated),
description: DEPRECATED_WARM_MESSAGE,
},
},
})}`;
result += `export const ${hookName} =`;
if (!isGet) {
result += `<TExtra extends any>`;
}
const params = [
`${isGet ? TVariables : ""}`,
`options?:${
hasPaging
? `UseInfiniteQueryOptions<${TQueryFnData}, ${TError}>`
: isGet
? `UseQueryOptions<${TQueryFnData}, ${TError}>`
: `UseMutationOptions<${TQueryFnData}, ${TError},${
TVariables === ""
? "{_extraVariables?:TExtra} | undefined"
: `{${TVariables} _extraVariables?:TExtra}`
}>`
},`,
`configOverride?:AxiosRequestConfig`,
];
result += ` (
${params.join("")}
) => {`;
if (isGet) {
result += `
const { key, fun } = ${hookName}.info(${getParamsString()} options,configOverride);
`;
if (hasPaging) {
result += `const {
data: { pages } = {},
data,
...rest
} = useInfiniteQuery(
key,
({ pageParam = 1 }) =>
fun({
${hasPaging.name}:pageParam,
}),
{
getNextPageParam: (_lastPage, allPages) => allPages.length + 1,
...(options as any),
},
);
const list = useMemo(() => paginationFlattenData(pages), [pages]);
const hasMore = useHasMore(pages, list, queryParams);
return {...rest, data, list, hasMore}
`;
} else {
result += `return useQuery<${TQueryFnData}, ${TError}>(key,()=>
fun(),
options
)`;
}
} else {
result += `return useMutation<${TQueryFnData}, ${TError}, ${
TVariables === ""
? "{_extraVariables?:TExtra} | undefined"
: `{${TVariables} _extraVariables?: TExtra }`
}>((
${TVariables === "" ? "" : `{${getParamsString()}}`}
)=>${serviceName}(
${getParamsString()}
configOverride,
),
options
)`;
}
result += `
}
`;
if (isGet) {
result += `${hookName}.info = (${params.join("")}) => {
return {
key: ${deps},
fun: (${getQueryParamName("_param", true)}) =>
${serviceName}(
${getParamsString(true)}
configOverride
),
};
};`;
result += `${hookName}.prefetch = (
client: QueryClient,
${params.join("")}) => {
const { key, fun } = ${hookName}.info(${getParamsString()} options,configOverride);
return client.getQueryData(${deps})
? Promise.resolve()
: client.prefetchQuery(
key,
()=>fun(),
options
);
}`;
}
return result;
},
"",
);
code +=
types
.sort(({ name }, { name: _name }) => isAscending(name, _name))
.reduce((prev, { name: _name }) => {
const name = getSchemaName(_name);
if (!isMatchWholeWord(apisCode, name)) {
return prev;
}
return prev + ` ${name},`;
}, "import {") + '} from "./types"\n';
code += apisCode;
return code;
} catch (error) {
console.error(error);
return "";
}
}
export { generateHook };
|
5745e541f396b790fc7e8ed2cf6511e51fc4c495
|
TypeScript
|
mljs/spectra-processing
|
/src/xy/xyMaxY.ts
| 2.9375
| 3
|
import { DataXY } from 'cheminfo-types';
import { xGetFromToIndex } from '../x/xGetFromToIndex';
import { xyCheck } from './xyCheck';
/**
* Finds the max value in a zone
*
* @param data - Object that contains property x (an ordered increasing array) and y (an array)
* @param options - Options
* @returns - Max y on the specified range
*/
export function xyMaxY(
data: DataXY,
options: {
/**
* First value for xyMaxY in the X scale
*/
from?: number;
/**
* First point for xyMaxY
* @default 0
* */
fromIndex?: number;
/**
* Last point for xyMaxY
* @default x.length-1
* */
toIndex?: number;
/**
* Last value for xyMaxY in the X scale
*/
to?: number;
} = {},
): number {
xyCheck(data);
const { x, y } = data;
const { fromIndex, toIndex } = xGetFromToIndex(x, options);
let currentxyMaxY = y[fromIndex];
for (let i = fromIndex; i <= toIndex; i++) {
if (y[i] > currentxyMaxY) currentxyMaxY = y[i];
}
return currentxyMaxY;
}
|
2073169121f985c9c025f08dd1a9670405551a24
|
TypeScript
|
gcanti/functional-programming
|
/src/solutions/Magma01.ts
| 3.359375
| 3
|
/**
* Implementare la funzione `fromReadonlyArray`
*/
import { Magma } from 'fp-ts/Magma'
const fromReadonlyArray = <A>(M: Magma<A>) => (
as: ReadonlyArray<readonly [string, A]>
): Readonly<Record<string, A>> => {
const out: Record<string, A> = {}
for (const [k, a] of as) {
if (out.hasOwnProperty(k)) {
out[k] = M.concat(out[k], a)
} else {
out[k] = a
}
}
return out
}
// ------------------------------------
// tests
// ------------------------------------
import * as assert from 'assert'
const magmaSum: Magma<number> = {
concat: (first, second) => first + second
}
// una istanza di Magma che semplicemente ignora il primo argomento
const lastMagma: Magma<number> = {
concat: (_first, second) => second
}
// una istanza di Magma che semplicemente ignora il secondo argomento
const firstMagma: Magma<number> = {
concat: (first, _second) => first
}
const input: ReadonlyArray<readonly [string, number]> = [
['a', 1],
['b', 2],
['a', 3]
]
assert.deepStrictEqual(fromReadonlyArray(magmaSum)(input), { a: 4, b: 2 })
assert.deepStrictEqual(fromReadonlyArray(lastMagma)(input), { a: 3, b: 2 })
assert.deepStrictEqual(fromReadonlyArray(firstMagma)(input), { a: 1, b: 2 })
|
d142be74dd2879ecfecb27ac5edec26de8e99a71
|
TypeScript
|
getbreathelife/prettier-plugin-sort-imports
|
/tests/StrictGrouping/imports-with-file-level-comments.ts
| 2.71875
| 3
|
//@ts-ignore
// I am file top level comments
import threeLevelRelativePath from "../../../threeLevelRelativePath";
// I am stick to sameLevelRelativePath
import sameLevelRelativePath from "./sameLevelRelativePath";
// I am stick to third party comment
import thirdParty from "third-party";
// leading comment
import {
random // inner comment
} from './random';
// leading comment
export {
random // inner comment
} from './random';
import c from 'c';
import oneLevelRelativePath from "../oneLevelRelativePath";
import otherthing from "@core/otherthing";
import a from 'a';
import twoLevelRelativePath from "../../twoLevelRelativePath";
import component from "@ui/hello";
export default {
title: 'hello',
};
import fourLevelRelativePath from "../../../../fourLevelRelativePath";
import something from "@server/something";
import x from 'x';
// I am function comment
function add(a:number,b:number) {
return a + b; // I am inside function
}
|
7a4c2e5175fabfcf20a27d5a64b88f7a44ef1630
|
TypeScript
|
clehner/tzprofiles
|
/dapp/src/helpers/kepler.ts
| 2.734375
| 3
|
import {Kepler, getOrbitId} from 'kepler-sdk';
export const addToKepler = async (kepler: Kepler, orbit: string, ...obj: Array<any>) => {
obj.forEach((o) => console.log(o));
if (kepler) {
// Get around the error of possibly passing nothing.
let f = obj.pop();
if (!f) {
throw new Error('Empty array passed to saveToKepler');
}
const res = await kepler.put(orbit, f, ...obj);
if (!res.ok || res.status !== 200) {
throw new Error(`Failed to create orbit: ${res.statusText}`);
}
const addresses = await res.text();
return addresses.split('\n');
}
throw new Error('No Kepler integration found');
};
export const saveToKepler = async (kepler: Kepler, pkh: string, ...obj: Array<any>) => {
obj.forEach((o) => console.log(o));
if (kepler) {
// Get around the error of possibly passing nothing.
let f = obj.pop();
if (!f) {
throw new Error('Empty array passed to saveToKepler');
}
try {
const res = await kepler.createOrbit(f, ...obj);
if (!res.ok || res.status !== 200) {
throw new Error(`Failed to create orbit: ${res.statusText}`);
}
const addresses = await res.text();
return addresses.split('\n');
} catch (e) {
console.warn(`Failed in create new orbit with error: ${e?.message || JSON.stringify(e)}`)
console.warn("Trying existing orbit")
try {
let id = await getOrbitId(pkh, {domain: process.env.KEPLER_URL, index: 0});
return await addToKepler(kepler, id, ...[f, ...obj]);
} catch (err) {
throw err;
}
}
}
throw new Error('No Kepler integration found');
};
|
c5158b0bc2bbb071a49a57650909dd331423da96
|
TypeScript
|
kuukienator/generative-art
|
/src/sketches/00003/index.ts
| 2.984375
| 3
|
import { ArtWork, ArtWorkOptions } from '../../types/index';
import { getRandomInt } from '../../lib/math';
const artwork = (): ArtWork => {
const run = (canvas: HTMLCanvasElement, options: ArtWorkOptions) => {
const context = canvas.getContext('2d');
const size = canvas.width;
const step = 20;
const branches = 20;
const lineWidth = 2;
const clear = () => context.clearRect(0, 0, canvas.width, canvas.height);
const drawBranchesVertical = (
initialX: number,
initialY: number,
width: number,
isLeft: boolean
) => {
for (let j = 0; j < branches; j++) {
const y = getRandomInt(0, width);
const length = getRandomInt(step / 3, (step / 3) * 2);
context.lineWidth = lineWidth / 2;
context.beginPath();
context.moveTo(initialX + lineWidth / 2, initialY + y);
if (isLeft) {
context.lineTo(initialX + lineWidth / 2 - length, initialY + y);
} else {
context.lineTo(initialX + lineWidth / 2 + length, initialY + y);
}
context.stroke();
}
};
const drawBranchesHorizontal = (
initialX: number,
initialY: number,
width: number,
isUp: boolean
) => {
for (let j = 0; j < branches; j++) {
const x = getRandomInt(0, width);
const length = getRandomInt(step / 3, (step / 3) * 2);
context.lineWidth = lineWidth / 2;
context.beginPath();
context.moveTo(initialX + x, initialY + lineWidth / 2);
if (isUp) {
context.lineTo(initialX + x, initialY + lineWidth / 2 - length);
} else {
context.lineTo(initialX + x, initialY + lineWidth / 2 + length);
}
context.stroke();
}
};
const generateVertical = (
initialX: number,
initialY: number,
width: number,
height: number
) => {
const segments = width / step;
for (let i = 0; i <= segments; i++) {
const x = initialX + i * step;
drawBranchesVertical(x, initialY, width, false);
drawBranchesVertical(x, initialY, width, true);
}
};
const generateHorizontal = (
initialX: number,
initialY: number,
width: number,
height: number
) => {
const segments = height / step;
for (let i = 0; i <= segments; i++) {
const y = initialY + i * step;
drawBranchesHorizontal(initialX, y, width, false);
drawBranchesHorizontal(initialX, y, width, true);
}
};
const drawLines = (count: number) => {
const segment = size / count;
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
if ((j + i) % 2 === 1) {
generateHorizontal(i * segment, j * segment, segment, segment);
} else {
generateVertical(i * segment, j * segment, segment, segment);
}
}
}
};
const drawLinesRotated = () => {
const segment = size / 2;
generateHorizontal(0, 0, segment, segment);
generateVertical(segment, 0, segment, segment);
generateHorizontal(segment, segment, segment, segment);
generateVertical(0, segment, segment, segment);
};
const generate = () => {
clear();
context.fillStyle = 'rgba(247, 127, 0, 0.5)';
context.strokeStyle = 'rgba(214, 40, 40, 0.7)';
context.fillRect(0, 0, size, size);
for (let i = 0; i < 10; i++) {
drawLines(3);
}
};
generate();
return canvas;
};
return {
run,
name: 'Short Lines',
};
};
export default artwork;
|
aae6b894aca405ea0fb7dff26be2306882a4ddd1
|
TypeScript
|
aleksandragencheva/edtech-frontend
|
/src/hooks/usePostRequest.ts
| 3.1875
| 3
|
import axios from 'axios';
import { useEffect, useState } from 'react';
import config from '../config';
import isDev from '../utils/isDev';
export type PostRequestAction<T> = [(data: T) => void, boolean, string?];
/** @description Creates a POST request to the base URI set up in the config file and the endpoint provided as an argument
* @param {string} endpoint Endpoint to which the POST request is made
* @return {Array} The result, loading state and error state as an array which can be destructured
*/
const usePostRequest = <DataType>(endpoint: string): PostRequestAction<DataType> => {
const [calls, setCalls] = useState(0);
const [requestData, setRequestData] = useState<DataType | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [error, setError] = useState<string | undefined>(undefined);
/**
* Executes the POST request to the endpoint set in the hook definition
* @param data The payload of the POST request as an object
*/
const doRequest = (data: DataType) => {
setRequestData(data);
setIsLoading(true);
setCalls(calls + 1);
};
useEffect(() => {
if (!calls) return;
const postData = async () => {
try {
const url = config.baseURI + endpoint;
await axios.post(url, requestData);
} catch (e) {
if (isDev()) {
// eslint-disable-next-line no-console
console.error(e);
}
setError(e);
} finally {
setIsLoading(false);
}
};
postData();
}, [calls]);
return [doRequest, isLoading, error];
};
export default usePostRequest;
|
a7dc47932dbd75d5e5baf5972ff01f04597596ed
|
TypeScript
|
lykweb/full_stack
|
/ts/ts培训资料/ts资料-y/ts-laboratory/6.泛型.ts
| 4.375
| 4
|
//=========泛型===========
//泛型就是解决 类 接口 方法的复用性、以及对不特定数据类型的支持
interface Lengthwise {
length: number;
}
function identity<T extends Lengthwise>(arg: T): T {
console.log("👴", arg.length);
return arg;
// return "🌶";
}
const str = "typescript学习";
const result = identity<string>(str);
console.log(result);
//=======泛型类===========
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) {
return x + y;
};
console.log(myGenericNumber.add(30, 50));
//=================实操函数重载=================
//只能返回string类型的数据
// function getData(value:string):string{
// return value;
// }
// //同时返回 string类型 和number类型 (代码冗余)
// function getData1(value:string):string{
// return value;
// }
// function getData2(value:number):number{
// return value;
// }
//--------愚蠢些的函数重载--------
// function add(...rest: number[]): number;
// function add(...rest: string[]): string;
// function add(...rest: any[]) {
// let first = rest[0];
// if (typeof first === 'number') {
// return rest.reduce((pre, cur) => pre + cur);
// }
// if (typeof first === 'string') {
// return rest.join('');
// }
// }
// console.log(add(1, 2))
// console.log(add('a', 'b', 'c'));
//使用泛型后就可以解决这个问题
// T表示泛型,具体什么类型是调用这个方法的时候决定的
// 表示参数是什么类型就返回什么类型~~~
function getData<T>(value:T):T{
return value;
}
getData<number>(123);
getData<string>('1214231');
// 定义接口
interface ConfigFn{
<T>(value:T):void;
}
var getData2:ConfigFn=function<T>(value:T):T{
return value;
}
getData2<string>('张三');
// getData2<string>(1243); //错误
// 小彩蛋
// readonly修饰只能用于方括号的数组和元组上
// let err1: readonly Set<number>; // 错误!
// let err2: readonly Array<boolean>; // 错误!
// let okay: readonly boolean[]; // 无错误
// let okay2: readonly [boolean, string]; // 无错误
|
9a148cc097f6e31ebd36e07667c57dfa5062b910
|
TypeScript
|
arnaud420/drawmadaire-front
|
/src/hooks/usePlayer.ts
| 2.515625
| 3
|
import React, { useContext, useEffect, useState } from 'react';
import { Game, Player } from '../models/GameModel';
import { Action } from '../reducers/UserReducer';
import { GameContext } from '../contexts/GameProvider';
import { User } from '../models/UserModel';
import { UserContext } from '../contexts/UserProvider';
export const usePlayer = () => {
const [game] = useContext<[Game, React.Dispatch<Action>]>(GameContext);
const [user] = useContext<[User, React.Dispatch<Action>]>(UserContext);
const [player, setPlayer] = useState<Player|null>(null);
useEffect(() => {
if (game.players.length > 0 && user.id) {
const currentPlayer = game.players.find(p => p.userId === user.id);
if (currentPlayer) {
setPlayer(currentPlayer);
}
}
}, [game, user]);
return player;
}
|
5583889d2f59407faaed8d06b8747ae32b453fc9
|
TypeScript
|
green-fox-academy/Miluta1990
|
/week-01/day-4/print-even.ts
| 2.546875
| 3
|
'use strict';
// Create a program that prints all the even numbers between 0 and 500
for (let i: number = 2; i < 501; i = i +2 ) {console.log(i)};
|
e0c597a994968d8fcb16f3a8efa272e35917c4e1
|
TypeScript
|
hanlindev/resourceful-cancan-sequelize
|
/lib/resourceful-cancan-sequelize.d.ts
| 2.75
| 3
|
/// <reference types="express" />
import * as express from 'express';
import { IConditionalFilterCreator } from 'resourceful-router';
import * as Cancan from 'cancan';
import { ClassConstructor, InstanceCreator, ModelType, ActionsType, TargetsType, ConditionType } from 'cancan';
export interface AbilityConfig<TP, TT> {
model: ModelType<TP>;
actions: ActionsType;
targets: TargetsType<TT>;
condition?: ConditionType<TP, TT>;
}
export interface AbilitySpecs<TUserModel> {
entity: ClassConstructor<TUserModel> | InstanceCreator<TUserModel>;
configure: (cancan: Cancan) => any;
}
export interface CancanHelper<TReturn> {
(model: any, action: string, target: any): TReturn;
}
/**
* Extend this interface in a controller module to include all model classes
* that may be loaded by any action of that controller.
*/
export interface IControllerModels {
}
/**
* Make your UserInstance interface extend this to add type definintion
* to req.user
*/
export interface IUserModel {
}
/**
* Extend this interface to specify the models in a sequelize db instance.
*/
export interface IDb {
}
export interface RequestWithCancan<TDb, TControllerModels, TUserModel> extends express.Request {
user: TUserModel;
db: TDb;
cancanConfig: ResourcefulCancanOptions;
models: TControllerModels;
can: CancanHelper<boolean>;
cannot: CancanHelper<boolean>;
authorize: CancanHelper<void>;
}
export interface ResourcefulCancanOptions {
userPrimaryKey?: string;
userForeignKey?: string;
notFoundRedirect?: string;
unauthorizedRedirect?: string;
}
/**
* Config the middleware that configs the ability spec of cancan. The middleware
* will attach the ability spec to the request as well as the helper functions,
* i.e. can, cannot etc. In order for unmarshalling POST data to model data,
* you need to use appropriate body-parser middleware.
* @param {CancanConfig} config prperties to configure the abilities.
* @return {express.RequestHandler}
*/
export declare function resourcefulCancan<TDb, TUser>(db: TDb, abilities: AbilitySpecs<TUser>[], config?: ResourcefulCancanOptions): express.RequestHandler;
export interface ResourceLoaderConfig {
idName?: string;
pageSize?: number;
pageNumberName?: string;
}
export declare const defaultLoaderConfig: ResourceLoaderConfig;
/**
* Create a RequestHandler to extract the desired model object(s). If an ID is
* in the params or query, a specific model will be loaded. If not found, it
* will return a 404 response. If id is not in params or query, it will return a
* collection of model instances that belong to the current user. POST and
* UPDATE requests are special. The loader will check if body exists in the
* request object. If it is, it will try to find a JSON object keyed by the name
* in the resource loader config and unmarshal it to a Sequelize Model object
* without saving.
*
* @param {ResourceLoaderConfig} config for the resource loader.
* @return {express.RequestHandler} a RequestHandler function.
*/
export declare function loadResource(name: string, config?: ResourceLoaderConfig): IConditionalFilterCreator;
/**
* Load and authorize the resource. Resource loading strategy is the same as the
* loadResource function. After the resource is loaded, it will try to authorize
* it. If authorization succeeds, the next handler will be invoked otherwise
* it will return 401 unauthorized response or redirect to the given url.
*
* @param {string} name name of the resource to be loaded.
* @param {ResourceLoaderConfig} config
* @return {express.RequestHandler} the resource loader middleware.
*/
export declare function loadAndAuthorizeResource(name: string, config?: ResourceLoaderConfig): IConditionalFilterCreator;
|
1925b20fbe2f0f659cf0276fd78731a6c80020bc
|
TypeScript
|
Team-W4/MealMasterDashboard
|
/src/components/Texts/textSizes.ts
| 2.609375
| 3
|
import { variant } from 'styled-system';
enum textSizeEnum {
title,
h1,
h2,
large,
normal,
small,
}
export type TextSizeKeys = keyof typeof textSizeEnum;
export type TextSizeProps = {
size?: TextSizeKeys;
};
const textSizes = variant({
prop: 'size',
variants: {
title: {
fontSize: 'primer',
lineHeight: 'primer',
fontWeight: 'bold',
fontFamily: 'SofiaProBold',
},
h1: {
fontSize: 'bourgeois',
lineHeight: 'bourgeois',
fontWeight: 'normal',
},
h2: {
fontSize: 'pica',
lineHeight: 'pica',
fontWeight: 'light',
fontFamily: 'SofiaProLight',
},
large: {
fontSize: 'paragon',
lineHeight: 'paragon',
},
normal: {
fontSize: 'pica',
lineHeight: 'pica',
},
small: {
fontSize: 'brevier',
lineHeight: 'brevier',
},
},
});
export default textSizes;
|
84c386149c34baebc6e4e0520565da037793216f
|
TypeScript
|
chewtoys/api-1
|
/app/Main/Db/index.ts
| 2.71875
| 3
|
/**
* Класс для работы с БД
* @author Nikita Bersenev
*/
import mysql from "mysql";
const option = {
host: process.env.MYSQL_HOST,
port: Number(process.env.MYSQL_PORT),
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
};
const pool = mysql.createPool(option);
export default class DB {
/**
*
* @param {string} sql SQL код
* @param {any[]} [params] Переменные для экранизации
*/
async query(sql: string, params?: any[]) {
return new Promise((resolve, reject) => {
pool.query(sql, params, (err: mysql.MysqlError, res: mysql.FieldInfo) => {
if (err) reject(err);
resolve(res);
});
});
}
}
|
6b40677a0f7277a9377cfdd4eac924f95c68bb94
|
TypeScript
|
ScriptedAlchemy/storybook
|
/app/vue/src/client/preview/render.ts
| 2.546875
| 3
|
import dedent from 'ts-dedent';
import Vue from 'vue';
import { RenderContext } from './types';
export const COMPONENT = 'STORYBOOK_COMPONENT';
export const VALUES = 'STORYBOOK_VALUES';
const root = new Vue({
data() {
return {
[COMPONENT]: undefined,
[VALUES]: {},
};
},
render(h) {
const children = this[COMPONENT] ? [h(this[COMPONENT])] : undefined;
return h('div', { attrs: { id: 'root' } }, children);
},
});
export default function render({
storyFn,
kind,
name,
args,
showMain,
showError,
showException,
forceRender,
}: RenderContext) {
Vue.config.errorHandler = showException;
// FIXME: move this into root[COMPONENT] = element
// once we get rid of knobs so we don't have to re-create
// a new component each time
const element = storyFn();
if (!element) {
showError({
title: `Expecting a Vue component from the story: "${name}" of "${kind}".`,
description: dedent`
Did you forget to return the Vue component from the story?
Use "() => ({ template: '<my-comp></my-comp>' })" or "() => ({ components: MyComp, template: '<my-comp></my-comp>' })" when defining the story.
`,
});
return;
}
showMain();
// at component creation || refresh by HMR or switching stories
if (!root[COMPONENT] || !forceRender) {
root[COMPONENT] = element;
}
// @ts-ignore https://github.com/storybookjs/storrybook/pull/7578#discussion_r307986139
root[VALUES] = { ...element.options[VALUES], ...args };
if (!root.$el) {
root.$mount('#root');
}
}
|
9eb5a5f42eb97ec0c66538368f236ba838477f21
|
TypeScript
|
RedstoneGamez/Pterodactyl.js
|
/src/lib/models/User.ts
| 2.71875
| 3
|
interface UserOptions {
id: number;
externalId: any;
uuid: string;
internalId: string;
username: string;
email: string;
firstName: string;
lastName: string;
fullName: string;
language: string;
rootAdmin: boolean;
twoFactor: boolean;
updatedAt: Date;
createdAt: Date;
}
interface UserOptionsRaw {
id: number;
external_id: any;
uuid: string;
username: string;
email: string;
first_name: string;
last_name: string;
language: string;
root_admin: boolean;
'2fa': boolean;
updated_at: string;
created_at: string;
}
interface NewUserOptions {
externalId?: string;
username: string;
email: string;
firstName: string;
lastName: string;
password?: string;
admin?: boolean;
language?: string;
}
export { UserOptions, UserOptionsRaw, NewUserOptions };
class User implements UserOptions {
public id: number;
public externalId: any;
public uuid: string;
public internalId: string;
public username: string;
public email: string;
public firstName: string;
public lastName: string;
public fullName: string;
public language: string;
public rootAdmin: boolean;
public twoFactor: boolean;
public updatedAt: Date;
public createdAt: Date;
constructor(data: UserOptionsRaw) {
this.id = data.id;
this.externalId = data.external_id;
this.uuid = data.uuid;
this.internalId = data.uuid;
this.username = data.username;
this.email = data.email;
this.firstName = data.first_name;
this.lastName = data.last_name;
this.fullName = data.first_name + ' ' + data.last_name;
this.language = data.language;
this.rootAdmin = data.root_admin;
this.twoFactor = data['2fa'];
this.updatedAt = new Date(data.updated_at);
this.createdAt = new Date(data.created_at);
}
public toJSON(): any {
return {
id: this.id,
externalId: this.externalId,
uuid: this.uuid,
username: this.username,
email: this.username,
firstName: this.firstName,
lastName: this.lastName,
fullName: this.firstName + ' ' + this.lastName,
language: this.language,
rootAdmin: this.rootAdmin,
twoFactor: this.twoFactor,
updatedAt: this.updatedAt,
createdAt: this.createdAt
};
}
}
export default User;
|
0ea8d6a4c32f14038a1c971e0b4f56b6c3cb55f4
|
TypeScript
|
RafaelAPB/sidetree
|
/tests/mocks/MockOperationQueue.ts
| 2.984375
| 3
|
import IOperationQueue from '../../lib/core/versions/latest/interfaces/IOperationQueue';
/**
* A mock in-memory operation queue used by the Batch Writer.
*/
export default class MockOperationQueue implements IOperationQueue {
private latestTimestamp = 0;
private operations: Map<string, [number, Buffer]> = new Map();
async enqueue (didUniqueSuffix: string, operationBuffer: Buffer) {
this.latestTimestamp++;
this.operations.set(didUniqueSuffix, [this.latestTimestamp, operationBuffer]);
}
async dequeue (count: number): Promise<Buffer[]> {
// Sort the entries by their timestamp.
// If compare function returns < 0, a is before b, vice versa.
const sortedEntries = Array.from(this.operations.entries()).sort((a, b) => a[1][0] - b[1][0]);
const sortedKeys = sortedEntries.map(entry => entry[0]);
const sortedBuffers = sortedEntries.map(entry => entry[1][1]);
const bufferBatch = sortedBuffers.slice(0, count);
const keyBatch = sortedKeys.slice(0, count);
keyBatch.forEach((key) => this.operations.delete(key));
return bufferBatch;
}
async peek (count: number): Promise<Buffer[]> {
// Sort the entries by their timestamp.
const sortedValues = Array.from(this.operations.values()).sort((a, b) => a[0] - b[0]);
const sortedBuffers = sortedValues.map(entry => entry[1]);
const bufferBatch = sortedBuffers.slice(0, count);
return bufferBatch;
}
async contains (didUniqueSuffix: string): Promise<boolean> {
return this.operations.has(didUniqueSuffix);
}
}
|
d00adfdeb879e040eabfead72c6da018c4178e0f
|
TypeScript
|
delpillar/COMP2068-MailPilot-Build-2
|
/COMP2068-MailPilot-Build-2/Scripts/game.ts
| 2.59375
| 3
|
var stage: createjs.Stage;
var queue;
// game objects
var plane: Plane;
var island: Island;
var clouds = [];
var ocean: Ocean;
var scoreboard: Scoreboard;
// game constants
var CLOUD_NUM: number = 3;
var PLAYER_LIVES: number = 3;
var GAME_FONT = "40px Consolas";
var FONT_COLOUR = "#FFFF00";
// Preload function
function preload(): void {
queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.addEventListener("complete", init);
queue.loadManifest([
{ id: "plane", src: "images/plane.png" },
{ id: "island", src: "images/island.png" },
{ id: "cloud", src: "images/cloud.png" },
{ id: "ocean", src: "images/ocean.gif" },
{ id: "yay", src: "sounds/yay.ogg" },
{ id: "thunder", src: "sounds/thunder.ogg" }
]);
}
function init(): void {
stage = new createjs.Stage(document.getElementById("canvas"));
stage.enableMouseOver(20);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", gameLoop);
gameStart();
}
// Game Loop
function gameLoop(event): void {
ocean.update();
island.update();
plane.update();
for (var count = 0; count < CLOUD_NUM; count++) {
clouds[count].update();
}
collisionCheck();
scoreboard.update();
stage.update();
}
// Plane Class
class Plane {
image: createjs.Bitmap;
width: number;
height: number;
constructor() {
this.image = new createjs.Bitmap(queue.getResult("plane"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
this.image.regX = this.width * 0.5;
this.image.regY = this.height * 0.5;
this.image.y = 430;
stage.addChild(this.image);
}
update() {
this.image.x = stage.mouseX;
}
}
// Island Class
class Island {
image: createjs.Bitmap;
width: number;
height: number;
dy: number;
constructor() {
this.image = new createjs.Bitmap(queue.getResult("island"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
this.image.regX = this.width * 0.5;
this.image.regY = this.height * 0.5;
this.dy = 5;
stage.addChild(this.image);
this.reset();
}
reset() {
this.image.y = -this.height;
this.image.x = Math.floor(Math.random() * stage.canvas.width);
}
update() {
this.image.y += this.dy;
if (this.image.y > (this.height + stage.canvas.height)) {
this.reset();
}
}
}
// Island Class
class Cloud {
image: createjs.Bitmap;
width: number;
height: number;
dy: number;
dx: number;
constructor() {
this.image = new createjs.Bitmap(queue.getResult("cloud"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
this.image.regX = this.width * 0.5;
this.image.regY = this.height * 0.5;
stage.addChild(this.image);
this.reset();
}
reset() {
this.image.y = -this.height;
this.image.x = Math.floor(Math.random() * stage.canvas.width);
this.dy = Math.floor(Math.random() * 5 + 5);
this.dx = Math.floor(Math.random() * 4 - 2);
}
update() {
this.image.y += this.dy;
this.image.x += this.dx;
if (this.image.y > (this.height + stage.canvas.height)) {
this.reset();
}
}
}
// Ocean Class
class Ocean {
image: createjs.Bitmap;
width: number;
height: number;
dy: number;
constructor() {
this.image = new createjs.Bitmap(queue.getResult("ocean"));
this.width = this.image.getBounds().width;
this.height = this.image.getBounds().height;
this.dy = 5;
stage.addChild(this.image);
this.reset();
}
reset() {
this.image.y = -this.height + stage.canvas.height;
}
update() {
this.image.y += this.dy;
if (this.image.y >= 0) {
this.reset();
}
}
}
// Scoreboard Class
class Scoreboard {
label: createjs.Text;
labelString: string = "";
lives: number = PLAYER_LIVES;
score: number = 0;
width: number;
height: number;
constructor() {
this.label = new createjs.Text(this.labelString, GAME_FONT, FONT_COLOUR);
this.update();
this.width = this.label.getBounds().width;
this.height = this.label.getBounds().height;
stage.addChild(this.label);
}
update() {
this.labelString = "Lives: " + this.lives.toString() + " Score: " + this.score.toString();
this.label.text = this.labelString;
}
}
function distance(point1: createjs.Point, point2: createjs.Point):number {
var p1: createjs.Point;
var p2: createjs.Point;
var theXs: number;
var theYs: number;
var result: number;
p1 = new createjs.Point();
p2 = new createjs.Point();
p1.x = point1.x;
p1.y = point1.y;
p2.x = point2.x;
p2.y = point2.y;
theXs = p2.x - p1.x;
theYs = p2.y - p1.y;
theXs = theXs * theXs;
theYs = theYs * theYs;
result = Math.sqrt(theXs + theYs);
return result;
}
// Check Collision with Plane and Island
function planeAndIsland() {
var p1: createjs.Point = new createjs.Point();
var p2: createjs.Point = new createjs.Point();
p1.x = plane.image.x;
p1.y = plane.image.y;
p2.x = island.image.x;
p2.y = island.image.y;
if (distance(p1, p2) <= ((plane.height * 0.5) + (island.height * 0.5))) {
createjs.Sound.play("yay");
scoreboard.score += 100;
island.reset();
}
}
// Check Collision with Plane and Cloud
function planeAndCloud(theCloud: Cloud) {
var p1: createjs.Point = new createjs.Point();
var p2: createjs.Point = new createjs.Point();
var cloud: Cloud = new Cloud();
cloud = theCloud;
p1.x = plane.image.x;
p1.y = plane.image.y;
p2.x = cloud.image.x;
p2.y = cloud.image.y;
if (distance(p1, p2) <= ((plane.height * 0.5) + (cloud.height * 0.5))) {
createjs.Sound.play("thunder");
scoreboard.lives -= 1;
cloud.reset();
}
}
function collisionCheck() {
planeAndIsland();
for (var count = 0; count < CLOUD_NUM; count++) {
planeAndCloud(clouds[count]);
}
}
function gameStart(): void {
ocean = new Ocean();
island = new Island();
plane = new Plane();
for (var count = 0; count < CLOUD_NUM; count++) {
clouds[count] = new Cloud();
}
scoreboard = new Scoreboard();
}
|
df65c1366738614548001de3f43b67019d209201
|
TypeScript
|
kations/unikit
|
/src/util/deepMerge.ts
| 3.84375
| 4
|
interface IIsObject {
(item: any): boolean;
}
interface IObject {
[key: string]: any;
}
interface IDeepMerge {
(target: IObject, ...sources: Array<IObject>): IObject;
}
/**
* @description Method to check if an item is an object. Date and Function are considered
* an object, so if you need to exclude those, please update the method accordingly.
* @param item - The item that needs to be checked
* @return {Boolean} Whether or not @item is an object
*/
export const isObject: IIsObject = (item: any): boolean => {
return item === Object(item) && !Array.isArray(item);
};
/**
* @description Method to perform a deep merge of objects
* @param {Object} target - The targeted object that needs to be merged with the supplied @sources
* @param {Array<Object>} sources - The source(s) that will be used to update the @target object
* @return {Object} The final merged object
*/
const deepMerge: IDeepMerge = (
target: IObject,
...sources: Array<IObject>
): IObject => {
// return the target if no sources passed
if (!sources.length) {
return target;
}
const result: IObject = target;
if (isObject(result)) {
const len: number = sources.length;
for (let i = 0; i < len; i += 1) {
const elm: any = sources[i];
if (isObject(elm)) {
for (const key in elm) {
if (elm.hasOwnProperty(key)) {
if (isObject(elm[key])) {
if (!result[key] || !isObject(result[key])) {
result[key] = {};
}
deepMerge(result[key], elm[key]);
} else {
if (Array.isArray(result[key]) && Array.isArray(elm[key])) {
// concatenate the two arrays and remove any duplicate primitive values
result[key] = Array.from(new Set(result[key].concat(elm[key])));
} else {
result[key] = elm[key];
}
}
}
}
}
}
}
return result;
};
export default deepMerge;
|
2bb8d1222e879e3a7a1cbe19ae2e2fb28abacce6
|
TypeScript
|
PacktPublishing/Hands-on-Web-Development-with-ASP.NET-Core-and-Angular-7
|
/Section 2/ex 2.1/ClientApp/src/app/models/repository.ts
| 2.59375
| 3
|
import { Movie } from "./movie.model";
import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
const moviesUrl = "/api/movies";
@Injectable()
export class Repository {
public movie: Movie;
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<Movie>(baseUrl + 'api/movies/GetMovie')
.subscribe(result => {
this.movie = result;
},
error => console.error(error));
this.getMovie(3);
}
getMovie(id: number) {
//console.log("Movie Data Requested");
this.http.get(moviesUrl + "/" + id)
.subscribe(response => { this.movie = response });
}
}
|
ab3c9b876abafa45ecdd189d88a26f266ecc4c50
|
TypeScript
|
Pinenam/AstarPathfinding
|
/src/Point.ts
| 3.21875
| 3
|
//Point定义为一个用来记录方格关键信息的类
export default class Point
{
public xIndex:number;//方格的x坐标
public yIndex:number;//方格的y坐标
public F:number=0;//A*算法的F值,默认值为0
public G:number=0;//A*算法的G值,默认值为0
public H:number=0;//A*算法的H值,默认值为0
public parentPoint:Point=null;//Point的父节点,默认值为null
public isObstacle:boolean=false;//方格是不是障碍物,默认值为false
public sprite:Laya.Sprite=null;//Sprite 是基本的显示图形的显示列表节点, Sprite 默认没有宽高,默认不接受鼠标事件,也是一个容器类
public constructor(xIndex:number, yIndex:number, sprite:Laya.Sprite,isObstacle:boolean)
{
//以下是初始化过程
this.xIndex=xIndex;
this.yIndex=yIndex;
this.sprite=sprite;
this.isObstacle=isObstacle;
}
}
|
725272df22648a89bb8b305d6174fc05b2213587
|
TypeScript
|
singhong137/CocosCreatorDataStructuresAlgorithms
|
/assets/Script/test/TreeTest.ts
| 3.109375
| 3
|
import { BinarySearchTree, AVLTree, RedBlackTree } from "../data_structures/Tree";
const { ccclass, property } = cc._decorator;
@ccclass
export default class TreeTest extends cc.Component {
start(){
console.log('TreeTest---');
// const tree = new BinarySearchTree();
// const tree = new AVLTree();
const tree = new RedBlackTree();
tree.insert(11);
tree.insert(7);
tree.insert(15);
tree.insert(5);
tree.insert(3);
tree.insert(9);
tree.insert(8);
tree.insert(10);
tree.insert(13);
tree.insert(12);
tree.insert(14);
tree.insert(20);
tree.insert(18);
tree.insert(25);
tree.insert(6);
const printNode = (value: number) => console.log(value);
console.log('inOrderTraverse...');
tree.inOrderTraverse(printNode);
console.log('preOrderTraverse...');
tree.preOrderTraverse(printNode);
console.log('postOrderTraverse...');
tree.postOrderTraverse(printNode);
console.log('search min max...', tree.min(), tree.max());
console.log(tree.search(1) ? 'key 1 found.' : 'key 1 not found.');
console.log(tree.search(8) ? 'key 8 found.' : 'key 8 not found.');
console.log('remove 6...');
tree.remove(6);
tree.inOrderTraverse(printNode);
console.log('remove 5...');
tree.remove(5);
tree.inOrderTraverse(printNode);
console.log('remove 15...');
tree.remove(15);
tree.inOrderTraverse(printNode);
}
}
|
d04d03d22ec88e32c932e8d12aeb73dde754612f
|
TypeScript
|
Siteimprove/alfa
|
/packages/alfa-result/test/result.spec.ts
| 3.1875
| 3
|
import { test } from "@siteimprove/alfa-test";
import { Err } from "../src/err";
import { Ok } from "../src/ok";
import { Result } from "../src/result";
const n: Result<number, string> = Ok.of(1);
const err: Result<number, string> = Err.of("error");
test("#map() applies a function to an ok value", (t) => {
t.deepEqual(n.map((n) => n + 2).getUnsafe(), 3);
});
test("#map() does nothing to an err value", (t) => {
t.equal(
err.map((n) => n + 2),
err
);
});
test(".from() constructs a result from a thunk", (t) => {
const n = Result.from(() => 1);
t.deepEqual(n.getUnsafe(), 1);
});
test(".from() constructs a result from a thunk that throws", (t) => {
const err = Result.from((): number => {
throw "fail";
});
t.deepEqual(err.toJSON(), {
type: "err",
error: "fail",
});
});
test(".from() constructs a result from an async thunk", async (t) => {
const n = await Result.from(async () => 1);
t.deepEqual(n.getUnsafe(), 1);
});
test(".from() constructs a result from an async thunk that throws", async (t) => {
const err = await Result.from(async (): Promise<number> => {
throw "fail";
});
t.deepEqual(err.toJSON(), {
type: "err",
error: "fail",
});
});
|
1702242d35e4e131576e86b032726408cc495de3
|
TypeScript
|
onura/capturetheether
|
/test/lotteries/predicttheblockhash.ts
| 2.625
| 3
|
import { ethers } from "hardhat";
import { Signer } from "ethers";
import { expect } from "chai";
// 0x23a6A169e879809457D8A5857Fe61D004aff6717
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
describe("predicttheblockhash", function() {
it("Should solve the predict the block hash challenge", async function() {
this.timeout(0);
let abi = [
// "function lockInGuess(uint8 n) public payable",
"function isComplete() public view returns (bool)"
];
const targetAddr = "0x31a5369793F4c01496d00f45F7EBc9704Ba3cd4D";
let accounts = await ethers.getSigners();
let eoa = accounts[0];
let balance = await eoa.getBalance();
console.log(ethers.utils.formatEther(balance));
// connect to original contract
let contract = new ethers.Contract(targetAddr, abi, ethers.getDefaultProvider());
let target = contract.connect(eoa);
// deploy proxy contract
const factory = await ethers.getContractFactory("PredictTheBlockHashProxy");
/*
const proxyCont = await factory.deploy();
console.log("Malicious contract deployed at: " + proxyCont.address);
*/
const proxyCont = await factory.attach("0x23a6A169e879809457D8A5857Fe61D004aff6717");
/*
// lock the guess
let payval = { value: ethers.utils.parseEther('1') };
let tx = await proxyCont.guess(targetAddr, payval);
expect(tx.hash).to.not.be.undefined;
console.log(tx);
*/
// wait for 256 block
let provider = ethers.getDefaultProvider();
let settleNum = await provider.getBlockNumber();
let currentBlock: number;
/*
do {
await delay(60000);
currentBlock = await provider.getBlockNumber();
console.log("Current block num:" + currentBlock);
} while (currentBlock - settleNum < 257)
*/
let tx = await proxyCont.attack(targetAddr, 12101020);
expect(tx.hash).to.not.be.undefined;
console.log(tx);
});
});
|
6818a08721a0f7d6bac251adab186d5f6fa6935f
|
TypeScript
|
vishwakarma02/infiniteScroll
|
/src/app/pipes/date-ago.pipe.ts
| 2.953125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'dateAgo',
pure: true
})
export class DateAgoPipe implements PipeTransform {
transform(value: any, args?: any): string {
let counter, str = '';
if (value) {
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
if (seconds < 29){
// less than 30 seconds ago will show as 'Just now'
str = 'Just now';
}
const intervals = [
{
name: 'year',
seconds: 31536000
},
{
name: 'month',
seconds: 2592000
},
{
name: 'week',
seconds: 604800
},
{
name: 'day',
seconds: 86400
},
{
name: 'hour',
seconds: 3600
},
{
name: 'minute',
seconds: 60
},
{
name: 'second',
seconds: 1
}
];
intervals.forEach((interval): string | void => {
counter = Math.floor(seconds / interval.seconds);
if (counter > 0 && !str) {
if (counter === 1) {
str = `${counter} ${interval.name} ago`; // singular (1 day ago)
} else {
str = `${counter} ${interval.name}'s ago`; // plural (2 days ago)
}
}
});
}
return str;
}
}
|
95d86d4ea076a4f022f92c4a0e6e6d1b29154da7
|
TypeScript
|
RichardOtvos/reactant
|
/packages/reactant-module/src/core/spawnMiddlewares.ts
| 2.640625
| 3
|
import { applyMiddleware, Middleware, Store } from 'redux';
import { PluginModule } from './plugin';
import { storeKey } from '../constants';
/**
* ## Description
* Compose and spawn middlewares for Redux.
*
* ## Example
*
* ```ts
* import logger from 'redux-logger';
*
* @injectable()
* class Foo {}
*
* const app = createApp({
* modules: [spawnMiddlewares(logger)],
* main: Foo,
* render: () => {},
* });
* ```
*
* @param args middlewares for Redux
*/
const spawnMiddlewares = (...args: Middleware[]) => {
return class extends PluginModule {
readonly [storeKey]?: Store;
// eslint-disable-next-line prefer-spread
enhancer = applyMiddleware.apply(null, args);
};
};
export { spawnMiddlewares };
|
b16a048acfcbd52ac73099aa427653fda8b2b72c
|
TypeScript
|
hrdyjan1/notify-deprecated
|
/constants/helpers/basic.ts
| 2.796875
| 3
|
function noop() {}
function isDefined<T>(x: T | undefined | null): x is T {
return !(typeof x === 'undefined' || x === null);
}
function isNotDefined<T>(x: T | undefined | null): x is undefined | null {
return !isDefined(x);
}
function isString(x: unknown): x is string {
return typeof x === 'string';
}
export {isDefined, isString, isNotDefined, noop};
|
31d3377a34e4d36b32e6b2261bb5ce0d30953406
|
TypeScript
|
thx/rap2-delos
|
/src/models/bo/organization.ts
| 2.546875
| 3
|
import { Table, Column, Model, HasMany, AutoIncrement, PrimaryKey, AllowNull, DataType, Default, BelongsTo, BelongsToMany, ForeignKey, AfterCreate } from 'sequelize-typescript'
import { User, Repository, OrganizationsMembers, Logger } from '../'
@Table({ paranoid: true, freezeTableName: false, timestamps: true })
export default class Organization extends Model<Organization> {
@AfterCreate
static async createLog(instance: Organization) {
await Logger.create({
userId: instance.creatorId,
type: 'create',
organizationId: instance.id
})
}
@AutoIncrement
@PrimaryKey
@Column
id: number
@AllowNull(false)
@Column(DataType.STRING(256))
name: string
@Column(DataType.TEXT)
description: string
@Column(DataType.STRING(256))
logo: string
@AllowNull(false)
@Default(true)
@Column({ comment: 'true:public, false:private' })
visibility: boolean
@ForeignKey(() => User)
@Column
creatorId: number
@ForeignKey(() => User)
@Column
ownerId: number
@BelongsTo(() => User, 'creatorId')
creator: User
@BelongsTo(() => User, 'ownerId')
owner: User
@BelongsToMany(() => User, () => OrganizationsMembers)
members: User[]
@HasMany(() => OrganizationsMembers)
organizationMembersList: OrganizationsMembers[]
@HasMany(() => Repository, 'organizationId')
repositories: Repository[]
}
|
5c8cd40bbdbe06bc1cadb953487644b5f9392387
|
TypeScript
|
MaximilianoMoreno/wit-be
|
/lib/core/utils/utils.service.ts
| 3.265625
| 3
|
import * as moment from 'moment';
import { Types } from 'mongoose';
import { UTIL_CONSTANTS } from './utils.constants';
export class UtilsService {
/**
* Method used to clean all undefined, null or empty attributes inside the received object recursively.
*
* @param {Object} object
* @returns {Object}
*/
static clean(object: any): any {
for (let key in object) {
if (object[key] === null || typeof object[key] === 'undefined') {
delete object[key];
} else if (typeof object[key] === 'object' && typeof object[key].getMonth !== 'function'
&& !object[key].hasOwnProperty('lastIndex')) {
if (Object.keys(object[key]).length === 0) {
delete object[key];
} else {
let cleared = this.clean(object[key]);
if (Object.keys(cleared).length === 0 && typeof cleared.getMonth !== 'function') {
delete object[key];
} else {
object[key] = cleared;
}
}
}
}
return object;
}
/**
* Generates all dates based on a interval, since and util amount of times
*
* @static
* @param {number} startDay
* @param {number} endDay
* @param {number} interval
* @param {string} intervalUnit
* @param {number} since
* @param {string} sinceUnit
* @returns
* @memberof UtilsService
*/
static getIntervalDates(startDay: number, endDay: number, interval: number, intervalUnit: string, since: number, sinceUnit: string) {
let dates: Array<Date> = [];
let nextDate: Date;
let startDate: Date = moment().add(startDay, 'days').toDate();
let limit: Date = moment().add(startDay + endDay, 'days').toDate();
let firstOccurrence: Date = moment().add(<any>(startDay + since), sinceUnit).toDate();
if (moment(firstOccurrence).isBefore(limit)) {
dates.push(firstOccurrence);
nextDate = moment(dates[dates.length - 1]).add(<any>interval, intervalUnit).toDate();
while (moment(nextDate).isBefore(limit)) {
dates.push(nextDate);
nextDate = moment(dates[dates.length - 1]).add(<any>interval, intervalUnit).toDate();
}
}
return dates;
}
/**
* Method used to create a formatted id like 0000-0000-0000 with randon numbers.
*
* @returns {string}
*/
static generateRandomId(): string {
let result = '';
for(let i = 0; i <= 3; i++) {
result += Math.floor(1000 + Math.random() * 9000);
if(i != 3) {
result += '-';
}
}
return result;
}
/**
* Method to execute a for each in the async way.
*
* @param {Array<any>} array
* @param {Function} callback
* @returns {Promise<void>}
*/
static async asyncForEach(array: Array<any>, callback: Function) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
/**
* Method used to get the hour between two dates.
*
* @param {any} from
* @param {any} to
* @returns {number}
*/
static getHoursBetweenDates(from: any, to: any) {
return Math.abs(<any>new Date(to) - <any>new Date(from)) / UTIL_CONSTANTS.MILLISECONDS_IN_HOUR;
}
/**
* Compare two mongoose ids.
*
* @param id1
* @param id2
* @returns {boolean}
*/
static compareIds(id1: Types.ObjectId, id2: Types.ObjectId) {
return id1 === id2 || (id1 && id1.equals(id2));
};
}
|
466a3e248818fb6426a1c74a2c71841fe6011b16
|
TypeScript
|
fewer/fewer2
|
/src/querybuilder.ts
| 2.796875
| 3
|
import { getStaticMeta, Model } from './model';
import { getConnection } from './connect';
import { ModelInstance } from './modelinstance';
import {
ALL_FIELDS,
ColumnTypes,
CreateSelectionSet,
MODEL_INSTANCE_META,
} from './types';
import { Columns } from './columns';
enum ResultCount {
MANY = 'MANY',
SINGLE = 'SINGLE',
}
type QueryMeta = {
modelType: typeof Model;
where?: any;
plucked?: string[];
limit?: number;
offset?: number;
resultCount?: ResultCount;
};
export class QueryBuilder<
ModelType extends typeof Model,
Plucked = typeof ALL_FIELDS,
Count = ResultCount.MANY,
Result = Count extends ResultCount.MANY
? ModelInstance<ModelType, Plucked>[]
: ModelInstance<ModelType, Plucked>
> {
constructor(private meta: QueryMeta) {}
private promise?: Promise<Result>;
/**
* This is an internal helper that is used to construct the next QueryBuilder object.
*/
private __next__(partialMeta: Partial<QueryMeta>) {
const nextMeta = {
...this.meta,
...partialMeta,
};
if (partialMeta.plucked) {
nextMeta.plucked = [
...(this.meta.plucked ?? []),
...partialMeta.plucked,
];
}
return new QueryBuilder<any, any, any, any>(nextMeta);
}
where(
conditions: Partial<ColumnTypes<ModelType>>,
): QueryBuilder<ModelType, Plucked, Count> {
return this.__next__({
where: conditions,
});
}
pluck<NewKeys extends Columns<ModelType>>(
...keys: NewKeys[]
): QueryBuilder<ModelType, CreateSelectionSet<Plucked, NewKeys>, Count> {
return this.__next__({
plucked: keys as string[],
});
}
limit(limit: number): QueryBuilder<ModelType, Plucked, Count> {
return this.__next__({
limit,
});
}
offset(offset: number): QueryBuilder<ModelType, Plucked, Count> {
return this.__next__({
offset,
});
}
first(): QueryBuilder<ModelType, Plucked, ResultCount.SINGLE> {
return this.__next__({
limit: 1,
resultCount: ResultCount.SINGLE,
});
}
async then(
onFulfilled: (value: Result) => void,
onRejected?: (error: Error) => void,
): Promise<void> {
if (!this.promise) {
this.promise = this.executeQuery();
}
return this.promise.then(
(value) => {
onFulfilled(value);
},
(error) => {
onRejected?.(error);
},
);
}
private async executeQuery() {
let query = getConnection(this.meta.modelType.database).knex.select();
const staticMeta = getStaticMeta(this.meta.modelType);
if (this.meta.plucked) {
query = query.select(
...new Set([...this.meta.plucked, staticMeta.primaryKey]),
);
}
query = query.from(staticMeta.tableName);
if (this.meta.where) {
query = query.where(this.meta.where);
}
if (this.meta.limit) {
query = query.limit(this.meta.limit);
}
if (this.meta.offset) {
query = query.offset(this.meta.offset);
}
const create = (value: any) => {
const instance = this.meta.modelType.create(value);
instance[MODEL_INSTANCE_META].exists = true;
return instance as any;
};
const value = await query;
if (this.meta.resultCount === ResultCount.SINGLE) {
// TODO: What if it isn't here.
return create(value[0]);
} else {
return value.map((result) => create(result));
}
}
}
|
7a1145fc5281772f84b7ea5e637ffdd971ff20c6
|
TypeScript
|
tomwanzek/d3-v4-definitelytyped
|
/src/d3-scale-chromatic/index.d.ts
| 2.671875
| 3
|
// Type definitions for D3JS d3-scale-chromatic module 1.0.2
// Project: https://github.com/d3/d3-scale-chromatic/
// Definitions by: Hugues Stefanski <https://github.com/Ledragon>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// -----------------------------------------------------------------------
// Categorical
// -----------------------------------------------------------------------
/**An array of eight categorical colors represented as RGB hexadecimal strings. */
export const schemeAccent: Array<string>;
/**An array of eight categorical colors represented as RGB hexadecimal strings. */
export const schemeDark2: Array<string>;
/**An array of twelve categorical colors represented as RGB hexadecimal strings. */
export const schemePaired: Array<string>;
/**An array of nine categorical colors represented as RGB hexadecimal strings. */
export const schemePastel1: Array<string>;
/**An array of eight categorical colors represented as RGB hexadecimal strings. */
export const schemePastel2: Array<string>;
/**An array of nine categorical colors represented as RGB hexadecimal strings. */
export const schemeSet1: Array<string>;
/**An array of eight categorical colors represented as RGB hexadecimal strings. */
export const schemeSet2: Array<string>;
/**An array of twelve categorical colors represented as RGB hexadecimal strings. */
export const schemeSet3: Array<string>;
// -----------------------------------------------------------------------
// Diverging
// -----------------------------------------------------------------------
/**Given a number value in the range [0,1], returns the corresponding color from the “BrBG” diverging color scheme represented as an RGB string. */
export function interpolateBrBG(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “PRGn” diverging color scheme represented as an RGB string.*/
export function interpolatePRGn(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “PiYG” diverging color scheme represented as an RGB string.*/
export function interpolatePiYG(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “PuOr” diverging color scheme represented as an RGB string.*/
export function interpolatePuOr(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “RdBu” diverging color scheme represented as an RGB string.*/
export function interpolateRdBu(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “RdGy” diverging color scheme represented as an RGB string.*/
export function interpolateRdGy(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “RdYlBu” diverging color scheme represented as an RGB string.*/
export function interpolateRdYlBu(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “RdYlGn” diverging color scheme represented as an RGB string.*/
export function interpolateRdYlGn(value: number): string;
/** Given a number t in the range [0,1], returns the corresponding color from the “Spectral” diverging color scheme represented as an RGB string.*/
export function interpolateSpectral(value: number): string;
// -----------------------------------------------------------------------
// Sequential
// -----------------------------------------------------------------------
/**Given a number t in the range [0,1], returns the corresponding color from the “Blues” sequential color scheme represented as an RGB string. */
export function interpolateBlues(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “Greens” sequential color scheme represented as an RGB string. */
export function interpolateGreens(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “Greys” sequential color scheme represented as an RGB string. */
export function interpolateGreys(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “Oranges” sequential color scheme represented as an RGB string. */
export function interpolateOranges(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “Purples” sequential color scheme represented as an RGB string. */
export function interpolatePurples(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “Reds” sequential color scheme represented as an RGB string. */
export function interpolateReds(value: number): string;
// -----------------------------------------------------------------------
// Sequential(Multi-Hue)
// -----------------------------------------------------------------------
/**Given a number t in the range [0,1], returns the corresponding color from the “BuGn” sequential color scheme represented as an RGB string. */
export function interpolateBuGn(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “BuPu” sequential color scheme represented as an RGB string. */
export function interpolateBuPu(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “GnBu” sequential color scheme represented as an RGB string. */
export function interpolateGnBu(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “OrRd” sequential color scheme represented as an RGB string. */
export function interpolateOrRd(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “PuBuGn” sequential color scheme represented as an RGB string. */
export function interpolatePuBuGn(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “PuBu” sequential color scheme represented as an RGB string. */
export function interpolatePuBu(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “PuRd” sequential color scheme represented as an RGB string. */
export function interpolatePuRd(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “RdPu” sequential color scheme represented as an RGB string. */
export function interpolateRdPu(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “YlGnBu” sequential color scheme represented as an RGB string. */
export function interpolateYlGnBu(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “YlGn” sequential color scheme represented as an RGB string. */
export function interpolateYlGn(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “YlOrBr” sequential color scheme represented as an RGB string. */
export function interpolateYlOrBr(value: number): string;
/**Given a number t in the range [0,1], returns the corresponding color from the “YlOrRd” sequential color scheme represented as an RGB string. */
export function interpolateYlOrRd(value: number): string;
|
b8d748116a460b8d4767e3b31dbd96a6f6a6d5ec
|
TypeScript
|
BlasmethiaN/TODO-svelte
|
/src/lib/immutableStore.ts
| 2.796875
| 3
|
//! useless piece of CRAP
import { writable, Writable } from 'svelte/store'
import { produce } from 'immer'
export type WritableImmutable<TData> = Writable<TData> & {
update: (fn: (value: TData) => TData | void) => void
}
const writableImmutable = <TData>(value: TData): WritableImmutable<TData> => {
const writableFns = writable(value)
const { update } = writableFns
return {
...writableFns,
update: (fn: (value: TData) => TData | void) => update((value) => produce(value, fn))
}
}
export const createImmutableStore = <TData, TActions>(
value: TData,
actionsFn: (writableImmutableFns: WritableImmutable<TData>) => TActions
): { subscribe: Writable<TData>['subscribe'] } & TActions => {
const writableImmutableFns = writableImmutable(value)
const { subscribe } = writableImmutableFns
return { subscribe, ...actionsFn(writableImmutableFns) }
}
|
b87750811815ddae0dc31025b806d9ebff94030c
|
TypeScript
|
taisiusyut/taisiusyut
|
/packages/server/src/modules/book/dto/get-books.dto.ts
| 2.515625
| 3
|
import { Exclude, Transform } from 'class-transformer';
import { IsEnum, IsOptional, IsString, IsMongoId } from 'class-validator';
import { Category, Schema$Book, Param$GetBooks, BookStatus } from '@/typings';
import { QueryDto } from '@/utils/mongoose';
import { IsBookName } from './';
class Excluded
extends QueryDto
implements Partial<Record<keyof Schema$Book, unknown>> {
@Exclude()
cover?: string;
@Exclude()
description?: string;
@Exclude()
tags?: string[];
@Exclude()
wordCount?: number;
@Exclude()
numOfCollection?: number;
@Exclude()
category?: Category;
@Exclude()
latestChapter?: undefined;
@Exclude()
lastPublishedAt?: undefined;
}
class GetBooks
extends Excluded
implements
Partial<Omit<Param$GetBooks, keyof Excluded>>,
Partial<Omit<Record<keyof Schema$Book, unknown>, keyof Excluded>> {
@IsOptional()
@IsMongoId()
id?: string;
@IsOptional()
@IsBookName()
name?: string;
@IsString()
@IsOptional()
tag?: string;
@IsOptional()
@IsMongoId()
author?: string;
@IsOptional()
@IsString()
authorName?: string;
@IsOptional()
@IsEnum(BookStatus)
@Transform(({ value }) => value && Number(value))
status?: BookStatus;
}
export class GetBooksDto
extends GetBooks
implements
Required<Omit<Schema$Book, keyof GetBooks>>,
Required<Omit<Param$GetBooks, keyof GetBooks>> {}
|
8b5d0f9fd12918b4a47e9b9a0629c63a318b7c57
|
TypeScript
|
keystonejs/keystone
|
/tests/api-tests/fields/types/fixtures/float/non-null/test-fixtures.ts
| 2.578125
| 3
|
import { float } from '@keystone-6/core/fields';
export const name = 'Float with isNullable: false';
export const typeFunction = (x: any) => float({ ...x, db: { ...x?.db, isNullable: false } });
export const exampleValue = () => 6.28;
export const exampleValue2 = () => 6.283;
export const supportsUnique = true;
export const fieldName = 'testField';
export const supportsGraphQLIsNonNull = true;
export const supportsDbMap = true;
export const getTestFields = () => ({ testField: float({ db: { isNullable: false } }) });
export const initItems = () => {
return [
{ name: 'post1', testField: -21.5 },
{ name: 'post2', testField: 0 },
{ name: 'post3', testField: 1.2 },
{ name: 'post4', testField: 2.3 },
{ name: 'post5', testField: 3 },
{ name: 'post6', testField: 5 },
{ name: 'post7', testField: 20.8 },
];
};
export const storedValues = () => [
{ name: 'post1', testField: -21.5 },
{ name: 'post2', testField: 0 },
{ name: 'post3', testField: 1.2 },
{ name: 'post4', testField: 2.3 },
{ name: 'post5', testField: 3 },
{ name: 'post6', testField: 5 },
{ name: 'post7', testField: 20.8 },
];
|
af77ebc402da5475671605bc32c4545d986ecb12
|
TypeScript
|
villagestyle/react-tool-web
|
/src/store/tabs/reducer.ts
| 2.6875
| 3
|
import { Reducer } from "redux";
import { toggle, add, remove } from "./methods";
export const initialState: State[] = [
{
path: "/m/home",
name: "首页",
active: true
}
];
export interface State {
path: string;
name: string;
active: boolean;
}
export const tabsReducer: Reducer<State[]> = (
state = initialState,
actions
) => {
switch (actions.type) {
case "@@tabs/TOGGLE":
return toggle(state, actions.payload);
case "@@tabs/add":
return add(state, actions.payload);
case "@@tabs/remove":
return remove(state, actions.payload);
case "@@tabs/clear":
return [
{
path: "/m/home",
name: "首页",
active: true
}
];
default:
return state;
}
};
|
7eee5d8f94502e50eaee271ef0aaf3881fb8be7f
|
TypeScript
|
MuriloFuza/Next-Level-Week
|
/nlw-4/src/services/ClassificationService.ts
| 2.703125
| 3
|
import { getCustomRepository } from "typeorm";
import { UsersRepository } from "../repositories/UsersRepository";
import { SurveysUsersRepository } from "../repositories/SurveysUsersRepository";
class Classification {
async execute(id: string) {
let media = 0;
const usersRepository = getCustomRepository(UsersRepository);
const user = await usersRepository.findOne({
id
});
const surveysUsersRepository = getCustomRepository(SurveysUsersRepository);
const surveys = await surveysUsersRepository.find({
user_id: id
})
for (let i = 0; i < surveys.length; i += 1) {
const value = Number(surveys[i].value);
console.log(value);
media += value;
}
media = (media / surveys.length);
if (media >= 0 && media <= 6) {
user.classification = "detractor";
}
if (media >= 7 && media <= 8) {
user.classification = "passive";
}
if (media >= 9 && media <= 10) {
user.classification = "promoter";
}
await usersRepository.save(user);
}
}
export default new Classification();
|
27f0cf14acd9a1b74e8b618dc9780f1229006173
|
TypeScript
|
arturcarvalho/denodash
|
/src/object/pick.ts
| 2.859375
| 3
|
export const pick = (
obj: Record<string | number, any>,
props: Array<string | number>,
): Record<string | number, any> => {
const newObj: Record<string | number, any> = {};
for (let prop of props) {
if (obj[prop] !== undefined) {
newObj[prop] = obj[prop];
}
}
return newObj;
};
export default pick;
|
67b0ab056bb16bae15d385c3e9a4aaca624df42d
|
TypeScript
|
elie29/angular-fundamentals-seed
|
/app/passengers/components/passenger-form/passenger-form.component.ts
| 2.515625
| 3
|
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Baggage, Passenger } from '../../models/passenger.interface';
@Component({
selector: 'passenger-form',
styleUrls: ['passenger-form.component.scss'],
template: `
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<div>
Passenger Name: <input
type="text"
name="fullname"
[ngModel]="detail?.fullname"
required
#fullname="ngModel"
/>
<div class="error" *ngIf="fullname.dirty && fullname.errors?.required">Passenger name is required</div>
</div>
<div>
Passenger ID: <input
type="text"
name="id"
[ngModel]="detail?.id"
required
#id="ngModel"
/>
{{ id.errors | json }}
</div>
<div>
<label>
<input type="checkbox" name="checkedIn"
[ngModel]="detail?.checkedIn" (ngModelChange)="toggleCheckIn($event)" />
</label>
</div>
<div *ngIf="form.value?.checkedIn">
Check In Date: <input
type="text"
name="checkInDate"
[ngModel]="detail?.checkInDate"/>
</div>
<div>
Luggage:
<select name="baggage" [ngModel]="detail?.baggage">
<option *ngFor="let item of baggage"
[value]="item.key"
[selected]="item.key === detail?.baggage"
>
{{ item.value }}</option>
</select>
<select name="baggage" [ngModel]="detail?.baggage">
<option *ngFor="let item of baggage"
[ngValue]="item.key"
>
{{ item.value }}</option>
</select>
</div>
<div>
<button type="submit" [disabled]="form.invalid">Update passenger</button>
</div>
</form>
`
})
export class PassengerFormComponent {
@Input() detail: Passenger;
@Output() update: EventEmitter<Passenger> = new EventEmitter();
baggage: Baggage[] = [
{ key: 'none', value: 'No baggage' },
{ key: 'hand-only', value: 'Hand baggage' },
{ key: 'hold-only', value: 'Hold baggage' },
{ key: 'hand-hold', value: 'Hand and hold baggage' }
];
toggleCheckIn(checkedIn: boolean): void {
if (checkedIn) {
this.detail.checkInDate = Date.now();
}
}
onSubmit(form: NgForm): void {
if (form.valid) {
const passenger = { ...this.detail, ...form.value };
this.update.emit(passenger);
}
}
}
|
bcbfa5326057e33fc6b8c3547f2186f1d3845947
|
TypeScript
|
pfalzergbr/vtm-dice-ts-react
|
/src/diceEngine/generateRoll.ts
| 2.765625
| 3
|
import {
DiceMap,
DiceType,
Dice,
} from './diceTypes';
import {generateRandomDice} from './diceUtils'
export const generateRoll = (
diceNum: number,
diceMap: DiceMap,
type: DiceType
): Dice[] => {
const rollArray: Dice[] = [];
for (let i = 0; i < diceNum; i++) {
const rolledDice = generateRandomDice(diceMap, type);
rollArray.push(rolledDice);
}
return rollArray;
};
|
79884b85351527f68a2e808d3356b140a14a4f0c
|
TypeScript
|
AdreeUA/interviewT
|
/src/ducks/users.ts
| 2.671875
| 3
|
import { createAction, createReducer } from 'redux-act'
import axios from 'axios'
import { ReduxThunkCb } from '../store/types'
export const REDUCER = 'USERS'
const NS = `${REDUCER}__`
export interface UserState {
thumbnail: string
fullName: string
email: string
phone: string
}
export interface UsersState {
results: UserState[]
filtersResults: UserState[]
filtersData: { [key: string]: string }
isRequestError: boolean
isRequesting: boolean
}
export const initialState: UsersState = {
results: [],
filtersResults: [],
filtersData: {},
isRequestError: false,
isRequesting: false,
}
const reducer = createReducer({}, initialState)
const callFailure = createAction(`${NS}CALL_FAILURE`)
reducer.on(callFailure, (state) => ({
...state,
isRequestError: true,
isRequesting: false,
}))
const callSuccess = createAction(`${NS}CALL_SUCCESS`)
reducer.on(callSuccess, (state) => ({
...state,
isRequestError: false,
isRequesting: false,
}))
const callRequest = createAction(`${NS}CALL_REQUEST`)
reducer.on(callRequest, (state) => ({
...state,
isRequestError: false,
isRequesting: true,
}))
const set = createAction<any>(`${NS}SET`)
reducer.on(set, (state, users) => ({ ...state, results: users.results }))
const add = createAction<any>(`${NS}ADD`)
reducer.on(add, (state, { results }) => {
const user = results[0]
const nameField = user.name
const titleName = nameField.title
const firstName = nameField.first
const lastName = nameField.last
const fullName = `${titleName} ${firstName} ${lastName}`
const thumbnail = user.picture.thumbnail
const email = user.email
const phone = user.phone
return {
...state,
results: [ ...state.results, { thumbnail, fullName, email, phone } ],
}
})
export const setFilterData = createAction<any>(`${NS}SET_FILTER_DATA`)
reducer.on(setFilterData, (state, filterData) => {
return {
...state,
filtersData: {
...state.filtersData,
...filterData,
},
}
})
export const filterUsers = createAction(`${NS}FILTERS`)
reducer.on(filterUsers, (state) => {
const filterKey = Object.keys(state.filtersData)
const filtersResults = state.results.filter((user) => {
const filterCollection: boolean[] = []
filterKey.forEach((key) => {
const result = user[key].toLowerCase().includes(state.filtersData[key].toLowerCase())
return filterCollection.push(result)
})
return filterCollection.every((el: boolean) => el)
})
return {
...state,
filtersResults,
}
})
export const load = (): ReduxThunkCb => (dispatch) => {
return new Promise((resolve, reject) => {
dispatch(callRequest())
return axios
.get('https://randomuser.me/api/')
.then((response) => {
dispatch(add(response.data))
dispatch(filterUsers())
dispatch(callSuccess())
resolve()
})
.catch((error) => {
dispatch(callFailure())
reject(error)
})
})
}
export default reducer
|
4c9ef407cbce796c2b0916d6224bf974c0d90f7d
|
TypeScript
|
tBlabs/RaspberryPi.RemoteIO
|
/src/Services/Logger/ConsoleOutput.ts
| 2.65625
| 3
|
import 'reflect-metadata';
import { injectable } from "inversify";
import { ILoggerOutput } from './ILoggerOutput';
@injectable()
export class ConsoleOutput implements ILoggerOutput
{
private timeSinceLastLog: number = -1;
public Print(str): void
{
if (str === '')
{
console.log('');
return ;
}
const now = +(new Date());
const diff = now - (this.timeSinceLastLog==(-1) ? now : this.timeSinceLastLog);
this.timeSinceLastLog = now;
const s = ("+" + diff.toString()).padStart(6, ' ') + ` | ${ str }`;
console.log(s);
}
}
|
f0c642a6131d03ef7e6ec09b539b40a8332f8a17
|
TypeScript
|
fabiendv/Angular-Heroes
|
/src/app/hero.service.spec.ts
| 2.515625
| 3
|
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HeroService } from './hero.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from 'selenium-webdriver/http';
import { MessageService } from './message.service';
import { MockBackend } from '@angular/http/testing';
describe('HeroService', () => {
let service:HeroService;
let httpTestingController: HttpTestingController;
let heroServiceStub: Partial<HeroService>;
let http: HttpClient;
let messageService: MessageService;
let httpClientSpy: { get: jasmine.Spy };
let heroService: HeroService;
/*
beforeEach(() => {
// TODO: spy on other methods too
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
heroService = new HeroService(<any> httpClientSpy);
});
it('should return expected heroes (HttpClient called once)', () => {
const expectedHeroes: Hero[] =
[{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));
heroService.getHeroes().subscribe(
heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});
it('should return an error when the server returns a 404', () => {
const errorResponse = new HttpErrorResponse({
error: 'test 404 error',
status: 404, statusText: 'Not Found'
});
httpClientSpy.get.and.returnValue(asyncError(errorResponse));
heroService.getHeroes().subscribe(
heroes => fail('expected an error, not heroes'),
error => expect(error.message).toContain('test 404 error')
);
});
/*
beforeEach(() => {
TestBed.configureTestingModule({
imports:[HttpClientModule, HttpClientTestingModule],
providers: [HeroService,HttpClient]
});
httpTestingController = TestBed.get(HttpTestingController);
http=new HttpClient();
service=new HeroService(http,messageService);
});
it('should have a service instance', () => {
expect(service).toBeDefined();
});
it('should greet properly', () => {
const test = service.getHeroes();
console.log(test);
});
*/
/*
beforeEach(() => {
TestBed.configureTestingModule({
imports:[HttpClientModule, HttpClientTestingModule],
providers: [HeroService]
});
httpTestingController = TestBed.get(HttpTestingController);
});
beforeEach(inject([HeroService], s => {
service = s;
}));
//const fixture = TestBed.createComponent(BannerComponent)
it('should be created', inject([HeroService], (service: HeroService) => {
expect(service).toBeTruthy();
}));
it('should return heroes',()=>{
service.getHeroes().subscribe(
heroes => expect(heroes.length).toEqual(this.mockHeroes.length),
fail);
var test = service.getHeroes().heroes;
console.log("\n"+test);
});
*/
});
|
1aca7eb239af1efbb8b129ba58dc0b20c597bc76
|
TypeScript
|
zhaojianeng25/sceneedit
|
/mizmain/feijibase/feiji/src/src14lou/core/Encipher.ts
| 2.828125
| 3
|
module core{
export class Encipher{
private PROTO_TEA_C2S:string = "2f651cbf85539c977da645a90cbd6b62";
private PROTO_MD5_KEY:string = "40f09aa5ff525e8cc3a9d16bf1abc3c1";
private xor_key_c2s:number;
constructor (){
this.encipher_init(this.PROTO_TEA_C2S);
}
private encipher_init(c2s:string):void{
let tmp:string = MD5.hash(c2s);
let bys:ByteArray = new ByteArray();
bys.writeString(tmp);
bys.position = 2;
this.xor_key_c2s = bys.readInt();;
}
public encipher_reset(pkt:ByteArray):void{
let tmp:string = MD5.hashBinary(pkt);
tmp = tmp + this.PROTO_MD5_KEY;
this.encipher_init(tmp);
}
//发包前加密一下
public encipher_encode(pkt:ByteArray):number{
//没有内容就不加密了
if(pkt.length == 2){
return 0;
}
let i:number;
let tea_v_size:number;
tea_v_size = (pkt.length) >> 2;
for (i = 0; i < tea_v_size; i++){
let o = pkt.getInt32(i);
pkt.setInt32(i, pkt.getInt32(i) ^ this.xor_key_c2s);
}
this.xor_key_c2s = MathU.toInt(this.xor_key_c2s + 286331153);
return 0;
}
}
}
|
81e61c42261bf76513dba32ceac452b622e08418
|
TypeScript
|
liozassa/get-location
|
/src/models/location.model.ts
| 2.59375
| 3
|
import mongoose, { Document, Schema } from "mongoose";
import mongooseUniqueValidator from "mongoose-unique-validator";
export interface ILocation extends Document {
_id: string,
user_id: string,
date: number,
request_id: string,
lat: number,
lon: number,
water: boolean
};
var LocationSchema = new Schema({
_id: {type: Schema.Types.ObjectId, auto: true},
user_id: {type: String, require: true},
date: {type: Number, require: true},
request_id: {type: String, require: true},
lat: {type: Number, require: true},
lon: {type: Number, require: true},
water: {type: Boolean, require: true}
});
LocationSchema.plugin(mongooseUniqueValidator);
export const Location = mongoose.model<ILocation>('Location', LocationSchema);
|
118fa8fa77e721bc9be8554bd17f3969bddc77aa
|
TypeScript
|
janhesters/Ordersome-Waiter-App
|
/app/redux/reducers/settingsReducer/settingsReducer.test.ts
| 2.6875
| 3
|
import * as generics from '../../actions/generic/generic.actions';
import * as actions from '../../actions/settings/settings.actions';
import settingsReducer from './settingsReducer';
const incomingSetting = 'drinks';
const expected = ['drinks'];
describe('settings.reducer', () => {
it('should return the initial state', () => {
expect(settingsReducer(undefined, {} as any)).toEqual([]);
});
it('should handle the TOGGLE_SETTINGS event to add a setting', () => {
expect(settingsReducer([], actions.toggle(incomingSetting))).toEqual(expected);
});
it('should handle the TOGGLE_SETTINGS event to remove a setting', () => {
expect(settingsReducer(expected, actions.toggle(incomingSetting))).toEqual([]);
});
it('should return the initial state if it receives CLEAR', () => {
expect(settingsReducer(expected, generics.clear())).toEqual([]);
});
});
|
a8568e8c26210c987fac6471a6b5f8235f247dc6
|
TypeScript
|
SakiMuraoka/fairy-online
|
/src/entities/Participant.ts
| 2.78125
| 3
|
export class Participant {
public 'id': string
public 'name': string
public 'affiliation': string
public 'year': string
public 'sex': 'M' | 'F'
public 'age': number
public 'can_drive': boolean
public 'note': string
constructor() {
this.id = ''
this.name = ''
this.affiliation = ''
this.year = ''
this.sex = 'M'
this.age = 0
this.can_drive = false
this.note = ''
}
}
|
5b3590c8bbfe89017c01e43057f510aee1262b44
|
TypeScript
|
patarapolw/match-brackets
|
/src/index.ts
| 3.140625
| 3
|
import escapeRegExp from 'escape-string-regexp'
export class FindBrackets {
static escape = '\\'
escapeKey: string
regexMap: Record<'start' | 'end', RegExp>
/**
*
* @param start Beginning bracket
* @param end Ending bracket
* @param options
* - [options.escape] Whether to be escape-able. Supply a string if you want a custom escape token.
*/
constructor (
private start: string,
private end: string,
options: {
escape?: string | boolean
} = {}
) {
this.escapeKey = typeof options.escape === 'string'
? options.escape
: (options.escape ? FindBrackets.escape : '')
this.regexMap = {
start: new RegExp(`${
this.escapeKey ? `(?!${this.escapeKey})` : ''
}${escapeRegExp(start)}`, 'g'),
end: new RegExp(`${
this.escapeKey ? `(?!${this.escapeKey})` : ''
}${escapeRegExp(end)}`, 'g')
}
}
parse (s: string, offset: number = 0) {
const output: {
value: string
start: number
}[] = []
while (true) {
let start = regexIndexOf(s, this.regexMap.start, offset)
if (start === -1) {
break
}
start += this.start.length
offset = start + this.start.length
const end = regexIndexOf(s, this.regexMap.end, offset)
if (end === -1) {
break
}
const value = strSegment(s, start, end)
output.push({ value, start })
offset = end + this.end.length
}
return output
}
}
function regexIndexOf (src: string, q: RegExp, start: number = 0) {
src = start ? src.substr(start) : src
const i = src.search(q)
return i === -1 ? i : i + start
}
function strSegment (src: string, start: number, end?: number) {
return src.substr(start, end ? end - start : undefined)
}
|
bf1090a1a3c4c5ed315c99e5f5e773ec5c510684
|
TypeScript
|
stmobo/BasilBot
|
/web-src/helper.ts
| 3.1875
| 3
|
import $ from 'jquery';
export function addSubelement(elem: JQuery | HTMLElement, elemType: string, opts: Object): JQuery<HTMLElement> {
var new_elem = $("<" + elemType + ">", opts);
$(elem).append(new_elem);
return new_elem;
}
export function formatTimeSinceEvent(timestamp: number): string {
var now = new Date();
var elapsed_time = now.getTime() - Math.round(timestamp * 1000);
if (elapsed_time < 5 * 60 * 1000) {
// <5 minutes ago - display 'just now'
return 'just now';
} else if (elapsed_time < 60 * 60 * 1000) {
// < 1 hour ago - display minutes since event
return Math.floor(elapsed_time / (60 * 1000)) + ' minutes ago';
} else if (elapsed_time < 24 * 60 * 60 * 1000) {
// < 1 day ago - display hours since event
let n_hours = Math.floor(elapsed_time / (60 * 60 * 1000));
return n_hours + (n_hours === 1 ? ' hour ago' : ' hours ago');
} else {
// otherwise just display days since event
let n_days = Math.floor(elapsed_time / (24 * 60 * 60 * 1000));
return n_days + (n_days === 1 ? ' day ago' : ' days ago');
}
}
|
a64bf06a53da8983bd3fc09d1f11d3f05c6da092
|
TypeScript
|
PurnaSahithiAdduri/ChicagoSocialHub
|
/ChicagoSocialHub/ChicagoSocialHub/frontend/src/app/components/real-time-line-chart/SMA-24hr.ts
| 2.71875
| 3
|
import * as d3 from "d3";
import * as d3Shape from "d3-shape";
import { Charts } from "../../charts";
export class SimpleMovingAverage24hr implements Charts {
movingAverageLine24hr: d3Shape.Line<[number, number]>;
//Calculate simple moving Average
movingAverage = (data, numberOfPoints) => {
var datetime = new Date();
//getting time for past 24hrs
var targetTime = new Date(datetime);
var tzDifference = targetTime.getTimezoneOffset();
datetime = new Date(targetTime.getTime() - tzDifference * 60 * 1000);
var diffHours = datetime.getHours() - 25;
datetime.setHours(diffHours);
var arr =[];
for (var i = 0; i < 24; i++) {
datetime.setHours(datetime.getHours() + 1);
var gte2 = datetime.toISOString().slice(0, -5).replace('Z', ' ').replace('T', ' ');
arr.push(gte2);
}
return data.map((row, index, total) => {
const start = Math.max(0, index - numberOfPoints);
const end = index;
const subset = total.slice(start, end + 1);
const sum = subset.reduce((a, b) => {
return a + b["availableDocks"];
}, 0);
return {
lastCommunicationTime: row["lastCommunicationTime"],
avg: sum / subset.length
};
});
};
//drawLine(stations,x,y,svg) {
drawChart(stations, x, y, svg) {
var datetime = new Date();
//getting time for past 24hrs
var targetTime = new Date(datetime);
var tzDifference = targetTime.getTimezoneOffset();
datetime = new Date(targetTime.getTime() - tzDifference * 60 * 1000);
var diffHours = datetime.getHours() - 25;
datetime.setHours(diffHours);
var gte1 = datetime.toISOString().slice(0, -8).replace('Z', ' ').replace('T', ' ');
var arr =[];
for (var i = 0; i < 24; i++) {
datetime.setHours(datetime.getHours() + 1);
var gte2 = datetime.toISOString().slice(0, -5).replace('Z', ' ').replace('T', ' ');
arr.push(gte2);
/*console.log(stations.length);
if (stations[i].lastCommunicationTime.includes(gte2)) {
console.log("I am there");
} else {
console.log("I am not there...");
}*/
}
this.movingAverageLine24hr = d3Shape
.line()
.x((d: any) => x(new Date(d.lastCommunicationTime.replace(/-/g, '/'))))
.y((d: any) => y(d.avg))
.curve(d3.curveBasis);
var movingAverageData = this.movingAverage(stations, 720);
svg.append("path")
.datum(movingAverageData)
.attr("id", "movingAverageLine24hr")
.style("fill", "none")
.attr("stroke", "#3498DB") //#3498DB - blue
.attr("d", this.movingAverageLine24hr)
.text("Smart");
}
}
|
9430c2f3faf924b6a2f8dcab75271c3af79d23f7
|
TypeScript
|
annandrosiuk/js-mentoring-program
|
/back-end/src/types/function.types.ts
| 2.90625
| 3
|
import {
Achievement,
ActualAchievement,
ArchiveItem,
Challenge,
Status,
TaskForToday,
Task,
} from '@interfaces';
/**
* Returns a current task with its status by the challenge id
* @param {string} challengeId challengeId - id of current challenge
* @param {Challenge[]} challengesList challengesList - a list of all challenges
*/
export type getTaskForToday = (challengeId: string, challengesList: Challenge[]) => TaskForToday;
/**
* Returns a list of actual achievements by the challenge id
* @param {string} challengeId challengeId - id of current challenge
* @param {Challenge[]} challengesList challengesList - a list of all challenges
*/
export type getActualAchievements = (
challengeId: string,
challengesList: Challenge[]
) => ActualAchievement[];
/**
* Returns all past tasks with their results by the challenge id
* @param {string} challengeId challengeId - id of current challenge
* @param {Challenge[]} challengesList challengesList - a list of all challenges
*/
export type getTaskArchive = (challengeId: string, challengesList: Challenge[]) => ArchiveItem[];
/**
* Returns a new challenge using the following parameters:
* @param {Task[]} tasksList tasksList - a list of tasks
* @param {Achievement[]} achievementsList achievementsList - a list of achievements
* @param {number} challengeDuration challengeDuration - challenge duration that by default should be 30 days
* @param {number} numberOfAchievements numberOfAchievements - number of achievements – by default, challenge duration / 6
*/
export type startNewChallenge = (
tasksList: Task[],
achievementsList: Achievement[],
challengeDuration: number,
numberOfAchievements: number
) => Challenge;
/**
* Returns achievements status for the challenge by its achievements list and tasks status
* @param {Achievement[]} achievementsList achievementsList - a list of achievements
* @param {Status} tasksStatus tasksStatus - tasks status
*/
export type calculateAchievementsStatus = (
achievementsList: Achievement[],
tasksStatus: Status
) => Map<string, Status>;
|
6c45b43bf93ce9813ab4ee85173182c9d66af97d
|
TypeScript
|
ExoSuite/ExoRun
|
/test/tests/http-request-error.test.ts
| 2.875
| 3
|
import { HttpRequestError } from "@exceptions/HttpRequestError"
import { GeneralApiProblem, HttpResponse } from "@services/api"
const basicProblem: GeneralApiProblem = {
kind: HttpResponse.UNAUTHORIZED
}
const errors = {
"email": [
"The email field Is required."
],
"password": [
"The password field Is required."
]
};
describe("http request playError tests", () => {
test("must return correct message", () => {
try {
throw new HttpRequestError(basicProblem, {
config: undefined, data: undefined, duration: 0, headers: {}, originalError: null, status: 0,
ok: false, problem: "UNKNOWN_ERROR"
})
} catch (error) {
expect(error.what()).toBeDefined()
}
})
test("must return the problem", () => {
try {
throw new HttpRequestError(basicProblem, {
config: undefined, data: undefined, duration: 0, headers: {}, originalError: null, status: 0,
ok: false, problem: "UNKNOWN_ERROR"
})
} catch (error) {
expect(error.problem()).toEqual(basicProblem)
}
})
test("must return the playError array from server", () => {
try {
throw new HttpRequestError(basicProblem, {
config: undefined, data: { errors }, duration: 0, headers: {}, originalError: null, status: 0,
ok: false, problem: "UNKNOWN_ERROR"
})
} catch (error) {
expect(error.happened()).toEqual(errors)
}
})
test("must return the playError array from server and format it", () => {
try {
throw new HttpRequestError(basicProblem, {
config: undefined, data: { errors }, duration: 0, headers: {}, originalError: null, status: 0,
ok: false, problem: "UNKNOWN_ERROR"
})
} catch (error) {
expect(error.formattedErrors()).toBeDefined()
}
})
describe("BaseError http status code related tests ", () => {
try {
throw new HttpRequestError(basicProblem, {
config: undefined, data: { errors }, duration: 0, headers: {}, originalError: null, status: 0,
ok: false, problem: "UNKNOWN_ERROR"
})
} catch (error) {
test("BaseError 'is' method must return true", () => {
expect(error.is(HttpResponse.UNAUTHORIZED)).toBeTruthy()
})
test("BaseError 'isNot' method must return true", () => {
expect(error.isNot(HttpResponse.OK)).toBeTruthy()
})
test("BaseError 'code' must return the correct http code", () => {
expect(error.code()).toEqual(HttpResponse.UNAUTHORIZED)
})
}
})
})
|
3c45375cb20baff7f211ad1937858795c4af4d8e
|
TypeScript
|
shuki770/nestjs-template
|
/src/core/pipes/parse-number.pipe.ts
| 2.640625
| 3
|
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class ParseNumberPipe implements PipeTransform {
public transform(str: string, metadata: ArgumentMetadata): number | undefined {
if (!str) {
return undefined;
}
return parseFloat(str);
}
}
|
684b59c05143bc761530e12fd2a225a8101ebd33
|
TypeScript
|
snoopy1954/datastorage
|
/backend/src/routes/music/artist.ts
| 2.65625
| 3
|
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-return */
import express from 'express';
import Artist from '../../models/music/artist';
import { toArtist } from '../../utils/music';
const artistRouter = express.Router();
artistRouter.get('/', async (_request, response) => {
const artists = await Artist.find({});
response.json(artists.map(artist => artist.toJSON()));
});
artistRouter.get('/:id', async (request, response) => {
try {
const artist = await Artist.findById(request.params.id);
if (artist) response.json(artist.toJSON());
else response.status(404).end();
} catch (e) {
response.status(400).send(e.message);
}
});
artistRouter.post('/', async (request, response) => {
try {
const newArtist = new Artist(toArtist(request.body));
void await newArtist.save();
response.json(newArtist);
} catch (e) {
response.status(400).send(e.message);
}
});
artistRouter.delete('/:id', async (request, response) => {
try {
const artist = await Artist.findByIdAndRemove(request.params.id);
if (artist) response.json(artist.toJSON());
else response.status(404).end();
} catch (e) {
response.status(400).send(e.message);
}
});
artistRouter.put('/:id', async (request, response) => {
try {
const newArtist = toArtist(request.body);
const artist = await Artist.findByIdAndUpdate(request.params.id, newArtist, { new: true });
if (artist) response.json(artist.toJSON());
else response.status(404).end();
} catch (e) {
response.status(400).send(e.message);
}
});
export default artistRouter;
|
f4eabe194e29db92478da8ee6510b581a5d6ffa9
|
TypeScript
|
yshiliang/api-core-js
|
/packages/api-core/src/common/ApiContext.ts
| 2.859375
| 3
|
import { Context } from "koa"
import { IApiDescriptor, IParameterDescriptor, IServiceDescriptor } from "../service/types"
import * as ApiException from "./ApiException"
import { DLogger } from "./DLogger"
export interface ApiContextConstructor {
new(...args: any[]): ApiContext;
}
export class ApiContext {
/**
* koa
*/
koa: Context
/**
* 请求参数
*/
params?: any
/**
* 路径参数
*/
pathVarilables?: any
/**
* api分发
*/
service?: IServiceDescriptor
api?: IApiDescriptor
private parameterList?: any[]
constructor(ctx: Context, params: any) {
this.koa = ctx
this.params = params
}
fill(service: IServiceDescriptor, api: IApiDescriptor): this {
this.service = service
this.api = api
return this
}
protected parseParameter(descriptor: IParameterDescriptor, parameter?: any) {
if (descriptor.pathVariable) {//从请求path获取参数
parameter = this.pathVarilables?.[descriptor.name!]
if (!parameter) throw ApiException.ERROR_API_PARAMS_REQUIRED(descriptor.name!)
}
!parameter && (parameter = this.params[descriptor.name!]);
//默认参数处理
if (!parameter && typeof descriptor.defaultValue !== 'undefined') {
parameter = descriptor.defaultValue
}
//必填参数处理
if (typeof parameter === 'undefined' && descriptor.required) {
throw ApiException.ERROR_API_PARAMS_REQUIRED(descriptor.name!)
}
//TODO 参数类型处理
const typeString = descriptor.type?.name
if (typeString === 'Number') {
const number = Number(parameter)
if (isNaN(number)) throw ApiException.ERROR_API_PARAMS_NUMBER(descriptor.name!)
parameter = number
} else if (typeString === 'Array' && parameter && !Array.isArray(parameter)) {
throw ApiException.ERROR_API_PARAMS_ARRAY(descriptor.name!)
}
return parameter
}
//服务调用
async callApi() {
if (!this.service || !this.api) {
throw ApiException.ERROR_API_CONTEXT_INVALID
}
const parameterList: any[] = []
this.api.parameters?.map(descriptor => {
parameterList.push(this.parseParameter(descriptor))
})
this.parameterList = parameterList
DLogger.log('[------\nstart call api => ', this.api,
';\nwith parameters => ', this?.parameterList,
';\norigin request params is => ', this?.params, '\n--------]')
return this.api.method!.call(this.service.service, ...this.parameterList)
}
}
|
bb7291273017324838803ea431647cce77ce0048
|
TypeScript
|
kesne/advent-of-code-2020
|
/solutions/5.ts
| 3.265625
| 3
|
function getLocation(str: string) {
return str.split("").reduce(
([row, column], el) => {
if (el === "F") {
return [row.slice(0, row.length / 2), column];
} else if (el === "B") {
return [row.slice(row.length / 2), column];
} else if (el === "L") {
return [row, column.slice(0, column.length / 2)];
} else {
return [row, column.slice(column.length / 2)];
}
},
[
Array.from({ length: 128 }, (_, i) => i),
Array.from({ length: 8 }, (_, i) => i),
]
);
}
function formatInput(rawInput: string) {
return rawInput.split("\n").filter(Boolean);
}
export function solution1(rawInput: string) {
const input = formatInput(rawInput);
return input
.map((str) => getLocation(str).flat())
.reduce((acc, [row, column]) => {
return Math.max(acc, row * 8 + column);
}, 0);
}
export function solution2(rawInput: string) {
const input = formatInput(rawInput);
const seatIDs = input
.map((str) => getLocation(str).flat())
.map(([row, column]) => {
return row * 8 + column;
});
for (let i = 0; i < 128; i++) {
for (let j = 0; j < 8; j++) {
const seatID = i * 8 + j;
if (
!seatIDs.includes(seatID) &&
seatIDs.includes(seatID + 1) &&
seatIDs.includes(seatID - 1)
) {
return seatID;
}
}
}
}
|
cd2fc4dae01d873986ee6439aee8fb9f92e5540b
|
TypeScript
|
multitoken/calculator
|
/src/manager/multitoken/executors/PeriodRebalanceExecutorImpl.ts
| 2.546875
| 3
|
import { ExecuteResult } from '../../../repository/models/ExecuteResult';
import { TokenPriceHistory } from '../../../repository/models/TokenPriceHistory';
import { Multitoken } from '../multitoken/Multitoken';
import { AbstractRebalanceExecutor } from './AbstractRebalanceExecutor';
import { PeriodRebalanceExecutor } from './PeriodRebalanceExecutor';
import { ExecutorType } from './TimeLineExecutor';
export class PeriodRebalanceExecutorImpl extends AbstractRebalanceExecutor implements PeriodRebalanceExecutor {
private period: number;
private timeLineStep: number;
constructor(multitoken: Multitoken, priority: number) {
super(multitoken, priority);
this.period = 0;
}
public setupPeriod(sec: number): void {
console.log('set period', sec);
this.period = sec;
}
public prepareCalculation(btcHistoryPrice: TokenPriceHistory[],
timeLineStep: number,
amount: number,
startIndex: number,
endIndex: number): void {
super.prepareCalculation(btcHistoryPrice, timeLineStep, amount, startIndex, endIndex);
this.timeLineStep = timeLineStep;
}
public execute(timeLineIndex: number,
historyPriceInTime: Map<string, number>,
timestamp: number,
btcAmount: number,
txPrice: number): ExecuteResult | any {
super.execute(timeLineIndex, historyPriceInTime, timestamp, btcAmount, txPrice);
const weights: Map<string, number> = this.multitoken.getWeights();
const amounts: Map<string, number> = this.multitoken.getAmounts();
if ((this.timeLineStep * timeLineIndex) % this.period !== 0) {
return undefined;
}
let amount: number = 0;
let maxProportions: number = 0;
amounts.forEach((value, key) => {
amount += value * (historyPriceInTime.get(key) || 0);
});
const txFee: number = this.calculateTxFee(txPrice, historyPriceInTime);
historyPriceInTime.forEach((value, key) => this.oldCoinsPrice.set(key, value));
amount = Math.max(amount - txFee, 0);
if (amount <= 0) {
return undefined;
}
weights.forEach((value, key) => maxProportions += value);
historyPriceInTime.forEach((value, key) => {
const weight: number = weights.get(key) || 0;
const amountPerCurrency = weight / maxProportions * amount;
const count: number = amountPerCurrency / value;
amounts.set(key, count);
});
this.multitoken.setup(amounts, weights);
return undefined;
}
public getType(): ExecutorType {
return ExecutorType.PERIOD_REBALANCER;
}
}
|
cfda7e07e9e480e8cfa6f210b3079de1e0328a2c
|
TypeScript
|
mjkaehr/Shelf
|
/frontend/Shelf/src/app/models/feed.model.ts
| 2.671875
| 3
|
export class Feed {
event: string;
user: string;
timeStamp: Date;
userRatedGame: Boolean;
game_id: string;
rating: Number
gameName: string
constructor(response: any) {
this.event = response.event;
this.user = response.user;
this.timeStamp = response.time_stamp;
this.userRatedGame = response.userRatedGame
if(response.userRatedGame){
this.game_id = response.game_id;
this.rating = response.rating
this.gameName = response.gameName
}
}
}
|
2e09774bb5212c79017576d61ec19aa90aaf73c2
|
TypeScript
|
tais-nissizaki/coracao-papel-front
|
/src/app/pipes/formatar-data.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { DatasService } from '../services/datas.service';
@Pipe({
name: 'FormatarData',
})
export class FormatarDataPipe implements PipeTransform {
constructor(private datasService: DatasService) { }
transform(value: Date | string, attrs?: any): string | undefined {
if (value) {
let valorDate;
if(typeof value == 'string') {
valorDate = new Date(value);
} else {
valorDate = value;
}
if (attrs && attrs.length > 0 && attrs == 'com-hora') {
return this.datasService.formatarDataEHora(valorDate);
}
return this.datasService.formatarData(valorDate);
}
return undefined;
}
}
|
45f759fe33020363b7d647cd1cad67602bf6ccaf
|
TypeScript
|
davidkel/chai-fabric
|
/src/helpers/StateDatabase.ts
| 2.78125
| 3
|
import { Collection, ICollection } from './Collection';
import nano = require('nano');
export class StateDatabase {
private db: nano.DatabaseScope;
private collections: Map<string, Collection>;
constructor(url: string, port: string, login?: {username: string, password: string}) {
let connectionPath = url + ':' + port;
let connectionType = 'http';
if (login) {
connectionPath = login.username + ':' + login.password + '@' + connectionPath;
connectionType = 'https'
}
connectionPath = connectionType + '://' + connectionPath;
this.db = nano(connectionPath).db;
this.collections = new Map<string, Collection>();
}
public async getPrivateCollection(channel: string, chaincode: string, collectionName: string): Promise<ICollection> {
const mapCollectionName = channel + chaincode + collectionName;
if (this.collections.has(mapCollectionName)) {
return this.collections.get(mapCollectionName);
}
const stateCollectionName = await this.getCollectionName(channel, chaincode, collectionName);
const collection = new Collection(this.db, stateCollectionName);
this.collections.set(mapCollectionName, collection);
return collection;
}
public async getWorldState(channel: string, chaincode: string): Promise<Collection> {
const mapCollectionName = channel + chaincode;
if (this.collections.has(mapCollectionName)) {
return this.collections.get(mapCollectionName);
}
const stateCollectionName = await this.getCollectionName(channel, chaincode);
const collection = new Collection(this.db, stateCollectionName);
this.collections.set(mapCollectionName, collection);
return collection;
}
private async getCollectionName(channel: string, chaincode: string, collectionName?: string): Promise<string> {
const names = await this.db.list();
let formattedCollectionName = `${channel}_${chaincode}`;
if (collectionName) {
formattedCollectionName += '$$p' + collectionName.split('').map((char: string) => isUpperCase(char) ? '$' + char.toLowerCase() : char).join('');
}
const exists = names.find((name) => {
return name === formattedCollectionName;
});
if (!exists) {
throw new Error(`Collection with name ${collectionName} does not exist in state database for chaincode ${chaincode} in channel ${channel}`);
}
return exists;
}
}
function isUpperCase(char: string): boolean {
return char.toUpperCase() === char && char.toLowerCase() !== char;
}
|
7485726ffabfb2b0fae6448d510c74da9e9e5c23
|
TypeScript
|
codebysandip/nralcm
|
/src/lifecycle/exception-handler/IExceptionHandler.ts
| 2.921875
| 3
|
import { HttpContext } from "..";
/**
* Interface to implement ExceptionHandler
* ExceptionHandler can be use for logging errors. Errors occured in Rest api that not handled
* will catch by ExceptionHandler
*/
export interface IExceptionHandler {
/**
* Method for handle exception
* @param context HttpContext Object
* @param exception Exception Object
*/
handleException(context: HttpContext, exception: any): void;
}
|
12576c5baea632290301def4eaf9f2e7f39c5a06
|
TypeScript
|
dtandersen/screeps
|
/src/exception.ts
| 2.53125
| 3
|
export class EntityNotFound {
message: string;
constructor(message: string) {
this.message = message;
}
}
export class MemoryUndefined {
message: string;
constructor(message: string) {
this.message = message;
}
}
export class OutOfRange {
message: string;
constructor(message: string) {
this.message = message;
}
}
|
b86dcbfe8cb19a5be35739ce3cd4a802432cf9e0
|
TypeScript
|
podlove/podlove-publisher
|
/client/src/store/contributors.store.ts
| 2.546875
| 3
|
import { handleActions, createAction } from 'redux-actions'
import { PodloveContributor, PodloveGroup, PodloveRole } from '../types/contributors.types';
export type State = {
contributors: PodloveContributor[],
roles: PodloveRole[],
groups: PodloveGroup[]
}
export const initialState: State = {
contributors: [],
roles: [],
groups: [],
};
export const INIT = 'podlove/publisher/contributors/INIT'
export const SET_CONTRIBUTORS = 'podlove/publisher/contributors/SET_CONTRIBUTORS'
export const SET_ROLES = 'podlove/publisher/contributors/SET_ROLES'
export const SET_GROUPS = 'podlove/publisher/contributors/SET_GROUPS'
export const ADD_CONTRIBUTOR = 'podlove/publisher/contributors/ADD'
export const init = createAction<void>(INIT);
export const setContributors = createAction<PodloveContributor[]>(SET_CONTRIBUTORS);
export const setRoles = createAction<PodloveRole[]>(SET_ROLES);
export const setGroups = createAction<PodloveGroup[]>(SET_GROUPS);
export const addContributor = createAction<Partial<PodloveContributor>>(ADD_CONTRIBUTOR);
export const reducer = handleActions({
[SET_CONTRIBUTORS]: (state: State, action: { payload: PodloveContributor[] }): State => ({
...state,
contributors: action.payload
}),
[SET_ROLES]: (state: State, action: { payload: PodloveRole[] }): State => ({
...state,
roles: action.payload
}),
[SET_GROUPS]: (state: State, action: { payload: PodloveGroup[] }): State => ({
...state,
groups: action.payload
}),
[ADD_CONTRIBUTOR]: (state: State, action: { payload: PodloveContributor }): State => ({
...state,
contributors: [
...state.contributors,
action.payload
]
})
}, initialState);
export const selectors = {
contributors: (state: State) => state.contributors,
roles: (state: State) => state.roles,
groups: (state: State) => state.groups,
}
|
07944ec0a5a17551ee9053e674b16f4b733dfce7
|
TypeScript
|
thatcosmonaut/love-typescript-definitions
|
/include/modules/video/love.video.d.ts
| 2.765625
| 3
|
declare namespace love {
/**
* This module is responsible for decoding, controlling, and streaming video
* files.
*
*
* It can't draw the videos, see love.graphics.newVideo and Video objects for
* that.
* @noSelf
* @link [love.video](https://love2d.org/wiki/love.video)
*/
export namespace video {
/**
* Creates a new VideoStream. Currently only Ogg Theora video files are supported.
* VideoStreams can't draw videos, see love.graphics.newVideo for that.
*
* @param filename The file path to the Ogg Theora video file.
* @return {VideoStream} videostream, A new VideoStream.
*/
export function newVideoStream(filename: string): VideoStream;
/**
* Creates a new VideoStream. Currently only Ogg Theora video files are supported.
* VideoStreams can't draw videos, see love.graphics.newVideo for that.
*
* @param file The File object containing the Ogg Theora video.
* @return {VideoStream} videostream, A new VideoStream.
*/
export function newVideoStream(file: File): VideoStream;
}
}
|
9a9d4168fe08f53d8097d207a30618e4e67200e5
|
TypeScript
|
ylerjen/classe84.front
|
/src/app/actions/subscription.actions.ts
| 2.84375
| 3
|
import { Action } from '@ngrx/store';
import { Subscription } from '../models/Subscription';
import { ActionWithPayload } from './app.actions';
/**
* This is the type of subscription we want to retrieve
* as the store is the same for the EventSubscriptions and
* the UserSubscriptions
*/
export enum SubscriptionType {
/**
* Subscriptions of a user
*/
User,
/**
* Subscriptions to an event
*/
Event,
}
export enum SubscriptionActions {
getSubscriptionListStart = '[Subscription] get Start',
getSubscriptionListFinished = '[Subscription] get Finished',
getSubscriptionListFailed = '[Subscription] get Failed',
addSubscription = '[Subscription] add',
addSubscriptionFinished = '[Subscription] add Finished',
addSubscriptionFailed = '[Subscription] add Failed',
deleteSubscription = '[Subscription] delete',
deleteSubscriptionFinished = '[Subscription] delete Finished',
deleteSubscriptionFailed = '[Subscription] delete Failed',
updateSubscrList = '[Subscription] update list',
resetSubscriptionState = '[Subscription] reset state',
}
/**
* The contract to pass to the action when we
* want to retrieve the subscriptions
*/
export interface FetchSubscriptionCmd {
id: string;
type: SubscriptionType;
}
export function resetSubscriptionState(): Action {
return {
type: SubscriptionActions.resetSubscriptionState
};
}
export function addSubscription(payload: Subscription): ActionWithPayload<Subscription> {
return {
type: SubscriptionActions.addSubscription,
payload
};
}
export function addSubscriptionFinished(payload: Subscription): ActionWithPayload<Subscription> {
return {
type: SubscriptionActions.addSubscriptionFinished,
payload
};
}
export function addSubscriptionFailed(payload: Error): ActionWithPayload<Error> {
return {
type: SubscriptionActions.addSubscriptionFailed,
payload
};
}
export function updateSubscription(payload: Subscription): ActionWithPayload<Subscription> {
return {
type: SubscriptionActions.updateSubscrList,
payload
};
}
export function deleteSubscription(payload: Subscription): ActionWithPayload<Subscription> {
return {
type: SubscriptionActions.deleteSubscription,
payload
};
}
export function deleteSubscriptionFinished(payload: Subscription): ActionWithPayload<Subscription> {
return {
type: SubscriptionActions.deleteSubscriptionFinished,
payload
};
}
export function deleteSubscriptionFailed(payload: Error): ActionWithPayload<Error> {
return {
type: SubscriptionActions.deleteSubscriptionFailed,
payload
};
}
export function getSubscriptionStart(payload: FetchSubscriptionCmd): ActionWithPayload<FetchSubscriptionCmd> {
return {
type: SubscriptionActions.getSubscriptionListStart,
payload
};
}
export function getSubscriptionFinished(payload: Array<Subscription>): ActionWithPayload<Array<Subscription>> {
return {
type: SubscriptionActions.getSubscriptionListFinished,
payload
};
}
export function getSubscriptionFailed(payload: Error): ActionWithPayload<Error> {
return {
type: SubscriptionActions.getSubscriptionListFailed,
payload
};
}
|
f66631839a622b67c796d14911ebe89c171e9705
|
TypeScript
|
1728954833/project-manager
|
/src/util/project.ts
| 2.609375
| 3
|
import type { Command, Projects, Project } from '../interface'
import { readJSON, writeJson } from 'fs-extra'
import { configPath } from '../constant/file'
export const getProjects = async (): Promise<Projects> => {
return readJSON(configPath)
}
export const saveProject = async (
name: string,
project: Project
): Promise<Projects> => {
const oldProjects = await getProjects()
const newProjects = Object.assign(oldProjects, { [name]: project })
await writeJson(configPath, newProjects)
return newProjects
}
export const removeProject = async (name: string): Promise<boolean> => {
const projects = await getProjects()
delete projects[name]
await writeJson(configPath, projects)
return true
}
export const getProject = async (name: string): Promise<Project> => {
const projects = await getProjects()
return projects[name]
}
export const saveCommand = async (
name: string,
command: Command
): Promise<Project> => {
const project = await getProject(name)
if (!project) return project
project.commands = Object.assign(project.commands, {
[command.name]: command,
})
await saveProject(name, project)
return project
}
export const removeCommand = async (
name: string,
command: string
): Promise<boolean> => {
const project = await getProject(name)
if (!project) return project
delete project.commands[command]
await saveProject(name, project)
return true
}
|
ccd03d46f0ee9a9e07d94a518f27f3e38a968bf1
|
TypeScript
|
mpsk/forecast-weather
|
/src/services/LocationPosition.ts
| 2.578125
| 3
|
import Rest from './Rest';
import {REST} from '../SETTINGS';
export type LatLog = {
lat: number;
lon: number;
}
export type LocationInfo = LatLog & {
city: string;
country: string;
}
export default class LocationPosition {
private _rest: Rest;
constructor() {
this._rest = new Rest();
}
getServiceIpPosition(): Promise<LocationInfo> {
return this._rest
.get(REST.LOCATION_IP)
.then((data) => {
return data.status !== 'fail' ? data : this.getIpApiLocation()
});
}
getIpApiLocation(): Promise<LocationInfo> {
return this._rest
.get('http://ip-api.com/json')
.then((data) => (data as LocationInfo))
}
post() {
return this._rest.post('/');
}
}
|
4f7c4be2c32da9deabaa676191c8cb618c137a15
|
TypeScript
|
tetsuyaohira/atcoder-typescript
|
/src/abc167/B-EasyLinearProgramming.ts
| 3.046875
| 3
|
import * as fs from 'fs';
const [a, b, c, k]: number[] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n')[0].split(' ').map(Number);
let ans: number;
ans = (a >= k) ? k : a;
const kk = (a + b >= k) ? 0 : k - (a + b);
ans -= (c >= kk) ? kk : c;
console.log(ans);
|
a60a4af3906e521504b340b1f0540b773850c466
|
TypeScript
|
PauloDev13/curso-fullstack-javascript
|
/src/errors/NoContentException.ts
| 2.765625
| 3
|
import HttpException from './HttpException';
class NoContentException extends HttpException {
constructor(id?: string) {
let msg = '';
if (id) {
msg = `Registro não localizado para o ID: ${id}`;
} else {
msg = 'Não há registros cadastrados';
}
super(404, msg);
}
}
export default NoContentException;
|
06ca17a8beafde85fd34f8feb45a5dabf7fb67f5
|
TypeScript
|
tensorflow/tensorboard
|
/tensorboard/components/tf_utils/utils.ts
| 2.90625
| 3
|
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
export interface TagInfo {
displayName: string;
description: string;
}
/**
* Given many occurrences of tag info for a particular tag across
* multiple runs, create a representative info object. This is useful
* for plugins that display just one visualization per tag, instead of
* one per run--tag combination: each run--tag combination can have its
* own display name or description, so there is a dimension mismatch. We
* reconcile this as follows:
*
* - We only show a display name if all runs agree. Otherwise, or if
* there are no runs, we use the provided `defaultDisplayName`.
*
* - If all runs agree on a description, we use it. Otherwise,
* we concatenate all descriptions, annotating which ones
* came from which run, and display them in a list.
*
* NOTE: Per TensorBoard convention, we assume that the provided
* `description`s have sanitized HTML and are safe to render into the
* DOM, while the `displayName` may be an arbitrary string. The output
* of this function respects this convention as well.
*/
export function aggregateTagInfo(
runToTagInfo: {
[run: string]: TagInfo;
},
defaultDisplayName: string
): TagInfo {
let unanimousDisplayName: string | null | undefined = undefined;
const descriptionToRuns: {
[description: string]: string[];
} = {};
Object.keys(runToTagInfo).forEach((run) => {
const info = runToTagInfo[run];
if (unanimousDisplayName === undefined) {
unanimousDisplayName = info.displayName;
}
if (unanimousDisplayName !== info.displayName) {
unanimousDisplayName = null;
}
if (descriptionToRuns[info.description] === undefined) {
descriptionToRuns[info.description] = [];
}
descriptionToRuns[info.description].push(run);
});
const displayName =
unanimousDisplayName != null ? unanimousDisplayName : defaultDisplayName;
const description = (() => {
const descriptions = Object.keys(descriptionToRuns);
if (descriptions.length === 0) {
return '';
} else if (descriptions.length === 1) {
return descriptions[0];
} else {
const items = descriptions.map((description) => {
const runs = descriptionToRuns[description].map((run) => {
// We're splicing potentially unsafe display names into
// sanitized descriptions, so we need to sanitize them.
const safeRun = run
.replace(/</g, '<')
.replace(/>/g, '>') // for symmetry :-)
.replace(/&/g, '&');
return `<code>${safeRun}</code>`;
});
const joined =
runs.length > 2
? runs.slice(0, runs.length - 1).join(', ') +
', and ' +
runs[runs.length - 1]
: runs.join(' and ');
const runNoun = ngettext(runs.length, 'run', 'runs');
return `<li><p>For ${runNoun} ${joined}:</p>${description}</li>`;
});
const prefix = '<p><strong>Multiple descriptions:</strong></p>';
return `${prefix}<ul>${items.join('')}</ul>`;
}
})();
return {displayName, description};
}
function ngettext(k: number, enSingular: string, enPlural: string): string {
// Potential extension point for proper i18n infrastructure, if we
// ever implement it.
return k === 1 ? enSingular : enPlural;
}
|
636dcc6c35046d200e6615bd855c80904ba8d393
|
TypeScript
|
Linya-IronMan/SourceCodeReading-Vue-Next
|
/vue-next-testCode/proxy.ts
| 3.171875
| 3
|
// interface WeakMap<K extends object, V> { }
interface WeakMap<K extends object, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
}
interface WeakMapConstructor {
new <K extends object = object, V = any>(entries?: readonly [K, V][] | null): WeakMap<K, V>;
readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;
const reactiveMap = new WeakMap<any, any>()
const proxyMap = reactiveMap
let a = {}
let b = new Proxy(a, {})
const existingProxy = proxyMap.set(a, b)
console.log(existingProxy, '========')
|
ae2b5484a2c3cdb07aec3570f561f7bfa92ce7b9
|
TypeScript
|
ahmedsameh148/Task-1
|
/test.ts
| 2.984375
| 3
|
var fs = require('fs');
var rowData = fs.readFileSync('db.json');
var members = JSON.parse(rowData);
class Member{
public firstName:string = "";
public middleName:string = "";
public lastName:string = "";
public fullName:string = "";
public committee:string = "";
public joinDate:Date = new Date();
}
let grid: Member[][] = [];
let committees: string[] = [];
var check = function (name:string){
let i;
for(i=0; i<committees.length; ++i){
if(committees[i] === name)return i;
}
return i;
}
for(let i=0; i<100; i++){
grid[i]=[];
}
for(let i=0; i<members.length; i++) {
var tmp: Member = new Member();
tmp.committee = members[i].committee;
tmp.firstName = members[i].firstName;
tmp.joinDate = new Date(members[i].joinDate);
tmp.lastName = members[i].lastName;
tmp.middleName = members[i].middleName;
tmp.fullName = members[i].firstName + " " + members[i].middleName + " " + members[i].lastName;
var committe = tmp.committee;
let idx: number = check(committe);
if(grid[idx].length > 0){
grid[idx].push(tmp);
}
else {
committees.push(committe);
grid[idx].push(tmp);
}
};
for(let i=0; i<grid.length; i++){
if(grid[i].length <= 0)continue;
console.log("\n======================== "+committees[i] + " ====================");
grid[i].sort((a,b)=>{
if(a.fullName < b.fullName)return -1;
else if(a.fullName > b.fullName)return 1;
else return 0;
});
for(let y=0; y<grid[i].length; y++){
console.log((y+1)+"- Name : "+grid[i][y].fullName+" , Joined In : " + grid[i][y].joinDate.toUTCString());
}
}
|
7b142497746bc22878c80ae23dce9f80f3044456
|
TypeScript
|
sourtangie/software-internship-technical-assessment
|
/luhn.ts
| 3.296875
| 3
|
"use strict";
export function luhnChecker(inputStr: string) {
let length: number = inputStr.length;
let sum: number = 0;
let odd: boolean = false;
let currentDigit: number = 0;
let divideBy: number = 10;
let success: number = 0;
let fail: number = 1;
for (let i: number = (length - 1); i >= 0; i--) {
currentDigit = parseInt(inputStr[i], 10) | 0;
if (odd === true) {
currentDigit = currentDigit * 2 | 0;
}
if (currentDigit > 9) {
currentDigit = currentDigit - 9;
}
odd = !odd;
sum += currentDigit;
}
let divisionCheck: number = sum % divideBy;
if (divisionCheck === 0) {
return success;
}
return fail;
}
|
4f37471a5af573f1c8d71f5e68907316f9eae2ec
|
TypeScript
|
LJaks/country-app
|
/src/redux/actions/country.ts
| 2.78125
| 3
|
import { Dispatch } from 'redux'
import {
Country,
CountryActions,
FETCH_COUNTRIES_ERROR,
FETCH_COUNTRIES_PENDING,
FETCH_COUNTRIES_SUCCESS,
} from '../../types'
export function fetchCountriesPending() {
return {
type: FETCH_COUNTRIES_PENDING,
}
}
export function fetchCountriesSuccess(country: Country[]): CountryActions {
return {
type: FETCH_COUNTRIES_SUCCESS,
payload: { country },
}
}
export function fetchCountriesError(error: Error) {
return {
type: FETCH_COUNTRIES_ERROR,
payload: { error },
}
}
// Async action processed by redux-thunk middleware
export function fetchCountries() {
return (dispatch: Dispatch) => {
dispatch(fetchCountriesPending())
fetch(`https://restcountries.com/v3.1/all`)
.then((resp) => resp.json())
.then((countries) => {
dispatch(fetchCountriesSuccess(countries))
})
.catch((error) => {
dispatch(fetchCountriesError(error))
})
}
}
|
95894ee180bee324dbbbb6bd5641fa9f35a8013d
|
TypeScript
|
JayJayDee/TypeGraphQL-TypeORM-Example
|
/src/configurations/config-loader.ts
| 2.59375
| 3
|
import { config } from 'dotenv';
export const loadConfigurations =
async (env: {[key: string]: any}) => {
let source: {[key: string]: any} = {};
// if the DOTENV_PATH environment variable exists, load the dotenv file.
const dotEnvPath = env['DOTENV_PATH'];
if (dotEnvPath) {
const parsed = config({ path: dotEnvPath }).parsed;
if (parsed) source = parsed;
else {
throw new Error(`dotenv file not found or malformed dotenv file: ${dotEnvPath}`);
}
} else {
source = env;
}
return source;
};
|
dd214304745f25b3c50c2f1e73ca26ae8a9eea27
|
TypeScript
|
thaihoanganh/vcc-schema
|
/src/datatype/__tests__/unknown.test.ts
| 2.546875
| 3
|
import { unknown, UnknownType } from "../";
describe("DataType Unknown", () => {
const subject = unknown();
it("should have instance of UnknownType", () => {
expect(subject).toBeInstanceOf(UnknownType);
expect(subject.parser("this value has unknown type")).toEqual(
"this value has unknown type"
);
});
});
|
13ecf1b317a9f0bfd30650211f419cffbd13ff80
|
TypeScript
|
HeyMilie/angular
|
/tour-of-heroes/src/app/hero.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import Hero from './types/hero.type';
@Injectable({
providedIn: 'root'
})
export class HeroService {
heroes: Hero[] = [
{ id : 1, name : 'Batman' },
{ id : 2, name : 'Superman' },
{ id : 3, name : 'Spiderman' }
];
constructor() { }
getHeroes() : Hero[]{
return this.heroes;
}
// getHeroById(id: number): Hero {
// return this.heroes.find((hero) => hero.id === id);
// }
}
|
f7668a675717718d61f747cc1ddddf2b2abb86b9
|
TypeScript
|
Whitecoin-XWC/pen-dashboard
|
/src/hooks/accounting.ts
| 2.578125
| 3
|
import { LastCashoutActionResponse } from '../penjs'
import { useEffect, useState } from 'react'
import { Token } from '../models/Token'
import { beeDebugApi } from '../services/bee'
import { Balance, Settlement, useApiPeerBalances, useApiSettlements } from './apiHooks'
interface UseAccountingHook {
isLoading: boolean
isLoadingUncashed: boolean
error: Error | null
totalsent: Token
totalreceived: Token
accounting: Accounting[] | null
}
export interface Accounting {
peer: string
uncashedAmount: Token
balance: Token
received: Token
sent: Token
total: Token
}
/**
* Merges the balances, settlements and uncashedAmounts arrays into single array which is sorted by uncashed amounts (if any)
*
* @param balances Balances for all peers
* @param settlements Settlements for all peers which has some settlement
* @param uncashedAmounts Array of getPeerLastCashout responses which is needed to calculate uncashed amount
*
* @returns
*/
function mergeAccounting(
balances: Balance[] | null,
settlements?: Settlement[],
uncashedAmounts?: LastCashoutActionResponse[],
): Accounting[] | null {
// Settlements or balances are still loading or there is an error -> return null
if (!balances || !settlements) return null
const accounting: Record<string, Accounting> = {}
balances.forEach(
// Some peers may not have settlement but all have balance (therefore initialize sent, received and uncashed to 0)
({ peer, balance }) =>
(accounting[peer] = {
peer,
balance,
sent: new Token('0'),
received: new Token('0'),
uncashedAmount: new Token('0'),
total: balance,
}),
)
settlements.forEach(
({ peer, sent, received }) =>
(accounting[peer] = {
...accounting[peer],
sent,
received,
total: new Token(accounting[peer].balance.toBigNumber.plus(received.toBigNumber).minus(sent.toBigNumber)),
}),
)
// If there are no cheques (and hence last cashout actions), we don't need to sort and can return values right away
if (!uncashedAmounts) return Object.values(accounting)
uncashedAmounts?.forEach(({ peer, uncashedAmount }) => {
accounting[peer].uncashedAmount = new Token(uncashedAmount)
})
return Object.values(accounting).sort((a, b) =>
b.uncashedAmount.toBigNumber.minus(a.uncashedAmount.toBigNumber).toNumber(),
)
}
export const useAccounting = (): UseAccountingHook => {
const settlements = useApiSettlements()
const balances = useApiPeerBalances()
const [err, setErr] = useState<Error | null>(null)
const [isLoadingUncashed, setIsloadingUncashed] = useState<boolean>(false)
const [uncashedAmounts, setUncashedAmounts] = useState<LastCashoutActionResponse[] | undefined>(undefined)
const error = balances.error || settlements.error || err
useEffect(() => {
// We don't have any settlements loaded yet or we are already loading/have loaded the uncashed amounts
if (isLoadingUncashed || !settlements.settlements || uncashedAmounts || error) return
setIsloadingUncashed(true)
const promises = settlements.settlements.settlements
.filter(({ received }) => received.toBigNumber.gt('0'))
.map(({ peer }) => beeDebugApi.chequebook.getPeerLastCashout(peer))
Promise.all(promises)
.then(setUncashedAmounts)
.catch(setErr)
.finally(() => setIsloadingUncashed(false))
}, [settlements, isLoadingUncashed, uncashedAmounts, error])
const accounting = mergeAccounting(balances.peerBalances, settlements.settlements?.settlements, uncashedAmounts)
return {
isLoading: settlements.isLoadingSettlements || balances.isLoadingPeerBalances,
isLoadingUncashed,
error,
accounting,
totalsent: settlements.settlements?.totalSent || new Token('0'),
totalreceived: settlements.settlements?.totalReceived || new Token('0'),
}
}
|