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
|
|---|---|---|---|---|---|---|
3ceefcb4879e203133eb1fa7d6be231d41c770bd
|
TypeScript
|
mdnaufalh/mit_placement
|
/backend/src/staff/infrastructure/repositories/CollegeRepository.ts
| 2.578125
| 3
|
import ICollegeRepository from "../../core/interfaces/ICollegeRepository";
import { course } from "../models";
import { Course } from "../../core/types";
class CollegeRepository implements ICollegeRepository {
async fetchAllCourses(collegeId: number): Promise<Array<Course>> {
return (
await course
.forge()
.query((queryBuilder: any) => {
queryBuilder
.join("department", "department.id", "=", "course.id")
.where("department.college", collegeId);
})
.fetchAll({ columns: ["course.id", "course.name"] })
).toJSON();
}
}
export default new CollegeRepository();
|
963e848b28ca084e2f8d19ed9e3abb6fb753cd50
|
TypeScript
|
hadrien-thomas-zenika/kata-rxjs
|
/src/app/users/users.repository.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { User } from './user';
import { delay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UsersRepository {
private users: User[] = [
{
id: 'user1',
name: 'john'
},
{
id: 'user2',
name: 'ursula'
},
{
id: 'user3',
name: 'tim'
},
{
id: 'user4',
name: 'margareth'
},
{
id: 'user5',
name: 'mick'
},
{
id: 'user6',
name: 'heloise'
},
{
id: 'user7',
name: 'jeanne'
},
{
id: 'user8',
name: 'david'
},
];
constructor() {
}
public getUsers(): Observable<User[]> {
return of(this.users).pipe(
delay(2000)
);
}
public getUser(id: string): Observable<User> {
const userToFind: User = this.users.find((user: User) => user.id === id);
return of(userToFind).pipe(
delay(1000 + Math.random() * 3000)
);
}
public createUser(name: string): void {
this.users = [
...this.users,
{
id: `id-${name}`,
name
}
];
}
}
|
29f274210625983c3232028622c92eec4a344d1e
|
TypeScript
|
UnicornInReverse/YoshisAdventure
|
/dev/behavior/moveVertical.ts
| 2.9375
| 3
|
class MoveVertical implements Behavior{
public yoshi : Yoshi;
public mh: MoveHorizontal;
public idle: Idle;
public dead: Dead;
public shoot: Shoot;
constructor(y : Yoshi){
this.yoshi = y;
}
public performBehavior() : void{
this.yoshi.div.style.transform = "translate(" + this.yoshi.x + "px," + this.yoshi.y + "px)";
}
public onGoUp(){
this.yoshi.y -= this.yoshi.jumpDirection = 3;
if (this.yoshi.y < 0){
this.yoshi.y = 0;
}
}
public onGoDown(){
this.yoshi.y += this.yoshi.jumpDirection = 3;
if (this.yoshi.y > 332){
this.yoshi.y = 332;
}
console.log("this is Y: " + this.yoshi.y);
}
public onGoForward(){
this.mh.onGoForward();
}
public onGoBack(){
this.mh.onGoBack();
}
public onIdle(){
this.yoshi.behavior = new Idle(this.yoshi);
}
public onDead(): void {
this.dead.onDead();
}
public onShoot(): void{
this.shoot.onShoot();
}
}
|
e09cab306ef2803da2853960838113ab99f23735
|
TypeScript
|
Cloudstek/alfred-hugo
|
/src/updater.ts
| 2.59375
| 3
|
import { Cache } from '@cloudstek/cache';
import moment from 'moment';
import readPkg from 'read-pkg-up';
import axios from 'axios';
import semver from 'semver';
import { LatestVersion, UpdateSource } from './types';
/**
* Hugo updater
*/
export class Updater {
private readonly cache: Cache;
private readonly interval: number | moment.Duration;
/**
* Hugo updater
*/
constructor(cache: Cache, interval: number | moment.Duration) {
this.cache = cache;
this.interval = interval;
}
/**
* Check for updates
*
* @param source Update source (npm or packal)
* @param pkg Package.json contents. When undefined, will read from file.
*/
public async checkUpdates(source: string, pkg?: any): Promise<LatestVersion | void> {
// Check update source
if (!UpdateSource[source as any]) {
throw new Error('Invalid update source.');
}
const latest = this.cache.get(`latest_version_${source}`) as LatestVersion | undefined;
const lastCheck = moment.unix(this.cache.get(`last_check_${source}`) as number).utc();
// Check for updates online
if (!latest) {
// Check if the interval is past
if (lastCheck.isValid() && lastCheck.add(this.interval).isSameOrAfter(moment.utc())) {
return undefined;
}
switch (source.toLowerCase()) {
case 'npm':
return this.checkNpm(pkg);
case 'packal':
return this.checkPackal();
}
}
// Got it from cache!
latest.checkedOnline = false;
return latest;
}
/**
* Check Packal for updates
*/
private async checkPackal(): Promise<LatestVersion | void> {
// Bundle ID
const bundleId = process.env.alfred_workflow_bundleid;
if (!bundleId) {
throw new Error('No bundle ID, not checking Packal for updates.');
}
// Set last check time
this.cache.set('last_check_packal', moment.utc().unix(), this.interval);
// Packal URL
const searchParam: string = encodeURIComponent('site:packal.org ' + bundleId);
const pkgUrl = `https://encrypted.google.com/search?sourceid=chrome&ie=UTF-8&q=${searchParam}&btnI`;
const latest = await axios.get(`https://github.com/packal/repository/blob/master/${bundleId}/appcast.xml`)
.then((response) => {
// Get version from XML
const versionMatches = response.data.match(/<version>(.+)<\/version>/);
if (!versionMatches || versionMatches.length !== 2) {
throw new Error('No version found.');
}
if (!semver.valid(semver.coerce(versionMatches[1]))) {
throw new Error('Invalid version in response.');
}
return {
version: versionMatches[1],
url: pkgUrl,
checkedOnline: true,
};
})
.catch((err) => {
if (err.response && err.response.status === 404) {
return;
}
throw err;
});
// Cache results
this.cache.set('latest_version_packal', latest, this.interval);
return latest;
}
/**
* Check NPM for updates
*
* @param pkg Package.json contents. When undefined, will read from file.
*/
private async checkNpm(pkg?: any): Promise<LatestVersion | void> {
// Get details from package.json
pkg = pkg || readPkg.sync().packageJson;
if (!pkg.name || !pkg.version) {
throw new Error('Invalid package.json.');
}
// Set last check time
this.cache.set('last_check_npm', moment.utc().unix(), this.interval);
// NPM URL
const pkgUrl = `https://www.npmjs.com/package/${pkg.name}`;
// Check for updates
const latest = await axios.get(`https://registry.npmjs.org/${pkg.name}`)
.then((response) => {
if (!response.data['dist-tags'].latest) {
throw new Error('No latest version found in response.');
}
if (!semver.valid(semver.coerce(response.data['dist-tags'].latest))) {
throw new Error('Invalid version in response.');
}
return {
version: response.data['dist-tags'].latest,
url: pkgUrl,
checkedOnline: true,
};
})
.catch((err) => {
if (err.response && err.response.status === 404) {
return;
}
throw err;
});
// Cache results
this.cache.set('latest_version_npm', latest, this.interval);
return latest;
}
}
|
306db5f3be9523705046a10f0ce42a87bd4eb2f8
|
TypeScript
|
brendan-codes/service-example
|
/src/app/form/form.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
// define some form objects
username = null;
altusername = null;
constructor(private _http: HttpService) { }
ngOnInit() {
}
// getUser for BehaviorSubject workflow, instead of trying to bring the data back
// we just want to update the BehaviorSubject.
getUser() {
console.log(this.username);
// tell the service to update behavior subject
this._http.retrieveUser(this.username);
this.username = null;
}
// getUser for Callback workflow, good for trying to bring data to a single component
getUserAlt() {
// make sure to pass arrow functions
this._http.getGithubUser(this.username, (data) => {
this.altusername = data;
console.log(this.altusername);
})
}
}
|
e9daafe9dc9a1cb97a90efa9a93fe8f71234f6ca
|
TypeScript
|
npmdoc-dev/npmdoc-generator
|
/src/helpers.ts
| 3.0625
| 3
|
import { request } from 'gaxios';
interface PackageMetadata {
latest: string;
}
/**
* Get the latest tag for a given npm module
* @param {string} package name of the package
* @returns The semver version with the latest tag
*/
export async function getLatest(packageName: string) {
if (!packageName) {
throw new Error('Package is required.');
}
const url = `http://registry.npmjs.org/-/package/${packageName}/dist-tags`;
const packageRes = await request<PackageMetadata>({ url });
const latest = packageRes.data.latest;
return latest;
}
/**
* Parse a path and return the package name and version
* @param {string} path The path portion of the url to parse
*/
export function extractFromRoute(path: string) {
const parts = path
.split('/')
.filter(x => x.length)
.slice(1);
let name;
let version;
if (parts[0].startsWith('@')) {
switch (parts.length) {
case 2:
name = parts.join('/');
break;
case 3:
name = parts.slice(0, 2).join('/');
version = parts[2];
break;
default:
throw new Error(`Malformed url: ${path}`);
}
} else {
switch (parts.length) {
case 1:
name = parts[0];
break;
case 2:
name = parts[0];
version = parts[1];
break;
default:
throw new Error(`Malformed url: ${path}`);
}
}
if (name) {
name = name.toLowerCase();
}
return { name, version };
}
|
c26bb3e8319a4011219ef94dabad32f8ac9a2860
|
TypeScript
|
prabhugopal/weather-mate
|
/src/models/city.ts
| 2.734375
| 3
|
type Cord = {
lon : number,
lat : number
}
type City = {
id: number,
name: string,
state: string,
country: string,
coord: Cord
}
export type Location = {
city: City
}
|
b382f5ae82e75069054ee534de6d1afcb24aeb94
|
TypeScript
|
molstar/molstar
|
/src/mol-model-props/computed/secondary-structure/dssp/turns.ts
| 2.65625
| 3
|
/**
* Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
*/
import { DSSPContext, DSSPType } from './common';
/**
* The basic turn pattern is a single H bond of type (i, i + n).
* We assign an n-turn at residue i if there is an H bond from CO(i) to NH(i + n),
* i.e., “n-turn(i)=: Hbond(i, i + n), n = 3, 4, 5.”
*
* Type: T
*/
export function assignTurns(ctx: DSSPContext) {
const { proteinInfo, hbonds, flags } = ctx;
const turnFlag = [DSSPType.Flag.T3S, DSSPType.Flag.T4S, DSSPType.Flag.T5S, DSSPType.Flag.T3, DSSPType.Flag.T4, DSSPType.Flag.T5];
for (let idx = 0; idx < 3; idx++) {
for (let i = 0, il = proteinInfo.residueIndices.length - 1; i < il; ++i) {
// check if hbond exists
if (hbonds.getDirectedEdgeIndex(i, i + idx + 3) !== -1) {
flags[i] |= turnFlag[idx + 3] | turnFlag[idx];
if (ctx.params.oldDefinition) {
for (let k = 1; k < idx + 3; ++k) {
flags[i + k] |= turnFlag[idx + 3] | DSSPType.Flag.T;
}
} else {
for (let k = 0; k <= idx + 3; ++k) {
flags[i + k] |= turnFlag[idx + 3] | DSSPType.Flag.T;
}
}
}
}
}
}
|
349f30051758d6b02a50c0e4554bfac2642d8e28
|
TypeScript
|
tomsoftware/Settlers.ts
|
/src/resources/gfx/index-file.ts
| 2.78125
| 3
|
import { BinaryReader } from '../file/binary-reader';
import { IndexFileItem } from './index-file-item';
import { ResourceFile } from './resource-file';
export class IndexFile extends ResourceFile {
protected offsetTable: Int32Array;
public get length(): number {
return this.offsetTable.length;
}
public getItems(start: number, length?: number): IndexFileItem[] {
const end = length == null ? this.length : start + length;
const list: IndexFileItem[] = [];
for (let i = start; i < end; i++) {
const item = this.getItem(i);
if (item) {
list.push(item);
}
}
return list;
}
public getItem(index: number): IndexFileItem | null {
const offset = this.offsetTable[index];
if (!offset) {
return null;
}
const l = this.offsetTable.length;
let lenght = -1;
for (let i = index + 1; i < l; i++) {
if (this.offsetTable[i]) {
lenght = this.offsetTable[i] - offset;
break;
}
}
return {
index,
offset: (offset - 20) >> 2,
lenght: lenght >> 2
};
}
constructor(resourceReader: BinaryReader) {
super();
const reader = this.readResource(resourceReader);
/// read the object offsets
const imageCount = reader.length / 4;
this.offsetTable = new Int32Array(imageCount);
for (let i = 0; i < imageCount; i++) {
this.offsetTable[i] = reader.readIntBE();
}
}
}
|
2f868371bfeca43cd89bac0d131df11583f1b2a6
|
TypeScript
|
dianas11/childToParentInteraction
|
/src/app/child/child.component.ts
| 2.8125
| 3
|
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
// step 4 to be able to send the emit event out to the parent component we decorate with @Output
// what we are doing in the child component is listening to the button click event and then sending out a custom
// event called greetEvent. the parent component can now catch this event and execute any piece of code.
@Output() greetEvent = new EventEmitter();
name = 'TheMadMuse';
constructor() { }
ngOnInit(): void {
}
// step 3, from this method we need to be able to send a message to the parent
//component to ask the parent component to execute the greet method
callParentGreet(){
this.greetEvent.emit(this.name);
}
}
|
13dcdc428c891a571acbcda1f81607316eede68a
|
TypeScript
|
FilipeNeiva/TC-ely
|
/atividade3/app/ts/personagens.ts
| 3.453125
| 3
|
class Personagem {
protected _id: number;
protected _nome: string;
protected _energia: number;
protected static id: number = 0;
constructor(nome: string){
this._energia = 100;
this._nome = nome;
this._id = Personagem.id;
Personagem.id += 1;
}
estaVivo(): boolean{
if(this._energia > 0) return true;
return false;
}
defenderAtaque(valorAtaque: number){
if(this._energia - valorAtaque < 0) this._energia = 0;
else this._energia -= valorAtaque;
}
get id(): number{
return this._id;
}
}
class Soldado extends Personagem{
protected _forcaAtaque: number;
constructor(nome: string, forcaAtaque){
if(forcaAtaque <= 10 && forcaAtaque > 0){
super(nome);
this._forcaAtaque = forcaAtaque;
}else{
console.error("forca de ataque acima de 10 ou abaixo de 1")
}
}
atacar(oponente: Personagem){
oponente.defenderAtaque(this._forcaAtaque);
}
defenderAtaque(valorAtaque: number){
if(this._energia - valorAtaque < 0) this._energia = 0;
else this._energia -= Math.round(valorAtaque/2);
}
}
class Cavaleiro extends Soldado{
constructor(nome: string, valorAtaque: number){
super(nome, valorAtaque);
}
atacar(oponente: Personagem){
oponente.defenderAtaque(this._forcaAtaque * 2);
}
defenderAtaque(valorAtaque: number){
if(this._energia - valorAtaque < 0) this._energia = 0;
else this._energia -= Math.round(valorAtaque/3);
}
}
export {Personagem, Soldado, Cavaleiro};
|
a4a8013b515c5b01ab2652e38212f2a41f92f04b
|
TypeScript
|
JoabsonDeSouza/livrocast
|
/src/utils/formatTime.ts
| 3.09375
| 3
|
export function calculateTotalValue(length: number) {
const minutes = Math.floor(length / 60);
const seconds_int = length - minutes * 60;
const seconds_str = seconds_int.toString();
const seconds = seconds_str.substr(0, 2);
const time = minutes + ':' + seconds;
const result =
(minutes < 10 ? '0' + minutes : minutes) +
':' +
(Number(seconds) < 10 ? '0' + seconds : seconds);
return result;
}
export function calculateCurrentValue(currentTime: number) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time =
(current_minute < 10 ? '0' + current_minute : current_minute) +
':' +
(Number(current_seconds) < 10 ? '0' + current_seconds : current_seconds);
return current_time;
}
|
6ee4093e41a40d00b8cf21b548075a0696455b77
|
TypeScript
|
allenli178/deno-algorithm
|
/challenges/leetcode/0-99/1-e-two-sum/brute-force-functional.ts
| 3.484375
| 3
|
/**
* Monday Jan 11, 2021, created by hylerrix
* Runtime: 148 ms, faster than 6.56% of TypeScript online submissions for Two Sum.
* Memory Usage: 45 MB, less than 11.29% of TypeScript online submissions for Two Sum.
*/
function twoSum(nums: number[], target: number): number[] {
let answer: number[] = []
nums.forEach((n, index1) => {
nums.slice(index1 + 1).some((m, index2) => {
if (n + m === target) {
answer = [index1, index1 + index2 + 1]
return true
}
})
})
return answer
}
export default twoSum
|
1a2b508f19dbd4c750478f75d1510a2f94f9edc2
|
TypeScript
|
aleclarson/ee-ts
|
/spec/ee.spec.ts
| 3.28125
| 3
|
/* tslint:disable:no-empty */
import { EventEmitter as EE } from '../src/ee'
interface A {
foo(): void
bar(a: number, b: number): number
}
test('nullish listeners', () => {
let ee = new EE<A>()
ee.on('foo', undefined)
ee.on({ foo: null })
expect(ee[EE.ev]).toEqual({})
})
/**
* Recurring listeners
*/
test('add a recurring listener', () => {
let ee = new EE<A>()
let fn = jest.fn()
expect(ee.on('foo', fn)).toBe(fn)
ee.emit('foo')
expect(fn.mock.calls.length).toBe(1)
ee.emit('foo')
expect(fn.mock.calls.length).toBe(2)
})
test('add multiple recurring listeners', () => {
let ee = new EE<A>()
let fn = jest.fn()
expect(
ee.on({
foo: fn,
bar: fn,
})
).toBe(ee)
ee.emit('foo')
ee.emit('bar', 1, 2)
ee.emit('foo')
ee.emit('bar', 3, 4)
expect(fn.mock.calls).toEqual([[], [1, 2], [], [3, 4]])
})
test('emit returns last return value (excluding undefined)', () => {
let ee = new EE<A>()
ee.on('bar', () => {})
ee.on('bar', () => 1)
ee.on('bar', () => {})
ee.on('bar', () => 2)
ee.on('bar', () => {})
expect(ee.emit('bar', 1, 2)).toBe(2)
})
/**
* One-time listeners
*/
test('add a one-time listener', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => {})
ee.one('foo', fn)
ee.on('foo', () => {})
ee.emit('foo')
expect(EE.count(ee, 'foo')).toBe(2)
expect(fn).toHaveBeenCalledTimes(1)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
})
test('add multiple one-time listeners', () => {
let ee = new EE<A>()
let f1 = ee.one('foo', jest.fn())
let f2 = ee.one('foo', jest.fn())
ee.emit('foo')
ee.emit('foo')
expect(f1).toHaveBeenCalledTimes(1)
expect(f2).toHaveBeenCalledTimes(1)
expect(EE.count(ee, 'foo')).toBe(0)
})
test('remove a one-time listener', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => {})
ee.one('foo', fn)
ee.on('foo', () => {})
ee.off('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(2)
})
test('multiple consecutive one-time listeners', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.one('foo', fn)
ee.one('foo', fn)
ee.emit('foo')
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(2)
expect(EE.count(ee, 'foo')).toBe(0)
})
/**
* Removed listeners
*/
test('remove a recurring listener', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => {})
ee.on('foo', fn)
ee.on('foo', () => {})
ee.off('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(2)
})
test('remove the only listener of an event', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', fn)
ee.off('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(0)
})
test('remove the first listener of an event', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', fn)
ee.on('foo', () => {})
ee.off('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(1)
})
test('remove the last listener of an event', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => {})
ee.on('foo', fn)
ee.off('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(1)
})
test('remove all listeners of an event', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => fn())
ee.on('foo', () => fn())
ee.on('foo', () => fn())
ee.off('foo')
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(0)
})
test('remove all listeners of all events', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => fn())
ee.on('bar', () => fn())
ee.off('*')
ee.emit('foo')
ee.emit('bar', 1, 2)
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(0)
expect(EE.count(ee, 'bar')).toBe(0)
})
test('remove current listener during emit', () => {
let ee = new EE<A>()
let fn = jest.fn(() => {
ee.off('foo', fn)
})
ee.on('foo', () => {})
ee.on('foo', fn)
ee.on('foo', () => {})
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
expect(EE.count(ee, 'foo')).toBe(2)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
})
test('remove pending listener during emit', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', () => ee.off('foo', fn))
ee.on('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(0)
expect(EE.count(ee, 'foo')).toBe(1)
})
test('remove finished listener during emit', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', fn)
ee.on('foo', () => ee.off('foo', fn))
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
expect(EE.count(ee, 'foo')).toBe(1)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
})
test('remove a listener that was added twice', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', fn)
ee.on('foo', () => ee.off('foo', fn))
ee.on('foo', fn)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
expect(EE.count(ee, 'foo')).toBe(1)
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
})
test('remove a listener that was never added', () => {
let ee = new EE<A>()
let fn = jest.fn()
ee.on('foo', fn)
ee.off('foo', () => {})
ee.emit('foo')
expect(fn).toHaveBeenCalledTimes(1)
})
/**
* Listeners iterable
*/
test('iterate over listeners', () => {
let ee = new EE<A>()
let fn1 = ee.on('foo', jest.fn())
let fn2 = ee.on('foo', jest.fn())
expect([...ee.listeners('foo')]).toEqual([fn1, fn2])
})
test('try iterating over event with no listeners', () => {
let ee = new EE<A>()
expect([...ee.listeners('foo')]).toEqual([])
})
/**
* Disposables
*/
test('pass an array to collect disposables', () => {
let ee = new EE<A>()
let list: Array<{ dispose(): void }> = []
let fn1 = ee.on('foo', jest.fn(), list)
let fn2 = ee.on('foo', jest.fn(), list)
ee.emit('foo')
// Dispose the first listener.
list[0].dispose()
ee.emit('foo')
expect(fn1).toBeCalledTimes(1)
expect(fn2).toBeCalledTimes(2)
// Dispose the second listener.
list[1].dispose()
ee.emit('foo')
expect(fn2).toBeCalledTimes(2)
})
test('disposables can be collected for listener maps', () => {
let ee = new EE<A>()
let list: Array<{ dispose(): void }> = []
let foo = jest.fn()
ee.on({ foo }, list)
ee.emit('foo')
// Dispose the listener.
list[0].dispose()
ee.emit('foo')
expect(foo).toBeCalledTimes(1)
})
/**
* Loose event names
*/
test('loose event names', () => {
interface B {
[type: string]: () => number
}
let ee = new EE<B>()
let result: number | void = ee.emit('whatever')
expect(result).toBe(undefined)
})
/**
* Static functions
*/
describe('has(ee, "*")', () => {
it('returns true if "ee" has any listeners', () => {
let ee = new EE<A>()
expect(EE.has(ee, '*')).toBeFalsy()
let foo = ee.on('foo', () => {})
expect(EE.has(ee, '*')).toBeTruthy()
ee.off('foo', foo)
expect(EE.has(ee, '*')).toBeFalsy()
ee.on('bar', () => {})
expect(EE.has(ee, '*')).toBeTruthy()
})
})
describe('has(ee, key)', () => {
it('returns true if "ee" has any listeners for the given event key', () => {
let ee = new EE<A>()
expect(EE.has(ee, 'foo')).toBeFalsy()
expect(EE.has(ee, 'bar')).toBeFalsy()
let foo = ee.on('foo', () => {})
expect(EE.has(ee, 'foo')).toBeTruthy()
expect(EE.has(ee, 'bar')).toBeFalsy()
ee.off('foo', foo)
expect(EE.has(ee, 'foo')).toBeFalsy()
expect(EE.has(ee, 'bar')).toBeFalsy()
ee.on('bar', () => {})
expect(EE.has(ee, 'foo')).toBeFalsy()
expect(EE.has(ee, 'bar')).toBeTruthy()
})
})
describe('keys(ee)', () => {
it('returns an array of event keys that have listeners', () => {
let ee = new EE<A>()
expect(EE.keys(ee)).toEqual([])
ee.on('foo', () => {})
expect(EE.keys(ee)).toEqual(['foo'])
ee.on('bar', () => {})
expect(EE.keys(ee)).toEqual(['foo', 'bar'])
})
})
describe('unhandle(ee, key, listener)', () => {
it('handles an event when no other listeners exist', () => {
let ee = new EE<A>()
let foo = jest.fn()
EE.unhandle(ee, 'foo', foo)
ee.emit('foo')
expect(foo).toBeCalledTimes(1)
let fn = ee.on('foo', jest.fn())
ee.emit('foo')
expect(fn).toBeCalledTimes(1)
expect(foo).toBeCalledTimes(1)
ee.off('foo', fn)
ee.emit('foo')
expect(foo).toBeCalledTimes(2)
})
})
/**
* _onEventHandled && _onEventUnhandled
*/
class Foo extends EE<A> {
handled: jest.Mock
unhandled: jest.Mock
constructor() {
super()
this.handled = jest.fn()
this.unhandled = jest.fn()
}
_onEventHandled<T extends keyof A>(type: T): void {
this.handled()
}
_onEventUnhandled<T extends keyof A>(type: T): void {
this.unhandled()
}
}
test('on() triggers _onEventHandled()', () => {
let ee = new Foo()
ee.on('foo', () => {})
expect(ee.handled).toBeCalled()
})
test('on({}) triggers _onEventHandled()', () => {
let ee = new Foo()
ee.on({
foo: () => {},
})
expect(ee.handled).toBeCalled()
})
test('one() triggers _onEventHandled()', () => {
let ee = new Foo()
ee.one('foo', () => {})
expect(ee.handled).toBeCalled()
})
test('one({}) triggers _onEventHandled()', () => {
let ee = new Foo()
ee.one({
foo: () => {},
})
expect(ee.handled).toBeCalled()
})
test('off() triggers _onEventUnhandled()', () => {
let ee = new Foo()
let fn = () => {}
// Remove an unknown listener.
ee.off('foo', fn)
expect(ee.unhandled).not.toBeCalled()
// Remove a known listener.
ee.on('foo', fn)
ee.off('foo', fn)
expect(ee.unhandled).toBeCalled()
// Remove all known listeners for a specific key.
ee.on('foo', fn)
ee.off('foo')
expect(ee.unhandled).toBeCalledTimes(2)
// Remove all known listeners.
ee.on('foo', fn)
ee.off('*')
expect(ee.unhandled).toBeCalledTimes(3)
})
test('emit() triggers _onEventUnhandled()', () => {
let ee = new Foo()
ee.one('foo', () => {})
ee.emit('foo')
expect(ee.unhandled).toBeCalled()
})
|
bb45b2b1e45a8b552a3ac28d7abbadd662cfd73a
|
TypeScript
|
chdtu-fitis/deanoffice-frontend
|
/src/app/components/grade/grade-runner/models/GradeRunners.ts
| 2.9375
| 3
|
import {Course} from './Course';
import {Student} from './Student';
export class GradeRunners {
courses: Course[] = [];
constructor(public student: Student) {}
addCourse(course: Course): void {
const foundCourse = this
.courses
.find(coursesItem => coursesItem.isEqual(course))
;
if (foundCourse) {
return;
}
this.courses.push(course);
}
removeCourse(course: Course): void {
const indexOfCourse = this
.courses
.findIndex(coursesItem => coursesItem.isEqual(course))
;
if (indexOfCourse !== -1) {
this.courses.splice(indexOfCourse, 1);
}
}
getCountCourses(): number {
return this.courses.length;
}
}
|
ce609e94d775f694e4016caa7b25963c4d88d77d
|
TypeScript
|
wreilly/email-fabricator
|
/src/app/hbsp/hbsp.service.ts
| 2.515625
| 3
|
/* tslint:disable:no-string-literal */
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {BehaviorSubject, Subject, Observable, ObservableInput, of, throwError} from 'rxjs';
import {catchError, map, tap } from 'rxjs/operators';
import { Store } from '@ngrx/store';
/* Nah - I think this 'UIReducer' level is wrong.
You want "fromRoot" (see other 2 Angular projects: fitness; recipes)
import * as fromUIReducer from '../shared/ui.reducer';
*/
import * as fromRoot from '../app.reducer';
import * as fromUIActions from '../shared/ui.actions';
import {ThreePropsUser} from './three-props-user.model';
import { environment } from '../../environments/environment';
import set = Reflect.set;
/*
@Injectable({
providedIn: 'root'
}) // t.b.d { providedIn: root }
*/
@Injectable() // Testing: providers: [] in CoreModule << seemstabe ok
export class HbspService {
/* We do still use (see note below).
Also: this is only seen on DotNext, not DotPipe.
Q. Why?
A. Because DotNext is a Component invoking a Service
to do HTTP call and .subscribe to the results and to
update (.next()) an Observable on the Service to which
the Component has .subscribed(), in its ngOnInit().
So, it is in the course of the Component processing the
Observable's data, in the Component, that we update
the Component's MatDataTableSource.
So, the Component's very first initialization *also*
updates the MatDataTableSource, with this "sample" record.
Hence we get "1 of 1" (whether empty '' string or 'sample')
Less mysterious to have visible 'sample'.
(you know, maybe debatable which is better way to go
re: UX confusion on this pretty tiny point.)
Maybe depends how much of a perfectionist one is.
O la!
DotPipe by contrast is a Component invoking a Service
to do HTTP call, and NOT to .subscribe() to it, but to
instead just directly *return* the received Observable.
That is done via RxJs .pipe().map() return.
This means the Component *must* do .subscribe on that
returned Observable, right when it gets it (not set up
earlier in ngOnInit()) - to access its data.
So, this Component never has an initial "empty" or "sample"
version of the MatTableDataSource to display on initialization.
sampleUserFromHbspServiceBAK: ThreePropsUser[] = [{
username: 'sample', // sample-fromService',
profile: {
email: 'record', // email-fromService',
institutionName: 'placeholder', // univ-fromService',
}
}];
*/
/* Urgh. Well, turns out this "invisible" entry is fine
for the table row (not seen), BUT, the durned
table "1 of 1" does display :o(
*/
sampleUserFromHbspService: ThreePropsUser[] = [{
username: '', // yeah works well as empty string
profile: {
email: '',
institutionName: '',
}
}];
/* */
private myHeatUserInfoObservableInService$ = new BehaviorSubject<any>(this.sampleUserFromHbspService);
currentUserInfoInService$ = this.myHeatUserInfoObservableInService$.asObservable();
// https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/
/* No Longer Used
isLoadingObservableInService$ = new Subject<boolean>();
*/
/*
Hmm, used by BOTH DotPipe and DotNext ? At least, when doing RxJs.
Now doing NgRx - comment out for both ? Hmm.
*/
constructor(
private myHttpClient: HttpClient,
private myStore: Store<fromRoot.MyOverallState>
) { }
giveMeHeatUsersDotNext(): void {
// Does **NOT** use ' | async'
// RxJs (used w. boolean back in Component)
/* No Longer Used?
this.isLoadingObservableInService$.next(true);
*/
// Now NgRx
this.myStore.dispatch(new fromUIActions.StartIsLoading());
// N.B. **NO** 'return' on next line
this.myHttpClient.get(
'https://services.hbsp.harvard.edu/api/admin/users/authorization-status/PENDING',
{
params: {
size: '115', // arbitrarily "big enough" magic number ;o)
},
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
Authorization: `Bearer ${environment['hbsp-admin-user-token']}`,
},
}
).subscribe(
(userInfoWeSubscribedToInService) => {
/* N.B. TSLint complaint:
"(no-string-literal)" allowed
['data']['users'][0]['username'] <<
I chose "Suppress no-string-literal for current file"
*/
// tslint:disable-next-line:max-line-length
console.log('NOGO 01-A ? GOES :o)userInfoWeSubscribedToInService[\'data\'][\'users\'][0][\'username\']) ', userInfoWeSubscribedToInService['data']['users'][0]['username']); // << Very nice. My buddy, arkangel.cordero
// tslint:disable-next-line:max-line-length
console.log('NIFTY 03 HEY (userInfoWeSubscribedToInService as any).data.users[0].username ', (userInfoWeSubscribedToInService as any)
.data.users[0].username); // nifty 03
this.myHeatUserInfoObservableInService$.next( (userInfoWeSubscribedToInService as any).data.users);
setTimeout(
// Kinda unneeded artificial delay, to ensure we see Spinner a bit...
() => {
// RxJs
/* No Longer Used
this.isLoadingObservableInService$.next(false);
*/
// NgRx
this.myStore.dispatch(new fromUIActions.StopIsLoading());
},
1000
);
},
(httpGetError) => {
console.log('httpGetError DotNext ', httpGetError);
// RxJs
/* No Longer Used
this.isLoadingObservableInService$.next(false);
*/
// NgRx
this.myStore.dispatch(new fromUIActions.StopIsLoading());
}
); // /.subscribe()
} // /giveMeHeatUsersDotNext()
giveMeHeatUsersDotPipe(): Observable<object[]> {
// USES ' | async'
// For "DotPipe" - no NgRx isLoading biz here.
// It's over in Component. (Contrast "DotNext")
// hmm y not here?
// NgRx
this.myStore.dispatch(new fromUIActions.StartIsLoading());
// N.B. **YES** a 'return' on next line.
return this.myHttpClient.get(
'https://services.hbsp.harvard.edu/api/admin/users/authorization-status/PENDING',
{
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${environment['hbsp-admin-user-token']}`,
},
params: {
size: '115'
}
}
).pipe(
map(
(fromTapToMap: any) => { // WR__ Warning bit loosey goosey w any
console.log('03 PIPE | MAP SERVICE HTTP-Land fromTapToMap.data.users ', fromTapToMap.data.users);
/* YES: we *return* an ARRAY
(as an Observable, MBU)
[{…}, {…}, {…}, ]
0: {username: "arkangel.cordero",...
*/
return fromTapToMap.data.users;
}
), // /map()
catchError(
// (err, caught). Can throw error?
// https://rxjs-dev.firebaseapp.com/api/operators/catchError
(httpGetErrorDotPipe): ObservableInput<any> => {
/* Q. Can I call that 'httpGetErrorDotPipe' ?
Or do I have to call it 'err' ?
A. t.b.d. Mebbe yah
*/
console.log('err as in httpGetErrorDotPipe ', httpGetErrorDotPipe);
/* Yep:
err as in httpGetErrorDotPipe
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized",
*/
// RxJs
/* No Longer Used
this.isLoadingObservableInService$.next(false);
*/
// NgRx
this.myStore.dispatch(new fromUIActions.StopIsLoading());
/* No. Error message is not what you want to 'return' to
calling function in Component. No way.
*/
return of(httpGetErrorDotPipe); // ? NO
/* Didn't work hmm.
return throwError(httpGetErrorDotPipe);
*/
}
) // /catchError()
); // /.pipe()
} // /giveMeHeatUsersDotPipe()
}
|
fcc4cb00c8f0779fb7611ab736d16c1d15ded4ce
|
TypeScript
|
AuHau/bee-js
|
/src/utils/data.ts
| 2.515625
| 3
|
import { Readable } from 'stream'
// eslint-disable-next-line require-await
export async function prepareData (
data: string | Buffer | Readable
): Promise<Buffer | Readable> {
if (typeof data === 'string') {
return Buffer.from(data)
}
return data
}
|
18f1950a16628b64394192ec8db09bed26fbef5e
|
TypeScript
|
wu-ToStar/Web-base
|
/TypeScript/03类/src/05接口.ts
| 4.15625
| 4
|
(() => {
type myType = {
name: string;
age: number;
};
const obj: myType = {
name: "to",
age: 1,
};
/**
* 接口可以在定义的时候去限制类的结构
* 接口的所有的属性都不能有实际的值
* 接口只定义对象的结构,而不考虑实际值
* 在接口中所有的方法都是抽象方法
*/
interface myInterface {
name: string;
age: number;
}
interface myInterface {
gender: string
}
const obj2: myInterface = {
name: "to",
age: 25,
gender: "男"
};
/**
* 定义类时,可以使类去实现有关接口
* 实现接口就是满足接口的需求
*
*/
interface my{
name: string;
say():void
}
class MyClass implements my{
name: string
constructor(name: string) {
this.name=name
}
say() {
console.log("hi")
}
}
})();
|
c9aa08e804af33ccff9300048996fed12e96f44a
|
TypeScript
|
isabella232/sourcegraph-vscode
|
/src/git.ts
| 2.921875
| 3
|
import execa from 'execa'
import * as path from 'path'
import { log } from './log'
import { getRemoteUrlReplacements } from './config'
/**
* Returns the names of all git remotes, e.g. ["origin", "foobar"]
*/
async function gitRemotes(repoDir: string): Promise<string[]> {
const { stdout } = await execa('git', ['remote'], { cwd: repoDir })
return stdout.split('\n')
}
/**
* Returns the remote URL for the given remote name.
* e.g. `origin` -> `git@github.com:foo/bar`
*/
async function gitRemoteURL(repoDir: string, remoteName: string): Promise<string> {
let { stdout } = await execa('git', ['remote', 'get-url', remoteName], { cwd: repoDir })
const replacementsList = getRemoteUrlReplacements()
for (const r in replacementsList) {
if (typeof r === 'string') {
stdout = stdout.replace(r, replacementsList[r])
}
}
return stdout
}
/**
* Returns the remote URL of the first Git remote found.
*/
async function gitDefaultRemoteURL(repoDir: string): Promise<string> {
const remotes = await gitRemotes(repoDir)
if (remotes.length === 0) {
throw new Error('no configured git remotes')
}
if (remotes.length > 1) {
log.appendLine(`using first git remote: ${remotes[0]}`)
}
return await gitRemoteURL(repoDir, remotes[0])
}
/**
* Returns the repository root directory for any directory within the
* repository.
*/
async function gitRootDir(repoDir: string): Promise<string> {
const { stdout } = await execa('git', ['rev-parse', '--show-toplevel'], { cwd: repoDir })
return stdout
}
/**
* Returns either the current branch name of the repository OR in all
* other cases (e.g. detached HEAD state), it returns "HEAD".
*/
async function gitBranch(repoDir: string): Promise<string> {
const { stdout } = await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repoDir })
return stdout
}
/**
* Returns the Git repository remote URL, the current branch, and the file path
* relative to the repository root. Empty strings are returned if this cannot be
* determined.
*/
export async function repoInfo(filePath: string): Promise<[string, string, string]> {
let remoteURL = ''
let branch = ''
let fileRel = ''
try {
// Determine repository root directory.
const fileDir = path.dirname(filePath)
const repoRoot = await gitRootDir(fileDir)
// Determine file path, relative to repository root.
fileRel = filePath.slice(repoRoot.length + 1)
remoteURL = await gitDefaultRemoteURL(repoRoot)
branch = await gitBranch(repoRoot)
if (process.platform === 'win32') {
fileRel = fileRel.replace(/\\/g, '/')
}
} catch (e) {
log.appendLine(`repoInfo(${filePath}): ${e}`)
}
log.appendLine(`repoInfo(${filePath}): remoteURL="${remoteURL}" branch="${branch}" fileRel="${fileRel}"`)
return [remoteURL, branch, fileRel]
}
|
7e6f989a2a751e7d3122881765094cc4f1bea94c
|
TypeScript
|
alzuma/hotbark
|
/src/DI/ServiceDecorator.ts
| 2.625
| 3
|
import { GenericClassDecorator } from './GenericClassDecorator';
import { Type } from './Type';
export const Service = (): GenericClassDecorator<Type<object>> => {
return (target: Type<object>) => {
// do something with `target`, e.g. some kind of validation or passing it to the Injector and store them
};
};
|
ad53b134afd7dd2716e258996bb499a09ba9bed9
|
TypeScript
|
alvarezGarciaMarcos/git-repo-creator
|
/src/utils/configuration/configuration-utils.ts
| 2.875
| 3
|
import * as path from 'path'
import * as fs from 'fs-extra'
import Command from '@oclif/command';
import { IRepoConfig } from './config';
import { ConfigurationType } from './config';
interface AppConfiguration {
github: IRepoConfig;
gitlab: IRepoConfig;
bitbucket: IRepoConfig;
}
export class Configuration {
static async deleteConfiguration(ctx: Command, type: ConfigurationType){
let emptyConfig: AppConfiguration = this.getBaseConfig()
await this.saveConfiguration(ctx, emptyConfig.gitlab, type);
}
static async saveConfiguration(ctx: Command, config: IRepoConfig, type: ConfigurationType) {
let configuration: AppConfiguration = await this.getConfiguration(ctx)
let newConfiguration: IRepoConfig = config
switch(type) {
case "Github":
configuration.github = newConfiguration
break;
case "Gitlab":
configuration.gitlab = newConfiguration
break;
default:
configuration.bitbucket = newConfiguration
break;
}
this.writeConfiguration(ctx, configuration)
}
private static async writeConfiguration(ctx: Command, configuration: AppConfiguration) {
let filePath = path.join(ctx.config.configDir, 'config.json')
fs.writeFile(filePath, JSON.stringify(configuration))
}
static async getGithubConfiguration(ctx: Command): Promise< IRepoConfig> {
let configuration = await this.getConfiguration(ctx);
return configuration.github;
}
static async getGitlabConfiguration(ctx: Command): Promise<IRepoConfig> {
let configuration = await this.getConfiguration(ctx);
return configuration['gitlab'];
}
static async getBitbucketConfiguration(ctx: Command): Promise<IRepoConfig> {
let configuration = await this.getConfiguration(ctx);
return configuration['bitbucket'];
}
static async getConfiguration(ctx: Command): Promise<AppConfiguration> {
let filePath = path.join(ctx.config.configDir, 'config.json')
let userConfig: Promise<AppConfiguration>
if(await fs.pathExists(filePath)) {
userConfig = await fs.readJSON(filePath)
} else {
// Config file not created, let's create it
let baseConfig = this.getBaseConfig()
await fs.createFile(filePath)
await fs.writeFile(filePath, JSON.stringify(baseConfig))
// We read the created configuration
userConfig = await fs.readJSON(filePath)
}
return userConfig;
}
static async getConfigurationByType(ctx: Command, type: ConfigurationType): Promise<IRepoConfig> {
let configuration: AppConfiguration = await this.getConfiguration(ctx)
switch(type) {
case "Github":
return configuration.github
case "Gitlab":
return configuration.gitlab
default:
return configuration.bitbucket
}
}
private static getBaseConfig(): AppConfiguration {
return {
github: {
apiKey: undefined,
username: undefined
},
gitlab: {
apiKey: undefined,
username: undefined
},
bitbucket: {
apiKey: undefined,
username: undefined
}
}
}
}
|
a9a6c912c56c3a41aa0b9612564f52009259bc00
|
TypeScript
|
krakenui/octopus-mongo
|
/src/common/helper.ts
| 3.484375
| 3
|
export function randomString(length: number): string {
let result: string = "";
let characters: string =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let charactersLength: number = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export function isNullOrEmpty(str: string): boolean {
return str == null || str.length === 0;
}
|
376276aae02fcc5e9b4c892ebb798e51195fc6cf
|
TypeScript
|
srichandmalladi/CorporateQnA
|
/CorporateClient/src/app/models/answer.model.ts
| 2.6875
| 3
|
export class Answer {
id: number;
userId: number;
questionId: number;
description: string;
dateCreated: Date;
isBestAnswer: boolean;
constructor(args) {
this.id = +(args.id || 0);
this.userId = +(args.userId || localStorage['userId']);
this.questionId = +args.questionId;
this.description = args.description;
this.dateCreated = args.dateCreated;
this.isBestAnswer = args.isBestAnswer;
}
}
|
6b58cbfdbd651259bb77b8442eff2aa69c63d1ad
|
TypeScript
|
Jubrillionaire/user-hobbies
|
/backend/controllers/hobbies-controller.ts
| 2.65625
| 3
|
import { Request, Response } from 'express';
import Hobby from '../models/Hobby';
import User from '../models/User';
const getAllHobbies = async (req: Request, res: Response) => {
const id: string = req.params.id;
try {
const hobbies = await Hobby.find({user: id});
return res.status(200).json({ hobbies });
} catch (error) {
return res.send("unable to get hobbies");
}
}
const deleteHobby = async (req: Request, res: Response) => {
try {
const id: string = req.params.id;
const user_id: string = req.params.user_id
const user = await User.findOne({ _id: user_id })
user.hobbies.filter(i => i._id == user_id)
await user.save()
const deleted = await Hobby.findByIdAndDelete(id);
return res.status(204).send({msg: "Hobby deleted", deleted});
} catch (error) {
return res.send(error)
}
};
const createHobby = async (req: Request, res: Response) => {
const id: string = req.params.user_id;
const body: {
passionLevel: string,
name: string,
year: number
user: string
} = req.body ?? null;
try {
const user = await User.findOne({_id: body.user})
const createdHobby = await Hobby.create(body);
user.hobbies.push(createdHobby._id)
await user.save()
return res.status(201).json({
createdHobby,
});
} catch (error) {
return res.send(error)
}
}
export {
createHobby,
getAllHobbies,
deleteHobby
}
|
aae6f89139681104e3b3d7ce2e413ddfae362045
|
TypeScript
|
ozzyjones/eslint-string-wrapper
|
/src/StringWrapper.ts
| 3.15625
| 3
|
'use strict';
import { JavascriptExpressionParser } from './JavascriptExpressionParser';
import { StringExpression } from './StringExpression';
import { StringExpressionParser } from './StringParser';
import { VSCodeExtensions } from './VSCodeExtensions';
export class StringWrapper {
private quoteCharacter: string;
private _strExpression: StringExpression;
private _suffix: string;
/**
* Wrap a string onto multiple lines
*
* @param {string} inputStr String to be wrapped
* @param {number} maxLineLength The length of the string content at which to wrap the string
* @returns {string} Wrapped string
*/
public wrapString(inputStr: string, maxLineLength: number): string {
if (maxLineLength < 1) {
throw new Error(`Max line length must be 1 or greater. Given: ${maxLineLength}`);
}
const chunkSize = Math.floor(maxLineLength || 120);
const jsParser = new JavascriptExpressionParser();
const jsExpression = jsParser.parseExpression(inputStr);
const isJavascriptExpression = (jsExpression !== null);
if (isJavascriptExpression) {
inputStr = jsExpression.getContents();
this._setQuoteCharacter(jsExpression.getQuoteChar());
} else {
const strParser = new StringExpressionParser();
this._strExpression = strParser.parseExpression(inputStr);
const isStringExpression = (this._strExpression !== null);
if (isStringExpression) {
inputStr = this._strExpression.getContents();
this._suffix = this._strExpression.getSuffix();
this._setQuoteCharacter(this._strExpression.getQuoteChar());
} else {
throw new Error('Input is not a valid Javascript expression or string expression.');
}
}
const pieces = this._chunkString(inputStr, chunkSize);
const wrappedString = this._join(pieces, this.quoteCharacter);
let writeStr = wrappedString;
if (isJavascriptExpression) {
writeStr = jsExpression.getType() + ' ' + jsExpression.getVarname() + ' = \n' +
wrappedString + jsExpression.getSuffix();
} else {
writeStr = `\n${wrappedString}${this._suffix}`;
}
return writeStr;
}
private _chunkString(str: string, len: number): string[] {
const size = Math.ceil(str.length / len);
const ret = new Array(size);
let offset;
for (let i = 0; i < size; i++) {
offset = i * len;
ret[i] = str.substring(offset, offset + len);
}
return ret;
}
private _join(pieces: string[], quoteCharacter: string): string {
let s = '';
for (let i = 0; i < pieces.length; i++) {
const line = pieces[i];
s += `${quoteCharacter}${line}${quoteCharacter}`;
if (i !== pieces.length - 1) {
s += ' +\n';
}
}
return s;
}
private _setQuoteCharacter(quoteCharacter: string) {
this.quoteCharacter = quoteCharacter;
}
}
|
cb842ae4402384a262a5cca3e463944d28313c0b
|
TypeScript
|
tschm2/eMMA
|
/ConversationalUI/src/pages/about/about.ts
| 2.765625
| 3
|
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BarcodeScanner } from 'ionic-native';
@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
constructor(public navCtrl: NavController) {
}
showThis(elem) {
BarcodeScanner.scan().then((barcodeData) => {
console.log(barcodeData);
}, (err) => {
// An error occurred
});
class Base64 {
private PADCHAR: string = '=';
private ALPHA: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
private getByte(s: string, i: number): number {
const x = s.charCodeAt(i);
return x;
}
private getByte64(s: string, i: number): number {
const idx = this.ALPHA.indexOf(s.charAt(i));
return idx;
}
public decode (s: string): string {
let pads = 0,
i, b10, imax = s.length,
x = [];
s = String(s);
if (imax === 0) {
return s;
}
if (s.charAt(imax - 1) === this.PADCHAR) {
pads = 1;
if (s.charAt(imax - 2) === this.PADCHAR) {
pads = 2;
}
imax -= 4;
}
for (i = 0; i < imax; i += 4) {
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12) | (this.getByte64(s, i + 2) << 6) | this.getByte64(s, i + 3);
x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255, b10 & 255));
}
switch (pads) {
case 1:
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12) | (this.getByte64(s, i + 2) << 6);
x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255));
break;
case 2:
b10 = (this.getByte64(s, i) << 18) | (this.getByte64(s, i + 1) << 12);
x.push(String.fromCharCode(b10 >> 16));
break;
}
return x.join('');
}
public encode(s: string): string {
s = String(s);
let i, b10, x = [],
imax = s.length - s.length % 3;
if (s.length === 0) {
return s;
}
for (i = 0; i < imax; i += 3) {
b10 = (this.getByte(s, i) << 16) | (this.getByte(s, i + 1) << 8) | this.getByte(s, i + 2);
x.push(this.ALPHA.charAt(b10 >> 18));
x.push(this.ALPHA.charAt((b10 >> 12) & 63));
x.push(this.ALPHA.charAt((b10 >> 6) & 63));
x.push(this.ALPHA.charAt(b10 & 63));
}
switch (s.length - imax) {
case 1:
b10 = this.getByte(s, i) << 16;
x.push(this.ALPHA.charAt(b10 >> 18) + this.ALPHA.charAt((b10 >> 12) & 63) + this.PADCHAR + this.PADCHAR);
break;
case 2:
b10 = (this.getByte(s, i) << 16) | (this.getByte(s, i + 1) << 8);
x.push(this.ALPHA.charAt(b10 >> 18) + this.ALPHA.charAt((b10 >> 12) & 63) + this.ALPHA.charAt((b10 >> 6) & 63) + this.PADCHAR);
break;
}
return x.join('');
}
}
let test = new Base64();
var dada = "H4sIAAAAAAAEAK1UzW7aQBB+lY2vsaNd24DNLQmhRQktIrSRWuWwtge8wl6j9bpNQLxNHqO3vFhn7TglAXKqhPF4Z3bmm29+NtZ5pVOrb/W6lFHqudQPOz3LtgYaD13Kug6jDgtmLOgzr+95p9TtU4oGowQNIt+bh91o7vjzwHV8CCMn5FHghDGN58E86PDQOBtDMntcgdVntSxinoPUpdX/ubHOV6uRLLVCb5LHKUkgJ1dlCbKN4fshY14TsvHi2dakaG4P8J/Z1Mbn3oAeqiJvgdMQf3Uqs2LnjIXWFm0nqoyji0dUDNQZ+VJoMlRcrm3zqkDOIUvw7rTgaDH5iuJsuZiWEr9GqFxqURiE36QwRN3Orq2tvWkAuwGjXtf/GDA9BNhzKDsA7lytNfnMZWmT8fMfGacgU141FB0CeJFhTYs4TVQVL4+AZKHb890PWKXHWP1PIC/TIoNSgxISjZag9oHutkaliDjLz2xipKRS2CnC6CoBSgOZgCoLCfKk7RqXscD3jqfnHqxBx2EMMzyQ3tUDz1cZkGuuMpvcPT/JhXjNbDR+Qz+oKhWLSi7+pTS+eZ9RBIJcQMLVHK1wCAscjHpAavg4AWLxW8RLyHZyYPslOthHL40/klNAa2ayeUU3FBDtku3sARMlWVck5w9nxMdXRvTz0yITyDgjMx5loJFwEFJCmtfl3UPv97oe83pH2P8QKyKdNWZFY0a392+r8X5THWqu2xihqTW8H1HjiGuBy8fqb6yLesmx0PfqsjM0vhTaxLjjWWIy1k0Rh19wYZkgoGvqPoFMUDBob15U46psdDd4A1vmqll7JszgptRjMLDqM97Q8FrRBp9rW995hjYBqwvSqN1WzVo1C2idxjSuvYwa1qf40en17tvxdlvBawW/FTqt0G2vMSR4i8SkOEAY4dRnpBcS5nrE75CuofhWKwDdtPYCu4TjfibMbLgfYoXHoRviUkV/+dLkDoq8sExEqcmvIidm6y+5WZrlKuOSRLAAYRjTJ9b2LyrDpWuFBgAA";
var dada = test.decode(dada);
console.log(dada);
var itemToShow = document.getElementById(elem);
console.log(itemToShow);
}
}
|
8cb2ca0c7d52b9da9e6a0cf1f3ca4c8dbee57906
|
TypeScript
|
hfaulds/athena
|
/src/entities/Asteroid.ts
| 2.515625
| 3
|
import { Vec2, Polygon } from 'planck-js'
import Entity from './Entity'
import rand from '../util/rand'
export default class Asteroid extends Entity {
static createRandom(assets, components, position, world) {
var asteroidTextures = Object.keys(assets["textures"]["meteors"]);
var textureName = asteroidTextures[
Math.floor(Math.random() * asteroidTextures.length)
];
var velocity = Vec2(rand(0.1), rand(0.1));
var bodyAttributes= {
type : 'dynamic',
angularDamping : 5.0,
linearVelocity : velocity,
position : position,
};
var fixtureAttributes = {
density: 1000,
};
return new Asteroid(
assets,
world,
bodyAttributes,
components,
fixtureAttributes,
textureName
);
}
}
|
6a982434fec964686bf04c1d5e9074b8315b5810
|
TypeScript
|
nervosnetwork/neuron
|
/packages/neuron-wallet/src/models/chain/block-header.ts
| 2.84375
| 3
|
import TypeChecker from '../../utils/type-checker'
export default class BlockHeader {
public version: string
public timestamp: string
public hash: string
public parentHash: string
public number: string
public epoch: string
constructor(version: string, timestamp: string, hash: string, parentHash: string, number: string, epoch: string) {
// convert to regular string
this.version = BigInt(version).toString()
this.timestamp = BigInt(timestamp).toString()
this.number = BigInt(number).toString()
this.epoch = BigInt(epoch).toString()
this.hash = hash
this.parentHash = parentHash
TypeChecker.hashChecker(this.hash, this.parentHash)
TypeChecker.numberChecker(this.version, this.timestamp, this.number, this.epoch)
}
public static fromSDK(header: CKBComponents.BlockHeader): BlockHeader {
return new BlockHeader(
header.version,
header.timestamp,
header.hash,
header.parentHash,
header.number,
header.epoch
)
}
}
|
29082e133f281deb2b7482e751d84c00322854e5
|
TypeScript
|
navikt/syfooversikt
|
/test/utils/veiledereUtils.test.ts
| 2.625
| 3
|
import { expect } from 'chai';
import { filterVeiledereWithActiveOppgave } from '@/utils/veiledereUtils';
import { PersonOversiktStatusDTO } from '@/api/types/personoversiktTypes';
describe('veiledere utils', () => {
describe('filterVeiledereWithActiveOppgave', () => {
it('Returns empty list if no oppgaver', () => {
const veiledere = [
{
ident: 'Z999999',
fornavn: 'Vei',
etternavn: 'Leder',
},
];
const personOversiktStatus = [] as PersonOversiktStatusDTO[];
const veiledereWithOppgaver = filterVeiledereWithActiveOppgave(
veiledere,
personOversiktStatus
);
expect(veiledereWithOppgaver.length).to.equal(0);
});
it('Returns list of veiledere with tildelte personer', () => {
const tildeltVeileder = 'Z999999';
const veiledere = [
{
ident: tildeltVeileder,
fornavn: 'Vei',
etternavn: 'Leder',
},
{
ident: 'X000000',
fornavn: 'Ingen',
etternavn: 'Oppgaver',
},
];
const personOversiktStatus = [
{
veilederIdent: tildeltVeileder,
},
] as PersonOversiktStatusDTO[];
const veiledereWithOppgaver = filterVeiledereWithActiveOppgave(
veiledere,
personOversiktStatus
);
expect(veiledereWithOppgaver.length).to.equal(1);
expect(veiledereWithOppgaver[0]?.ident).to.equal(tildeltVeileder);
});
});
});
|
5a7f789d7628e3d1b247910118bfa0f5facd10dc
|
TypeScript
|
alexsando86/covid19-practice
|
/src/util/MakeRandomColor.ts
| 3.078125
| 3
|
class MakeRandomColor {
count: number;
colorArray: string[];
constructor(count: number) {
this.count = count;
this.colorArray = [];
}
randomColor() {
return Math.floor(Math.random() * 255);
}
setRgbaColor() {
for (let i = 0; i < this.count; i++) {
this.colorArray.push(`rgba(${this.randomColor()},${this.randomColor()},${this.randomColor()}, 0.6)`);
}
return this.colorArray;
}
}
export default MakeRandomColor;
|
79784f65be35f3cd0c0d33a25b8b1b7b780ac92b
|
TypeScript
|
umardev500/tracking-dockerize
|
/client/helpers/saveState.ts
| 2.828125
| 3
|
export interface StateProps {
state: any;
}
export const saveState = ({ state }: StateProps): void => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch (err) {
// Ignore error
}
};
|
4154b6cbde32ed9867586c62ea4296d109763990
|
TypeScript
|
hggntg/base
|
/utilities/.generated/src/add-try-catch-wrapper.ts
| 3.15625
| 3
|
export function addTryCatchWrapper(ClassImp: any, funcName){
let func: Function = ClassImp.prototype[funcName];
let funcString = func.toString();
let paramsString = funcString.split("(")[1].split(")")[0];
let expression = `ClassImp.prototype["${funcName}"] = function ${funcName}(${paramsString}){
try{
return func.apply(this, arguments);
}
catch(e){
console.error(e);
}
}`;
eval(expression);
}
|
92412d8b2d11fd569fad1068f230d46a62425a16
|
TypeScript
|
Amarilo/vacation-planner
|
/src/app/services/vacation/vacation.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { DatabaseService } from '../database/database.service';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class VacationService {
totalVacations = 20;
publicHolidays: any = [];
years: any = [];
yearsEmitter: Subject<any> = new Subject();
constructor(private dbService: DatabaseService) {
this.getPublicHolidays().then().catch(
(err) => console.error(err)
);
this.getYears();
}
async getPublicHolidays() {
try {
this.publicHolidays = await this.dbService.getPublicHolidays();
} catch (error) {
throw error;
}
}
getYears() {
this.dbService.getYears().then((years) => {
this.years = years;
this.yearsEmitter.next(years)
});
}
insertYear(year) {
this.dbService.insertYear(year).then(() => {
this.getYears()
}).catch((err) =>
console.error(err)
);
}
updateYear(year) {
this.dbService.updateYear(year).then(() => {
this.getYears()
}).catch((err) =>
console.error(err)
);
}
deleteYear(year) {
this.dbService.deleteYear(year).then(() => {
this.getYears()
}).catch((err) =>
console.error(err)
);
}
calcBusinessDays(startDate, endDate) {
let day = startDate;
let businessDays = {};
while (day.isSameOrBefore(endDate,'day')) {
if (!this.isFreeDay(day)) {
if(businessDays[day.year()]) {
businessDays[day.year()]++;
} else {
businessDays[day.year()] = 1;
}
};
day.add(1,'d');
}
return businessDays;
}
isFreeDay(day) {
return day.day()==0 || day.day()==6 || this.publicHolidays.includes(day.format('YYYY-MM-DD'));
}
getVacationInfo(start, end, takenVacationDays, current_vacationDays) {
let businessDays = this.calcBusinessDays(start, end);
let vacationDays = 0;
for(let year in businessDays) {
let vacationInc = this.round(this.totalVacations / this.getTotalBusinessDays(year),2);
vacationDays += businessDays[year] * vacationInc;
}
vacationDays = this.round(vacationDays, 2);
let vacationsRemaining = vacationDays - takenVacationDays + current_vacationDays;
vacationsRemaining = this.round(vacationsRemaining, 2);
return {
previously_had: current_vacationDays,
taken: takenVacationDays,
remaining: vacationsRemaining,
gathered: vacationDays
};
}
round(number, decimals) {
const multiplier = Math.pow(10, decimals);
return Math.round(number * multiplier) / multiplier;
}
getTotalBusinessDays(year) {
for(let item of this.years){
if(item.year == year) {
return item.business_days;
}
}
return NaN;
}
async toggleHolidays(dayArray) {
try {
let holidaysToRemove = [];
let holidaysToAdd = [];
dayArray.forEach(element => {
let elementPlace = this.publicHolidays.indexOf(element);
if(elementPlace > -1) {
holidaysToRemove.push(element);
} else {
holidaysToAdd.push(element);
}
});
await this.dbService.deletePublicHolidays(holidaysToRemove);
await this.dbService.insertPublicHolidays(holidaysToAdd);
await this.getPublicHolidays();
} catch (error) {
throw error;
}
}
}
|
eae95fdf0d16f0e2799f986a59b6956d9a2bc049
|
TypeScript
|
wdpm/vue-shop
|
/src/utils/DateFormat.ts
| 3.4375
| 3
|
// 格式化日期(和时间)
class DateFormat {
// format 参数可以由以下格式组合:
/*
YYYY
YY
MM
MMM
MMMM
DD
hh
mm
ss
*/
// 区分大小写;可以添加空格或其他符号;不要使用上面未包含的格式。
// 参考资料:
// https://www.w3.org/TR/NOTE-datetime
// https://en.wikipedia.org/wiki/Date_format_by_country
public static format(
date: string | number | Date,
format = 'YYYY-MM-DD'
) {
// 生成年、月、日、时、分、秒
const _date = new Date(date)
const YYYY = _date.getFullYear().toString()
const YY = YYYY.substring(YYYY.length - 2, YYYY.length)
const MM = (_date.getMonth() + 1).toString().padStart(2, '0')
const MMM = this.months[_date.getMonth()]
const MMMM = this.Months[_date.getMonth()]
const DD = _date.getDate().toString().padStart(2, '0')
const hh = _date.getHours().toString().padStart(2, '0')
const mm = _date.getMinutes().toString().padStart(2, '0')
const ss = _date.getSeconds().toString().padStart(2, '0')
// 对格式字符串进行替换
let r = format
r = r.replace('YYYY', YYYY)
r = r.replace('YY', YY)
r = r.replace('MMMM', MMMM)
r = r.replace('MMM', MMM)
r = r.replace('MM', MM)
r = r.replace('DD', DD)
r = r.replace('hh', hh)
r = r.replace('mm', mm)
r = r.replace('ss', ss)
return r
}
private static readonly months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sept',
'Oct',
'Nov',
'Dec'
]
private static readonly Months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
}
export { DateFormat }
|
d61aa8f4472da640822af3d38d171a152edcd374
|
TypeScript
|
FIFALibrary/dbmaster-cli
|
/lib/utils/aggregate.utils.ts
| 3.015625
| 3
|
import { RawData } from '../interfaces';
export interface Aggregated {
value: string | number;
count: number;
}
export const aggregateFn = (agg: Aggregated[], data: RawData, field: string): void => {
const value = data[field];
const index = agg.findIndex((f) => f.value === value);
if (index === -1) {
agg.push({ value, count: 1 });
} else {
agg[index] = { ...agg[index], count: agg[index].count + 1 };
}
};
export const sortAggregateFn = (a: Aggregated, b: Aggregated) => b.count - a.count;
|
5560d06c037c5bcdb45f27b39832d3a39452d4c6
|
TypeScript
|
a-wizard-work/FontBundles-Converter
|
/src/utils/api-client.ts
| 2.65625
| 3
|
const apiClient = (
url: string,
{
method,
data,
headers: customHeaders,
noJsonInResponse,
...customConfig
}: any = {}
): Promise<any> => {
const config = {
method: method ?? "GET",
body: data ? JSON.stringify(data) : undefined,
headers: {
"Content-Type": data ? "application/json" : undefined,
...customHeaders
},
...customConfig
};
return window.fetch(url, config).then(async (response) => {
if (noJsonInResponse) {
if (response.ok) {
return { ok: true };
} else {
return Promise.reject("error " + response.status);
}
}
const responseData = await response.json();
if (response.ok) {
return responseData;
} else {
return Promise.reject({ ...responseData, requestUrl: url });
}
});
};
export default apiClient;
|
098b81d1acbf6afcafd49cb18192f75302d0b30b
|
TypeScript
|
little-green-man/nova-taskfinder
|
/src/parsers/composer.ts
| 2.71875
| 3
|
class Composer {
packageProcessName: string;
packageJsonPath: string;
tasks: any[];
constructor() {
this.tasks = [];
this.packageProcessName = 'composer';
this.packageJsonPath = `${nova.workspace.path}/composer.json`;
}
findTasks() {
const composerFile = nova.fs.stat(this.packageJsonPath);
if (composerFile && composerFile.isFile()) {
try {
const contents = nova.fs.open(this.packageJsonPath).read() as string;
const json = JSON.parse(contents);
if (json.hasOwnProperty('scripts')) {
for (var key in json.scripts) {
if (json.scripts.hasOwnProperty(key)) {
const task = new Task(key);
task.setAction(
Task.Run,
new TaskProcessAction(this.packageProcessName, {
cwd: nova.workspace.path as string,
args: ['run', key],
shell: true,
})
);
this.tasks.push(task);
}
}
}
} catch (e) {
console.log(e);
}
}
}
provideTasks() {
this.tasks = [];
this.findTasks();
console.info(`${this.packageJsonPath} has ${this.tasks.length} task(s)`);
return this.tasks;
}
}
export default Composer;
|
a82bf009976b1ce40f94f6a02f9d03e0cdf6bf84
|
TypeScript
|
zalibhai2121/TCSStackTraining
|
/typescript/typesOfLoop.ts
| 3.46875
| 3
|
let num:Array<number> = [100,200,300,400,500,600];
console.log("Classical loop: ");
for(let i = 0; i<num.length; i++){
console.log(num[i]);
}
console.log("For in loop: ");
for(let i in num){
console.log("Index "+ i+ "is " + num[i]);
}
console.log("using of loop --- use most in angular");
for(let n of num){
console.log("Value "+n);
}
|
917c6c7adfa9f18276fc90aa1485376b3857fd2e
|
TypeScript
|
tylercole8899/passionproject
|
/src/type.d.ts
| 2.546875
| 3
|
interface SingleCoin {
id: string,
name: string,
symbol: string,
rank: number,
price_usd: string,
percent_change_1h: string,
percent_change_24h: string,
percent_change_7d: string
}
interface SingleCoinState {
data: SingleCoin
}
interface CoinTableData {
data: SingleCoin[],
info: {
coins_num: number,
time: number
}
viewIndividual: boolean,
individual: string
}
interface TableAction {
type: string,
tableData: CoinTableData
}
type DispatchType = (args: TableAction) => TableAction
|
4d9a34ed42a74a78ab420104235d2e19e1c6545f
|
TypeScript
|
heremaps/harp.gl
|
/@here/harp-webtile-datasource/lib/WebTileDataSource.ts
| 2.609375
| 3
|
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
* Licensed under Apache 2.0, see full license in LICENSE
* SPDX-License-Identifier: Apache-2.0
*/
import { TileKey, TilingScheme, webMercatorTilingScheme } from "@here/harp-geoutils";
import { CopyrightInfo, DataSource, DataSourceOptions, Tile } from "@here/harp-mapview";
import { getOptionValue } from "@here/harp-utils";
import THREE = require("three");
import { WebTileLoader } from "./WebTileLoader";
/**
* An interface for the rendering options that can be passed to the [[WebTileDataSource]].
*/
export interface WebTileRenderingOptions {
/**
* Opacity of the rendered images.
* @defaultValue 1.0
*/
opacity?: number;
/**
* Force Material to use transparency from texture if available
* @defaultValue false
*/
transparent?: boolean;
/**
* RenderOrder for order in which to render WebTileDataSouurces
* @defaultValue 0
* @deprecated Use instead `dataSourceOrder` on {@link DataSource}
*/
renderOrder?: number;
}
export interface WebTileDataProvider {
/**
* The method to create the Texture that will be applied to the Tile
*
* If the Promise is resolved with an undefined Texture, the Tile is considered loaded
* and having no data.
* If the Promise is rejected, it is considered a temporary failure and the tile will be
* disposed and recreated if visible again.
* @param tile - Tile to which the texture will be applied.
* @param abortSignal - Optional AbortSignal to cancel the request.
*/
getTexture: (
tile: Tile,
abortSignal?: AbortSignal
) => Promise<[THREE.Texture | undefined, CopyrightInfo[]] | undefined>;
}
/**
* Options for [[WebTileDataSource]].
*/
export interface WebTileDataSourceOptions
extends Omit<DataSourceOptions, "enablePicking" | "styleSetName"> {
/**
* A DataProvider that will provide the tiles.
*/
dataProvider: WebTileDataProvider;
/**
* The resolution of Web Tile images, defaults to 512.
*/
resolution?: WebTileDataSource.resolutionValue;
/**
* Options affecting the rendering of the web tiles.
*/
renderingOptions?: WebTileRenderingOptions;
}
/**
* Instances of `WebTileDataSource` can be used to add Web Tile to [[MapView]].
*
* Example:
*
* ```typescript
* const webTileDataSource = new WebTileDataSource({
* dataProvider: {
* getTexture: <your custom implementation>
* }
* });
* ```
* @see {@links DataSource}
*/
export class WebTileDataSource extends DataSource {
protected readonly m_resolution: WebTileDataSource.resolutionValue;
protected dataProvider: WebTileDataProvider;
private m_opacity: number = 1;
private readonly m_renderOrder: number = 0;
private m_transparent: boolean = false;
/**
* Constructs a new `WebTileDataSource`.
*
* @param m_options - Represents the [[WebTileDataSourceParameters]].
*/
constructor(protected readonly m_options: WebTileDataSourceOptions) {
super(m_options);
this.dataProvider = this.m_options.dataProvider;
this.cacheable = true;
this.m_opacity = this.m_options.renderingOptions?.opacity ?? 1;
this.m_transparent =
this.m_options.renderingOptions?.transparent === true || this.m_opacity < 1;
this.m_renderOrder = this.m_options.renderingOptions?.renderOrder ?? 0;
this.m_resolution = getOptionValue(
m_options.resolution,
WebTileDataSource.resolutionValue.resolution512
);
}
/**
* Sets the opacity for the WebTileDataSource, will only affect not yet loaded or not cached
* tiles.
*
* Use WebTileDataSource:clearCache and MapView:markTilesDirty to reload all tiles with the
* new opacity setting.
*/
set opacity(value: number) {
this.m_opacity = value;
if (this.m_opacity < 1) {
this.m_transparent = true;
} else if (this.m_options.renderingOptions?.transparent !== true) {
this.m_transparent = false;
}
}
/**
* Gets the opacity of the WebTileDataSource.
*/
get opacity(): number {
return this.m_opacity;
}
get resolution(): WebTileDataSource.resolutionValue {
return this.m_resolution as WebTileDataSource.resolutionValue;
}
/**
* Gets the renderOrder of the WebTileDataSource.
*
* @deprecated Use instead the `dataSourceOrder` on {@link DataSource}
*/
get renderOrder(): number {
return this.m_renderOrder;
}
/**
* Gets whether tiles of this WebTileDataSource are transparent.
*/
get transparent(): boolean {
return this.m_transparent;
}
/** @override */
shouldPreloadTiles(): boolean {
return true;
}
/** @override */
getTilingScheme(): TilingScheme {
return webMercatorTilingScheme;
}
/** @override */
getTile(tileKey: TileKey) {
const tile: Tile = new Tile(this, tileKey);
tile.tileLoader = new WebTileLoader(this, tile, this.dataProvider);
return tile;
}
/** @override */
isFullyCovering(): boolean {
return true;
}
}
/**
* Definitions of variable values to be used with `WebTileDataSource`
*/
export namespace WebTileDataSource {
export enum ppiValue {
ppi72 = 72,
ppi250 = 250,
ppi320 = 320,
ppi500 = 500
}
export enum resolutionValue {
resolution256 = 256,
resolution512 = 512
}
}
|
c930c538a5149dd301dcaaa4828a0938598c73a3
|
TypeScript
|
boostcamp-2020/Project01-C-User-Event-Collector
|
/backend/src/route/playlist/controller.ts
| 2.515625
| 3
|
import { Request, Response, NextFunction } from 'express';
import * as playlistService from '../../services/playlist';
const getPlaylists = async (req: Request, res: Response, next: NextFunction): Promise<any> => {
try {
const playlists = await playlistService.getPlaylists();
if (!playlists) return res.status(404).json({ message: 'Playlist Not Found' });
return res.status(200).json({ success: true, data: playlists });
} catch (err) {
console.error(err);
return next(err);
}
};
const getPlaylistByPlaylistId = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<any> => {
try {
const { playlistId } = req.params;
const playlist = await playlistService.getPlaylistByPlaylistId(parseInt(playlistId, 10));
if (!playlist) return res.status(404).json({ message: 'Playlist Not Found' });
return res.status(200).json({ success: true, data: playlist });
} catch (err) {
console.error(err);
return next(err);
}
};
export { getPlaylists, getPlaylistByPlaylistId };
|
35350027e49c13e17ce6a62b7c520b6d300d3a95
|
TypeScript
|
scottdao/picture-collection-apply
|
/web/src/store/reducers/counter.ts
| 3.0625
| 3
|
import { ADD, MINUS } from '../constants/counter'
const INITIAL_STATE = {
num: 0
}
import { handleActions } from 'redux-actions';
const initState = {};
const counter = handleActions(
{
[ADD]: (state, { payload }) => {
// console.log(state)
return { ...state, num: state.num+1};
},
[MINUS]:(state, {payload})=>{
return {...state, num:state.num - 1}
}
},
INITIAL_STATE,
);
export { counter };
// export default function counter (state = INITIAL_STATE, action) {
// switch (action.type) {
// case ADD:
// return {
// ...state,
// num: state.num + 1
// }
// case MINUS:
// return {
// ...state,
// num: state.num - 1
// }
// default:
// return state
// }
// }
|
807505204b128fba8ad6de7530aed53e4dc6deac
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/browser/client-translate-browser/types/DetectedLanguageLowConfidenceException.ts
| 2.53125
| 3
|
import { ServiceException as __ServiceException__ } from "@aws-sdk/types";
/**
* <p>The confidence that Amazon Comprehend accurately detected the source language is low. If a low confidence level is acceptable for your application, you can use the language in the exception to call Amazon Translate again. For more information, see the <a href="https://docs.aws.amazon.com/comprehend/latest/dg/API_DetectDominantLanguage.html">DetectDominantLanguage</a> operation in the <i>Amazon Comprehend Developer Guide</i>. </p>
*/
export interface DetectedLanguageLowConfidenceException
extends __ServiceException__<_DetectedLanguageLowConfidenceExceptionDetails> {
name: "DetectedLanguageLowConfidenceException";
}
export interface _DetectedLanguageLowConfidenceExceptionDetails {
/**
* _String shape
*/
Message?: string;
/**
* <p>The language code of the auto-detected language from Amazon Comprehend.</p>
*/
DetectedLanguageCode?: string;
}
|
7aec2b831e01ae8b0d92de875c86a7c5415ea85b
|
TypeScript
|
Nash-BETA/HeadFirstObjectOriented
|
/session_1/1-1/Guitar.ts
| 2.90625
| 3
|
export class Guitar {
serialNumber: string;
price: number;
builder: string;
model: string;
type: string;
backWood: string;
topWood: string;
public constructor(serialNumber: string, price: number,
builder: string, model: string, type: string,
backWood: string, topWood: string) {
this.serialNumber = serialNumber;
this.price = price;
this.builder = builder;
this.model = model;
this.type = type;
this.backWood = backWood;
this.topWood = topWood;
}
public getSerialNumber():string{
return this.serialNumber;
}
public getPrice():number {
return this.price;
}
public setPrice(newPrice: number): void {
this.price = newPrice;
}
public getBuilder():string {
return this.builder;
}
public getModel():string {
return this.model;
}
public getType():string {
return this.type;
}
public getBackWood():string {
return this.backWood;
}
public getTopWood():string {
return this.topWood;
}
}
|
afc98d09989ce71a6cfc6ce6c0fe55ac073444d1
|
TypeScript
|
zhaobenx/Virus-game
|
/src/js/shapes.ts
| 3.296875
| 3
|
import { Node } from "./core"
export class Shape extends Node {
x: number;
y: number;
color: string;
ctx: CanvasRenderingContext2D;
}
export class Vector2 {
x: number;
y: number;
constructor(x: number = 0, y: number = 0) {
this.x = x;
this.y = y;
}
norm(): Vector2 {
if (this.x == 0 && this.y == 0)
return new Vector2(1, 0);
length = Math.sqrt(this.x * this.x + this.y * this.y);
return new Vector2(this.x / length, this.y / length);
}
angle(): number {
if (this.x == 0 && this.y == 0)
return 0;
return Math.atan2(this.y, this.x);
}
length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
zero(): boolean {
return this.x == 0 && this.y == 0
}
clear(): void {
this.x = 0;
this.y = 0;
}
}
export class Circle extends Shape {
radius: number;
constructor(x: number, y: number, radius: number, color: string) {
super();
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
update_position(dx: number, dy: number): void {
this.x += Math.round(dx);
this.y += Math.round(dy);
}
public draw(): void {
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = this.color;
this.ctx.fill();
this.ctx.restore();
}
}
|
cb2e3276cc6dc4388a7c541ecac4d7a522991f1e
|
TypeScript
|
khirayama/clap
|
/web/src/clap/components/ComponentPool.ts
| 2.921875
| 3
|
export class ComponentPool {
private static pool: { [key: string]: any } = {};
public static register(nodeType: string, component: any) {
ComponentPool.pool[nodeType] = component;
}
public static take(nodeType: string) {
return ComponentPool.pool[nodeType];
}
}
|
0daccb5b9cfd02a6d47972afdbf76edc2d485407
|
TypeScript
|
jrmce/moveon
|
/src/moveon.ts
| 2.546875
| 3
|
import * as vscode from 'vscode';
export class MoveOn {
private disposable: vscode.Disposable;
private position: vscode.Position;
private line: vscode.TextLine;
private config: vscode.WorkspaceConfiguration;
private moveOnChars: string[];
private disabled: boolean;
constructor() {
this.config = vscode.workspace.getConfiguration('moveOn');
this.moveOnChars = this.config.get('moveOnFrom') as string[];
this.disabled = this.config.get('disabled') as boolean;
if (!this.disabled) {
this.registerCommands();
}
}
execute(editor: vscode.TextEditor, edit: vscode.TextEditorEdit, args: any[]) {
if (this.disabled) {
this.skip();
return;
}
this.position = editor.selection.active;
this.line = editor.document.lineAt(this.position);
if (this.validLocation(editor.document)) {
this.moveCursor(editor);
} else {
this.skip();
return;
}
}
dispose(): void {
this.disposable.dispose();
}
private registerCommands(): void {
if (this.disposable != null) {
return;
}
const execute: vscode.Disposable = vscode.commands.registerTextEditorCommand('moveOn.execute', this.execute, this);
const disable: vscode.Disposable = vscode.commands.registerCommand('moveOn.disable', this.disable, this);
const enable: vscode.Disposable = vscode.commands.registerCommand('moveOn.enable', this.enable, this);
this.disposable = vscode.Disposable.from(...[execute, disable]);
}
private disable(): void {
this.disabled = true;
}
private enable(): void {
this.registerCommands();
this.disabled = false;
}
private validLocation(doc: vscode.TextDocument) {
if (this.line.text === '') {
return false;
}
const nextChar = this.line.text[this.position.character];
if (this.moveOnChars.indexOf(nextChar) === -1) {
return false;
}
return true;
}
private moveCursor(editor: vscode.TextEditor): void {
const position = this.getNewCursorPosition();
editor.selection = new vscode.Selection(position, position);
}
private getNewCursorPosition(): vscode.Position {
return new vscode.Position(this.position.line, this.position.character + 1);
}
private skip(): void {
vscode.commands.executeCommand('tab');
}
}
|
889112e14b9522de5aea5ba2339eb1e005126e23
|
TypeScript
|
gonnavis/3d-game-shaders-for-beginners
|
/demonstration/three.js/lib/three.js/src/core/BufferGeometry.d.ts
| 2.796875
| 3
|
import { BufferAttribute } from './BufferAttribute';
import { Box3 } from './../math/Box3';
import { Sphere } from './../math/Sphere';
import { Matrix4 } from './../math/Matrix4';
import { Vector2 } from './../math/Vector2';
import { Vector3 } from './../math/Vector3';
import { Object3D } from './Object3D';
import { Geometry } from './Geometry';
import { DirectGeometry } from './DirectGeometry';
import { EventDispatcher } from './EventDispatcher';
import { InterleavedBufferAttribute } from './InterleavedBufferAttribute';
/**
* This is a superefficent class for geometries because it saves all data in buffers.
* It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the necessary buffer calculations.
* It is mainly interesting when working with static objects.
*
* @see {@link https://github.com/mrdoob/three.js/blob/master/src/core/BufferGeometry.js|src/core/BufferGeometry.js}
*/
export class BufferGeometry extends EventDispatcher {
/**
* This creates a new BufferGeometry. It also sets several properties to an default value.
*/
constructor();
static MaxIndex: number;
/**
* Unique number of this buffergeometry instance
*/
id: number;
uuid: string;
name: string;
type: string;
index: BufferAttribute | null;
attributes: {
[name: string]: BufferAttribute | InterleavedBufferAttribute;
};
morphAttributes: {
[name: string]: ( BufferAttribute | InterleavedBufferAttribute )[];
};
morphTargetsRelative: boolean;
groups: { start: number; count: number; materialIndex?: number }[];
boundingBox: Box3 | null;
boundingSphere: Sphere | null;
drawRange: { start: number; count: number };
userData: {[key: string]: any};
readonly isBufferGeometry: true;
getIndex(): BufferAttribute | null;
setIndex( index: BufferAttribute | number[] | null ): void;
setAttribute( name: string, attribute: BufferAttribute | InterleavedBufferAttribute ): BufferGeometry;
getAttribute( name: string ): BufferAttribute | InterleavedBufferAttribute;
deleteAttribute( name: string ): BufferGeometry;
addGroup( start: number, count: number, materialIndex?: number ): void;
clearGroups(): void;
setDrawRange( start: number, count: number ): void;
/**
* Bakes matrix transform directly into vertex coordinates.
*/
applyMatrix4( matrix: Matrix4 ): BufferGeometry;
rotateX( angle: number ): BufferGeometry;
rotateY( angle: number ): BufferGeometry;
rotateZ( angle: number ): BufferGeometry;
translate( x: number, y: number, z: number ): BufferGeometry;
scale( x: number, y: number, z: number ): BufferGeometry;
lookAt( v: Vector3 ): void;
center(): BufferGeometry;
setFromObject( object: Object3D ): BufferGeometry;
setFromPoints( points: Vector3[] | Vector2[] ): BufferGeometry;
updateFromObject( object: Object3D ): void;
fromGeometry( geometry: Geometry, settings?: any ): BufferGeometry;
fromDirectGeometry( geometry: DirectGeometry ): BufferGeometry;
/**
* Computes bounding box of the geometry, updating Geometry.boundingBox attribute.
* Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null.
*/
computeBoundingBox(): void;
/**
* Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute.
* Bounding spheres aren't' computed by default. They need to be explicitly computed, otherwise they are null.
*/
computeBoundingSphere(): void;
/**
* Computes vertex normals by averaging face normals.
*/
computeVertexNormals(): void;
merge( geometry: BufferGeometry, offset?: number ): BufferGeometry;
normalizeNormals(): void;
toNonIndexed(): BufferGeometry;
toJSON(): any;
clone(): this;
copy( source: BufferGeometry ): this;
/**
* Disposes the object from memory.
* You need to call this when you want the bufferGeometry removed while the application is running.
*/
dispose(): void;
/**
* @deprecated Use {@link BufferGeometry#groups .groups} instead.
*/
drawcalls: any;
/**
* @deprecated Use {@link BufferGeometry#groups .groups} instead.
*/
offsets: any;
/**
* @deprecated Use {@link BufferGeometry#setIndex .setIndex()} instead.
*/
addIndex( index: any ): void;
/**
* @deprecated Use {@link BufferGeometry#addGroup .addGroup()} instead.
*/
addDrawCall( start: any, count: any, indexOffset?: any ): void;
/**
* @deprecated Use {@link BufferGeometry#clearGroups .clearGroups()} instead.
*/
clearDrawCalls(): void;
/**
* @deprecated Use {@link BufferGeometry#setAttribute .setAttribute()} instead.
*/
addAttribute(
name: string,
attribute: BufferAttribute | InterleavedBufferAttribute
): BufferGeometry;
/**
* @deprecated Use {@link BufferGeometry#deleteAttribute .deleteAttribute()} instead.
*/
removeAttribute( name: string ): BufferGeometry;
addAttribute( name: any, array: any, itemSize: any ): any;
}
|
73004ad32c2ed1a0fd71e2d50ccd9e9c4f1643a8
|
TypeScript
|
pawelparker/Nirikshak
|
/packages/core/tests/jestMatchers/bodyMatchers.test.ts
| 2.59375
| 3
|
import { toMatchBody } from "../../src/jestMatchers/bodyMatchers";
const Entries: {
input: boolean;
expected: boolean;
output: {
pass: boolean;
message: string;
};
}[] = [
{
input: true,
expected: true,
output: {
pass: true,
message: "Response bodies matched",
},
},
{
input: false,
expected: false,
output: {
pass: true,
message: "Response bodies matched",
},
},
{
input: true,
expected: false,
output: {
pass: false,
message: "Response bodies did not match",
},
},
{
input: false,
expected: true,
output: {
pass: false,
message: "Response bodies did not match",
},
},
];
describe(`Body matcher`, () => {
test.each(Entries)(`entry:%#`, (entry) => {
const { pass, message } = toMatchBody(entry.input, entry.expected);
expect(pass).toBe(entry.output.pass);
expect(message()).toBe(entry.output.message);
});
});
|
bc2b5378795c6fef7cdcfdc4aee211f499500172
|
TypeScript
|
kemicofa/rgng
|
/enums/type.ts
| 2.65625
| 3
|
export enum Type {
MALE = "male",
FEMALE = "female",
LAST = "last"
}
|
be772323b142dc274231c5b38df2f4467e6b7c51
|
TypeScript
|
passosfe/aiticketmanager
|
/server/src/app/models/User.ts
| 2.546875
| 3
|
import bcrypt from 'bcryptjs';
import {
Length,
IsNotEmpty,
IsEmail,
IsString,
MinLength,
IsBoolean,
IsOptional,
IsDate,
IsUUID,
} from 'class-validator';
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
BaseEntity,
BeforeInsert,
BeforeUpdate,
OneToMany,
} from 'typeorm';
import { Comment } from './Comment';
import { Group } from './Group';
import { Ticket } from './Ticket';
@Entity('users')
export class User extends BaseEntity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user);
}
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('varchar', { length: 255, nullable: false })
@Length(5, 255)
@IsNotEmpty()
name: string;
@Column('varchar', { length: 254, nullable: false, unique: true })
@IsEmail()
@IsNotEmpty()
email: string;
@IsString()
@MinLength(6)
password: string;
@Column('varchar', { length: 60, nullable: false })
password_hash: string;
@Column('boolean', { default: false })
@IsBoolean()
@IsOptional()
is_admin: boolean;
@Column('timestamp', { nullable: true })
@IsOptional()
@IsDate()
last_login: Date;
@Column('timestamp', { nullable: true })
@IsOptional()
@IsDate()
deprovisioned_at: Date;
@Column('varchar', { length: 255, nullable: true })
@IsOptional()
token: string;
@Column('timestamp', { nullable: true })
@IsOptional()
@IsDate()
token_created_at: Date;
@OneToMany(() => Ticket, ticket => ticket.requester)
requester_tickets: Ticket[];
@OneToMany(() => Ticket, ticket => ticket.support)
support_tickets: Ticket[];
@OneToMany(() => Comment, comment => comment.author)
comments: Comment[];
@Column('uuid', { nullable: false })
@IsUUID()
@IsNotEmpty()
group_id: string;
@ManyToOne(() => Group, group => group.id, {
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
})
@JoinColumn({ name: 'group_id' })
group: Group;
@CreateDateColumn()
public created_at: Date;
@UpdateDateColumn()
public updated_at: Date;
@BeforeInsert()
@BeforeUpdate()
async hash(): Promise<void> {
if (this.password) {
this.password_hash = await bcrypt.hash(this.password, 8);
this.password = '';
}
}
async checkPassword(password: string): Promise<boolean> {
return bcrypt.compare(password, this.password_hash);
}
}
|
795bc8c9b4633984cf523db2254a18a40a172ba2
|
TypeScript
|
JoshuaKGoldberg/TypeStat
|
/src/shared/NameGenerator.ts
| 3.296875
| 3
|
/**
* Generates new names that are unique per file.
*/
export class NameGenerator {
private readonly countsPerBase = new Map<string, number>();
public constructor(private readonly sourceFileName: string) {}
public generateName(base: string) {
const existingCount = this.countsPerBase.get(base);
if (existingCount === undefined) {
this.countsPerBase.set(base, 1);
return `${this.sourceFileName}${base}`;
}
this.countsPerBase.set(base, existingCount + 1);
return `${this.sourceFileName}${base}${existingCount + 1}`;
}
}
|
0294c314bd087f535f10b18ad94784bf9891df8d
|
TypeScript
|
tlaukkan/reality-space
|
/src/common/reality/Decode.ts
| 2.78125
| 3
|
import {Encode} from "./Encode";
export class Decode {
static login(parts: string[]) : [string, string, string, string] {
return [
parts[1],
Decode.decodeString(parts[2]),
parts[3],
parts[4]];
}
static loginResponse(parts: string[]) : [string, string] {
return [
parts[1],
parts[2]];
}
static add(parts: string[]) : [string, number, number, number, number, number, number, number, string, string] {
return [
parts[1],
parseFloat(parts[2]),
parseFloat(parts[3]),
parseFloat(parts[4]),
parseFloat(parts[5]),
parseFloat(parts[6]),
parseFloat(parts[7]),
parseFloat(parts[8]),
parts[9],
parts[10]];
}
static added(parts: string[]) : [number, string, number, number, number, number, number, number, number, string, string] {
return [
parseInt(parts[1]),
parts[2],
parseFloat(parts[3]),
parseFloat(parts[4]),
parseFloat(parts[5]),
parseFloat(parts[6]),
parseFloat(parts[7]),
parseFloat(parts[8]),
parseFloat(parts[9]),
parts[10],
parts[11]];
}
static update(parts: string[]) : [string, number, number, number, number, number, number, number] {
return [
parts[1],
parseFloat(parts[2]),
parseFloat(parts[3]),
parseFloat(parts[4]),
parseFloat(parts[5]),
parseFloat(parts[6]),
parseFloat(parts[7]),
parseFloat(parts[8])];
}
static updated(parts: string[]) : [number, number, number, number, number, number, number, number] {
return [
parseInt(parts[1]),
parseFloat(parts[2]),
parseFloat(parts[3]),
parseFloat(parts[4]),
parseFloat(parts[5]),
parseFloat(parts[6]),
parseFloat(parts[7]),
parseFloat(parts[8])];
}
static remove(parts: string[]) : [string] {
return [
parts[1],
];
}
static removed(parts: string[]) : [number, string] {
return [
parseInt(parts[1]),
parts[2]
];
}
static describe(parts: string[]) : [string, string] {
return [
parts[1],
parts[2],
];
}
static described(parts: string[]) : [number, string] {
return [
parseInt(parts[1]),
parts[2]
];
}
static act(parts: string[]) : [string, string, string] {
return [
parts[1],
parts[2],
parts[3]
];
}
static acted(parts: string[]) : [number, string, string] {
return [
parseInt(parts[1]),
parts[2],
parts[3]
];
}
static notify(parts: string[]) : [string, string] {
return [
parts[1],
parts[2]
];
}
static notified(parts: string[]) : [string, string] {
return [
parts[1],
parts[2]
];
}
static decodeString(value: string): string {
if (value.indexOf('\\') != -1) {
return value.replace("\\\\1", "\\").replace("\\\\2", Encode.SEPARATOR)
} else {
return value;
}
}
}
|
e6531bd7e61150ca946b3aa12fee48d4f07db488
|
TypeScript
|
Scyllizzy/Fall-2019-PigDiceGame
|
/typescript/dice.ts
| 3.53125
| 4
|
/**
* Generates a random number between the min and max value.
* Min is inclusive.
* Max is exclusive.
* @param minValue Minimum value for randomly generated number inclusive.
* @param maxValue Maximun value for randomly generated number exclusive.
*/
function generateRandomValue(minValue:number, maxValue:number):number{
let min = Math.ceil(minValue);
let max = Math.floor(maxValue);
return Math.floor(Math.random() * (max - min)) + min;
}
/**
* Switches the players turn.
*/
function changePlayers():void{
let currentPlayerName = document.getElementById("current");
let player1Name = (<HTMLInputElement>document.getElementById("player1")).value;
let player2Name = (<HTMLInputElement>document.getElementById("player2")).value;
//swap from player to player by comparing current name to player names
//set currentPlayerName to the next player
if (currentPlayerName.innerHTML == player1Name) {
currentPlayerName.innerHTML = player2Name;
}
else {
currentPlayerName.innerHTML = player1Name;
}
}
window.onload = function(){
let newGameBtn = document.getElementById("new_game");
newGameBtn.onclick = createNewGame;
document.getElementById("roll").onclick = rollDie;
document.getElementById("hold").onclick = holdDie;
}
function createNewGame(){
//set player 1 and player 2 scores to 0
resetScores();
//verify each player has a name
if (arePlayerNamesPresent()) {
//if both players do have a name start the game!
document.getElementById("turn").classList.add("open");
(<HTMLInputElement>document.getElementById("total")).value = "0";
//lock in player names and then change players
document.getElementById("player1").setAttribute("disabled", "disabled");
document.getElementById("player2").setAttribute("disabled", "disabled");
changePlayers();
}
}
/**
* Checks if both player 1 and player 2 have input in their textboxes.
*/
function arePlayerNamesPresent():boolean {
clearErrors();
let isValid = true;
let player1Name = (<HTMLInputElement>document.getElementById("player1")).value;
let player2Name = (<HTMLInputElement>document.getElementById("player2")).value;
//if both players don't have a name display error
if (player1Name.trim() == "" || player1Name == null) { //Simulate isNullOrWhiteSpace from C# because I like that particular method.
displayError("Player 1", "span1");
isValid = false;
}
if (player2Name.trim() == "" || player2Name == null) {
displayError("Player 2", "span2");
isValid = false;
}
return isValid;
}
/**
* Clears the span error messages displayed on the form.
*/
function clearErrors():void {
let spans = document.querySelectorAll("span");
for (let i = 0; i < spans.length; i++) {
spans[i].innerHTML = "";
}
}
/**
* Displays an error for the player with an invalid name in a span element.
* @param player The player that has an invalid name.
* @param spanID The ID of the span for the error to display in.
*/
function displayError(player:string, spanID:string):void {
document.getElementById(spanID).innerHTML = "You must enter a name for " + player + ".";
}
/**
* Resets all the scores back to its original state.
*/
function resetScores():void {
(<HTMLInputElement>document.getElementById("score1")).value = "0";
(<HTMLInputElement>document.getElementById("score2")).value = "0";
resetDieAndTotal();
}
/**
* Rolls the die, displays the die roll, and adds die roll to the current total.
*/
function rollDie():void{
let currTotal = parseInt((<HTMLInputElement>document.getElementById("total")).value);
//roll the die and get a random value 1 - 6 (use generateRandomValue function)
let dieRoll = generateRandomValue(1, 7); //max is exclusive, min is inclusive
//if the roll is 1
if (dieRoll == 1) {
//change players
changePlayers();
//set current total to 0
currTotal = 0;
}
else { //if the roll is greater than 1
//add roll value to current total
currTotal += dieRoll;
}
displayDieRoll(dieRoll);
displayCurrTotal(currTotal);
}
/**
* Displays current total on form.
* @param currTotal The current total the user has accumulated.
*/
function displayCurrTotal(currTotal: number):void {
(<HTMLInputElement>document.getElementById("total")).value = currTotal.toString();
}
/**
* Sets the die roll to value player rolled.
* @param dieRoll The number the die rolled.
*/
function displayDieRoll(dieRoll: number):void {
(<HTMLInputElement>document.getElementById("die")).value = dieRoll.toString();
}
/**
* Adds the total accumulated from the turn and adds it to the total score.
* Resets the die and total.
* Checks if anybody won.
*/
function holdDie():void{
//get the current turn total
let turnTotal = parseInt((<HTMLInputElement>document.getElementById("total")).value);
//determine who the current player is
let currplayer = document.getElementById("current").innerHTML;
let player1 = (<HTMLInputElement>document.getElementById("player1")).value;
if (currplayer == player1) { //add the current turn total to the player's total score
addTotalToScore(turnTotal, "score1");
}
else {
addTotalToScore(turnTotal, "score2");
}
resetDieAndTotal();
if (didEitherPlayerWin()) {
gameOver();
}
else {
changePlayers();
}
}
/**
* Figures out who won and return the winners name.
*/
function whoWon():string {
let player1Score = parseInt((<HTMLInputElement>document.getElementById("score1")).value);
let player2Score = parseInt((<HTMLInputElement>document.getElementById("score2")).value);
if (player1Score >= 100) {
return (<HTMLInputElement>document.getElementById("player1")).value;
}
if (player2Score >= 100) {
return (<HTMLInputElement>document.getElementById("player2")).value;
}
}
/**
* Checks if either player's score is at or above 100.
* Returns true if so, returns false if not.
*/
function didEitherPlayerWin():boolean {
let player1Score = parseInt((<HTMLInputElement>document.getElementById("score1")).value);
let player2Score = parseInt((<HTMLInputElement>document.getElementById("score2")).value);
//check if player1's score > 100
if (player1Score >= 100 || player2Score >= 100) {
return true;
}
}
/**
* Displays a winner and resets the form back to where players can now re-enter their name.
*/
function gameOver():void {
displayWinner();
resetForm();
}
/**
* Resets the form back to its original state.
* Players can now re-enter their name.
*/
function resetForm():void {
(<HTMLFormElement>document.getElementById("form")).reset();
document.getElementById("turn").classList.remove("open");
(<HTMLInputElement>document.getElementById("player1")).disabled = false;
(<HTMLInputElement>document.getElementById("player2")).disabled = false;
}
/**
* Displays the winner of the game in an alert box.
*/
function displayWinner() {
let winner = whoWon();
alert(winner + " won!");
}
/**
* Resets the turn total to 0 and die display to an empty string.
*/
function resetDieAndTotal():void {
(<HTMLInputElement>document.getElementById("total")).value = "0";
(<HTMLInputElement>document.getElementById("die")).value = "";
}
/**
* Adds the total accumulated from the turn to the current players total.
*/
function addTotalToScore(turnTotal:number, scoreID:string):void {
let score = <HTMLInputElement>document.getElementById(scoreID); //Grab score element
let scoreValue = parseInt(score.value); //Take the num and parse it
scoreValue += turnTotal; //Add the turn total to the scoreValue
score.value = scoreValue.toString(); //Put the score value into the textbox
}
|
52dadd42784b1cfa361ad367a4bc53e89d5e9871
|
TypeScript
|
ZsZs/processpuzzle-util
|
/projects/processpuzzle-util-lib/src/lib/classes/object-util/object-util.spec.ts
| 3.40625
| 3
|
import { ObjectUtil } from './object-util';
describe('ObjectUtil behaviour', () => {
const nullObject: any = null;
const undefinedObject = undefined ;
const notNullObject: any = 'something';
const stringObject = 'some string';
const numberObject = 128;
const classInstance: Date = new Date();
beforeEach(() => {});
it('isNullOrUndefined() returns true when null or undefined, othervise false', () => {
expect( ObjectUtil.isNullOrUndefined( nullObject ) ).toBeTruthy();
expect( ObjectUtil.isNullOrUndefined( undefinedObject ) ).toBeTruthy();
expect( ObjectUtil.isNullOrUndefined( notNullObject ) ).toBeFalsy();
});
it('isNull() returns true when null, othervise false', () => {
expect( ObjectUtil.isNull( nullObject ) ).toBeTruthy();
expect( ObjectUtil.isNull( undefinedObject ) ).toBeFalsy();
expect( ObjectUtil.isNull( notNullObject ) ).toBeFalsy();
});
it('isUndefined() returns true when undefined, othervise false', () => {
expect( ObjectUtil.isUndefined( nullObject ) ).toBeFalsy();
expect( ObjectUtil.isUndefined( undefinedObject ) ).toBeTruthy();
expect( ObjectUtil.isUndefined( notNullObject ) ).toBeFalsy();
});
it('isString() returns true when type of object is string, othervise false', () => {
expect( ObjectUtil.isString( stringObject ) ).toBeTruthy();
expect( ObjectUtil.isString( numberObject ) ).toBeFalsy();
expect( ObjectUtil.isString( nullObject ) ).toBeFalsy();
expect( ObjectUtil.isString( undefinedObject ) ).toBeFalsy();
});
it('isObject() returns true when valid object (class instance) or null, othervise false', () => {
expect( ObjectUtil.isObject( classInstance ) ).toBeTruthy();
expect( ObjectUtil.isObject( nullObject ) ).toBeTruthy();
expect( ObjectUtil.isObject( stringObject ) ).toBeFalsy();
expect( ObjectUtil.isObject( numberObject ) ).toBeFalsy();
expect( ObjectUtil.isObject( notNullObject ) ).toBeFalsy();
expect( ObjectUtil.isObject( undefinedObject ) ).toBeFalsy();
});
});
|
09aabb3e3936c8d58c805e37d6e7dff9138975b4
|
TypeScript
|
rheehot/dynamo1
|
/src/connection/from-dynamo-attribute.ts
| 2.78125
| 3
|
import { AttributeValue, AttributeMap } from 'aws-sdk/clients/dynamodb'
export function fromDynamoAttributeMap(item: AttributeMap): {[key: string]: any} {
return Object.keys(item).reduce((carry, key) => Object.assign(carry, {
[key]: fromDynamoAttribute(item[key]),
}), {})
}
export function fromDynamoAttribute(item: AttributeValue): any {
if (item.NULL) {
return null
}
if (item.S) {
return item.S
}
if (item.N) {
return +item.N
}
if (typeof item.BOOL !== 'undefined') {
return item.BOOL
}
if (item.L) {
return item.L.map(fromDynamoAttribute)
}
if (item.M) {
const m = item.M
return Object.keys(m).reduce((carry, key) => Object.assign(carry, {
[key]: fromDynamoAttribute(m[key]),
}), {})
}
return {}
}
|
86d2b4e64b548f0039c46db2f909b3ebebc14575
|
TypeScript
|
vvakar/dynamic-programming
|
/algos/Levenshtein-memoize.ts
| 3.90625
| 4
|
/**
* Levenshtein distance using recursion/memoizing, also known as top-down solution.
*
* Strategy:
* 1. we only need to memoize based on a and b length rather than a and b because it's always going to be the tail end of each.
* 2. we additionally memoize each step taken so we can reconstruct the path
*
* Step Legend:
* A - keep a side, remove one b
* B - keep b side, remove one a
* E - a and b equal, remove both
* X - a and b different, remove both
*
*/
let memo: any;
export default function levenshteinMemoize(a: string, b: string) {
memo = {};
memo[key('', '')] = dist('', 0);
const d = editDistanceMemo(a, b);
const path = reconstructPath(a, b);
return {value: d.value, path: path};
}
function dist(step: string, value: number): StateEntry {
return {direction: step, value: value};
}
function key(a: string, b: string) {
return a.length + '--' + b.length;
}
function editDistanceMemo(a: string, b: string) {
const prop = key(a, b);
if (memo[prop]) return memo[prop];
let res;
if (a.length === 0) res = dist('A'.repeat(b.length), b.length);
else if (b.length === 0) res = dist('B'.repeat(a.length), a.length);
else {
const ahead = a.charAt(0);
const atail = a.substring(1);
const bhead = b.charAt(0);
const btail = b.substring(1);
if (ahead === bhead)
res = dist('E', editDistanceMemo(atail, btail).value);
else {
const aa = editDistanceMemo(a, btail);
const bb = editDistanceMemo(atail, b);
const xx = editDistanceMemo(atail, btail);
if (xx.value <= aa.value && xx.value <= bb.value)
res = dist('X', xx.value + 1);
else if (bb.value <= aa.value)
res = dist('B', bb.value + 1);
else
res = dist('A', aa.value + 1);
}
}
return memo[prop] = res;
}
function reconstructPath(a: string, b: string): any {
const k = key(a, b);
const dist = memo[k];
switch (dist.direction) {
case 'E':
case 'X':
return dist.direction + reconstructPath(a.substr(1), b.substr(1));
case 'A':
return dist.direction + reconstructPath(a, b.substr(1));
case 'B':
return dist.direction + reconstructPath(a.substr(1), b);
default:
return dist.direction;
}
}
interface StateEntry {
readonly value: number;
readonly direction: string;
}
|
ebe3908a4e6fa60286e667b090d5a76be75ea43b
|
TypeScript
|
LearnItWell2018/DevFrontcontroller
|
/src/app/model/CustomerAddress.ts
| 2.53125
| 3
|
export class CustomerAddress {
private id:String;
private pincode:String;
private street:String;
private roomorflatno:String;
private nearestLandMark:String;
constructor(id:String, pincode:String, street:String, roomorflatno:String, nearestLandMark:String) {
this.id = id;
this.nearestLandMark = nearestLandMark;
this.pincode = pincode;
this.roomorflatno = roomorflatno;
this.street = street;
}
}
|
fca20eef303fed10d054a70ad6f9632716a69224
|
TypeScript
|
linuxninja39/GeneAnnotationClient
|
/src/app/pipes/first-item.pipe.ts
| 2.734375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { Log } from 'ng2-logger';
const log = Log.create('FirstItemPipe');
@Pipe({
name: 'firstItem'
})
export class FirstItemPipe implements PipeTransform {
transform(itemList: Array<any>, orderField: string, ascending: boolean = true): any {
let func;
// log.info('array is to start', [...itemList]);
if (ascending) {
func = (b, a) => {
// log.info('comparing b to a', b, a);
if (a[orderField] < b[orderField]) {
return -1;
}
if (a[orderField] > b[orderField]) {
return 1;
}
return 0;
};
} else {
func = (a, b) => {
// log.info('comparing a to b', a, b);
if (a[orderField] < b[orderField]) {
return -1;
}
if (a[orderField] > b[orderField]) {
return 1;
}
return 0;
};
}
// log.info('array is now', [...itemList]);
itemList.sort(func);
return itemList.pop();
}
}
|
402f77199f37dfa8c370ab502bc424eb408dff11
|
TypeScript
|
drahoja9/AutoGram
|
/frontend/src/lib/parse/Lexer.ts
| 3.9375
| 4
|
/**
* Abstract base convenience class for all lexers.
*/
export default abstract class LexerBase<TokType, Token> {
/** Currenly inspected character. */
protected curr: string;
/** Source buffer that is currently being lexed. Always ends with a nul character. */
protected buff: string;
/** Next token to be lexed. */
protected nextTok: Token;
/**
* Constructs basic lexer with provided source buffer.
* @param buff Source buffer to be lexed.
*/
constructor(buff: string) {
this.buff = buff + '\0';
this.advance();
}
/** Returns a next lexed token. */
public lex(): Token {
const tok = this.nextTok;
if (!this.isEof()) {
this.lexImpl();
}
return tok;
}
/**
* Returns a next token to be lexed, without actualy
* moving a buffer pointer.
*/
public peekNext(): Token {
return this.nextTok;
}
/** Updateds current buffer */
protected advance(): void {
this.curr = this.buff[0];
this.buff = this.buff.slice(1, this.buff.length);
}
/**
* Creates a new token of provided type and sets it as a next token.
* @param type A type of the new token.
* @param value Value of the new token.
*/
protected abstract formToken(type: TokType, value: string | null): void;
/**
* Actualy perform lexing of the next token.
*/
protected abstract lexImpl(): void;
/**
* Retuerns `true` if current token is Eof, `false` otherwise.
*/
protected abstract isEof(): boolean;
}
|
c48c177af5c1bff4ea390f13313f72746a09583c
|
TypeScript
|
webbegg/RunoX
|
/src/commands/start-game.command.ts
| 2.96875
| 3
|
import { GameCommand } from "./game.command";
import { GameState } from "../models/game-state.model";
import { Card } from "../models/card.model";
export class StartGameCommand extends GameCommand {
execute(state: GameState) {
const handsLength = 7; // randomDeck.length / 4; // 4 jugadores
if (!state.playersGroup.players.length) {
console.error("No hay jugadores en la partida");
return;
}
state.playersGroup.players.forEach((player, index) => {
player.hand.addCards(
state.deck.cards.splice(index * handsLength, handsLength)
);
});
let firstStackCard = state.deck.takeCard() as Card;
while(firstStackCard.isSpecialCard()) {
state.deck.addCards([firstStackCard]);
state.deck.shuffle();
firstStackCard = state.deck.takeCard() as Card;
}
state.stack.addCard(firstStackCard);
state.turn.setPlayerTurn(state.playersGroup.players[0]);
}
}
|
d65b7284bb07ff11544f32b102d30965bc2ac6ab
|
TypeScript
|
shreyakaushik1/Test_material
|
/src/app/views/form/form.component.ts
| 2.6875
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
export interface Office{
name: string;
}
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.sass']
})
export class FormComponent implements OnInit {
firstName:string;
lastName:string;
gender:string;
numberOfMiles:number;
myControl = new FormControl();
filteredOptions: Observable<Office[]>;
offices: Office[] = [
{name: 'Roush'},
{name: 'Pasta'},
{name: 'CCD'},
{name: 'SVC'},
{name: 'Main Building'},
]
enableAutocomplete = true;
constructor() { }
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this._filter(name) : this.offices.slice())
);
}
toEnableAutocomplete(){
console.log(this.enableAutocomplete);
}
displayFn(offices?: Office): string | undefined {
return offices ? offices.name : undefined;
}
private _filter(name: string): Office[] {
const filterValue = name.toLowerCase();
return this.offices.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}
}
|
a1da06077566392758f7d95da7581006cd3ea54a
|
TypeScript
|
Swasth-Digital-Health-Foundation/C19CareAssist
|
/gateway/src/utils/auth-helper.ts
| 2.59375
| 3
|
import * as moment from 'moment';
const NodeRSA = require('node-rsa');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
import { ACCESSTOKEN_SECRET, REFRESHTOKEN_SECRET, API_TOKEN_PRIVATEKEY, API_TOKEN_PUBLICKEY } from './secrets';
import logger from '../utils/logger'
const generateToken = (param: any, data: any) => {
const token = jwt.sign({ exp: moment.utc().add(param.ttl, 'minute').valueOf(), data: data }, param.secret, { algorithm: param.algorithm, issuer: "healthgateway" });
return token;
}
class AuthHelper {
verify(type: string, token: string) {
let secret = null, maxAge = '1h';
switch (type) {
case 'access_token':
secret = ACCESSTOKEN_SECRET;
maxAge = '24h';
break;
case 'refresh_token':
secret = REFRESHTOKEN_SECRET;
maxAge = '15d'
break;
default:
break;
}
try {
const data = jwt.verify(token, secret, { maxAge });
const hasExpired = moment.utc(data.exp).isBefore(moment.utc());
if(!hasExpired) return data;
else return false;
} catch (error) {
logger.error('jwt verification failed.',error);
return false;
}
}
generateApiToken(data: object) {
const token = generateToken({ ttl: 10, secret: Buffer.from(API_TOKEN_PRIVATEKEY, 'base64').toString('ascii'), algorithm: 'RS256' }, data)
return token;
}
generateAccessToken(data: object) {
const token = generateToken({ ttl: 10, secret: ACCESSTOKEN_SECRET, algorithm: 'HS256' }, data)
return token;
}
generateRefreshToken(data: object) {
const token = generateToken({ ttl: 10 * 60 * 24 * 15, secret: REFRESHTOKEN_SECRET, algorithm: 'HS256' }, data)
return token;
}
generateGatewayToken(secret: string, data: object) {
const token = generateToken({ ttl: 10, secret: secret, algorithm: 'HS256' }, data)
return token;
}
generateAppSecret() {
return crypto.randomBytes(48).toString('hex');
}
generateRSAKeyPair() {
const key = new NodeRSA();
const publicKey = Buffer.from(key.exportKey('pkcs8-public-pem')).toString('base64');
const privateKey = Buffer.from(key.exportKey('pkcs8-pem')).toString('base64');
return { privateKey, publicKey }
}
getApiTokenPublicKey() {
return {
publicKey: API_TOKEN_PUBLICKEY,
encoding: 'base64'
}
}
}
export default new AuthHelper()
|
837ef8989ffc2960599225252959dee089e82383
|
TypeScript
|
kristianmandrup/zebkit
|
/src/ui/core/Manager.ts
| 2.5625
| 3
|
/**
* UI manager class. The class is widely used as base for building
* various UI managers like paint, focus, event etc. Manager is
* automatically registered as input and component events listener
* if it implements appropriate events methods handlers
* @class zebkit.ui.Manager
* @constructor
*/
import events from './events';
abstract class Manager {
constructor() {
if (events != null) {
events.bind(this);
}
}
}
export default Manager;
|
32151410d7d5d1387ef3b211e0a49305bd87e0ec
|
TypeScript
|
MaddozS/punto-de-venta-frontend
|
/renderer/utils/formatMoney.ts
| 2.90625
| 3
|
import Dinero from "dinero.js";
const withNoExtraFormat = (formatedPrice: string) =>
formatedPrice.replace(/MX/g, "");
const withCustomFormat = (priceString: string) => `${priceString} MXN`;
const formatMoney = (amount: number) => {
const priceObject = Dinero({ amount: amount * 100, currency: "MXN" });
const priceString = withNoExtraFormat(priceObject.toFormat("$0,0.00"));
return withCustomFormat(priceString);
};
export default formatMoney;
|
6528f50e0b78b1fe796bc41d63486590af517b03
|
TypeScript
|
efried/language-buffet
|
/ts/main.ts
| 3.609375
| 4
|
const ajv = new require('ajv')() // Why is this difficult to add a type annotation to?
const jsonStrings = require('./jsonStrings')
const playerSchema = {
type: 'object',
required: ['name', 'winPercent'],
properties: {
name: {type: 'string'},
winPercent: {type: ['number', 'null']},
},
}
interface Player {
name: string
winPercent: number // All fields can be null in TS by default.
}
function introduce(player : Player) {
if (player.winPercent) {
console.log(`${player.name} wins ${player.winPercent}% of the time.`)
} else {
console.log(`${player.name} is a new player.`)
}
}
try {
const player: Player = JSON.parse(jsonStrings.goodJson) // We claim this returns a Player, but TypeScript provides no guarantee.
const isValid: boolean = ajv.validate(playerSchema, player) // Here's the guarantee, but that's tied to the playerSchema, not the Player interface.
if (isValid) {
introduce(player)
delete player.name // Why am I allowed to do this?
introduce(player)
} else {
console.error(ajv.errorsText())
}
} catch (error) { // Catch clause cannot have a type annotation.
console.error(`Here's what went wrong. ${error}`)
}
// The TypeScript compiler won't tell us about an unhandled exception.
// For some reason my compiler keeps yelling at me about errors in AJV.
// TypeScript's configuration seems daunting, but I don't think it really is.
// The annoying part is the typings files, and how that all works. Will have to look into that more.
// Immediately TypeScript seems awesome for the majority of our use cases.
// However when it comes adding confidence around external data, it does nothing, or worse.
// In our case the `: Player` annotation is providing some value by not allowing us to access
// members of the `player` object that are not in the Player interface.
// However, it's really the `playerSchema` that doing the heavy lifting here,
// and that is defined parallel to the Player interface. I don't know how to have one help declare the other.
// And you have to declare what's effectively the same thing twice to get both runtime and compile time checks.
|
88cf188b157187fe1a8f3d7d72d27e16acc7f350
|
TypeScript
|
link1900/scottdbnet
|
/src/games/simpleCanvas/CanvasElement.ts
| 3.09375
| 3
|
import { v4 as uuid } from "uuid";
export interface CanvasElementProps {
id?: string;
name?: string;
visible?: boolean;
active?: boolean;
}
export default class CanvasElement {
public id: string;
public name: string;
public visible: boolean;
public active: boolean;
constructor({
id = uuid(),
name = "",
visible = true,
active = true
}: CanvasElementProps) {
this.id = id;
this.name = name;
this.visible = visible;
this.active = active;
}
public _draw(canvas: HTMLCanvasElement) {
if (this.visible) {
this.draw(canvas);
}
}
public _simulate(elements: CanvasElement[]) {
if (this.active) {
this.simulate(elements);
}
}
public draw(canvas: HTMLCanvasElement) {}
public simulate(elements: CanvasElement[]) {}
public enable() {
this.visible = true;
this.active = true;
}
public disable() {
this.visible = false;
this.active = false;
}
public onClick(elements: CanvasElement[]) {}
public containsPoint(pointX: number, pointY: number): boolean {
return false;
}
}
|
b0efb8075f2d2f9003ffcbf287a6977587384060
|
TypeScript
|
Devidian/devidian-tv-api
|
/src/user-account/entities/user-account.entity.ts
| 2.578125
| 3
|
import { BaseEntity, MongoCollection } from '#/utils';
import { Exclude, Expose } from 'class-transformer';
import { IsEmail, IsNotEmpty, IsOptional, Length } from 'class-validator';
import { hostname } from 'os';
import { cpuUsage } from 'process';
export class UserAccountEntity extends BaseEntity {
@IsNotEmpty()
@Length(3)
name: string;
@Exclude({ toPlainOnly: true })
password: string; // SHA256
@IsOptional() // in case of openid we may not have an email on registration
@IsEmail()
@Expose({ groups: ['owner', 'admin'] })
email: string;
@IsOptional()
country: string;
@Exclude({ toPlainOnly: true })
verification: VerificationEntity[];
@Expose({ groups: ['owner', 'admin'] })
steam: {
id: string;
identifier: string;
displayName: string;
photos: { value: string }[];
connectedOn: Date;
};
@Expose({ groups: ['owner', 'admin'] })
flags: Record<string, boolean>;
public get isAdmin(): boolean {
return this.flags['admin'] || false;
}
/**
* returns large medium or small image if available
*
* @readonly
* @type {string}
* @memberof UserAccountEntity
*/
@Expose()
public get avatarUrl(): string {
return this.avatarLargeUrl || this.avatarMediumUrl || this.avatarSmallUrl;
}
@Expose()
public get avatarSmallUrl(): string {
return this.steam?.photos[0]?.value;
}
@Expose()
public get avatarMediumUrl(): string {
return this.steam?.photos[1]?.value;
}
@Expose()
public get avatarLargeUrl(): string {
return this.steam?.photos[2]?.value;
}
public get isEmailVerified(): boolean {
return !!this.verification.find((v) => v.field == 'email' && v.verifiedOn != null);
}
public validatePassword(password: string): boolean {
return MongoCollection.hash256(password) === this.password;
}
public setPassword(pw: string): void {
if (!pw) return;
this.password = MongoCollection.hash256(pw);
}
public createVerificationToken(field: string): UserAccountEntity {
const d = new Date(Date.now() + 24 * 60 * 60 * 1000);
const t = MongoCollection.hash256(field + d + Math.random() + hostname() + cpuUsage().system);
const verificationToken: VerificationEntity = {
field,
verifiedOn: null,
token: t,
tokenValidUntil: d,
};
this.verification = this.verification.filter((v) => v.field != field);
this.verification.push(verificationToken);
return this;
}
}
|
73a61c0d5fee43ec613546e3b6f92140cad5285a
|
TypeScript
|
BLing88/recipe-developer
|
/server/src/validate.ts
| 2.671875
| 3
|
require("dotenv").config();
import jwt from "jsonwebtoken";
import jwksClient from "jwks-rsa";
const client = jwksClient({
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
});
const getKey: jwt.GetPublicKeyOrSecret = (header, callback) => {
client.getSigningKey(header.kid!, (err, key) => {
const signingKey =
(key as jwksClient.CertSigningKey).publicKey ||
(key as jwksClient.RsaSigningKey).rsaPublicKey;
callback(null, signingKey);
});
};
interface DecodedResponse {
decoded: {
exp: number;
iss: string;
aud: string[];
};
}
interface ErrorResponse {
error: jwt.VerifyErrors | string;
}
type IsTokenValidResponse = DecodedResponse | ErrorResponse;
export const isDecodedResponse = (
res: IsTokenValidResponse
): res is DecodedResponse => {
return (res as DecodedResponse).decoded !== undefined;
};
export const isTokenValid = async (
token: string
): Promise<IsTokenValidResponse> => {
if (token) {
const bearerToken = token.split(" ");
const result = new Promise<IsTokenValidResponse>((resolve, reject) => {
jwt.verify(
bearerToken[1],
getKey,
{
audience: process.env.API_IDENTIFIER,
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
algorithms: ["RS256"],
},
(error, decoded) => {
if (error) {
resolve({ error });
}
if (decoded) {
resolve({ decoded } as DecodedResponse);
}
}
);
});
return result;
}
return { error: "No token provided" };
};
|
ebd14581810e306e12cdeb1e30ddca84aab31d62
|
TypeScript
|
akritii1/dbs_test
|
/Ritesh_TS_Day1/smallest.ts
| 3.421875
| 3
|
function smallest (n1:number,n2:number):number{
if(n1>n2)
return n2;
else
return n1;
}
console.log("Smallest is :"+smallest(20,100));
|
6eac1a3a30930a644a7fd121209aa0514879f1f1
|
TypeScript
|
pp123pp/tweakpane
|
/lib/plugin/util.ts
| 2.953125
| 3
|
import {
InputParams,
InputParamsOption,
InputParamsOptionDictionary,
} from '../api/types';
import {findConstraint} from './common/constraint/composite';
import {Constraint} from './common/constraint/constraint';
import {ListConstraint, ListItem} from './common/constraint/list';
import {StepConstraint} from './common/constraint/step';
import {getDecimalDigits} from './common/number-util';
function normalizeInputParamsOptions<T>(
options: InputParamsOption<unknown>[] | InputParamsOptionDictionary<unknown>,
convert: (value: unknown) => T,
): InputParamsOption<T>[] {
if (Array.isArray(options)) {
return options.map((item) => {
return {
text: item.text,
value: convert(item.value),
};
});
}
const textToValueMap = options;
const texts = Object.keys(textToValueMap);
return texts.reduce((result, text) => {
return result.concat({
text: text,
value: convert(textToValueMap[text]),
});
}, [] as InputParamsOption<T>[]);
}
/**
* Tries to create a list constraint.
* @template T The type of the raw value.
* @param params The input parameters object.
* @param convert The converter that converts unknown value into T.
* @return A constraint or null if not found.
*/
export function createListConstraint<T>(
params: InputParams,
convert: (value: unknown) => T,
): ListConstraint<T> | null {
if ('options' in params && params.options !== undefined) {
return new ListConstraint(
normalizeInputParamsOptions(params.options, convert),
);
}
return null;
}
/**
* @hidden
*/
export function findListItems<T>(
constraint: Constraint<T> | undefined,
): ListItem<T>[] | null {
const c = constraint
? findConstraint<ListConstraint<T>>(constraint, ListConstraint)
: null;
if (!c) {
return null;
}
return c.options;
}
function findStep(constraint: Constraint<number> | undefined): number | null {
const c = constraint ? findConstraint(constraint, StepConstraint) : null;
if (!c) {
return null;
}
return c.step;
}
/**
* @hidden
*/
export function getSuitableDecimalDigits(
constraint: Constraint<number> | undefined,
rawValue: number,
): number {
const sc = constraint && findConstraint(constraint, StepConstraint);
if (sc) {
return getDecimalDigits(sc.step);
}
return Math.max(getDecimalDigits(rawValue), 2);
}
/**
* @hidden
*/
export function getBaseStep(
constraint: Constraint<number> | undefined,
): number {
const step = findStep(constraint);
return step ?? 1;
}
/**
* @hidden
*/
export function getSuitableDraggingScale(
constraint: Constraint<number> | undefined,
rawValue: number,
): number {
const sc = constraint && findConstraint(constraint, StepConstraint);
const base = Math.abs(sc?.step ?? rawValue);
return base === 0 ? 0.1 : Math.pow(10, Math.floor(Math.log10(base)) - 1);
}
|
41108e05f1caca135b06ffaffa20ea91a1130236
|
TypeScript
|
Areyesfigueroa/Data-Structures-Practice
|
/src/DataStructures/Queue/Queue.ts
| 3.9375
| 4
|
export{}
export class Queue<Type> {
#elements:Type[] = [];
//Add element from the back
enqueue: (e:Type) => void = (e) => {
this.#elements.push(e);
}
//Remove element from the front
dequeue: () => Type | undefined = () => {
return this.#elements.shift();
}
isEmpty: () => boolean = () => {
return this.#elements.length === 0;
}
length: () => number = () => {
return this.#elements.length;
}
peek: () => Type = () => {
return this.#elements[0];
}
}
// let q = new Queue<number>();
// for(let i:number = 1; i <= 7; i++) {
// q.enqueue(i);
// }
// console.log(q.peek());
// console.log(q.length());
// //dequeue all elements
// while(!q.isEmpty()) {
// console.log(q.dequeue());
// }
// console.log(q.length());
|
3f3506d85a8f6be706b6fa756b0697c07baa6cb3
|
TypeScript
|
hillmychen/react-typescript-template
|
/src/api/common/types.ts
| 2.65625
| 3
|
/*
* @Author: Hughie
* @Date: 2021-04-18 18:10:20
* @LastEditors: Hughie
* @LastEditTime: 2021-04-18 18:17:05
* @Description:
*/
// 登录接口
export interface LoginRequest {
/** 手机号 */
phone: string
/** 密码 */
password: string
}
export interface LoginResponse {
/** ID */
id: number
/** 用户昵称 */
nickname: string
/** 手机号码 */
phone: string
/** 用户token */
token: string
/** 角色 */
role: string
/** 当前项目 */
study?: {
id: string
}
}
// 验证token
export interface CheckTokenResponse extends LoginResponse {
/** 用户名 */
username?: string
}
// 获取验证码
export interface GetAuthCodeRequest {
/** 手机号码 */
phone: string
/** 随机字符串 */
nonce: string
/** 签名 */
signature: string
/** 验证类型 */
category: GetAuthCodeRequestCategory
}
export type GetAuthCodeRequestCategory = 'login' | 'register' | 'reset' | 'bind'
// 上传文件
export type UploadFileResponse = UploadFileResponseItem[]
export interface UploadFileResponseItem {
filename: string
url: string
}
// 修改密码请求
export interface ChangePasswordRequest {
/** 原密码 */
old_password: string
/** 新密码 */
new_password: string
}
|
1d4638f34cb9c4cfa03f013bfd1fba39b9054037
|
TypeScript
|
avaschenko/la-components
|
/packages/utils/src/formatters/spaceSeparateThousands/spaceSeparateThousands.test.ts
| 3.078125
| 3
|
import spaceSeparateThousands from './spaceSeparateThousands';
import expect from 'expect.js';
describe('spaceSeparateThousands', () => {
const testOptions = [
{ input: 0, output: '0' },
{ input: 1, output: '1' },
{ input: -1, output: '-1' },
{ input: 1.1, output: '1.1' },
{ input: 1000, output: '1 000' },
{ input: 1000000, output: '1 000 000' },
{ input: 123456789, output: '123 456 789' },
{ input: 1000.001, output: '1 000.001' },
{ input: 1000000.00001, output: '1 000 000.00001' },
{ input: 123456789.000001, output: '123 456 789.000001' },
{ input: 1000, output: '1.000', customSeparator: '.' },
{ input: 1000000, output: '1.000.000', customSeparator: '.' },
{ input: 123456789, output: '123.456.789', customSeparator: '.' },
{ input: 1.1, output: '1.1', lengNumber: 2 },
{ input: 1000, output: '10 00', lengNumber: 2 },
{ input: 1000000, output: '1 00 00 00', lengNumber: 2 },
{ input: 123456789, output: '1 23 45 67 89', lengNumber: 2 },
{ input: 1000, output: '1000', lengNumber: 4 },
{ input: 1000000, output: '100 0000', lengNumber: 4 },
{ input: 123456789, output: '1 2345 6789', lengNumber: 4 },
];
testOptions.forEach((item, index) => {
const result = spaceSeparateThousands(item.input, item.customSeparator, item.lengNumber);
it(`Option ${index + 1}:
${item.input} => ${item.output} lengNumber=${item.lengNumber} result=${result}`, () => {
expect(result).to.be(item.output);
});
});
});
|
33ea0f9b870126969007d6eb703e058c66f2fba8
|
TypeScript
|
mtuduri/angular2-mdl
|
/dist/components/common/animations.d.ts
| 2.609375
| 3
|
export interface AnimationPlayer {
onDone(fn: () => void): void;
play(): void;
}
export declare class NativeWebAnimationPlayer implements AnimationPlayer {
private element;
private keyframes;
private duration;
private easing;
private onDoneCallback;
constructor(element: any, keyframes: {
[key: string]: string | number;
}[], duration: number, easing: string);
onDone(fn: () => void): void;
play(): void;
}
export declare class NoopAnimationPlayer implements AnimationPlayer {
private element;
private keyframes;
private duration;
private easing;
private onDoneCallback;
constructor(element: any, keyframes: {
[key: string]: string | number;
}[], duration: number, easing: string);
onDone(fn: () => void): void;
play(): void;
}
export declare abstract class Animations {
abstract animate(element: any, keyframes: {
[key: string]: string | number;
}[], duration: number, easing: string): AnimationPlayer;
}
export declare class NativeWebAnimations implements Animations {
animate(element: any, keyframes: {
[key: string]: string | number;
}[], duration: number, easing: string): AnimationPlayer;
}
export declare class NoopWebAnimations implements Animations {
animate(element: any, keyframes: {
[key: string]: string | number;
}[], duration: number, easing: string): AnimationPlayer;
}
|
c8748db3f1505c206378b01fc4ced9946b59cc25
|
TypeScript
|
b4nst/stream-mock
|
/src/writable/BufferWritableMock.ts
| 3.3125
| 3
|
/**
* @module writable
*/
import {Writable, WritableOptions} from 'stream'
import {chunk2Buffer} from '../helpers'
import IWritableMock from './IWritableMock'
/**
* BufferWritableMock is a writable stream working in normal (buffer) mode.
*
* @example
* ```typescript
* import { BufferWritableMock } from 'stream-mock';
*
* const writer = new BufferWritableMock();
* writer.write('l', err => {
* if (!err) console.log(writer.data);
* });
* writer.end();
* writer.on('finish', () => console.log(writer.flatData.toString()));
* ```
* ```bash
* >
* [ <Buffer 6c> ]
* l
* ```
*/
export default class BufferWritableMock extends Writable
implements IWritableMock {
/**
* Internal buffer, filled on every write
*/
public data: Buffer[];
/**
* Data flattern, filled on final callback (when [[BufferWritableMock.end]]) is called.
*/
public flatData: Buffer;
/**
* @param options Writable options. objectMode will be overwritten to false.
*/
constructor(options: WritableOptions = {}) {
options.objectMode = false;
super(options);
this.data = [];
}
// tslint:disable-next-line:function-name Not responsible of this function name
public _write(
chunk: Buffer | string,
encoding: BufferEncoding,
callback: (error?: Error | null) => void
) {
this.data.push(chunk2Buffer({ chunk, encoding }));
callback();
}
// tslint:disable-next-line:function-name Not responsible of this function name
public _final(callback: (error?: Error | null) => void) {
this.flatData = Buffer.concat(this.data);
callback();
}
}
|
dc03285e1ff74f82328215aefc07f41256c9bddf
|
TypeScript
|
PeterStaev/NativeScript-Status-Bar
|
/sample/StatusBarSample/typings/tns-core-modules/ui/core/view.d.ts
| 2.953125
| 3
|
declare module "ui/core/view" {
import style = require("ui/styling");
import dependencyObservable = require("ui/core/dependency-observable");
import proxy = require("ui/core/proxy");
import gestures = require("ui/gestures");
import color = require("color");
import observable = require("data/observable");
import animation = require("ui/animation");
/**
* Gets a child view by id.
* @param view - The parent (container) view of the view to look for.
* @param id - The id of the view to look for.
* Returns an instance of a view (if found), otherwise undefined.
*/
export function getViewById(view: View, id: string): View;
/**
* Iterates through all child views (via visual tree) and executes a function.
* @param view - Starting view (parent container).
* @param callback - A function to execute on every child. If function returns false it breaks the iteration.
*/
export function eachDescendant(view: View, callback: (child: View) => boolean);
/**
* Gets an ancestor from a given type.
* @param view - Starting view (child view).
* @param criterion - The type of ancestor view we are looking for. Could be a string containing a class name or an actual type.
* Returns an instance of a view (if found), otherwise undefined.
*/
export function getAncestor(view: View, criterion: string | Function): View;
export function isEventOrGesture(name: string, view: View): boolean;
/**
* Defines interface for an optional parameter used to create a view.
*/
export interface Options {
/**
* Gets or sets the desired width of the view.
*/
width?: number;
/**
* Gets or sets the desired height of the view.
*/
height?: number;
/**
* Gets or sets the minimum width the view may grow to.
*/
minWidth?: number;
/**
* Gets or sets the minimum height the view may grow to.
*/
minHeight?: number;
/**
* Gets or sets the alignment of this view within its parent along the Horizontal axis.
*/
horizontalAlignment?: string;
/**
* Gets or sets the alignment of this view within its parent along the Vertical axis.
*/
verticalAlignment?: string;
/**
* Specifies extra space on the left side of this view.
*/
marginLeft: number;
/**
* Specifies extra space on the top side of this view.
*/
marginTop: number;
/**
* Specifies extra space on the right side of this view.
*/
marginRight: number;
/**
* Specifies extra space on the bottom side of this view.
*/
marginBottom: number;
/**
* Gets or sets the visibility of this view.
*/
visibility?: string;
/**
* [Deprecated. Please use className instead] Gets or sets the CSS class of this view.
*/
cssClass?: string;
/**
* Gets or sets the CSS class name of this view.
*/
className?: string;
/**
* Gets or sets the id of this view.
*/
id?: string;
}
/**
* This class is the base class for all UI components.
* A View occupies a rectangular area on the screen and is responsible for drawing and layouting of all UI components within.
*/
export class View extends proxy.ProxyObject implements ApplyXmlAttributes {
/**
* Gets or sets the corner radius of the view.
*/
borderRadius: number;
/**
* Gets or sets the border width of the view.
*/
borderWidth: number;
/**
* Gets or sets the border color of the view.
*/
borderColor: color.Color;
/**
* String value used when hooking to loaded event.
*/
public static loadedEvent: string;
/**
* String value used when hooking to unloaded event.
*/
public static unloadedEvent: string;
/**
* Represents the observable property backing the id property of each View.
*/
public static idProperty: dependencyObservable.Property;
/**
* [Deprecated. Please use className instead.] Represents the observable property backing the cssClass property of each View.
*/
public static cssClassProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the className property of each View.
*/
public static classNameProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the isEnabled property of each View.
*/
public static isEnabledProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the isUserInteractionEnabled property of each View.
*/
public static isUserInteractionEnabledProperty: dependencyObservable.Property;
constructor(options?: Options);
//----------Style property shortcuts----------
/**
* Gets or sets the color of the view.
*/
color: color.Color;
/**
* Gets or sets the background color of the view.
*/
backgroundColor: color.Color;
/**
* Gets or sets the background image of the view.
*/
backgroundImage: string;
/**
* Gets or sets the minimum width the view may grow to.
*/
minWidth: number;
/**
* Gets or sets the minimum height the view may grow to.
*/
minHeight: number;
/**
* Gets or sets the desired width of the view.
*/
width: number;
/**
* Gets or sets the desired height of the view.
*/
height: number;
/**
* Gets or sets margin style property.
*/
margin: string;
/**
* Specifies extra space on the left side of this view.
*/
marginLeft: number;
/**
* Specifies extra space on the top side of this view.
*/
marginTop: number;
/**
* Specifies extra space on the right side of this view.
*/
marginRight: number;
/**
* Specifies extra space on the bottom side of this view.
*/
marginBottom: number;
/**
* Gets or sets the alignment of this view within its parent along the Horizontal axis.
*/
horizontalAlignment: string;
/**
* Gets or sets the alignment of this view within its parent along the Vertical axis.
*/
verticalAlignment: string;
/**
* Gets or sets the visibility of the view.
*/
visibility: string;
/**
* Gets or sets the opacity style property.
*/
opacity: number;
//----------Style property shortcuts----------
/**
* Gets or sets the translateX affine transform of the view.
*/
translateX: number;
/**
* Gets or sets the translateY affine transform of the view.
*/
translateY: number;
/**
* Gets or sets the scaleX affine transform of the view.
*/
scaleX: number;
/**
* Gets or sets the scaleY affine transform of the view.
*/
scaleY: number;
/**
* Gets or sets the X component of the origin point around which the view will be transformed. The deafault value is 0.5 representing the center of the view.
*/
originX: number;
/**
* Gets or sets the Y component of the origin point around which the view will be transformed. The deafault value is 0.5 representing the center of the view.
*/
originY: number;
/**
* Gets or sets the rotate affine transform of the view.
*/
rotate: number;
/**
* Gets or sets a value indicating whether the the view is enabled. This affects the appearance of the view.
*/
isEnabled: boolean;
/**
* Gets or sets a value indicating whether the user can interact with the view. This does not affect the appearance of the view.
*/
isUserInteractionEnabled: boolean;
/**
* Gets or sets the id for this view.
*/
id: string;
/**
* [Deprecated. Please use className instead.] Gets or sets the CSS class for this view.
*/
cssClass: string;
/**
* Gets or sets the CSS class name for this view.
*/
className: string;
/**
* Gets the style object associated to this view.
*/
style: style.Style;
/**
* Gets the View instance that parents this view. This property is read-only.
*/
parent: View;
/**
* Gets is layout is valid. This is a read-only property.
*/
isLayoutValid: boolean;
cssType: string;
visualState: string;
/**
* Gets owner page. This is a read-only property.
*/
page: View;
/**
* This is called to find out how big a view should be. The parent supplies constraint information in the width and height parameters.
* The actual measurement work of a view is performed in onMeasure(int, int), called by this method. Therefore, only onMeasure(int, int) can and must be overridden by subclasses.
* @param widthMeasureSpec Horizontal space requirements as imposed by the parent
* @param heightMeasureSpec Vertical space requirements as imposed by the parent
*/
public measure(widthMeasureSpec: number, heightMeasureSpec: number): void;
/**
* Assign a size and position to a view and all of its descendants
* This is the second phase of the layout mechanism. (The first is measuring). In this phase, each parent calls layout on all of its children to position them. This is typically done using the child measurements that were stored in the measure pass().
* Derived classes should not override this method. Derived classes with children should override onLayout. In that method, they should call layout on each of their children.
* @param l Left position, relative to parent
* @param t Top position, relative to parent
* @param r Right position, relative to parent
* @param b Bottom position, relative to parent
*/
public layout(left: number, top: number, right: number, bottom: number): void;
/**
* Returns the raw width component.
*/
public getMeasuredWidth(): number;
/**
* Returns the raw height component.
*/
public getMeasuredHeight(): number;
/**
* Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree.
*/
public requestLayout(): void;
/**
* Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.
* When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an exception, thrown by measure(int, int).
* @param widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
* @param heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
*/
public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void;
/**
* Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
*/
public onLayout(left: number, top: number, right: number, bottom: number): void;
/**
* This method must be called by onMeasure(int, int) to store the measured width and measured height. Failing to do so will trigger an exception at measurement time.
* @param measuredWidth The measured width of this view. May be a complex bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL.
* @param measuredHeight The measured height of this view. May be a complex bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL.
*/
public setMeasuredDimension(measuredWidth: number, measuredHeight: number): void;
public layoutNativeView(left: number, top: number, right: number, bottom: number): void;
public static measureChild(parent: View, child: View, widthMeasureSpec: number, heightMeasureSpec: number): { measuredWidth: number; measuredHeight: number };
public static layoutChild(parent: View, child: View, left: number, top: number, right: number, bottom: number): void;
/**
* Utility to reconcile a desired size and state, with constraints imposed
* by a MeasureSpec. Will take the desired size, unless a different size
* is imposed by the constraints. The returned value is a compound integer,
* with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
* optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
* size is smaller than the size the view wants to be.
*/
public static resolveSizeAndState(size: number, specSize: number, specMode: number, childMeasuredState: number): number;
/**
* Returns the child view with the specified id.
*/
getViewById<T extends View>(id: string): T;
/**
* Tries to focus the view.
* Returns a value indicating whether this view or one of its descendants actually took focus.
*/
public focus(): boolean;
/**
* Sets in-line CSS string as style.
* @param style - In-line CSS string.
*/
public setInlineStyle(style: string) : void;
public getGestureObservers(type: gestures.GestureTypes): Array<gestures.GesturesObserver>;
/**
* [Deprecated. Please use the on() instead.] Adds a gesture observer.
* @param type - Type of the gesture.
* @param callback - A function that will be executed when gesture is received.
* @param thisArg - An optional parameter which will be used as `this` context for callback execution.
*/
observe(type: gestures.GestureTypes, callback: (args: gestures.GestureEventData) => void, thisArg?: any);
/**
* A basic method signature to hook an event listener (shortcut alias to the addEventListener method).
* @param eventNames - String corresponding to events (e.g. "propertyChange"). Optionally could be used more events separated by `,` (e.g. "propertyChange", "change") or you can use gesture types.
* @param callback - Callback function which will be executed when event is raised.
* @param thisArg - An optional parameter which will be used as `this` context for callback execution.
*/
on(eventNames: string | gestures.GestureTypes, callback: (data: observable.EventData) => void, thisArg?: any);
/**
* Removes listener(s) for the specified event name.
* @param eventNames Comma delimited names of the events or gesture types the specified listener is associated with.
* @param callback An optional parameter pointing to a specific listener. If not defined, all listeners for the event names will be removed.
* @param thisArg An optional parameter which when set will be used to refine search of the correct callback which will be removed as event listener.
*/
off(eventNames: string | gestures.GestureTypes, callback?: any, thisArg?: any);
/**
* Raised when a loaded event occurs.
*/
on(event: "loaded", callback: (args: observable.EventData) => void, thisArg?: any);
/**
* Raised when an unloaded event occurs.
*/
on(event: "unloaded", callback: (args: observable.EventData) => void, thisArg?: any);
public animate(options: animation.AnimationDefinition): Promise<void>;
public createAnimation(options: animation.AnimationDefinition): animation.Animation;
// Lifecycle events
onLoaded(): void;
onUnloaded(): void;
isLoaded: boolean;
_addView(view: View, atIndex?: number);
_propagateInheritableProperties(view: View)
_inheritProperties(parentView: View)
_removeView(view: View);
_context: any /* android.content.Context */;
public _applyXmlAttribute(attribute: string, value: any): boolean;
// TODO: Implement logic for stripping these lines out
}
/**
* Base class for all UI components that implements custom layouts.
*/
export class CustomLayoutView extends View {
}
/**
* Defines an interface for a View factory function.
* Commonly used to specify the visualization of data objects.
*/
interface Template {
/**
* Call signature of the factory function.
* Returns a new View instance.
*/
(): View;
}
/**
* Defines an interface for adding arrays declared in xml.
*/
interface AddArrayFromBuilder {
/**
* A function that is called when an array declaration is found in xml.
* @param name - Name of the array.
* @param value - The actual value of the array.
*/
_addArrayFromBuilder(name: string, value: Array<any>): void;
}
/**
* Defines an interface for adding a child element declared in xml.
*/
interface AddChildFromBuilder {
/**
* Called for every child element declared in xml.
* This method will add a child element (value) to current element.
* @param name - Name of the element.
* @param value - Value of the element.
*/
_addChildFromBuilder(name: string, value: any): void;
}
/**
* Defines an interface used to create a member of a class from string representation (used in xml declaration).
*/
interface ApplyXmlAttributes {
/**
* Called for every attribute in xml declaration. <... fontAttributes="bold" ../>
* @param attributeName - the name of the attribute (fontAttributes)
* @param attrValue - the value of the attribute (bold)
* Should return true if this attribute is handled and there is no need default handler to process it.
*/
_applyXmlAttribute(attributeName: string, attrValue: any): boolean;
}
}
|
489f75bb5de7782a96ce980dba58eb2c8a45ed96
|
TypeScript
|
mshzidan22/akoam-scraper-api
|
/src/app.ts
| 2.53125
| 3
|
import express from 'express';
import { AkoamLink } from './AkoamLink';
import {run} from './script'
var path = require('path');
const app = express();
const port = process.env.PORT || 3000
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
})
app.get('/akoamapi', (req, res) => {
const link = req.query.link;
const isPlayList = req.query.isPlayList
const mostRecent = req.query.mostRecent
const episodeToscrap = req.query.episodeToscrap
const neededQuality = req.query.neededQuality
let akoamLink = new AkoamLink()
akoamLink.setLink(link).setIsPlayList(isPlayList).setMostRecent(mostRecent)
.setEpisodeToscrap(episodeToscrap).setNeededQuality(neededQuality)
console.log(akoamLink.mostRecent + "is the most recent")
run(akoamLink).then(out => res.send(out)).catch(console.log)
});
app.listen(port, err => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
|
998e8e05d5affe85111e70db7139c21468fc9845
|
TypeScript
|
edwinvillota/portfolio_v2_api
|
/src/users/dao/users.dao.ts
| 2.8125
| 3
|
import { User } from '../models/User';
import { CreateUserDto } from '../dto/create.user.dto';
import { PutUserDto } from '../dto/put.user.dto';
import { PatchUserDto } from '../dto/patch.user.dto';
import debug from 'debug';
const log: debug.IDebugger = debug('app:in-memory-dao');
type PatchUserAttributesType = keyof PutUserDto;
class UserDao {
users: Array<CreateUserDto> = [];
constructor() {
log('Created new instance of UsersDao');
}
async getUsers() {
return User.findAll();
}
async addUser(userFields: CreateUserDto) {
const newUser = await User.create(userFields);
return newUser;
}
async getUserById(userId: string) {
return User.findByPk(userId);
}
async putUserById(userId: string, user: PutUserDto) {
const userToUpdate = await User.findByPk(userId);
if (userToUpdate) {
const updatedUser = await userToUpdate.update(user);
return updatedUser;
} else {
return null;
}
}
async patchUserById(userId: string, user: PatchUserDto) {
const userToPatch = await User.findByPk(userId);
if (userToPatch) {
const attributesAllowedToPatch: PatchUserAttributesType[] = ['firstName', 'lastName'];
const updatedAttributes: { [x: string]: any } = {};
for (const field of attributesAllowedToPatch) {
if (field in user) {
updatedAttributes[field] = user[field];
}
}
const patchedUser = await userToPatch.update(updatedAttributes);
return patchedUser;
} else {
return null;
}
}
async removeUserById(userId: string) {
const userToRemove = await User.findByPk(userId);
if (userToRemove) {
try {
userToRemove.destroy();
return `User with user id ${userId} has been deleted`;
} catch (error) {
return `Error: ${error}`;
}
}
return `User with user id ${userId} not found`;
}
async getUserByEmail(email: string) {
const user = await User.findOne({
where: {
email: email,
},
});
if (user) {
return user;
} else {
return null;
}
}
}
export default new UserDao();
|
ba445159cba1541d04d9fa73cf9ae6003f1699f0
|
TypeScript
|
jacobclarke92/waverider-tonejs
|
/src/fileManager.ts
| 2.515625
| 3
|
import { Store } from 'redux'
import { ReduxStoreType, ThunkDispatchType } from './types'
import { downloadData } from './utils/blobUtils'
import { updateProjectMeta } from './reducers/project'
import { overwriteInstruments } from './reducers/instruments'
import { overwriteEffects } from './reducers/effects'
import { overwriteDesk } from './reducers/desk'
let store: Store
export function init(_store: Store) {
store = _store
}
export function saveProjectFile() {
const { project, desk, devices, effects, instruments } = store.getState() as ReduxStoreType
if (!project.title) {
const title = prompt('Please name your project', 'Untitled')
if (!title) return
store.dispatch(updateProjectMeta({ title }))
setTimeout(saveProjectFile, 100)
return
}
const state = { project, desk, devices, effects, instruments }
const data = JSON.stringify(state, null, 2)
downloadData(data, 'text/json', `${project.title || 'project'}.json`)
}
export function loadProjectFile(file: string) {
console.log('----- LOADING PROJECT FILE -----')
let data: ReduxStoreType
try {
data = JSON.parse(file) as ReduxStoreType
} catch (error) {
console.warn('Unable to load file', error)
return false
}
if (!data) return false
if (data.instruments) (store.dispatch as ThunkDispatchType)(overwriteInstruments(data.instruments))
if (data.effects) (store.dispatch as ThunkDispatchType)(overwriteEffects(data.effects))
if (data.desk) (store.dispatch as ThunkDispatchType)(overwriteDesk(data.desk))
console.log('----- PROJECT FILE LOADED -----')
}
|
652fc4a0e3efabdd05e11eb7eb0fef8790e0fa0a
|
TypeScript
|
wybosys/nnt.game.h5
|
/project/src/nnt/gui/bitmap.ts
| 2.609375
| 3
|
module nn {
// 和使用textmerge划分的数据保持一致
export type Point9 = [number, number, number, number];
export abstract class CBitmap extends Widget {
constructor(res?: TextureSource) {
super();
}
dispose() {
super.dispose();
}
protected _initSignals() {
super._initSignals();
this._signals.register(SignalChanged);
}
/** 9点 */
point9: Point9;
/** 素材 */
imageSource: TextureSource;
/** 填充模式 */
fillMode = FillMode.STRETCH;
/** 期望的大小 */
preferredFrame: Rect;
}
}
|
cb761950e29da81733bc2c605e603efd2b7615b9
|
TypeScript
|
gsanta/silhouette-people
|
/src/model/objects/game_object/GameObjectState.ts
| 2.796875
| 3
|
import { GameObject } from "./GameObject";
export enum GameObjectStateName {
CharacterIdleState = 'CharacterIdleState',
CharacterWalkingState = 'CharacterWalkingState',
BikeIdleState = 'BikeIdleState',
BikeMovingState = 'BikeMovingState'
}
export abstract class GameObjectState {
protected _isDirty = false;
protected character: GameObject;
constructor(meshObj: GameObject) {
this.character = meshObj;
if (meshObj.stateController && meshObj.stateController.state) {
meshObj.stateController.state.exitState();
}
}
isDirty() {
return this._isDirty;
}
clearDirty() {
this._isDirty = false;
}
update(deltaTime: number) {}
enterState() {}
exitState() {
this.character.animation.stopCurrentAnimation();
}
}
|
c1c6b5e47e8a976de08b4140bfa58c8538e0144a
|
TypeScript
|
RamiroMaydana/API-express-ts-mongo
|
/src/rutas/UsuarioRutas.ts
| 2.765625
| 3
|
// Modulos de Express
import { Request, Response, NextFunction, Router} from 'express';
// Esquema de documento Usuario
import Usuario from '../modelos/Usuario';
class UserRouter {
router: Router;
constructor(){
this.router = Router();
this.routes();
}
async obtenerUsuarios(req: Request, res: Response){
const usuarios = await Usuario.find();
res.json(usuarios);
}
async obtenerUsuario(req: Request, res: Response){
//const usuario = await Usuario.findById(req.params.id).populate('posts');
const usuario = await Usuario.findById(req.params.id);
res.json(usuario);
}
async crearUsuario(req: Request, res: Response){
const nuevoUsuario = new Usuario(req.body);
await nuevoUsuario.save();
res.json({ status: 200, nuevoUsuario});
}
async actualizarUsuario(req: Request, res: Response){
const { id } = req.params;
const usuario = await Usuario.findByIdAndUpdate(id, req.body, {new:
true } );
res.json(usuario);
}
async eliminarUsuario(req: Request, res: Response){
const { id } = req.params;
const usuario=await Usuario.findByIdAndRemove(id);
res.json(usuario);
}
routes(){
this.router.get('/', this.obtenerUsuarios);
this.router.get('/:id', this.obtenerUsuario);
this.router.post('/', this.crearUsuario);
this.router.put('/:id', this.actualizarUsuario);
this.router.delete('/:id', this.eliminarUsuario);
}
}
const userRouter = new UserRouter();
export default userRouter.router;
|
f9e74b6bee2634098da7e16ac1c280acce706aa4
|
TypeScript
|
jinleili/rum-app
|
/src/utils/formatPath.ts
| 2.5625
| 3
|
import { isWindow } from 'utils/env';
export default (path: string, options: { truncateLength: number }) => {
const _path = isWindow ? path.replaceAll('/', '\\') : path;
return _path.length > options.truncateLength
? `...${_path.slice(-options.truncateLength)}`
: _path;
};
|
bcf196a332c026c08b9867fa93cca87703088373
|
TypeScript
|
brice-dymas/pedag
|
/src/main/webapp/app/entities/administrateur/administrateur.model.ts
| 2.734375
| 3
|
import { IUser } from 'app/entities/user/user.model';
import { Grade } from 'app/entities/enumerations/grade.model';
export interface IAdministrateur {
id?: number;
nom?: string;
prenom?: string | null;
email?: string;
grade?: Grade;
user?: IUser | null;
}
export class Administrateur implements IAdministrateur {
constructor(
public id?: number,
public nom?: string,
public prenom?: string | null,
public email?: string,
public grade?: Grade,
public user?: IUser | null
) {}
}
export function getAdministrateurIdentifier(administrateur: IAdministrateur): number | undefined {
return administrateur.id;
}
|
866131d8fccb06328f54e1d83a82da01d76ae1d9
|
TypeScript
|
I-dela/KLM-Project-FrontEnd
|
/src/app/services/equipment.service.spec.ts
| 2.578125
| 3
|
import {getTestBed, TestBed} from '@angular/core/testing';
import {EquipmentService} from './equipment.service';
import {Equipment, EquipmentStatus} from '../models/equipment';
import {EquipmentType} from '../models/equipmentType';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {of} from 'rxjs';
/*
Author: Ilias Delawar , 500783016
*/
describe('Equipment', () => {
// We declare the variables that we'll use for the Test Controller and for our Service
let httpTestingController: HttpTestingController;
let service: EquipmentService;
let injector: TestBed;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [EquipmentService],
imports: [HttpClientTestingModule]
});
// We inject our service (which imports the HttpClient) and the Test Controller
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(EquipmentService);
injector = getTestBed();
});
afterEach(() => {
httpTestingController.verify();
});
// Angular default test added when you generate a service using the CLI
it('should be created', () => {
expect(service).toBeTruthy();
});
// it("returnEquipments should return data", () => {
// let equipmentType: EquipmentType = new EquipmentType();
// equipmentType.subgroup = 'Nitrogen cart';
// equipmentType.id = 2;
// equipmentType.group = 'Nitrogen cart';
// equipmentType.abbreviation = 'NC';
//
// // let mockEquipment = new Equipment('STK003', 'Ilias', equipmentType, EquipmentStatus.usable, null, 0, 0);
//
// // const dummyList = [mockEquipment];
//
// const dummyList: Equipment[] = [{
// serialNumber: "STK0003",
// id: "Ilias" ,
// type: equipmentType,
// status : EquipmentStatus.usable,
// statusDescription: null,
// longitude: 0,
// latitude: 0
// }];
//
//
// spyOn(service,'returnEquipmentList').and.returnValue(of(dummyList));
//
//
// service.returnEquipmentList().subscribe((res) => {
// expect(res).toEqual(dummyList)
// });
//
// const req = httpTestingController.expectOne('http://localhost:8080/equipment/');
// expect(req.request.method).toBe('GET');
// req.flush(dummyList);
//
// });
it("getEquipmentById should return one Object of equipment", ()=>{
let equipmentType: EquipmentType = new EquipmentType();
equipmentType.subgroup = 'Nitrogen cart';
equipmentType.id = 2;
equipmentType.group = 'Nitrogen cart';
equipmentType.abbreviation = 'NC';
const dummyEquipment ={
serialNumber: "STK0003",
id: "Ilias" ,
type: equipmentType,
status : EquipmentStatus.usable,
statusDescription: null,
longitude: 0,
latitude: 0
};
spyOn(service,'getEquipmentById').withArgs("STK0003").and.returnValue(of(dummyEquipment));
service.getEquipmentById("STK0003").subscribe((data:any) => {
expect(data).toEqual(dummyEquipment);
})
})
});
|
ee83cbc78517447ef95a2f90bba79e12c939d0fd
|
TypeScript
|
ByzantineFailure/UNIAC-Player
|
/src/lib/handlers/party_api.ts
| 2.609375
| 3
|
import {Express, Response} from "express";
import {Spotify} from "../spotify";
import {AsyncHandler, ErrorCodes, Handler, IAddTrackRequest, IErrorMessage, IGetPlayStateResponse} from "../../types/api";
import * as Paths from "../paths";
import { Authentication, redirectForAuth } from "./auth";
const TRACK_URI_REGEX = /spotify:track:(.+)/.compile();
// Also handles setting the error states and sending the error object. If false, stop handler.
// Realistically this should be a middleware but I'm too lazy to restructure things right now.
function trackUriIsValid(uri: string, response: Response): boolean {
if (!uri || !TRACK_URI_REGEX.test(uri)) {
response.status(400);
response.send({
code: ErrorCodes.MALFORMATTED_URI,
message: 'Missing or malformatted URI, please ensure your uri matches "spotify:track:ID"'
});
response.end();
return false;
}
return true;
}
async function sendTracksAsResponse(spotify: Spotify, response: Response) {
const rawTracks = await spotify.getPartyPlaylistTracks();
const tracks = rawTracks.map((rawTrack) => rawTrack.track);
const playlist = spotify.playlist;
response.status(200);
response.send({
playlist,
tracks
});
response.end();
}
function sendPlaystateAsReponse(spotify: Spotify, response: Response) {
const responseBody: IGetPlayStateResponse = {
currentTrack: spotify.currentTrack ? spotify.currentTrack.track : null,
isPlaying: !!spotify.isPlaying,
};
response.status(200);
response.send(responseBody);
response.end();
}
function getTracklistHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
try {
sendTracksAsResponse(spotify, res);
} catch (error) {
res.status(500);
res.send(error);
res.end();
}
};
}
function addTrackHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
const request: IAddTrackRequest = req.body;
if (!trackUriIsValid(request.uri, res)) {
return;
}
try {
await spotify.addTrackToPlaylist(request.uri, request.toFront);
sendTracksAsResponse(spotify, res);
} catch (error) {
// TODO figure out needle's error response object and give 404 for an unknown uri.
console.log(error);
res.status(500);
res.send(error);
res.end();
}
};
}
function removeTrackHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
const request: IAddTrackRequest = req.body;
if (!trackUriIsValid(request.uri, res)) {
return;
}
if (spotify.currentTrack && spotify.currentTrack.track.uri === request.uri) {
const errorResponse: IErrorMessage = {
code: ErrorCodes.CANNOT_REMOVE_CURRENTLY_PLAYING,
message: "Cannot remove the currently playing track!",
};
res.status(400);
res.send(errorResponse);
res.end();
return;
}
try {
await spotify.removeTrackFromPlaylist(request.uri);
sendTracksAsResponse(spotify, res);
} catch (error) {
// TODO figure out needle's error response object and give 404 for an unknown uri.
console.log(error);
res.status(500);
res.send(error);
res.end();
}
};
}
function getCurrentTrackHandler(spotify: Spotify): Handler {
return (req, res) => {
sendPlaystateAsReponse(spotify, res);
};
}
function nextTrackHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
if (spotify.currentTrack === null || spotify.currentTracklist.length <= 1) {
const errorResponse = {
code: ErrorCodes.CANNOT_SKIP,
message: "Cannot skip track; no track playing or not enough tracks in queue",
};
res.send(errorResponse);
res.status(400);
res.end();
return;
}
await spotify.partyNextTrack();
sendPlaystateAsReponse(spotify, res);
};
}
function startPlaybackHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
if (spotify.currentTrack !== null && spotify.isPlaying) {
const errorMessage: IErrorMessage = {
code: ErrorCodes.ALREADY_PLAYING,
message: "Already playing, cannot "
};
res.status(400);
res.send(errorMessage);
res.end();
return;
}
await spotify.partyStartPlayback();
sendPlaystateAsReponse(spotify, res);
};
}
function pausePlaybackHandler(spotify: Spotify): AsyncHandler {
return async (req, res) => {
if (spotify.currentTrack === null) {
const errorMessage: IErrorMessage = {
code: ErrorCodes.NOT_PLAYING,
message: "Not playing right now, cannot pause",
};
res.status(400);
res.send(errorMessage);
res.end();
return;
}
await spotify.partyPausePlayback();
sendPlaystateAsReponse(spotify, res);
};
}
export function registerPartyHandlers(app: Express, spotify: Spotify, auth: Authentication) {
app.get(Paths.PARTY_GET_TRACKS_PATH, redirectForAuth(auth, getTracklistHandler(spotify)));
app.put(Paths.PARTY_ADD_TRACK_PATH, redirectForAuth(auth, addTrackHandler(spotify)));
app.delete(Paths.PARTY_REMOVE_TRACK_PATH, redirectForAuth(auth, removeTrackHandler(spotify)));
app.get(Paths.PARTY_GET_CURRENT_TRACK_PATH, redirectForAuth(auth, getCurrentTrackHandler(spotify)));
app.post(Paths.PARTY_NEXT_TRACK_PATH, redirectForAuth(auth, nextTrackHandler(spotify)));
app.post(Paths.PARTY_PLAY_PATH, redirectForAuth(auth, startPlaybackHandler(spotify)));
app.post(Paths.PARTY_PAUSE_PATH, redirectForAuth(auth, pausePlaybackHandler(spotify)));
}
|
d13559ab1918dce0bf510911af234ac5e5602bbc
|
TypeScript
|
isabella232/hotspot-app
|
/src/utils/location.ts
| 3.34375
| 3
|
import * as Location from 'expo-location'
export type LocationCoords = { latitude: number; longitude: number }
export const reverseGeocode = async (latitude: number, longitude: number) =>
Location.reverseGeocodeAsync({ latitude, longitude })
export const getCurrentPosition = async (
accuracy: Location.LocationAccuracy = Location.LocationAccuracy.Balanced,
) => {
const pos = await Location.getCurrentPositionAsync({ accuracy })
return pos.coords
}
function toRad(x: number): number {
return (x * Math.PI) / 180
}
export const distance = (coords1: LocationCoords, coords2: LocationCoords) => {
const { latitude: lat1, longitude: lon1 } = coords1
const { latitude: lat2, longitude: lon2 } = coords2
const R = 6371 // km
const x1 = lat2 - lat1
const dLat = toRad(x1)
const x2 = lon2 - lon1
const dLon = toRad(x2)
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) *
Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2)
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
const d = R * c
return d
}
|
5fc3b19a9ee88b021a8ee9fcb2ad65f2610d9919
|
TypeScript
|
intjr/github-state
|
/projects/simple-store/src/app/store/actions.ts
| 2.65625
| 3
|
import { Resort } from './models';
import { Action } from './store';
export enum SidenavActionTypes {
HideSidenav = '[Sidenav] Hide Sidenav',
ShowSidenav = '[Sidenav] Show Sidenav'
}
export class HideSidenav implements Action {
readonly type = SidenavActionTypes.HideSidenav;
}
export class ShowSidenav implements Action {
readonly type = SidenavActionTypes.ShowSidenav;
}
export type SidenavAction = HideSidenav | ShowSidenav;
export enum ResortActions {
LoadResorts = '[resorts] Load',
LoadResortsFail = '[resorts] Load fail',
LoadResortsSuccess = '[resorts] Load success'
}
export class LoadResorts implements Action {
readonly type = ResortActions.LoadResorts;
}
export class LoadResortsFail implements Action {
readonly type = ResortActions.LoadResortsFail;
constructor(public error: Error) {}
}
export class LoadResortsSuccess implements Action {
readonly type = ResortActions.LoadResortsSuccess;
constructor(public resorts: Resort[]) {}
}
export type ResortAction = LoadResorts | LoadResortsSuccess | LoadResortsFail;
|
7a52a6a0bb15fc642a7c2bbfaa5fa5ed309e31e2
|
TypeScript
|
boltex/morejs
|
/src/moreOutline.ts
| 2.5625
| 3
|
import * as vscode from 'vscode';
import { More } from './more';
/**
* * Structural node type used by the model.
* (vscode needs TreeItem via getTreeItem in the TreeDataProvider)
*/
export interface PNode {
header: string;
gnx: string;
children: PNode[];
parent?: PNode;
selected?: boolean;
}
/**
* * Icon path names used in leoNodes for rendering in treeview
*/
interface Icon {
light: string;
dark: string;
}
/**
* * Tree item type node that gets displayed by vscode
*/
export class MoreNode extends vscode.TreeItem {
constructor(
public label: string, // Node headline
public collapsibleState: vscode.TreeItemCollapsibleState, // Computed in receiver/creator
public pnode: PNode,
public dirty: boolean,
public hasBody: boolean,
private _icons: Icon[]
) {
super(label, collapsibleState);
this.command = {
command: 'morejs.selectNode',
title: '',
arguments: [this.pnode],
};
}
// @ts-ignore
public get iconPath(): Icon {
return this._icons[0];
}
}
/**
* * Outline Provider for immutable test structures
*/
export class MoreOutlineProvider implements vscode.TreeDataProvider<PNode> {
private _onDidChangeTreeData: vscode.EventEmitter<PNode | undefined | null | void> = new vscode.EventEmitter<PNode | undefined | null | void>();
readonly onDidChangeTreeData: vscode.Event<PNode | undefined | null | void> = this._onDidChangeTreeData.event;
private _icons: Icon[];
// * IMMUTABLE sample test outline structures. Each with predefined 'selected' node.
public modelId: number;
public model: PNode[][] = [];
public model1: PNode[] = [
{
header: 'node1',
gnx: '1',
children: [],
},
{
header: 'node2',
gnx: '2',
children: [],
selected: true // predefined as 'selected'.
},
{
header: 'node3',
gnx: '3',
children: [
{
header: 'childNode4',
gnx: '4',
children: [],
},
{
header: 'childNode5',
gnx: '5',
children: [],
},
],
},
];
public model2: PNode[] = [
{
header: 'node6',
gnx: '6',
children: [],
},
{
header: 'node7',
gnx: '7',
children: [
{
header: 'node8',
gnx: '8',
children: [
{
header: 'childNode9',
gnx: '9',
children: [],
},
],
},
],
},
{
header: 'childNode10',
gnx: '10',
children: [],
selected: true // predefined as 'selected'.
}
];
// MUTABLE text bodies to test modifications and display transitions.
public bodies: { [gnx: string]: string } = {
'1': 'node1 body',
'2': 'node2 body',
'3': 'node3 body',
'4': 'node4 body',
'5': 'node5 body',
'6': 'node6 body',
'7': 'node7 body',
'8': 'node8 body',
'9': 'node9 body',
'10': 'node10 body',
};
constructor(
private _context: vscode.ExtensionContext,
private _more: More
) {
this._icons = this._buildNodeIconPaths(_context);
this.modelId = 0;
this._buildParents(this.model1);
this._buildParents(this.model2);
this.model.push(this.model1);
this.model.push(this.model2);
console.log('Starting MOREJS tree provider');
}
public switchModel(p_id: number) {
console.log('switch model to:', p_id);
// Either 1 or 2
if (p_id === 1) {
this.modelId = 0;
} else {
this.modelId = 1;
}
}
public refreshTreeRoot(): void {
console.log('REFRESH');
this._onDidChangeTreeData.fire();
}
public getTreeItem(element: PNode): MoreNode {
let w_body = this.bodies[element.gnx];
if (element.selected) {
setTimeout(() => {
this._more.revealTreeViewNode(element, { select: true, focus: false });
this._more!.applyNodeToBody(element, false, false);
}, 0);
}
return new MoreNode(
element.header,
element.children.length
? vscode.TreeItemCollapsibleState.Collapsed
: vscode.TreeItemCollapsibleState.None,
element,
false,
!!w_body && !!w_body.length,
this._icons
);
}
public getChildren(element?: PNode): vscode.ProviderResult<PNode[]> {
if (element) {
console.log('REFRESH a node');
return element.children;
} else {
console.log('REFRESH Root!!', this.modelId);
return this.model[this.modelId];
}
}
public getParent(p_node: PNode): vscode.ProviderResult<PNode> | null {
console.log('getParent:', p_node.gnx);
return p_node.parent;
}
private _buildNodeIconPaths(p_context: vscode.ExtensionContext): Icon[] {
return Array(16)
.fill('')
.map((p_val, p_index) => {
return {
light: p_context.asAbsolutePath(
'resources/light/box' + ('0' + p_index).slice(-2) + '.svg'
),
dark: p_context.asAbsolutePath(
'resources/dark/box' + ('0' + p_index).slice(-2) + '.svg'
),
};
});
}
/**
* Recursively set node's parent member.
* @param p_nodes Children array of nodes to have their parents set recursively.
* @param p_parent Current node being processed. Undefined if root node children.
*/
private _buildParents(p_nodes: PNode[], p_parent?: PNode): void {
p_nodes.forEach(p_node => {
p_node.parent = p_parent;
this._buildParents(p_node.children, p_node
);
});
}
}
|
4fbdf58d39a8f2acc22b13962db347b9ca1faa5c
|
TypeScript
|
martindesc/TechnoWeb
|
/2-typescript wNM/src/server.ts
| 2.546875
| 3
|
import express = require('express')
const app = express()
const port: string = process.env.PORT || '8080'
import { MetricsHandler } from './metrics'
app.get('/metrics.json', (req: any, res: any) => {
MetricsHandler.get((err: Error | null, result?: any) => {
if (err) {
throw err
}
res.json(result)
})
})
app.get('/', (req: any, res: any) => {
res.write(
'<div class="col-md-6 col-md-offset-3">' +
'<h1>Home page</h1>' +
'<div>' +
'Welcome to the home page of the second lab : express ! </br></br>' +
'If you want to navigate to the page "hello.ejs", just add "/hello" inside the address :)' +
'</div>' +
'</div>')
res.end()
})
app.get('/hello', (req: any, res: any) => {
res.write('<div class="col-md-6 col-md-offset-3">' +
'<h1>Hello</h1>' +
'<button class="btn btn-success" id="show-metrics">' +
'Bring the metrics' +
'</button>' +
'<div id="metrics"></div>' +
'</div>' +
'<script>' +
"$('#show-metrics').click((e) => {" +
'e.preventDefault();' +
'$.getJSON("/metrics.json", {}, (data) => {' +
'const content = data.map(d => {' +
"return 'timestamp: '+d.timestamp+', value: '+d.value+'';" +
'})' +
"$('#metrics').append(content.join('\n'));" +
'});' +
'})' +
'</script>')
res.end()
})
app.listen(port, (err: Error) => {
if (err) {
throw err
}
console.log(`server is listening on port ${port}`)
})
|
b08b8f6dd12b934f32d459c4b9a8920c1a543f44
|
TypeScript
|
ZeroCho/DefinitelyTyped
|
/types/parse5-htmlparser2-tree-adapter/parse5-htmlparser2-tree-adapter-tests.ts
| 2.5625
| 3
|
import * as parse5 from "parse5";
import treeAdapter = require('parse5-htmlparser2-tree-adapter');
// htmlparser2 AST
const htmlparser2Document = parse5.parse("<html>", {
treeAdapter
});
htmlparser2Document; // $ExpectType Document
htmlparser2Document.name; // $ExpectType "root"
htmlparser2Document.type; // $ExpectType "root"
htmlparser2Document["x-mode"]; // $ExpectType DocumentMode
const htmlparser2Node = htmlparser2Document as treeAdapter.Node;
htmlparser2Node.next; // $ExpectType Node
htmlparser2Node.nextSibling; // $ExpectType Node
htmlparser2Node.nodeType; // $ExpectType number
htmlparser2Node.parent; // $ExpectType ParentNode
htmlparser2Node.parentNode; // $ExpectType ParentNode
htmlparser2Node.prev; // $ExpectType Node
htmlparser2Node.previousSibling; // $ExpectType Node
htmlparser2Node.type; // $ExpectType string
const htmlparser2ParentNode = htmlparser2Document as treeAdapter.ParentNode;
htmlparser2ParentNode; // $ExpectType ParentNode
htmlparser2ParentNode.childNodes[0]; // $ExpectType Node
htmlparser2ParentNode.children[0]; // $ExpectType Node
htmlparser2ParentNode.firstChild; // $ExpectType Node
htmlparser2ParentNode.lastChild; // $ExpectType Node
const htmlparser2Doctype = htmlparser2Document.childNodes[0] as treeAdapter.DocumentType;
htmlparser2Doctype; // $ExpectType DocumentType
htmlparser2Doctype.data; // $ExpectType string
htmlparser2Doctype.name; // $ExpectType "!doctype"
htmlparser2Doctype["x-name"]; // $ExpectType string
htmlparser2Doctype["x-publicId"]; // $ExpectType string
htmlparser2Doctype["x-systemId"]; // $ExpectType string
const htmlparser2Element = htmlparser2Document.childNodes[0] as treeAdapter.Element;
htmlparser2Element; // $ExpectType Element
htmlparser2Element.attribs["someAttr"]; // $ExpectType string
htmlparser2Element["x-attribsNamespace"]["someAttr"]; // $ExpectType string
htmlparser2Element["x-attribsPrefix"]["someAttr"]; // $ExpectType string
htmlparser2Element.namespace; // $ExpectType string
htmlparser2Element.tagName; // $ExpectType string
htmlparser2Element.sourceCodeLocation!; // $ExpectType ElementLocation
const htmlparser2TextNode = htmlparser2Document.childNodes[0] as treeAdapter.TextNode;
htmlparser2TextNode.data; // $ExpectType string
htmlparser2TextNode.nodeValue; // $ExpectType string
htmlparser2TextNode.sourceCodeLocation!; // $ExpectType Location
const htmlparser2CommentNode = htmlparser2Document.childNodes[0] as treeAdapter.CommentNode;
htmlparser2CommentNode.data; // $ExpectType string
htmlparser2CommentNode.nodeValue; // $ExpectType string
htmlparser2CommentNode.sourceCodeLocation!; // $ExpectType Location
|
8514a1b4f0fd58020ae3bc0cc271fdc19fd3ac20
|
TypeScript
|
felixroos/blog
|
/content/components/common/isPrime.ts
| 3.203125
| 3
|
// returns true if the given number is prime
export const isPrime = num => {
for (let i = 2, s = Math.sqrt(num); i <= s; i++)
if (num % i === 0) return false;
return num > 1;
}
|
e8c90903da629c3ffa5e088ce6b3e94ff9c866d1
|
TypeScript
|
zeroc0d3/graphql-zeus
|
/src/TreeToTS/functions/fullSubscriptionConstruct.ts
| 2.734375
| 3
|
import { StringFunction } from './models';
export const fullSubscriptionConstruct: StringFunction = {
ts: `
const fullSubscriptionConstruct = (fn: SubscriptionFunction) => (
t: 'query' | 'mutation' | 'subscription',
tName: string,
) => (o: Record<any, any>, variables?: Record<string, any>) =>
fn(queryConstruct(t, tName)(o), variables);
export const fullSubscriptionConstructor = <F extends SubscriptionFunction, R extends keyof ValueTypes>(
fn: F,
operation: 'query' | 'mutation' | 'subscription',
key: R,
) =>
((o, variables) => fullSubscriptionConstruct(fn)(operation, key)(o as any, variables)) as SubscriptionToGraphQL<
ValueTypes[R],
GraphQLTypes[R]
>;
`,
js: `
const fullSubscriptionConstruct = (fn) => (
t,
tName,
) => (o, variables) =>
fn(queryConstruct(t, tName)(o), variables);
export const fullSubscriptionConstructor = (
fn,
operation,
key,
) =>
((o, variables) => fullSubscriptionConstruct(fn)(operation, key)(o, variables))
`,
};
|
9a884555f9ab2f768c68163fa3ed59f0a4d41cd7
|
TypeScript
|
kenchris/lit-element
|
/src/lit-element.ts
| 2.59375
| 3
|
import { html, render } from '../node_modules/lit-html/lib/lit-extended.js';
import { TemplateResult } from '../node_modules/lit-html/lit-html.js';
export { html } from '../node_modules/lit-html/lib/lit-extended.js';
export { TemplateResult } from '../node_modules/lit-html/lit-html.js';
export interface PropertyOptions {
type?: BooleanConstructor | DateConstructor | NumberConstructor | StringConstructor|
ArrayConstructor | ObjectConstructor;
value?: any;
attrName?: string;
computed?: string;
}
export interface ListenerOptions {
target: string | EventTarget,
eventName: string,
handler: Function
}
export interface Map<T> {
[key: string]: T;
}
export function createProperty(prototype: any, propertyName: string, options: PropertyOptions = {}): void {
if (!prototype.constructor.hasOwnProperty('properties')) {
Object.defineProperty(prototype.constructor, 'properties', { value: {} });
}
prototype.constructor.properties[propertyName] = options;
// Cannot attach from the decorator, won't override property.
Promise.resolve().then(() => attachProperty(prototype, propertyName, options));
}
function attachProperty(prototype: any, propertyName: string, options: PropertyOptions) {
const { type: typeFn, attrName } = options;
function get(this: LitElement) { return this.__values__[propertyName]; }
function set(this: LitElement, v: any) {
// @ts-ignore
let value = (v === null || v === undefined) ? v : (typeFn === Array ? v : typeFn(v));
this._setPropertyValue(propertyName, value);
if (attrName) {
this._setAttributeValue(attrName, value, typeFn);
}
this.invalidate();
}
Object.defineProperty(prototype, propertyName, options.computed ? {get} : {get, set});
}
export function whenAllDefined(result: TemplateResult) {
const template = result.template;
const rootNode = template.element.content;
const walker = document.createTreeWalker(rootNode, NodeFilter.SHOW_ELEMENT, null as any, false);
const deps = new Set();
while (walker.nextNode()) {
const element = walker.currentNode as Element;
if (element.tagName.includes('-')) {
deps.add(element.tagName.toLowerCase());
}
}
return Promise.all(Array.from(deps).map(tagName => customElements.whenDefined(tagName)));
}
export class LitElement extends HTMLElement {
private _needsRender: boolean = false;
private _lookupCache: Map<HTMLElement> = {};
private _attrMap: Map<string> = {};
private _deps: Map<Array<Function>> = {};
__values__: Map<any> = {};
_setPropertyValue(propertyName: string, newValue: any) {
this.__values__[propertyName] = newValue;
if (this._deps[propertyName]) {
this._deps[propertyName].map((fn: Function) => fn());
}
}
_setPropertyValueFromAttributeValue(attrName: string, newValue: any) {
const propertyName = this._attrMap[attrName];
const { type: typeFn } = (this.constructor as any).properties[propertyName];
let value;
if (typeFn.name === 'Boolean') {
value = (newValue === '') || (!!newValue && newValue === attrName.toLowerCase());
} else {
value = (newValue !== null) ? typeFn(newValue) : undefined;
}
this._setPropertyValue(propertyName, value);
}
_setAttributeValue(attrName: string, value: any, typeFn: any) {
// @ts-ignore
if (typeFn.name === 'Boolean') {
if (!value) {
this.removeAttribute(attrName);
} else {
this.setAttribute(attrName, '');
}
} else {
this.setAttribute(attrName, value);
}
}
static get properties(): Map<PropertyOptions> {
return {};
}
static get listeners(): Array<ListenerOptions> {
return [];
}
static get observedAttributes(): string[] {
return Object.keys(this.properties)
.map(key => (<any>this.properties)[key].attrName)
.filter(name => name);
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
for (const propertyName in (this.constructor as any).properties) {
const options = (this.constructor as any).properties[propertyName];
const { value, attrName, computed } = options;
// We can only handle properly defined attributes.
if (typeof(attrName) === 'string' && attrName.length) {
this._attrMap[attrName] = propertyName;
}
// Properties backed by attributes have default values set from attributes, not 'value'.
if (!attrName && value !== undefined) {
this._setPropertyValue(propertyName, value);
}
const match = /(\w+)\((.+)\)/.exec(computed);
if (match) {
const fnName = match[1];
const targets = match[2].split(/,\s*/);
const computeFn = () => {
const values = targets.map(target => (<any>this)[target]);
if ((<any>this)[fnName] && values.every(entry => entry !== undefined)) {
const computedValue = (<any>this)[fnName].apply(this, values);
this._setPropertyValue(propertyName, computedValue);
}
};
for (const target of targets) {
if (!this._deps[target]) {
this._deps[target] = [ computeFn ];
} else {
this._deps[target].push(computeFn);
}
}
computeFn();
}
}
}
static withProperties() {
for (const propertyName in this.properties) {
attachProperty(this.prototype, propertyName, this.properties[propertyName]);
}
return this;
}
renderCallback() {
render(this.render(this), this.shadowRoot as ShadowRoot);
}
// @ts-ignore
render(self: any): TemplateResult {
return html``;
}
attributeChangedCallback(attrName: string, _oldValue: string, newValue: string) {
this._setPropertyValueFromAttributeValue(attrName, newValue);
this.invalidate();
}
connectedCallback() {
for (const attrName of (this.constructor as any).observedAttributes) {
this._setPropertyValueFromAttributeValue(attrName, this.getAttribute(attrName));
}
this.invalidate().then(() => {
for (const listener of (this.constructor as any).listeners as Array<ListenerOptions>) {
const target = typeof listener.target === 'string' ? this.$(listener.target) : listener.target;
target.addEventListener(listener.eventName, listener.handler.bind(this));
}
});
}
async invalidate() {
if (!this._needsRender) {
this._needsRender = true;
// Schedule the following as micro task, which runs before
// requestAnimationFrame. All additional invalidate() calls
// before will be ignored.
// https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
this._needsRender = await false;
this.renderCallback();
}
}
$(id: string) {
let value = this._lookupCache[id];
if (!value && this.shadowRoot) {
const element = this.shadowRoot.getElementById(id);
if (element) {
value = element;
this._lookupCache[id] = element;
}
}
return value;
}
}
|
c42325d69c76a271ee946b4389a2d2bf4f15e4c1
|
TypeScript
|
ryefimchuk/responsive-box
|
/src/media-queries/compiler/parser/features/width-node.ts
| 2.640625
| 3
|
import { FeatureNode } from './feature-node';
export class WidthNode extends FeatureNode {
constructor(width: number) {
super('width', width);
}
public toJS(): string {
return `width === ${this.value}`;
}
}
|
90a2c9eb52777c1c33b3101a5e68bbb7202d48c6
|
TypeScript
|
korirsammy/DatingApp
|
/DatingApp-SPA/src/app/_directives/hasRole.directive.ts
| 2.53125
| 3
|
import { Directive, Input, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
@Input() appHasRole:string[];
isVisble=false;
constructor(private viewContainerRef:ViewContainerRef,
private templateRef:TemplateRef<any>,
private authService:AuthService) { }
ngOnInit(){
const userRoles=this.authService.decodedToken.role as Array<string>
//if there are no role,clear view container ref
if(!userRoles){
this.viewContainerRef.clear();
}
//if a user has a role needed, render the element
if(this.authService.roleMatch(this.appHasRole)){
if(!this.isVisble){
this.isVisble=true;
this.viewContainerRef.createEmbeddedView(this.templateRef);
}else{
this.isVisble=false;
this.viewContainerRef.clear();
}
}
}
}
|
d98ef666c964f0cfd2db8d64365502d016c572cf
|
TypeScript
|
halbtale/graphql-project
|
/graphql-typescript/src/structure/user/UserResolver.ts
| 2.625
| 3
|
import { DocumentType } from '@typegoose/typegoose';
import {Resolver, Query, Arg, Ctx, Authorized, FieldResolver, ResolverInterface, Root, Mutation} from 'type-graphql'
import { CommentModel } from '../comment/CommentModel';
import { Comment } from '../comment/CommentSchema';
import { ContextType } from '../context/ContextType';
import { PostModel } from '../post/PostModel';
import { Post } from '../post/PostSchema';
import { getHashedPassword, getSignedJwt, verifyPassword } from '../utils/utils';
import { UserModel } from './UserModel';
import { AuthPayload, CreateUserInput, User } from './UserSchema';
@Resolver()
export class UserQueryResolver {
@Query(returns => [User])
users(@Arg("query", {nullable: true}) query?: string) {
if (!query) {
return UserModel.find({});
}
return UserModel.find({
name: new RegExp(query, 'i')
});
}
@Authorized()
@Query(returns => User)
me(@Ctx() ctx: ContextType) {
return UserModel.findOne(ctx.currentUser._id);
}
}
@Resolver()
export class UserMutationResolver {
@Mutation(returns => AuthPayload)
async createUser(@Arg("data") data: CreateUserInput) {
if (data.password.length < 8) {
throw new Error('Password must be at least 8 characters long');
}
const password = await getHashedPassword(data.password);
const user = new UserModel({
...data,
password
})
await user.save();
return {
user,
token: await getSignedJwt(user._id)
}
}
@Mutation(returns => AuthPayload)
async login(@Arg("email") email: string, @Arg("password") password: string) {
const user = await UserModel.findOne({email});
if (!user) {
throw new Error('User not found');
}
const valid = await verifyPassword(password, user.password);
if (!valid) {
throw new Error('Incorrect password');
}
return {
user,
token: await getSignedJwt(user._id)
}
}
}
@Resolver(of => User)
export class UserTypeResolver implements ResolverInterface<User> {
@FieldResolver(returns => [Post])
async posts(@Root() user: DocumentType<User>): Promise<Post[]> {
const posts = await PostModel.find({
author: user._id,
published: true
});
return posts;
}
@FieldResolver(returns => [Comment])
async comments(@Root() user: DocumentType<User>): Promise<Comment[]> {
const comments = await CommentModel.find({author: user._id});
return comments;
}
}
|
9cad010ecd41b70ee07d7f0a6c885783547ce013
|
TypeScript
|
Devcon4/Sparrow
|
/src/models/Member.ts
| 2.5625
| 3
|
export default class Member {
id = '';
fullName = '';
avatarUrl = '';
constructor(init: Partial<Member>) {
Object.assign(this, init);
}
}
|
8bb2187c553bd09e0d824bb90872462b85db8562
|
TypeScript
|
qiwi/repocrawler
|
/packages/reporters/src/main/ts/parsers.ts
| 2.515625
| 3
|
import { PackageJson } from '@qiwi/npm-types'
import { TRepoCrawlerReportResultItem } from '@qiwi/repocrawler-common'
import { ILogger } from '@qiwi/substrate'
import { parse } from '@yarnpkg/lockfile'
import {
EDependencyType,
TDependency,
TDepsSource,
TFoldedDependency,
} from './interfaces'
import { getRepoName, normalizeVersion } from './utils'
const dependencyTypeMap: {
[key: string]: keyof Pick<PackageJson, 'dependencies' | 'devDependencies' | 'peerDependencies' | 'optionalDependencies'>
} = {
[EDependencyType.DEFAULT]: 'dependencies',
[EDependencyType.DEV]: 'devDependencies',
[EDependencyType.PEER]: 'peerDependencies',
[EDependencyType.OPTIONAL]: 'optionalDependencies',
}
export const dependencyRecordsToArray = (
// eslint-disable-next-line default-param-last
deps: Record<string, string> = {},
crawlerResult: TRepoCrawlerReportResultItem,
): TFoldedDependency[] =>
foldDependencies(
Object.keys(deps).map((name) => ({
name,
version: deps[name],
})),
crawlerResult,
)
export const getDependencies = (
crawlerResult: TRepoCrawlerReportResultItem,
depType: EDependencyType,
): TFoldedDependency[] | undefined => {
const packageJson = crawlerResult.package
if (!packageJson) {
return
}
return depType === EDependencyType.ALL
? [
...dependencyRecordsToArray(
packageJson[dependencyTypeMap[EDependencyType.DEFAULT] as keyof PackageJson['dependencies']],
crawlerResult,
),
...dependencyRecordsToArray(
packageJson[dependencyTypeMap[EDependencyType.DEV] as keyof PackageJson['devDependencies']],
crawlerResult,
),
...dependencyRecordsToArray(
packageJson[dependencyTypeMap[EDependencyType.PEER] as keyof PackageJson['peerDependencies']],
crawlerResult,
),
...dependencyRecordsToArray(
packageJson[dependencyTypeMap[EDependencyType.OPTIONAL] as keyof PackageJson['optionalDependencies']],
crawlerResult,
),
]
: dependencyRecordsToArray(
packageJson[dependencyTypeMap[depType]],
crawlerResult,
) || []
}
export const getYarnLockDependencies = (yarnLock?: string, logger: ILogger = console): any => {
try {
if (yarnLock) {
return parse(yarnLock).object
}
} catch (e) {
logger.warn(e)
}
}
export const getDepsBySource = (
crawlerResult: TRepoCrawlerReportResultItem,
source: TDepsSource,
depType?: EDependencyType,
logger: ILogger = console,
): TFoldedDependency[] | undefined => {
const { shrinkLock, yarnLock, packageLock } = crawlerResult
switch (source) {
case 'package':
return getDependencies(crawlerResult, depType || EDependencyType.ALL)
case 'auto':
return (
lockEntriesToDependencyArray(crawlerResult, shrinkLock?.dependencies) ||
lockEntriesToDependencyArray(
crawlerResult,
getYarnLockDependencies(yarnLock, logger),
) ||
lockEntriesToDependencyArray(
crawlerResult,
packageLock?.dependencies,
) ||
getDependencies(crawlerResult, EDependencyType.ALL)
)
case 'lock':
return (
lockEntriesToDependencyArray(crawlerResult, shrinkLock?.dependencies) ||
lockEntriesToDependencyArray(
crawlerResult,
getYarnLockDependencies(yarnLock),
) ||
lockEntriesToDependencyArray(crawlerResult, packageLock?.dependencies)
)
}
}
const foldDependencies = (
deps: TDependency[],
crawlerResultItem: TRepoCrawlerReportResultItem,
) =>
deps.reduce<TFoldedDependency[]>((acc, { name, version }) => {
const dep = acc.find((item) => item.name === name)
if (dep) {
dep.versions.includes(version) || dep.versions.push(version)
} else {
acc.push({
name,
versions: [normalizeVersion(version)],
repo: getRepoName(crawlerResultItem),
})
}
return acc
}, [])
export const lockEntriesToDependencyArray = (
crawlerResult: TRepoCrawlerReportResultItem,
entries?: Record<string, { version: string }>,
): TFoldedDependency[] | undefined => {
if (!entries) {
return
}
return foldDependencies(
Object.keys(entries).map((name) => ({
name: normalizeLockEntryName(name),
version: entries[name].version,
})),
crawlerResult,
)
}
export const normalizeLockEntryName = (name: string): string =>
name.replace( /@[\d*.^x~-]+$/, '')
|