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
|
|---|---|---|---|---|---|---|
3ad1343277362a51ea307a358e2f1627491ed11e
|
TypeScript
|
Yeulma/findParisRestrooms-frontend
|
/src/app/model/route.ts
| 2.828125
| 3
|
export class Route {
intersections: Array<any>;
distance: number;
duration: number;
constructor(intersections: Array<any>, distance: number, duration: number) {
this.intersections = intersections;
this.distance = distance;
this.duration = duration;
}
}
|
64c8bf0804f168d9af10955a7781d3102401bdd3
|
TypeScript
|
sdileep/authpack
|
/packages/admin/src/screens/UpdatePermission.ts
| 2.640625
| 3
|
import * as yup from 'yup'
import { createElement as create, FC, useEffect } from 'react'
import {
useSchema,
Layout,
Control,
InputString,
testAlphanumeric,
Page,
} from '@authpack/theme'
import { createUseServer } from '../hooks/useServer'
export const UpdatePermission: FC<{
id: string
change?: (id?: string) => void
}> = ({ id, change }) => {
const gqlGetPermission = useGetPermission()
const gqlUpdatePermission = useUpdatePermission()
const schema = useSchema({
schema: SchemaUpdatePermission,
poller: value => {
gqlUpdatePermission
.fetch({ id, value })
.then(({ permission }) => change && change(permission.id))
},
})
useEffect(() => {
gqlGetPermission
.fetch({ id })
.then(({ permission }) => schema.set(permission))
// eslint-disable-next-line
}, [id])
return create(Page, {
title: 'Update',
subtitle: 'Permission',
children: create(Layout, {
column: true,
padding: true,
divide: true,
children: !gqlGetPermission.data
? null
: [
create(Control, {
key: 'name',
label: 'Name',
error: schema.error('name'),
children: create(InputString, {
value: schema.value('name'),
change: schema.change('name'),
placeholder: 'Admin Editor',
}),
}),
create(Control, {
key: 'tag',
label: 'Tag',
helper: 'A unique identifier for the permission',
error: schema.error('tag'),
children: create(InputString, {
value: schema.value('tag'),
change: schema.change('tag'),
placeholder: 'admin_editor',
}),
}),
create(Control, {
key: 'description',
label: 'Description',
error: schema.error('description'),
children: create(InputString, {
value: schema.value('description'),
change: schema.change('description'),
placeholder: 'User can...',
}),
}),
],
}),
})
}
const SchemaUpdatePermission = yup.object().shape({
name: yup.string().required('Please provide the permission name'),
tag: yup
.string()
.test(
'alphamun',
'Please use only numbers, letters and underscores',
testAlphanumeric
)
.required('Please provide the permission tag'),
description: yup.string(),
})
const useGetPermission = createUseServer<{
permission: {
name: string
tag: string
description?: string
}
}>({
query: `
query GetPermission($id: String!) {
permission: GetPermission(id: $id) {
name
tag
description
}
}
`,
})
const useUpdatePermission = createUseServer<{
permission: {
id: string
}
}>({
query: `
mutation UpdatePermission($id: String!, $value: UpdatePermissionValue!) {
permission: UpdatePermission(id: $id, value: $value) {
id
}
}
`,
})
|
eaf0cee12a7d6585795a09955e450fd4c1e8707d
|
TypeScript
|
Mushorwell/Bitcube-TypeScript-Exercise-1
|
/app/validate.ts
| 2.9375
| 3
|
import * as Helpers from './utility';
import Person from './person';
export function Validate(){
const user = new Person();
user.forenames = Helpers.getValue("forename");
user.surname = Helpers.getValue("surname");
user.nickname = Helpers.getValue("nickname");
user.email = Helpers.getValue("email");
user.password = Helpers.getValue("password")
let message: string = "";
//Validate forename
if (user.forenames.length < 1){
message = "Forenames need to be more than one letter.";
Helpers.logger(message);
}
if (user.surname.length < 2){
message = "Surname needs to be more than two letters.";
Helpers.logger(message);
}
if (user.email.length < 4){
message = "email needs to be more than four letters and must have an @ sign.";
Helpers.logger(message);
} else if(user.email.indexOf('@')<0){
message = "email needs to be more than four letters and must have an @ sign.";
Helpers.logger(message);
}
if (user.password.length >= 4){
let passwordCheck: boolean = (user.password === Helpers.getValue("confirm_password"));
if(!passwordCheck) {
message = "Password needs to be more than four letters and should match.";
Helpers.logger(message);
}
}else{
message = "Password needs to be more than four letters and should match."
Helpers.logger(message);
}
}
|
db1fc7b15f7d51e4a10623ddbbb30351d98ebc53
|
TypeScript
|
ahape/scrabble-core
|
/src/functions/getnextturn.ts
| 3.265625
| 3
|
export function getNextTurn(
teams: number,
teamTurn: number,
oppositeDirection: boolean
): number {
if (oppositeDirection) {
return (teamTurn - 1) % teams || teams;
}
// Ensure non-zero (e.g. if 3 teams: 1 -> 2 -> 3 -> 1)
return (teamTurn + 1) % teams || teams;
}
|
f18be0b2f05832739082b6cd5059f59054b7a7cf
|
TypeScript
|
npmcdn-to-unpkg-bot/myContact
|
/app/app.component.ts
| 2.609375
| 3
|
import {Component} from '@angular/core';
import {Contact} from './contact';
const CONTACTS:Contact[] = [
{mobile: 454567, name: "jomon"},
{mobile: 768874, name: "Sijo"},
{mobile: 8764587, name: "Sumesh"},
{mobile: 988567576, name: "Sreeja"},
{mobile: 9768745665, name: "Rekha"},
{mobile: 87873554, name: "Sreeraju"},
{mobile: 43546789, name: "Biju"}
];
@Component({
selector: 'my-app',
template: `
<h2>{{title}}</h2>
<input #newContact
(keyup.enter)="addContact(newContact.value)"
(blur)="addContact(newContact.value); newContact.value='' ">
<button (click)=addContact(newContact.value)>Add</button>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Mobile</th>
<th>Name</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let contact of contacts;let i = index">
<td>{{i+1}}</td>
<td>{{contact.mobile}}</td>
<td>{{contact.name}}</td>
<td [class.selected]="contact === selectedContact" >
<button (click)="onSelect(contact)" type="button" class="btn btn-default btn-xs"><i class="badge">EDIT</i> </button>
</td>
</tr>
</tbody>
</table>
<div *ngIf="selectedContact">
<h2>{{selectedContact.name}} details!</h2>
<div>
<label>name: </label><br>
<input [(ngModel)]="selectedContact.name" placeholder="name"/><br/>
<label>Mobile: (Press [Enter] to update details)</label><br>
<input #number_box (keyup.enter)="selectedContact.mobile=number_box.value" value="{{selectedContact.mobile}}" placeholder="mobile"/>
</div>
</div>
`
})
export class AppComponent {
title = "My Contact";
contacts = CONTACTS;
selectedContact:Contact;
onSelect(contact:Contact) {
this.selectedContact = contact;
console.log(contact);
}
addContact(newName:string) {
var mobile = Math.floor(Math.random() * 100000);
this.contacts.push({mobile: mobile, name: newName});
}
}
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
|
85b5080bbe9f1f35d355ddebbeed945420a7e35d
|
TypeScript
|
julien-c/klaus
|
/node/app/TemplateInfo.ts
| 2.671875
| 3
|
import * as util from 'util';
import * as child_process from 'child_process';
import { Context } from './Context';
import { Repo } from './Repo';
import { c } from '../lib/Log';
import { Utils } from '../lib/Utils';
const __exec = util.promisify(child_process.exec);
/**
* Info not directly linked to the `context` itself
* but that we want to display in the webpage.
*/
export namespace TemplateInfo {
export async function info(
context: Context,
pageUrl: string,
): Promise<{
refs: Repo.Refs;
/**
* We implement a "Check on GitHub" link that opens
* the "same" page on GitHub (for repos which have a remote there).
* Peruse it to check that things work the same.
*
* Might also work for other remotes...
*/
remoteLink?: string;
}> {
const refs = await Repo.refs(context.repo);
try {
let remoteUrl = (await __exec(
`git config --get remote.origin.url`,
{ cwd: context.repo.path() }
)).stdout.trim();
if (! remoteUrl.startsWith('https:')) {
throw new Error(`non supported remote`);
}
remoteUrl = Utils.trimSuffix(remoteUrl, `.git`);
const relativeToRepo = Utils.trimPrefix(
pageUrl,
`/${context.repoName}`
);
const remoteLink = remoteUrl+relativeToRepo;
return { refs, remoteLink };
} catch(err) {
return { refs };
}
}
}
|
5ed52db069479290efd5391277ba9159e8b8b4ba
|
TypeScript
|
barylyak/IT-blog
|
/src/app/shared/services/posts.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import {IPost} from '../interfaces/post.model';
import {Subject} from 'rxjs';
import {FAKE_POSTS_LIST} from '../constants/posts.constant';
@Injectable({
providedIn: 'root'
})
export class PostsService {
public list: IPost[] = FAKE_POSTS_LIST;
public postUpdated$ = new Subject();
constructor() { }
getPosts(): IPost[] {
return this.list;
}
getInterview(): IPost[] {
const postList: IPost[] = this.list.filter((ele) => {
return ele.category === 'inteview';
});
return postList;
}
getUpdates(): any[] {
const postList = [] = this.list.filter((ele) => {
return ele.category === 'updates';
});
return postList;
}
getEvents(): IPost[] {
const postList: IPost[] = this.list.filter((ele) => {
return ele.category === 'events';
});
return postList;
}
getPostById(id: number): IPost {
const postIndex: number = this.list.findIndex(elem => elem.id === id);
console.log(postIndex);
return this.list[postIndex];
}
create(post: IPost): void {
post.id = 0;
if (this.list.length > 0) {
post.id = this.list.slice(-1)[0].id + 1;
}
this.list.push(post);
this.postUpdated$.next('updated');
}
}
|
7358636dd43fb9e60905d3cc958276e1718e2467
|
TypeScript
|
JulianLeviston/fast-check
|
/test/unit/check/arbitrary/FrequencyArbitrary.utest.spec.ts
| 2.65625
| 3
|
import * as fc from '../../../../lib/fast-check';
import { Arbitrary } from '../../../../src/check/arbitrary/definition/Arbitrary';
import { Shrinkable } from '../../../../src/check/arbitrary/definition/Shrinkable';
import { frequency } from '../../../../src/check/arbitrary/FrequencyArbitrary';
import { Random } from '../../../../src/random/generator/Random';
import * as stubArb from '../../stubs/arbitraries';
const frequencyValidInputsArb = fc
.tuple(
fc.record({ weight: fc.integer({ min: 1 }), arbitraryValue: fc.integer() }),
fc.array(fc.record({ weight: fc.integer({ min: 1 }), arbitraryValue: fc.integer() })),
fc.array(fc.record({ weight: fc.integer({ min: 1 }), arbitraryValue: fc.integer() }))
)
.map(([positiveWeightMeta, headingWeightsMeta, traillingWeightsMeta]) => {
return [...headingWeightsMeta, positiveWeightMeta, ...traillingWeightsMeta].map((meta) => ({
weight: meta.weight,
arbitrary: stubArb.single(meta.arbitraryValue, true),
expectedValue: meta.arbitraryValue,
}));
});
class LazyArb extends Arbitrary<any> {
constructor(readonly arbBuilder: () => Arbitrary<any>) {
super();
}
generate(mrng: Random): Shrinkable<any, any> {
return this.arbBuilder().generate(mrng);
}
withBias(freq: number) {
return this.arbBuilder().withBias(freq);
}
}
describe('FrequencyArbitrary', () => {
describe('frequency', () => {
it('Should call Random generator to generate values between 0 and total weight (not included)', () =>
fc.assert(
fc.property(frequencyValidInputsArb, fc.nat(), (validInputs, generateSeed) => {
// Arrange
const arb = frequency(...validInputs);
const totalWeight = validInputs.reduce((acc, cur) => acc + cur.weight, 0);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn();
nextInt.mockImplementation((a = 0, b = 0) => a + (generateSeed % (b - a + 1)));
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
arb.generate(fakeRandom);
// Assert
expect(nextInt).toHaveBeenCalledTimes(1);
expect(nextInt).toHaveBeenCalledWith(0, totalWeight - 1);
})
));
it('Should call the right arbitrary to generate the value', () =>
fc.assert(
fc.property(
frequencyValidInputsArb,
fc.nat(),
fc.nat(),
(validInputs, arbitrarySelectionSeed, generateSeed) => {
// Arrange
const selectedArbitraryIndex = arbitrarySelectionSeed % validInputs.length;
const selectedArbitrary = validInputs[selectedArbitraryIndex];
fc.pre(selectedArbitrary.weight > 0);
const totalWeightBefore = validInputs
.slice(0, selectedArbitraryIndex)
.reduce((acc, cur) => acc + cur.weight, 0);
const arb = frequency(...validInputs);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn();
nextInt.mockImplementation(() => totalWeightBefore + (generateSeed % selectedArbitrary.weight));
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
const g = arb.generate(fakeRandom).value_;
// Assert
expect(g).toBe(selectedArbitrary.expectedValue);
}
)
));
it('Should call the first arbitrary to generate the value when maxDepth of 0', () =>
fc.assert(
fc.property(frequencyValidInputsArb, (validInputs) => {
// Arrange
const arb = frequency({ maxDepth: 0 }, ...validInputs);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn();
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
const g = arb.generate(fakeRandom).value_;
// Assert
expect(nextInt).not.toHaveBeenCalled();
expect(g).toBe(validInputs[0].expectedValue);
})
));
it('Should call the first arbitrary to generate the value as soon as maxDepth has been reached', () => {
// Arrange
const arb: Arbitrary<any> = frequency(
{ maxDepth: 5 },
{ weight: 0, arbitrary: stubArb.single(0) },
{ weight: 1, arbitrary: new LazyArb(() => arb).map((d) => [d]) }
);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn().mockReturnValue(0);
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
const g = arb.generate(fakeRandom).value_;
// Assert
expect(nextInt).toHaveBeenCalledTimes(5); // maxDepth
expect(g).toEqual([[[[[0]]]]]); // const mapper = (d) => [d]; mapper(mapper(mapper(mapper(mapper(0))))) is [[[[[0]]]]]
});
it('Should not share depth accross distinct instances of frequency (if not requested)', () => {
// Arrange
const arb: Arbitrary<any> = frequency(
{ maxDepth: 1 },
{ weight: 0, arbitrary: stubArb.single(0) },
{
weight: 1,
arbitrary: frequency(
{ maxDepth: 1 },
{ weight: 0, arbitrary: stubArb.single(0) },
{
weight: 1,
arbitrary: frequency(
{ maxDepth: 1 },
{ weight: 0, arbitrary: stubArb.single(0) },
{ weight: 1, arbitrary: stubArb.single(1) }
).map((d) => [d]),
}
).map((d) => [d]),
}
);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn().mockReturnValue(0);
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
const g = arb.generate(fakeRandom).value_;
// Assert
expect(nextInt).toHaveBeenCalledTimes(3); // once per instance of frequency
expect(g).toEqual([[1]]);
});
it('Should share depth accross distinct instances of frequency if requested', () => {
// Arrange
const arb: Arbitrary<any> = frequency(
{ maxDepth: 1, depthIdentifier: 'toto' },
{ weight: 0, arbitrary: stubArb.single(0) },
{
weight: 1,
arbitrary: frequency(
{ maxDepth: 1, depthIdentifier: 'titi' },
{ weight: 0, arbitrary: stubArb.single(0) },
{
weight: 1,
arbitrary: frequency(
{ maxDepth: 1, depthIdentifier: 'toto' },
{ weight: 0, arbitrary: stubArb.single(0) },
{ weight: 1, arbitrary: stubArb.single(1) }
).map((d) => [d]),
}
).map((d) => [d]),
}
);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn().mockReturnValue(0);
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
const g = arb.generate(fakeRandom).value_;
// Assert
expect(nextInt).toHaveBeenCalledTimes(2); // one for toto, one for titi
expect(g).toEqual([[0]]);
});
it('Should ask ranges containing negative values as we go deeper in the structure if depthFactor', () => {
// Arrange
const arb: Arbitrary<any> = frequency(
{ depthFactor: 0.1 },
{ weight: 1, arbitrary: stubArb.single(0) },
{ weight: 1000, arbitrary: new LazyArb(() => arb).map((d) => [d]) }
);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn().mockImplementation((a, b) => {
// we stop on the first negative value of a
if (a < 0) return a;
// otherwise we return b to go deeper in the tree
else return b;
});
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
arb.generate(fakeRandom).value_;
// Assert
expect(nextInt).toHaveBeenCalledWith(0, 1000); // first calls: 0-1000 contains 1001 values
expect(nextInt).toHaveBeenCalledWith(-1, 1000); // as we go deeper (too deep)
});
it('Should never ask ranges containing negative values as we go deeper in the structure if depthFactor with weight of 0 on first arbitrary', () => {
// Arrange
const arb: Arbitrary<any> = frequency(
{ depthFactor: 0.1 },
{ weight: 0, arbitrary: stubArb.single(0) },
{ weight: 1000, arbitrary: new LazyArb(() => arb).map((d) => [d]) }
);
const nextInt: jest.Mock<number, [] | [number] | [number, number]> = jest.fn().mockImplementation((a, b) => {
// we stop on the first negative value of a
if (a < 0) return a;
// otherwise we return b to go deeper in the tree
else return b;
});
const fakeRandom = { nextInt: nextInt as Random['nextInt'] } as Random;
// Act
try {
arb.generate(fakeRandom).value_;
fail('Stack overflow expected as the structure is going deeper and deeper without any end case');
} catch (err) {
// noop
}
// Assert
expect(nextInt).toHaveBeenCalledWith(0, 999); // first calls: 0-999 contains 1000 values
expect(nextInt).not.toHaveBeenCalledWith(-1, 999); // never called as first arbitrary has a weight of zero
});
it('Should reject calls without any weighted arbitraries', () => {
expect(() => frequency()).toThrowError();
});
it('Should reject calls without weight', () => {
expect(() => frequency({ arbitrary: stubArb.single(0), weight: undefined! })).toThrowError(
/expects weights to be integer values/
);
});
it('Should reject calls without arbitrary', () => {
expect(() => frequency({ arbitrary: undefined!, weight: 1 })).toThrowError(/expects arbitraries to be specified/);
});
it('Should reject calls including at least one strictly negative weight', () =>
fc.assert(
fc.property(
fc.integer({ max: -1 }),
fc.array(fc.nat()),
fc.array(fc.nat()),
(negativeWeight, headingWeights, traillingWeights) => {
expect(() =>
frequency(
...[...headingWeights, negativeWeight, ...traillingWeights].map((weight) => ({
weight,
arbitrary: stubArb.single(0),
}))
)
).toThrowError();
}
)
));
it('Should reject calls having a total weight of zero', () =>
fc.assert(
fc.property(fc.nat({ max: 1000 }), (numEntries) => {
// Combined with: 'Should reject calls including at one strictly negative weight'
// it means that we have: 'Should reject calls having a total weight inferior or equal to zero'
expect(() =>
frequency(
...[...Array(numEntries)].map(() => ({
weight: 0,
arbitrary: stubArb.single(0),
}))
)
).toThrowError();
})
));
it('Should not reject calls defining a strictly positive total weight without any negative weights', () =>
fc.assert(
fc.property(
fc.integer({ min: 1 }),
fc.array(fc.nat()),
fc.array(fc.nat()),
(positiveWeight, headingWeights, traillingWeights) => {
expect(() =>
frequency(
...[...headingWeights, positiveWeight, ...traillingWeights].map((weight) => ({
weight,
arbitrary: stubArb.single(0),
}))
)
).not.toThrowError();
}
)
));
});
});
|
3ae02416b4a4902569bfa9a37d17b0e49f91ece0
|
TypeScript
|
copyit/homura
|
/src/utils/index.ts
| 2.640625
| 3
|
import fetch from 'node-fetch';
import { parse } from 'node-html-parser';
export async function getFaviconByUrl(url: string): Promise<string | undefined> {
if (!url.length) return undefined;
const linkRes = await fetch(url);
const html = await linkRes.text();
const root = parse(html);
const links = root.querySelectorAll('link');
const findByContent = (content: string): undefined | string => {
const target = links.find((x) => x.getAttribute('rel') === content);
if (!target) return undefined;
const href = target.getAttribute('href');
if (!href) return undefined;
return href.startsWith('/') ? url + href : href;
};
const shortCut = findByContent('shortcut icon');
if (shortCut) return shortCut;
const icon = findByContent('icon');
if (icon) return icon;
const appleIcon = findByContent('apple-touch-icon');
if (appleIcon) return appleIcon;
return undefined;
}
|
a79bcacb0fe32b5af6748a0a081a9055d9568566
|
TypeScript
|
franck-co/boulangeries-front
|
/src/utils/easy-peasy-decorators/create-store.ts
| 2.765625
| 3
|
import * as easyPeasy from "easy-peasy";
import { ToStoreType } from './types';
//import { metadataStorage } from "./metadata-storage";
export function createStore<T extends object = {} , C extends object = {}>(storeModel?:C) {
const store = easyPeasy.createStore<any>(storeModel);
return store as easyPeasy.Store<ToStoreType<T>>;
}
type freeObj = {[key:string]:any}
interface createTypedHooksReturn<Model extends object> {
useStoreActions: <Result>(
mapActions: (actions: easyPeasy.Actions<ToStoreType<Model>>) => Result,
) => Result;
useStoreActionsLoose: <Result>(
mapActions: (actions: easyPeasy.Actions<ToStoreType<Model>> & freeObj) => Result,
) => Result;
useStoreState: <Result>(
mapState: (state: ToStoreType<Model>) => Result,
dependencies?: any[],
) => Result;
useStoreStateLoose: <Result>(
mapState: (state: ToStoreType<Model> & freeObj) => Result,
dependencies?: any[],
) => Result;
useStoreDispatch: () => easyPeasy.Dispatch<ToStoreType<Model>>;
}
export function createTypedHooks<Model extends object>(): createTypedHooksReturn<Model> {
const hooks = easyPeasy.createTypedHooks<any>();
return {
useStoreActions: hooks.useStoreActions,
useStoreActionsLoose: hooks.useStoreActions,
useStoreState: hooks.useStoreState,
useStoreStateLoose: hooks.useStoreState,
useStoreDispatch:hooks.useStoreDispatch
} as any;
}
// interface createLocalTypedHooksReturn<LocalModel extends object> {
// useStoreActions: <Result>(
// mapActions: (actions: easyPeasy.Actions<ToStoreType<LocalModel>>) => Result,
// ) => Result;
// useStoreActionsLoose: <Result>(
// mapActions: (actions: easyPeasy.Actions<ToStoreType<LocalModel>> & freeObj) => Result,
// ) => Result;
// useStoreState: <Result>(
// mapState: (state: ToStoreType<LocalModel>) => Result,
// dependencies?: any[],
// ) => Result;
// useStoreStateLoose: <Result>(
// mapState: (state: ToStoreType<LocalModel> & freeObj) => Result,
// dependencies?: any[],
// ) => Result;
// useStoreDispatch: () => easyPeasy.Dispatch<ToStoreType<LocalModel>>;
// }
// type HolderMapFn<StoreModel extends object> = (store: ToStoreType<StoreModel>) => object
// export function createLocalHooks<StoreModel extends object, LocalModel extends object>(holderMapFn : HolderMapFn<StoreModel>): createLocalTypedHooksReturn<LocalModel> {
// const hooks = easyPeasy.createTypedHooks<any>();
// return {
// useStoreActions: (localMapFn)=> hooks.useStoreActions(store =>localMapFn(holderMapFn(store as ToStoreType<StoreModel>))),
// useStoreActionsLoose: hooks.useStoreActions,
// useStoreState: hooks.useStoreState,
// useStoreStateLoose: hooks.useStoreState,
// useStoreDispatch:hooks.useStoreDispatch
// } as any;
// }
interface createLocalTypedHooksReturn<LocalModel extends object> {
useLocalActions: <Result>(
mapActions: (actions: easyPeasy.Actions<ToStoreType<LocalModel>>) => Result,
) => Result;
useLocalActionsLoose: <Result>(
mapActions: (actions: easyPeasy.Actions<ToStoreType<LocalModel>> & freeObj) => Result,
) => Result;
useLocalState: <Result>(
mapState?: (state: ToStoreType<LocalModel>) => Result,
dependencies?: any[],
) => Result;
useLocalStateLoose: <Result>(
mapState: (state: ToStoreType<LocalModel> & freeObj) => Result,
dependencies?: any[],
) => Result;
}
type HolderMapFn<StoreModel extends object> = (store: ToStoreType<StoreModel>) => object;
export function createLocalHooksFactory<StoreModel extends object>(hooks){
return function createLocalHooks<LocalModel extends object>(holderMapFn : HolderMapFn<StoreModel>): createLocalTypedHooksReturn<LocalModel> {
//const hooks = easyPeasy.createTypedHooks<any>();
return {
useLocalActions: (localMapFn = (S=>S))=> hooks.useStoreActions(store =>localMapFn(holderMapFn(store as ToStoreType<StoreModel>))),
useLocalActionsLoose: (localMapFn = S=>S)=> hooks.useStoreActions(store =>localMapFn(holderMapFn(store as ToStoreType<StoreModel>))),
useLocalState: (localMapFn = S=>S)=> hooks.useStoreState(store =>localMapFn(holderMapFn(store as ToStoreType<StoreModel>))),
useLocalStateLoose: (localMapFn = S=>S)=> hooks.useStoreState(store =>localMapFn(holderMapFn(store as ToStoreType<StoreModel>))),
} as any;
}
}
//Peut être faire createLocalHooks et createLocalHooksLoose pour que la holderMapFn soit puisse être loose
|
77a90daecfbd289dc60a8d550e71ad2a6e620c12
|
TypeScript
|
MaksimMandSC/nestjs-ws-wrapper
|
/example/nest-socket-test/src/jwt.strategy.ts
| 2.5625
| 3
|
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { UserService, User } from './user/user.service';
const cookieExtractor = (req: any) => {
let token: null | string = null;
if (req && req.cookies && req.cookies.jwt) {
token = req.cookies.jwt;
}
return token;
};
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly userService: UserService) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
cookieExtractor,
ExtractJwt.fromAuthHeaderAsBearerToken(),
]),
ignoreExpiration: false,
secretOrKey: 'secret',
});
}
validate(payload: {
exp: number;
iat: number;
sub: number;
username: string;
}): User {
return this.userService.findById(payload.sub + '');
}
}
|
a5d1ae2b698c09cc17ced33e469053ce6ab8705a
|
TypeScript
|
lanemt/definitelytyped.github.io
|
/types/binary-split/index.d.ts
| 2.5625
| 3
|
// Type definitions for binary-split 1.0
// Project: https://github.com/maxogden/binary-split#readme
// Definitions by: Krisztián Balla <https://github.com/krisztianb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.2
/// <reference types="node" />
import { Transform } from 'stream';
export = BinarySplit;
/**
* Split streams of binary data.
* @param splitOn The matcher for the splitting points in the stream. Default: os.EOL
*/
declare function BinarySplit(
splitOn?: string | Buffer | ArrayBuffer | SharedArrayBuffer | number[] | BigInt[] | Uint8Array | object,
): Transform;
|
e065d0bf16cb9b402c3b7e2b9eec6124c9f2f898
|
TypeScript
|
kaplantm/guitar-practice
|
/src/hooks/useInterval.ts
| 2.859375
| 3
|
import React from "react";
import { Nullable } from "../lib/constants/types";
// via https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export default function useInterval(
callback: () => void,
delay: Nullable<number>
) {
const savedCallback = React.useRef<any>(null);
// Remember the latest callback.
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
React.useEffect(() => {
function tick() {
const func: () => void = savedCallback.current;
if (typeof func === "function") {
func();
}
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
|
f505b093468403736e9f83526df2da1775350e6c
|
TypeScript
|
ericlewis/Relay.swift
|
/relay-compiler-language-swift/src/swiftJSX.ts
| 2.9375
| 3
|
export interface SwiftElement {
type: string | SwiftComponent;
props: any;
}
export type SwiftChild = SwiftElement | string;
export type SwiftNode = null | undefined | SwiftChild | SwiftFragment;
export type SwiftFragment = SwiftNode[];
export type SwiftComponent<Props = any> = (props: Props) => SwiftElement | null;
type CollapsibleNodeKind = 'var' | 'case' | 'import';
export function swiftJSX(
tagName: string | SwiftComponent,
attrs: any,
...children: SwiftNode[]
): SwiftElement | null {
return { type: tagName, props: { ...attrs, children } };
}
export const Fragment = 'swiftFragment';
export const DeclarationGroup = 'swiftDeclarationGroup';
export function renderSwift(
element: SwiftElement,
options?: {
defaultAccessLevel?: AccessLevel;
}
): string {
const renderer = new Renderer();
_renderSwift(renderer, element, {
defaultAccessLevel: options?.defaultAccessLevel,
});
return renderer.text;
}
interface RenderContext {
inline?: boolean;
inProtocol?: boolean;
inSwitch?: boolean;
defaultAccessLevel?: AccessLevel;
}
interface BuiltinRenderFunction<Props> {
(renderer: Renderer, props: Props, context: RenderContext): void;
}
const builtins: Record<string, BuiltinRenderFunction<any>> = {
[Fragment]: (renderer, props, context) => {
_renderSwift(renderer, props.children, context);
},
[DeclarationGroup]: (
renderer,
{ children }: { children: SwiftNode[] },
context
) => {
let previousNodeKind: CollapsibleNodeKind | null = null;
children = children.flat().filter(child => child != null);
for (let i = 0; i < children.length; i++) {
const child = children[i];
let newNodeKind: CollapsibleNodeKind | null = null;
if (typeof child === 'object' && 'type' in child) {
if (child.type === 'var' && !child.props.children.length) {
newNodeKind = 'var';
} else if (child.type === 'case') {
newNodeKind = 'case';
} else if (child.type === 'import') {
newNodeKind = 'import';
}
}
if (i !== 0) {
if (
previousNodeKind === null ||
newNodeKind === null ||
previousNodeKind !== newNodeKind
) {
renderer.appendLine('');
}
}
_renderSwift(renderer, child, context);
previousNodeKind = newNodeKind;
}
},
import(renderer, { module }: { module: string }) {
renderer.appendLine(`import ${module}`);
},
struct(
renderer,
{
name,
inherit = [],
access,
children,
}: {
name: string;
inherit?: string[];
access?: AccessLevel;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(
`struct ${name}${inherit.length ? `: ${inherit.join(', ')}` : ''} {`
);
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
},
enum(
renderer,
{
name,
inherit = [],
access,
children,
}: {
name: string;
inherit: string[];
access?: AccessLevel;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(`enum ${name}`);
if (inherit.length) {
renderer.append(`: ${inherit.join(', ')}`);
}
renderer.append(' {');
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
},
protocol(
renderer,
{
name,
access,
children,
}: {
name: string;
access?: AccessLevel;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(`protocol ${name} {`);
renderer.indent();
_renderSwift(renderer, children, { ...context, inProtocol: true });
renderer.outdent();
renderer.appendLine('}');
},
extension(
renderer,
{
name,
inherit = [],
where = [],
children,
}: {
name: string;
inherit?: string[];
where?: string[];
children: SwiftNode[];
},
context
) {
renderer.appendLine(`extension ${name}`);
if (inherit.length) {
renderer.append(`: ${inherit.join(', ')}`);
}
if (where.length) {
renderer.append(` where ${where.join(', ')}`);
}
renderer.append(' {');
if (!children.length) {
renderer.append('}');
return;
}
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
},
typealias(
renderer,
{
name,
children,
access,
}: {
name: string;
children: SwiftNode[];
access?: AccessLevel;
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(`typealias ${name} = `);
_renderSwift(renderer, children, { ...context, inline: true });
},
var(
renderer,
{
name,
type,
isStatic = false,
access,
children,
}: {
name: string;
type: string;
isStatic?: boolean;
access?: AccessLevel;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(`${isStatic ? 'static ' : ''}var ${name}: ${type}`);
if (context.inProtocol) {
renderer.append(' { get }');
return;
}
if (children.length) {
renderer.append(' {');
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
}
},
init(
renderer,
{
parameters = [],
access,
throws = false,
children,
}: {
parameters: SwiftNode[];
access?: AccessLevel;
throws: boolean;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append('init(');
for (let i = 0; i < parameters.length; i++) {
if (i !== 0) {
renderer.append(', ');
}
_renderSwift(renderer, parameters[i], { ...context, inline: true });
}
renderer.append(')');
if (throws) {
renderer.append(' throws');
}
renderer.append(' {');
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
},
function(
renderer,
{
name,
parameters = [],
returns,
isStatic = false,
isAsync = false,
access,
children,
}: {
name: string;
parameters: SwiftNode[];
returns?: string;
isStatic?: boolean;
isAsync?: boolean;
access?: AccessLevel;
children: SwiftNode[];
},
context
) {
renderer.appendLine(formatAccess(access, context));
renderer.append(`${isStatic ? 'static ' : ''}func ${name}(`);
for (let i = 0; i < parameters.length; i++) {
if (i !== 0) {
renderer.append(', ');
}
_renderSwift(renderer, parameters[i], { ...context, inline: true });
}
renderer.append(`)`);
if (isAsync) {
renderer.append(` async`);
}
if (returns) {
renderer.append(` -> ${returns}`);
}
renderer.append(` {`);
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
renderer.appendLine('}');
},
case(
renderer,
{
name,
parameters = [],
isDefault = false,
children,
}: {
name?: SwiftNode;
parameters?: SwiftNode[];
isDefault: boolean;
children: SwiftNode[];
},
context
) {
if (isDefault) {
renderer.appendLine('default');
} else {
renderer.appendLine('case ');
_renderSwift(renderer, name, { ...context, inline: true });
if (parameters.length) {
renderer.append('(');
for (let i = 0; i < parameters.length; i++) {
if (i !== 0) {
renderer.append(', ');
}
_renderSwift(renderer, parameters[i], { ...context, inline: true });
}
renderer.append(')');
}
}
if (context.inSwitch) {
renderer.append(':');
renderer.indent();
_renderSwift(renderer, children, context);
renderer.outdent();
} else {
if (children.length) {
renderer.append(' = ');
_renderSwift(renderer, children, { ...context, inline: true });
}
}
},
paramdecl(
renderer,
{
label,
name,
type,
defaultValue,
}: {
label?: string;
name: string;
type: string;
defaultValue?: SwiftNode;
},
context
) {
if (label) {
renderer.append(`${label} `);
}
renderer.append(`${name}: ${type}`);
if (defaultValue) {
renderer.append(' = ');
_renderSwift(renderer, defaultValue, { ...context, inline: true });
}
},
switch(
renderer,
{
value,
children,
}: {
value: SwiftNode;
children: SwiftNode[];
},
context
) {
renderer.appendLine('switch ');
_renderSwift(renderer, value, { ...context, inline: true });
renderer.append(' {');
_renderSwift(renderer, children, { ...context, inSwitch: true });
renderer.appendLine('}');
},
call(
renderer,
{
receiver,
name,
parameters = [],
expanded = false,
}: {
receiver?: SwiftNode;
name: string;
parameters?: SwiftNode[];
expanded?: boolean;
},
context
) {
renderer.appendLine(`${receiver != null ? `${receiver}.` : ''}${name}(`);
if (expanded) {
renderer.indent();
}
parameters = parameters.filter(p => !!p);
for (let i = 0; i < parameters.length; i++) {
if (i !== 0) {
renderer.append(',');
if (!expanded) {
renderer.append(' ');
}
}
_renderSwift(renderer, parameters[i], { ...context, inline: !expanded });
}
if (expanded) {
renderer.outdent();
renderer.appendLine(')');
} else {
renderer.append(')');
}
},
param(
renderer,
{
label,
children,
}: {
label?: string;
children: SwiftNode[];
},
context
) {
const text = `${label ? `${label}: ` : ''}`;
if (context.inline) {
renderer.append(text);
} else {
renderer.appendLine(text);
}
renderer.continueLine();
_renderSwift(renderer, children, { ...context, inline: true });
},
available(
renderer,
{
versions,
children,
}: {
versions: string[];
children: SwiftNode[];
},
context
) {
renderer.appendLine(`@available(${versions.join(', ')}, *)`);
_renderSwift(renderer, children, context);
},
await(renderer, { children }: { children: SwiftNode[] }, context) {
renderer.appendLine(`await `);
renderer.continueLine();
_renderSwift(renderer, children, context);
},
compilecheck(
renderer,
{
condition,
children,
}: {
condition: SwiftNode;
children: SwiftNode[];
},
context
) {
renderer.appendLine('#if ');
_renderSwift(renderer, condition, { ...context, inline: true });
_renderSwift(renderer, children, context);
renderer.appendLine('#endif');
},
literal(renderer, props: SwiftLiteralProps, context) {
const appendLine = context.inline
? text => {
renderer.append(text);
}
: text => {
renderer.appendLine(text);
};
if ('string' in props) {
appendLine(JSON.stringify(props.string));
} else if ('int' in props) {
appendLine(String(props.int));
} else if ('bool' in props) {
appendLine(String(props.bool));
} else if ('array' in props) {
appendLine('[');
renderer.indent();
const innerContext = { ...context, inline: !props.expanded };
for (let i = 0; i < props.array.length; i++) {
if (i !== 0) {
renderer.append(',');
if (innerContext.inline) {
renderer.append(' ');
}
}
_renderSwift(renderer, props.array[i], innerContext);
}
renderer.outdent();
if (props.expanded) {
renderer.appendLine(']');
} else {
renderer.append(']');
}
} else if ('dict' in props) {
appendLine('[');
renderer.indent();
const innerContext = { ...context, inline: !props.expanded };
for (let i = 0; i < props.dict.length; i++) {
if (i !== 0) {
renderer.append(',');
if (innerContext.inline) {
renderer.append(' ');
}
}
const [key, value] = props.dict[i];
_renderSwift(renderer, key, innerContext);
renderer.append(': ');
renderer.continueLine();
_renderSwift(renderer, value, innerContext);
}
renderer.outdent();
if (props.expanded) {
renderer.appendLine(']');
} else {
renderer.append(']');
}
} else {
throw new Error('unrecognized props for literal');
}
},
};
function _renderSwift(
renderer: Renderer,
element: SwiftNode,
context: RenderContext = {}
) {
if (!element) {
return;
}
if (Array.isArray(element)) {
for (const node of element) {
_renderSwift(renderer, node, context);
}
return;
}
if (typeof element === 'string') {
if (context.inline) {
renderer.append(element);
} else {
renderer.appendLine(element);
}
return;
}
if (typeof element.type === 'string') {
if (element.type in builtins) {
const renderFn = builtins[element.type];
renderFn(renderer, element.props, context);
return;
}
throw new Error(`Unrecognized Swift element type '${element.type}'`);
} else {
const rendered = element.type(element.props);
if (!rendered) {
return;
}
return _renderSwift(renderer, rendered, context);
}
}
class Renderer {
lines: string[];
private level: number;
private shouldContinue: boolean;
constructor() {
this.lines = [];
this.level = 0;
this.shouldContinue = false;
}
appendLine(line: string) {
if (this.shouldContinue) {
this.append(line);
} else {
this.trimIfNeeded();
this.lines.push(' '.repeat(this.level) + line);
}
}
append(text: string) {
if (this.shouldContinue) {
this.shouldContinue = false;
}
if (this.lines.length) {
this.lines[this.lines.length - 1] += text;
} else {
this.appendLine(text);
}
}
continueLine() {
this.shouldContinue = true;
}
indent() {
this.level++;
}
outdent() {
this.level--;
}
get text(): string {
this.trimIfNeeded();
return this.lines.join('\n');
}
private trimIfNeeded() {
if (!this.lines.length) {
return;
}
const idx = this.lines.length - 1;
this.lines[idx] = this.lines[idx].trimEnd();
}
}
type AccessLevel = 'public' | 'internal' | 'fileprivate' | 'private';
type SwiftLiteralProps =
| { string: string }
| { int: number }
| { bool: boolean }
| { array: SwiftNode[]; expanded?: boolean }
| { dict: [SwiftNode, SwiftNode][]; expanded?: boolean };
function formatAccess(
access: AccessLevel | null | undefined,
context: RenderContext
): string {
if (context.inProtocol) {
return '';
}
if (!access) {
access = context.defaultAccessLevel;
}
if (!access) {
return '';
}
return `${access} `;
}
|
892e7ac65d4edaa38901d1b247001a622605163a
|
TypeScript
|
joost-de-vries/mst-bookstore-ts
|
/src/stores/BookStore.test.ts
| 2.640625
| 3
|
import * as fs from "fs"
import { when } from "mobx"
import { ShopStore } from "./ShopStore"
const bookFetcher = () => Promise.resolve(JSON.parse(fs.readFileSync("./public/books.json", "UTF-8")))
it("bookstore fetches data", done => {
const store = ShopStore.create({}, { fetch: bookFetcher })
when(
() => store.isLoading === false,
() => {
expect(store.books.size).toBe(4)
expect(store.books.get("978-1933988177")!.price).toBe(30.5)
done()
}
)
})
it("bookstore sorts data", done => {
const store = ShopStore.create({}, { fetch: bookFetcher })
when(
() => store.isLoading === false,
() => {
expect(store.sortedAvailableBooks.map(book => book.name)).toEqual([
"Lucene in Action, Second Edition",
"Sophie's World : The Greek Philosophers",
"The Lightning Thief",
"The Sea of Monsters"
])
done()
}
)
})
|
e79b6cc42cb462b8f749f6b71382cca5be2b302c
|
TypeScript
|
alairon/XieraBot
|
/xiera/components/Event/Events.ts
| 2.65625
| 3
|
import quests = require('./Quests');
import casino = require('./Casino');
import WebJSON = require('../Network/WebJSON');
import Search = require('./SearchEvents');
import { UTCStrings } from '../Core/Date/UTCStrings';
import { Messages } from '../Core/Messages/Messages';
import { TimeStrings } from '../Core/Date/TimeStrings';
import { EventObject, IndexedEventObject, IndexedQueryEventObject, SearchEntity, SearchIndexEntity } from './@types/Events';
import { MessageEmbed } from 'discord.js';
// Regular expression for URLs
// Format: http(s):// ...
const urlRegExp = /https?:\/\/.*/mi;
export class Events{
private quests: Array<object>;
private casino: Array<object>;
private eventURL: string;
private eventHTTPConfig: object;
private questsSearch: Search.Search;
private refreshInterval: number;
private overrideRefreshInterval: number;
private eventRefreshTimeout: NodeJS.Timeout;
// Constructor
constructor(){
this.quests = [];
this.casino = [];
this.eventURL = null;
this.eventHTTPConfig = null;
this.refreshInterval = 10800000; // Default: 3 hours
this.overrideRefreshInterval = 3600000; // 1 hour
}
// Returns the URL to where the JSON is located
public getEventURL(): string{
return (this.eventURL);
}
// Returns the HTTP configuration for where the JSON is located
public getEventHTTPConfig(): object{
return (this.eventHTTPConfig);
}
// Provides the contents in the Quests array
public getEvents(): string{
return (JSON.stringify(this.quests));
}
// Provides the contents from the Casino array
public getCasinoEvents(): string{
console.log(JSON.stringify(this.casino));
return (JSON.stringify(this.casino));
}
// Sets the URL
private setURL(url: string): boolean{
if (this.validURL(url)){
this.eventURL = url;
return (true);
}
return (false);
}
// Sets the HTTP configuration
private setHTTPConfig(config: object): void{
this.eventHTTPConfig = config;
}
// Clears the stored quest and casino arrays.
private clearEvents(): void{
this.quests = [];
this.casino = [];
}
// Adds an individual urgent quest or concert
private addEvent(event: EventObject, searchIndex: SearchEntity): void{
if (event){
const title: string = event.title;
const categoryId: number = event.categoryId;
const startTime: string = event.startTime;
const endTime: string = event.endTime;
const parsedEvent = new quests.Quests({title, categoryId, startTime, endTime});
if (searchIndex){
parsedEvent.addIndexData(searchIndex.item.tags, searchIndex.item.alt);
}
this.quests.push(parsedEvent);
}
}
// Adds an individual casino event
private addCasinoEvent(event: EventObject): boolean{
if (event){
const title: string = event.title;
const categoryId: number = event.categoryId;
const startTime: string = event.startTime;
const endTime: string = event.endTime;
const parsedEvent = new casino.Casino({title, categoryId, startTime, endTime});
this.casino.push(parsedEvent);
return (true);
}
return (false);
}
// Tests if the URL is in the correct format. See the constant urlRegExp above.
private validURL(url: string): boolean{
if (urlRegExp.test(url)){
return (true);
}
return (false);
}
private async sortEvents(EventData: Array<object>): Promise<Array<object>>{
const events = EventData;
events.sort((a: EventObject, b: EventObject) => {
const aStartTime = a.startTime;
const bStartTime = b.startTime;
if (aStartTime < bStartTime) return (-1);
if (aStartTime > bStartTime) return (1);
return (0);
});
return (events);
}
// Downloads a JSON from a specific URL
private async downloadEvents(): Promise<object>{
if (this.eventURL) {
const events = await WebJSON.WebJSON.getJSON(this.eventURL);
return (events);
}
const events = await WebJSON.WebJSON.getJSON(this.eventHTTPConfig);
return (events);
}
public async initEvents(options?: string | object, refreshInterval?: number): Promise<void>{
if (options){
if (typeof(options) == 'string') {
const url = <string>options;
if (!this.setURL(url)){
console.log('[EVENTS] The URL isn\'t valid');
return (null);
}
}
else {
this.setHTTPConfig(options);
}
}
if (refreshInterval * 3600000 > 1000){
this.refreshInterval = refreshInterval * 3600000; // in hours
console.log(`[EVENTS] Updated the refresh interval to: ${TimeStrings.totalTimeString(refreshInterval * 3600000)}`);
}
// Load the events
const ScheduleEvents: IndexedEventObject = <IndexedEventObject>(await this.downloadEvents());
this.questsSearch = new Search.Search();
if (!ScheduleEvents){
return (null);
}
let uqCounter = 0; // Event ID 9
let concertCounter = 0; // Event ID 10
let casinoCounter = 0; // Event ID 11
let leagueCounter = 0; // Event ID 12
let otherCounter = 0; // Other IDs
let skippedCounter = 0; // Skipped Events
const now = Date.now();
//Insert the events into the appropriate array
for (const idx in ScheduleEvents){
// Find the tags from the UQ table, if any
let searchIndex: SearchEntity = await this.questsSearch.searchIndex(ScheduleEvents[idx].title);
for (const idy in ScheduleEvents[idx].events){
const eventData: EventObject = {
title: ScheduleEvents[idx].title,
categoryId: ScheduleEvents[idx].categoryId,
startTime: UTCStrings.getISOStringWithLocale(ScheduleEvents[idx].events[idy].startDate, ScheduleEvents[idx].schedule.timeZone),
endTime: UTCStrings.getISOStringWithLocale(ScheduleEvents[idx].events[idy].endDate, ScheduleEvents[idx].schedule.timeZone)
}
// Skip the current event if it has already passed
if (now > new Date(eventData.endTime).getTime()) {
skippedCounter++;
continue;
}
switch(ScheduleEvents[idx].categoryId){
case 9: // Urgent Quests
this.addEvent(eventData, searchIndex);
uqCounter++;
break;
case 10: // Live Concerts
this.addEvent(eventData, searchIndex);
concertCounter++;
break;
case 11: // Casino Boosts
this.addCasinoEvent(eventData);
casinoCounter++;
break;
case 12: // ARKS League
this.addEvent(eventData, searchIndex);
leagueCounter++;
break;
default:
// All other event types
console.log(`===== UNDEFINED EVENT =====\nEvent: ${eventData.title}\nID: ${eventData.categoryId}\n===========================`);
this.addEvent(eventData, searchIndex);
otherCounter++;
break;
}
}
}
console.log(`===== Event Summary =====
Urgent Quests: ${uqCounter}
Concerts: ${concertCounter}
Casino Boosts: ${casinoCounter}
ARKS League: ${leagueCounter}
Other Events: ${otherCounter}
Events Skipped: ${skippedCounter}\n=========================`);
// Sort the data
this.quests = await this.sortEvents(this.quests);
this.casino = await this.sortEvents(this.casino);
// Initializes the search for Events
const questStrings = JSON.parse(JSON.stringify(this.quests));
this.questsSearch.updateSearch(questStrings);
// Starts the timeout for this process to be repeated, clears the existing one if present
if (this.eventRefreshTimeout) clearTimeout(this.eventRefreshTimeout);
// Sets up when the bot should fetch the next update
if ((uqCounter + concertCounter + leagueCounter + otherCounter) < 10){
this.eventRefreshTimeout = setTimeout(async () => {this.clearEvents(); this.initEvents();}, this.overrideRefreshInterval);
console.log(`[EVENTS] There is a shortage of events, presumably due to the current schedule ending soon.`);
console.log(`[EVENTS] Temporarily overriding the configured refresh interval to force an update in: ${TimeStrings.totalTimeString(this.overrideRefreshInterval)}`);
}
else {
this.eventRefreshTimeout = setTimeout(async () => {this.clearEvents(); this.initEvents();}, this.refreshInterval);
console.log(`[EVENTS] Events have been updated. The next scheduled update is in: ${TimeStrings.totalTimeString(this.refreshInterval)}`);
}
}
// Searches for the events
public async searchEvents(searchTerm: string, embedFlag?: boolean, name?: string): Promise<string|MessageEmbed>{
const results = await this.questsSearch.searchEvents(searchTerm);
if (embedFlag){
if (name){
return (this.generateSearchResultsMessageEmbed(<SearchIndexEntity>results, searchTerm, name));
}
return (this.generateSearchResultsMessageEmbed(<SearchIndexEntity>results, searchTerm));
}
return (this.generateSearchResultsMessage(<SearchIndexEntity>results, searchTerm));
}
private generateSearchResultsMessage(searchResults: SearchIndexEntity, searchTerm: string): string{
const MessageResponse = new Messages();
let now = Date.now();
const maxResults = 5;
let results = 0;
let omittedResults = 0;
if (searchResults){
for (const idx in searchResults){
const eventStartTime = new Date(searchResults[idx].item.startTime).getTime();
const eventEndTime = new Date(searchResults[idx].item.endTime).getTime();
if (results < maxResults){
if ((now >= eventStartTime) && (now <= eventEndTime)){
MessageResponse.addMessageln(`**${searchResults[idx].item.title}**\`\`\`ldif\nHappening now!\nEnds in: ${TimeStrings.totalTimeString(eventEndTime-now)}\`\`\``);
results++;
}
else if (now < eventStartTime){
MessageResponse.addMessageln(`**${searchResults[idx].item.title}**\`\`\`ldif\nStarts in: ${TimeStrings.totalTimeString(eventStartTime-now)}\`\`\``);
results++;
}
}
else{
omittedResults++;
}
}
if (results == 0){
MessageResponse.addMessageln(`There doesn't seem to be any upcoming events related to \`${searchTerm}\` for this time period.`);
}
else{
MessageResponse.addHeaderMessageln(`Here's the next couple of events that I could find based on \`${searchTerm}\``);
if (omittedResults > 0){
if (omittedResults == 1){
MessageResponse.addMessageln(`There's **${omittedResults}** more event related to \`${searchTerm}\` scheduled to happen soon`);
}
else{
MessageResponse.addMessageln(`There's **${omittedResults}** more events related to \`${searchTerm}\` scheduled to happen soon`);
}
}
MessageResponse.addMessage(`These countdown times shown were based on ${UTCStrings.getTimestamp(new Date(now))} UTC`);
}
}
else {
MessageResponse.addMessageln(`There doesn't seem to be any results showing up for \`${searchTerm}\`.`);
}
// Return the message
return (MessageResponse.getMessage());
}
private generateSearchResultsMessageEmbed(searchResults: SearchIndexEntity, searchTerm: string, user?: string): MessageEmbed{
const embed = new MessageEmbed();
let now = Date.now();
const maxResults = 5;
let results = 0;
let omittedResults = 0;
embed.setTitle('Event Search Results');
embed.setColor('#da79b1');
embed.setTimestamp();
if (searchResults){
for (const idx in searchResults){
const eventStartTime = new Date(searchResults[idx].item.startTime).getTime();
const eventEndTime = new Date(searchResults[idx].item.endTime).getTime();
if (results < maxResults){
if ((now >= eventStartTime) && (now <= eventEndTime)){
embed.addField(`${searchResults[idx].item.title}`, `**This event is currently active!**\nEnds in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
results++;
}
else if (((eventStartTime-now) < 900000) && (now < eventEndTime)){
embed.addField(`${searchResults[idx].item.title}`, `**This event will start soon!**\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
}
else if (now < eventStartTime){
embed.addField(`${searchResults[idx].item.title}`, `Scheduled for \`${UTCStrings.getShortTimestamp(new Date(searchResults[idx].item.startTime))} UTC\`\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
results++;
}
}
else{
omittedResults++;
}
}
if (results == 0){
if (user){
embed.setDescription(`Hey ${user}! I tried looking for \`${searchTerm}\`, but there doesn't seem to be any more events for this time period.`);
}
else {
embed.setDescription(`There doesn't seem to be any more events containing \`${searchTerm}\` for this time period.`);
}
}
else{
if (user){
embed.setDescription(`Hi ${user}, thanks for waiting! Here's what I could find for \`${searchTerm}\`\n\u200B`);
}
else {
embed.setDescription(`Thanks for waiting! Here's what I could find for \`${searchTerm}\`\n\u200B`);
}
if (omittedResults > 0){
if (omittedResults == 1){
if (user){
embed.setDescription(`Hey ${user}, thanks for waiting! Here's what I could find for \`${searchTerm}\`. There's also **${omittedResults}** more result for \`${searchTerm}\` that is scheduled to happen soon\n\u200B`);
}
else {
embed.setDescription(`Thanks for waiting! Here's what I could find for \`${searchTerm}\`. There's also **${omittedResults}** more result for \`${searchTerm}\` that is scheduled to happen soon\n\u200B`);
}
}
else{
if (user){
embed.setDescription(`Hey ${user}, thanks for waiting! Here's what I could find for \`${searchTerm}\`. There's also **${omittedResults}** more results for \`${searchTerm}\` that are scheduled to happen soon\n\u200B`);
}
else {
embed.setDescription(`Thanks for waiting! Here's what I could find for \`${searchTerm}\`. There's also **${omittedResults}** more results for \`${searchTerm}\` that are scheduled to happen soon\n\u200B`);
}
}
}
}
}
else {
if (user){
embed.setDescription(`Hey ${user}, there doesn't seem to be any results coming up for \`${searchTerm}\`.`);
}
else {
embed.setDescription(`There doesn't seem to be any results coming up for \`${searchTerm}\`.`);
}
}
// Return the message
return (embed);
}
public async searchUpcomingEvents(): Promise<string>{
const MessageResponse = new Messages();
const maxResults = 5;
let results = 0;
const now = Date.now();
const data = <IndexedQueryEventObject>this.quests;
for (const idx in data){
const eventStartTime = new Date(data[idx].startTime).getTime();
const eventEndTime = new Date(data[idx].endTime).getTime();
if (results < maxResults){
if ((now >= eventStartTime) && (now <= eventEndTime)){
MessageResponse.addMessageln(`**${data[idx].title}**\`\`\`ldif\nHappening now!\nEnds in: ${TimeStrings.totalTimeString(eventEndTime-now)}\`\`\``);
results++;
}
else if (now < eventStartTime){
MessageResponse.addMessageln(`**${data[idx].title}**\`\`\`ldif\nStarts in: ${TimeStrings.totalTimeString(eventStartTime-now)}\`\`\``);
results++;
}
}
else{
break;
}
}
if (results > 0){
if (results == 1){
MessageResponse.addHeaderMessageln(`Here's the last scheduled event:`);
}
else {
MessageResponse.addHeaderMessageln(`Here's the next few scheduled events:`);
}
if (results < maxResults){
MessageResponse.addMessageln(`That's all I could find for this week! Hopefully Casra will give me the intel - in a neat, organized package for once!`);
}
MessageResponse.addMessage(`These countdown times shown were based on ${UTCStrings.getTimestamp(new Date(now))} UTC`);
}
else{
MessageResponse.addMessage(`There doesn't seem to be any upcoming events. I can feel Casra dumping a large unorganized pile of events on me any moment now...`)
}
return (MessageResponse.getMessage());
}
public async searchUpcomingEventsEmbed(user?: string): Promise<MessageEmbed>{
const embed = new MessageEmbed();
const maxResults = 5;
let results = 0;
let activeUQ = false;
const now = Date.now();
const data = <IndexedQueryEventObject>this.quests;
embed.setColor('#da79b1');
embed.setTitle('Upcoming Events');
embed.setTimestamp();
for (const idx in data){
const eventStartTime = new Date(data[idx].startTime).getTime();
const eventEndTime = new Date(data[idx].endTime).getTime();
if (results < maxResults){
// An active event
if ((now >= eventStartTime) && (now <= eventEndTime)){
switch(data[idx].categoryId){
// Code 9: UQ
case 9:
embed.setColor('#da0000');
embed.addField(`${data[idx].title}`, `**This is an active urgent quest!**\nEnds in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
embed.setFooter('Good luck out there, ARKS!');
activeUQ = true;
break;
// Code 10: Concert
case 10:
if (!activeUQ) {
embed.setColor('#007900');
embed.setTitle('Live Concert!');
embed.setFooter('KOI☆恋!');
}
embed.addField(`${data[idx].title}`, `**There is a live concert happening now!**\nEnds in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
break;
// Code 12: ARKS League
case 12:
if (!activeUQ){
embed.setTitle('Active ARKS League');
embed.setFooter('Good luck, operatives!');
}
embed.addField(`${data[idx].title}`, `**The ARKS League is currently active!**\nEnds in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
break;
default:
if (!activeUQ){
embed.setTitle('Active Event');
}
embed.addField(`${data[idx].title}`, `> **This event is in progress!**\n> Ends in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
}
results++;
}
// An upcoming event within 15 minutes of it starting
else if (((eventStartTime-now) < 900000) && (now < eventEndTime)){
switch(data[idx].categoryId){
// Code 9: UQ
case 9:
embed.setColor('#da0000');
embed.setFooter('Be sure to check your classes/loadouts and don\'t forget your buffs!');
embed.addField(`${data[idx].title}`, `**This urgent quest will start soon!**\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
activeUQ = true;
break;
// Code 10: Concert
case 10:
if (!activeUQ) {
embed.setFooter('Be prepared for an urgent quest right after!');
}
embed.addField(`${data[idx].title}`, `**This concert will start soon!**\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
break;
// Code 12: ARKS League
case 12:
embed.addField(`${data[idx].title}`, `**The league will start soon!**\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
default:
embed.addField(`${data[idx].title}`, `**This event will start soon!**\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
break;
}
results++;
}
// An upcoming event
else if (now < eventStartTime){
embed.addField(`${data[idx].title}`, `Scheduled for \`${UTCStrings.getShortTimestamp(new Date(data[idx].startTime))} UTC\`\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
results++;
}
}
else{
break;
}
}
if (results > 0){
if (results == 1){
if (user){
embed.setDescription(`Hello ${user}! Here's the last scheduled event`);
}
else {
embed.setDescription(`Here's the last scheduled event`);
}
}
else if (results < maxResults){
if (user){
embed.setDescription(`Hey ${user}! Here's all the events I could find. Hopefully there will be a new list soon!`);
}
else {
embed.setDescription(`Here's all the events I could find! Hopefully Casra will give me the intel in a neat, organized package for once!`);
}
}
else {
if (user){
embed.setDescription(`Hello ${user}! Here's the next few scheduled events\n\u200B`);
}
else {
embed.setDescription(`Here's the next few scheduled events\n\u200B`);
}
}
}
else{
if (user){
embed.setDescription(`Hmm... There doesn't seem to be any upcoming events, ${user}. Hopefully we won't have to wait long for the next set of events`);
}
else {
embed.setDescription(`Hmm, there doesn't seem to be any upcoming events. I can feel Casra dumping a large unorganized pile of events on me any moment now...`)
}
}
return (embed);
}
public async searchUpcomingCasinoEvents(): Promise<string>{
const MessageResponse = new Messages();
const maxResults = 5;
let results = 0;
const now = Date.now();
const data = <IndexedQueryEventObject>this.casino;
for (const idx in data){
const eventStartTime = new Date(data[idx].startTime).getTime();
const eventEndTime = new Date(data[idx].endTime).getTime();
if (results < maxResults){
if ((now >= eventStartTime) && (now <= eventEndTime)){
MessageResponse.addMessageln(`**${data[idx].title}**\`\`\`ldif\nHappening now!\nEnds in: ${TimeStrings.totalTimeString(eventEndTime-now)}\`\`\``);
results++;
}
else if (now < eventStartTime){
MessageResponse.addMessageln(`**${data[idx].title}**\`\`\`ldif\nStarts in: ${TimeStrings.totalTimeString(eventStartTime-now)}\`\`\``);
results++;
}
}
else{
break;
}
}
if (results > 0){
if (results == 1){
MessageResponse.addHeaderMessageln(`Here's the last scheduled event:`);
}
else {
MessageResponse.addHeaderMessageln(`Here's the next few scheduled events:`);
}
if (results < maxResults){
MessageResponse.addMessageln(`That's all I could find. Hopefully Diehl will provide an update soon!`);
}
MessageResponse.addMessage(`These countdown times shown were based on ${UTCStrings.getTimestamp(new Date(now))} UTC`);
}
else{
MessageResponse.addMessage(`There doesn't seem to be any boosts at the casino for now. Hopefully Diehl will provide an update soon!`);
}
return (MessageResponse.getMessage());
}
// Generates an embed containing information about casino boosts
public async searchUpcomingCasinoEventsEmbed(user?: string): Promise<MessageEmbed>{
const embed = new MessageEmbed();
const maxResults = 5;
let results = 0;
const now = Date.now();
const data = <IndexedQueryEventObject>this.casino;
for (const idx in data){
const eventStartTime = new Date(data[idx].startTime).getTime();
const eventEndTime = new Date(data[idx].endTime).getTime();
if (results < maxResults){
if ((now >= eventStartTime) && (now <= eventEndTime)){
embed.addField(`${data[idx].title}`, `**Currently in progress!**\nEnds in \`${TimeStrings.totalTimeString(eventEndTime-now)}\`\n\u200B`);
results++;
}
else if (now < eventStartTime){
embed.addField(`${data[idx].title}`, `Scheduled for \`${UTCStrings.getShortTimestamp(new Date(data[idx].startTime))} UTC\`\nStarts in \`${TimeStrings.totalTimeString(eventStartTime-now)}\`\n\u200B`);
results++;
}
}
else{
break;
}
}
if (results > 0){
if (results == 1){
if (user){
embed.setDescription(`Hey ${user}! Here's the last scheduled casino event. Hopefully Diehl wil provide an update soon!\n\u200B`);
}
else {
embed.setDescription(`Here's the last scheduled casino event. Hopefully Diehl wil provide an update soon!\n\u200B`);
}
}
else if (results < maxResults){
embed.setDescription(`These are the last few scheduled casino events. Hopefully Diehl will provide an update soon!\n\u200B`);
}
else {
if (user){
embed.setDescription(`Hey ${user}! Here's the next few scheduled boosts\n\u200B`);
}
else {
embed.setDescription(`Here's the next few scheduled boosts\n\u200B`);
}
}
}
else{
embed.setDescription(`There doesn't seem to be any boosts going on at the casino right now. Hopefully Diehl will provide an update soon!`);
}
embed.setColor('#da79b1');
embed.setTitle('Casino Boosts');
embed.setTimestamp();
return (embed);
}
}
|
5b226358d9b1f4233845f2ec766fc6c1fcdc2f4b
|
TypeScript
|
sindresorhus/type-fest
|
/source/has-required-keys.d.ts
| 4.03125
| 4
|
import type {RequiredKeysOf} from './required-keys-of';
/**
Creates a type that represents `true` or `false` depending on whether the given type has any required fields.
This is useful when you want to create an API whose behavior depends on the presence or absence of required fields.
@example
```
import type {HasRequiredKeys} from 'type-fest';
type GeneratorOptions<Template extends object> = {
prop1: number;
prop2: string;
} & (HasRequiredKeys<Template> extends true
? {template: Template}
: {template?: Template});
interface Template1 {
optionalSubParam?: string;
}
interface Template2 {
requiredSubParam: string;
}
type Options1 = GeneratorOptions<Template1>;
type Options2 = GeneratorOptions<Template2>;
const optA: Options1 = {
prop1: 0,
prop2: 'hi'
};
const optB: Options1 = {
prop1: 0,
prop2: 'hi',
template: {}
};
const optC: Options1 = {
prop1: 0,
prop2: 'hi',
template: {
optionalSubParam: 'optional value'
}
};
const optD: Options2 = {
prop1: 0,
prop2: 'hi',
template: {
requiredSubParam: 'required value'
}
};
```
@category Utilities
*/
export type HasRequiredKeys<BaseType extends object> = RequiredKeysOf<BaseType> extends never ? false : true;
|
5bdfa90ee8d0ee0920af60c643c869bbc9778368
|
TypeScript
|
joshhunt/clips-destiny
|
/app/components/utils.ts
| 2.671875
| 3
|
/* eslint-disable import/prefer-default-export */
import fs from 'fs';
import path from 'path';
import util from 'util';
import { sortBy } from 'lodash';
const readdir = util.promisify(fs.readdir);
const VIDEO_REGEX = /^Destiny 2 (?<year>\d{4})\.(?<month>\d{2})\.(?<day>\d{2}) - (?<hour>\d{2})\.(?<minute>\d{2})\.(?<seconds>\d{2})\.(?<milliseconds>\d{2})\.DVR\.mp4$/;
export interface BasicVideoData {
fileName: string;
filePath: string;
endDate: Date;
}
export async function listVideosInDir(folderDir: string) {
const files = await readdir(folderDir);
const videos: BasicVideoData[] = [];
files.forEach(fileName => {
const reResult = fileName.match(VIDEO_REGEX);
const filePath = path.join(folderDir, fileName);
if (!reResult || !reResult.groups) {
return;
}
const params = reResult.groups;
const endDate = new Date(
Number(params.year),
Number(params.month) - 1,
Number(params.day),
Number(params.hour),
Number(params.minute),
Number(params.seconds),
Number(params.milliseconds)
);
videos.push({
fileName,
filePath,
endDate
});
});
return sortBy(videos, video => video.endDate);
}
export function dateRangeOverlaps(
aStart: Date,
aEnd: Date,
bStart: Date,
bEnd: Date
) {
if (aStart <= bStart && bStart <= aEnd) return true; // b starts in a
if (aStart <= bEnd && bEnd <= aEnd) return true; // b ends in a
if (bStart < aStart && aEnd < bEnd) return true; // a in b
return false;
}
|
4d12109cdbefba18e0267a8bc77a60c230fc6377
|
TypeScript
|
mpajunen/advent-of-code
|
/2020/day9.ts
| 3.21875
| 3
|
import { Grid, Input, Num, List, Str, Vec2 } from '../common'
const findContiguousSum = (nums: number[], target: number): number[] => {
for (let i = 0; i < nums.length; i++) {
let sum = nums[i]
for (let j = i + 1; j < nums.length; j++) {
sum += nums[j]
if (sum === target) {
return nums.slice(i, j)
}
if (sum > target) {
break
}
}
}
return []
}
const PREAMBLE_SIZE = 25
export default (rows: string[]) => {
const nums = rows.map(r => parseInt(r))
const preamble = index => nums.slice(index - PREAMBLE_SIZE, index)
const isValid = (num, i) => Num.pairSums(preamble(i)).includes(num)
const getWeakness = target => {
const range = findContiguousSum(nums, target)
return Math.min(...range) + Math.max(...range)
}
const result1 = nums.find((n, i) => i >= PREAMBLE_SIZE && !isValid(n, i))
const result2 = getWeakness(result1)
return [result1, result2, 29221323, 4389369]
}
|
48aec81745b881fbef0a956a6909ef8da63b525f
|
TypeScript
|
fpaschos/simple-bank-system
|
/react-ui/src/services/hooks.ts
| 3.3125
| 3
|
import {useEffect, useRef, useState} from "react";
// From https://usehooks.com/usePrevious/
export let usePrevious: (value: any) => any;
usePrevious = (value: any) => {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
};
// From https://usehooks.com/useWindowSize/
export const useWindowSize = () => {
const isClient = typeof window === 'object';
const size = getSize();
function getSize() {
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined
};
}
const [windowSize, setWindowSize] = useState(getSize);
useEffect(() => {
if (!isClient) {
return () => {};
}
function handleResize() {
setWindowSize(size);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [size,isClient]); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
};
|
92544a485959b3647f1b34a5735e75f8359c5191
|
TypeScript
|
kong2630929821/message
|
/src/chat/server/tests/db_test.ts
| 2.828125
| 3
|
import { EnumType, TabMeta, Type } from '../../../pi/struct/sinfo';
import { Bucket, createMemoryBucket, createPersistBucket } from '../../utils/db';
import { UserInfo } from './foo.s';
const test_basic_db_operation = () => {
const m = new TabMeta(new EnumType(Type.Str), new EnumType(Type.Str));
// memory db
const memBucket = createPersistBucket('hello', m);
memBucket.put<string, string>('hi', 'Hello');
// write different key type and value type
memBucket.put<number, number>(1, 100);
// memBucket.get(1); // should panic
console.log(memBucket.get<string, string>('hi'));
if (memBucket.delete<string>('hi')) {
console.log('delete exist key success');
} else {
console.log('delete exist key failed');
}
// delete not exist key
if (memBucket.delete<string>('wtf')) {
console.log('delete non-exist key success');
} else {
console.log('delete non-exist key failed');
}
// file db
const persistBucket = createMemoryBucket('hello', m);
persistBucket.put<string, string>('11', '22');
console.log(persistBucket.get<string, string>('11'));
};
const test_write_structInfo = () => {
const meta = new TabMeta(new EnumType(Type.U32), new EnumType(Type.Struct, UserInfo._$info));
const m = createMemoryBucket('TEST', meta);
const v = new UserInfo();
v.uid = 99202;
v.phone = '你是谁';
m.put<Type.Struct, any>(123, v);
console.log(m.get(123));
};
const test_iterdb = () => {
const m = new TabMeta(new EnumType(Type.Str), new EnumType(Type.Str));
// memory db
const memBucket = createPersistBucket('foo', m);
memBucket.put<string, string>('hi1', 'world1');
memBucket.put<string, string>('hi2', 'world2');
memBucket.put<string, string>('hi3', 'world3');
const it = memBucket.iter<string>('hi');
const item1 = it.nextElem();
const item2 = it.nextElem();
const item3 = it.nextElem();
if (item1[1] !== 'world1' && item2[1] !== 'world2' && item3[1] !== 'world3') {
throw new Error('Test iterdb failed');
} else {
console.log('Test iterDb successed');
}
};
const test_read_from_exist_bucket = () => {
const bkt = new Bucket('file', 'foo');
console.log('read_from_exist_bucket', bkt.get('hi1'));
};
const test_batch_read = () => {
const bkt = new Bucket('file', 'foo');
const v = bkt.get(['hi1', 'hi2', 'hi3']);
console.log('test_batch_read', v);
};
const test_batch_write_then_read = () => {
const bkt = new Bucket('file', 'foo');
const keys = ['batch1', 'batch2', 'batch3'];
const vals = ['batch_value1', 'batch_value2', 'batch_value3'];
bkt.put(keys, vals);
const v = bkt.get(keys);
console.log('batch_write_then_read:', v);
if (v[0] === vals[0] && v[1] === vals[1] && v[2] === vals[2]) {
console.log('test batch write then read success');
} else {
console.log('test batch write then read failed');
}
};
export const test_db = () => {
test_basic_db_operation();
test_write_structInfo();
test_iterdb();
test_read_from_exist_bucket();
test_batch_read();
test_batch_write_then_read();
};
|
ad3c243da881a2a8fda8dff34f903157c8527bbf
|
TypeScript
|
bsorrentino/mac-cleaner
|
/src/main.ts
| 2.71875
| 3
|
import 'zx/globals'
import inquirer, { Answers } from 'inquirer';
import { Stats } from 'fs';
import { EMPTY, from, Observable, map, mergeMap } from 'rxjs';
import {basename} from 'path'
import { Command } from 'commander';
import untildify from 'untildify'
type SearchOptions = {
excludeDirs:Array<RegExp>
onlyin?:string
exact?:boolean
}
type FileInfo = { path:string, stats?:Stats };
const sortFileInfo = ( a:FileInfo, b:FileInfo ) => {
if( a.path < b.path ) return -1;
if( a.path > b.path ) return 1;
return 0;
}
/**
*
* @param path
* @param stats
* @returns
*/
function FileInfo( path:string, stats?:Stats ) {
return { path:path, stats:stats };
}
/**
*
* @param name
* @param options
*/
function mdFindAsync( name:string, options:SearchOptions ) {
const { excludeDirs, onlyin, exact } = options
let params = [ '-name', name ]
if( onlyin ) {
params.push( '-onlyin', onlyin )
}
async function* fetchResult () {
$.verbose = false
const { stderr, stdout } = await $`mdfind ${params}`
const predicate_true = ( _:string ) => true
const isLineValid = ( line:string ) => line && line.trim().length > 0
const excludeDirFilter = excludeDirs.length > 0 ?
( line:string ) => !excludeDirs.some( pp => line.match( pp )!=null) :
predicate_true ;
const exactFilter = (exact) ?
(line:string) => basename(line).localeCompare(name, undefined, { sensitivity: 'accent'} )===0 :
predicate_true ;
const lines = stdout.split('\n')
.filter( isLineValid )
.filter( excludeDirFilter )
.filter( exactFilter )
for ( const line of lines) {
const stat = await fs.stat( line )
yield FileInfo( line, stat )
}
}
return {
[Symbol.asyncIterator]: () => fetchResult()
}
}
/**
*
* @param fileInfo
* @param pageSize
* @returns
*/
function makeChoices( fileInfo:FileInfo[], pageSize:number ):Observable<Answers>{
const module = inquirer.createPromptModule( )
const choices = fileInfo
.map( f => ( { name: f.path, value: f } ))
return from( module( [{
name:'elements',
type: 'checkbox',
choices: choices,
pageSize: pageSize
}]))
}
/**
*
* @param value
*/
function print( value:FileInfo ) {
if( !value.stats ) {
console.log( chalk.red( value.path ))
}
else if( value.stats.isFile() )
console.log( chalk.blueBright( value.path ))
else if( value.stats.isDirectory() )
console.log( chalk.cyanBright( value.path ))
}
/**
*
* @param file
* @param dryRun
* @returns
*/
function remove( file:FileInfo, dryRun = false ):Observable<FileInfo> {
if( file.stats ) {
if( file.stats.isFile() ) {
console.log( `rm '${file.path}'`)
}
else if( file.stats.isDirectory() ) {
console.log( `rm -r '${file.path}'`)
}
if( !dryRun ) {
from(fs.remove( file.path )).pipe( map( v => file ))
}
}
return EMPTY;
}
/**
*
* @param version
*/
export function main( version?:string ) {
const program = new Command()
const p = program
.version( version ?? 'unknown', '-v --version')
.option( '--excludeDir <dir[,dir,...]>', 'exclude folder list')
.option( '--onlyin <dir>', 'search exclusively in <dir>')
.option( '--dryRun', 'simulate execution (file will non be deleted)')
.option( '--pageSize <n>', 'number of lines that will be shown per page', '10')
.option( '--exact', 'match exactly the given name', false)
.arguments( '<name>' )
.action( runSearchAsync )
if (process.argv.slice(2).length == 0) {
program.outputHelp()
}
else {
p.parse(process.argv)
}
}
async function runSearchAsync( appName:string, options:any ) {
process.stdout.write('\x1Bc')
console.log( `${chalk.underline('Search for:')} ${chalk.blueBright.bold(appName)}`)
let excludeDirs:Array<RegExp> = [];
if( options.excludeDir ) {
excludeDirs = String(options.excludeDir).split(',')
.map( p => untildify(p) )
.map( p => (new RegExp( '^' + p ) ) )
}
const files = Array<FileInfo>()
for await (const f of mdFindAsync( appName, {
excludeDirs:excludeDirs,
onlyin:options.onlyin,
exact:options.exact
})) {
if( f.stats?.isFile() || f.stats?.isDirectory()) {
files.push( f )
}
}
console.log( `\n${chalk.red.bold('Selected files will be removed')}\n`)
makeChoices( files.sort( sortFileInfo ), Number(options.pageSize) )
.pipe(
mergeMap( v => from(v.elements) ),
mergeMap( (f:any) => remove(f, options.dryRun ) ))
.subscribe(
v => {},
err => console.error( err),
() => console.log('\n')
)
}
|
1071efa02f4f52957d0b4fe0026d6e948267edf2
|
TypeScript
|
krishanmarco/object-param-parser
|
/__tests__/parsers/ParamParser.spec.ts
| 2.90625
| 3
|
/** Created by Krishan Marco Madan [krishanmarco@outlook.com] [http://www.krishanmadan.com] [29-Jun-18|4:43 PM] © */
import {
ParamParser,
Parser,
Validators,
} from '../../src';
describe('parsers/ParamParser', () => {
it('Should parse values correctly', () => {
const { a } = new ParamParser()
.get('a.a.a')
.parse({ a: { a: { a: 'aaa' } } });
expect(a).toBe('aaa');
});
it('Should rename values correctly', () => {
const { ab } = new ParamParser()
.getAs('a.b', 'ab')
.parse({ a: { b: 'ab' } });
expect(ab).toBe('ab');
});
it('Should rename values correctly (nested)', () => {
const val = new ParamParser()
.getAs('a.b', 'b.a')
.parse({ a: { b: 'ab' } });
expect(val).toEqual({ b: { a: 'ab' } });
});
it('Should invoke error handler on required value not set', () => {
const parser = new ParamParser()
.withCustomErrorHandler(() => {
throw new Error();
})
.get('a.b');
expect(() => parser.parse({ a: { b: null } })).toThrow();
});
it('Should not invoke error handler on required value not set', () => {
const parser = new ParamParser()
.withCustomErrorHandler(() => {
throw new Error();
})
.get('a.b');
expect(() => parser.parse({ a: { b: 'a' } })).not.toThrow();
});
it('Should invoke custom error handler on required value not set and default error handler not set', () => {
const parser = new ParamParser()
.get('a.b', {
onError: () => {
throw new Error();
},
});
expect(() => parser.parse({ a: { b: null } })).toThrow();
});
it('Should use default value (constant)', () => {
const { a } = new ParamParser()
.get('a', { def: 'x' })
.parse();
expect(a).toBe('x');
});
it('Should use default value (function)', () => {
const { a } = new ParamParser()
.get('a', { def: () => 'x' })
.parse();
expect(a).toBe('x');
});
it('Should validate value', () => {
const parser = new ParamParser()
.get('a', {
validate: [(_) => false, (_) => true],
onError: () => {
throw new Error();
},
});
expect(() => parser.parse()).toThrow();
});
it('Should not validate undefined if req=false', () => {
const parser = new ParamParser()
.get('a.b', {
validate: Validators.isEmail,
req: false,
});
expect(() => parser.parse({ a: {} })).not.toThrow();
});
it('Should sanitize value', () => {
const { a } = new ParamParser()
.get('a', {
sanitize: [(val) => val + 'y', (val) => val + 'z'],
})
.parse({ a: 'x' });
expect(a).toBe('xyz');
});
it('Should statically parse values', () => {
const { a, b, c } = Parser.parse({
a: { a: 'a' },
b: { b: 'b' },
d: { d: 'c' },
}, [
{ path: 'a.a' },
{ path: 'b.b' },
{ path: 'd.d', as: 'c' },
]);
expect(a).toBe('a');
expect(b).toBe('b');
expect(c).toBe('c');
});
it('Should statically parse values', () => {
const { a, b, c } = Parser.parse({
a: { a: 'a' },
b: { b: 'b' },
c: { c: 'c' },
}, [
{
path: 'a.a',
select: false,
},
{
path: 'b.b',
select: true,
},
{
path: 'c.c',
},
]);
expect(a).toBeUndefined();
expect(b).toBe('b');
expect(c).toBe('c');
});
});
describe('ParamParser (Form version)', () => {
it('Should parse a JSON form def correctly (arrays)', () => {
const result = Parser.create()
.addAll(JSON.stringify({
'users[*]': {},
'users': {
as: 'allowedUsers',
},
}))
.parse({
users: [
{ name: 'User1', email: 'user1@test.com' },
{ name: 'User2', email: 'user2@test.com' },
],
});
const { users, allowedUsers } = result;
expect(users.length).toBe(2);
expect(users[0]).toHaveProperty('email', 'user1@test.com');
expect(users[0]).toHaveProperty('name', 'User1');
expect(users[1]).toHaveProperty('email', 'user2@test.com');
expect(users[1]).toHaveProperty('name', 'User2');
expect(allowedUsers.length).toBe(2);
expect(allowedUsers[0]).toHaveProperty('email', 'user1@test.com');
expect(allowedUsers[0]).toHaveProperty('name', 'User1');
expect(allowedUsers[1]).toHaveProperty('email', 'user2@test.com');
expect(allowedUsers[1]).toHaveProperty('name', 'User2');
});
it('Should throw on invalid JSON form def (arrays)', () => {
const parser = Parser.httpParser()
.addAll(JSON.stringify({
'users[*].email': {
sanitize: 'email',
validate: 'isEmail',
},
}));
expect(() => {
parser.parse({
users: [
{ name: 'User1', email: 'user1@test.com' },
{ name: 'User2', email: 'invalidEmailAddress' },
],
});
}).toThrow();
});
it('Should parse a JSON form def correctly (nested arrays)', () => {
const result = Parser.create()
.addAll(JSON.stringify({
'oldUsers[*].emails[*]': {
sanitize: 'email',
validate: 'isEmail',
},
}))
.parse({
oldUsers: [
{ emails: ['user-1@test.com', 'user--1@test.com', 'user---1@test.com'] },
{ emails: ['user-2@test.com', 'user--2@test.com', 'user---2@test.com'] },
],
});
const { emails } = result;
expect(emails.length).toBe(6);
expect(emails[0]).toBe('user-1@test.com');
expect(emails[1]).toBe('user--1@test.com');
expect(emails[2]).toBe('user---1@test.com');
expect(emails[3]).toBe('user-2@test.com');
expect(emails[4]).toBe('user--2@test.com');
expect(emails[5]).toBe('user---2@test.com');
});
it('Should parse a JSON form def correctly (nested objects in arrays)', () => {
const result = Parser.create()
.addAll(JSON.stringify({
'info[*]': {},
'info[0]': {
as: 'info0',
},
'info[0].test': {},
'info[0].nonExistantValue': {
req: false,
},
'info[1]': {
as: 'info1',
validate: {
f: 'equals',
p: { val: 'RandomString' },
},
},
'info[3][2].email': {
sanitize: 'email',
validate: 'isEmail',
},
}))
.parse({
info: [
{ test: 'dynamic-object' },
'RandomString',
1,
[
'user3@test.com',
'user3',
{ name: 'User4', email: 'user4@test.com' },
],
],
});
const {
info,
info0,
test,
nonExistantValue,
info1,
email,
} = result;
expect(info.length).toBe(4);
expect(info0).toHaveProperty('test', 'dynamic-object');
expect(test).toBe('dynamic-object');
expect(nonExistantValue).toBeUndefined();
expect(info1).toBe('RandomString');
expect(email).toBe('user4@test.com');
});
});
|
b2fd6840ec12cc6e4ca557db13f9fbb0045f4786
|
TypeScript
|
Keemluvr/pokedex
|
/src/services/pokemons.ts
| 2.859375
| 3
|
import { Dispatch, SetStateAction } from "react"
import http from "@/helpers/http"
import {
PokemonColor,
PokemonColorList,
PokemonList,
ThemeCardBackground
} from "@/types"
import { Pokemon } from "@/types"
export const listPokemons = async (
path?: string,
setLoading?: Dispatch<SetStateAction<boolean>>
): Promise<PokemonList | undefined> => {
const result = await http<PokemonList>().get(path ? path : "/pokemon")
const pokemons = result?.data
const colors = await getColors()
const results = await Promise.all(
(pokemons as PokemonList)?.results?.map(async (pokemon) => {
const info = (await getPokemonByIdOrName(pokemon.name)) as Pokemon
let color = "black"
colors?.results?.map((c) => {
if (!!c.species.find((specie) => specie.name === pokemon.name))
color = c.name
})
return {
...pokemon,
...info,
color
}
})
).then((results) => ({ ...pokemons, results } as PokemonList))
setLoading?.(false)
return results
}
export const getPokemonByIdOrName = async (
name: string | number,
setLoading?: Dispatch<SetStateAction<boolean>>
): Promise<Pokemon | undefined> => {
const result = await http<Pokemon>().get(`/pokemon/${name}`)
const pokemon = result?.data
const colors = await getColors()
let color = "black"
if (pokemon) {
colors?.results?.map((c) => {
if (!!c.species.find((specie) => specie.name === pokemon.name))
color = c.name
})
setLoading?.(false)
if (pokemon)
return {
...pokemon,
color: color as ThemeCardBackground
}
}
}
export const getTypeByName = async (
name: string,
setLoading?: Dispatch<SetStateAction<boolean>>
): Promise<Pokemon | undefined> => {
const result = await http<Pokemon>().get(`/type/${name}`)
setLoading?.(false)
return result?.data
}
export const getColorByName = async (
name: string,
setLoading?: Dispatch<SetStateAction<boolean>>
): Promise<PokemonColor | undefined> => {
const result = await http<PokemonColor>().get(`/pokemon-color/${name}`)
setLoading?.(false)
return result?.data
}
export const getColors = async (
setLoading?: Dispatch<SetStateAction<boolean>>
) => {
const result = await http<PokemonColorList>().get(`/pokemon-color`)
const colors = result?.data
const results = await Promise.all(
(colors as PokemonColorList)?.results?.map(async (color) => {
const info = (await getColorByName(color.name)) as PokemonColor
return {
...color,
species: info.pokemon_species
}
})
).then((results) => ({ ...colors, results } as PokemonColorList))
setLoading?.(false)
return results
}
|
dfa65012f29cd8b8cc6968cfc6f16ac1852b453e
|
TypeScript
|
alessandrapaulaf/scheduling-job
|
/src/helpers/jobs/index.ts
| 2.71875
| 3
|
import IJob from "../../models/job";
const filterAndSortbyDate = (jobs: IJob[], init: Date) => {
return jobs
.filter((job: IJob) => job.maxDate >= init)
.sort((a, b) => {
return (a.maxDate as any) - (b.maxDate as any);
});
};
const convertToJobModel = (object: any): IJob => {
return {
id: parseInt(object.id),
description: object.description,
maxDate: new Date(object.maxDate),
executed: false,
estimatedTime:
parseInt(object.estimatedTime) ||
parseInt(object.estimatedTime.split(" ")[0]),
};
};
const getCounterProcesses = (jobs: IJob[], timeLimitToProcess: number) => {
return Math.ceil(
jobs.reduce((total: number, job: IJob) => {
return total + job.estimatedTime;
}, 0) / timeLimitToProcess
);
};
const getOutsideWindowExecute = (jobs: any[], init: string) => {
return jobs.filter((job) => job.maxDate <= init);
};
const getOutsideLimitExecution = (jobs: any[], limitTime: number) => {
return jobs.filter((job) => {
const estimated =
parseInt(job.estimatedTime) || parseInt(job.estimatedTime.split(" ")[0]);
return estimated > limitTime;
});
};
export {
filterAndSortbyDate,
convertToJobModel,
getCounterProcesses,
getOutsideWindowExecute,
getOutsideLimitExecution,
};
|
1f038ad105473c0a7f850c2d5fec67c5e3e6599d
|
TypeScript
|
HZ-HBO-ICT/formula-1-racing-game
|
/src/app.ts
| 3.671875
| 4
|
/// <reference path="Car.ts" />
/// <reference path="KeyboardListener.ts" />
class Game {
// Necessary canvas attributes
private readonly canvas: HTMLCanvasElement;
private readonly ctx: CanvasRenderingContext2D;
// KeyboardListener so the player can move
private keyboardListener: KeyboardListener;
// the state of the game: begin, dice and end
private gameState: string;
private winner: string;
constructor(canvas: HTMLCanvasElement) {
this.canvas = canvas;
this.ctx = this.canvas.getContext("2d");
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.keyboardListener = new KeyboardListener();
this.gameState = "begin";
this.loop();
}
/**
* Function to give a number between 1 and 6
* @returns {number} number - number between 1 and 6
*/
private rollDice(): number {
return this.randomNumber(1, 6);
}
/**
* Method for the Game Loop
* Based on the game state some actions have to be executed
*/
private loop = () => {
this.draw();
requestAnimationFrame(this.loop);
};
/**
* Function to draw all the cars on the canvas
*/
private draw() {
}
/**
* Writes text to the canvas
* @param {string} text - Text to write
* @param {number} fontSize - Font size in pixels
* @param {number} xCoordinate - Horizontal coordinate in pixels
* @param {number} yCoordinate - Vertical coordinate in pixels
* @param {string} alignment - Where to align the text
* @param {string} color - The color of the text
*/
public writeTextToCanvas(
text: string,
fontSize: number = 20,
xCoordinate: number,
yCoordinate: number,
alignment: CanvasTextAlign = "center",
color: string = "red"
) {
this.ctx.font = `${fontSize}px Minecraft`;
this.ctx.fillStyle = color;
this.ctx.textAlign = alignment;
this.ctx.fillText(text, xCoordinate, yCoordinate);
}
/**
* Renders a random number between min and max
* @param {number} min - minimal time
* @param {number} max - maximal time
*/
public randomNumber(min: number, max: number): number {
return Math.round(Math.random() * (max - min) + min);
}
}
/**
* Start the game whenever the entire DOM is loaded
*/
let init = () =>
new Game(document.getElementById("canvas") as HTMLCanvasElement);
// Add EventListener to load the game whenever the browser is ready
window.addEventListener("load", init);
|
6738fac1addda0f306ff3bd15ae6b1273ae0b0ea
|
TypeScript
|
AUSdomgarcia/angular2-journey
|
/038 Exercise/angular2-quiz/src/question.component.ts
| 2.609375
| 3
|
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Question } from './question.model';
@Component({
selector: 'question',
template: `
<p>
<strong>{{question.text}}</strong>
</p>
<div class="indent">
<div *ngFor="let option of question.options">
<label>
<input type="radio" [name]="question.id" [value]="option.id"
(click)="answer.emit($event.target.value)" [disabled]="checked">
{{option.text}}
</label>
</div>
<p *ngIf="correct === true">✔ Correct</p>
<p *ngIf="correct === false">✘ Incorrect</p>
</div>
`,
styles: [`
.indent {
margin-left: 3ex;
}
`]
})
export class QuestionComponent {
@Input() question: Question;
@Input() correct: boolean;
@Output() answer = new EventEmitter<string>();
get checked() {
return this.correct !== undefined;
}
}
|
05cf68a5242ca24c4aac403e0787f0eccd0f8a61
|
TypeScript
|
xXD4rkC0d3rXx/ab-testing
|
/src/modules/CacheTest.ts
| 2.53125
| 3
|
import Test from "../core/Test";
import {ICacheTest, ITestField, ITestFieldAdapter} from "../../types";
import {checkLocalStorage, checkWindowSupport} from "../helpers/checkSupports";
export default class CacheTest extends Test implements ICacheTest {
private readonly storage: Storage | undefined
constructor(name: string, fields: ITestField[]) {
if (!checkLocalStorage) {
console.error('Local storage is not supported')
return
}
super(name, fields)
if (checkWindowSupport()) {
this.storage = window.localStorage
}
}
check(): ITestFieldAdapter {
const cacheField = this.getCacheActiveField()
if (cacheField) {
this.setActiveField(cacheField)
const newActiveField = this.getActiveField()
if (newActiveField !== undefined) {
return newActiveField
}
} else {
const field = super.check()
this.setItem(`ab_active_field_${ this.name }`, field.name)
}
const findEl = this.getActiveField()
if (findEl) {
return findEl
}
// TODO Fix IT
return {
weight: 1,
name: '0'
}
}
protected getSerializeName(testName: string, fieldName: string) {
return `${ testName }_${ fieldName }`
}
protected getCacheActiveField() {
return this.getItem(`ab_active_field_${ this.name }`)
}
protected setItem(key: string, value: any) {
if (this.storage !== undefined) {
this.storage.setItem(key, value.toString())
}
}
protected getItem(key: string): string | undefined {
if (this.storage !== undefined) {
const getValue = this.storage.getItem(key)
return getValue === null ? undefined : getValue
}
}
}
|
92d5321bd874a6075511f341528b779b50c7785f
|
TypeScript
|
AlaaSayed794/image-processing-api-udacity-nd
|
/src/tests/indexSpec.ts
| 2.5625
| 3
|
import supertest from 'supertest';
import app from '../index';
import { getImage, getImagesDir } from '../utils/fsUtils';
import fs from 'fs';
import path from 'path';
const request = supertest(app);
describe('Test endpoint responses', () => {
const validFile = 'fjord';
const invalidFile = 'nonExistingFile';
const width = 300;
const height = 400;
it('gets the main endpoint', async () => {
const response = await request.get('/');
expect(response.status).toBe(200);
expect(response.text).toBe(
'use api/images?filename={yourfilename} to get started'
);
});
it('gets the api endpoint', async () => {
const response = await request.get('/api');
expect(response.status).toBe(200);
expect(response.text).toBe(
'use api/images?filename={yourfilename} to get started'
);
});
it('get api/images with invalid file', async () => {
const response = await request.get('/api/images?filename=' + invalidFile);
expect(response.status).toBe(400);
expect(response.text).toBe('file name is invalid');
});
it('get api/images with no parameters', async () => {
const response = await request.get('/api/images');
expect(response.status).toBe(400);
expect(response.text).toBe(
'please provide valid filename as a query parameter'
);
});
it('get api/images with valid file', async () => {
const response = await request.get('/api/images?filename=' + validFile);
expect(response.status).toBe(200);
});
it('get api/images with valid file and resized width', async () => {
const response = await request.get(
`/api/images?filename=${validFile}&width=${width}`
);
expect(response.status).toBe(200);
});
it('get api/images with valid file and resized height', async () => {
const response = await request.get(
`/api/images?filename=${validFile}&height=${height}`
);
expect(response.status).toBe(200);
});
it('get api/images with valid file and resized width and height', async () => {
const response = await request.get(
`/api/images?filename=${validFile}&width=${width}&height=${height}`
);
expect(response.status).toBe(200);
});
it('test the image resizing function with invalid file', async () => {
expect(await getImage(invalidFile, width, height)).toBe(
'path does not exist'
);
});
it('test the image resizing function with valid file', async () => {
const filename = `${validFile}-width${width}-height${height}.jpg`;
expect(await getImage(validFile, width, height)).toContain(filename);
expect(
fs.existsSync(
path.join(await getImagesDir(__dirname), 'resized', filename)
)
).toBeTruthy();
});
});
|
f2d19a45fff9b9abaee8ff4e8aa1ad70df350d70
|
TypeScript
|
selfrefactor/rambda
|
/source/indexBy-spec.ts
| 3.203125
| 3
|
import {indexBy} from 'rambda'
const list = [{a: {b: '1'}}, {a: {c: '2'}}, {a: {b: '3'}}]
describe('indexBy', () => {
it('happy', () => {
const result = indexBy(x => x.a.b, list)
const curriedResult = indexBy<any>(x => x.a.b)(list)
result.foo?.a.b // $ExpectType string | undefined
curriedResult // $ExpectType { [x: string]: any; }
})
it('with string', () => {
const result = indexBy('a.b', list)
const curriedResult = indexBy<any>('a.b')(list)
result.foo?.a.b // $ExpectType string | undefined
curriedResult // $ExpectType { [key: string]: any; }
})
it('with interface', () => {
interface Foo {
a: string,
}
const interfaceList = [{a: 'foo'}, {a: 'bar'}]
const result = indexBy<Foo>(x => {
x.a // $ExpectType string
return x.a
}, interfaceList)
const curriedResult = indexBy<Foo>(x => {
x.a // $ExpectType string
return x.a
})(interfaceList)
result // $ExpectType { [x: string]: Foo; }
curriedResult // $ExpectType { [x: string]: Foo; }
})
})
|
0077a76f759d8a26d48275a0e1a1722b838f78af
|
TypeScript
|
angular/angular
|
/packages/benchpress/test/validator/regression_slope_validator_spec.ts
| 2.546875
| 3
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, MeasureValues, RegressionSlopeValidator} from '../../index';
{
describe('regression slope validator', () => {
let validator: RegressionSlopeValidator;
function createValidator({size, metric}: {size: number, metric: string}) {
validator = Injector
.create({
providers: [
RegressionSlopeValidator.PROVIDERS,
{provide: RegressionSlopeValidator.METRIC, useValue: metric},
{provide: RegressionSlopeValidator.SAMPLE_SIZE, useValue: size}
]
})
.get(RegressionSlopeValidator);
}
it('should return sampleSize and metric as description', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.describe()).toEqual({'sampleSize': 2, 'regressionSlopeMetric': 'script'});
});
it('should return null while the completeSample is smaller than the given size', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.validate([])).toBe(null);
expect(validator.validate([mv(0, 0, {})])).toBe(null);
});
it('should return null while the regression slope is < 0', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.validate([mv(0, 0, {'script': 2}), mv(1, 1, {'script': 1})])).toBe(null);
});
it('should return the last sampleSize runs when the regression slope is ==0', () => {
createValidator({size: 2, metric: 'script'});
const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})];
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
it('should return the last sampleSize runs when the regression slope is >0', () => {
createValidator({size: 2, metric: 'script'});
const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})];
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
});
}
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
|
b7286b3f2084c43803a1df8b900be07f78427cf6
|
TypeScript
|
uwdata/draco-tuner
|
/src/model/collection-item.ts
| 2.921875
| 3
|
import _ from 'lodash';
import { Chart, ChartObject } from './chart';
import { ConstraintMapObject } from './constraint-map';
import { Pair, PairObject } from './pair';
import { DracoSolution, ViolationMap } from './spec';
export interface CollectionItemObject {
type: CollectionItemType;
}
export class CollectionItem {
static CHART: 'chart' = 'chart';
static PAIR: 'pair' = 'pair';
static isChart = function(item: CollectionItemObject): item is ChartObject {
return item.type === CollectionItem.CHART;
};
static isPair = function(item: CollectionItemObject): item is PairObject {
return item.type === CollectionItem.PAIR;
};
static getEval = function(item: CollectionItemObject, constraintMap: ConstraintMapObject): CollectionItemEvalType {
if (CollectionItem.isChart(item)) {
return Chart.getEval(item, constraintMap);
}
if (CollectionItem.isPair(item)) {
return Pair.getEval(item, constraintMap);
}
};
static getViolationMap = function(item: CollectionItemObject): ViolationMap {
if (CollectionItem.isChart(item)) {
if (!DracoSolution.isDefined(item.sol)) {
return {};
}
return item.sol.violations;
}
if (CollectionItem.isPair(item)) {
const violationMap = {};
if (DracoSolution.isDefined(item.left.sol)) {
_.extend(violationMap, item.left.sol.violations);
}
if (DracoSolution.isDefined(item.right.sol)) {
_.extend(violationMap, item.right.sol.violations);
}
return violationMap;
}
};
}
export type CollectionItemType = typeof CollectionItem.CHART | typeof CollectionItem.PAIR;
export class CollectionItemEval {
static PASS: 'pass' = 'pass';
static FAIL: 'fail' = 'fail';
static UNSAT: 'unsat' = 'unsat';
static fromBoolean(bool: boolean): CollectionItemEvalType {
switch (bool) {
case true:
return CollectionItemEval.PASS;
case false:
return CollectionItemEval.FAIL;
default:
return CollectionItemEval.UNSAT;
}
}
static toScore(itemEval: CollectionItemEvalType): number {
switch (itemEval) {
case CollectionItemEval.PASS:
return 1;
case undefined:
case CollectionItemEval.FAIL:
case CollectionItemEval.UNSAT:
return 0;
}
}
static toColor(itemEval: CollectionItemEvalType): string {
switch (itemEval) {
case undefined:
return CollectionItemEval.WHITE;
case CollectionItemEval.PASS:
return CollectionItemEval.GREEN;
case CollectionItemEval.FAIL:
return CollectionItemEval.RED;
case CollectionItemEval.UNSAT:
return CollectionItemEval.GREY;
default:
return CollectionItemEval.WHITE;
}
}
static BLUE = '#75a8f9';
static RED = '#f97486';
static WHITE = '#fff';
static GREEN = '#aff7b3';
static ORANGE = '#ffcd51';
static LIGHTBLUE = '#eaf4ff';
static GREY = '#d8d8d8';
}
export type CollectionItemEvalType =
| typeof CollectionItemEval.PASS
| typeof CollectionItemEval.FAIL
| typeof CollectionItemEval.UNSAT;
export class CollectionItemComparator {
static LESS_THAN: '<' = '<';
static LESS_THAN_OR_EQUAL: '<=' = '<=';
static EQUAL: '=' = '=';
}
export type CollectionItemComparatorType =
| typeof CollectionItemComparator.LESS_THAN
| typeof CollectionItemComparator.LESS_THAN_OR_EQUAL
| typeof CollectionItemComparator.EQUAL;
|
f0884c370052047e828e30b2e1e208732bb65205
|
TypeScript
|
KonstantinKliukach/js-warm-up
|
/passwordValidation.ts
| 3.484375
| 3
|
/*
You need to write regex that will validate a password to make sure it meets the following criteria:
At least six characters long
contains a lowercase letter
contains an uppercase letter
contains a number
Valid passwords will only be alphanumeric characters.
*/
function validate(password: string) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{6,})(^\w+$)/.test(password);
}
|
3a28f620348e1afe3761c02cb200b5d55e7b53f3
|
TypeScript
|
minimizelab/sincerewines
|
/www/src/utils/functions.ts
| 3.375
| 3
|
import { WineType } from '../types/types';
export const wineType = (type: WineType): string | null => {
if (type === 'Red') return 'RÖDA VINER';
if (type === 'White') return 'VITA VINER';
if (type === 'Rose') return 'ROSÉVINER';
return null;
};
export const createArrayString = (array: Array<string>): string => {
if (array.length <= 1) {
return array[0];
} else {
let names = '';
array.forEach((item, i, arr) => {
if (arr.length - 1 === i) {
names = names + item;
} else {
names = names + item + ', ';
}
});
return names;
}
};
const addClassName = (classNames: string, newClassName: string): string =>
classNames.length ? classNames.concat(' ', newClassName) : newClassName;
export const combineClasses = (
classNames: Array<string | undefined | { [key: string]: boolean | undefined }>
): string => {
let result = '';
classNames.forEach((item) => {
switch (typeof item) {
case 'string':
if (item.length > 0) result = addClassName(result, item);
break;
case 'object':
Object.entries(item).forEach(([key, val]) => {
if (val && key.length > 0) {
result = addClassName(result, key);
}
});
break;
default:
break;
}
});
return result;
};
|
da97436caf2f2e479e955e2343a45ca33589dbb4
|
TypeScript
|
aws/jsii
|
/packages/jsii/test/negatives/neg.implementation-changes-types.3.ts
| 3.1875
| 3
|
export class Superclass {}
export class Subclass extends Superclass {}
export interface ISomething {
takeSomething(argument: Superclass): void;
}
export class Something implements ISomething {
public takeSomething(_argument: Subclass): void {
// Nothing
}
}
|
81d5755690a833bf1fe0c713132667ae7c59188b
|
TypeScript
|
willowv/aeronauts-test
|
/src/simulation/map/map.test.ts
| 3.015625
| 3
|
import { Dijkstras } from "./map";
let testMapAdjacency = [
[false, true, true, false], // start node is adjacent to 2 and 3
[true, false, false, true], // mid nodes are adjacent to start and end, but not eachother
[true, false, false, true],
[false, true, true, false],
]; // end node is adjacent to 2 and 3
test("Dijkstras Algorithm implementation", () => {
// Run dijkstra's on each node
let dijkstras0 = Dijkstras(testMapAdjacency, 0);
expect(dijkstras0.distances).toEqual([0, 1, 1, 2]);
expect(dijkstras0.nextStepToward).toEqual([-1, 1, 2, 1]);
let dijkstras1 = Dijkstras(testMapAdjacency, 1);
expect(dijkstras1.distances).toEqual([1, 0, 2, 1]);
expect(dijkstras1.nextStepToward).toEqual([0, -1, 0, 3]);
let dijkstras2 = Dijkstras(testMapAdjacency, 2);
expect(dijkstras2.distances).toEqual([1, 2, 0, 1]);
expect(dijkstras2.nextStepToward).toEqual([0, 0, -1, 3]);
let dijkstras3 = Dijkstras(testMapAdjacency, 3);
expect(dijkstras3.distances).toEqual([2, 1, 1, 0]);
expect(dijkstras3.nextStepToward).toEqual([1, 1, 2, -1]);
});
|
d72ded4ee9a5112a2e33b282379a762d9a52c00e
|
TypeScript
|
abdukhashimov/simple-todo-backend
|
/src/controllers/TodoGroupController.ts
| 2.5625
| 3
|
import { Request, Response, NextFunction } from 'express'
import { IRequest } from '../lib/Request'
import TodoGroup, { ITodoGroup } from '../models/TodoGroup'
import { ApiResponse } from '../lib/ApiResponse'
import { isValidObjectId } from 'mongoose'
export default class {
async create(req: IRequest, res: Response, next: NextFunction) {
try {
const toDoName: string = req.body.name
const userId = req.session.user._id
const existingName = await TodoGroup.findOne({
author: userId,
name: toDoName,
})
if (existingName) {
return new ApiResponse(res).error(400, 'TODO_GROUP_EXIST')
}
const toDoGroup: { name: string; author: string } = {
name: req.body.name,
author: req.session.user._id,
}
const savedToDoGroup: ITodoGroup = await TodoGroup.create(toDoGroup)
return new ApiResponse(res).success(savedToDoGroup)
} catch (e) {
return new ApiResponse(res).error(500, 'SERVER_ERROR')
}
}
async getAll(req: IRequest, res: Response, next: NextFunction) {
try {
const allToDoGroups = await TodoGroup.find({
author: req.session.user._id,
})
return new ApiResponse(res).success(allToDoGroups)
} catch (e) {
return new ApiResponse(res).error(500, 'SERVER_ERROR')
}
}
async getOne(req: IRequest, res: Response, next: NextFunction) {
try {
const toDoGroup = await TodoGroup.findById(req.params.id).populate(
'todos'
)
return new ApiResponse(res).success(toDoGroup)
} catch (e) {
return new ApiResponse(res).error(500, 'SERVER_ERROR')
}
}
async delete(req: IRequest, res: Response, next: NextFunction) {
try {
const todoGroup = await TodoGroup.findByIdAndDelete(req.params.id)
if (!todoGroup) {
return new ApiResponse(res).error(
404,
`Object not found with id of ${req.params.id}`
)
}
return new ApiResponse(res).success(todoGroup)
} catch (e) {
new ApiResponse(res).error(500, 'SERVER_ERROR')
throw new Error(`Delete TODOGroups error: ${e}`)
}
}
async update(req: IRequest, res: Response) {
try {
const todoGroup = await TodoGroup.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true,
}
)
if (!todoGroup) {
return new ApiResponse(res).error(404, 'TODO_GROUP_NOT_FOUND')
}
return new ApiResponse(res).success(todoGroup)
} catch (e) {
new ApiResponse(res).error(500, 'SERVER_ERROR')
throw new Error(`Update TODOGroups error: ${e}`)
}
}
}
|
5a550ba6ea0602ba5e1722bb4fa5f7ced632a0a1
|
TypeScript
|
isoundy000/BehaviourTree-ai
|
/source/src/behaviourTree/decorators/Decorator.ts
| 2.65625
| 3
|
module behaviourTree {
export abstract class Decorator<T> extends Behavior<T>{
public child!: Behavior<T>;
public invalidate(){
super.invalidate();
this.child.invalidate();
}
}
}
|
71ef7ac95f7480a9538e02b8096aaa707a77c462
|
TypeScript
|
abhishekkanal1805/Jen
|
/services/utilities/timingUtility.ts
| 2.765625
| 3
|
/*!
* Copyright © 2019 Deloitte. All rights reserved.
*/
import * as log from "lambda-log";
import * as moment from "moment";
import { Constants } from "../../common/constants/constants";
import { errorCodeMap } from "../../common/constants/error-codes-map";
import * as config from "../../common/objects/config";
import { BadRequestResult } from "../../common/objects/custom-errors";
export class TimingUtility {
/**
* Generated start date for generation of activities
* @param requestStart
* @param repeat
* @param previousEndDate
*/
public static calculateStartDate(requestStartDate, requestEndDate, repeat) {
log.info("Entering TimingUtility.calculateStartDate()");
let dateArray = [];
let offsetString;
let boundsPeriodPresent = false;
try {
if (repeat && repeat.boundsPeriod && repeat.boundsPeriod.start) {
boundsPeriodPresent = true;
offsetString = this.getOffsetString(repeat.boundsPeriod.start);
dateArray.push(repeat.boundsPeriod.start);
}
if (requestStartDate) {
if (offsetString) {
requestStartDate = this.formatDate(requestStartDate, offsetString);
}
dateArray.push(requestStartDate);
}
// sort end dates
dateArray = dateArray.sort((dateOne, dateTwo) => moment(dateOne).diff(dateTwo)).filter(Boolean);
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
if (requestStartDate && boundsPeriodPresent) {
log.info("start date calculated as :: " + dateArray[dateArray.length - 1]);
return dateArray[dateArray.length - 1];
} else {
log.info("start date calculated as :: " + dateArray[0]);
return dateArray[0];
}
}
/**
* Returns offset in string format of the given date
* @param date
* @param offsetString
*/
public static getOffsetString(date) {
log.info("Entering TimingUtility.getOffsetString()");
let offsetString;
const offset = moment.parseZone(date).utcOffset();
if (moment(date, Constants.DATE_TIME, true).isValid()) {
if (offset != 0) {
offsetString = moment(date)
.utcOffset(offset)
.format(Constants.TIMEZONE_FORMAT);
} else {
offsetString = Constants.TIMEZONE_FORMAT;
}
} else if (moment(date, Constants.DATE_TIME_ONLY, true).isValid()) {
offsetString = " ";
}
log.info("Exiting TimingUtility.getOffsetString()");
return offsetString;
}
/**
* this function adds offsetString to the inputDate
* @param inputDate
* @param offsetString
* @returns dateString
*/
public static formatDate(inputDate, offsetString) {
log.info("Entering TimingUtility.formatDate()");
const offset = moment.parseZone(inputDate).utcOffset();
offsetString = offsetString.trim();
// if date contains only date then don't need to format the date
if (!moment(inputDate, Constants.DATE, true).isValid()) {
// format date with no timezone and then append the offsetString at the end of the date
inputDate = moment
.utc(inputDate)
.utcOffset(offset)
.format(Constants.DATE_TIME_ONLY);
inputDate = inputDate.concat(offsetString);
}
log.info("Exiting TimingUtility.formatDate()");
return inputDate;
}
/**
* Generates end date for activity generation
* @param startDate
* @param endDate
* @param repeat
* @param code
*/
public static calculateEndDate(startDate, endDate, repeat, code) {
log.info("Entering TimingUtility.calculateEndDate()");
let dateArray = [];
try {
if (endDate) {
dateArray.push(endDate);
}
if (repeat) {
if (repeat.boundsPeriod && repeat.boundsPeriod.end) {
dateArray.push(repeat.boundsPeriod.end);
}
if (repeat.boundsDuration && repeat.boundsDuration.value) {
const boundsDurationValue = repeat.boundsDuration.value;
const boundsDurationCode = repeat.boundsDuration.code;
dateArray.push(TimingUtility.getEndDateForCode(startDate, boundsDurationValue, boundsDurationCode));
}
}
if (code && repeat && repeat.count) {
switch (code) {
case "SDY":
dateArray.push(TimingUtility.getEndDateForCode(startDate, repeat.count, Constants.FHIR_DAY_UNIT));
break;
case "SDT":
break;
case "SDC":
dateArray.push(TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.duration, repeat.durationUnit));
break;
case "SDW":
dateArray.push(TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.period, repeat.periodUnit));
break;
case "SID":
dateArray.push(TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.period, repeat.periodUnit));
break;
case "NA":
const date = TimingUtility.calculateEndDateForCustomCode(repeat, startDate);
if (date) {
dateArray.push(date);
}
}
}
// sort date array
dateArray = dateArray.sort((dateOne, dateTwo) => moment(dateOne).diff(dateTwo)).filter(Boolean);
log.info("End date calculated as :: " + dateArray[0]);
log.info("Exiting TimingUtility.calculateEndDate()");
return dateArray[0];
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
/**
* Generates end date for activity generation
* @param startDate
* @param requestEnd
* @param repeat
* @param code
*/
public static calculateEndDateForCustomCode(repeat, startDate) {
log.info("Entering TimingUtility.calculateEndDateForCustomCode()");
let date;
try {
if (repeat.dayOfWeek) {
if (repeat.period && repeat.periodUnit) {
date = TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.period, repeat.periodUnit);
}
} else if (repeat.dayOfCycle) {
if (Constants.ALLOWED_DURATION_UNITS.includes(repeat.durationUnit)) {
date = TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.duration, repeat.durationUnit);
}
} else {
if (repeat.period && repeat.periodUnit) {
date = TimingUtility.getEndDateForCode(startDate, repeat.count * repeat.period, repeat.periodUnit);
}
}
log.info("Exiting TimingUtility.calculateEndDateForCustomCode()");
return date;
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
/**
* this function adds specified duration to the given date using moment library
* @param date
* @param period
* @param periodUnit
* @returns date
*/
public static getEndDateForCode(inputDate, period, fhirPeriodUnit) {
log.info("Entering TimingUtility.getEndDateForCode()");
let date;
try {
const offset = moment.parseZone(inputDate).utcOffset();
const periodUnit = config.unitsMap[fhirPeriodUnit];
const endOfDayTime: any = Constants.ALLOWED_UNITS.includes(fhirPeriodUnit) ? Constants.EMPTY_VALUE : Constants.DAY;
const unit = Constants.DURATION_UNITS.includes(fhirPeriodUnit) ? periodUnit : Constants.DAYS;
const dateFormat = moment(inputDate, Constants.DATE_TIME, true).isValid() ? Constants.DATE_TIME : Constants.DATE;
if (offset == 0) {
// while adding period, moment adds period from next periodUnit value so subtract one periodUnit value
date = moment
.utc(inputDate)
.add(period, periodUnit)
.subtract(1, unit)
.endOf(endOfDayTime);
// if start date contains only date and time then format date according to that only
if (moment(inputDate, Constants.DATE_TIME_ONLY, true).isValid()) {
date = date.format(Constants.DATE_TIME_ONLY);
} else {
// if format is of date only then format the date other wise return ISO string
date = dateFormat === Constants.DATE ? date.format(dateFormat) : date.toISOString();
}
} else {
date = moment
.utc(inputDate)
.add(period, periodUnit)
.subtract(1, unit) // while adding period, moment adds period from next periodUnit value so subtract one periodUnit value
.endOf(endOfDayTime)
.utcOffset(offset)
.format(Constants.DATE_TIME);
}
log.info("Exiting TimingUtility.getEndDateForCode()");
return date;
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
/**
* this function adds specified duration to the given date using moment library
* @param date
* @param period
* @param periodUnit
* @returns date
*/
public static addMomentDuration(inputDate, period, fhirPeriodUnit) {
log.info("Entering TimingUtility.addMomentDuration()");
let date;
try {
const offset = moment.parseZone(inputDate).utcOffset();
const periodUnit = config.unitsMap[fhirPeriodUnit];
const dateFormat = moment(inputDate, Constants.DATE_TIME, true).isValid() ? Constants.DATE_TIME : Constants.DATE;
if (offset == 0) {
// while adding period, moment adds period from next periodUnit value so subtract one periodUnit value
date = moment.utc(inputDate).add(period, periodUnit);
// if start date contains only date and time then format date according to that only
if (moment(inputDate, Constants.DATE_TIME_ONLY, true).isValid()) {
date = date.format(Constants.DATE_TIME_ONLY);
} else {
// if format is of date only then format the date other wise return ISO string
date = dateFormat === Constants.DATE ? date.format(dateFormat) : date.toISOString();
}
} else {
date = moment
.utc(inputDate)
.add(period, periodUnit)
.utcOffset(offset)
.format(Constants.DATE_TIME);
}
log.info("Exiting TimingUtility.addMomentDuration()");
return date;
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
/**
* This function checks if start date is there and returns the same else it returns current date as a start date
* @param start
* @returns start
*/
public static getStartDate(start) {
log.info("Entering TimingUtility.getStartDate()");
if (!start) {
start = moment
.utc()
.utcOffset(0)
.toISOString();
}
log.info("Exiting TimingUtility.getStartDate()");
return start;
}
/**
* This function checks if end date is there and returns the same else it constructs end date as start date + 365 days
* @param start
* @param end
* @returns end
*/
public static getEndDate(start, end) {
log.info("Entering TimingUtility.getEndDate()");
try {
const offset = moment.parseZone(start).utcOffset();
if (!end) {
if (offset == 0) {
// offset zero means start date is a zulu date and end date needs to have same offset as of start dare
end = moment
.utc(start)
.endOf(Constants.DAY)
.add(1, Constants.YEARS)
.utcOffset(offset);
// if start contains only date and time then format end according to that only
if (moment(start, Constants.DATE_TIME_ONLY, true).isValid()) {
end = end.format(Constants.DATE_TIME_ONLY);
} else {
end = end.toISOString();
}
} else {
// start date is utc date and end date needs to have same offset as of start date
end = moment
.utc(start)
.endOf(Constants.DAY)
.add(1, Constants.YEARS)
.utcOffset(offset)
.format(Constants.DATE_TIME);
}
}
log.info("Exiting TimingUtility.getEndDate()");
return end;
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
/**
* This function formats given date
* @param endDate
* @returns endDate
*/
public static formatEndDate(endDate) {
log.info("Entering TimingUtility.formatEndDate()");
const offset = moment.parseZone(endDate).utcOffset();
if (moment(endDate, Constants.DATE, true).isValid()) {
log.info("end Date Format is : " + Constants.DATE);
endDate = moment
.utc(endDate)
.endOf(Constants.DAY)
.utcOffset(offset)
.toISOString();
}
log.info("Exiting TimingUtility.formatEndDate()");
return endDate;
}
/**
* This function generates date based on given input parameters using moment library.
* @param start
* @param timeOfDay
* @param dayOfWeek
* @param period
* @param periodUnit
* @param startOfDay
* @param endOfDay
* @param dateFormat
* @param count
* @param offset
* @returns date
*/
public static generateDate(start, timeOfDay, dayOfWeek, period, periodUnit, startOfDay, endOfDay, dateFormat, count, offset) {
log.info("Entering TimingUtility.generateDate()");
let date;
try {
if (offset == 0) {
date = moment
.utc(start)
.add(count * period, periodUnit)
.startOf(startOfDay)
.endOf(endOfDay)
.day(dayOfWeek)
.add(moment.duration(timeOfDay));
// if start date contains only date and time then format date according to that only
if (moment(start, Constants.DATE_TIME_ONLY, true).isValid()) {
date = date.format(Constants.DATE_TIME_ONLY);
} else {
// if format is of date only then format the date other wise return ISO string
date = dateFormat === Constants.DATE ? date.format(dateFormat) : date.toISOString();
}
} else {
date = moment
.utc(start)
.utcOffset(offset)
.add(count * period, periodUnit)
.startOf(startOfDay)
.endOf(endOfDay)
.day(dayOfWeek)
.add(moment.duration(timeOfDay))
.format(dateFormat);
}
// log.info("Generated Date : " + date);
log.info("Exiting TimingUtility.generateDate()");
return date;
} catch (err) {
throw new BadRequestResult(errorCodeMap.OperationFailed.value, errorCodeMap.OperationFailed.description);
}
}
}
|
1f6b026bcaacf0d512c742c4e6a28a754a7364eb
|
TypeScript
|
paulreitz/gw2-craft-angular
|
/src/app/models/node.model.ts
| 2.8125
| 3
|
import { ItemModel } from './item.model';
import { RecipeModel } from './recipe.model';
export class NodeModel {
item_id: number;
children: Array<NodeModel>;
id: string;
item: ItemModel;
constructor(item_id: number) {
this.item_id = item_id;
this.id = (parseInt(Math.random() * Math.pow(2, 34) + "" + 10)).toString(36).toUpperCase();
}
getItem(): ItemModel {
return this.item;
}
setChildren(recipe: RecipeModel): void {
this.item = recipe.items["item_" + this.item_id.toString(10)];
this.item.name = this.item.name.replace("‘", "'");
var node: {id: number, children?: Array<{item_id: number, count: number}>} = recipe.nodes["node_" + this.item_id.toString(10)];
this.children = [];
if (node.children) {
node.children.forEach(child => {
for (var i = 0; i < child.count; i++) {
var childNode: NodeModel = new NodeModel(child.item_id);
childNode.setChildren(recipe);
this.children.push(childNode);
}
});
}
}
getBaseMaterials(items: {[key: string]: {item: ItemModel, count: number}}) {
if (this.children && this.children.length) {
this.children.forEach(child => { child.getBaseMaterials(items);});
}
else {
if (items["item_" + this.item_id.toString(10)]) {
var count = items["item_" + this.item_id.toString(10)].count;
count++;
items["item_" + this.item_id.toString(10)].count = count;
}
else {
items["item_" + this.item_id.toString(10)] = {item: this.item, count: 1};
}
}
}
getDetails(parent?: string): any {
var data: {id: string, item: ItemModel, width: number, parent?: string, children?: Array<any>} =
{
id: this.id,
item: this.item,
width: this.item.name.replace("‘", "'").length * 8 + 40
}
if (parent) {
data.parent = parent;
}
if (this.children && this.children.length) {
data.children = [];
this.children.forEach(child => {
data.children.push(child.getDetails(this.id));
})
}
return data;
}
getDepth(): number {
var count = 1;
if (this.children && this.children.length) {
var innerCount:number = 0;
this.children.forEach(child => {
var i = child.getDepth();
if (i > innerCount) {
innerCount = i;
}
});
count += innerCount;
}
return count;
}
getBreadth(): number {
var base: {[key:string]: {item: ItemModel, count: number}} = {};
this.getBaseMaterials(base);
var count:number = 0;
for (var key in base) {
count += base[key].count;
}
return count;
}
}
|
5512ae46ec2b5198d17c96377e2e1665e60cca12
|
TypeScript
|
CanadianCommander/rbtgen
|
/client/src/lib/report/sql/NodeOutputSqlGenerator.ts
| 2.75
| 3
|
import NodeOutput from "@/lib/report/reportModel/NodeOutput";
import {FieldType} from "@/lib/report/databaseModel/FieldType";
import ReportNode from "@/lib/report/reportModel/ReportNode";
import TemplateUtil from "@/lib/report/sql/TemplateUtil";
import ReportQueryService from "@/lib/report/ReportQueryService";
export default class NodeOutputSqlGenerator
{
// ==========================================================
// Public class methods
// ==========================================================
/**
* generate sql for the given node output.
* @param nodeOutput
* @param atRoot - is this sql being generated for the root node or not?
* @param reportNode - the report node of this node output
*/
public static generateSql(nodeOutput: NodeOutput, reportNode: ReportNode, atRoot = false): string
{
let fieldSql: string = this.generateFieldSql(nodeOutput, reportNode);
if (nodeOutput.aggregator && reportNode.groupOutputs)
{
fieldSql = nodeOutput.aggregator.toSql(fieldSql);
}
fieldSql = this.applyPrefixSuffix(fieldSql, nodeOutput);
if (atRoot && nodeOutput.alias)
{
fieldSql = this.applyAlias(fieldSql, nodeOutput);
}
else if (nodeOutput.aggregator && reportNode.groupOutputs)
{
// if we aggregate we must preserve the field name
fieldSql += ` AS ${nodeOutput.name}`;
}
return fieldSql;
}
/**
* generate sql for the field of this node output. This excludes aggregation, suffix, prefix, alias ... ect
* @param nodeOutput
* @param reportNode - the report node of this node output
* @protected
*/
public static generateFieldSql(nodeOutput: NodeOutput, reportNode: ReportNode): string
{
if (nodeOutput.type === FieldType.CUSTOM)
{
return TemplateUtil.replaceColumnTags(nodeOutput.field.customSql, reportNode);
}
if (nodeOutput.entity === reportNode.entity)
{
return `${reportNode.transientId}.${nodeOutput.field.name}`;
}
else
{
const reportQueryService = new ReportQueryService();
const closestNode = reportQueryService.getClosestNodeByName(nodeOutput.entity.name, reportNode);
return `${closestNode.transientId}.${nodeOutput.field.name}`;
}
}
// ==========================================================
// Protected class methods
// ==========================================================
/**
* apply a suffix and prefix to the provided sql if applicable
* @param sql - sql to transform
* @param nodeOutput - the node output for this sql
* @protected
*/
protected static applyPrefixSuffix(sql: string, nodeOutput: NodeOutput): string
{
if (nodeOutput.staticPrefix)
{
sql = `CONCAT( '${nodeOutput.staticPrefix}', (${sql}))`;
}
if (nodeOutput.staticSuffix)
{
sql = `CONCAT((${sql}), '${nodeOutput.staticSuffix}')`;
}
return sql;
}
/**
* apply a suffix to the provided sql if applicable
* @param sql - sql to transform
* @param nodeOutput - the node output for this sql
* @protected
*/
protected static applyAlias(sql: string, nodeOutput: NodeOutput): string
{
if (nodeOutput.alias)
{
sql = `${sql} AS '${nodeOutput.alias}'`;
}
return sql;
}
}
|
bed91cad141b81f3741ea9d5ec7d8dd6d26f6ded
|
TypeScript
|
magland/sortingview-gui
|
/src/plugins/sortingview/gui/extensions/timeseries/TimeseriesViewNew/Mda.ts
| 3.1875
| 3
|
class Mda {
_N1: number = 1
_N2: number = 1
_N3: number = 1
_N4: number = 1
_N5: number = 1
_totalSize: number = 1
_data: Float32Array | Float64Array | Int16Array = new Float32Array(1)
constructor(n1?: number, n2?: number, n3?: number, n4?: number, n5?: number) {
this.allocate(n1 || 1, n2 || 1, n3, n4, n5)
}
allocate(n1: number, n2: number, n3?: number, n4?: number, n5?: number): void {
this._N1 = n1 || 1
this._N2 = n2 || 1
this._N3 = n3 || 1
this._N4 = n4 || 1
this._N5 = n5 || 1
this._totalSize = this._N1 * this._N2 * this._N3 * this._N4 * this._N5
this._data = new Float32Array(this._totalSize)
this._data.fill(0)
}
N1(): number {return this._N1}
N2(): number {return this._N2}
N3(): number {return this._N3}
N4(): number {return this._N4}
N5(): number {return this._N5}
totalSize(): number {return this._totalSize}
value(i1: number, i2?: number, i3?: number, i4?: number, i5?: number): number {
if (i2 === undefined) {
return this._data[i1]
}
else if (i3 === undefined) {
return this._data[i1 + this._N1 * i2]
}
else if (i4 === undefined) {
return this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3]
}
else if (i5 === undefined) {
return this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3 + this._N1 * this._N2 * this._N3 * i4]
}
else {
return this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3 + this._N1 * this._N2 * this._N3 * i4 + this._N1 * this._N2 * this._N3 * this._N4 * i5]
}
}
setValue(val: number, i1: number, i2: number, i3?: number, i4?: number, i5?: number): void {
if (i2 === undefined) {
this._data[i1] = val
}
else if (i3 === undefined) {
this._data[i1 + this._N1 * i2] = val
}
else if (i4 === undefined) {
this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3] = val
}
else if (i5 === undefined) {
this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3 + this._N1 * this._N2 * this._N3 * i4] = val
}
else {
this._data[i1 + this._N1 * i2 + this._N1 * this._N2 * i3 + this._N1 * this._N2 * this._N3 * i4 + this._N1 * this._N2 * this._N3 * this._N4 * i5] = val
}
}
data(): Float32Array | Float64Array | Int16Array {
return this._data
}
dataCopy(): Float32Array | Float64Array | Int16Array {
return this._data.slice()
}
setData(d: Float32Array | Float64Array | Int16Array): void {
this._data = d
}
clone(): Mda {
var ret = new Mda(this._N1, this._N2, this._N3, this._N4, this._N5)
ret.setData(this.dataCopy())
return ret
}
reshape(n1: number, n2: number, n3?: number, n4?: number, n5?: number): void {
n2 = n2 || 1; n3 = n3 || 1; n4 = n4 || 1; n5 = n5 || 1
var tot = n1 * n2 * n3 * n4 * n5
if (tot !== this._totalSize) {
throw Error('Unable to reshape... incompatible size: ' + n1 + 'x' + n2 + 'x' + n3 + 'x' + n4 + 'x' + n5 + ' ' + this.N1() + 'x' + this.N2() + 'x' + this.N3() + 'x' + this.N4() + 'x' + this.N5())
}
this._N1 = n1
this._N2 = n2
this._N3 = n3
this._N4 = n4
this._N5 = n5
}
getChunk(i: number, size: number): Mda {
var ret = new Mda(size, 1)
ret.setData(this._data.subarray(i, i + size))
return ret
}
subArray(arg1: number, arg2: number, arg3?: number, arg4?: number, arg5?: number, arg6?: number): Mda {
let iii, sss, ret
if (arg3 === undefined) {
return this.getChunk(arg1, arg2)
}
else if (arg5 === undefined) {
if (arg4 === undefined) throw Error('Unexpected')
if ((arg3 !== this.N1()) || (arg1 !== 0)) {
throw Error('This case not supported yet: subArray.');
}
iii = arg2 * this.N1()
sss = arg4 * this.N1()
ret = this.getChunk(iii, sss)
ret.reshape(arg3, arg4)
return ret
}
else {
if (arg6 === undefined) throw Error('Unexpected')
if ((arg4 !== this.N1()) || (arg1 !== 0)) {
throw Error('This case not supported yet: subArray.');
}
if ((arg5 !== this.N2()) || (arg2 !== 0)) {
throw Error('This case not supported yet: subArray.');
}
iii = arg3 * this.N1() * this.N2()
sss = arg6 * this.N1() * this.N2()
ret = this.getChunk(iii, sss)
ret.reshape(arg4, arg5, arg6)
return ret
}
}
setFromArrayBuffer(buf: ArrayBuffer): void {
var X = new Int32Array(buf.slice(0, 64))
// var num_bytes_per_entry = X[1];
var num_dims = X[2]
let dims: number[] = []
if ((num_dims < 1) || (num_dims > 5)) {
throw Error('Invalid number of dimensions: ' + num_dims);
}
for (var i = 0; i < num_dims; i++) {
dims.push(X[3 + i])
}
var dtype = get_dtype_string(X[0])
var header_size = (num_dims + 3) * 4;
if (dtype === 'float32') {
const data = new Float32Array(buf.slice(header_size))
this.allocate(dims[0], dims[1], dims[2], dims[3], dims[4])
this.setData(data)
return
}
else if (dtype === 'float64') {
const data = new Float64Array(buf.slice(header_size))
this.allocate(dims[0], dims[1], dims[2], dims[3], dims[4])
this.setData(data)
return
}
else if (dtype === 'int16') {
const data = new Int16Array(buf.slice(header_size))
this.allocate(dims[0], dims[1], dims[2], dims[3], dims[4])
this.setData(data)
return
}
else {
throw Error('Unsupported dtype: ' + dtype)
}
}
setFromBase64(x: string): void {
this.setFromArrayBuffer(_base64ToArrayBuffer(x));
}
minimum(): number {
if (this._data.length === 0) return 0
var ret = this._data[0]
for (let i = 0; i < this._data.length; i++) {
if (this._data[i] < ret) ret = this._data[i]
}
return ret
}
maximum(): number {
if (this._data.length === 0) return 0
var ret = this._data[0]
for (let i = 0; i < this._data.length; i++) {
if (this._data[i] > ret) ret = this._data[i]
}
return ret
}
toList(): number[] {
let A: number[] = []
for (let a of this._data) A.push(a);
return A
}
}
function get_dtype_string(num: number): string {
if (num === -2) return 'byte'
if (num === -3) return 'float32'
if (num === -4) return 'int16'
if (num === -5) return 'int32'
if (num === -6) return 'uint16'
if (num === -7) return 'float64'
return ''
}
function _base64ToArrayBuffer(base64: string): ArrayBuffer {
var binary_string = window.atob(base64)
var len = binary_string.length
var bytes = new Uint8Array(len)
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i)
}
return bytes.buffer
}
export default Mda
|
0dde316defebc56d7f9bf51cbf956132a9f49cb6
|
TypeScript
|
antvis/G2Plot
|
/__tests__/unit/plots/rose/pattern-spec.ts
| 2.515625
| 3
|
import { Rose } from '../../../../src';
import { salesByArea } from '../../../data/sales';
import { createDiv } from '../../../utils/dom';
describe('rose: pattern', () => {
const rose = new Rose(createDiv(), {
width: 400,
height: 300,
data: salesByArea,
xField: 'area',
yField: 'sales',
meta: {
sales: {
nice: true,
formatter: (v) => `${Math.floor(v / 10000)}万`,
},
},
});
rose.render();
it('pattern: obj', () => {
rose.update({
pattern: {
type: 'line',
},
});
const geometry = rose.chart.geometries[0];
const elements = geometry.elements;
expect(elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
expect(elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
expect(elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
rose.update({
pattern: null,
});
expect(rose.chart.geometries[0].elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
expect(rose.chart.geometries[0].elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
expect(rose.chart.geometries[0].elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
});
it('pattern: callback', () => {
rose.update({
pattern: ({ area }) => {
if (area === '中南') {
return { type: 'dot' };
}
},
});
expect(rose.chart.geometries[0].elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
expect(rose.chart.geometries[0].elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
expect(rose.chart.geometries[0].elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
});
afterAll(() => {
rose.destroy();
});
});
|
98536fabc7c77a017139cb3ab4156bcbf4b23e49
|
TypeScript
|
faverill/attendApp
|
/ClientApp/app/components/courses/courses.service.ts
| 2.515625
| 3
|
// import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Course } from './course.model';
import { ActivatedRoute, Router } from '@angular/router';
import { OnInit } from '@angular/core';
export class CoursesService {
coursesChanged = new Subject<Course[]>();
myCourse: Course;
courses: Course[] = [new Course(1001, 'Alegbra I', 'Mike Smith',
'http://static6.businessinsider.com/image/553e63c6ecad04144fe9d417/9-science-backed-ways-men-can-appear-more-attractive-to-women.jpg',
'This class will teach you how to solve simple linear equations', new Date),
new Course(2002, 'Alegbra II', 'Irina Shayk',
'http://www.wonderslist.com/wp-content/uploads/2015/10/Hottest-Russian-Girl-Irina-Shayk.jpg',
'This class will teach you how to solve more complicated equations', new Date)];
constructor() { }
getCourses() {
return this.courses.slice();
}
getCourse(id: number) {
return this.courses.find(x => x.id === id);
}
getNewId() {
let maxId = 0;
for (let c of this.courses) {
if ( c.id >= maxId ) {
maxId = c.id;
}
}
return maxId + 1;
}
addCourse(myCourse: Course) {
this.courses.push(myCourse);
this.coursesChanged.next(this.courses.slice());
}
updateCourse(id: number, newCourse: Course) {
let myCourse = this.courses.find(x => x.id === id);
// Find the index of myCourse in courses.
let index = 0;
for (let c of this.courses) {
if( c.id === myCourse.id) {
break;
}
index += 1;
}
// alert('in updateCourse with index = ' + index);
// console.log('courses.length = ' + this.courses.length);
if (index <= this.courses.length -1 ) {
this.courses[index] = newCourse;
this.coursesChanged.next(this.courses.slice());
//this.router.navigate(['courses']);
}
}
deleteCourse(myId: number) {
let index = 0;
for (let c of this.courses) {
if (c.id === myId) {
break;
}
index += 1;
}
this.courses.splice(index,1);
this.coursesChanged.next(this.courses.slice());
}
setCourses(courses: Course[]) {
this.courses = courses;
this.coursesChanged.next(this.courses.slice());
}
}
|
6a033e1f08ffd7a5348592cffb759fe555c29d68
|
TypeScript
|
story-ai/story-frontend-old
|
/src/strings/i18n.ts
| 2.71875
| 3
|
import { STRINGS } from "../config";
function replace(s: string, data: any[], i: number = 0): any[] {
if (i >= data.length) return [s];
const subs = s.split(`\${${i}}`).map(sub => replace(sub, data, i + 1));
const result = [subs[0]];
for (let subi = 1; subi < subs.length; subi++) {
result.push(data[i]);
result.push(subs[subi]);
}
return result.reduce((arr, v) => arr.concat(v), []);
}
export function i18n(strings: TemplateStringsArray, ...data: any[]) {
const keys = data.map((x, i) => `\${${i}}`);
const template = [].concat
.apply([], strings.map((s, i) => (i > 0 ? [`\${${i - 1}}`, s] : [s])))
.join("");
const newTemplate = STRINGS[template] || template;
return replace(newTemplate, data);
}
|
790a156e7317e96ac019dec76db8b3a6c712278c
|
TypeScript
|
EitanElbaz/json-2-yup
|
/src/tests/types/date/nullable.test.ts
| 2.890625
| 3
|
import { DateSchema, NumberSchema } from 'yup';
import { toYup } from 'src/toYup';
import { DateTypeSchema } from 'src/types';;
const schemaNullable: DateTypeSchema = {
type: 'date',
min: [''] as any, //purposely wrong for code coverage
max: [''] as any, //purposely wrong for code coverage
strict: true,
nullable: true,
};
const schemaNotNullable: DateTypeSchema = {
type: 'date',
strict: true,
nullable: false,
};
const yupNullableSchema = toYup(schemaNullable) as DateSchema;
const yupNotNullableSchema = toYup(schemaNotNullable) as DateSchema;
test('nullable expect fail', async () => {
expect(yupNullableSchema.isValidSync([])).toBe(false);
expect(yupNullableSchema.isValidSync({})).toBe(false);
expect(yupNullableSchema.isValidSync('2020-01-01')).toBe(false);
});
test('nullable expect pass', async () => {
expect(yupNullableSchema.isValidSync(new Date('2020-01-01'))).toBe(true);
expect(yupNullableSchema.isValidSync(null)).toBe(true);
expect(yupNullableSchema.isValidSync(undefined)).toBe(true);
});
test('not nullable expect fail', async () => {
expect(yupNotNullableSchema.isValidSync(null)).toBe(false);
expect(yupNotNullableSchema.isValidSync([])).toBe(false);
expect(yupNotNullableSchema.isValidSync({})).toBe(false);
expect(yupNotNullableSchema.isValidSync('2020-01-01')).toBe(false);
});
test('not nullable expect pass', async () => {
expect(yupNotNullableSchema.isValidSync(new Date('2020-01-01'))).toBe(true);
});
|
511c8ee7118e865ffdeb41fbed3d8e76f6e61a8b
|
TypeScript
|
ducin-public/itcorpo-angular-app
|
/src/app/api/employees.mock.ts
| 2.546875
| 3
|
import { Employee } from "./dto";
export const mockEmployees: Employee[] = [{
id: 1,
nationality: 'US',
departmentId: 2,
keycardId: 'ABC123',
account: '123456789',
salary: 100000,
office: ['San Francisco', 'United States of America'],
firstName: 'John',
lastName: 'Doe',
title: 'Software Engineer',
contractType: 'contract',
email: 'john.doe@example.com',
hiredAt: '2022-01-01',
expiresAt: '2023-01-01',
personalInfo: {
age: 30,
phone: '123-456-7890',
email: 'john.doe@example.com',
dateOfBirth: '1992-01-01',
address: {
street: '123 Main St',
city: 'Anytown',
country: 'USA',
},
},
skills: ['JavaScript', 'Angular', 'Node.js'],
bio: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
imgURL: 'https://example.com/image.jpg',
}];
|
eae7c53b0a521676a2186be5a61f412153ca59df
|
TypeScript
|
Motke84/Experimental-Twitter
|
/FrontEnd/app/Infra/Pipes/summary.pipe.ts
| 2.703125
| 3
|
import { Pipe, PipeTransform } from '@angular/core'
@Pipe({
name: 'summery'
})
export class SummaryPipe implements PipeTransform {
endSummary = "...";
delemiter = " ";
transform(value: string, args: string[]): string {
if (value) {
var wordsCount = args && args.length > 0 ?
wordsCount = parseInt(args[0]) : 10;
var words = value.split(this.delemiter);
var sentence = " ";
if (words.length <= wordsCount)
return value;
for (var i = 0; i < wordsCount; i++) {
sentence = sentence.concat(words[i] + this.delemiter);
}
return sentence.concat(this.endSummary);
}
}
}
|
aaa3daa911ea729f9491dede427d510b3fe7fe4e
|
TypeScript
|
makstraw/Friday.TypeScript
|
/Friday.Base/Extensions/Array/LINQ/Methods/GroupBy.ts
| 3.09375
| 3
|
///<reference path="../../../../Collections/KeyValuePair.ts"/>
interface Array<T> {
GroupBy<TKey>(keySelector: SelectorWithIndex<T, TKey>): Array<Friday.Collections.KeyValuePair<TKey, Array<T>>>;
GroupBy<TKey>(keySelector: SelectorWithIndex<T, TKey>, elementSelector: SelectorWithIndex<T, T>, compareSelector?: HashSelector<TKey>): Array<Friday.Collections.KeyValuePair<TKey, Array<T>>>;
GroupBy<TKey, TElement>(keySelector: SelectorWithIndex<T, TKey>, elementSelector: SelectorWithIndex<T, TElement>, compareSelector?: HashSelector<TKey>): Array<Friday.Collections.KeyValuePair<TKey, Array<T>>>;
GroupBy<TKey, TElement>(keySelector: SelectorWithIndex<T, TKey> | Selector<T, TKey>, elementSelector?: SelectorWithIndex<T, TElement> | Selector<T, TElement>, compareSelector?: HashSelector<TKey>): Array<Friday.Collections.KeyValuePair<TKey, Array<T>>>;
}
Array.prototype.GroupBy = function (keySelector: SelectorWithIndex<any, any> | Selector<any, any>,
elementSelector?: SelectorWithIndex<any, any> | Selector<any, any>,
compareSelector?: HashSelector<any>): Array<Friday.Collections.KeyValuePair<any, any>> {
if (!elementSelector) elementSelector = (source, index) => source;
let output: Array<Friday.Collections.KeyValuePair<any, Array<any>>> = [];
this.forEach((x: any, i: any) => {
let key = (keySelector as SelectorWithIndex<any, any>)(x, i);
let element = (elementSelector as SelectorWithIndex<any, any>)(x, i);
let array = output.First(item => Friday.System.IsEquatable(item.Key) ? item.Key.Equals(key) : item.Key === key);
if (array !== null && array instanceof Friday.Collections.KeyValuePair && Array.isArray(array.Value)) array.Value.push(element);
else output.push(new Friday.Collections.KeyValuePair<any,Array<any>>(key, [element]));
});
return output;
}
|
60cf467c8f752ae23a57f3d3f220d3a8402eae6e
|
TypeScript
|
Wesleyss071299/FotonBooks
|
/server/src/schemas/User.ts
| 2.609375
| 3
|
import Mongoose, { Schema, model, Document } from 'mongoose'
interface UserInterface extends Document {
name: string
email: string
password:string,
}
const UserSchema = new Schema({
name: String,
email: String,
password: String,
}, {
timestamps: true
})
export default model<UserInterface>('User', UserSchema)
|
aa7b618b21d9b8d944cbf00e1c2edf1a6988d012
|
TypeScript
|
HugoMontes/curso-typescript
|
/07_herencia.ts
| 3.6875
| 4
|
// Crear la clase padre
class Padre{
// Atributos de clase
public nombre:string
public edad:number
// Constructor de clase
constructor(nombre:string, edad:number){
this.nombre = nombre
this.edad = edad
}
// Metodo de clase
mostrarDatosPadre():void{
console.log(`Nombre: ${this.nombre}`)
console.log(`Edad: ${this.edad}`)
}
}
// Crear la clase hijo que hereda de padre
class Hijo extends Padre{
// Atributos de clase
public apellido:string
// Constructor de clase hijo
constructor(nombre:string, edad:number, apellido:string){
// Llamar al constructor de la clase padre
super(nombre, edad)
this.apellido = apellido
}
// Metodo de la clase
mostrarDatosHijo():void {
this.mostrarDatosPadre();
console.log(`Apellido: ${this.apellido}`);
}
}
// Instanciar una clase
const hijo1 = new Hijo('Pedro', 22, 'Perez')
console.log(`Bienvenido ${hijo1.nombre}`);
hijo1.mostrarDatosHijo()
|
9c9af8fa070379772458a1785937f6b656fe4f26
|
TypeScript
|
jsfuentes/Next-Base
|
/src/utils/time.ts
| 2.890625
| 3
|
import * as Sentry from "@sentry/react";
const debug = require("debug")("app:utils:time");
export function secondsToString(secs: number): string {
const hours = Math.floor(secs / (60 * 60));
const divisor_for_minutes = secs % (60 * 60);
const minutes = Math.floor(divisor_for_minutes / 60);
let timeStr = "";
if (hours > 0) {
timeStr += `${hours} hour${hours === 1 ? "" : "s"}`;
}
if (minutes > 0) {
timeStr += timeStr === "" ? "" : " ";
timeStr += `${minutes} min${minutes === 1 ? "" : "s"}`;
}
return timeStr;
}
export function secondsToHighlyRoundedString(secs: number): string {
const days = Math.floor(secs / (3600 * 24));
const hours = Math.floor(secs / (60 * 60));
const divisor_for_minutes = secs % (60 * 60);
const minutes = Math.floor(divisor_for_minutes / 60);
if (days > 0) {
return `${days} day${days === 1 ? "" : "s"} ago`;
}
if (hours > 0) {
return `${hours} hour${hours === 1 ? "" : "s"} ago`;
}
if (minutes > 0) {
return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
}
if (secs > 10) {
return "less than a minute ago";
}
return "a few seconds ago";
}
// expects end_time and start_time and returns duration in seconds
// export function eventToDuration(
// event: SlingShowEvent | SlingShowSubevent | SlingShowFormEvent
// ): number {
// if (!event || !event.end_time || !event.start_time) {
// return -1;
// }
//
// return (+new Date(event.end_time) - +new Date(event.start_time)) / 1000;
// }
//weird sentry error for this girl in Taiwan - https://sentry.io/organizations/slingshow/issues/1938098845/events/cb98f25eee9d42ccab4d46b47938c528/?project=5265091
// EDT
export function getTimezone(): string {
try {
try {
const tz = new Date()
.toLocaleTimeString("en-us", { timeZoneName: "short" })
.split(" ")[2];
return tz;
} catch (err) {
console.error(
"Date:",
new Date(),
new Date().toLocaleTimeString("en-us", { timeZoneName: "short" })
);
Sentry.captureException(err);
}
} catch (err) {
//to catch some localetimestring failure
Sentry.captureException(err);
}
return "Local Time";
}
// "America/New_York"
export function getPlaceTimezone(): string | null {
return typeof Intl === "object"
? Intl.DateTimeFormat().resolvedOptions().timeZone
: null;
}
export function roundUp(value: number, factor = 1): number {
return Math.ceil(value / factor) * factor;
}
export function getClockFormattedTime(
secs: number,
showEmptyHours = false
): string {
let isNegative = false;
//no need for decimal places in this string
secs = Math.round(secs);
if (secs < 0) {
isNegative = true;
secs = secs * -1;
}
const hours = Math.floor(secs / (60 * 60));
const divisor_for_minutes = secs % (60 * 60);
const minutes = Math.floor(divisor_for_minutes / 60);
const seconds = secs % 60;
let clockString = "";
if (isNegative) {
clockString = "-";
}
if (hours) {
clockString += minTwoDigits(hours) + ":";
} else if (showEmptyHours) {
clockString += "00:";
}
clockString += `${minTwoDigits(minutes)}:${minTwoDigits(seconds)}`;
// debug("getClockFormattedTime", {
// secsin: secs,
// hours,
// minutes,
// seconds,
// clockString,
// });
return clockString;
}
function minTwoDigits(num: number) {
return ("0" + num).slice(-2);
}
export function clockFormattedToSeconds(clockString: string) {
let hrs = 0;
let mins = 0;
let secs = 0;
const parts = clockString.split(":");
if (parts.length === 3) {
hrs = parseInt(parts[0]);
mins = parseInt(parts[1]);
secs = parseInt(parts[2]);
} else if (parts.length === 2) {
mins = parseInt(parts[0]);
secs = parseInt(parts[1]);
} else {
console.error("Failed to parse clockString", clockString);
}
return hrs * 60 * 60 + mins * 60 + secs;
}
export function secondsToTimerFormat(secs: number): string {
if (secs < 0) {
secs = secs * -1;
}
const minutes = Math.min(Math.floor(secs / 60), 99);
const seconds = secs % 60;
let timerString = "";
timerString += `${minTwoDigits(minutes)}:${minTwoDigits(seconds)}`;
return timerString;
}
export function secondsToHms(d: number) {
d = Number(d);
const h = Math.floor(d / 3600);
const m = Math.floor((d % 3600) / 60);
const s = Math.floor((d % 3600) % 60);
const hDisplay =
h > 0 ? h + (h == 1 ? " hr" : " hrs") + (m > 0 || s > 0 ? ", " : "") : "";
const mDisplay =
m > 0 ? m + (m == 1 ? " min" : " mins") + (s > 0 ? ", " : "") : "";
const sDisplay = s > 0 ? s + (s == 1 ? " sec" : " secs") : "";
return hDisplay + mDisplay + sDisplay;
}
|
23d3448e4fd2a7869ccc7e6b9ec953ff05699d73
|
TypeScript
|
lanemt/definitelytyped.github.io
|
/types/wav/wav-tests.ts
| 2.5625
| 3
|
import { createReadStream } from 'fs';
import { Reader, Writer, FileWriter } from 'wav';
const file = createReadStream('track01.wav');
const reader = new Reader();
const reader2 = new Reader();
const writer = new Writer({
sampleRate: 16000,
channels: 1
});
const fileWriter = new FileWriter('./test.wav', {
sampleRate: 16000,
channels: 1
});
reader.on('format', (format) => {
console.log(format);
reader.pipe(writer);
});
reader2.on('format', (format) => {
console.log(format);
reader2.pipe(fileWriter);
});
file.pipe(reader);
|
0c4cbd55d5e1c99f43e9a3c28fff732361bad2a6
|
TypeScript
|
SlepoRus/alla_pugacheva
|
/src/helpers/actions.ts
| 2.765625
| 3
|
import {Character} from "../core/Character";
import {WeaponSpecial} from "../types/items";
import {GameEvents} from "../core/Event";
export function getDamageOnFight(ch1: Character, ch2: Character) {
const dmg = ch1.getCharacterDamage();
const def = ch2.getCharacterDefence();
return Math.max(dmg - def, 0);
}
export function getExpByDMGLVL(chDMG: number, chLVL1: number, chLVL2: number) {
const lvlDec = Math.max(chLVL2 - chLVL1, 1);
return lvlDec * (chDMG/2);
}
export function doActionByMuteHammers(client: any, channel: string, userName: string, spec: WeaponSpecial[]) {
if (spec.includes(WeaponSpecial.MUTE_LITE)) {
GameEvents.muteByLiteBanHammerLite(channel, userName);
}
if (spec.includes(WeaponSpecial.MUTE_MEDIUM)) {
GameEvents.muteByMediumBanHammer(channel, userName)
}
if (spec.includes(WeaponSpecial.MUTE_HARD)) {
GameEvents.muteByHardBanHammer(channel, userName)
}
}
|
d4b54c90d24bafc16c91883680da776de3ad42d2
|
TypeScript
|
jambit/wdio-cucumber-selected-steps
|
/packages/library/src/support/elements/selectOption.ts
| 3.125
| 3
|
import { ElementQuery } from '../elementQuery';
import { failMessage } from '../failMessage';
const TYPE_HANDLERS = {
name: (element: ElementQuery, value: string) => element().selectByAttribute('name', value),
value: (element: ElementQuery, value: string) => element().selectByAttribute('value', value),
text: (element: ElementQuery, value: string) => element().selectByVisibleText(value),
};
const TYPES = Object.keys(TYPE_HANDLERS);
type Type = keyof typeof TYPE_HANDLERS;
/**
* Select an option of a select element
* @param type Type of method to select by
* @param value Value to select by
* @param element The element query
*/
export default (type: Type, value: string, element: ElementQuery): void => {
failMessage(() => expect(TYPES).toContain(type), `Invalid type: '${type}'. Valid types are: ${TYPES.join(', ')}'`);
const handler = TYPE_HANDLERS[type];
handler(element, value);
};
|
310a6c27a52a1e1fb29331da1c1a125024cf1d8d
|
TypeScript
|
mark-ting/228-discord-bot
|
/src/commands/Help.ts
| 2.640625
| 3
|
import { CommandDetailEmbed } from '@embeds/CommandDetailEmbed'
import { CommandListEmbed } from '@embeds/CommandListEmbed'
import { Command, Parameter } from '@models/Command'
import { Core } from '@src/Core'
import { Message, PermissionString } from 'discord.js'
import { Arguments } from 'yargs-parser'
class HelpCommand extends Command {
public readonly id = 'help'
public readonly namespace = 'General'
public readonly desc = 'List commands or parameters for a specified command'
public readonly neededPerms: PermissionString[] = []
public readonly params: Parameter[] = [
{
name: 'command',
required: false,
description: 'Name of command.'
}
]
action = async (core: Core, message: Message, args: Arguments) => {
if (!args['command'] && args._.length === 0) {
const allowableCommands = Array.from(core.commandList.values())
.filter(command => {
return message.member.permissions.has(command.neededPerms)
})
const embed = new CommandListEmbed(allowableCommands)
message.channel.send(embed)
return
}
const commandName = args['command'] || args._[0]
if (!core.commandList.has(commandName)) {
message.reply(`\`${commandName}\` is not a recognized command.`)
return
}
const command = core.commandList.get(commandName)
const embed = new CommandDetailEmbed(command)
message.channel.send(embed)
}
}
export = HelpCommand
|
562fc8f9c72fcd48f432d807b9f6cce5de7bc102
|
TypeScript
|
AmyAssist/Amy-Web
|
/src/app/Plugins/Navigation/Components/departure-planner/departure-planner.component.ts
| 2.59375
| 3
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { NavigationDataService } from '../../Services/navigation-data.service';
import { NavPath } from '../../Objects/navPath';
import { BestTransportResult } from '../../Objects/bestTransportResult';
import { combineLatest, Observable } from 'rxjs';
import { FormControl } from '@angular/forms';
import { map, startWith } from 'rxjs/operators';
class Tag {
constructor(readonly name: string) { }
}
/*
Component for the departure-planner functionality of the Navigation-Plugin
it is Part of the navigation component
@author: Tobias Siemonsen
*/
@Component({
selector: 'app-departure-planner',
templateUrl: './departure-planner.component.html',
styleUrls: ['./departure-planner.component.css'],
encapsulation: ViewEncapsulation.None,
})
export class DeparturePlannerComponent implements OnInit {
navPathData: NavPath;
from: string;
to: string;
timeDate: Date;
travelMode: string;
showWhen: boolean;
whenTime: string;
whenTimeDate: Date;
bestTransport: BestTransportResult;
transit: boolean;
tags: Observable<Tag[]>;
originFilteredTags: Observable<Tag[]>;
destinationFilteredTags: Observable<Tag[]>;
originField = new FormControl();
destinationField = new FormControl();
getTagDisplayName(t: Tag) {
return t ? t.name : '';
}
constructor(private readonly navigationService: NavigationDataService) { }
ngOnInit() {
this.showWhen = false;
this.transit = false;
this.navPathData = new NavPath();
this.bestTransport = new BestTransportResult();
this.loadTags();
}
/*
This method loads the tags from the backend so they can be displayed in the UI
and work as an entry string
*/
loadTags() {
this.tags = this.navigationService.getTags().pipe(map(tags => tags.map(t => new Tag(t))));
const mapping = map(([text, tags]) => tags.filter(tag => {
let searchText: string;
if (text instanceof Tag) {
searchText = text.name;
} else {
searchText = text;
}
return tag.name.toLowerCase().indexOf(searchText.toLowerCase()) === 0;
}));
this.originFilteredTags = combineLatest(
this.originField.valueChanges.pipe(startWith('')) as Observable<string | Tag>,
this.tags.pipe(startWith([]))
).pipe(mapping);
this.destinationFilteredTags = combineLatest(
this.destinationField.valueChanges.pipe(startWith('')) as Observable<string | Tag>,
this.tags.pipe(startWith([]))
).pipe(mapping);
}
/*
This Method executes the main functionality, it calls the createRoute Method
and send the object with the backend service to the backend,
then it uses the recieved time object to display it.
*/
async searchWhen(from: string | Tag, to: string | Tag, date: string) {
this.createRoute(from, to, date);
this.navPathData.travelmode = this.travelMode;
this.navigationService.when(this.navPathData).subscribe((data: string) => {
this.whenTime = data;
this.whenTimeDate = new Date(this.whenTime);
this.showWhen = true;
});
}
/*
This Method creates an navPath object which is send to the navigation backend to calculate the best travel mode
*/
createRoute(from: string | Tag, to: string | Tag, date: string) {
if (from instanceof Tag) {
this.navPathData.originTag = from.name;
} else {
this.navPathData.origin = from;
}
if (to instanceof Tag) {
this.navPathData.destinationTag = to.name;
} else {
this.navPathData.destination = to;
}
this.timeDate = new Date(date);
this.navPathData.time = this.timeDate.toISOString();
}
}
|
0273eea71c8e96528f72753056957c7963559bd8
|
TypeScript
|
takumi-maki/techpit-form
|
/front/src/domain/entity/alert.ts
| 2.515625
| 3
|
export type AlertState = {
severity: AlertSeverity;
message: string;
open: boolean;
};
export type AlertSeverity = "error" | "success";
|
b98e2f59ad8fad018e664ba14b889b4792ec66e9
|
TypeScript
|
Julien5151/bros-node-server
|
/src/utils/middlewares/auth.ts
| 2.75
| 3
|
import { RequestHandler } from "express";
import jwt, { Secret } from "jsonwebtoken";
import { User } from "../../models/user";
import { SpecialUsers, UserRole } from "../types/enums";
import { CustomError } from "../types/interfaces";
export const authController: RequestHandler = async (req, res, next) => {
// Extract token from request
const token = req.get("Authorization");
// If a token is found, verify it
if (token) {
// Try to verify the token
try {
// If environment variable DEV_TOKEN exists we're not in prod
if (process.env.DEV_TOKEN && token === process.env.DEV_TOKEN) {
// If correct dev token is used, proceed to next middlewares with dev admin role
res.locals.userId = SpecialUsers["dev-admin"];
res.locals.userRole = UserRole.admin;
next();
} else {
// We're in production, verify token
const decodedToken = jwt.verify(
token,
process.env.TOKEN_SECRET as Secret
);
// Extract user id to fetch role from DB
const userId = (decodedToken as any).id;
const user = await User.load(userId);
// Add user to locals
res.locals.user = user;
// Proceed to next middlewares
next();
}
} catch (err) {
// If token couldn't be verified, throw 401 error
const verifyError: CustomError = {
statusCode: 401,
message: "Invalid token",
};
next(verifyError);
}
} else {
// If token or Authorization header is missing, throw 401 error
const missingTokenError: CustomError = {
statusCode: 401,
message: "No token provided",
};
next(missingTokenError);
}
};
|
2913924c1498f0adb79bf2695975d7a8d55006ef
|
TypeScript
|
lauri3new/light-fp
|
/src/Arrow/index.ts
| 3.109375
| 3
|
// import { Either, Left, Right } from '../Either'
// import { Context } from './Server/index'
// // Orthogonal
// // Composable
// type naka = { ok: number }
// type yela = { ok: 123, nok: 'xhe' }
// const af = <A, B, D>(f: (_:A) => B, g: (_:B) => D) => (v: A) => g(f(v))
// const toStuff = (): yela => ({ ok: 123, nok: 'xhe' })
// const fromSomeStuff = (a: naka) => 'hello'
// af(toStuff, fromSomeStuff)
// type Subset<T, U> = { [key in keyof T]: key extends keyof U ? T[key] : never }
// export interface ArrowT<C, E, A, I > {
// __val: (_: I) => Promise<[Either<E, A>, C]>
// __tag: string
// map: <B>(f:(_:A) => B) => ArrowT<C, E, B, I>
// ctxMap: <CC >(f:(_:C) => CC) => ArrowT<CC, E, A, I>
// combineA: (f:ArrowT<C, E, A, I>) => ArrowT<C, E, A, I>
// andThenCtxF: <B, EE>(f:(__:C) => Promise<Either<E | EE, B>>) => ArrowT<C, E | EE, B, I>
// andThenF: <B, EE>(f:(_:A, __:C) => Promise<Either<E | EE, B>>) => ArrowT<C, E | EE, B, I>
// andThen: <CC, B, EE, CI>(f:ArrowT<CC, EE, B, C>) => ArrowT<CC, E | EE, B, I>
// flatMap: <B, EE>(f:(_:A, __:C) => ArrowT<C, EE, B, I>) => ArrowT<C, E | EE, B, I>
// thenChangeCtx: <EE, CC >(f:(_:A, __:C) => Promise<Either<EE, CC>>) => ArrowT<CC, E | EE, A, I>
// thenMergeCtx: <EE, CC >(f:(_:A, __:C) => Promise<Either<EE, CC>>) => ArrowT<CC & C, E | EE, A, I>
// leftMap: <EE>(f:(_:E) => EE) => ArrowT<C, EE, A, I>
// leftMapP: <EE>(f:(_:E, __:I) => Promise<EE>) => ArrowT<I, EE, A, I>
// runWith: <L, M, N>(
// c: I,
// f: (_:A) => L,
// g: (_:E) => M,
// j: (_?: Error) => N
// ) => Promise<L | M | N>
// }
// export const ArrowT = <C, E, A, I >(val:(_: I) => Promise<[Either<E, A>, C]>): ArrowT<C, E, A, I> => ({
// __val: val,
// __tag: 'ArrowT',
// map: <B>(f: (_:A) => B) => ArrowT<C, E, B, I>((c: I) => val(c).then(([eitherA, g]) => [eitherA.map(f), g])),
// leftMap: <EE>(f: (_:E) => EE) => ArrowT<C, EE, A, I>((c: I) => val(c).then(([eitherA, g]) => [eitherA.leftMap(f), g])),
// leftMapP: <EE>(f:(_:E, __: I) => Promise<EE>) => ArrowT<I, EE, A, I>((c: I) => val(c)
// .then(
// ([eitherA]): Promise<[Either<EE, A>, I]> => eitherA.match(
// left => f(left, c).then(res => [Left(res), c] as [Left<EE>, I]),
// async right => [Right(right), c] as [Right<A>, I]
// )
// )),
// ctxMap: <CC >(f: (_:C) => CC) => ArrowT<CC, E, A, I>((c: I) => val(c).then(([eitherA, g]) => [eitherA, f(g)])),
// andThenCtxF: <B, EE>(f:(__:C) => Promise<Either<E | EE, B>>) => ArrowT<C, E | EE, B, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, B>, C]> => eitherA.match(
// e => {
// const r = Promise.resolve<[Either<E, B>, C]>([Left(e), g])
// return r
// },
// a => {
// const r = f(g).then(b => [b, g]) as Promise<[Either<EE, B>, C]>
// return r
// }
// )
// )
// ),
// andThenF: <B, EE>(f:(_:A, __:C) => Promise<Either<E | EE, B>>) => ArrowT<C, E | EE, B, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, B>, C]> => eitherA.match(
// e => {
// const r = Promise.resolve<[Either<E, B>, C]>([Left(e), g])
// return r
// },
// a => {
// const r = f(a, g).then(b => [b, g]) as Promise<[Either<EE, B>, C]>
// return r
// }
// )
// )
// ),
// andThen: <CC, B, EE, CI>(f:ArrowT<CC, EE, B, C>) => ArrowT<CC, E | EE, B, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, B>, CC]> => eitherA.match(
// e => {
// const r = Promise.resolve<[Either<E, B>, CC]>([Left(e), g] as unknown as [Either<E, B>, CC])
// return r
// },
// a => {
// const r = f.__val(g)
// return r
// }
// )
// )
// ),
// combineA: (f:ArrowT<C, E, A, I>) => ArrowT<C, E, A, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]) => eitherA.match(
// e => f.__val(c),
// a => [Right(a), g]
// )
// )
// ),
// thenChangeCtx: <CC, EE>(f:(_:A, __:C) => Promise<Either<E | EE, CC>>) => ArrowT<CC, E | EE, A, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, A>, CC]> => eitherA.match(
// e => {
// const r = Promise.resolve([Left(e), g]) as unknown as Promise<[Either<E, A>, CC]>
// return r
// },
// a => {
// const r = f(a, g).then(b => b.match(
// e => [Left(e), g],
// rr => [eitherA, rr]
// )) as Promise<[Either<EE, A>, CC]>
// return r
// }
// )
// )
// ),
// thenMergeCtx: <EE, CC >(f:(_:A, __:C) => Promise<Either<EE, CC>>) => ArrowT<CC & C, E | EE, A, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, A>, CC & C]> => eitherA.match(
// e => {
// const r = Promise.resolve([Left(e), g]) as Promise<[Either<E, A>, C & CC]>
// return r
// },
// a => {
// const r = f(a, g).then(b => b.match(
// e => [Left(e), g],
// rr => [eitherA, { ...g, ...rr }]
// )) as Promise<[Either<EE, A>, C & CC]>
// return r
// }
// )
// )
// ),
// flatMap: <B, EE>(f:(_:A, __:C) => ArrowT<C, EE, B, I>) => ArrowT<C, E | EE, B, I>(
// (c: I) => val(c)
// .then(
// ([eitherA, g]): Promise<[Either<E | EE, B>, C]> => eitherA.match(
// e => {
// const r = Promise.resolve<[Either<E, B>, C]>([Left(e), g])
// return r
// },
// a => {
// const r = f(a, g)
// return r.__val(c)
// }
// )
// )
// ),
// runWith: <L, M, N>(
// c: I,
// f: (_:A) => L,
// g: (_:E) => M,
// j: (_?: Error) => N
// ) => val(c).then(
// ([a, _c]) => a.match(
// none => g(none),
// some => f(some)
// )
// )
// .catch(
// j
// )
// })
// type Service = { userService: { get: () => number } }
// type User = {
// name: string
// id: number
// }
// type withUser = {
// user: User
// }
// type With<A, B> = {
// A: B
// }
// type newType = With<'user', any>
// export const ofContext = <Context >(): ArrowT<Context, never, undefined, Context> => ArrowT(async (c: Context) => [Right(undefined), c])
// export const extendContext = <A extends Context>(): ArrowT<A, never, undefined, A> => ArrowT(async (c: A) => [Right(undefined), c])
// export const of = <Value, Context>(v: Value) => ArrowT<Context, never, Value, Context>(async (c: Context) => [Right(v), c])
// // export const fromCtx = <Context, E, nextContext>(v: (c: Context) => Promise<Either<E, nextContext>>) => ArrowT<Context, E, undefined, nextContext>((_: Context) => v(_).then(eitherCtx => e))
// export const fromEither = <E, A, Context = {}>(eitherA: Either<E, A>) => ArrowT<Context, E, A, Context>(async (c: Context) => [eitherA, c])
// export const fromPromise = <E, A, Context = {}>(eitherA: Promise<A>) => ArrowT<Context, E, A, Context>((c: Context): Promise<[Either<E, A>, Context]> => eitherA.then(a => [Right(a), c] as [Right<A>, Context]).catch((e: E) => [Left(e), c]))
// export const fromPEither = <E, A, Context = {}>(eitherA: Promise<Either<E, A>>) => ArrowT<Context, E, A, Context>((c: Context) => eitherA.then(a => [a, c]))
// export const sequence = <A, B, C, D >(as: ArrowT<A, B, C, D>[]): ArrowT<A, B, C[], D> => as.reduce(
// (acc, arrowA) => acc.flatMap((a, _) => arrowA.map(c => [...a, c])), ArrowT<A, B, C[], D>(async (ctx: D) => [Right<C[], B>([]), ctx as unknown as A])
// )
// const getUser = (service: Service) => service.userService.get()
// // later in program
// // mapK ?
// // semiFlatMap ?
// // flatMapSync ?
// // tap
// // type alias <A,B,C,D> to <A,B,C>
// // bimap? whats this zip? zip is ArrowT<Ctx, E, A>.zip(ArrowT<Ctx, E, A>): ArrowT<Ctx, E, [A, B]>
// // more constructors - promise, function, either...
// // sequence? or not... sequence is bimap?
// // clone?
// // what else is useful - logging?
// // runWithoutContext
// const hi = of<number, {userService:()=> number, dabaService:() => string}>(12)
// .andThenF(async (n: number, ctx: { userService: () => number }) => (Math.random() < 0.8 ? Right(n * 5) : Left('yela')))
// const xhe = of<number, {userService:()=> number, dabaService:() => string}>(12)
// .andThenF(async (n: number, ctx: { userService: () => number }) => Right(n * 5))
// .thenMergeCtx(async (n: number, ctx: { dabaService: () => string }) => Right({ yela: 'ooh' }))
// .leftMap(a => 'wasup')
// export const composeA = <A, B, C, D, E, F, G>(a: ArrowT<A, B, C, D>, b: ArrowT<E, F, G, A>) => a.andThen(b)
// export const combineA = <A extends Context, B, C, D>(...as: ArrowT<A, B, C, D>[]): ArrowT<A, B, C, D> => {
// if (as.length === 1) return as[0]
// if (as.length === 2) return as[0].combineA(as[1])
// const [a, b, ...aas] = as
// return combineA(a.combineA(b), ...as)
// }
// const aef = ofContext<yela>()
// const baf = <A extends { ok: number }>() => of<number, A>(5).ctxMap((a) => ({ ...a, xhama: 234 }))
// aef.andThen(baf())
// // .andThenF(async (_, b: naka) => Righst({}))
// // const b = hi
// // .andThenA(xhe)
// // .runWith(
// // { userService: () => 5, dabaService: () => 'hello' },
// // a => console.log('yekaSheka', a),
// // a => console.log('fail', a),
// // a => console.log('err', a)
// // )
// type IUser = {
// id: number
// name: string
// }
// type firebase = {
// firebase: { validate: (_: number) => IUser }
// }
// // export const composeKHandler = <A extends Context, B extends Context, C extends Context>(a: ArrowT<B, Context, Context, A>, b: ArrowT<C, Context, Context, B>): ArrowT<C, Context, Context, A> => b.andThen(b)
// const ga = (a: string) => Promise.resolve({ ok: 123, xhaba: 234 })
// const gb = (a: { ok: number }) => Promise.resolve('daba')
// const gc = (a: string) => Promise.resolve('daba')
// const composekleisli = <A, B, C>(a: (_:A) => Promise<B>, b: (_:B) => Promise<C>) => (aa: A) => a(aa).then(b)
// const yelal = composekleisli(ga, gb)
// interface Arrow<S, E, Sout> {
// __val: (_:S) => Promise<Either<E, Sout>>
// map: <S2out>(f: (_:Sout) => S2out) => Arrow<S, E, S2out>
// leftMap: <E2>(f: (_:E) => E2) => Arrow<S, E2, Sout>
// flatMap: <E2, S2Out>(f: (_:Sout) => Arrow<Sout, E2, S2Out>) => Arrow<S, E | E2, S2Out>
// andThen: <E2, S2Out>(_: Arrow<Sout, E | E2, S2Out>) => Arrow<S, E | E2, S2Out>
// andThenMerge: <E2, S2Out>(_: Arrow<Sout, E | E2, S2Out>) => Arrow<S, E | E2, Sout & S2Out>
// andThenF: <E2, S2Out>(f: (_:Sout) => Promise<Either<E, S2Out>>) => Arrow<S, E | E2, S2Out>
// runWith: <A, B, C>(
// context: S,
// f: (_:Sout) => A,
// g: (_:E) => B,
// j: (_?: Error) => C
// ) => Promise<A | B | C>
// }
// const Arrow = <S, E, Sout>(__val: (_:S) => Promise<Either<E, Sout>>) => ({
// __val,
// map: <S2out>(f: (_:Sout) => S2out) => Arrow<S, E, S2out>((_:S) => __val(_).then(a => a.map(f))),
// leftMap: <E2>(f: (_:E) => E2) => Arrow<S, E2, Sout>((_:S) => __val(_).then(a => a.leftMap(f))),
// flatMap: <E2, S2Out>(f: (_:Sout) => Arrow<S, E2, S2Out>) => Arrow<S, E | E2, S2Out>(
// (a: S) => __val(a).then((eitherS2): Promise<Either<E | E2, S2Out>> => eitherS2.match(
// e => Promise.resolve(Left(e)),
// s2 => f(s2).__val(a)
// ))
// ),
// andThen: <E2, S2Out>(f: Arrow<Sout, E2, S2Out>) => Arrow<S, E | E2, S2Out>(
// (a: S) => __val(a).then((eitherS2): Promise<Either<E | E2, S2Out>> => eitherS2.match(
// e => Promise.resolve(Left(e)),
// s2 => f.__val(s2)
// ))
// ),
// andThenF: <E2, S2Out>(f: (_:Sout) => Promise<Either<E, S2Out>>) => Arrow<S, E | E2, S2Out>(
// (a: S) => __val(a).then((eitherS2): Promise<Either<E | E2, S2Out>> => eitherS2.match(
// e => Promise.resolve(Left(e)),
// s2 => f(s2)
// ))
// ),
// andThenMerge: <E2, S2Out>(f: Arrow<Sout, E2, S2Out>) => Arrow<S, E | E2, Sout & S2Out>(
// (a: S) => __val(a).then((eitherS2): Promise<Either<E | E2, Sout & S2Out>> => eitherS2.match(
// e => Promise.resolve(Left(e)),
// s2 => f.__val(s2).then(eitherS => eitherS.map(a2 => ({ ...s2, ...a2 })))
// ))
// ),
// runWith: <A, B, C>(
// context: S,
// f: (_:Sout) => A,
// g: (_:E) => B,
// j: (_?: Error) => C
// ) => __val(context).then(
// (eitherS) => eitherS.match(
// none => g(none),
// some => f(some)
// )
// )
// .catch(
// j
// )
// })
|
a5ec4a558aae64608388ce2f2d4fd94719136509
|
TypeScript
|
magicly/ts-egg-demo
|
/app/service/home.ts
| 2.578125
| 3
|
import { Service } from 'egg';
interface NewsResult {
success: boolean;
data: Array<{
id: string;
author_id: string;
content: string;
title: string;
create_at: string;
author: {
loginname: string;
avatar_url: string;
};
}>;
}
export default class Home extends Service {
/**
* get topics
* @param page - page number
* @param pageSize - page count
*/
public async getTopics(page?: number, pageSize?: number): Promise<NewsResult> {
page = page || 1;
pageSize = pageSize || this.getConfig().pageSize;
try {
const result = await this.request(`topics`, {
data: {
page,
limit: 1,
},
});
return result;
} catch (e) {
this.ctx.logger.error(e);
}
}
private getConfig() {
return this.app.config.news;
}
/**
* request api
* @param api - Api name
* @param opts - urllib options
*/
private async request(api: string, opts?: object) {
const options = {
dataType: 'json',
timeout: ['30s', '30s'],
...opts,
};
const result = await this.ctx.curl(`${this.getConfig().urlPrefix}/${api}`, options);
return result.data;
}
}
|
c11549de0171e9688563443ca79e6e3410a9c05d
|
TypeScript
|
growyourlist/gyl-admin-ui
|
/src/common/api.ts
| 2.625
| 3
|
import { apiRequest } from "./apiRequest"
export interface List {
name: string
id: string
sourceEmail: string | null
}
export const fetchListsList = async (): Promise<List[]> => {
const response = await apiRequest('/admin/lists')
const lists = await response.json()
return <List[]>lists
}
export const postList = async (list: List): Promise<string> => {
const response = await apiRequest('/admin/list', {
method: 'POST',
body: JSON.stringify(list)
})
if (!response.ok) {
throw new Error(await response.text())
}
return await response.text()
}
|
87f07349b83f847dd8e9b829ca9f77df00bbf6a2
|
TypeScript
|
JR-Pikachu/JR-Blog
|
/src/app/article.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
interface ArticleEditResponse {
success: boolean;
}
@Injectable({
providedIn: 'root'
})
export class ArticleService {
private _api = 'http://localhost:3000/';
private httpOptions = {
headers: new HttpHeaders({ 'Content-type' : 'application/json' })
};
constructor(private http: HttpClient) { }
init() {
console.log('service articles ok');
}
// API call - For register - SAMPLE V2 avec User pour TOUT
registerArticle(articleDataSent) {
console.log('articleAdd from articleService');
console.log(articleDataSent);
return this.http.post<ArticleEditResponse>(this._api + 'api/articles/', articleDataSent,
this.httpOptions);
}
// API call - For Getting - SAMPLE V2 avec User pour TOUT
getArticles() {
console.log('getArticles from articleService');
return this.http.get<ArticleEditResponse>(this._api + 'api/articles/');
}
getArticle(id: string) {
console.log('getArticles from articleService');
return this.http.get<ArticleEditResponse>(this._api + 'api/articles/' + id);
}
}
|
32f27429453ccca20e4a2037dfc469c873f356a0
|
TypeScript
|
CarlosWGama/ionic2-lista-compras
|
/src/providers/compras.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import { Compra } from './../models/compra.model';
declare var firebase;
@Injectable()
export class Compras {
private db;
private usuarioID;
constructor() {
console.log('Hello Compras Provider');
this.db = firebase.database();
this.usuarioID = firebase.auth().currentUser.uid;
firebase.auth().onAuthStateChanged((user) => {
if (user)
this.usuarioID = user.uid;
});
}
/**
* Lista todas as compras do usuário logado
*/
getCompras(): Promise<Compra[]> {
return this.db.ref('/compras/' + this.usuarioID).once('value').then(snapshot => {
let compras: Compra[] = [];
if (snapshot.val() && Object.keys(snapshot.val()).length > 0) {
Object.keys(snapshot.val()).forEach(key => {
let data = snapshot.val()[key];
compras.push(Compra.parseJSON(data));
});
}
return compras;
});
}
/**
* Busca uma compra pelo ID
*/
getCompra(id: string): Promise<Compra> {
return this.db.ref('/compras/' + this.usuarioID + '/' + id).once('value').then(snapshot => {
return Compra.parseJSON(snapshot.val());
});
}
/**
* Cadastra uma nova compra
*/
cadastrar(compra: Compra):void {
let newKey = this.db.ref('/compras/'+this.usuarioID).push().key;
compra.ID = newKey;
this.db.ref('/compras/' + this.usuarioID + '/' + newKey).set(compra);
}
/**
* Edita uma compra pelo ID
*/
editar(id: string, compra: Compra):void {
this.db.ref('/compras/'+ this.usuarioID + '/' + id).set(compra);
}
/**
* Remove uma compra
*/
excluir(id: string): void {
this.db.ref('/compras/' + this.usuarioID + '/' + id).set(null);
}
}
|
ebc23d0e8f19eeff2de655ef06fef2f5cf066611
|
TypeScript
|
mjwbenton/mattb.tech-graphql-api
|
/api-lambda/src/SpotifyApi.ts
| 2.640625
| 3
|
import axios from "axios";
import doAndCache from "./doAndCache";
import { getAccessToken } from "@mattb.tech/graphql-api-oauth-lib";
import { KeyValueCache } from "@apollo/utils.keyvaluecache";
export type Playlist = {
id: string;
name: string;
description: string;
tracks: Array<Track>;
link: string;
};
export type Track = {
id: string;
name: string;
artists: Array<Artist>;
album: Album;
};
export type Artist = {
id: string;
name: string;
};
export type Album = {
id: string;
name: string;
images: Array<Image>;
};
export type Image = {
url: string;
width: number;
height: number;
};
export class SpotifyDataSource {
constructor(private readonly cache: KeyValueCache) {}
public async getPlaylist(playlist: string): Promise<Playlist> {
const cacheKey = `playlist-${playlist}`;
return doAndCache(this.cache, cacheKey, async () => {
const accessToken = await getAccessToken("spotify");
const response = (
await axios.get(`https://api.spotify.com/v1/playlists/${playlist}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
).data;
const { id, name, description } = response;
const link = response.external_urls.spotify;
const tracks: Array<Track> = response.tracks.items.map((t: any) => {
return {
id: t.track.id,
name: t.track.name,
album: {
id: t.track.album.id,
name: t.track.album.name,
images: t.track.album.images,
},
artists: t.track.artists.map((a: any) => ({
id: a.id,
name: a.name,
})),
};
});
return { id, name, description, tracks, link };
});
}
public async getLikedTracks(limit: number = 3): Promise<Array<Track>> {
const cacheKey = `likedTracks-${limit}`;
return doAndCache(this.cache, cacheKey, async () => {
const accessToken = await getAccessToken("spotify");
const response = (
await axios.get(`https://api.spotify.com/v1/me/tracks?limit=${limit}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
).data;
const tracks: Array<Track> = response.items.map((t: any) => {
return {
id: t.track.id,
name: t.track.name,
album: {
id: t.track.album.id,
name: t.track.album.name,
images: t.track.album.images,
},
artists: t.track.artists.map((a: any) => ({
id: a.id,
name: a.name,
})),
};
});
return tracks;
});
}
}
|
8defd46ef2924f0fcaae661149a87d0174a52ec1
|
TypeScript
|
sujithreddy9493/ngbatch
|
/typescript/interface.ts
| 3.40625
| 3
|
function interconnect(data:number, b:number ){
console.log(typeof data);
data ="nameDetails"
console.log(typeof data);
}
interconnect("content", 10);
interconnect(10,"20");
let dataInfo:string[] =["suji","nani"]
let details:[string,string] = ["",""]
let name_2:string;
name_2 =10;
console.log("name",name_2);
let testFn:() =>string;
testFn =10;
testFn = () =>{
return "10";
}
let obj_1:{name:string, age:number}
obj_1 ={
name:"krishna";
age: 23
}
let arr_1:[number,string] =[10,"suji"]
arr_1.push(20);
let test_fn1:() => Array<string>
test_fn1= ()=>{
console.log("ravi");
return["testdata"]
}
function name_5<T>(data:T):<T>()=>T
let fnDef = (a) => a*3;
console.log(fnDef(10))
interface employeeDetails {
name:string;
age:number;
adhaarNo:number;
phone:number;
bloodgroup:string;
email:string;
salary:number;
city?:string;
[key:string]:any;
}
var detailsOfTheEmployee : employeeDetails[];
detailsOfTheEmployee=[
{
name:"suji",
age: 23;
adhaarNo: 967618847962;
phone:9493580957;
bloodgroup:"A+";
email:"sujithreddy@gmail.com";
salary:25000;
city:"hyderabad"
address:"shridihills awllyn colnoy";
}
]
|
03baa223c8bb8186ad44d7bcf56ab3724b47ddaa
|
TypeScript
|
stnswz/nextjs-examples
|
/components/hooks/useDataLoadAPI.ts
| 2.609375
| 3
|
import { useState, useEffect } from 'react';
import axios, {AxiosResponse} from 'axios';
const useDataLoadAPI = (preloadedData:any, initialURL:string, initialSearchText:string): Array<any> => {
console.log('useDataLoadAPI')
const [url, setURL] = useState(initialURL);
const [searchText, setSearchText] = useState(initialSearchText);
const [responseData, setResponseData] = useState(preloadedData);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
console.log(' -> useDataLoadAPI -> useEffect searchText: ' + searchText)
const loadData = async () => {
setIsError(false)
setIsLoading(true)
await axios.get(url, {params: {query: searchText}})
.then ((response: AxiosResponse<Record<string, unknown>>) => {
setResponseData(response.data)
})
.catch((error) => {
setIsError(true)
})
setIsLoading(false)
}
if(searchText !== '') loadData()
}, [url, searchText])
return [{responseData, searchText, isLoading, isError}, setSearchText]
}
export default useDataLoadAPI
|
3f373c9d38ae93945c0a90c20f3251c28a8b8b30
|
TypeScript
|
nomanHasan/datatable
|
/ng-datatable/src/app/table-data/table-data.model.ts
| 3.265625
| 3
|
// import * as randomWords from 'random-words';
// const randomWords = () => 'CELL';
const word = (length = 7) => {
if (!length) {
length = num(10);
}
const vowels = 'aeiou';
const constants = 'qwrtpsdfghjklzxcvbnm';
let text = '';
Array(length)
.fill(0)
.forEach(element => {
text += constants.includes(text[text.length - 1])
? (Math.random() > 0.8
? letter(constants)
: letter(vowels))
: ((Math.random() > 0.45)
? letter(vowels)
: letter(constants));
});
text = text
.slice(0, 1)
.toUpperCase() + text.slice(1);
return text;
};
const num = (max, min = 0) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
const letter = string => {
return string[num(string.length - 1)];
};
const randomWords = word;
const range = (length) => {
return Array.from(Array(length).fill(0));
};
const getPlainArray = (row, col) => {
const tableData = [];
range(row).forEach((r, i) => {
const rowData = [];
rowData.push(i);
range(col).forEach(c => {
rowData.push(randomWords());
});
tableData.push(rowData);
});
return tableData;
};
const getTableData = (row, col) => {
const tableData = [];
const cols = ['index'];
range(col).forEach(c => {
cols.push(randomWords());
});
range(row).forEach((r, i) => {
let rowData = {};
rowData = {
'index': i
};
cols.forEach((c, index) => {
if (c === 'index') {
return;
}
rowData = {
...rowData,
[c]: randomWords()
};
});
tableData.push(rowData);
if (i % 10000 === 0) {
console.log('Row Generated: ', i);
}
});
return {tableData, columns: cols};
};
export const TableData = {
getPlainArray,
getTableData
};
|
082dc8902c88f0a34f03a40dd971ff83bdccf5e3
|
TypeScript
|
dorward/intercode
|
/app/javascript/CmsAdmin/queries.generated.ts
| 2.5625
| 3
|
/* eslint-disable */
import * as Types from '../graphqlTypes.generated';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
export type CmsAdminBaseQueryQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type CmsAdminBaseQueryQuery = (
{ __typename: 'Query' }
& { convention?: Types.Maybe<(
{ __typename: 'Convention' }
& Pick<Types.Convention, 'id'>
)>, currentAbility: (
{ __typename: 'Ability' }
& Pick<Types.Ability, 'can_create_cms_navigation_items'>
) }
);
export const CmsAdminBaseQueryDocument = gql`
query CmsAdminBaseQuery {
convention {
id
}
currentAbility {
can_create_cms_navigation_items
}
}
`;
/**
* __useCmsAdminBaseQueryQuery__
*
* To run a query within a React component, call `useCmsAdminBaseQueryQuery` and pass it any options that fit your needs.
* When your component renders, `useCmsAdminBaseQueryQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useCmsAdminBaseQueryQuery({
* variables: {
* },
* });
*/
export function useCmsAdminBaseQueryQuery(baseOptions?: Apollo.QueryHookOptions<CmsAdminBaseQueryQuery, CmsAdminBaseQueryQueryVariables>) {
return Apollo.useQuery<CmsAdminBaseQueryQuery, CmsAdminBaseQueryQueryVariables>(CmsAdminBaseQueryDocument, baseOptions);
}
export function useCmsAdminBaseQueryLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<CmsAdminBaseQueryQuery, CmsAdminBaseQueryQueryVariables>) {
return Apollo.useLazyQuery<CmsAdminBaseQueryQuery, CmsAdminBaseQueryQueryVariables>(CmsAdminBaseQueryDocument, baseOptions);
}
export type CmsAdminBaseQueryQueryHookResult = ReturnType<typeof useCmsAdminBaseQueryQuery>;
export type CmsAdminBaseQueryLazyQueryHookResult = ReturnType<typeof useCmsAdminBaseQueryLazyQuery>;
export type CmsAdminBaseQueryQueryResult = Apollo.QueryResult<CmsAdminBaseQueryQuery, CmsAdminBaseQueryQueryVariables>;
|
1adf9797d326a65f192233ea169f3c28c21c1be3
|
TypeScript
|
arcanist123/transpiler
|
/packages/transpiler/src/keywords.ts
| 2.78125
| 3
|
import * as abaplint from "@abaplint/core";
/** Replaces javascript keywords in ABAP source code, in-memory only */
export class Keywords {
public handle(reg: abaplint.IRegistry) {
reg.parse();
for (const o of reg.getObjects()) {
if (!(o instanceof abaplint.ABAPObject)) {
continue;
}
for (const f of o.getABAPFiles()) {
let tokens: abaplint.Token[] = [];
for (const s of f.getStatements()) {
tokens = tokens.concat(this.traverse(s, f));
}
if (tokens.length === 0) {
continue;
}
const rows = f.getRawRows();
for (const t of tokens.reverse()) {
const original = rows[t.getRow() - 1];
const index = t.getEnd().getCol() - 1;
rows[t.getRow() - 1] = original.substring(0, index) + "_" + original.substring(index);
}
reg.updateFile(new abaplint.MemoryFile(f.getFilename(), rows.join("\n")));
}
}
reg.parse();
}
private traverse(node: abaplint.INode, file: abaplint.ABAPFile): abaplint.Token[] {
// https://www.w3schools.com/js/js_reserved.asp
const keywords: string[] = [
"abstract", "arguments", "await", "boolean",
"break", "byte", "case", "catch",
"char", "class", "const", "continue",
"debugger", "default", "do",
"double", "else", "enum", "eval",
"export", "extends", "false", "final",
"finally", "float", "for", "function",
"goto", "if", "implements", "import",
"in", "instanceof", "int", "interface",
"let", "long", "native", "new",
"null", "package", "private", "protected",
"public", "return", "short", "static",
"switch", "synchronized", "this",
"throw", "throws", "transient", "true",
"try", "typeof", "var", "void",
"volatile", "while", "yield"];
// "with"
// "delete"
let ret: abaplint.Token[] = [];
for (const c of node.getChildren()) {
if (c instanceof abaplint.Nodes.TokenNodeRegex) {
if (keywords.some(k => k === c.getFirstToken().getStr().toLowerCase())) {
ret.push(c.getFirstToken());
}
} else if (c instanceof abaplint.Nodes.TokenNode) {
continue;
} else {
ret = ret.concat(this.traverse(c, file));
}
}
return ret;
}
}
|
48a553d83bec568b136c585fbb8e4e1866a0ad39
|
TypeScript
|
andirsun/nestjs-rest-api
|
/src/modules/time/application/time.service.ts
| 3.015625
| 3
|
import { Injectable } from "@nestjs/common";
/*JS Moment dependence */
const moment = require('moment-timezone');
/*Additional interfaces*/
import { UserPromCodeInterface } from "../../../barbers/user/domain/interfaces/user-promcode.interface";
@Injectable()
export class TimeService{
/*
This function takes as a parameter an hour in HH:mm:ss format and returns the received time in
its amount in minutes. Is used in setDurationInMinutes function.
*/
setDuration(difference:string) : number {
return (moment.duration(difference)._data.hours)*60 + moment.duration(difference)._data.minutes;
}
/*
This functions cast from date string to moment object and return it
*/
setMomentObject(date:string) : object {
return moment(date);
}
/*
This return a date string that represents the difference between two dates (moments objects)
*/
setDifference(now: object, then: object) : string{
return moment.utc(moment(then,"DD/MM/YYYY HH:mm:ss").diff(moment(now,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss");
}
/*
This function set the service and order duration into the order docuemnt
*/
async setDurationInMinutes(newNow: string, newThen: string) : Promise<number>{
let now : object = await this.setMomentObject(newNow);
let then : object = await this.setMomentObject(newThen);
let difference = await this.setDifference(now, then);
return this.setDuration(difference)
}
/*
This function set the promotional code expiration date
*/
setPromExpirationDate(currentDate: string, differenceInDays: number): string{
const expirationDate: string = moment(currentDate, "YYYY-MM-DD HH:mm").add(differenceInDays,'days').format("YYYY-MM-DD HH:mm");
return expirationDate
}
/*
This function return de current date in HH:mm:ss format
*/
getCurrentDate(): string{
return moment().tz('America/Bogota').format("YYYY-MM-DD HH:mm");
}
/*
check if a code is not expired
*/
async getPromCodeExpiryConfirmation(expirationDate: string): Promise <boolean>{
let currentDate: string = this.getCurrentDate();
if(currentDate <= expirationDate){
return true
}
return false
}
/*
check in a array of codes, which code is not expired
*/
async getExpiredCodes(codesArray: UserPromCodeInterface[]): Promise<UserPromCodeInterface[]>{
let codes:UserPromCodeInterface[] = [];
//Check which code has already expired and forget it
for(let i = 0; i < codesArray.length; i++){
let isExpired: boolean = await this.getPromCodeExpiryConfirmation(codesArray[i].expirationDate)
//Set array with valid codes only
if(isExpired){
codes.push(codesArray[i])
}
}
return codes;
}
/*
Get a year of a specific date
*/
getYear(date : string): number {
return parseInt(moment(date).year());
}
/*
Get a week name of a specific date
*/
getWeekNumber(date : string): number {
return parseInt(moment(date).week());
}
/*
Get a time (YYYY:MM:DD) with a year and week given
*/
getTimeWithYearAndWeek(year : number, week : number): string {
return moment().isoWeekYear(year).isoWeek(week).startOf('week').format("YYYY-MM-DD");
}
}
|
e4ed61e2bf12da0c43e1087b44ae588e63c222f1
|
TypeScript
|
omerman/simple-forgein-exchange-positions-table
|
/packages/client/src/typings/common/data-table.ts
| 2.8125
| 3
|
export type IOrderDirection = 'asc' | 'desc';
export interface IGetDataOptions<T> {
page: number,
rowsPerPage: number,
orderBy?: keyof T,
orderDirection?: IOrderDirection,
searchPhrase?: string,
}
export interface IDataTable<T> {
getTotalCount: () => Promise<number>;
getData: (options: IGetDataOptions<T>) => Promise<T[]>;
}
|
108099097c54b2bd4eb80f847cd6cadc213c0ff1
|
TypeScript
|
anhquandlqb2001/roadmap-server-nodejs
|
/src/controllers/user.ts
| 2.609375
| 3
|
import { Request, Response } from "express";
import { formValidate } from "../lib/util/formValidate";
import findOneAndUpdateOrCreate from "../lib/util/findOneAndUpdateOrCreate";
import { IFormDataToClientSuccess, EProvider } from "../lib/types/form.type";
import User from "../models/user";
// POST: Dang ky - Provider: local
export const register = async (req: Request, res: Response) => {
try {
const { email, password } = req.body;
const errors = formValidate(email, password);
if (errors) {
return res.json({ success: false, errors });
}
const user = new User();
user.email = email;
user.password = password;
user.provider = "LOCAL";
await user.save();
req.session.userId = user._id;
return res.json({
success: true,
data: { email: user.email, provider: user.provider },
});
} catch (error) {
if (error.code === 11000) {
return res.json({
success: false,
errors: [{ name: "email", error: "Email da ton tai" }],
});
}
}
};
// POST: Dang nhap voi tai khoan local
export const loginLocal = async (req: Request, res: Response) => {
const { email, password } = req.body;
const errors = formValidate(email, password);
if (errors) {
return res.json({ success: false, errors });
}
// // Kiem tra email co ton tai
const user = await User.findOne({ email });
if (!user) {
return res.json({
success: false,
errors: [
{ name: "email", error: "Sai tai khoan hoac mat khau" },
{ name: "password", error: "Sai tai khoan hoac mat khau" },
],
});
}
// // Kiem tra mat khau
if (!(await user.verifyPassword(password))) {
return res.json({
success: false,
errors: [{ name: "password", error: "Sai mat khau" }],
});
}
// dang nhap thanh cong
req.session.userId = user._id;
return res.json({
success: true,
data: { email: user.email, provider: user.provider },
});
};
// POST: Dang nhap voi facebook
export const loginFacebook = async (req: Request, res: Response) => {
const user = await findOneAndUpdateOrCreate(req.body);
// dang nhap thanh cong
req.session.userId = user._id;
return res.json({
success: true,
data: { email: user.email, provider: EProvider.Facebook },
} as IFormDataToClientSuccess);
};
// GET: Kiem tra thong tin nguoi dung trong session neu ton tai
export const current = async (req: Request, res: Response) => {
const userId = req.session.userId;
if (!userId) return res.json({ user: null });
const user = await User.findById(userId);
if (!user) {
return res.json({ user: null });
}
const mapArr = user.maps.map((map) => {
return { mapHasStarted: map.mapId, ownerMapId: map._id };
});
return res.json({
success: true,
user: {
email: user.email,
jwt: user?.jwt,
provider: user.provider,
_id: userId
},
map: mapArr,
});
};
|
ba4529e3a27a16bb9e5c4f662700463fa58b26d8
|
TypeScript
|
SINHASantos/fusionjs
|
/fusion-core/src/sanitization.ts
| 2.84375
| 3
|
/** Copyright (c) 2018 Uber Technologies, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/*
We never want developers to be able to write `ctx.template.body.push(`<div>${stuff}</div>`)`
because that allows XSS attacks by default (e.g. if stuff === '<script>alert(1)</script>')
Instead, they should use html`<div>{stuff}</div>` so interpolated data gets automatically escaped
We trust the markup outside of interpolation because it's code written by a developer with commit permissions,
which can be audited via code reviews
*/
import type {SanitizedHTMLWrapper} from './types';
// eslint-disable-next-line import/no-mutable-exports
let html: (
strings: TemplateStringsArray,
...expressions: Array<string>
) => SanitizedHTMLWrapper,
dangerouslySetHTML: (html: string) => any,
consumeSanitizedHTML: (h: SanitizedHTMLWrapper) => string,
escape: (str: string) => string;
if (__NODE__) {
const forbiddenChars = {
'<': '\\u003C',
'>': '\\u003E',
'"': '\\u0022',
'&': '\\u0026',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
};
const replaceForbidden = (c) => forbiddenChars[c];
const key = Symbol('sanitized html');
const inspect = Symbol.for('nodejs.util.inspect.custom');
html = (
[head, ...rest]: TemplateStringsArray,
...values: Array<string>
): SanitizedHTMLWrapper => {
const obj = {};
Object.defineProperty(obj, inspect, {
value: function inspectHtml() {
return consumeSanitizedHTML(this);
},
});
Object.defineProperty(obj, key, {
enumerable: false,
configurable: false,
value: head + values.map((s, i) => escape(s) + rest[i]).join(''),
});
return obj;
};
dangerouslySetHTML = (str: string): any =>
html(
// @ts-expect-error not a template string array, but implementation allows that as well
[str]
);
escape = (str: any): string => {
if (str && str[key] !== undefined) return consumeSanitizedHTML(str);
return String(str).replace(/[<>&"\u2028\u2029]/g, replaceForbidden);
};
consumeSanitizedHTML = (h: SanitizedHTMLWrapper): string => {
if (typeof h === 'string') {
throw new Error(`Unsanitized html. Use html\`${h}\``);
}
return h[key];
};
}
const replaceEscaped = (c) => String.fromCodePoint(parseInt(c.slice(2), 16));
const unescape = (str: string): string => {
return str.replace(
/\\u003C|\\u003E|\\u0022|\\u002F|\\u2028|\\u2029|\\u0026/g,
replaceEscaped
);
};
export {html, dangerouslySetHTML, consumeSanitizedHTML, escape, unescape};
|
f4ef7647bac62ff041fef73d015ce5f373f33db0
|
TypeScript
|
gitEllE-if/TypeScript_lessons
|
/src/scripts/search-results.ts
| 2.5625
| 3
|
import { renderBlock, insertBlock, removeBlockChilds } from './lib';
import { Place } from './domain/place';
import { placeStorage } from './storage';
export function renderSearchStubBlock(): void {
renderBlock(
'search-results-block',
`
<div class="before-results-block">
<img src="img/start-search.png" />
<p>Чтобы начать поиск, заполните форму и нажмите "Найти"</p>
</div>
`
)
}
export function renderEmptyOrErrorSearchBlock(reasonMessage: string): void {
renderBlock(
'search-results-block',
`
<div class="no-results-block">
<img src="img/no-results.png" />
<p>${reasonMessage}</p>
</div>
`
)
}
export function renderSearchResultsBlock(): void {
renderBlock(
'search-results-block',
`
<div class="search-results-header">
<p>Результаты поиска</p>
<div class="search-results-filter">
<span><i class="icon icon-filter"></i> Сортировать:</span>
<select id="search-results-sorting">
<option value="ascendingPrice" selected="selected">Сначала дешёвые</option>
<option value="descendingPrice">Сначала дорогие</option>
<option value="ascendingRemoteness">Сначала ближе</option>
</select>
</div>
</div>
<ul class="results-list" id="search-result-list">
</ul>
`
);
}
export function renderSearchResultsItem(place: Place, placeInFavorite: boolean): void {
insertBlock(
'search-result-list',
`
<li class="result">
<div class="result-container">
<div class="result-img-container">
<div class="favorites ${placeInFavorite ? ' active' : ''}" id="favorite${place.id}"></div>
<img class="result-img" src=${place.image} alt="">
</div>
<div class="result-info">
<div class="result-info--header">
<p>${place.name}</p>
<p class="price">${place.price}₽</p>
</div>
<div class="${place.remoteness ? 'result-info--map' : 'invisible'}">
<i class="map-icon"></i> ${place.remoteness} км от вас
</div>
<div class="result-info--descr">${place.description}</div>
<div class="result-info--footer">
<div>
<button id="book-btn${place.id}">Забронировать</button>
</div>
</div>
</div>
</div>
</li>
`
);
}
export function putSearchResultsItems(places: Place[]): void {
for (const place of places) {
renderSearchResultsItem(place, placeStorage.hasItem(place))
document.getElementById(`favorite${place.id}`)?.addEventListener('click', place.toggleFavEventHandler);
document.getElementById(`book-btn${place.id}`)?.addEventListener('click', place.bookEventHandler);
}
}
export function delSearchResultsItems(places: Place[]): void {
for (const place of places) {
document.getElementById(`favorite${place.id}`)?.removeEventListener('click', place.toggleFavEventHandler);
document.getElementById(`book-btn${place.id}`)?.removeEventListener('click', place.bookEventHandler);
}
removeBlockChilds('search-result-list');
}
|
3aa40516d907f947a99f8c083673dea8f90d1c38
|
TypeScript
|
mcampster/angular-routing
|
/src/state/stateComparer.ts
| 2.71875
| 3
|
/// <reference path="../refs.d.ts" />
/// <reference path="state.ts" />
class StateComparer {
public buildStateArray(state, params) {
function extractParams() {
var paramsObj = {};
if (current.route) {
forEach(current.route.params, (param, name) => {
paramsObj[name] = params[name];
});
}
return paramsObj;
}
var states = [],
current = state;
do {
states.push({ state: current, params: extractParams() });
} while (current = current.parent);
return states;
}
public compare(from, to, fromParams, toParams, forceReload) {
var fromArray = this.buildStateArray(from, fromParams || {}),
toArray = this.buildStateArray(to, toParams),
count = Math.max(fromArray.length, toArray.length),
fromAtIndex,
toAtIndex,
stateChanges = false,
paramChanges = !equals(fromParams, toParams);
for (var i = 0; i < count; i++) {
fromAtIndex = fromArray[fromArray.length - i - 1];
toAtIndex = toArray[toArray.length - i - 1];
if (isUndefined(toAtIndex)) {
toArray[0].isChanged = stateChanges = true;
} else if (isUndefined(fromAtIndex)
|| forceReload === toAtIndex.state.fullname
|| toAtIndex.state.fullname !== fromAtIndex.state.fullname
|| !equals(toAtIndex.params, fromAtIndex.params)) {
toAtIndex.isChanged = stateChanges = true;
} else {
toAtIndex.isChanged = false;
}
}
//TODO: if ReloadOnOptional is false, but parameters are changed.
// we should raise the update event instead.
toArray[0].isChanged = stateChanges = stateChanges || (toArray[0].state.reloadOnOptional && paramChanges);
return {
array: toArray.reverse(),
stateChanges: stateChanges,
paramChanges: paramChanges
};
}
}
|
0179103b57d4469f24819667f37b8d49822e78f1
|
TypeScript
|
Fowindev/grin-server
|
/src/controller/index.ts
| 2.90625
| 3
|
import express from 'express';
import { RouteEntry, RoutesMetadata } from "../methods";
interface ControllerMetadata {
basePath?: string;
middlewares?: express.RequestHandler[];
routes: RouteEntry[];
}
interface ControllerOptions {
middlewares?: express.RequestHandler[];
overwrite?: boolean;
}
/**
* Class decorator to create a Controller class that handles Routes
* @param {string=} basePath Base path
* @param {ControllerOptions=} options Controller Options
* @returns {ClassDecorator} Class Decorator
*/
const Controller = (
basePath?: string,
options?: ControllerOptions
): ClassDecorator => {
return <T extends Function>(constructor: T) => {
let controllerMetadata:
| ControllerMetadata
| undefined = Reflect.getOwnMetadata("grin:controller", constructor);
let routesMetadata: RoutesMetadata | undefined = Reflect.getOwnMetadata(
"grin:routes",
constructor
);
if (controllerMetadata) {
if (options?.overwrite) {
controllerMetadata = undefined;
} else {
throw new Error(
`Controller Class ${constructor.name} is already a Controller`
);
}
}
controllerMetadata = {
basePath: basePath,
middlewares: options?.middlewares,
routes: routesMetadata?.routes || [],
};
Reflect.defineMetadata("grin:controller", controllerMetadata, constructor);
};
};
export type { ControllerMetadata, ControllerOptions };
export { Controller };
|
f71784c56b0c384d710c3b05effeb45d56e539e4
|
TypeScript
|
chriswa/voxel2
|
/src/common/v3.ts
| 3.4375
| 3
|
const EPSILON = 0.000001
export default class v3 {
a: Float32Array
constructor(x = 0, y = 0, z = 0) {
this.a = new Float32Array([ x, y, z ])
}
get x() { return this.a[0] }
get y() { return this.a[1] }
get z() { return this.a[2] }
set x(v: number) { this.a[0] = v }
set y(v: number) { this.a[1] = v }
set z(v: number) { this.a[2] = v }
clone() {
return new v3(this.a[0], this.a[1], this.a[2])
}
set(x: number, y: number, z: number) {
this.a[0] = x
this.a[1] = y
this.a[2] = z
return this
}
setFrom(b: v3) {
this.a[0] = b.a[0]
this.a[1] = b.a[1]
this.a[2] = b.a[2]
return this
}
setSum(b: v3, c: v3) {
this.a[0] = b.a[0] + c.a[0]
this.a[1] = b.a[1] + c.a[1]
this.a[2] = b.a[2] + c.a[2]
return this
}
toString() {
return this.a[0] + ',' + this.a[1] + ',' + this.a[2]
}
get id() {
return this.a[0] + ',' + this.a[1] + ',' + this.a[2]
}
// operations involving no arguments
lengthSqr() {
const ax = this.a[0], ay = this.a[1], az = this.a[2]
return ax * ax + ay * ay + az * az
}
length() {
return Math.sqrt(this.lengthSqr())
}
ceil() {
this.a[0] = Math.ceil(this.a[0])
this.a[1] = Math.ceil(this.a[1])
this.a[2] = Math.ceil(this.a[2])
return this
}
floor() {
this.a[0] = Math.floor(this.a[0])
this.a[1] = Math.floor(this.a[1])
this.a[2] = Math.floor(this.a[2])
return this
}
negate() {
this.a[0] = -(this.a[0])
this.a[1] = -(this.a[1])
this.a[2] = -(this.a[2])
return this
}
invert() {
this.a[0] = 1 / this.a[0]
this.a[1] = 1 / this.a[1]
this.a[2] = 1 / this.a[2]
return this
}
normalize() {
const lenSqr = this.lengthSqr()
if (lenSqr > 0) {
this.multiplyScalar(1 / Math.sqrt(lenSqr))
}
return this
}
// operations involving a scalar argument
multiplyScalar(scalar: number) {
this.a[0] *= scalar
this.a[1] *= scalar
this.a[2] *= scalar
return this
}
divideScalar(scalar: number) {
this.a[0] /= scalar
this.a[1] /= scalar
this.a[2] /= scalar
return this
}
// operations involving a second vector
add(that: v3) {
this.a[0] += that.a[0]
this.a[1] += that.a[1]
this.a[2] += that.a[2]
return this
}
subtract(that: v3) {
this.a[0] -= that.a[0]
this.a[1] -= that.a[1]
this.a[2] -= that.a[2]
return this
}
multiply(that: v3) {
this.a[0] *= that.a[0]
this.a[1] *= that.a[1]
this.a[2] *= that.a[2]
return this
}
divide(that: v3) {
this.a[0] /= that.a[0]
this.a[1] /= that.a[1]
this.a[2] /= that.a[2]
return this
}
dot(that: v3) {
return this.a[0] * that.a[0] + this.a[1] * that.a[1] + this.a[2] * that.a[2]
}
cross(that: v3) {
const ax = this.a[0], ay = this.a[1], az = this.a[2]
const bx = that.a[0], by = that.a[1], bz = that.a[2]
this.a[0] = ay * bz - az * by
this.a[1] = az * bx - ax * bz
this.a[2] = ax * by - ay * bx
return this
}
lerp(that: v3, t: number) {
const ax = this.a[0], ay = this.a[1], az = this.a[2]
this.a[0] = ay + t * (that.a[0] - ax)
this.a[1] = az + t * (that.a[1] - ay)
this.a[2] = ax + t * (that.a[2] - az)
return this
}
exactEquals(that: v3) {
return this.a[0] === that.a[0] && this.a[1] === that.a[1] && this.a[2] === that.a[2]
}
equals(that: v3) {
const ax = this.a[0], ay = this.a[1], az = this.a[2]
const bx = that.a[0], by = that.a[1], bz = that.a[2]
return (Math.abs(ax - bx) <= EPSILON * Math.max(1.0, Math.abs(ax), Math.abs(bx)) &&
Math.abs(ay - by) <= EPSILON * Math.max(1.0, Math.abs(ay), Math.abs(by)) &&
Math.abs(az - bz) <= EPSILON * Math.max(1.0, Math.abs(az), Math.abs(bz)))
}
}
|
7ba200069665e65448b6cbfcd7dea81ca766e3d9
|
TypeScript
|
marcelomanchester/ToDoList
|
/todo-app/src/app/todo-list/todo-list.component.ts
| 2.515625
| 3
|
import { Component} from '@angular/core';
@Component({
selector: 'todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent {
atividade: string = '';
nova: string = '';
listaAtividades:Array<string> = [];
pesquisa: string = '';
listaPesquisa = [];
check: boolean;
constructor() {
this.listaAtividades = [];
this.pesquisa = '';
this.check = true;
}
updatePesquisa(event){
this.pesquisa = event.target.value;
this.addPesquisa();
}
updateAtividade(event) {
this.atividade = event.target.value;
}
addAtividade(event) {
this.nova = this.atividade.trim();
if(this.checkAtividade(this.nova)){
this.listaAtividades.push(this.atividade);
this.addPesquisa();
}
}
addPesquisa(){
this.listaPesquisa = [];
for(var i=0; i< this.listaAtividades.length; i++){
if( this.listaAtividades[i].indexOf(this.pesquisa) >= 0){
this.listaPesquisa.push(this.listaAtividades[i]);
}
}
}
delAtividade(tarefa){
for(var i=0; i< this.listaAtividades.length; i++){
if (this.listaAtividades[i] == tarefa){
this.listaAtividades.splice(i, 1);
this.addPesquisa();
}
}
}
checkAtividade(nova):boolean{
if (this.nova.length > 25 || this.nova.length == 0 ){
this.check = false;
return(this.check);
}
else{
this.check = true;
return(this.check)
}
}
}
|
e1520738691e720a999e270751ef5fcd5864c99a
|
TypeScript
|
angulardynamic/DataBroker
|
/src/filter/jsonata.ts
| 2.625
| 3
|
// TODO: Implement JSONata
// //var jsonata = require("jsonata");
// import * as jsonata from 'jsonata';
// import { Injectable } from '@angular/core';
// @Injectable()
// export class Jsonata
// {
// filter(query: string, item: any, data: any): boolean
// {
// let expression = jsonata(query);
// let result = expression.evaluate(data);
// let itemMatch = false;
// query.forEach(q => {
// //console.log(" q:", q);
// if (q.type == "or")
// {
// q.filters.forEach(filter => {
// //console.log(" filter:", filter);
// //if (filter.op == "eq")
// if (true)
// {
// //console.log(" data:", data);
// let matches;
// let testItem = item[filter.prop];
// const matchAgainst: any = this.template.parseTpl(filter.filterBinding, data, matches);
// //console.log(" testItem: ", testItem, " matchAgainst: ", matchAgainst);
// // console.log(` filterItem:"`, filterItem,
// // '",typeof filterItem:', typeof filterItem, " _.isNil(filterItem):", _.isNil(filterItem),
// // " _.isEmpty(filterItem):", _.isEmpty(filterItem),
// // " filterItem.length:", filterItem.length
// // );
// //if (filterItem == null || filterItem == undefined || typeof filterItem === 'undefined')
// //if (!filterItem || _.isNil(filterItem) || _.isEmpty(filterItem) || filterItem == "" || filterItem.length <= 0)
// if (matchAgainst === "undefined")
// {
// //console.log("filterItem == undefined");
// itemMatch = true;
// }
// else
// {
// let testItemType = typeof testItem;
// let matchAgainstConverted;
// if (testItemType === "string")
// {
// //TODO: setting for case sensitive
// if (true)
// {
// testItem = testItem.toLowerCase();
// matchAgainstConverted = matchAgainst.toLowerCase();
// }
// //TODO: Finish
// // else
// // {
// // matchAgainstConverted = matchAgainst;
// // }
// }
// else if (testItemType === "number")
// {
// //matchAgainstConverted = Number(matchAgainst);
// matchAgainstConverted = +matchAgainst;
// }
// //console.log(` testItemType: ${testItemType}`, " typeof matchAgainstConverted:", typeof matchAgainstConverted);
// //console.log("filterItem != undefined");
// if (filter.op === "eq" && testItem === matchAgainstConverted)
// {
// //console.log(` item[${filter.prop}] === data.${filter.filterBinding}`);
// itemMatch = true;
// }
// else if (filter.op === "like" && typeof testItem === "string" && testItem.indexOf(matchAgainstConverted) >= 0)
// {
// itemMatch = true;
// }
// else
// {
// //console.log(` item[${filter.prop}]: ${item[filter.prop]} !== data.${filter.filterBinding}: ${filterItem}`);
// }
// //console.log("testItem: ", testItem, "matchAgainstConverted: ", matchAgainstConverted, "filter.op:", filter.op, "itemMatch: ", itemMatch);
// }
// }
// else
// {
// //console.log(` filter.op = ${filter.op}`);
// }
// })
// }
// else
// {
// //console.log(` q.type = ${q.type}`);
// }
// });
// return itemMatch;
// }
// }
|
253061f94efd6fe702fe1ae0e7a8d648c0ee94a2
|
TypeScript
|
htndev/server-toolkit
|
/src/graphql/types/exists.type.ts
| 2.78125
| 3
|
import { Field, ObjectType } from '@nestjs/graphql';
@ObjectType({ description: 'API response, that something exists or not.' })
export class ExistsType {
@Field(() => Boolean)
exists!: boolean;
}
|
402038fe233f9ed7223ec5c4eaed5a8dde99a326
|
TypeScript
|
doubleproject/cli
|
/src/tests/lib/utils/compat.test.ts
| 2.546875
| 3
|
import * as os from 'os';
import test from 'ava';
import * as compat from '../../../lib/utils/compat';
test('should be able to untildify path', t => {
const home = os.homedir();
t.is(compat.untildify('~'), home);
t.is(compat.untildify('~/hello'), `${home}/hello`);
t.is(compat.untildify('~/hello/~/world'), `${home}/hello/~/world`);
});
test('untildify should not modify paths without leading tilde', t => {
t.is(compat.untildify('/'), '/');
t.is(compat.untildify('hello'), 'hello');
t.is(compat.untildify('~hello/~/world'), '~hello/~/world');
});
|
8c720f95c7e8d9ca2a099e98960b752f2c70ec0c
|
TypeScript
|
LudmilaSchlegelova/Attribute-Directives-Angular-project
|
/attributeDirectives/src/app/custom-directive/custom-directives-item/custom-directives-item.component.ts
| 2.5625
| 3
|
import { Component, OnInit } from '@angular/core';
import { customAnimation } from 'src/app/customanimation';
interface Countries {
id: number;
title: string;
visible: string;
}
@Component({
selector: 'app-custom-directives-item',
templateUrl: './custom-directives-item.component.html',
styleUrls: ['./custom-directives-item.component.css'],
animations: [customAnimation],
})
export class CustomDirectivesItemComponent implements OnInit {
countries: Countries[] = [
{ id: 1, title: 'Bulgary', visible: 'isVisible' },
{ id: 2, title: 'Canada', visible: 'isVisible' },
{ id: 3, title: 'China', visible: 'isVisible' },
{ id: 4, title: 'India', visible: 'isVisible' },
{ id: 5, title: 'Angola', visible: 'isVisible' },
{ id: 6, title: 'Chile', visible: 'isVisible' },
{ id: 7, title: 'Greece', visible: 'isVisible' },
];
constructor() {}
ngOnInit(): void {}
isVisible(id: number) {
const newCountries = this.countries.map((country) => {
if (country.id === id) {
country.visible = 'isNotVisible';
console.log(country);
return country;
}
return country;
});
this.countries = newCountries;
}
}
|
947f1bbcffc35c97a94b8698066c369abcfe89c3
|
TypeScript
|
toteach/client-ui
|
/src/types.ts
| 2.546875
| 3
|
export type TColorModifiers =
'white' |
'black' |
'light' |
'dark' |
'primary' |
'info' |
'success' |
'warning' |
'danger' |
'text';
export type TSizes =
'small' |
'medium' |
'large';
export type TPositions =
'top' |
'left' |
'bottom' |
'right';
export type TStates =
'active' |
'focus' |
'hover';
|
a4b33ede88ac15c51a2f89895652578198f67bb2
|
TypeScript
|
fltenwall/pnpm
|
/packages/supi/src/install/createVersionsOverrider.ts
| 2.71875
| 3
|
import { Dependencies, PackageManifest, ReadPackageHook } from '@pnpm/types'
import parseWantedDependency from '@pnpm/parse-wanted-dependency'
import semver from 'semver'
export default function (overrides: Record<string, string>): ReadPackageHook {
const genericVersionOverrides = [] as VersionOverride[]
const versionOverrides = [] as VersionOverrideWithParent[]
Object.entries(overrides)
.forEach(([selector, newPref]) => {
if (selector.includes('>')) {
const [parentSelector, childSelector] = selector.split('>')
versionOverrides.push({
newPref,
parentWantedDependency: parseWantedDependency(parentSelector),
wantedDependency: parseWantedDependency(childSelector),
} as VersionOverrideWithParent)
return
}
genericVersionOverrides.push({
newPref,
wantedDependency: parseWantedDependency(selector),
} as VersionOverride)
})
return ((pkg: PackageManifest) => {
overrideDepsOfPkg(pkg, versionOverrides.filter(({ parentWantedDependency }) => {
return parentWantedDependency.alias === pkg.name && (
!parentWantedDependency.pref || semver.satisfies(pkg.version, parentWantedDependency.pref)
)
}))
overrideDepsOfPkg(pkg, genericVersionOverrides)
return pkg
}) as ReadPackageHook
}
interface VersionOverride {
parentWantedDependency?: {
alias: string
pref?: string
}
wantedDependency: {
alias: string
pref?: string
}
newPref: string
}
interface VersionOverrideWithParent extends VersionOverride {
parentWantedDependency: {
alias: string
pref?: string
}
}
function overrideDepsOfPkg (pkg: PackageManifest, versionOverrides: VersionOverride[]) {
if (pkg.dependencies != null) overrideDeps(versionOverrides, pkg.dependencies)
if (pkg.optionalDependencies != null) overrideDeps(versionOverrides, pkg.optionalDependencies)
if (pkg.devDependencies != null) overrideDeps(versionOverrides, pkg.devDependencies)
return pkg
}
function overrideDeps (versionOverrides: VersionOverride[], deps: Dependencies) {
for (const versionOverride of versionOverrides) {
const actual = deps[versionOverride.wantedDependency.alias]
if (
actual &&
(
!versionOverride.wantedDependency.pref ||
actual === versionOverride.wantedDependency.pref ||
semver.validRange(actual) != null &&
semver.validRange(versionOverride.wantedDependency.pref) != null &&
semver.subset(actual, versionOverride.wantedDependency.pref)
)
) {
deps[versionOverride.wantedDependency.alias] = versionOverride.newPref
}
}
}
|
c311ebacc0fb6d027f58fb3a49997d21eec09363
|
TypeScript
|
Nasisolo/vscode-database
|
/src/extension/engine/mysql-ssl.ts
| 2.59375
| 3
|
import * as fs from 'fs';
import { createConnection, ConnectionConfig } from 'mysql';
import {MySQLType} from './mysql-pass';
import { AnyObject } from '../../typeing/common';
export class MySQLSSLType extends MySQLType {
public ca: string;
public key: string;
public cert: string;
constructor() {
super();
this.ca = '';
this.key = '';
this.cert = '';
}
getName() {
if (this.name) {
return this.name;
}
return `${this.host}:${this.port} (${this.typeName})`;
}
/**
* @param {object} fields
* @return {Promise}
*/
connectPromise({host, username, password, socket, key, cert, ca}: AnyObject): Promise<undefined> {
const [hostName, port = '3306'] = host.split(':');
this.host = hostName;
this.port = port;
this.username = username;
this.password = password;
this.ca = ca;
this.key = key;
this.cert = cert;
const setting: ConnectionConfig = {
host: this.host,
port: parseInt(port, 10),
user: username,
password: password,
ssl: {
rejectUnauthorized : false,
ca : fs.readFileSync(ca).toString(),
key : fs.readFileSync(key).toString(),
cert : fs.readFileSync(cert).toString(),
}
};
if (socket) {
this.socket = hostName;
setting.socketPath = hostName;
delete setting.host;
delete setting.port;
}
const connection = createConnection(setting);
return new Promise((resolve, reject) => {
connection.connect((err: Error) => {
if (err) {
reject(err.message);
} else {
this.connection = connection;
resolve();
}
});
});
}
/**
* @return {object} - object with some data to save
*/
getDataToRestore(){
return Promise.resolve({
type: this.type,
name: this.name,
host: this.host + ':' + this.port,
socket: this.socket,
ca: this.ca,
key: this.key,
cert: this.cert,
database: this.currentDatabase,
});
}
/**
* @param {object} fields - result getDataToRestore() function
* @return {Promise}
*/
restoreConnection(fields: AnyObject): Promise<undefined>{
return this.connectPromise(fields);
}
}
MySQLSSLType.prototype.typeName= 'MySql (SSL)';
MySQLSSLType.prototype.fieldsToConnect = [
{
type: 'text',
defaultValue: 'localhost',
name: 'host',
title: 'Host',
info: '(e.g host, 127.0.0.1, with port 127.0.0.1:3333)'
},
{
type: 'checkbox',
defaultValue: false,
name: 'socket',
title: 'via socket',
info: '(if you want to connect via socket, enter socketPath in the host field)'
},
{
type: 'text',
defaultValue: '',
name: 'ca',
title: 'CA',
info: '(Server certificates - path to `root.crt`)'
},
{
type: 'text',
defaultValue: '',
title: 'KEY',
name: 'key',
info: '(Client key - path to `client.key`)'
},
{
type: 'text',
defaultValue: '',
title: 'CERT',
name: 'cert',
info: '(Client certificates - path to `client.crt`)'
}
];
export default MySQLSSLType;
|
63fc186d8f4025a9b00656daeca998e84e75e3fc
|
TypeScript
|
danicv94/hitTheButton
|
/src/app/multi/multi.page.ts
| 2.609375
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-multi',
templateUrl: './multi.page.html',
styleUrls: ['./multi.page.scss'],
})
export class MultiPage {
showStart: boolean = true;
showCountdown: boolean = false;
showGame: boolean = false;
timeout: number = 3;
timeLeft: number = 5;
scorePlayer1: number = 0;
scorePlayer2: number = 0;
winnerScore: number = 0;
endGame: boolean = false;
winner: string = '';
// For timers we should create a service
startGame() {
this.showStart = false;
this.showCountdown = true;
this.showGame = true;
setTimeout(time => {
if (this.timeout > 0) {
this.timeout -= 1;
this.startGame();
}
else {
this.showCountdown = false;
this.startTimer();
}
}, 1000)
}
startTimer() {
setTimeout(time => {
if (this.timeLeft > 0) {
this.timeLeft -= 1;
this.startTimer();
}
else {
this.finishGame();
}
}, 1000)
}
finishGame() {
this.endGame = true;
if (this.scorePlayer1 > this.scorePlayer2) {
this.winner = 'Player1';
this.winnerScore = this.scorePlayer1;
}
else if (this.scorePlayer2 > this.scorePlayer1) {
this.winner = 'Player2';
this.winnerScore = this.scorePlayer2;
}
else {
this.winner = 'Draw'
}
}
increaseScore(player: number) {
if (player === 1) this.scorePlayer1 += 1;
if (player === 2) this.scorePlayer2 += 1;
}
restartGame() {
this.showGame = true;
this.timeout = 3;
this.timeLeft = 5;
this.scorePlayer1 = 0;
this.scorePlayer2 = 0;
this.winnerScore = 0;
this.endGame = false;
this.startGame();
}
}
|
618264f8457a3bf046210f8d2787fd7d7fdd80e8
|
TypeScript
|
nilaymaj/git-playground
|
/src/simulator/git-repository/index-file/index.test.ts
| 2.953125
| 3
|
import IndexFile from './index';
import { FileBlob } from '../../file-system';
import { createSampleFS } from '../../file-system/index.test';
import ObjectStorage from '../object-storage';
import { hashBlobObject } from '../object-storage/hash-object';
import { InvalidArgError } from '../../utils/errors';
const createSampleIndex = () => {
const objectStorage = new ObjectStorage();
const fs = createSampleFS();
const { indexFile, storage } = IndexFile.fromFileTree(
fs._fs._tree,
objectStorage
);
return { indexFile, objectStorage: storage, fs };
};
test('Create index from file tree', () => {
const { indexFile, fs } = createSampleIndex();
const indexItems = indexFile.entries();
// 4 files -> 4 index entries
expect(indexFile.size()).toBe(4);
expect(indexItems.length).toBe(4);
// Check if the index entries are right
const indexItem0 = indexItems[0];
expect(indexItem0.path).toStrictEqual(['dir1', 'dir2', 'file3']);
const file3 = fs.get(['dir1', 'dir2', 'file3']) as FileBlob;
const file3Hash = hashBlobObject({ type: 'blob', fileData: file3 });
expect(indexItem0.entry.objectHash).toBe(file3Hash);
const indexItem1 = indexItems[1];
expect(indexItem1.path).toStrictEqual(['dir1', 'file1']);
const file1 = fs.get(['dir1', 'file1']) as FileBlob;
const file1Hash = hashBlobObject({ type: 'blob', fileData: file1 });
expect(indexItem1.entry.objectHash).toBe(file1Hash);
const indexItem2 = indexItems[2];
expect(indexItem2.path).toStrictEqual(['dir1', 'file2']);
const file2 = fs.get(['dir1', 'file2']) as FileBlob;
const file2Hash = hashBlobObject({ type: 'blob', fileData: file2 });
expect(indexItem2.entry.objectHash).toBe(file2Hash);
const indexItem3 = indexItems[3];
expect(indexItem3.path).toStrictEqual(['file4']);
const file4 = fs.get(['file4']) as FileBlob;
const file4Hash = hashBlobObject({ type: 'blob', fileData: file4 });
expect(indexItem3.entry.objectHash).toBe(file4Hash);
});
test('Get index entry', () => {
const { indexFile, fs } = createSampleIndex();
// Throw error if empty path is provided
expect(() => indexFile.get([])).toThrowError(InvalidArgError);
// Return `null` for non-existent entries
expect(indexFile.get(['?'])).toBeNull();
expect(indexFile.get(['dir1', '?'])).toBeNull();
// Regular work day: get index entry for file under root
const file4 = fs.get(['file4']) as FileBlob;
const file4Hash = hashBlobObject({ type: 'blob', fileData: file4 });
const indexEntry4 = indexFile.get(['file4']);
expect(indexEntry4?.objectHash).toBe(file4Hash);
// Regular work day: get index entry for file at nested path
const file1 = fs.get(['dir1', 'file1']) as FileBlob;
const file1Hash = hashBlobObject({ type: 'blob', fileData: file1 });
const indexEntry1 = indexFile.get(['dir1', 'file1']);
expect(indexEntry1?.objectHash).toBe(file1Hash);
});
test('Upsert entry at path', () => {
const { indexFile } = createSampleIndex();
const sample = { objectHash: 'foo' };
// Can't have index entry at root
expect(() => indexFile.upsert([], sample)).toThrowError(InvalidArgError);
// Regular work day: update entry for file under root
const newIndex1 = indexFile.upsert(['file4'], sample);
expect(newIndex1.get(['file4'])?.objectHash).toBe('foo');
// Regular work day: update entry for file at nested path
const newIndex2 = indexFile.upsert(['dir1', 'file2'], sample);
expect(newIndex2.get(['dir1', 'file2'])?.objectHash).toBe('foo');
// Regular work day: upSERT entry for new file inside new directory
const newIndex3 = indexFile.upsert(['dir3', 'file5'], sample);
expect(newIndex3.get(['dir3', 'file5'])?.objectHash).toBe('foo');
});
test('Remove index entry', () => {
const { indexFile } = createSampleIndex();
// There are no entries at root, so this should fail
expect(() => indexFile.remove([])).toThrowError(InvalidArgError);
// Index entries that don't exist, can't be removed
expect(() => indexFile.remove(['dir1'])).toThrowError(InvalidArgError);
// Regular work day: remove index entry for file under root
const newIndex1 = indexFile.remove(['file4']);
expect(newIndex1.get(['file4'])).toBeNull();
// Regular work day: remove index entry for file at nested path
const newIndex2 = indexFile.remove(['dir1', 'file1']);
expect(newIndex2.get(['dir1', 'file1'])).toBeNull();
});
test('Get path section of index file', () => {
const { indexFile } = createSampleIndex();
// Regular work day: return "prospective" section for non-existent paths
const section1 = indexFile.getPathSection(['dir2']);
expect(section1.start).toBe(3);
expect(section1.end).toBe(3);
// Regular work day: Section limits for directory
const section2 = indexFile.getPathSection(['dir1']);
expect(section2.start).toBe(0);
expect(section2.end).toBe(3);
// Regular work day: Section for single file
const section3 = indexFile.getPathSection(['file4']);
expect(section3.start).toBe(3);
expect(section3.end).toBe(4);
});
|
ccd5c67f094df0a8e826edeb4e8e376fe9313f79
|
TypeScript
|
Shomrey/Remote-laboratory-engineer-thesis
|
/Server/src/user/error/user-not-found.error.ts
| 2.53125
| 3
|
import {HttpException, HttpStatus} from "@nestjs/common";
export class UserNotFoundError extends HttpException {
constructor(userId: number) {
super(`User with ID ${userId} was not found`, HttpStatus.NOT_FOUND);
}
}
|
c1c968353a285f3ccecde08b2cc6346e8aa51335
|
TypeScript
|
matejanajdanov/Finanse-app
|
/src/resolvers/User.ts
| 2.71875
| 3
|
import {
UseMiddleware,
ObjectType,
Resolver,
Mutation,
Field,
Query,
Ctx,
Arg,
} from "type-graphql";
import { AuthMiddleware } from "../middlewares/authMiddleware";
import { RequestResponseExpress } from "../types";
import { hash, verify } from "argon2";
import { User } from "../entity/User";
@ObjectType()
export class ErrorFieldUser {
@Field()
field: "username" | "password";
@Field()
message: string;
}
@ObjectType()
export class UserResponse {
@Field(() => User, { nullable: true })
user?: User;
@Field(() => [ErrorFieldUser], { nullable: true })
errors?: ErrorFieldUser[];
}
@Resolver()
export class UserResolver {
@Query(() => [User])
async users(): Promise<User[]> {
return await User.find();
}
@Query(() => User, { nullable: true })
async currentUser(
@Ctx() { req, res }: RequestResponseExpress
): Promise<User> {
if (!req.session.userId) return null;
const user = await User.findOne(
{ id: req.session.userId },
{ relations: ["profile", "category"] }
);
return user;
}
@Mutation(() => UserResponse, { nullable: true })
async register(
@Arg("username") username: string,
@Arg("password") password: string,
@Arg("confirmPassword") confirmPassword: string,
@Ctx() { req, res }: RequestResponseExpress
): Promise<UserResponse> {
if (username.length < 6 || username.length > 16) {
return {
errors: [
{
field: "username",
message: "Set username length between 6 and 16 characters",
},
],
};
}
if (
password.length < 6 ||
password.length > 16 ||
password !== confirmPassword
) {
return {
errors: [
{
field: "password",
message: "Set password length between 6 and 16 characters",
},
],
};
}
const user = await User.findOne({ username: username });
if (user) {
return {
errors: [
{
field: "username",
message: "Username aleready exists",
},
],
};
}
const hashPassword = await hash(password);
const newUser = new User();
newUser.username = username;
newUser.password = hashPassword;
await newUser.save();
req.session.userId = newUser.id;
return { user: newUser };
}
@Mutation(() => UserResponse)
async login(
@Arg("username") username: string,
@Arg("password") password: string,
@Ctx() { req, res }: RequestResponseExpress
): Promise<UserResponse> {
if (username.length < 6 || username.length > 16) {
return {
errors: [
{
field: "username",
message: "Set username length 6 char",
},
],
};
}
if (password.length < 6 || password.length > 16) {
return {
errors: [
{
field: "password",
message: "Password is not correct",
},
{
field: "username",
message: "Password is not correct",
},
],
};
}
const user = await User.findOne(
{ username },
{ relations: ["profile", "category"] }
);
if (!user) {
return {
errors: [
{
field: "username",
message: "User doesn't exists",
},
],
};
}
const isVerified = await verify(user.password, password);
if (!isVerified) {
return {
errors: [
{
field: "password",
message: "Password is not correct",
},
],
};
}
req.session.userId = user.id;
return { user };
}
@Mutation(() => Boolean)
@UseMiddleware(AuthMiddleware)
logout(@Ctx() { req }: RequestResponseExpress): Boolean {
req.session.destroy((error) => {
console.log(error);
});
return true;
}
}
|
c772c30274a18b06cdae1f0f0513219148656141
|
TypeScript
|
future4code/Lucas-Campioto
|
/semana19/FutureBook/src/business/usecase/user/deleteFriendshipUC.ts
| 2.75
| 3
|
import { UserDB } from "../../../data/userDataBase";
export class DeleteFriendshipUC {
constructor(private db: UserDB){}
public async execute(input: DeleteFriendshipInput): Promise<DeleteFriendshipOutput>{
try{
await this.db.deleteFriendship(input.userId, input.friendId)
await this.db.deleteFriendship(input.friendId, input.userId)
return { message: "broken friendship"}
}catch(err){
console.log(err)
return { message: "user not found" }
}
}
}
export interface DeleteFriendshipInput{
userId:string,
friendId:string
}
export interface DeleteFriendshipOutput{
message:string
}
|
34635df4ebae0ca582458af4c4126070df7164f0
|
TypeScript
|
dlabaj/patternfly-react
|
/packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/layouts/defaultLayoutFactory.ts
| 2.59375
| 3
|
import {
Graph,
Layout,
LayoutFactory,
ForceLayout,
ColaLayout,
ConcentricLayout,
DagreLayout,
GridLayout,
BreadthFirstLayout
} from '@patternfly/react-topology';
import { ColaGroupsLayout } from '@patternfly/react-topology/dist/esm/layouts/ColaGroupsLayout';
const defaultLayoutFactory: LayoutFactory = (type: string, graph: Graph): Layout | undefined => {
switch (type) {
case 'BreadthFirst':
return new BreadthFirstLayout(graph);
case 'Cola':
return new ColaLayout(graph);
case 'ColaNoForce':
return new ColaLayout(graph, { layoutOnDrag: false });
case 'Concentric':
return new ConcentricLayout(graph);
case 'Dagre':
return new DagreLayout(graph);
case 'Force':
return new ForceLayout(graph);
case 'Grid':
return new GridLayout(graph);
case 'ColaGroups':
return new ColaGroupsLayout(graph, { layoutOnDrag: false });
default:
return new ColaLayout(graph, { layoutOnDrag: false });
}
};
export default defaultLayoutFactory;
|
afb89e1799ff1a2c0f59b57fc077a85b9adf4260
|
TypeScript
|
Simply-divine/Bower_in_Production
|
/production/bower_components/amcharts4/src/.internal/charts/elements/FlowDiagramLink.ts
| 2.640625
| 3
|
/**
* FlowDiagramLink module
*/
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Sprite } from "../../core/Sprite";
import { Container, IContainerProperties, IContainerEvents, IContainerAdapters } from "../../core/Container";
import { FlowDiagramDataItem } from "../types/FlowDiagram";
import { LinearGradient } from "../../core/rendering/fills/LinearGradient";
import { RadialGradient } from "../../core/rendering/fills/RadialGradient";
import { Pattern } from "../../core/rendering/fills/Pattern";
import { registry } from "../../core/Registry";
import { Bullet } from "../elements/Bullet";
import { Color } from "../../core/utils/Color";
import { ListTemplate, ListDisposer } from "../../core/utils/List";
import { Polyline } from "../../core/elements/Polyline";
import { Line } from "../../core/elements/Line";
import { InterfaceColorSet } from "../../core/utils/InterfaceColorSet";
import * as $iter from "../../core/utils/Iterator";
import * as $type from "../../core/utils/Type";
/**
* ============================================================================
* REQUISITES
* ============================================================================
* @hidden
*/
/**
* Defines properties for [[FlowDiagramLink]].
*/
export interface IFlowDiagramLinkProperties extends IContainerProperties {
/**
* [tension description]
*
* @todo Description
*/
tension?: number;
/**
* [startX description]
*
* @todo Description
*/
startX?: number;
/**
* [startY description]
*
* @todo Description
*/
startY?: number;
/**
* [endX description]
*
* @todo Description
*/
endX?: number;
/**
* [endY description]
*
* @todo Description
*/
endY?: number;
/**
* [linkWidth description]
*
* @todo Description
*/
linkWidth?: number;
/**
* [startAngle description]
*
* @todo Description
*/
startAngle?: number;
/**
* [endAngle description]
*
* @todo Description
*/
endAngle?: number;
/**
* Should link be filled with a solid color, color of from node, color of toNode or gradient between node colors.
*/
colorMode?: "solid" | "gradient" | "fromNode" | "toNode";
/**
* [controlPointDistance description]
*
* @todo Description
*/
controlPointDistance?: number;
/**
* [maskBullets description]
*
* @todo Description
*/
maskBullets?: boolean;
/**
* [tooltipLocation description]
*
* @todo Description
*/
tooltipLocation?: number;
}
/**
* Defines events for [[FlowDiagramLink]].
*/
export interface IFlowDiagramLinkEvents extends IContainerEvents { }
/**
* Defines adapters for [[FlowDiagramLink]].
*
* @see {@link Adapter}
*/
export interface IFlowDiagramLinkAdapters extends IContainerAdapters, IFlowDiagramLinkProperties { }
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* This class creates a link (waved color-filled line) between two nodes in a
* Flow Diagram.
*
* @see {@link IFlowDiagramLinkEvents} for a list of available events
* @see {@link IFlowDiagramLinkAdapters} for a list of available Adapters
* @important
*/
export class FlowDiagramLink extends Container {
/**
* Defines available properties.
*/
public _properties!: IFlowDiagramLinkProperties;
/**
* Defines available adapters.
*/
public _adapter!: IFlowDiagramLinkAdapters;
/**
* Defines available events.
*/
public _events!: IFlowDiagramLinkEvents;
/**
* Defines a type of data item used by this class.
*/
public _dataItem: FlowDiagramDataItem;
/**
* A gradiend instance that is used to provided colored gradient fills for
* the Flow link.
*/
protected _gradient: LinearGradient;
/**
* List of bullets
* @ignore
*/
protected _bullets: ListTemplate<Bullet>;
/**
* Link sprite
*/
public link: Sprite;
/**
* Bullets mask spite
*/
protected _bulletsMask: Sprite;
/**
* Bullets container
*/
protected _bulletsContainer: Container;
/**
* Spline which goes through the middle of a link, used to calculate bullet and tooltip positions, invisible by default
*/
public middleLine: Line | Polyline;
/**
* Constructor
*/
constructor() {
super();
this.className = "FlowDiagramLink";
let interfaceColors = new InterfaceColorSet();
this.maskBullets = false;
this.colorMode = "fromNode";
this.layout = "none";
this.isMeasured = false;
this.startAngle = 0;
this.endAngle = 0;
this.strokeOpacity = 0;
// this is very important, otherwise the container will be shifted
this.verticalCenter = "none";
this.horizontalCenter = "none";
this.tooltipText = "{fromName}→{toName}:{value.value}";
this.tooltipLocation = 0.5;
this.link = this.createChild(Sprite);
this.link.shouldClone = false;
this.link.setElement(this.paper.add("path"));
this.link.isMeasured = false;
this.fillOpacity = 0.2;
this.fill = interfaceColors.getFor("alternativeBackground");
this.applyTheme();
}
/**
* Positions bullets
* @ignore
*/
protected positionBullets() {
$iter.each(this.bullets.iterator(), (bullet) => {
bullet.parent = this.bulletsContainer;
bullet.maxWidth = this.maxWidth;
bullet.maxHeight = this.maxHeight;
this.positionBullet(bullet);
})
}
/**
* Bullets container
*/
public get bulletsContainer(){
if(!this._bulletsContainer){
let bulletsContainer = this.createChild(Container);
bulletsContainer.shouldClone = false;
bulletsContainer.layout = "none";
this._bulletsContainer = bulletsContainer;
}
return this._bulletsContainer;
}
/**
* Bullets mask sprite
*/
public get bulletsMask(){
if(!this._bulletsMask){
let bulletsMask = this.createChild(Sprite);
bulletsMask.shouldClone = false;
bulletsMask.setElement(this.paper.add("path"));
bulletsMask.isMeasured = false;
this._bulletsMask = bulletsMask;
}
return this._bulletsMask;
}
/**
* Positions bullets at relative bullet.locationX position on the link.
* @ignore
*/
protected positionBullet(bullet: Bullet) {
let location = bullet.locationX;
if (!$type.isNumber(location)) {
location = bullet.locationY;
}
if (!$type.isNumber(location)) {
location = 0.5;
}
let point = this.middleLine.positionToPoint(location);
bullet.moveTo(point);
let rotationField = bullet.propertyFields.rotation;
let angle: number;
if (bullet.dataItem) {
let dataContext: any = bullet.dataItem.dataContext;
angle = dataContext[rotationField];
}
if (!$type.isNumber(angle)) {
angle = point.angle;
}
bullet.rotation = angle;
}
/**
* [startAngle description]
*
* @todo Description
* @param value Start angle
*/
public set startAngle(value: number) {
this.setPropertyValue("startAngle", value, true);
}
/**
* @return Start angle
*/
public get startAngle(): number {
return this.getPropertyValue("startAngle");
}
/**
* [endAngle description]
*
* @todo Description
* @param value End angle
*/
public set endAngle(value: number) {
this.setPropertyValue("endAngle", value, true);
}
/**
* @return End angle
*/
public get endAngle(): number {
return this.getPropertyValue("endAngle");
}
/**
* Should link be filled with a solid color, color of from node, color of toNode or gradient between node colors.
* Some of the links, like ChordLink does not support gradiens well.
*
* @param value Fill mode
*/
public set colorMode(value: "solid" | "gradient" | "fromNode" | "toNode") {
if (value == "gradient") {
let color = this.fill;
this.gradient.stops.clear();
if(color instanceof Color){
this.gradient.addColor(color);
this.gradient.addColor(color);
}
this.fill = this.gradient;
this.stroke = this.gradient;
}
this.setPropertyValue("colorMode", value, true);
}
/**
* Fill mode
*/
public get colorMode(): "solid" | "gradient" | "fromNode" | "toNode" {
return this.getPropertyValue("colorMode");
}
/**
* Should link bullets be masked or not
*
* @param value
* @default false;
*/
public set maskBullets(value: boolean) {
this.setPropertyValue("maskBullets", value, true);
}
/**
* @return mask bullets value
*/
public get maskBullets(): boolean {
return this.getPropertyValue("maskBullets");
}
/**
* Relative location of a tooltip.
* @default 0.5
*
* @param value
*/
public set tooltipLocation(value: number) {
this.setPropertyValue("tooltipLocation", value, true);
}
/**
* Tooltip location value
*/
public get tooltipLocation(): number {
return this.getPropertyValue("tooltipLocation");
}
/**
* Adds color steps in the link gradient.
*
* @param value Fill option
*/
protected setFill(value: Color | Pattern | LinearGradient | RadialGradient) {
super.setFill(value)
let gradient = this._gradient;
if (gradient && value instanceof Color) {
gradient.stops.clear();
gradient.addColor(value);
gradient.addColor(value);
}
}
/**
* Updates bounding box based on element dimension settings.
*
* @ignore Exclude from docs
*/
public measureElement(): void {
}
/**
* List of bullets
*
* @return [description]
*/
public get bullets(): ListTemplate<Bullet> {
if (!this._bullets) {
this._bullets = new ListTemplate<Bullet>(new Bullet());
this._disposers.push(new ListDisposer(this._bullets));
this._disposers.push(this._bullets.template);
this._bullets.events.on("inserted", (event) => {
event.newValue.events.on("propertychanged", (event) => {
if (event.property == "locationX" || event.property == "locationY") {
this.positionBullet(event.target);
}
}, undefined, false)
}, undefined, false)
}
return this._bullets;
}
/**
* Copies properties from another [[FlowDiagramLink]].
*
* @param source Source link
*/
copyFrom(source: this) {
super.copyFrom(source);
this.bullets.copyFrom(source.bullets);
let middleLine = this.middleLine;
if(middleLine){
if (middleLine instanceof Line && source.middleLine instanceof Line) {
middleLine.copyFrom(source.middleLine);
}
if (middleLine instanceof Polyline && source.middleLine instanceof Polyline) {
middleLine.copyFrom(source.middleLine);
}
}
this.link.copyFrom(source.link);
}
/**
* @ignore Exclude from docs
* @return Tooltip X (px)
*/
getTooltipX(): number {
if (this.middleLine) {
return this.middleLine.positionToPoint(this.tooltipLocation).x;
}
}
/**
* @ignore Exclude from docs
* @return Tooltip Y (px)
*/
getTooltipY(): number {
if (this.middleLine) {
return this.middleLine.positionToPoint(this.tooltipLocation).y;
}
}
/**
* A gradiend instance that is used to provided colored gradient fills for
* the Flow link.
*/
public get gradient(){
if(!this._gradient){
this._gradient = new LinearGradient();
}
return this._gradient;
}
}
/**
* Register class in system, so that it can be instantiated using its name from
* anywhere.
*
* @ignore
*/
registry.registeredClasses["FlowDiagramLink"] = FlowDiagramLink;
|
4a5cf3d883b36c53ac9dfdc5520f9f89ef91cf35
|
TypeScript
|
leomleao/pricingIC
|
/src/users/users.service.ts
| 2.890625
| 3
|
import { Inject, Injectable, BadRequestException} from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';
@Injectable()
export class UsersService {
constructor( @Inject('UserRepositoryToken') private readonly userRepository: Repository<User>) { }
/**
* @param conds is an object with desired conditions, e.g { id: '123 '}
* @return Returns the found user or error response.
*/
async findOne(conds) {
try {
return await this.userRepository.findOne({ where: conds});
} catch (err) {
return err;
}
}
/**
* @param user is the entity User using typeorm definitions
* @return Returns the created user.
*/
async create(user: User) {
const SALT_WORK_FACTOR = 10;
const response = bcrypt.hash(user.password, SALT_WORK_FACTOR).then((hash) => {
const userWithHash = Object.assign({}, user, {
password: hash,
});
return this.userRepository.save(userWithHash);
}).then((userData) => {
userData.id = undefined;
userData.password = undefined;
return userData;
}).catch((err) => {
throw new BadRequestException(err);
});
return response;
}
}
|
2409c4b3cad95c0351572fc9214edc4eb0891938
|
TypeScript
|
kuboosoft/fx_cast
|
/ext/src/lib/options.ts
| 3.3125
| 3
|
"use strict";
import defaultOptions, { Options } from "../defaultOptions";
/**
* Fetches `options` key from storage and returns it as
* Options interface type.
*/
async function getAll (): Promise<Options> {
const { options }: { options: Options } =
await browser.storage.sync.get("options");
return options;
}
/**
* Takes Options object and sets to `options` storage key.
* Returns storage promise.
*/
async function setAll (options: Options): Promise<void> {
return browser.storage.sync.set({ options });
}
/**
* Gets specific option from storage and returns it as its
* type from Options interface type.
*/
async function get<T extends keyof Options> (name: T): Promise<Options[T]> {
const options = await getAll();
if (options.hasOwnProperty(name)) {
return options[name];
}
}
/**
* Sets specific option to storage. Returns storage
* promise.
*/
async function set<T extends keyof Options> (
name: T
, value: Options[T]): Promise<void> {
const options = await getAll();
options[name] = value;
return setAll(options);
}
/**
* Gets existing options from storage and compares it
* against defaults. Any options in defaults and not in
* storage are set. Does not override any existing options.
*/
async function update (defaults = defaultOptions): Promise<void> {
const oldOpts = await getAll();
const newOpts: Partial<Options> = {};
// Find options not already in storage
for (const [ optName, optVal ] of Object.entries(defaults)) {
if (!oldOpts.hasOwnProperty(optName)) {
newOpts[optName] = optVal;
}
}
// Update storage with default values of new options
return setAll({
...oldOpts
, ...newOpts
});
}
export default {
get, getAll
, set, setAll
, update
};
|
eace868b2065d46ca8d865b78ded52766cd2c3c9
|
TypeScript
|
Swiftx/koa-restful-router
|
/src/decorators.ts
| 3.078125
| 3
|
export const RESTfulType = Symbol();
export const RESTfulName = Symbol();
export const RESTfulCheck = Symbol();
export const MethodArgs = Symbol();
/**
* REST资源控制器
* @param {string} path
* @param {Object} where
* @returns {(target: Function) => void}
* @constructor
*/
export const RESTful = (path:string,where?:Object) => (target:Function) =>{
target.prototype[RESTfulType] = true;
target.prototype[RESTfulName] = path;
target.prototype[RESTfulCheck] = where;
};
/**
* GET参数装饰器
* @returns {(target, methodName: string, paramIndex: number) => void}
* @constructor
*/
export const Get = (name?:string) => (target: Object, propertyKey: string | symbol, parameterIndex: number) => {
if(target[propertyKey][MethodArgs] === undefined)
target[propertyKey][MethodArgs] = [];
target[propertyKey][MethodArgs][parameterIndex] = {
from : 'GET',
name : name
}
};
/**
* POST参数装饰器
* @returns {(target, methodName: string, paramIndex: number) => void}
* @constructor
*/
export const Post = (name?:string) => (target: Object, propertyKey: string | symbol, parameterIndex: number) => {
if(target[propertyKey][MethodArgs] === undefined)
target[propertyKey][MethodArgs] = [];
target[propertyKey][MethodArgs][parameterIndex] = {
from : 'POST',
name : name
}
};
/**
* Ctx参数装饰器
* @returns {(target, methodName: string, paramIndex: number) => void}
* @constructor
*/
export const Ctx = (name?:string) => (target: Object, propertyKey: string | symbol, parameterIndex: number) => {
if(target[propertyKey][MethodArgs] === undefined)
target[propertyKey][MethodArgs] = [];
target[propertyKey][MethodArgs][parameterIndex] = {
from : 'Ctx',
name : name
}
};
|
851ae37234b55b16028f95b63a66afbee4cfbc7e
|
TypeScript
|
osharper/SignalR4SimpleWebRtc
|
/Scripts/EventEmitter.ts
| 3.453125
| 3
|
interface IEventEmitter
{
on(eventName: string, callback: (...args: any[]) => void) : IEventEmitter;
emit(eventName: string, ...args: any[]);
off?(eventName: string, exCallback?: Function);
}
class EventEmitter implements IEventEmitter {
protected events: { [event: string]: Function[] } = {};
on(event: string, fn: (...args: any[]) => void) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(fn);
return this;
}
emit(event: string, ...args: any[]) {
if (!this.events[event] || this.events[event].length === 0) return;
for (var i = 0; i < this.events[event].length; i++) {
var fn = this.events[event][i];
fn.apply(this, args);
}
}
off(event: string, fn?: Function) {
if (!this.events[event] || this.events[event].length === 0) return;
if (!fn) {
delete this.events[event];
return;
}
var fnIdx = this.events[event].indexOf(fn);
if (fnIdx === -1) return;
this.events[event].splice(fnIdx, 1);
if (this.events[event].length === 0) delete this.events[event];
}
}
|
d5c936ada3e5d6fef773430f9312a5a7fc6fab53
|
TypeScript
|
thierry-capgemini/jump-the-queue-nextjs
|
/pages/api/visitor.ts
| 2.6875
| 3
|
import {environment} from '../../environments/environment'
import fetch from 'isomorphic-unfetch'
export default async (req, res) => {
// Get data from your database
const { visitor } = await req.body
console.log('visitor was here', visitor)
const baseUrl = environment.baseUrlRestServices;
const url = `${baseUrl}/visitormanagement/v1/visitor`
//try {
// const response = await fetch(url)
const response = await fetch(url,{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(visitor)
})
if (response.status === 200) {
// const { token } = await response.json()
console.log('got here')
// console.log(token);
console.log(response);
// await login({ token }) ok next step
res.status(200).json(response)
} else{
console.log('not 200')
}
// if (response.ok) {
// const { id } = await response.json()
// return res.status(200).json({ token: id })
// } else {
// // https://github.com/developit/unfetch#caveats
// // const error = new Error(response.statusText)
// // error.response = response
// // throw error
// }
// } catch (error) {
// const { response } = error
// return response
// ? res.status(response.status).json({ message: response.statusText })
// : res.status(400).json({ message: error.message })
// }
//res.status(200).json({token: '1'})
}
// export default (req, res) => {
// const {
// query: { id, name },
// method
// } = req
// const baseUrl = environment.baseUrlRestServices;
// `${baseUrl}/visitormanagement/v1/visitor`
// switch (method) {
// case 'GET':
// // Get data from your database
// res.status(200).json({ id, name: `User ${id}` })
// break
// case 'PUT':
// // Update or create data in your database
// res.status(200).json({ id, name: name || `User ${id}` })
// break
// default:
// res.setHeader('Allow', ['GET', 'PUT'])
// res.status(405).end(`Method ${method} Not Allowed`)
// }
// }
// export default async (req, res) => {
// const { visitor } = await req.body
// console.log('visitor', visitor)
// // const url = `https://api.github.com/users/${username}`
// const baseUrl = environment.baseUrlRestServices;
// const url = `${baseUrl}/visitormanagement/v1/visitor`
// try {
// const response = await fetch(url)
// if (response.ok) {
// const { id } = await response.json()
// return res.status(200).json({ token: id })
// } else {
// // https://github.com/developit/unfetch#caveats
// // const error = new Error(response.statusText)
// // error.response = response
// // throw error
// }
// } catch (error) {
// const { response } = error
// return response
// ? res.status(response.status).json({ message: response.statusText })
// : res.status(400).json({ message: error.message })
// }
// }
|
693272fd9000d9c18fc512661b8b60cf2f1ce387
|
TypeScript
|
scottostler/conspirator
|
/test/game.ts
| 2.65625
| 3
|
import { expect } from 'chai';
import * as cards from '../src/cards';
import { Copper, Estate } from '../src/sets/common';
import * as testsupport from './testsupport';
import * as util from '../src/utils';
import expectEqualCards = testsupport.expectEqualCards;
import expectPlayerHandSize = testsupport.expectPlayerHandSize;
var fiveCopperHand = [Copper, Copper, Copper, Copper, Copper];
describe('Game.beginNewTurn', () => {
it('players should discard hand, and draw 5 cards after turn', () => {
const [game, decider1, decider2] = testsupport.setupTwoPlayerGame();
game.start();
const player1Hand = game.activePlayer.hand.cards;
decider1.playTreasures([]);
decider1.buyCard(null);
decider2.playTreasures([]);
expect(game.players[0].getFullDeck()).to.have.lengthOf(10);
expect(cards.asNames(game.inPlay.cards)).to.be.empty;
expectEqualCards(game.players[0].discard.cards, player1Hand);
expect(game.players[0].deck.cards).to.be.empty;
expectPlayerHandSize(game.players[0], 5);
});
});
describe('Game.isExactCardInPlay', () => {
it('should match exact cards in play', () => {
const [game, decider1, decider2] = testsupport.setupTwoPlayerGame(fiveCopperHand);
game.start();
decider1.playTreasures([Copper, Copper, Copper]);
expect(game.inPlay.includes(game.activePlayer.hand.cards[0])).to.be.false;
expect(game.inPlay.includes(game.inPlay.cards[0])).to.be.true;
});
});
|
06f9f0807b7fd6902b11e4522367e7283b06c24d
|
TypeScript
|
yeomann/nestjs-oauth2
|
/src/apps/oauth2/modules/oauth2/utils/index.ts
| 2.671875
| 3
|
import { Response } from 'express';
import { ResponseModes } from '../constants';
import * as qs from 'querystring';
import { AuthRequest } from '../auth.request';
/**
* Handle consent redirect, based on response_mode param
* Available modes:
* * query (default): return the params as querystring
* * fragment: return the params as url fragment
* * form_post: render an html form that auth submit with POST method to the redirect url
* @param res
* @param responseMode
* @param returnTo
* @param params
*/
export const handleResponseMode = (
res: Response,
responseMode: ResponseModes,
returnTo: string,
params: Record<string, any>,
) => {
switch (responseMode) {
case ResponseModes.query:
return res.status(302).redirect(this.makeRedirectUri(returnTo, params));
case ResponseModes.fragment:
return res.status(302).redirect(this.makeRedirectUri(returnTo, undefined, params));
case ResponseModes.form_post:
return res.render('form_post', {
returnTo,
hiddenFields: params,
layout: false,
});
}
}
export const makeRedirectUri = (uri: string, params?: Record<string, any>, hash?: Record<string, any>) => {
const url = new URL(uri);
if (params) {
url.search = qs.stringify(params);
}
if (hash) {
url.hash = qs.stringify(hash);
}
return url.toString();
}
export const getAuthRequestFromSession = (session: any): AuthRequest => {
const authRequest = session.authRequest as AuthRequest;
if (!authRequest) {
throw new Error('Authorization request was not present in the session.');
}
delete session.authRequest;
return authRequest;
}
|