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
|
|---|---|---|---|---|---|---|
385a0a8373ebf0fc851d7ae61a87d4d7b6878077
|
TypeScript
|
dmitrygorkun/athena
|
/src/common/image/image.dto.ts
| 2.625
| 3
|
import {IsNotEmpty, MaxLength} from 'class-validator';
import {Image} from './image.definition';
export const PHOTO_TITLE_LENGTH = 100;
export const PHOTO_LINK_LENGTH = 100;
export class ImageDto implements Image {
@IsNotEmpty()
@MaxLength(PHOTO_TITLE_LENGTH)
alt: string;
@IsNotEmpty()
@MaxLength(PHOTO_TITLE_LENGTH)
title: string;
@IsNotEmpty()
@MaxLength(PHOTO_LINK_LENGTH)
url: string;
}
|
973aea6b0a435a26e81b26e85333e716a9217c5d
|
TypeScript
|
rraziel/es-validation
|
/packages/decorators/src/decorators/Negative.ts
| 2.84375
| 3
|
import { addConstraint } from './addConstraint';
import { ConstraintDecorator } from './ConstraintDecorator';
import { ConstraintProperties } from './ConstraintProperties';
/**
* Negative decorator, used to define that an element must be a negative number
* @param target Target
* @param propertyKey Property key
* @param descriptor Descriptor
*/
const Negative: ConstraintDecorator = <T>(target, propertyKey, descriptor) => {
const constraintProperties: ConstraintProperties<T> = new ConstraintProperties<T>(target, propertyKey, descriptor, 'Negative');
constraintProperties.attributes = {
zero: false
};
addConstraint(constraintProperties);
};
/**
* NegativeOrZero decorator, used to define that an element must be a negative number or zero
* @param target Target
* @param propertyKey Property key
* @param descriptor Descriptor
*/
const NegativeOrZero: ConstraintDecorator = <T>(target, propertyKey, descriptor) => {
const constraintProperties: ConstraintProperties<T> = new ConstraintProperties<T>(target, propertyKey, descriptor, 'Negative');
constraintProperties.decoratorName = 'NegativeOrZero';
constraintProperties.attributes = {
zero: true
};
addConstraint(constraintProperties);
};
export {
Negative,
NegativeOrZero
};
|
a218f772819db8c8fb810c936a2516323836a4f4
|
TypeScript
|
Yalm/cdiego
|
/src/products/entities/product.entity.ts
| 2.515625
| 3
|
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { Category } from 'src/categories/entities/category.entity';
import { OrderToProduct } from 'src/orders/entities/order-detail.entity';
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 300 })
name: string;
@Column()
price: number;
@Column({ length: 191 })
cover: string;
@Column()
stock: number;
@Column({ length: 400 })
shortDescription: string;
@Column()
description?: string;
@Column({ default: true })
status: boolean;
@ManyToOne(() => Category, category => category.products)
category: Category;
@OneToMany(() => OrderToProduct, orderToProduct => orderToProduct.product)
orderToProducts!: OrderToProduct[];
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
|
52454a360c83317082be69427bbeede43abe99b8
|
TypeScript
|
EmilSroka/ESE-evaluator
|
/apps/api/src/app/utils/neo4j/props-stringify.ts
| 3.234375
| 3
|
export function propsStringify(object: Record<string, any>): string {
const items = [];
for (const [key, value] of Object.entries(object)) {
if (isObjectOrFunction(value))
throw new Error(`Cannot stringify ${value} to neo4j format`);
if (hasSpace(key)) throw new Error(`Key "${key}" contains space`);
const item = `${key}: ${JSON.stringify(value)}`;
items.push(item);
}
return `{ ${items.join(', ')} }`;
}
export function isObjectOrFunction(value: any): boolean {
if (value != null && typeof value === 'object') return true;
return typeof value === 'function';
}
export function hasSpace(value: string): boolean {
return / /.test(value);
}
|
ad63ae9464843aaffdb63914b1e23fbcc3c1ee05
|
TypeScript
|
tbaraza/solution
|
/src/app/services/tariff/tariff.service.ts
| 2.765625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError, of, Observable } from 'rxjs';
// TO DO: Move this to a type file
export type Tariff = {
id: number,
name: string,
speed: {
downloadSpeed: number,
uploadSpeed: number,
metric: string
},
price: number,
benefits: string[]
}
export type FilterCriteria = 'recommended' | 'downloadSpeed' | 'uploadSpeed' | 'price';
@Injectable({
providedIn: 'root'
})
export class TariffService {
constructor(
private http: HttpClient
) {}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: better job of transforming error for user consumption
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
getTariffs() {
return this.http.get('/assets/tariffs.json')
.pipe(catchError(() => {
return throwError(this.handleError('fetching tariffs', of([])));
}));
}
sortTariffs(tariffs: Tariff[], criteria: FilterCriteria) {
if (criteria === 'uploadSpeed' || criteria === 'downloadSpeed') {
return tariffs.sort((a: Tariff, b: Tariff) => a.speed[criteria] - b.speed[criteria]);
} else if (criteria === 'price') {
return tariffs.sort((a: Tariff, b: Tariff) => a[criteria] - b[criteria]);
} else {
throw new Error('Invalid sort criteria');
}
}
}
|
ab59115829f83506630063e7b1d6ed3a7a2d6ab4
|
TypeScript
|
actions/download-artifact
|
/src/download-artifact.ts
| 2.921875
| 3
|
import * as core from '@actions/core'
import * as artifact from '@actions/artifact'
import * as os from 'os'
import {resolve} from 'path'
import {Inputs, Outputs} from './constants'
async function run(): Promise<void> {
try {
const name = core.getInput(Inputs.Name, {required: false})
const path = core.getInput(Inputs.Path, {required: false})
let resolvedPath
// resolve tilde expansions, path.replace only replaces the first occurrence of a pattern
if (path.startsWith(`~`)) {
resolvedPath = resolve(path.replace('~', os.homedir()))
} else {
resolvedPath = resolve(path)
}
core.debug(`Resolved path is ${resolvedPath}`)
const artifactClient = artifact.create()
if (!name) {
// download all artifacts
core.info('No artifact name specified, downloading all artifacts')
core.info(
'Creating an extra directory for each artifact that is being downloaded'
)
const downloadResponse = await artifactClient.downloadAllArtifacts(
resolvedPath
)
core.info(`There were ${downloadResponse.length} artifacts downloaded`)
for (const artifact of downloadResponse) {
core.info(
`Artifact ${artifact.artifactName} was downloaded to ${artifact.downloadPath}`
)
}
} else {
// download a single artifact
core.info(`Starting download for ${name}`)
const downloadOptions = {
createArtifactFolder: false
}
const downloadResponse = await artifactClient.downloadArtifact(
name,
resolvedPath,
downloadOptions
)
core.info(
`Artifact ${downloadResponse.artifactName} was downloaded to ${downloadResponse.downloadPath}`
)
}
// output the directory that the artifact(s) was/were downloaded to
// if no path is provided, an empty string resolves to the current working directory
core.setOutput(Outputs.DownloadPath, resolvedPath)
core.info('Artifact download has finished successfully')
} catch (err) {
core.setFailed(err.message)
}
}
run()
|
f013f5a2447a55d5f223b911231064ebc7301e03
|
TypeScript
|
tingdahaideshengyin/chat
|
/client/src/core/view/pannel/mediator/PomeloTestMediator.ts
| 2.671875
| 3
|
module game {
export class PomeloTestMediator extends BaseMediator{
public static NAME:string = "PomeloTestMediator";
public constructor(viewComponet: any = null) {
super(PomeloTestMediator.NAME, viewComponet);
}
//重写消息列表
public listNotificationInterests():Array<any>{
return [
PanelNotify.OPEN_POMELO,
PanelNotify.CLOSE_POMELO
];
}
//重写消息处理
private pomeloTest:PomeloTest = new PomeloTest();
public handleNotification(notification: puremvc.INotification):void
{
switch(notification.getName()){
case PanelNotify.OPEN_POMELO:
//显示消息面板
this.showUI(this.pomeloTest, false, 0, 0, 1);
break;
case PanelNotify.CLOSE_POMELO:
//关闭消息面板
this.closePanel(1);
break;
case SysNotify.SERVER_BACK_DATA:
//服务器返回结果
var data: any = notification.getBody();
//接收到消息
if(data == ""){
return;
}
this.onServerBackData(data);
break;
}
}
/*-----------------------------------------------------------------------------------------
初始化UI
-----------------------------------------------------------------------------------------*/
public initUI():void{
//连接按钮
this.pomeloTest.conectButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.connectToserver, this);
//断开按钮
this.pomeloTest.stopButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onStopButtonTouch, this)
//关闭按钮
this.pomeloTest.closeButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onCloseBtnTouch, this);
}
//-------------------------------------------------------------------------------------------
//发送登陆消息
//-------------------------------------------------------------------------------------------
private connectToserver():void{
var host:string = "192.168.1.222";
var port:number = 3010;
pomelo.PomeloSocker.connectServer(host, port);
}
//断开按钮
private onStopButtonTouch():void{
pomelo.PomeloSocker.closeNet();
}
//-------------------------------------------------------------------------------------------
//关闭按钮
//-------------------------------------------------------------------------------------------
private onCloseBtnTouch():void{
this.closePanel(1);
//下面的方法也可行,但是发送消息,多用于不同对象(class)之间的通信
//如果是相同对象,直接调用本对象方法更容易
//this.facade().sendNotification(PanelNotify.CLOSE_MAP);
//this.sendNotification(PanelNotify.CLOSE_MAP);
}
//-------------------------------------------------------------------------------------------
//收到服务器消息
//-------------------------------------------------------------------------------------------
private onServerBackData(data:any):void{
this.pomeloTest.showText.text = <string>data;
}
}
}
|
b6392075046a11a4a58993a2e1309ddff648de71
|
TypeScript
|
geetanaik/Shopping-cart-5.0
|
/src/app/service/auth.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { User } from '../model/user.model';
import { Http, RequestOptions, Headers } from "@angular/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import { AppResponse } from "../model/app-response";
import { AppSettings } from '../config/app.settings';
import { SignUp } from '../model/signup.model';
@Injectable()
export class AuthService {
public token:string;
constructor(private http:Http) {
// set token if saved in local storage
//This will be helpful when ever we refresh page
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
/**
*
* @param mid mongoid given to the added product
* by the mongodb database
*/
//public authUser(user:User) : Observable<AppResponse> {
public authUser(user:User) : Observable<SignUp>{
//step is normal response
//console.log("mid = "+mid);
console.log("_@_@_@Uploading produc data!");
console.log(user);
//setting data into post
var options = new RequestOptions({
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'})
});
// first - URI
//second //product =body
//third options =header
// let step=this.http.post("http://localhost:3000/v1/auth",user,options);
//let step=this.http.post(AppSettings.API_ENDPOINT+'/auth',user,options );
let step=this.http.post(AppSettings.AUTH_ENDPOINT+"/auth",user,options); //going to authenticate and generate token
//Now we have to read response as json
//jsonData hold arary of JavaScript object
//var data={status:"success",message:"Hey! your profile has been deleted successfully into the database!!!!!!!!!!!!!!!"};
//res.json(data);
let jsonData=step.map((response) => response.json());
return jsonData;
}
//public signupUser(signup:)
/**
*
* @param mid mongoid given to the added product
* by the mongodb database
*/
public signupUser(signup:SignUp) : Observable<AppResponse> {
//setting data into post
var options = new RequestOptions({
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'})
});
// first - URI
//second //product =body
//third options =header
//let step=this.http.post(AppSettings.API_ENDPOINT+"/signup",signup,options);
let step=this.http.post(AppSettings.AUTH_ENDPOINT+"/signup",signup,options);
//Now we have to read response as json
//jsonData hold arary of JavaScript object
//var data={status:"success",message:"Hey! your profile has been deleted successfully into the database!!!!!!!!!!!!!!!"};
//res.json(data);
//export class AppResponse {
///public status:string;
//public message:string;
///}
//{status:"success",message:"Hey! your profile has been deleted successfully into the database!!!!!!!!!!!!!!!"};
let jsonData=step.map((response) => response.json());
return jsonData;
}
}
|
4f32b4c05108328630a3b776ac3302699a500eb6
|
TypeScript
|
markusbohl/hexa-contacts
|
/src/frameworkLayer/validators/NewContactDataValidator.ts
| 2.828125
| 3
|
/* tslint:disable */
import {AbstractValidator} from 'fluent-ts-validator';
import {injectable} from 'inversify';
@injectable()
export class NewContactDataValidator extends AbstractValidator<any> {
constructor() {
super();
this.validateIfAny(data => data.firstName)
.isString()
.when(data => data.firstName != null)
.withFailureMessage('firstName must be of type string');
this.validateIfAny(data => data.lastName)
.isString()
.when(data => data.lastName != null)
.withFailureMessage('lastName must be of type string');
this.validateIfAny(data => data.email)
.isString()
.isEmail()
.when(data => data.email != null && data.email !== '')
.withFailureMessage('email must be a valid email-address');
this.validateIfAny(data => data.dateOfBirth)
.isString()
.matches(/\d{4}-\d{2}-\d{2}/)
.when(data => data.dateOfBirth != null && data.dateOfBirth !== '')
.withFailureMessage('dateOfBirth-format must be YYYY-MM-DD');
}
}
|
50351c538c03a3d9759ccaa154440daedc02db2f
|
TypeScript
|
vvtstrain/vite-plugin-externals
|
/src/utils.ts
| 2.65625
| 3
|
export function isObject(o: unknown):boolean {
return Object.prototype.toString.call(o) === '[object Object]'
}
|
b95aff124c675b41f74d12964886f3734b55d4d5
|
TypeScript
|
GetStream/stream-js
|
/src/personalization.ts
| 2.90625
| 3
|
import { StreamClient, APIResponse, UR, DefaultGenerics } from './client';
/**
* Manage api calls for personalization
* The collection object contains convenience functions such as get, post, delete
* @class Personalization
*/
export type PersonalizationAPIResponse<StreamFeedGenerics extends DefaultGenerics = DefaultGenerics> = APIResponse & {
app_id: string;
next: string;
results: Array<StreamFeedGenerics['personalizationType']>;
limit?: number;
offset?: number;
version?: string;
};
export class Personalization<StreamFeedGenerics extends DefaultGenerics = DefaultGenerics> {
client: StreamClient<StreamFeedGenerics>;
/**
* Initialize the Personalization class
* @link https://getstream.io/activity-feeds/docs/node/personalization_introduction/?language=js
* @method constructor
* @memberof Personalization.prototype
* @param {StreamClient} client - The stream client
*/
constructor(client: StreamClient<StreamFeedGenerics>) {
this.client = client;
}
/**
* Get personalized activities for this feed
*
* @method get
* @memberof Personalization.prototype
* @param {string} resource - personalized resource endpoint i.e "follow_recommendations"
* @param {object} options Additional options
* @return {Promise<PersonalizationAPIResponse<StreamFeedGenerics>>} Promise object. Personalized feed
* @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'})
*/
get(resource: string, options: Record<string, string> & { token?: string } = {}) {
return this.client.get<PersonalizationAPIResponse<StreamFeedGenerics>>({
url: `${resource}/`,
serviceName: 'personalization',
qs: options,
token: options.token || this.client.getPersonalizationToken(),
});
}
/**
* Post data to personalization endpoint
*
* @method post
* @memberof Personalization.prototype
* @param {string} resource - personalized resource endpoint i.e "follow_recommendations"
* @param {object} options - Additional options
* @param {object} data - Data to send in the payload
* @return {Promise<PersonalizationAPIResponse<StreamFeedGenerics>>} Promise object. Data that was posted if successful, or an error.
* @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'})
*/
post(resource: string, options: Record<string, string> = {}, data: UR = {}) {
return this.client.post<PersonalizationAPIResponse<StreamFeedGenerics>>({
url: `${resource}/`,
serviceName: 'personalization',
qs: options,
body: data,
token: this.client.getPersonalizationToken(),
});
}
/**
* Delete metadata or activities
*
* @method delete
* @memberof Personalization.prototype
* @param {object} resource - personalized resource endpoint i.e "follow_recommendations"
* @param {object} options - Additional options
* @return {Promise<PersonalizationAPIResponse<StreamFeedGenerics>>} Promise object. Data that was deleted if successful, or an error.
* @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'})
*/
delete(resource: string, options: Record<string, string> = {}) {
return this.client.delete<PersonalizationAPIResponse<StreamFeedGenerics>>({
url: `${resource}/`,
serviceName: 'personalization',
qs: options,
token: this.client.getPersonalizationToken(),
});
}
}
|
9179b55f1ff26b022a08e1c719620d839dce9bbd
|
TypeScript
|
blockframes/blockframes
|
/libs/utils/src/lib/form/forms/form-field-list.form.ts
| 2.8125
| 3
|
import { FormArray, FormControl, FormGroup } from '@angular/forms';
// DISCLAIMER
// THIS IS A DRAFT, PLEASE DO NOT USE OR EDIT
export class FormFieldList extends FormGroup {
constructor(private defaultTemplate) {
super({
first: new FormControl(),
list: new FormArray([]),
})
}
get first() {
return this.get('first');
}
get list() {
return this.get('list') as FormArray;
}
get value() {
if (!this.isDefault(this.first.value)) {
return [ this.first.value, ...this.list.value ]
} else {
return this.list.value.filter(v => !this.isDefault(v));
}
}
isDefault(value): boolean {
return deepEqual(this.defaultTemplate, value);
}
add(value) {
if (!this.first.value) {
this.first.setValue(value);
} else {
this.list.push(new FormControl(value));
}
}
push(control: AbstractControl): void {
if (this.isDefault(this.first.value)) {
this.first.setValue(control.value);
} else {
this.list.push(control);
}
}
insert(index: number, control: AbstractControl): void {
if (index === 0) {
const firstValue = this.first.value;
this.list.insert(0, new FormControl(firstValue));
this.first.setValue(control.value);
} else {
this.list.insert(index - 1, control);
}
}
at(index) {
return index === 0
? this.first
: this.list.at(index - 1);
}
removeAt(index: number) {
if (index === 0) {
if (this.list.controls.length) {
const control = this.list.at(0);
this.list.removeAt(0)
this.first.reset(control.value);
} else {
this.first.reset();
}
} else {
this.list.removeAt(index - 1);
}
}
setControl(index: number, control: AbstractControl): void {
if (index === 0) {
this.first.setValue(control.value);
} else {
this.list.setControl(index - 1, control);
}
}
setValue(value: any[]) {
this.first.setValue(value.shift());
this.list.setValue(value);
}
patchValue(value: any[]): void {
this.first.patchValue(value.shift());
this.list.patchValue(value);
}
reset(value: any = []): void {
this.first.reset(value.shift());
this.list.reset(value);
}
getRawValue(): any[] {
if (!this.isDefault(this.first.value)) {
return [ this.first.value, ...this.list.value ]
} else {
return this.list.getRawValue().filter(v => !this.isDefault(v));
}
}
clear(): void {
this.first.reset();
this.list.clear();
}
}
|
9fd254ba32014392fb64a45a42d9fa6db42a96a8
|
TypeScript
|
geoffb/jamuary-2018
|
/lib/sim/Entity.ts
| 2.8125
| 3
|
import { IRectangle } from "./math";
export class Entity implements IRectangle {
x = 0;
y = 0;
width = 16;
height = 16;
health = 1;
vx = 0;
vy = 0;
speed = 60;
dx = 0;
sprite = -1;
jumpImpulse = -125;
private jumpCount = 0;
public get right(): number {
return this.x + this.width;
}
public get bottom(): number {
return this.y + this.height;
}
public jump() {
if (this.jumpCount > 0) { return; }
this.vy += this.jumpImpulse;
this.jumpCount++;
}
public land() {
this.jumpCount = 0;
}
}
|
897529ae71f6d1411478cb2585ae8301c9d744cc
|
TypeScript
|
uninitlzd/vite-plugin-markdown
|
/src/index.ts
| 2.703125
| 3
|
import Frontmatter from 'front-matter'
import MarkdownIt from 'markdown-it'
import { Transform, Plugin } from 'vite'
import { parseDOM, DomUtils } from 'htmlparser2'
import { Element, Node as DomHandlerNode } from 'domhandler'
export enum Mode {
TOC = "toc",
HTML = "html",
REACT = "react",
VUE = "vue"
}
export interface PluginOptions {
mode?: Mode[]
markdown?: (body: string) => string
markdownIt?: MarkdownIt | MarkdownIt.Options
}
const markdownCompiler = (options: PluginOptions): MarkdownIt | { render: (body: string) => string } => {
if (options.markdownIt) {
if (options.markdownIt instanceof MarkdownIt || (options.markdownIt?.constructor?.name === 'MarkdownIt')) {
return options.markdownIt as MarkdownIt
} else if (typeof options.markdownIt === 'object') {
return MarkdownIt(options.markdownIt)
}
} else if (options.markdown) {
return { render: options.markdown }
}
return MarkdownIt({ html: true, xhtmlOut: options.mode?.includes(Mode.REACT) })
}
class ExportedContent {
#exports: string[] = []
#contextCode = ''
addContext (contextCode: string): void {
this.#contextCode += `${contextCode}\n`
}
addExporting (exported: string): void {
this.#exports.push(exported)
}
export (): string {
return [this.#contextCode, `export { ${this.#exports.join(', ')} }`].join('\n')
}
}
const transform = (options: PluginOptions): Transform => {
return {
test: ({ path }) => path.endsWith('.md'),
transform: ({ code, path }) => {
const content = new ExportedContent()
const fm = Frontmatter<unknown>(code)
content.addContext(`const attributes = ${JSON.stringify(fm.attributes)}`)
content.addExporting('attributes')
const html = markdownCompiler(options).render(fm.body)
if (options.mode?.includes(Mode.HTML)) {
content.addContext(`const html = ${JSON.stringify(html)}`)
content.addExporting('html')
}
if (options.mode?.includes(Mode.TOC)) {
const root = parseDOM(html)
const indicies = root.filter(
rootSibling => rootSibling instanceof Element && ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(rootSibling.tagName)
) as Element[]
const toc: { level: string; content: string }[] = indicies.map(index => ({
level: index.tagName.replace('h', ''),
content: DomUtils.getInnerHTML(index)
}))
content.addContext(`const toc = ${JSON.stringify(toc)}`)
content.addExporting('toc')
}
if (options.mode?.includes(Mode.REACT)) {
const root = parseDOM(html, { lowerCaseTags: false })
const subComponentNamespace = 'SubReactComponent'
const markCodeAsPre = (node: DomHandlerNode): void => {
if (node instanceof Element) {
if (node.tagName.match(/^[A-Z].+/)) {
node.tagName = `${subComponentNamespace}.${node.tagName}`
}
if (['pre', 'code'].includes(node.tagName) && node.attribs?.class) {
node.attribs.className = node.attribs.class
delete node.attribs.class
}
if (node.tagName === 'code') {
const codeContent = DomUtils.getInnerHTML(node)
node.attribs.dangerouslySetInnerHTML = `vfm{{ __html: \`${codeContent.replace(/([\\`])/g, "\\$1")}\`}}vfm`
node.childNodes = []
}
if (node.childNodes.length > 0) {
node.childNodes.forEach(markCodeAsPre)
}
}
}
root.forEach(markCodeAsPre)
const h = DomUtils.getOuterHTML(root).replace(/"vfm{{/g, '{{').replace(/}}vfm"/g, '}}')
const reactCode = `
const markdown =
<div>
${h}
</div>
`
const compiledReactCode = `
function (props) {
Object.keys(props).forEach(function (key) {
SubReactComponent[key] = props[key]
})
${require('@babel/core').transformSync(reactCode, { ast: false, presets: ['@babel/preset-react'] }).code}
return markdown
}
`
content.addContext(`import React from "react"\nconst ${subComponentNamespace} = {}\nconst ReactComponent = ${compiledReactCode}`)
content.addExporting('ReactComponent')
}
if (options.mode?.includes(Mode.VUE)) {
const root = parseDOM(html)
// Top-level <pre> tags become <pre v-pre>
root.forEach((node: DomHandlerNode) => {
if (node instanceof Element) {
if (['pre', 'code'].includes(node.tagName)) {
node.attribs['v-pre'] = 'true'
}
}
})
// Any <code> tag becomes <code v-pre> excepting under `<pre>`
const markCodeAsPre = (node: DomHandlerNode): void => {
if (node instanceof Element) {
if (node.tagName === 'code') node.attribs['v-pre'] = 'true'
if (node.childNodes.length > 0) node.childNodes.forEach(markCodeAsPre)
}
}
root.forEach(markCodeAsPre)
const { code: compiledVueCode } = require('@vue/compiler-sfc').compileTemplate({ source: DomUtils.getOuterHTML(root), filename: path })
content.addContext(compiledVueCode.replace('\nexport function render(', '\nfunction vueRender(') + `\nconst VueComponent = { render: vueRender }\nVueComponent.__hmrId = ${JSON.stringify(path)}\nconst VueComponentWith = (components) => ({ components, render: vueRender })\n`)
content.addExporting('VueComponent')
content.addExporting('VueComponentWith')
}
return {
code: content.export()
}
}
}
}
export const plugin = (options: PluginOptions = {}): Plugin => {
return {
transforms: [transform(options)]
}
}
export default plugin
exports.default = plugin
|
2b979d89a6816cbe8dbe6cc470ffbcf52055401d
|
TypeScript
|
aleclofabbro/marbles
|
/src/lib/utils/action-proxy/emitAction.ts
| 2.71875
| 3
|
import { abstractProxy } from './abstractProxy';
import StrictEventEmitter from 'strict-event-emitter-types';
import { EventEmitter } from 'events';
type Emitter<T> = StrictEventEmitter<EventEmitter, T>
export const emitAction = <T extends { [key: string]: (...args: any[]) => any }>(emitter: Emitter<T>) => {
return abstractProxy<T>(
(prop) =>
(...args: any) => `string` === typeof prop &&
emitter.emit(prop, ...args))
}
|
cd6cab639db99e66010fa6f1de38c82a61bc2bf3
|
TypeScript
|
rontian/navmesh
|
/packages/navmesh/src/nav-mesh.test.ts
| 3.421875
| 3
|
import NavMesh from "./navmesh";
import Vector2 from "./math/vector-2";
const v2 = (x: number, y: number) => new Vector2(x, y);
describe("An empty NavMesh instance", () => {
let emptyNavMesh: NavMesh;
beforeAll(() => (emptyNavMesh = new NavMesh([])));
it("should not throw an error on construction", () => {
expect(() => emptyNavMesh).not.toThrow();
});
it("should always return null when queried for a path", () => {
const path = emptyNavMesh.findPath(v2(10, 20), v2(30, 50));
expect(path).toBeNull();
});
});
describe("A simple, fully connected NavMesh instance", () => {
let navMesh: NavMesh;
/*
- - - - -
- 1 - 2 -
- - - - -
*/
// prettier-ignore
const polygons = [
[v2(0,0), v2(10,0), v2(10,10), v2(0,10)], // 1
[v2(10,0), v2(20,0), v2(20,10), v2(10,10)] // 2
];
beforeAll(() => (navMesh = new NavMesh(polygons)));
it("should return a direct path when points are in the same polygon", () => {
const path = navMesh.findPath(v2(0, 0), v2(5, 5));
expect(path).toEqual([v2(0, 0), v2(5, 5)]);
});
it("should return null when a point is outside all polygon", () => {
const path = navMesh.findPath(v2(-10, 0), v2(5, 5));
expect(path).toBeNull();
});
it("should return a path when points are in neighboring polygons", () => {
const path = navMesh.findPath(v2(5, 5), v2(15, 5));
expect(path).toEqual([v2(5, 5), v2(15, 5)]);
});
it("should return a path when points are on the edges of the polygons", () => {
const path = navMesh.findPath(v2(0, 0), v2(20, 10));
expect(path).toEqual([v2(0, 0), v2(20, 10)]);
});
});
describe("A NavMesh instance with two islands", () => {
let navMesh: NavMesh;
/*
- - - - - -
- 1 - - 2 -
- - - - - -
*/
// prettier-ignore
const polygons = [
[v2(0,0), v2(10,0), v2(10,10), v2(0,10)], // 1
[v2(40,0), v2(50,0), v2(50,10), v2(40,10)], // 2
];
beforeAll(() => (navMesh = new NavMesh(polygons)));
it("should return null when queried for a path between islands", () => {
const path = navMesh.findPath(v2(0, 0), v2(40, 0));
expect(path).toBeNull();
});
});
describe("A NavMesh instance with a corner", () => {
let navMesh: NavMesh;
/*
- - - - -
- 1 - 2 -
- - - - -
- 3 -
- - -
*/
// prettier-ignore
const polygons = [
[v2(0,0), v2(10,0), v2(10,10), v2(0,10)], // 1
[v2(10,0), v2(20,0), v2(20,10), v2(10,10)], // 2
[v2(10,10), v2(20,10), v2(20,20), v2(10,20)] // 3
];
beforeAll(() => (navMesh = new NavMesh(polygons)));
it("should return a path that hugs the corner", () => {
const path = navMesh.findPath(v2(0, 0), v2(10, 20));
expect(path).toEqual([v2(0, 0), v2(10, 10), v2(10, 20)]);
});
});
describe("isPointInMesh", () => {
let navMesh: NavMesh;
/*
- - - - - - - -
- 1 - 2 - - 4 -
- - - - - - - -
- 3 -
- - -
*/
// prettier-ignore
const polygons = [
[v2(0,0), v2(10,0), v2(10,10), v2(0,10)], // 1
[v2(10,0), v2(20,0), v2(20,10), v2(10,10)], // 2
[v2(10,10), v2(20,10), v2(20,20), v2(10,20)], // 3
[v2(30,0), v2(40,0), v2(40,10), v2(30,10)] // 4
];
beforeAll(() => (navMesh = new NavMesh(polygons)));
it("should return true if point is on the edge of a polygon", () => {
expect(navMesh.isPointInMesh(v2(0, 0))).toEqual(true);
expect(navMesh.isPointInMesh(v2(10, 0))).toEqual(true);
expect(navMesh.isPointInMesh(v2(10, 10))).toEqual(true);
expect(navMesh.isPointInMesh(v2(40, 10))).toEqual(true);
});
it("should return true if point is in a polygon in the mesh", () => {
expect(navMesh.isPointInMesh(v2(5, 5))).toEqual(true);
expect(navMesh.isPointInMesh(v2(10, 5))).toEqual(true);
expect(navMesh.isPointInMesh(v2(32, 2))).toEqual(true);
});
it("should return false for a point outside the mesh", () => {
expect(navMesh.isPointInMesh(v2(-10, -20))).toEqual(false);
expect(navMesh.isPointInMesh(v2(25, 0))).toEqual(false);
expect(navMesh.isPointInMesh(v2(300, 100))).toEqual(false);
});
});
describe("findClosestMeshPoint", () => {
let navMesh: NavMesh;
/*
- - - - - - - -
- 1 - 2 - - 4 -
- - - - - - - -
- 3 -
- - -
*/
// prettier-ignore
const polygons = [
[v2(0,0), v2(10,0), v2(10,10), v2(0,10)], // 1
[v2(10,0), v2(20,0), v2(20,10), v2(10,10)], // 2
[v2(10,10), v2(20,10), v2(20,20), v2(10,20)], // 3
[v2(30,0), v2(40,0), v2(40,10), v2(30,10)] // 4
];
beforeAll(() => (navMesh = new NavMesh(polygons)));
it("should return null for points outside of the max distance", () => {
expect(navMesh.findClosestMeshPoint(v2(-100, 0), 10).polygon).toBeNull();
});
it("should return poly 1 for point inside poly 1", () => {
const result = navMesh.findClosestMeshPoint(v2(5, 5));
expect(result?.polygon?.id).toBe(0);
expect(result?.point).toEqual({ x: 5, y: 5 });
});
it("should return poly 1 or 2 for point on shared edge between poly 1 and 2", () => {
const result = navMesh.findClosestMeshPoint(v2(10, 5));
expect(result?.polygon?.id).toBeGreaterThanOrEqual(0);
expect(result?.polygon?.id).toBeLessThanOrEqual(1);
});
it("should return top left corner of poly 1 for a point just outside of top left corner", () => {
const result = navMesh.findClosestMeshPoint(v2(-10, -10));
expect(result?.point).toEqual({ x: 0, y: 0 });
});
it("should return top middle of poly 1 for a point just outside of top middle", () => {
const result = navMesh.findClosestMeshPoint(v2(-10, 5));
expect(result?.point).toEqual({ x: 0, y: 5 });
});
it("should return poly 2 or 4 for a point equidistant from them", () => {
const result = navMesh.findClosestMeshPoint(v2(25, 5));
const isPoly2or4 = result?.polygon?.id === 1 || result?.polygon?.id === 3;
expect(isPoly2or4).toBe(true);
});
});
|
816b3ec4f5cfd1d0952f5f207664c72e6928f17c
|
TypeScript
|
nehagupta84/stalk-opentracing-js
|
/tutorials/09-context-propagation-ts-decorators/src/client.ts
| 2.609375
| 3
|
import { opentracing, stalk } from '../../../';
import fetch from 'node-fetch';
const sleep = (duration: number) => new Promise(resolve => setTimeout(resolve, duration));
// Let's require our decorators
const { Tag, Component } = stalk.decorators.Tag;
const { Trace, TraceAsync } = stalk.decorators.Trace;
/**
* Set-up stalk tracer with jaeger reporter.
*/
const stalkTracer = new stalk.Tracer();
opentracing.initGlobalTracer(stalkTracer);
const globalTracer = opentracing.globalTracer();
const jaegerReporter = new stalk.reporters.JaegerReporter({
jaegerBaseUrl: 'http://localhost:14268',
process: {
serviceName: 'my-awesome-client',
tags: { }
},
fetch: fetch as any,
});
stalkTracer.addReporter(jaegerReporter);
setInterval(() => jaegerReporter.report(), 1000);
/**
* Main function, wrapped with a class
*/
class ClientDemo {
@TraceAsync({ relation: 'newTrace' })
async main(span: opentracing.Span) {
span.log({ message: 'doing some serious fake calculation' });
await sleep(250);
span.log({ message: 'Phew, now lets send request to server' });
// Injection is still the same way
const headers = {};
stalkTracer.inject(span, opentracing.FORMAT_TEXT_MAP, headers);
// stalkTracer.inject(span, stalk.formats.JaegerFormatName, headers);
// stalkTracer.inject(span, stalk.formats.ZipkinB3FormatName, headers);
try {
const response = await fetch(`http://localhost:3000/endpoint`, { headers });
const text = await response.text();
console.log(`Got response from server: ${text}`);
} catch (err) {
console.error(err);
span.log({ event: 'error', message: err.message, stack: err.stack, 'error.kind': err.name })
span.setTag('error', true);
}
}
}
const demo = new ClientDemo();
demo.main(null);
|
b57cf9a7a06e5fa4dedca8e59ffb6c9225283408
|
TypeScript
|
jamesfer/functional-validator
|
/src/make-constraint.ts
| 3.1875
| 3
|
import { isFunction } from 'lodash-es';
import { castPromise, MaybePromise } from './utils';
/**
* A rule message function is a way to create dynamic messages based on the user's input.
*/
export type RuleMessageFn<P = void> = (
value: any,
options: ConstraintOptions,
params: P,
) => string;
/**
* A rule's message can be a simple string, or a function that accepts the extra options that
* the validator passed to it.
*/
export type RuleMessage<P = void> = string | RuleMessageFn<P>;
/**
* The options that are passed to a constraint when it is evaluated against some data.
*/
export interface ConstraintOptions {
key: string;
keyPath: string[];
parent: any;
root: any;
}
/**
* The options that can be passed to the make constraint function.
*/
export interface GlobalOptions<P = void> {
message?: RuleMessage<P>;
}
/**
* A constraint is a single check run against the data to confirm that it is valid.
*/
export type Constraint<P = void> = (
value: any,
options: ConstraintOptions,
params: P,
) => MaybePromise<boolean>;
/**
* Validation function that returns multiple messages
*/
export type GroupConstraint<T> = (
value: any,
options: ConstraintOptions,
) => MaybePromise<T | undefined>;
/**
* An internal constraint the function that is actually run by the validator. It usually wraps a
* constraint and handles evaluating the message function.
*/
export type InternalConstraint = GroupConstraint<string>;
/**
* Evaluates a message function to produce a string.
*/
function produceMessage<P>(
message: RuleMessage<P> | undefined,
value: any,
options: ConstraintOptions,
params: P,
): string | undefined {
return isFunction(message) ? message(value, options, params) : message;
}
/**
* Constructs an internal constraint function. This is used by rules to produce a function that can
* be run by the validator.
*/
/* tslint:disable max-line-length */
export function makeConstraint(options: { message: RuleMessage<undefined>, constraint: Constraint<undefined> }): InternalConstraint;
export function makeConstraint<P>(options: { message: RuleMessage<P>, constraint: Constraint<P>, params: P }): InternalConstraint;
/* tslint:enable max-line-length */
export function makeConstraint<P>({ message, constraint, params }: {
message: RuleMessage<P>,
constraint: Constraint<P>,
params?: P,
}): InternalConstraint {
return (value, constraintOptions) => (
castPromise(constraint(value, constraintOptions, params as P))
.then(passed => passed ? undefined
: produceMessage(message, value, constraintOptions, params as P))
);
}
|
4c013d1d7af2e5da041a391c9f2f255f9020722b
|
TypeScript
|
chenji336/cj-taskmgr
|
/src/app/login/login/login.component.ts
| 2.53125
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { Quote } from '../../domain/quote.model';
import * as fromRoot from '../../reducers';
import * as quoteActions from '../../actions/quote.action';
import { LoginAction } from '../../actions/auth.action';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
form: FormGroup;
quote$: Observable<Quote>;
constructor(
private fb: FormBuilder,
private store$: Store<fromRoot.State>
) { }
ngOnInit() {
this.form = this.fb.group({
// 不要Validators.compose,直接用数组也是ok的
email: ['lisixxx@independent.co.uk', Validators.compose([
Validators.required, Validators.email, // this.validate,使用到service,这里不需要validate
])],
password: ['123456', Validators.required]
});
this.quote$ = this.store$.select(fromRoot.getQuote); // 1.fromRoot.getQuote => state.quote;2. .slect理解成filter+distinctUntilChanged
this.quote$.subscribe(q => {
console.log('quote$-q:', q);
// q['ttt'] = 123; // 如果进行了storeFreeze,那么这里扩展属性就会报错
})
this.store$.dispatch(new quoteActions.LoadAction(null));
}
validate(c: FormControl): {[key: string]: any} | null {
if (!c.value) {
return null;
}
const pattern = /^wang+/;
if (pattern.test(c.value)) {
return null;
}
return {
emailNoValid: 'The email must start with wang'
};
}
onSubmit({value, valid}, ev: Event): void {
ev.preventDefault();
console.log('login-value:', JSON.stringify(value)); // {"email":"111wang@163.com","password":"fsdfds"}
console.log('login-valid:', JSON.stringify(valid)); // valid: false
// setValidators会覆盖email的所有Validators,所以required和email都会消失
// 这个可以作为动态验证,比如异步返回的内容进行判断
// this.form.controls['email'].setValidators(this.validate);
if (!valid) {
return;
}
this.store$.dispatch(new LoginAction(value));
}
}
|
948a617bd08fe0edc2769180f2598efd484f3545
|
TypeScript
|
aitoroses/chevrotain
|
/test/parse/grammar/resolver_spec.ts
| 2.5625
| 3
|
import {gast} from "../../../src/parse/grammar/gast_public"
import {HashTable} from "../../../src/lang/lang_extensions"
import {GastRefResolverVisitor} from "../../../src/parse/grammar/resolver"
import {ParserDefinitionErrorType} from "../../../src/parse/parser_public"
describe("The RefResolverVisitor", () => {
it("will fail when trying to resolve a ref to a grammar rule that does not exist", () => {
let ref = new gast.NonTerminal("missingRule")
let topLevel = new gast.Rule("TOP", [ref])
let topLevelRules = new HashTable<gast.Rule>()
topLevelRules.put("TOP", topLevel)
let resolver = new GastRefResolverVisitor(topLevelRules)
resolver.resolveRefs()
expect(resolver.errors).to.have.lengthOf(1)
expect(resolver.errors[0].message).to.contain("Invalid grammar, reference to rule which is not defined --> missingRule")
expect(resolver.errors[0].type).to.equal(ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF)
expect(resolver.errors[0].ruleName).to.equal("TOP")
})
})
|
6b7ca0a08e5980724fa44f4f96f73b487db7bc2b
|
TypeScript
|
aviabird/tax-app
|
/src/app/services/tax-calculator.service.ts
| 2.859375
| 3
|
import { Investor } from './../models/investor';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { TaxSlabsService } from './tax-slabs.service';
import { Slab } from '../models/slab';
import { SalaryRange } from '../models/salary-range';
@Injectable()
export class TaxCalculatorService {
slabs: Slab[];
// investor$: Observable<any>;
constructor(private taxSlabService: TaxSlabsService) {
this.slabs = taxSlabService.getSlabs();
}
// This Function Calculates tax for investor
// using his information i.e Age and Income
taxReturn(income: number, age: number): any {
var salaryRanges: SalaryRange[] = this.retriveSalaryRange(age);
var initialTax = this.calculateInitialTaxAmt(salaryRanges, income);
var surCharge = this.calcSurchargeIfAny(income, initialTax);
var eduCess = this.calcEduCess(initialTax, surCharge);
var totalTax = Math.floor(this.calcTotalTax(initialTax, eduCess, surCharge));
// this.investor$.tax = totalTax;
return totalTax;
}
// Retrive Salary Range in which the investor falls
retriveSalaryRange(age: number): SalaryRange[] {
var salaryRange: SalaryRange[] = [];
this.slabs.forEach(slab => {
// Check for min-max age condition
slab.maxAge = (slab.maxAge == -1) ? Infinity:slab.maxAge;
console.log("Slab maxAge is and age is" + slab.maxAge + " " + age);
if(slab.minAge <= age && age <= slab.maxAge){
console.log("Found Slab Range and In If condition");
salaryRange = slab.salaryRanges;
}
})
return salaryRange;
}
// Calculate Initial Tax Amount i.e Tax excluding Edu Cess and Surrcharge
calculateInitialTaxAmt(salaryRanges: SalaryRange[], income: number) {
var remain_hash = {};
var constTax:number = 0;
var constDiffAmt:number = 0;
var tax:number = 0;
salaryRanges.forEach(salaryRange => {
// Check for -1, if yes convert it to infinity
salaryRange.maxSal = (salaryRange.maxSal == -1) ? Infinity: salaryRange.maxSal;
if (salaryRange.minSal <= income && income <= salaryRange.maxSal){
tax = this.currentSalRangeTaxPlusConstTax(income,
constDiffAmt,
constTax,
salaryRange.percentage
)
console.log("Tax in Salary range is :", tax)
console.log("Calculating tax in salary range", salaryRange.maxSal);
return tax;
}
else {
// Calculate Constant amount and constant tax
// if amount is not in salary range
constDiffAmt += this.calcConstDiffAmt(salaryRange.minSal, salaryRange.maxSal);
constTax += this.calcConstTax(salaryRange.minSal, salaryRange.maxSal, salaryRange.percentage)
}
})
return tax;
}
// Constant Tax plus Tax for Current Salary Range
currentSalRangeTaxPlusConstTax(income: number,
constDiffAmt: number,
constTax: number,
percentage: number): number {
return ((income - constDiffAmt) * percentage + constTax);
}
// Calculate Diff Amount between two ranges
// E.g 25,0000 to 50,0000 = 25,00000
calcConstDiffAmt(minSal: number, maxSal: number): number {
return (maxSal - minSal);
}
// Calculate ConstTax for a range
// E.g: Tax For salary Range between 0-2,50000
// will always be 0
// that is first 2,50000 for all individuals will always
// have no tax
calcConstTax(minSal: number, maxSal: number, percentage: number): number {
return ((maxSal - minSal) * percentage)
}
// Surcharge
// Calculates Surcharge if investor income
// is greater than 1 Cr;
// Surcharge of 15% is charged on tax
// if income is greater than 1 crore
// Else surcharge is 0%;
calcSurchargeIfAny(income: number, tax: number): number {
if (income < 10000000){
return 0
}
else{
var initialSurcharge = (tax * 0.15);
var finalSurcharge = this.checkForMarginalRelief(initialSurcharge, income, tax);
return finalSurcharge;
}
}
// Check if person falls under margianl relief by
// comparing incrementalIncome and initial_surcharge
// return the one that is less
checkForMarginalRelief(initialSurcharge: number, income: number, tax: number): number {
// income above 1 Cr.
var incrementalIncome = (income - 10000000)
if (incrementalIncome < initialSurcharge){
return incrementalIncome;
}
else{
return initialSurcharge;
}
}
// Education Cess
// Calculates education cess on tax
// Default Education cess on tax in India is 3%
calcEduCess(initialTax: number, surCharge: number): number {
return ((initialTax + surCharge) * 0.03);
}
// Total tax
// Finnaly Add Educationl Cess , Surcharge to Inital tax
// and get Total Tax for the investor;
calcTotalTax(initialTax: number, eduCess: number, surCharge: number): number {
return (initialTax + eduCess + surCharge);
}
}
// End
|
e77d34cd996e44ce1f814d90d8eef1dd8d06463d
|
TypeScript
|
moepyxxx/practice-ts-pokemon
|
/src/controller/MainController.ts
| 2.875
| 3
|
import { Hero } from "../model/human/Hero";
import { MapField } from '../model/field/MapField';
import { Place } from '../model/field/Place';
import { Ordinary } from "../model/human/Ordinary";
import { Trainer } from "../model/human/Trainer";
import { PokemonAppearPlace } from "../model/field/PokemonAppearPlace";
import { TWildPokemons } from '../utils/type/TWildPokemons';
import { ExceptPokemon } from "../model/pokemon/ExceptPokemon";
import { Pokemon } from "../model/pokemon/Pokemon";
export class MainController {
public static _instance: MainController;
/**
* 現在のフィールド
*/
public _field: MapField;
/**
* 現在の場所
*/
public _place: Place;
/**
* 主人公
*/
public _hero: Hero;
private constructor() {
}
set hero(hero: Hero) {
this._hero = hero;
}
public static getInstance(): MainController {
if (!this._instance) {
this._instance = new MainController();
this._instance.renderSerif('ゲームをはじめよう');
}
return this._instance;
}
set field(field: MapField) {
this._field = field;
console.log(`${this._field.name}に移動した`);
}
set place(place: Place) {
this._place = place;
console.log(`${this._place._name}に移動した`);
}
heroWalk(place?: Place): ExceptPokemon | void {
console.log(`${this._hero.name}は${place?._name}のあたりを歩いた`);
let assignedPokemon;
if (this._place instanceof PokemonAppearPlace) {
const wildPokemons: TWildPokemons[] = this._place._wildPokemons;
const filterWildPokemons: TWildPokemons[] = wildPokemons.filter(pokemon => pokemon.trigger === 'すすむ');
assignedPokemon = this.assignAppearPokemon(filterWildPokemons);
}
if (!assignedPokemon) {
return;
}
const enemy = new ExceptPokemon(assignedPokemon.pokemon, assignedPokemon.lebel);
return enemy;
}
heroTalkTo(human: Trainer | Ordinary) {
// human.talk();
}
assignAppearPokemon(pokemons: TWildPokemons[]) {
let allRange = 0;
const assignTarget: { pokemon: Pokemon, min: number, max: number, lebelRange: number[] }[] = [];
pokemons.forEach((current, index) => {
const pokemon = current.pokemon;
const lebelRange = current.lebelRange;
const min = allRange;
const max = allRange + current.appearingRate
allRange += current.appearingRate;
assignTarget.push({ pokemon, min, max, lebelRange })
});
const randomNum = Math.random() * allRange;
const result = assignTarget.find((target) => {
return (randomNum > target.min) && (randomNum < target.max);
});
let resultPokemon;
let randomLebelNum;
let resultLebel;
if (result) {
resultPokemon = result.pokemon;
randomLebelNum = Math.floor(Math.random() * result.lebelRange.length);
resultLebel = result.lebelRange[randomLebelNum];
return {
pokemon: resultPokemon,
lebel: resultLebel
};
}
}
/**
* ゲームオーバー処理
*/
gameOver() {
this.renderSerif(`${this._hero.name}には戦えるポケモンがいない。目の前が真っ暗になった`);
this._hero._onHandPokemons.forEach(pokemon => {
pokemon._remainingHp = pokemon.basicTotalStatus.hp;
pokemon._statusAilment = null;
});
}
renderSerif(serif: any): void{
console.log(serif);
}
}
|
055ae7d2a558045ebd21513d951576abe7adc99b
|
TypeScript
|
Moventes/ionic-components
|
/componentes/src/components/autocomplete/autocomplete-modal.ts
| 2.765625
| 3
|
import { Component, forwardRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NavParams, Searchbar, ViewController } from 'ionic-angular';
/**
* Component providing a searchbar input which autocomplete returned by Google Maps API
*
* @example
* //TODO
*/
@Component({
selector: 'mv-autocomplete-modal',
templateUrl: 'autocomplete-modal.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AutocompleteModalComponent),
multi: true
}
]
})
export class AutocompleteModalComponent<T> implements ControlValueAccessor {
@ViewChild('search') searchBar: Searchbar;
/**
* Full list of results
*/
list: T[];
/**
* Boolean that indicates if the "custom address he typed could be presented on the list"
*/
allowCustom: boolean;
/**
* The component needs a label option to fill the placeholder
*/
label: string;
/**
* Boolean that indicates if user can validate the "custom address he typed or not"
*/
customEnabled: boolean;
/**
* Function returning an html string for item displaying
*/
display: Function;
/**
* Function returning a filtered array
*/
filter: Function;
/**
* Function returning an object <T> ffrom a string
*/
factory: Function;
/**
* The component needs a model (ngModel od formControlName) option that will store the returned address
*/
private _itemValue: T;
/**
* {string} Item formatted as it will appear in the dom
*/
private _displayedItemValue = '';
/**
* Filterd list
*/
private results: T[] = [];
private get itemValue(): T {
return this._itemValue;
}
private set itemValue(val: T) {
this._itemValue = val;
this.propagateChange(this._itemValue);
}
private get displayedItemValue() {
return this._displayedItemValue;
}
private set displayedItemValue(val) {
this._displayedItemValue = val;
}
constructor(
private params: NavParams,
private viewCtrl: ViewController
) { }
ionViewDidEnter() {
this.label = this.params.get('label');
this.list = this.params.get('list');
this.display = this.params.get('display');
this.filter = this.params.get('filter');
this.factory = this.params.get('factory');
this.allowCustom = this.params.get('allowCustom');
this.customEnabled = false;
setTimeout(() => {
this.searchBar.setFocus();
}, 500);
}
/**
* Empties the propositions list.
* Called before its filling or when there are not results from Google services
*/
private setFilteredList(results = null) {
this.results = results || [];
}
/**
* This method is part of ControlValueAccessor interface.
* Its role is to set value from the model to the DOM
*
* @param value Value given from the model
*/
public writeValue(value: T) {
if (value) {
this.displayedItemValue = this.display(value);
} else {
this.displayedItemValue = null;
}
}
/**
* This method is part of ControlValueAccessor interface.
* Its role is to set the function that will propagate changes from the DOM to the model.
*
* @param fn {function} Angular internal function
*/
public registerOnChange(fn) {
this.propagateChange = fn;
}
/**
* This method is part of ControlValueAccessor interface.
* Not used here
*/
public registerOnTouched(): void { }
/**
* Container for the propagation function.
*/
public propagateChange = (_: any) => { };
/**
* When user type something in the searchbar,
* this method updates the formatted address of the address model.
* This also calls the method responsible of filling the propositions list with AutocompleteService.
*/
public inputOnSearchbar(onInput: boolean) {
if (this.displayedItemValue && this.allowCustom) {
this.itemValue = this.factory(this.displayedItemValue);
} else {
this.itemValue = null;
}
if (this.customEnabled && onInput) {
this.customEnabled = false;
} else {
// Nothing to do...
}
if (!this.list) {
this.setFilteredList(this.list);
} else {
if (this.displayedItemValue) {
this.setFilteredList(this.list.filter((item: T) => this.filter(item, this.displayedItemValue)));
} else {
this.setFilteredList(this.list);
}
}
if (!this.customEnabled) {
this.customEnabled = true;
} else {
// Nothing to do...
}
}
/**
* This method is called when the user validates input without any result,
* the address only contains the formatted address entered in the search bar
*/
selectCustomItem() {
this.viewCtrl.dismiss(this.itemValue);
}
/**
* This method is called when user select a proposition in the list.
* The Google PlaceService is called to get precise informations about this place.
* the address object is built with those informations.
*
* @param item Selected item from propositon list
*/
public selectSearchResult(item) {
this.itemValue = item;
this.viewCtrl.dismiss(this.itemValue);
this.setFilteredList();
}
closeModal() {
this.viewCtrl.dismiss();
}
}
|
66c7682d581c29c26495b21ab91963b566dfda3e
|
TypeScript
|
stsr9/tv_bland
|
/src/api/shows-api.ts
| 2.609375
| 3
|
import { http } from './http/http'
import { ApiEndpointUrls } from './api-endpoint-urls'
import { Show } from 'models/show'
import { Actor } from 'models/actor'
interface ShowsInterface {
fetchEpisodeDetails(id: string): Promise<Show>
}
class ShowsAPI implements ShowsInterface {
fetchEpisodeDetails(id: string): Promise<Show> {
return http({
method: 'get',
url: `${ApiEndpointUrls.shows}/${id}`
})
}
showCast(id: string): Promise<Actor[]> {
return http({
method: 'get',
url: `${ApiEndpointUrls.shows}/${id}/cast`
})
}
}
export default new ShowsAPI()
|
9332b33cfd2b4b1db035ec85b0f13d2eadbb2e36
|
TypeScript
|
poeticsoft/learning
|
/streamdata/src/server/server.ts
| 2.84375
| 3
|
// https://medium.com/factory-mind/websocket-node-js-express-step-by-step-using-typescript-725114ad5fe4
import * as express from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';
import * as path from 'path';
const app = express();
// INTERFACE
const publicRoot = path.join(__dirname, '../../', 'public');
console.log(publicRoot);
app.use(express.static(publicRoot)); //Serves resources from public folder
// SERVER
//initialize a simple http server
const server = app.listen(process.env.PORT || 8999, () => {
const serverData: any = server.address();
console.log(`Server started on port ${ serverData.port } :)`);
});
// WEBSOCKET
//initialize the WebSocket server instance
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws: WebSocket) => {
/* connection is up, let's add a simple simple event
ws.on('message', (message: string) => {
//log the received message and send it back to the client
console.log('received: %s', message);
ws.send(`Hello, you sent -> ${message}`);
});
*/
/* send immediatly a feedback to the incoming connection
ws.send('Hi there, I am a WebSocket server');
*/
setInterval(() => {
ws.send('data ' + Math.random());
}, 1000);
});
|
421eb6b0fb6f9345d57d6e2a5a862c763b76eb81
|
TypeScript
|
YaoZeyuan/leetcode
|
/resolve/二刷/100.ts
| 3.828125
| 4
|
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
function canSameTravel(node1: TreeNode, node2: TreeNode) {
if (node1 === null) {
if (node2 === null) {
return true
}
return false
} else {
if (node2 === null) {
return false
}
}
// 到这一步说明两边都不是null
if (node1.val !== node2.val) {
return false
}
// 然后同时检测左侧和右侧
return canSameTravel(node1.left, node2.left) && canSameTravel(node1.right, node2.right)
}
return canSameTravel(p, q)
}
|
a7ab62c5b2692a9d692bbcac5b2f5ae663021502
|
TypeScript
|
wenqi73/ng-template-parser
|
/src/main.ts
| 2.953125
| 3
|
import { Lexer } from './expression_parser/lexer';
import { Parser } from './expression_parser/parser';
export function parse(expr: any) {
switch (typeof expr) {
case 'string':
const lexer = new Lexer();
const parser = new Parser(lexer);
return parser.parse(expr);
default:
console.log('cannot parse');
break;
}
}
const foo = parse('12345.222');
console.log(foo());
|
0a9f35f2cc72df1f6fd1d8b4646dcb4fdcd8b337
|
TypeScript
|
taoalpha/typecript-algorithms
|
/src/algorithms/math/bits/bitLength.ts
| 3.625
| 4
|
/**
* Return the number of bits used in the binary representation of the number.
*
*/
export default function bitLength(number: number): number {
let bitsCounter = 0;
while ((1 << bitsCounter) <= number) {
bitsCounter += 1;
}
return bitsCounter;
}
|
0bc8e0c2dc8e798de4c190edd5d821c866253a6f
|
TypeScript
|
AmirHus/getInformation
|
/src/utilities/informationLoader.ts
| 2.84375
| 3
|
//IMPORTS GOES HERE
export class InformationLoader
implements ILoader<InputGeneric, Promise<OutputGeneric>> {
//INJECTED DEPENDANCIES
dependancyA: ILoader<
{
input: InputGeneric,
},
Promise<{
output: OutputGeneric;
}>
>;
dependancyB: (input: inputGeneric) => Promise<unknown[]>;
dependancyC: string;
constructor(options: IInformationLoaderOptions) {
this.dependancyA = options.dependancyA;
this.dependancyB = options.dependancyB;
this.dependancyC = options.dependancyC;
}
async load(request: InputGeneric) {
// CODE GET PART OF THE INFORMATION
try {
//CODE TO LOAD OTHER PART OF THE INFORMATION
} catch (error) {
//CHECK CUSTOM ERROR
if (error instanceof OtherPartNotFoundError) {
return { configs: [] } as IFoundInformation;
}
throw error;
}
return loadedInformation;
}
}
|
aa9848356f50e24a869bf0707ed977e3c8dd178d
|
TypeScript
|
Guezin/pontte-challenge
|
/src/modules/users/useCases/UpdateUserUseCases.ts
| 2.625
| 3
|
import { inject, injectable } from 'tsyringe'
import AppError from '@shared/errors/AppError'
import cpfValidate from '@shared/utils/cpfValidate'
import User from '@modules/users/infra/typeorm/entities/User'
import IUserRepository from '@modules/users/repositories/IUserRepository'
import IContractRepository from '@modules/contracts/repositories/IContractRepository'
interface IRequest {
user_id: string
name: string
email: string
cpf: string
monthly_income: number
date_of_birth: string
marital_status: string
address: string
}
@injectable()
class UpdateUserUseCases {
constructor(
@inject('UserRepository')
private userRepository: IUserRepository,
@inject('ContractRepository')
private contractRepository: IContractRepository
) {}
public async execute({
user_id,
name,
email,
cpf,
monthly_income,
date_of_birth,
marital_status,
address
}: IRequest): Promise<User> {
if (!cpfValidate(cpf)) {
throw new AppError('Sorry, enter a valid cpf.')
}
const user = await this.userRepository.findById(user_id)
const contract = await this.contractRepository.findByUserId(user_id)
if (!user) {
throw new AppError('Sorry, user not found')
}
if (!contract) {
throw new AppError(
'It is necessary to create a contract first and then update user data',
401
)
}
if (contract.state === 'approved') {
throw new AppError('Unable to update, contract in approved status', 401)
} else if (contract.state === 'rejected') {
throw new AppError('Unable to update, contract in rejected status', 401)
}
const updatedUser = Object.assign(user, {
name,
email,
cpf,
monthly_income,
date_of_birth,
marital_status,
address
})
const reponse = await this.userRepository.save(updatedUser)
return reponse
}
}
export default UpdateUserUseCases
|
67604c6cf10520e0967073c3acb25011290dac1a
|
TypeScript
|
teohrt/auth-task
|
/src/db/dbClient.ts
| 2.640625
| 3
|
/* eslint-disable max-len */
import { Pool, QueryResult, PoolClient } from 'pg';
import { Logger } from 'winston';
export interface DBClient {
createUser: (username: string, passwordHash: string, salt: string) => Promise<QueryResult>;
getUserByName: (username: string) => Promise<QueryResult>;
createTask: (ownerId: number, status: string, name: string, description: string, dueDate: string) => Promise<QueryResult>;
getAllTasksFromUser: (id: number) => Promise<QueryResult>;
getTask: (taskId: number) => Promise<QueryResult>;
updateTask: (taskId: number, status: string, name: string, description: string, dueDate: string) => Promise<QueryResult>;
deleteTask: (taskId: number) => Promise<QueryResult>;
}
export default async (logger: Logger): Promise<DBClient> => {
const pool = new Pool({
host: process.env.PGHOST,
port: Number(process.env.PGPORT),
database: process.env.PGDATABASE,
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
});
let client: PoolClient;
try {
client = await pool.connect();
logger.info('DB Connected');
} catch (err) {
logger.error(`DB connection error: ${err.stack}`);
}
const dbQuery = async (queryString: string): Promise<QueryResult> => {
try {
logger.debug(`Query: ${queryString}`);
return await new Promise((resolve, reject) => {
client.query(queryString, (err: Error, res) => {
if (err) {
reject(err.stack);
}
resolve(res);
});
});
} catch (err) {
return null as any;
}
};
return {
createUser: async (username, passwordHash, salt) => dbQuery(`
INSERT INTO app_user(username, password_hash, salt)
VALUES ('${username}', '${passwordHash}', '${salt}')
RETURNING id;
`),
getUserByName: async (username) => dbQuery(`
SELECT * FROM app_user
WHERE username = '${username}';
`),
createTask: async (ownerId, status, name, description, dueDate) => dbQuery(`
INSERT INTO task(owner_id, status, name, description, due_date)
VALUES (${ownerId}, '${status}', '${name}', '${description}', '${dueDate}')
RETURNING id;
`),
getAllTasksFromUser: async (ownerId) => dbQuery(`
SELECT * FROM task
WHERE owner_id = ${ownerId};
`),
getTask: async (taskId) => dbQuery(`
SELECT * FROM task
WHERE id = ${taskId};
`),
updateTask: async (taskId, status, name, description, dueDate) => dbQuery(`
UPDATE task
SET status = '${status}',
name = '${name}',
description = '${description}',
due_date = '${dueDate}'
WHERE id = ${taskId};
`),
deleteTask: async (taskId) => dbQuery(`
DELETE FROM task
WHERE id = ${taskId};
`),
};
};
|
95d55a108d90b44e61ba00ba17a970acda9abff2
|
TypeScript
|
ronaldogdn/cicloPagamento
|
/API/src/controllers/CicloController.ts
| 2.640625
| 3
|
import { Request, Response }from "express";
import { resolveProjectReferencePath } from "typescript";
import CicloSchema from "../models/CicloSchema";
class CicloController{
async listar(request: Request, response:Response){
try{
const ciclos = await CicloSchema.find();
// response.status(200).json({
// data: ciclos,
// error:false,
// msg:"Lista de ciclos de pagamento atualizada!"
// });
response.status(200).json(ciclos);
}catch(error){
response.status(404).json({
data: error,
error: true,
msg: "Não foi possível listar os ciclos de pagamento",
});
}
}
async listarPorId(request: Request, response: Response){
try {
const { id } = request.params;
const ciclo = await CicloSchema.findOne({ _id: id });
// console.log(await CicloSchema.exists({ _id: id }));
// console.log(await CicloSchema.find({ _id: id }).countDocuments());
if (ciclo != null) {
//response.status(200).json({ data: ciclo, error: false, msg: "Ciclo encontrado!" });
response.status(200).json(ciclo);
} else {
response.status(404).json({ data: ciclo, error: false, msg: "Ciclo não encontrado!" });
}
} catch (error) {
response.status(400).json({ data: error, error: true, msg: "Esse não é um formato válido para o ID!" });
}
}
//método assíncrono
async cadastrar(request: Request, response:Response){
try{
const novoCiclo = await CicloSchema.create(request.body);
response.status(201).json(novoCiclo);
/*response.status(201).json({
data: novoCiclo,
error:false,
msg:"Ciclo cadastrado."
});*/
}
catch(error){
response.status(400).json({
data: error,
error: true,
msg: "Não foi possível adicionar o ciclo",
});
}
}
async excluir(request: Request, response:Response){
try {
const { id } = request.params;
console.log(id);
const ciclo = await CicloSchema.deleteOne({ _id: id });
if (ciclo != null) {
response
.status(200)
.json(ciclo);
}
response
.status(400)
.json({ data: ciclo, error: false, msg: "ciclo não encontrado!" });
} catch (error) {
response
.status(400)
.json({ data: error, error: true, msg: "Formato de id não válido!" });
}
}
async alterar(request: Request, response: Response) {
if (!request.body) {
response.status(404).json({
error: true,
msg: "Está faltando o body da request!",
});
}
//const { id } = request.params;
console.log(request.body);
//tomar cuidado que _id precisa ser o que está
//vindo do request
const { _id, data, creditos, debitos } = request.body;
try {
const result = await CicloSchema.updateOne(
{ _id: _id },
{
$set: {
data: data,
creditos: creditos,
debitos: debitos,
},
}
);
if (result != null) {
response.status(200).json({
data: result,
error: false,
msg: "Ciclo atualizado com sucesso!",
});
}
response.status(404).json({
data: data,
error: true,
msg: "Ciclo não encontrado!",
});
} catch (err) {
response.status(200).json({
data: err,
error: true,
msg: "Ciclo não encontrado!",
});
}
}
//recupera a data do ciclo para exibição no FRONT
async recuperaDataMesAno(request: Request, response: Response){
let ano:number = Number(request.params.ano);
let mes:number = Number(request.params.mes);
let ciclos = await CicloSchema.find({}).sort({ date: -1});
for(let ciclo of ciclos){
if(ciclo.data.getFullYear() === ano &&
ciclo.data.getMonth() === mes)
{
return response.status(200).json(ciclo);
}
}
return response.status(404).json({msg:"Não encontrado."});
}
}
//exportar somente o objeto
export { CicloController };
|
9d1231f566c0c76228fc46840152371bbb0cf52c
|
TypeScript
|
CodeAndChillClub/plusnew
|
/src/instances/types/Array/Instance.ts
| 2.703125
| 3
|
import PlusnewAbstractElement from '../../../PlusnewAbstractElement';
import ChildrenInstance from '../ChildrenInstance';
import Instance, { getPredeccessor } from '../Instance';
import types from '../types';
import reconcile from './reconcile';
/**
* ArrayInstances are used for representing lists in the shadowdon
* and they correspond for creating and deleting instances of the corresponding entities
*/
export default class ArrayInstance extends ChildrenInstance {
public nodeType = types.Array;
public type = types.Array;
public props: (PlusnewAbstractElement)[];
public executeChildrenElementWillUnmount = true;
constructor(
abstractElements: (PlusnewAbstractElement)[],
parentInstance: Instance,
getPredecessor: getPredeccessor,
) {
super(abstractElements, parentInstance, getPredecessor);
this.props = abstractElements;
this.addChildren(abstractElements);
}
/**
* updates the shadowdom and dom
*/
public reconcile(newAbstractElements: PlusnewAbstractElement[]) {
reconcile(newAbstractElements, this);
}
/**
* gets dom element predecessing the array for the children instances
* and returns the predeccessor of this array
*/
public getChildrenPredeccessor() {
return this.getPredecessor();
}
}
|
450e2c22641a4a3043efe06f04edb8ed5ea34c61
|
TypeScript
|
kagankarakaya/open-conquest-world-server
|
/src/Response.ts
| 3.25
| 3
|
/**
*
*
* @export
* @class Response
*/
export class Response {
public service: string;
public operation: string;
public data: any;
/**
*Creates an instance of Response.
* @param {*} service
* @param {*} operation
* @param {*} data
* @memberof Response
*/
constructor(service, operation, data) {
this.service = service;
this.operation = operation;
this.data = data;
}
getService(): string {
return this.service;
}
getOperation(): string {
return this.operation;
}
getData(): any {
return this.data;
}
/**
*
*
* @param {*} json
* @return {Response}
* @memberof Response
*/
fromJson(json) {
return new Response(json.service, json.operation, json.data);
}
/**
*
* @return {Response}
* @memberof Response
*/
toJson() {
return {
'service': this.service,
'operation': this.operation,
'data': this.data,
};
}
}
|
dd0d27898d81f87e4654b9821c46404411fef72c
|
TypeScript
|
AbinJames/MoneyManager
|
/MoneyManagerAngular/src/app/savings-parameters/savings-parameter-filter.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'SavingsParameterFilterPipe' })
export class SavingsParameterFilterPipe implements PipeTransform {
transform(savingsParameterList: any[], savingsParameterName: string, minAmount: number, maxAmount: number, minBalance: number, maxBalance: number, filterEnabled: boolean) {
console.log("\nsavingsParameterName " + savingsParameterName
+ "\nminAmount " + minAmount
+ "\nmaxAmount " + maxAmount
+ "\nfilterEnabled " + filterEnabled);
//return original list if filtered button is not clicked
if (!filterEnabled) {
return savingsParameterList;
}
//if savingsParameter balance is not empty, select value satisfying balance filter
if (minBalance || maxBalance && (minBalance <= maxBalance)) {
savingsParameterList = savingsParameterList.filter(
item =>
(maxBalance >= item.savingsParameterBalance) && (item.savingsParameterBalance >= minBalance)
);
}
//if savingsParameterName is not empty the filter savingsParameter by savingsParameterName
if (savingsParameterName) {
savingsParameterList = savingsParameterList.filter(
item =>
item.savingsParameterName.toLowerCase().includes(
savingsParameterName.toLowerCase()
)
);
}
//return filtered list
return savingsParameterList;
}
}
|
797c2d386baff5fb4572c43ac44b05cec5b698e5
|
TypeScript
|
yamatatsu/receptron
|
/packages/orgWeb/src/domains/org/index.ts
| 2.65625
| 3
|
import { Subject } from "rxjs";
import { scan } from "rxjs/operators";
// Model
export type Org = { name: string };
// Events
export const orgAdded$ = new Subject<Org>();
// State
const initial: Org[] = [];
export const orgState$ = orgAdded$.pipe(
scan((orgs, org) => [...orgs, org], initial),
);
|
a8a5044538236af54d7e508f380c5eeac79c2bfc
|
TypeScript
|
wlf-io/deno-cliffy
|
/command/upgrade/provider/deno_land.ts
| 2.578125
| 3
|
import { Provider, Versions } from "../provider.ts";
export interface DenoLandProviderOptions {
name?: string;
}
export class DenoLandProvider extends Provider {
name = "deno.land";
private readonly repositoryUrl = "https://deno.land/x/";
private readonly registryUrl = "https://deno.land/x/";
private readonly moduleName?: string;
constructor({ name }: DenoLandProviderOptions = {}) {
super();
this.moduleName = name;
}
async getVersions(
name: string,
): Promise<Versions> {
const response = await fetch(
`https://cdn.deno.land/${this.moduleName ?? name}/meta/versions.json`,
);
if (!response.ok) {
throw new Error(
"couldn't fetch the latest version - try again after sometime",
);
}
return await response.json();
}
getRepositoryUrl(name: string): string {
return new URL(`${this.moduleName ?? name}/`, this.repositoryUrl).href;
}
getRegistryUrl(name: string, version: string): string {
return new URL(`${this.moduleName ?? name}@${version}/`, this.registryUrl)
.href;
}
}
|
df62a2579b3b4d89afa6b91edf13dc6aebaa01d6
|
TypeScript
|
matthewtff/voter
|
/build/frontend/ts/room.ts
| 3
| 3
|
/// <reference path="utils.ts" />
class Room {
private static kRoomInfoPath = "room.info";
private static kRoomIdFieldName = "room_id";
private static kRoomPageAddress = "/html/room.html";
private room_id_ : string;
constructor(room_info : Object) {
if (!Room.Validate(room_info))
return null;
this.room_id_ = room_info[Room.kRoomIdFieldName];
}
id() : string {
return this.room_id_;
}
static Validate (info : Object) : Boolean {
return info.hasOwnProperty(Room.kRoomIdFieldName) &&
Utils.IsString(info[Room.kRoomIdFieldName]);
}
static MoveToRoom(room_id : string) {
document.location.href = Room.kRoomPageAddress + '#' + room_id;
}
}
|
9907b709b2a4190fe3ce0cf495e8b0e6a0632ec3
|
TypeScript
|
andreyshr/weather-widget
|
/src/modules/geolocation/geolocation.ts
| 2.796875
| 3
|
import { TCoordinates } from "@/api/location-api/types";
export class GeolocationModule {
public static getLocation(): Promise<TCoordinates> {
return new Promise((resolve, reject) => {
const onSuccess = (position: GeolocationPosition) => {
resolve({
lat: position.coords.latitude,
lon: position.coords.longitude,
});
};
const onError = (err: GeolocationPositionError) => reject(err);
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
}
}
|
d74472ac3c3cd5d49aebb058b5e1544881641001
|
TypeScript
|
kesla/sucrase
|
/src/transformers/Transformer.ts
| 2.546875
| 3
|
export default interface Transformer {
preprocess(): void;
// Return true if anything was processed, false otherwise.
process(): boolean;
getPrefixCode(): string;
getSuffixCode(): string;
};
|
1f009aa65c25bc8f270165b1a79fa3b15d881886
|
TypeScript
|
providenetwork/indra
|
/modules/client/src/lib/utils.ts
| 2.8125
| 3
|
import { BigNumber, bigNumberify, hexlify, randomBytes, solidityKeccak256 } from "ethers/utils";
import { isNullOrUndefined } from "util";
// Give abrv = true to abbreviate hex strings and xpubs to look like "xpub6FEC..kuQk"
export const stringify = (obj: object, abrv: boolean = false): string =>
JSON.stringify(
obj,
(key: string, value: any): any =>
value && value._hex
? bigNumberify(value).toString()
: abrv && value && typeof value === "string" && value.startsWith("xpub")
? `${value.substring(0, 8)}..${value.substring(value.length - 4)}`
: abrv && value && typeof value === "string" && value.startsWith("0x")
? `${value.substring(0, 6)}..${value.substring(value.length - 4)}`
: value,
2,
);
// Capitalizes first char of a string
export const capitalize = (str: string): string =>
str.substring(0, 1).toUpperCase() + str.substring(1);
export const objMap = <T, F extends keyof T, R>(
obj: T,
func: (val: T[F], field: F) => R,
): { [key in keyof T]: R } => {
const res: any = {};
for (const key in obj) {
if ((obj as any).hasOwnProperty(key)) {
res[key] = func(key as any, obj[key] as any);
}
}
return res;
};
export const objMapPromise = async <T, F extends keyof T, R>(
obj: T,
func: (val: T[F], field: F) => Promise<R>,
): Promise<{ [key in keyof T]: R }> => {
const res: any = {};
for (const key in obj) {
if ((obj as any).hasOwnProperty(key)) {
res[key] = await func(key as any, obj[key] as any);
}
}
return res;
};
export const insertDefault = (val: string, obj: any, keys: string[]): any => {
const adjusted = {} as any;
keys.concat(Object.keys(obj)).map((k: any): any => {
// check by index and undefined
adjusted[k] = isNullOrUndefined(obj[k])
? val // not supplied set as default val
: obj[k];
});
return adjusted;
};
export const delay = (ms: number): Promise<void> =>
new Promise((res: any): any => setTimeout(res, ms));
export const delayAndThrow = (ms: number, msg: string = ""): Promise<void> =>
new Promise((res: any, rej: any): any => setTimeout((): void => rej(msg), ms));
export const createLinkedHash = (
amount: BigNumber,
assetId: string,
paymentId: string,
preImage: string,
): string => {
return solidityKeccak256(
["uint256", "address", "bytes32", "bytes32"],
[amount, assetId, paymentId, preImage],
);
};
export const withdrawalKey = (xpub: string): string => {
return `${xpub}/latestNodeSubmittedWithdrawal`;
};
export const createRandom32ByteHexString = (): string => {
return hexlify(randomBytes(32));
};
export const createPaymentId = createRandom32ByteHexString;
export const createPreImage = createRandom32ByteHexString;
|
af37275cf78280f7e05434c2f0dbf02f6396908c
|
TypeScript
|
sz-piotr/jscodegolf
|
/frontend/src/domain/groupResults.ts
| 3.0625
| 3
|
import { TestResult } from './execute'
import { TestCase } from './challenge'
export interface ResultGroup {
message: string,
type: 'PASS' | 'FAIL',
items: ResultGroupItem[],
}
export interface ResultGroupItem {
test: TestCase,
result: TestResult,
}
export function groupResults (cases: TestCase[], results: TestResult[]): ResultGroup[] {
const { passes, errors, fails } = splitIntoTypes(cases, results)
return [
...groupPasses(passes),
...groupErrors(errors),
...groupFails(fails),
]
}
function groupPasses (items: ResultGroupItem[]): ResultGroup[] {
if (items.length === 0) {
return []
}
return [{
message: `${items.length} correct results`,
type: 'PASS',
items,
}]
}
type ErrorItem = { test: TestCase, result: { type: 'ERROR', message: string } }
function groupErrors (input: ErrorItem[]) {
const groups: ResultGroup[] = []
for (const item of input) {
const group = groups.find(x => x.message === item.result.message)
if (group) {
group.items.push(item)
} else {
groups.push({
message: item.result.message,
type: 'FAIL',
items: [item],
})
}
}
return groups
}
function splitIntoTypes (cases: TestCase[], results: TestResult[]) {
const passes = []
const errors = []
const fails = []
for (let i = 0; i < cases.length; i++) {
const test = cases[i]
const result = results[i] || { type: 'ERROR', message: 'Missing result' }
if (result.type === 'PASS') {
passes.push({ test, result })
} else if (result.type === 'ERROR') {
errors.push({ test, result })
} else if (result.type === 'FAIL') {
fails.push({ test, result })
}
}
return { passes, errors, fails }
}
type FailItem = { test: TestCase, result: { type: 'FAIL', result: any } }
function groupFails (items: FailItem[]): ResultGroup[] {
if (items.length === 0) {
return []
}
return [{
message: `${items.length} incorrect results`,
type: 'FAIL',
items
}]
}
|
4bc746217c09211a5c1a79ccdab890b892f60d62
|
TypeScript
|
luisiiyoo/cards-game-frontend
|
/src/model/resources.ts
| 2.734375
| 3
|
export type Metadata = string | number | boolean | undefined;
export interface Resource {
id: number;
name: string;
shortDescription: string;
description: string;
url: string;
complexity: string; //'easy' | 'medium' | 'hard' | 'god';
tags: string[];
metadata: { [key: string]: Metadata };
}
|
0ed5927ec201d1e659cb3d66d312d7909e5e0c2a
|
TypeScript
|
sekwah41/spq
|
/src/__tests__/PromiseQueue.test.ts
| 3.203125
| 3
|
import { PromiseQueue } from "../PromiseQueue";
import { QueuedPromiseFactory } from "../TaskTypes";
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe("Basic checks on QueuedPromise", () => {
let customQueue: PromiseQueue;
let QueuedPromise: QueuedPromiseFactory;
beforeEach(() => {
customQueue = new PromiseQueue(1);
QueuedPromise = customQueue.QueuedPromise;
});
it("Checking when resolving, that the promise resolves", () => {
const promise = QueuedPromise((resolve) => {
resolve(2);
});
return expect(promise).resolves.toEqual(2);
});
it("Async with return resolves", () => {
const promise = QueuedPromise(async () => {
return 3;
});
return expect(promise).resolves.toEqual(3);
});
it("Async with throw rejects", () => {
const promise = QueuedPromise(async () => {
throw 4;
});
return expect(promise).rejects.toEqual(4);
});
it("Checking when rejected that the promise rejects", () => {
const promise = QueuedPromise((resolve, reject) => {
reject(6);
});
return expect(promise).rejects.toEqual(6);
});
it("catch() works", () => {
const promise = QueuedPromise((resolve, reject) => {
reject(5);
});
return expect(promise).rejects.toEqual(5);
});
});
describe("Basic checks on QueuedPromise", () => {
let customQueue: PromiseQueue;
let QueuedPromise: QueuedPromiseFactory;
beforeEach(() => {
customQueue = new PromiseQueue(1);
QueuedPromise = customQueue.QueuedPromise;
});
it("Checking when rejected that only catch is fired", (done) => {
const promise = QueuedPromise((resolve, reject) => {
reject(6);
});
let hasRunThen = false;
let hasRunCatch = false;
promise
.then(() => {
hasRunThen = true;
})
.catch(() => {
hasRunCatch = true;
})
.finally(() => {
expect(hasRunThen).toBe(false);
expect(hasRunCatch).toBe(true);
done();
});
});
it("Checking when rejected and reject is provided in then that only catch is fired", (done) => {
const promise = QueuedPromise((resolve, reject) => {
reject(6);
});
let hasRunThen = false;
let hasRunCatch = false;
promise
.then(
() => {
hasRunThen = true;
},
() => {
hasRunCatch = true;
},
)
.finally(() => {
expect(hasRunThen).toBe(false);
expect(hasRunCatch).toBe(true);
done();
});
});
it("catch() works", (done) => {
const returnedValues: any[] = [];
const promise = QueuedPromise((resolve, reject) => {
reject(5);
});
promise
.catch((e: any) => {
returnedValues.push(e);
returnedValues.push(2);
})
.finally(() => {
expect(returnedValues).toMatchObject([5, 2]);
done();
});
});
});
describe("Promise order check", () => {
it("Single queue (Forces set order)", (done) => {
const customQueue = new PromiseQueue(1);
const QueuedPromise = customQueue.QueuedPromise;
const returnedValues: any[] = [];
QueuedPromise((resolve: () => void) => {
returnedValues.push(1);
resolve();
});
QueuedPromise((resolve: () => void) => {
setTimeout(() => {
returnedValues.push(2);
resolve();
}, 10);
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(3);
resolve();
});
customQueue.on("finished", () => {
expect(returnedValues).toMatchObject([1, 2, 3]);
done();
});
});
it("Single queue async (Forces set order)", (done) => {
const customQueue = new PromiseQueue(1);
const QueuedPromise = customQueue.QueuedPromise;
const returnedValues: any[] = [];
QueuedPromise(async () => {
returnedValues.push(1);
});
QueuedPromise(async () => {
await sleep(10);
returnedValues.push(2);
});
QueuedPromise(async () => {
returnedValues.push(3);
});
customQueue.on("finished", () => {
expect(returnedValues).toMatchObject([1, 2, 3]);
done();
});
});
it("Double queue", (done) => {
const customQueue = new PromiseQueue(2);
const QueuedPromise = customQueue.QueuedPromise;
const returnedValues: any[] = [];
QueuedPromise((resolve: () => void) => {
returnedValues.push(1);
resolve();
});
QueuedPromise((resolve: () => void) => {
setTimeout(() => {
returnedValues.push(2);
resolve();
}, 10);
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(3);
resolve();
});
customQueue.on("finished", () => {
expect(returnedValues).toMatchObject([1, 3, 2]);
done();
});
});
it("Emit finished event", (done) => {
const customQueue = new PromiseQueue(2);
const QueuedPromise = customQueue.QueuedPromise;
const returnedValues: any[] = [];
customQueue.on("finished", () => {
expect(returnedValues).toMatchObject([1, 2, 3]);
done();
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(1);
resolve();
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(2);
resolve();
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(3);
resolve();
});
});
it("Pause Queue", (done) => {
const customQueue = new PromiseQueue(2);
const QueuedPromise = customQueue.QueuedPromise;
customQueue.pause();
const returnedValues: any[] = [];
QueuedPromise((resolve: () => void) => {
returnedValues.push(1);
resolve();
});
QueuedPromise((resolve: () => void) => {
setTimeout(() => {
returnedValues.push(2);
resolve();
}, 5);
});
QueuedPromise((resolve: () => void) => {
returnedValues.push(3);
resolve();
});
setTimeout(() => {
expect(returnedValues).toMatchObject([]);
}, 10);
setTimeout(() => {
expect(returnedValues).toMatchObject([]);
customQueue.resume();
}, 20);
customQueue.on("finished", () => {
expect(returnedValues).toMatchObject([1, 3, 2]);
done();
});
});
});
describe("Works with promise functions", () => {
it("Resolves", async () => {
const customQueue = new PromiseQueue(1);
const QueuedPromise = customQueue.QueuedPromise;
const testPromise = QueuedPromise((resolve: (text: string) => void) => {
resolve("Value has returned");
});
const testPromise2 = QueuedPromise((resolve: (text: string) => void) => {
resolve("Here is another");
});
const testPromise3 = QueuedPromise((resolve: (text: string) => void) => {
resolve("My name is steve");
});
await expect(testPromise).resolves.toEqual("Value has returned");
await expect(testPromise2).resolves.toEqual("Here is another");
await expect(testPromise3).resolves.toEqual("My name is steve");
});
it("Works with promise all", async () => {
const customQueue = new PromiseQueue(1);
const QueuedPromise = customQueue.QueuedPromise;
const testPromise = QueuedPromise((resolve: (text: string) => void) => {
resolve("test1");
});
const testPromise2 = QueuedPromise((resolve: (text: string) => void) => {
resolve("test2");
});
const testPromise3 = QueuedPromise((resolve: (text: string) => void) => {
resolve("test3");
});
await expect(Promise.all([testPromise, testPromise2, testPromise3])).resolves.toEqual(["test1", "test2", "test3"]);
});
it("Works with await", async () => {
const customQueue = new PromiseQueue(1);
const QueuedPromise = customQueue.QueuedPromise;
const result = await QueuedPromise((resolve: (text: string) => void) => {
resolve("Await test");
});
expect(result).toEqual("Await test");
});
});
|
2324adf280febbba11f20db0c11ea516483034a9
|
TypeScript
|
kolserdav/ads-panel
|
/src/routes/user/post.forgot.ts
| 2.640625
| 3
|
import * as Types from '../../types';
import * as lib from '../../lib';
import * as orm from '../../orm';
import * as utils from '../../utils';
import express from 'express';
/**
* POST /user/forgot
* Запрос на смену пароля .
* Передаётся почта в email, создается и отправляется ключ, который при переходе на GET /user/forgot
* проверяет ключ и генерирует токен на смену пароля.
* @email {string} - почта
*/
export default async function postForgot(req: express.Request, res: express.Response): Promise<any> {
const { email } = req.body;
if (!email) {
return res.status(400).json({
result: 'warning',
message: 'Адрес почты не передан',
body: {},
});
}
if (!lib.checkEmail(email)) {
return res.status(400).json({
result: 'warning',
message: 'Адрес почты имеет неверный формат',
body: {},
});
}
const getByEmail: Types.OrmResult = await orm.user.getByEmail(email);
if (getByEmail.error === 1) {
console.warn(`<${Date()}>`, '[Warning: getByEmail.error === 1]', {
url: req.url,
headers: req.headers,
});
return res.status(500).json({
result: 'error',
message: 'Ошибка проверки почты пользователя',
body: {
stdErrMessage: getByEmail.data,
},
});
}
if (getByEmail.data.length === 0) {
return res.status(400).json({
result: 'warning',
message: 'Указанная почта не найдена',
body: {
email,
},
});
}
const user: Types.User = getByEmail.data[0];
const uid: any = user.id;
const dateNow = Date.now();
// Изменяет updated на основе timestamp
const updateRes: Types.OrmResult = await orm.user.changeUpdated(dateNow, uid);
if (updateRes.error === 1) {
console.warn(`<${Date()}>`, '[Warning: updateRes.error === 1]', {
url: req.url,
headers: req.headers,
});
const updateWarnRes: Types.ServerHandlerResponse = {
result: 'error',
message: 'Ошибка генерации ключа ссылки',
body: {
stdErrMessage: updateRes.data,
},
};
return res.status(500).json(updateWarnRes);
}
// Отправляет письмо с сылкой на смену пароля
const sendRes: Types.OrmResult = await utils.getForgotEmail(user.email, dateNow, user.first_name);
if (sendRes.error === 1) {
console.warn(`<${Date()}>`, '[Warning: sendRes.error === 1]', {
url: req.url,
headers: req.headers,
});
return res.status(502).json({
result: 'error',
message: 'Не удалось отправить письмо с ссылкой на смену пароля',
body: {
stdErrMessage: sendRes.data,
},
});
}
const sendConfirmRes: Types.ServerHandlerResponse = {
result: 'success',
message: 'Письмо с сcылкой подтверждения отправлено на указанный адрес почты',
body: {
email,
},
};
return res.status(201).json(sendConfirmRes);
}
|
6bf1c85eb1a611a57195ca1ad51e062f48f39d3a
|
TypeScript
|
RetroCraft/ics4u-culm
|
/src/Token.ts
| 3.734375
| 4
|
import { Keyword } from "./Keyword.js";
/**
* A JavaScript value that can be represented as other values.
*
* ex. `false === ![]`
*/
export class Token extends Keyword {
/**
* Parent keywords/tokens/primitives
*/
public keys: Keyword[];
/**
* Instantiate a Token
* @param value Name/literal value to replace for
* @param keys Obfuscated value as list of Keyword values
* @param priority Depth in tree
*/
public constructor(
value: string,
keys: Keyword[],
priority: number,
returnsString: boolean = true
) {
super();
this.value = value;
this.keys = keys;
this.priority = priority;
this.returnsString = returnsString;
console.assert(
priority > 0,
"Priority of Token should be non-zero. Use Primitive for base Keywords."
);
}
/**
* @inheritdoc
*/
public toString() {
return this.keys.join("");
}
}
|
3243aabc319c26b4050065a123a23790b005eeb4
|
TypeScript
|
sanderlab/AlignmentViewer2.0
|
/src/common/__tests__/Utils.test.ts
| 3.171875
| 3
|
import { stringToColor } from "../Utils";
const defaultColor = {
hex: "#000000",
rgb: { red: 0, green: 0, blue: 0 }
};
describe("Utilities", () => {
describe("stringToColor", () => {
it("Should fail to convert hex shorthand with no hash and be default.", () => {
expect(stringToColor("fff")).toEqual(defaultColor);
});
it("Should convert hex shorthand with a hash.", () => {
const expected = {
hex: "#ffffff",
rgb: { red: 255, green: 255, blue: 255 }
};
expect(stringToColor("#fff")).toEqual(expected);
});
it("Should fail to convert hex with no hash and be default.", () => {
expect(stringToColor("00ffff")).toEqual(defaultColor);
});
it("Should convert hex with a hash.", () => {
const expected = {
hex: "#ff00ff",
rgb: { red: 255, green: 0, blue: 255 }
};
expect(stringToColor("#ff00ff")).toEqual(expected);
});
it("Should convert color name.", () => {
const expected = {
hex: "#008000",
rgb: { red: 0, green: 128, blue: 0 }
};
expect(stringToColor("green")).toEqual(expected);
});
it("Should fail to convert fake color name and result in default.", () => {
expect(stringToColor("NotGreenBlue")).toEqual(defaultColor);
});
/*
it("Should throw an error on a bad hex.", () => {
const expected = "Bad Hex";
expect(() => stringToColor("")).toThrowError(expected);
expect(() => stringToColor("gggggg")).toThrowError(expected);
expect(() => stringToColor("ggg")).toThrowError(expected);
expect(() => stringToColor("#gggggg")).toThrowError(expected);
expect(() => stringToColor("#ggg")).toThrowError(expected);
expect(() => stringToColor("-gggggg")).toThrowError(expected);
expect(() => stringToColor("-ggg")).toThrowError(expected);
expect(() => stringToColor("-#gggggg")).toThrowError(expected);
expect(() => stringToColor("-#ggg")).toThrowError(expected);
expect(() => stringToColor("#-gggggg")).toThrowError(expected);
expect(() => stringToColor("#-ggg")).toThrowError(expected);
});*/
});
});
|
755c730ce0a697c1fd56530e08598d56a314cc34
|
TypeScript
|
ashikalik/avanto
|
/src/app/core/service/language-setting.service.ts
| 2.796875
| 3
|
import { Injectable, Inject, PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from '@angular/common';
/**
* LanguageSettingService service class
* Stores the current language in local storage
*/
@Injectable({
providedIn: "root"
})
export class LanguageSettingService {
/** The key for language */
private languageKey: string;
private directionKey: string;
private startDirectionKey: string;
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
this.languageKey = "CURRENT_LANGUAGE";
this.directionKey = "CURRENT_DIRECTION";
this.startDirectionKey = "START_DIRECTION";
}
// public getLanguage() {
// return "ar";
// }
/**
* Store language in local storage
* @param { string } language - The language
* @return { void }
*/
public setLanguage(language: string) {
if (isPlatformBrowser(this.platformId)) {
localStorage.setItem(this.languageKey, language);
}
}
/**
* Retrieve language from local storage
* @param { none }
* @return { String } - The language
*/
public getLanguage() {
if (isPlatformBrowser(this.platformId)) {
const language: string = localStorage.getItem(this.languageKey);
if (language) {
return language;
}
}
this.setLanguage("ar");
return "ar";
}
/**
* Remove language from local storage
* @param { none }
* @return { void }
*/
public removeLanguage() {
if (isPlatformBrowser(this.platformId)) {
localStorage.removeItem(this.languageKey);
}
}
}
|
8862be49451e26623a3f3067082dc5dff98965ba
|
TypeScript
|
shailendrasharma83/aws-apigw-lambda-dynamodb-typescript
|
/src/scalar/SensorDataBuilder.ts
| 2.609375
| 3
|
import {SensorData} from "./SensorData";
import { Payload } from "./Payload";
import {SensorDataService} from "../services/sensor-data.service";
import {ResponseBuilder} from "../shared/response-builder";
export class SensorDataBuilder implements Partial<SensorData>{
SensorId: string;
TimeStamp: Date;
Topic: string;
Payload: Payload
public constructor() {
}
withSensorId(value: string): this & Pick<SensorData, 'SensorId'> {
return Object.assign(this, { SensorId: value });
}
withTimeStamp(value: Date): this & Pick<SensorData, 'Timestamp'> {
return Object.assign(this, { Timestamp: value });
}
withTopic(value: string): this & Pick<SensorData, 'Topic'> {
return Object.assign(this, { Topic: value });
}
withPayload(value: Payload): this & Pick<SensorData, 'Payload'> {
return Object.assign(this, { Payload: value });
}
build(this: SensorData) {
return new SensorData(this);
}
}
|
1c8dfb24bc84e5027d1558c77bcdb92df3fe33b7
|
TypeScript
|
AdamDKing/training-code
|
/4-web/angular-demo/src/app/pipe.component.ts
| 2.546875
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-pipe',
template: `
<p>
Pipes are a way to write display-value transformations that you can declare in your HTML.<br>
Current date w/o pipe: {{ currentTime }}<br>
Current date with medium date and lowercase pipes: {{currentTime | date:'medium' | lowercase}}<br>
</p>
`,
styles: []
})
export class PipeComponent implements OnInit {
currentTime: Date
constructor() { }
ngOnInit() {
setInterval(() => { this.currentTime = new Date(); }, 1000 );
}
}
|
3fa434f0f2f7455e9bd71ce2fda56bcdcfee27cf
|
TypeScript
|
tjrexer/webiny-js
|
/packages/app-page-builder-editor/src/contexts/compose.ts
| 3.125
| 3
|
export const composeAsync = (functions: Array<Function> = []): Function => {
return (input: unknown): Promise<any> => {
if (!functions.length) {
return Promise.resolve();
}
// Create a clone of function chain to prevent modifying the original array with `shift()`
let index = -1;
const next = (input: unknown) => {
index++;
const fn = functions[index];
if (!fn) {
return Promise.resolve(input);
}
return new Promise(async (resolve, reject) => {
try {
resolve(await fn(input, next));
} catch (e) {
reject(e);
}
});
};
return next(input);
};
};
export const composeSync = (functions: Array<Function> = []): Function => {
return (input: unknown) => {
if (!functions.length) {
return input;
}
// Create a clone of function chain to prevent modifying the original array with `shift()`
let index = -1;
const next = (input: unknown) => {
index++;
const fn = functions[index];
if (!fn) {
return input;
}
return fn(input, next);
};
return next(input);
};
};
|
0ea74a09de1b5b22ca0e7b5405d8d2d28f99e4a7
|
TypeScript
|
pandy123/documentPerisistence
|
/src/persistent/converter/DateTimeConverter.ts
| 2.90625
| 3
|
import { PersistentAccessEnum } from '../PersistentAccessEnum';
import { PersistentAnnotation } from '../PersistentAnnotation';
import { PersistentContext } from '../PersistentContext';
import { PersistentFactory } from '../PersistentFactory';
import { FieldConverter } from './FieldConverter';
/**
* 时间日期持久化器。
*/
export class DateTimeConverter extends FieldConverter {
/** 格式 */
public format: string;
/**
* 构造处理。
*/
public constructor(accessCd: PersistentAccessEnum = PersistentAccessEnum.GetSet, format: string = 'YYYYMMDDHH24MISS') {
super(accessCd);
// 设置属性
this.format = format;
}
/**
* 加载设置信息。
*
* @param factory 工厂
* @param context 环境
* @param item 内容
* @param config 设置
* @param annotation 描述器
*/
public load(factory: PersistentFactory, context: PersistentContext, item: any, config: any, annotation: PersistentAnnotation) {
// 获得数据
var value = this.getDataValue(annotation, config);
// 加载数据
var datetime = item[annotation.name];
if (value) {
if (value.constructor == String) {
datetime.parse(value as string, this.format);
} else if (value.time) {
datetime.set(value.time);
}
}
}
/**
* 存储设置信息。
*
* @param factory 工厂
* @param context 环境
* @param item 内容
* @param config 设置
* @param annotation 描述器
*/
public save(factory: PersistentFactory, context: PersistentContext, item: any, config: any, annotation: PersistentAnnotation) {
var datetime = item[annotation.name];
if (datetime) {
var value = datetime.format(this.format);
if (!value != null) {
this.setDataValue(annotation, config, value);
}
}
}
/**
* 复制设置信息。
*
* @param factory 工厂
* @param context 环境
* @param source 来源
* @param target 目标
* @param annotation 描述器
*/
public copy(factory: PersistentFactory, context: PersistentContext, source: any, target: any, annotation: PersistentAnnotation) {
var name = annotation.name;
var sourceDateTime = source[name];
var targetDateTime = target[name];
targetDateTime.assign(sourceDateTime);
}
}
|
13ada6f272e575a51f26a3cc7eebc3bdf6af22b9
|
TypeScript
|
Rian8337/Alice
|
/src/database/managers/aliceDb/ChannelDataCollectionManager.ts
| 2.828125
| 3
|
import { DatabaseCollectionManager } from "@alice-database/managers/DatabaseCollectionManager";
import { ChannelActivity } from "@alice-database/utils/aliceDb/ChannelActivity";
import { DatabaseChannelActivity } from "@alice-structures/database/aliceDb/DatabaseChannelActivity";
import { Collection as DiscordCollection } from "discord.js";
/**
* A manager for the `channelactivity` collection.
*/
export class ChannelActivityCollectionManager extends DatabaseCollectionManager<
DatabaseChannelActivity,
ChannelActivity
> {
protected override readonly utilityInstance: new (
data: DatabaseChannelActivity
) => ChannelActivity = ChannelActivity;
override get defaultDocument(): DatabaseChannelActivity {
const date: Date = new Date();
date.setUTCHours(0, 0, 0, 0);
return {
timestamp: date.getTime(),
channels: [],
};
}
/**
* Gets channel statistics based on the given range.
*
* @param from The minimum time range.
* @param to The maximum time range.
* @returns The channel statistics from the given range.
*/
getFromTimestampRange(
from: number,
to: number
): Promise<DiscordCollection<number, ChannelActivity>> {
return this.get("timestamp", {
timestamp: {
$gte: from,
$lte: to,
},
});
}
}
|
c5d5b5756731a97de1e2e9eab7c072f2ba4fd718
|
TypeScript
|
akheron/optics-ts
|
/src/standalone/reread.tspec.ts
| 3.15625
| 3
|
import { expectType } from './test-utils.tspec.js'
import * as O from '.'
import type { Expected } from './errors.js'
const optic = O.reread((x: string) => x.toUpperCase())
describe('reread', () => {
it('get - source not of the correct type', () => {
const result = O.get(optic, true)
expectType<Expected<string, boolean>>()(result)()
const result2 = O.get(optic, null)
expectType<Expected<string, null>>()(result2)()
const result3 = O.get(optic, undefined)
expectType<Expected<string, undefined>>()(result3)()
})
it('set - source not of the correct type', () => {
const result = O.set(optic, 'foo', 123)
expectType<Expected<string, number>>()(result)()
})
it('set - value not an array', () => {
const result = O.set(optic, 123, 'foo')
expectType<Expected<string, number>>()(result)()
})
})
|
75facc0adb078b064bea404c3093e1e9e6971da7
|
TypeScript
|
ElliotZacharoff/hypixel-translators-bot
|
/src/commands/Info/thread.ts
| 2.53125
| 3
|
import { Command, GetStringFunction } from "../../index"
const command: Command = {
name: "thread",
description: "Gives you a link to the thread announcing this discord",
cooldown: 120,
allowDM: true,
channelWhitelist: ["549894938712866816", "624881429834366986", "730042612647723058", "551693960913879071"], // bots staff-bots bot-development admin-bots
async execute(interaction, getString: GetStringFunction) {
await interaction.reply(getString("thread", { thread: "<https://hypixel.net/threads/1970571>" }))
}
}
export default command
|
a646c69b7370813c90bbb7344f2987854ddb7141
|
TypeScript
|
nohanna/angular-micro-frontends
|
/projects/shared/src/lib/pipes/prefix.pipe.ts
| 2.578125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { ActivatedRoute, UrlSegment } from '@angular/router';
@Pipe({
name: 'prefix',
})
export class PrefixPipe implements PipeTransform {
constructor(private route: ActivatedRoute) {}
transform(route: string[]): string[] {
const segments: UrlSegment[] = this.route.firstChild?.snapshot?.url;
if (segments?.length > 0) {
const paths: string[] = segments.map((s: UrlSegment) => s.path);
const prefix: string[] = paths && paths.includes('second') ? paths : [];
return [...prefix, ...route];
} else {
return route;
}
}
}
|
df9587ab344fb5d33805511ff777414af02bce0d
|
TypeScript
|
moovin-hackathon/anunnakis-backend
|
/src/Repository/Contract.ts
| 2.765625
| 3
|
export abstract class RepositoryContract {
protected applyPaginator (filter: FilterDefault, options: any) {
const page = this.getPage(filter)
const size = this.getSize(filter)
options.offset = (page - 1) * size
options.limit = size
}
protected getPage (filter: FilterDefault) {
let page = 1
if (parseInt(filter.page) > 0) {
page = parseInt(filter.page)
}
return page
}
protected getSize (filter: FilterDefault) {
let size = 15
if (parseInt(filter.size) > 0) {
size = parseInt(filter.size)
if (parseInt(filter.size) > 100) {
size = 100
}
}
return size
}
}
export interface FilterDefault {
page?: string
size?: string
}
|
a2821cdb3773caf0a5327d3776b3b6e47af25678
|
TypeScript
|
mcaon/coopera-favela-back
|
/models.ts
| 2.53125
| 3
|
const ProducModel = {
id: '66a405cb-ec37-4a6b-b91f-a2c979002ba6',
name: 'Bolo de Laranja',
value: 38.5,
description: 'Bolo de Laranja sem cobertura',
image: 'iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB',
};
const DeliverymanModel = {
id: 'ac105d65-7c26-479c-94a3-cdac214016d2',
name: 'Pedro Bastos',
};
const OrderModel = {
id: 'ad8459be-00a3-4d4b-9cb7-aea0063d5116',
products: [
{
id: '66a405cb-ec37-4a6b-b91f-a2c979002ba6',
name: 'Bolo de Laranja',
value: 38.5,
},
],
address: 'Rua Dionéis, 25 - Rocinha - RJ',
};
const DeliveryModel = {
id: '117983ee-54f5-41d5-84ad-5c0a8f51fc2d',
order: {
id: 'ad8459be-00a3-4d4b-9cb7-aea0063d5116',
products: [
{
id: '66a405cb-ec37-4a6b-b91f-a2c979002ba6',
name: 'Bolo de Laranja',
value: 38.5,
},
],
address: 'Rua Dionéis, 25 - Rocinha - RJ',
},
deliveryman: {
id: 'ac105d65-7c26-479c-94a3-cdac214016d2',
name: 'Pedro Bastos',
},
};
// 1 Order => n Products
// 1 Delivery => 1 Order
// 1 Delivery => 1 Deliveryman
const models = {
ProducModel,
DeliverymanModel,
OrderModel,
DeliveryModel,
};
export default models;
|
9a91b4061f88d754fee8f3e8d8296af5b38617c9
|
TypeScript
|
bookmarkbao/vscode-jest
|
/src/setup-wizard/wizard-helper.ts
| 2.78125
| 3
|
/**
* helper functions that are used across components/files
*/
import * as vscode from 'vscode';
import * as path from 'path';
import {
WizardStatus,
WizardAction,
ActionableMenuItem,
ActionMenuOptions,
ActionableButton,
WizardSettings,
JestSettings,
ConfigEntry,
ActionableMessageItem,
WizardContext,
ActionMessageType,
ActionInputBoxOptions,
ActionInputResult,
ActionableMenuResult,
ActionMenuInput,
ActionInput,
isActionableButton,
} from './types';
export const jsonOut = (json: unknown): string => JSON.stringify(json, undefined, 4);
export const actionItem = <T = WizardStatus>(
id: number,
label: string,
detail: string,
action: WizardAction<T>
): ActionableMenuItem<T> => ({
id,
label,
detail,
action,
});
/**
* methods to handle button click in vscode UI
* @param button should be either ActionableButton or the system BackButton.
* @returns
*/
const handleButtonClick = <T>(button: vscode.QuickInputButton): ActionableButton<T> | undefined => {
if (button === vscode.QuickInputButtons.Back) {
return undefined;
}
if (isActionableButton(button)) {
return button as ActionableButton<T>;
}
throw new Error(`expect actionableButton but got ${JSON.stringify(button)}`);
};
/**
*
* @param items
* @param options
* @returns the selected item or undefined if no selection (esc or backButton click)
*/
export const showActionMenu = async <T = WizardStatus>(
items: ActionableMenuItem<T>[],
options: ActionMenuOptions<T> = {}
): Promise<ActionableMenuResult<T>> => {
const quickPick = vscode.window.createQuickPick<ActionableMenuItem<T>>();
quickPick.items = items;
quickPick.title = options.title;
quickPick.value = options.value || '';
quickPick.placeholder = options.placeholder;
quickPick.canSelectMany = false;
quickPick.ignoreFocusOut = true;
if (options.rightButtons) {
quickPick.buttons = options.rightButtons;
}
if (options.enableBackButton) {
quickPick.buttons = [vscode.QuickInputButtons.Back, ...(quickPick.buttons || [])];
}
const logging = options?.verbose
? (msg: string): void => console.log(`<showActionMenu> ${msg}`)
: undefined;
try {
const input = await new Promise<ActionMenuInput<T>>((resolve) => {
quickPick.onDidChangeSelection((selectedItems) =>
selectedItems.length === 1 ? resolve(selectedItems[0]) : resolve(undefined)
);
quickPick.onDidTriggerButton((button) => resolve(handleButtonClick(button)));
quickPick.show();
if (
options.selectItemIdx != null &&
options.selectItemIdx >= 0 &&
options.selectItemIdx < items.length
) {
quickPick.selectedItems = [items[options.selectItemIdx]];
}
});
if (!input) {
logging?.('no selection is made');
return undefined;
}
if (input === vscode.QuickInputButtons.Back) {
logging?.('back button is clicked');
return undefined;
}
logging?.(`"${isActionableButton(input) ? `button ${input.id}` : input.label}" is selected`);
return input.action();
} catch (e) {
return Promise.reject(e);
} finally {
quickPick.dispose();
}
};
/**
*
* @param title
* @param value
* @param options
* @returns string if "enter", undefined if "ESC" or backButton click
*/
export const showActionInputBox = async <T = WizardStatus>(
options?: ActionInputBoxOptions<T>
): Promise<ActionInputResult<T>> => {
const inputBox = vscode.window.createInputBox();
inputBox.title = options?.title;
inputBox.value = options?.value || '';
inputBox.prompt = options?.prompt;
inputBox.ignoreFocusOut = true;
inputBox.buttons = options?.rightButtons || [];
if (options?.enableBackButton) {
inputBox.buttons = [vscode.QuickInputButtons.Back, ...inputBox.buttons];
}
const logging = options?.verbose
? (msg: string): void => console.log(`<ShowActionInputBox> ${msg}`)
: undefined;
try {
const input = await new Promise<ActionInput<T>>((resolve) => {
inputBox.onDidAccept(() => resolve(inputBox.value));
inputBox.onDidHide(() => resolve(undefined));
inputBox.onDidTriggerButton((button) => resolve(handleButtonClick(button)));
inputBox.show();
});
if (!input) {
logging?.(`no input received`);
return undefined;
}
if (input === vscode.QuickInputButtons.Back) {
logging?.(`back button is clicked`);
return undefined;
}
if (isActionableButton(input)) {
logging?.(`button ${input.id} is clicked: `);
return input.action();
}
logging?.(`input box received "${input}"`);
return input;
} catch (e) {
return Promise.reject(e);
} finally {
inputBox.dispose();
}
};
export const showActionMessage = async <T = WizardStatus>(
type: ActionMessageType,
message: string,
...buttons: ActionableMessageItem<T>[]
): Promise<ActionableMenuResult<T>> => {
let button;
switch (type) {
case 'info':
button = await vscode.window.showInformationMessage(message, { modal: true }, ...buttons);
break;
case 'warning':
button = await vscode.window.showWarningMessage(message, { modal: true }, ...buttons);
break;
case 'error':
button = await vscode.window.showErrorMessage(message, { modal: true }, ...buttons);
break;
}
return await button?.action();
};
export const getConfirmation = async (
type: ActionMessageType,
msg: string,
yesTitle = 'Yes',
noTitle = 'No',
onCancel: 'yes' | 'no' = 'no'
): Promise<boolean> => {
const choice = await showActionMessage(
type,
msg,
{
id: 1,
title: yesTitle,
isCloseAffordance: onCancel === 'yes',
action: () => Promise.resolve(true),
},
{
id: 0,
title: noTitle,
isCloseAffordance: onCancel === 'no',
action: () => Promise.resolve(false),
}
);
return choice ?? onCancel === 'yes' ? true : false;
};
export const DEBUG_CONFIG_PLATFORMS = ['windows', 'linux', 'osx'];
const getRuntimeExecutable = (
cmd: string,
args: string[]
): Partial<vscode.DebugConfiguration | undefined> => {
const commonConfig = {
program: undefined,
};
if (cmd === 'npm') {
const extraArgs = args.includes('--') ? [] : ['--'];
return { runtimeExecutable: 'npm', args: extraArgs, ...commonConfig };
}
if (cmd === 'yarn') {
return { runtimeExecutable: 'yarn', args: [], ...commonConfig };
}
};
// regex to match surrounding quotes
const cmdQuotesRegex = /^["']+|["']+$/g;
export const cleanupCommand = (command: string): string => command.replace(cmdQuotesRegex, '');
// regex that match single, double quotes and "\" escape char"
const cmdSplitRegex = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([^\s'"]+)/g;
export const parseCmdLine = (cmdLine: string): string[] => {
const parts = cmdLine.match(cmdSplitRegex) || [];
// clean up command
if (parts.length > 0) {
parts[0] = cleanupCommand(path.normalize(parts[0]));
}
return parts;
};
/**
* perform cmdLine validation check:
* 1. for npm script, make sure there is a '--' argument
*
* @param cmdLine
* @ return invalid reason or undefined if it's valid
*/
export const validateCommandLine = (cmdLine: string): string | undefined => {
const [cmd, ...cmdArgs] = parseCmdLine(cmdLine);
if (!cmd || cmd.trim() === '') {
return 'command line can not be empty';
}
if (cmd.trim().toLowerCase() === 'npm') {
if (!cmdArgs.includes('--')) {
return 'npm run-script should include flag "--" so the extension can append extra arguments at run time';
}
}
};
/**
* create new debug config by merging the given command line and root-path accordingly.
* @param config
* @param cmdLine t
* @param absoluteRootPath if given, will be used as "cwd" of the debug config. If the commandLine uses relative path, it will be converted to
* absolute path based on this root path; otherwise it will be converted relative to the "${workspaceFolder}"
* @param preservePlatformSections
*/
export const mergeDebugConfigWithCmdLine = (
config: vscode.DebugConfiguration,
cmdLine: string,
absoluteRootPath?: string,
preservePlatformSections = false
): vscode.DebugConfiguration => {
const [cmd, ...cmdArgs] = parseCmdLine(cmdLine);
if (!cmd) {
throw new Error(`invalid cmdLine: ${cmdLine}`);
}
let finalConfig: vscode.DebugConfiguration;
const { cwd, args: configArgs, ...restConfig } = config;
const _cwd = absoluteRootPath ? absoluteRootPath : cwd;
const rteConfig = getRuntimeExecutable(cmd, cmdArgs);
if (rteConfig) {
const { args: rteConfigArgs = [], ...restRteConfig } = rteConfig;
finalConfig = {
...restConfig,
cwd: _cwd,
...restRteConfig,
args: [...cmdArgs, ...rteConfigArgs, ...configArgs],
};
} else {
// convert the cmd to absolute path
const p = path.isAbsolute(cmd)
? cmd
: absoluteRootPath
? path.join(absoluteRootPath, cmd)
: ['${workspaceFolder}', cmd].join(path.sep);
finalConfig = { ...restConfig, cwd: _cwd, program: p, args: [...cmdArgs, ...configArgs] };
}
if (!preservePlatformSections) {
DEBUG_CONFIG_PLATFORMS.forEach((p) => delete finalConfig[p]);
}
return finalConfig;
};
/**
* get releveant settings from vscode config (settings.json and launch.json) of the given workspace
* @param workspace
*/
export const getWizardSettings = (workspace: vscode.WorkspaceFolder): WizardSettings => {
const wsSettings: WizardSettings = {};
// populate jest settings
const jestSettings = vscode.workspace.getConfiguration('jest', workspace.uri);
JestSettings.forEach((name) => {
const value = jestSettings.get<string>(name)?.trim();
if (!value) {
return;
}
wsSettings[name] = value;
if (name === 'rootPath' && value) {
const rootPath = cleanupCommand(value);
wsSettings['absoluteRootPath'] = path.normalize(
path.isAbsolute(rootPath) ? rootPath : path.join(workspace.uri.fsPath, rootPath)
);
}
});
// populate debug config settings
const value = vscode.workspace
.getConfiguration('launch', workspace.uri)
.get<vscode.DebugConfiguration[]>('configurations');
if (value) {
wsSettings['configurations'] = value;
}
return wsSettings;
};
export const createSaveConfig =
(context: WizardContext) =>
(...entries: ConfigEntry[]): Promise<void> => {
const { workspace, message } = context;
const config = vscode.workspace.getConfiguration(undefined, workspace.uri);
const promises = entries.map((e) => {
message(`Updating "${e.name}" in vscode`);
return config.update(e.name, e.value, vscode.ConfigurationTarget.WorkspaceFolder);
});
return Promise.all(promises)
.then(() => {
message(`All updates saved successfully`);
})
.catch((e) => {
message(`Some config.update failed: ${jsonOut(e)}`);
throw e;
});
};
|
e99bae4b58c346a4ce34acd97e52502d3b275189
|
TypeScript
|
fearthecowboy/scratchpad
|
/compute/2015-06-15/models/DiskInstanceView.ts
| 2.703125
| 3
|
import { InstanceViewStatus } from './InstanceViewStatus';
/**
* @description The instance view of the disk.
*/
export interface DiskInstanceView {
/**
* @description The disk name.
*/
name: string;
/**
* @description The resource status information.
*/
statuses: Array<InstanceViewStatus>;
}
|
2762aa9d7e56139b055d39637d85d8166b9b8e00
|
TypeScript
|
Xananax/gameover
|
/src/utils/Signal/CounterSignal/CounterSignal.d.ts
| 2.53125
| 3
|
/// <reference path="../Signal/Signal.d.ts" />
interface CounterSignal extends Signal<any,any>{
increment(n?:number):CounterSignal;
decrement(n?:number):CounterSignal;
isCounterSignal:boolean;
count:number;
}
|
52cd0654d7d8f6fb934b959f4787e9be2d34f398
|
TypeScript
|
ZnoGouDj/codewars-challenges
|
/7kyu/7kyu-find-the-longest-gap.ts
| 4.125
| 4
|
// A binary gap within a positive number num is any sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of num.
// For example:
// 9 has binary representation 1001 and contains a binary gap of length 2.
// 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3.
// 20 has binary representation 10100 and contains one binary gap of length 1.
// 15 has binary representation 1111 and has 0 binary gaps.
// Write function gap(num) that, given a positive num, returns the length of its longest binary gap.
// The function should return 0 if num doesn't contain a binary gap.
// Test.assertEquals(gap(9),2);
// Test.assertEquals(gap(529),4);
// Test.assertEquals(gap(20),1);
// Test.assertEquals(gap(15),0);
function gap(num: number): number {
let binary: string[] = Array.from(num.toString(2));
let counter = 0;
let finArr = [];
for (let i = 0; i < binary.length; i++) {
if (binary[i] === '0') {
counter++;
} else {
finArr.push(counter);
counter = 0;
}
}
finArr.sort();
return finArr[finArr.length - 1];
}
//top
const gap1 = (num: number): number => (num.toString(2).match(/10+(?=1)/g) || [' ']).sort().pop().length - 1;
//top2
function gap2(num: number): number {
let binary = num.toString(2);
let zeros = binary.match(/0+(?=1)/g) || [''];
let longest = zeros.sort().pop();
return longest.length;
}
|
255fc324700b1731691cde6e43ae6ea525e3038a
|
TypeScript
|
OlaIstra/cleevio
|
/src/store/reducers/trips.ts
| 3.140625
| 3
|
import * as actionTypes from '../actions/actionTypes'
import { ActionTripType } from '../actions/trips'
export type Country = {
id?: string
value: string
text: string
icon: string
}
export type ErrorType = {
message: string
}
type InitialStateType = {
countries: Array<Country>
loading: boolean
error: null | ErrorType
}
const initialState: InitialStateType = {
countries: [],
loading: false,
error: null,
}
export const tripsReducer = (state = initialState, action: ActionTripType): InitialStateType => {
switch (action.type) {
case actionTypes.FETCH_TRIPS_START:
return {
...state,
loading: true,
error: null,
}
case actionTypes.FETCH_TRIPS_SUCCESS:
return {
...state,
loading: false,
countries: action.countries,
error: null,
}
case actionTypes.FETCH_TRIPS_FAIL:
return {
...state,
loading: false,
error: action.error,
}
default:
return state
}
}
|
e8cbb1e633218bc25be98b1471c955078973733d
|
TypeScript
|
Daru13/interactive-turing-machine
|
/src/ts/view/graph-interaction/pen-and-touch/Touch.ts
| 3.09375
| 3
|
import { Graph } from "../../Graph";
import { TuringMachine } from "../../../model/TuringMachine";
import { ModifiedPointerEvent } from "../ModifiedPointerEvent";
import { NodeTool } from "../tools/NodeTool";
/**
* A class to define actions to do when a user uses touch
*/
export class Touch{
/** node tool associated to touch. */
nodeTool : NodeTool;
/** turing machine to pass to the node tool. */
turingMachine: TuringMachine;
constructor(graph: Graph, turingMachine: TuringMachine) {
this.turingMachine = turingMachine;
this.nodeTool = new NodeTool(graph, turingMachine);
}
/**
* Action when the touch is down
* @param e
*/
pointerDown(e: ModifiedPointerEvent): void {
this.nodeTool.pointerDown(e);
}
/**
* Action when the touch moves
* @param e
*/
pointerMove(e: ModifiedPointerEvent): void {
this.nodeTool.pointerMove(e);
}
/**
* Action when the touch is up
* @param e
*/
pointerUp(e: ModifiedPointerEvent): void {
this.nodeTool.pointerUp(e);
}
/**
* Action when the touch leaves
* @param e
*/
pointerLeave(e: ModifiedPointerEvent): void {
this.nodeTool.pointerLeave(e);
}
/**
* Action when the touch clicks
* @param e
*/
click(e: ModifiedPointerEvent): void {
this.nodeTool.pointerClick(e);
}
}
|
2cbd065f720319da991278d954f9ebeaa1f642a9
|
TypeScript
|
ArchitectingSoftware/se575-container-demo
|
/rest-node-koa/src/app.ts
| 2.671875
| 3
|
import * as Koa from 'koa'
import * as Router from 'koa-router'
import {PaperDB, IPaper} from './paperDB'
import Axios from 'axios'
import * as config from './config.json'
let app = new Koa();
let router = new Router();
// Environmental Setup
const environment = process.env.NODE_ENV || 'development'
let envConfig = config[environment.toLowerCase()]
if(!envConfig){
let msg = "Cant find the desired configuration for environment variable NODE_ENV " +
"that is currently set to " + process.env.NODE_ENV + " using environment " +
"for development as default. If you think this might be incorrect please "+
"check and likely adjust the config.json file."
console.log(msg)
envConfig = config['development']
}
console.log('Using this configuration: ',envConfig)
//Get all publications from the PaperDB object
router.get('/publications', async http => {
http.response.body = PaperDB
})
//Filter on the PaperDB object by paper id
router.get('/publications/:id', async http => {
let id = http.params['id']
//http.response.body = http.params['id']
let paper = PaperDB.find(p => p.id == id)
if (paper)
http.response.body = paper
else
http.response.ctx.throw(404)
})
//Get data from a remote (micro)service using the Axios http client. This client
//return a promise thus the await on the caller side.
async function getRemoteUrlData(url: string){
try{
const response = await Axios.get(url)
return response.data
} catch(error){
console.log ('Error from fetching url data ',error)
return null
}
}
//Get a particular paper by its id and enrich with location information
router.get('/publications/:id/location', async http => {
let id = http.params['id']
//adding an optional location_details option that is provided from a
//companion service
let paper: IPaper & {location_details?: any} = PaperDB.find(p => p.id == id)
if (paper) {
const remoteUrl = "http://"+envConfig.code_host+":"+envConfig.code_port+"/url/"+paper.code
let rData = await getRemoteUrlData(remoteUrl)
if(rData)
paper.location_details = rData
http.response.body = paper
}
else
http.response.ctx.throw(404)
})
//Now setup the internal middleware and listen for connections on target
//port based on the configuration
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(envConfig.local_port);
console.log('Server started on port', envConfig.local_port)
|
da2c62f4fd1f6cc308354675abfef278e3f9f097
|
TypeScript
|
blocklycraft/MineBlock
|
/src/mineblock.ts
| 2.53125
| 3
|
import * as vscode from 'vscode';
import * as path from 'path';
import * as util from './util';
export class MineBlock {
static context: vscode.ExtensionContext;
constructor(_context: vscode.ExtensionContext) {
MineBlock.context = _context;
this.regEventListeners();
this.checkEditor();
}
private checkEditor(): void {
if (vscode.window.activeTextEditor) {
if (path.extname(vscode.window.activeTextEditor.document.fileName) === '.mineblock') {
let file = vscode.window.activeTextEditor.document.fileName;
vscode.commands.executeCommand('workbench.action.closeActiveEditor').then(() => {
util.Utils.regPanel(file);
});
}
}
}
private regEventListeners(): void {
//监听打开事件,并拦截指定文件
vscode.workspace.onDidOpenTextDocument(this.onOpenDoc);
//监听文件删除事件,并确定是否关闭编辑器
vscode.workspace.onDidDeleteFiles(this.onRmDoc);
//监听文件重命名事件,保证编辑器状态同步
vscode.workspace.onDidRenameFiles(this.onRnDoc);
}
private onOpenDoc(doc: vscode.TextDocument): void {
//判断扩展名
if (path.extname(doc.fileName) === '.mineblock') {
vscode.commands.executeCommand('workbench.action.closeActiveEditor').then(() => {
if (!util.Utils.hasPanel(doc.fileName)) {
util.Utils.regPanel(doc.fileName);
}else{
util.Utils.activePanel(doc.fileName);
}
});
}
}
private onRmDoc(e: vscode.FileDeleteEvent): void {
e.files.forEach((file) => {
if (path.extname(file.path) === '.mineblock' && util.Utils.hasPanel(file.fsPath)) {
util.Utils.closePanel(file.fsPath);
}
});
}
private onRnDoc(e: vscode.FileRenameEvent): void {
//重新打开编辑器
e.files.forEach((file)=>{
if(path.extname(file.oldUri.toString()) === '.mineblock'){
util.Utils.closePanel(file.oldUri.fsPath);
}
if(path.extname(file.newUri.toString()) === '.mineblock'){
if (!util.Utils.hasPanel(file.newUri.fsPath)) {
util.Utils.regPanel(file.newUri.fsPath);
}
}
});
}
}
|
392caa48dbb6da2072c2ae6253aa3300c02ee1f6
|
TypeScript
|
szpakm/redux-store-templates
|
/src/toggle/index.d.ts
| 2.515625
| 3
|
declare module "redux-store-templates/toggle";
import { Reducer } from "redux";
import { ApplyOptions } from "../models";
export type ToggleState = boolean;
/* create reducer */
export interface ToggleOptions {
initial?: boolean;
toggleOn?: ApplyOptions;
makeTrueOn?: ApplyOptions;
makeFalseOn?: ApplyOptions;
setOn?: ApplyOptions;
resetOn?: ApplyOptions;
}
export function createReducer(opt: ToggleOptions): Reducer<ToggleState>;
/* create selector */
export interface CreateSelectorOptions {
selector(state: any): ToggleState;
}
export function createSelector(
opt: CreateSelectorOptions
): (state: any) => ToggleState;
|
e81a011694c542c18086090827a1331b2e10c559
|
TypeScript
|
Failender/dgo-frontend
|
/app/src/app/routes/kampf/kampf-render/konva-util.ts
| 2.671875
| 3
|
import Konva from 'konva';
export function createImage(x: number, y: number, src: string, callback: (element) => any): void {
const image = new Image();
image.onload = () => {
const element = new Konva.Image({
width: image.width,
height: image.height,
x, y,
image
});
if (callback) {
callback(element);
}
};
image.src = src;
}
export function createGroup(x: number, y: number) {
return new Konva.Group({
x, y
});
}
export function createRect(x: number, y: number, width: number, height: number, fill: string, stroke: string, strokeWidth: number) {
return new Konva.Rect({
x, y, width, height, fill, stroke, strokeWidth
});
}
export function createCircle(x: number, y: number, radius: number, stroke: string, fill?: string) {
return new Konva.Circle({
x, y, radius, stroke, fill
});
}
|
bb090ac76e9f9727d046042f776ff79f927eae6f
|
TypeScript
|
papercuptech/eldc
|
/proto/test2.ts
| 2.875
| 3
|
/*
const install = Context.install
const {ARG_N, ARG_LAST, CLASS, FRAME,} = install
install([
['global',
['setTimeout',
['$', ARG_N(0)]
]
],
['child_process',
['exec',
['$', ARG_LAST],
['_',
['send', ['$', ARG_LAST]]
]
]
],
['global',
['FileReader',
['_',
['$',
['onload'],
['onerror'],
FRAME((moniker) => {
const onLoadSid = moniker.onload()
const onErrorSid = moniker.onerror()
return function(result) {
return install.frameObject()
}
})
]
],
]
],
['global',
['Something',
['prototype',
['_', // find owner of child
['upChain']
]
]
]
]
])
*/
/*
function Trap(...args:any[]) {
}
Initialize() {
}
Trap(Context.monikers.global.FileReader._.$.onload(), function(next, args) {//}, this_, link) {
return next(args)
})
const monikers = Context.monikers
Context.intercept(monikers.global.setTimeout)
const MyCtx = Context({contexualProp: 'default'})
MyCtx(() => {
MyCtx.contextualProp = 'Parent'
console.log(MyCtx.id, 'before', MyCtx.contextualProp)
MyCtx(() => {
MyCtx.contextualProp = 'Child 1'
setTimeout(() => console.log(MyCtx.id, MyCtx.contextualProp), 100)
})
MyCtx({contextualProp: 'Child 2'},
async () => await new Promise(resolve =>
setTimeout(() => {
console.log(MyCtx.id, MyCtx.contextualProp)
resolve()
}, 200)
)
)
const myCtxFactory = MyCtx({contexualProp: 'Factory Default'})
myCtxFactory(() => {
MyCtx.contextualProp == 'Step Child'
setTimeout(() => console.log(MyCtx.id, MyCtx.contextualProp), 300)
})
myCtxFactory(() => {
setTimeout(() => console.log(MyCtx.id, MyCtx.contextualProp), 400)
})
console.log(MyCtx.id, 'after', MyCtx.contextualProp)
})
const throws = MyCtx.contextualProp
@newjs
export class Service {
perform(using) {console.log(`Default attempting ${using}...?`)}
}
class Provider {
perform(using) {console.log(`Look at me! I'm performing ${using}!!!`)}
}
box(Service, Provider)(() => {
const x = new Service()
if(!(x instanceof Service)) throw new Error('will never throw')
x.perform('a miracle')
})
const x = new Service()
if(!(x instanceof Service)) throw new Error('will never throw')
x.perform('a miracle')
box(
Service, class {
perform(using) {return `${using}?? Can't. I'm a mockery of the universe`}
}
)(() => {
const x = new Service()
if(!(x instanceof Service)) throw new Error('will never throw')
x.perform('a miracle')
})
box(Service, class Patch extends Service[newjs.Outer] {
perform(using) {return `${using}?? Can't. I'm a mockery of the universe`}
})(() => {
const x = new Service()
if(!(x instanceof Service)) throw new Error('will never throw')
x.perform('a miracle')
})
*/
/*
I wondered if javascript's `new` could be "highjacked" and then transformed into the ultimate object factory. This would mean dependency injection, mocking, and 'hot-patching' coudl all
*/
|
1680f89557e1195e73eceb9c4777eeb5bc012148
|
TypeScript
|
renanmav/relayable
|
/packages/server/src/modules/question/QuestionModel.ts
| 2.546875
| 3
|
import mongoose, { Schema, Document, Model } from 'mongoose'
import { IUser } from '../user/UserModel'
import { IAnswer } from '../answer/AnswerModel'
const questionSchema = new Schema(
{
content: {
type: String,
required: true,
},
upvotes: [
{
type: Schema.Types.ObjectId,
ref: 'User',
},
],
downvotes: [
{
type: Schema.Types.ObjectId,
ref: 'User',
},
],
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
views: [
{
type: Schema.Types.ObjectId,
ref: 'User',
},
],
anonymous_views: {
type: Number,
default: 0,
},
tags: { type: [String] },
answers: [
{
type: Schema.Types.ObjectId,
ref: 'Answer',
},
],
time_first_answer: Date,
},
{
timestamps: {
createdAt: 'createdAt',
updatedAt: 'updatedAt',
},
collection: 'question',
}
)
export interface IQuestion extends Document {
content: string
upvotes: IUser[]
downvotes: IUser[]
author: IUser | string
views: IUser[]
anonymous_views: number
tags?: string[]
answers: IAnswer[] | string[]
createdAt: Date
updatedAt: Date
time_first_answer: Date
}
const QuestionModel: Model<IQuestion> = mongoose.model('Question', questionSchema)
export default QuestionModel
|
199607709806036a550fdfffd0a619c9598b1822
|
TypeScript
|
qhun-engine/engine
|
/src/resource/sprite/SpriteImageExtractor.ts
| 2.59375
| 3
|
import { Injectable } from "@qhun-engine/base";
import { SpriteResource } from "./SpriteResource";
import { DimensionSize } from "../../constraint/Dimension";
import { ImageResource } from "./ImageResource";
import { ImageCropService } from "../util/ImageCropService";
import { Rectangle } from "../../math/Rectangle";
interface SpriteDecoupleResult extends DimensionSize {
/**
* name/number of the picture
*/
name: string | number;
/**
* the final image element for rendering
*/
image: ImageResource;
}
/**
* responsable for decoupling sprite images from a sprite sheet using
* the given metadata
*/
@Injectable()
export class SpriteImageExtractor {
constructor(
private cropService: ImageCropService
) { }
/**
* extracts all images from the sprite sheet using the given metadata
* @param sprite the sprite to get the data from
*/
public async extractImagesFromSpriteSheet(sprite: SpriteResource): Promise<SpriteDecoupleResult[]> {
const convertPromiseStack: Promise<SpriteDecoupleResult>[] = [];
// iterate over every possible sub file
const frames = sprite.getAnimation().frames;
Object.keys(frames).forEach(frameName => {
const frameData = frames[frameName];
// convert this frame into an image
const rect = new Rectangle(frameData.frame.x, frameData.frame.y, frameData.frame.w, frameData.frame.h);
convertPromiseStack.push(this.cropService.extractFromImage(sprite.getData(), rect).then(imageData => {
return {
name: frameName,
image: (new ImageResource("@internal:canvas", "@internal:canvas")).setData(imageData)
} as SpriteDecoupleResult;
}));
});
return Promise.all(convertPromiseStack);
}
}
|
76b85c901b3c02458a87820cc2b6bd75655762fc
|
TypeScript
|
mattallsop/hack-cambridge-website
|
/src/hc-scripts/teams/get.ts
| 2.546875
| 3
|
import { Hacker, HackerApplication, Team, TeamMember } from 'server/models';
import { createHandler } from '../utils';
import { getHackerFromEmailOrApplicationSlug } from './utils';
export default {
command: 'get <email|applicationId>',
desc: 'Get the team for a hacker',
aliases: [],
builder(yargs) {
return yargs;
},
// `email` represents an email or an application ID. We need to call this variable
// either "email" or "applicationId" to get the correct argument defined in the command.
handler: createHandler(async ({ email }) => {
const emailOrApplicationId = email;
const user = await getHackerFromEmailOrApplicationSlug(emailOrApplicationId);
const teamMember = await user.getTeam();
if (teamMember === null) {
throw new Error('Hacker is not in a team.');
}
const team = await Team.findOne({
where: {
id: teamMember.teamId
},
include: [
{
model: TeamMember,
required: true,
include: [
{
model: Hacker,
include: [{ model: HackerApplication }],
},
],
}
]
});
console.log(`${emailOrApplicationId} is in team ${team.id}. Members:`);
team.teamMembers.map(member =>
console.log(`* Hacker: ${member.hacker.id} ${member.hacker.firstName} ${member.hacker.lastName} <${member.hacker.email}>. ` +
`Application: ${member.hacker.hackerApplication.id} ${member.hacker.hackerApplication.applicationSlug}`));
})
};
|
8dd19316b59ee03e3cbac557813cf1ea2c57cbc1
|
TypeScript
|
nvh/web-build-tools
|
/apps/api-extractor/src/api/mixins/ApiFunctionLikeMixin.ts
| 2.640625
| 3
|
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.s
import { ApiItem, ApiItem_parent, IApiItemJson, IApiItemConstructor, IApiItemOptions } from '../model/ApiItem';
import { ApiParameter } from '../model/ApiParameter';
/** @public */
export interface IApiFunctionLikeMixinOptions extends IApiItemOptions {
overloadIndex: number;
parameters?: ApiParameter[];
}
export interface IApiFunctionLikeJson extends IApiItemJson {
overloadIndex: number;
parameters: IApiItemJson[];
}
const _overloadIndex: unique symbol = Symbol('ApiFunctionLikeMixin._overloadIndex');
const _parameters: unique symbol = Symbol('ApiFunctionLikeMixin._parameters');
/** @public */
// tslint:disable-next-line:interface-name
export interface ApiFunctionLikeMixin extends ApiItem {
readonly overloadIndex: number;
readonly parameters: ReadonlyArray<ApiParameter>;
addParameter(parameter: ApiParameter): void;
serializeInto(jsonObject: Partial<IApiItemJson>): void;
}
/** @public */
export function ApiFunctionLikeMixin<TBaseClass extends IApiItemConstructor>(baseClass: TBaseClass):
TBaseClass & (new (...args: any[]) => ApiFunctionLikeMixin) { // tslint:disable-line:no-any
abstract class MixedClass extends baseClass implements ApiFunctionLikeMixin {
public readonly [_overloadIndex]: number;
public readonly [_parameters]: ApiParameter[];
/** @override */
public static onDeserializeInto(options: Partial<IApiFunctionLikeMixinOptions>,
jsonObject: IApiFunctionLikeJson): void {
baseClass.onDeserializeInto(options, jsonObject);
options.overloadIndex = jsonObject.overloadIndex;
options.parameters = [];
for (const parameterObject of jsonObject.parameters) {
options.parameters.push(ApiItem.deserialize(parameterObject) as ApiParameter);
}
}
// tslint:disable-next-line:no-any
constructor(...args: any[]) {
super(...args);
const options: IApiFunctionLikeMixinOptions = args[0];
this[_overloadIndex] = options.overloadIndex;
this[_parameters] = [];
if (options.parameters) {
for (const parameter of options.parameters) {
this.addParameter(parameter);
}
}
}
public get overloadIndex(): number {
return this[_overloadIndex];
}
public get parameters(): ReadonlyArray<ApiParameter> {
return this[_parameters];
}
public addParameter(parameter: ApiParameter): void {
const existingParent: ApiItem | undefined = parameter[ApiItem_parent];
if (existingParent !== undefined) {
throw new Error(`This ApiParameter has already been added to another function: "${existingParent.name}"`);
}
this[_parameters].push(parameter);
parameter[ApiItem_parent] = this;
}
/** @override */
public serializeInto(jsonObject: Partial<IApiFunctionLikeJson>): void {
super.serializeInto(jsonObject);
jsonObject.overloadIndex = this.overloadIndex;
const parameterObjects: IApiItemJson[] = [];
for (const parameter of this.parameters) {
const parameterJsonObject: Partial<IApiItemJson> = {};
parameter.serializeInto(parameterJsonObject);
parameterObjects.push(parameterJsonObject as IApiItemJson);
}
jsonObject.parameters = parameterObjects;
}
}
return MixedClass;
}
/** @public */
export namespace ApiFunctionLikeMixin {
export function isBaseClassOf(apiItem: ApiItem): apiItem is ApiFunctionLikeMixin {
return apiItem.hasOwnProperty(_parameters);
}
}
|
2f6af738d058251d5860624b6dad1c2311e9d8c3
|
TypeScript
|
ptcmyanmar/Beyond-Horizon-Project
|
/src/reducers/browser.ts
| 2.65625
| 3
|
import {ActionPayload, Browser, BrowserPayload} from 'actions/interfaces';
import {
ADD_BROWSER_TAB,
ADD_TO_BROWSER_FAVORITES,
ADD_TO_BROWSER_HISTORY,
BROWSER_FOCUS,
CLEAR_BROWSER_HISTORY,
CLOSE_ALL_BROWSER_TABS,
CLOSE_BROWSER_TAB,
REMOVE_FROM_BROWSER_FAVORITES,
SET_ACTIVE_BROWSER_TAB,
UPDATE_BROWSER_TAB,
UPDATE_MANAGEMENT,
} from 'actions/types';
const browserReducer = (
state: Browser = {
history: [],
favorites: [],
tabs: [],
activeTab: null,
shouldFocus: false,
showManagement: false,
},
{type, payload}: ActionPayload<BrowserPayload>,
) => {
switch (type) {
case ADD_TO_BROWSER_HISTORY:
if (state.history.find((e) => e!.url === payload!.history!.url)) {
return state;
}
return {
...state,
history: [...state.history, payload!.history!],
};
case ADD_TO_BROWSER_FAVORITES:
const newFavorite = state.favorites;
newFavorite.push(payload!.favorite);
return {
...state,
favorites: newFavorite,
};
case REMOVE_FROM_BROWSER_FAVORITES:
return {
...state,
favorites: state.favorites.filter((item) => item.url !== payload.url),
};
case CLEAR_BROWSER_HISTORY:
return {
...state,
history: [],
};
case CLOSE_ALL_BROWSER_TABS:
return {
...state,
tabs: [],
};
case ADD_BROWSER_TAB:
if (payload!.id && payload!.url) {
return {
...state,
activeTab: payload!.id,
tabs: [...state.tabs, {url: payload!.url, id: payload!.id}],
};
} else return state;
case CLOSE_BROWSER_TAB:
const tabs = state.tabs.filter((tab) => tab!.id !== payload!.id);
return {
...state,
tabs,
};
case SET_ACTIVE_BROWSER_TAB:
return {
...state,
activeTab: payload!.id!,
};
case UPDATE_BROWSER_TAB:
return {
...state,
tabs: state.tabs.map((tab) => {
if (tab!.id === payload!.id) {
return {...tab, ...payload!.data};
}
return {...tab};
}),
};
case BROWSER_FOCUS:
return payload!.shouldFocus !== undefined
? {...state, shouldFocus: payload!.shouldFocus}
: state;
case UPDATE_MANAGEMENT:
return payload!.showManagement !== undefined
? {...state, showManagement: payload!.showManagement}
: state;
default:
if (state.favorites) return state;
return {...state, favorites: []};
}
};
export default browserReducer;
|
88c4aa0e7d8a4bc0c2dc81bc96e489174c353ef2
|
TypeScript
|
mglezsosa/type-or-treat-2020
|
/4.ts
| 3.46875
| 3
|
// You got roped into the cutest halloween competition, judging
// doggy halloween pet costumes at the annual parade.
declare function decideWinner(breed: string, costume: string): { name: string, video: string }
window.decideWinner = someoneElseDecides
// Oh, actually you didn't - someone else got to do the fun bit...
// Though you can watch it on zoom: http://www.tompkinssquaredogrun.com/halloween
// Instead, you've been asked to help tally up a scoreboard of the most
// popular costumes according to the most popular breeds. You've built
// out a quick implementation below, but it loses type information.
// Now the contest is over, you feel it's your duty to refactor this
// code to retain type information - you've heard that the 4.1 beta includes
// something which helps with typing string manipulation.
const breeds = ["Hound", "Corgi", "Pomeranian"] as const
const costumes = ["Pumpkin", "Hot Dog", "Bumble Bee"] as const
type Lowercase<T extends string> = `${lowercase T}`
function createBreedCostumeId(breed: typeof breeds[number], costume: typeof costumes[number]) {
return `${breed}-${costume}`.toLowerCase() as Lowercase<`${typeof breed}-${typeof costume}`>
}
function tallyPopularWinners(_breeds: typeof breeds, _costumes: typeof costumes) {
const winners: Record<
ReturnType<typeof createBreedCostumeId>,
ReturnType<typeof decideWinner>
> = {} as any
for (const breed of _breeds) {
for (const costume of _costumes) {
const id = createBreedCostumeId(breed, costume)
winners[id] = decideWinner(breed, costume)
}
}
return winners
}
// You can run this example in order to see what the shape of the data looks like, but
// the result will have keys which are lowercased for every mix of breed and costume, e.g:
// {
// "hound-pumpkin": {...},
// "hound-hot dog": {...},
// "hound-bumble bee": {...},
// "corgi-pumpkin": {...}
// ...
// }
const winners = tallyPopularWinners(breeds, costumes)
console.log(winners)
// Passes
winners["hound-pumpkin"].name
// Should fail
winners["pumpkin-pumpkin"].video
// Spoilerific tips below:
// 1: This builds off ideas from day 3, which builds of previous days too
// 2: The implementation will require an `as` or two alas, but with some
// work you can partially find an answer
// Mainly just adding a quick implementation, so that you can run the
// code above without a problem:
function someoneElseDecides(_breed: string, _costume: string): { name: string, video: string } {
// Yes, all these dogs have a name which is just a hexcode... hah
const genRanHex = (size: number) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
return {
name: genRanHex(6),
video: genRanHex(6)
}
}
|
216cdf9eea7ad231a16a7e4ecc92043c81bf5a9f
|
TypeScript
|
CofeeWithRose/WaveRolling
|
/release/plugins/decoder/interfaces/IWavDecoder.d.ts
| 2.578125
| 3
|
import { IEventHandle } from "../../../main/interfaces/IEventHandle";
export interface RangeSegment {
cacheIndex: number;
offset: number;
length: number;
cacheOffset: number;
}
export declare class DataBufferRange {
length: number;
segments: RangeSegment[];
}
export interface DecodedInfo {
audioBuffer: AudioBuffer;
startTime: number;
endTime: number;
duration: number;
}
/**
*
* the events in decoder.
*
* 解码器事件.
*/
export interface WaveDecoderEvents {
error: Error;
abort: void;
process: DecodedInfo;
waitting: void;
complete: void;
}
/**
* triggerable events.
*
* 可以触发的解码器事件.
*/
export declare class WaveDecoderEventsTrigger {
error: Error;
abort: void;
process: DecodedInfo;
waitting: void;
complete: void;
}
/**
* An audio progresive decoder, only surport wav format in pacm encoding.
*/
export interface IWavDecoder extends IEventHandle<WaveDecoderEventsTrigger, WaveDecoderEvents> {
/**
* start decode when this method execute, if this method excute more than once, nothing will happend.
*
* @param {ArrayBuffer} firstPiceArrayBuffer the first splice ArrayBuffer of wave audio data from xhr\fetch\file,
* also receive the whole ArrayBuffer.
*/
decode(firstPiceArrayBuffer: ArrayBuffer): void;
/**
* add the rest data to decode.
*
* @param {ArrayBuffer} buffer the next pices ArrayBuffer of wave audio, you can append several times before complete,
* when you append extra data, it will be iignore.
*/
appendBuffer(buffer: ArrayBuffer): void;
abort(): void;
onprocess(info: DecodedInfo): void;
onwaitting(): void;
oncomplete(): void;
onabort(): void;
onerror(error: Error): void;
}
|
e7af9be26c658364795c5c3681ef9237182ac6e5
|
TypeScript
|
HaskellJacobCurry/haskell-ts
|
/dist/Typeclass/Data/Monoid/Dual_.d.ts
| 2.84375
| 3
|
import { ISemigroup } from '../Semigroup';
import { IMonoid } from '../Monoid';
declare const URI: "Dual";
declare type URI = typeof URI;
export { URI };
interface Dual<A> {
URI: URI;
value: A;
}
export { Dual };
declare let get: <A>(_: Dual<A>) => A;
export { get };
declare let createDual: <A>(value: A) => Dual<A>;
export { createDual as create };
declare let append: <A>(_: ISemigroup<A>) => (dual0: Dual<A>) => (dual1: Dual<A>) => Dual<A>;
export { append };
declare let mempty: <A>(_: IMonoid<A>) => () => Dual<A>;
export { mempty };
/** Semigroup a => Semigroup (Dual a) */
declare let Semigroup: <A>(_: ISemigroup<A>) => ISemigroup<Dual<A>>;
export { Semigroup };
declare let Monoid: <A>(_: IMonoid<A>) => ISemigroup<Dual<A>> & IMonoid.Base<Dual<A>> & IMonoid.Ext<Dual<A>>;
export { Monoid };
declare type Constructor = typeof createDual;
export { Constructor };
interface HDual {
URI: URI;
get: <A>(_: Dual<A>) => A;
create: <A>(value: A) => Dual<A>;
Semigroup: typeof Semigroup;
Monoid: typeof Monoid;
append: <A>(_: ISemigroup<A>) => (dual0: Dual<A>) => (dual1: Dual<A>) => Dual<A>;
mempty: <A>(_: IMonoid<A>) => () => Dual<A>;
}
export { HDual };
declare let Dual: Constructor & HDual;
export default Dual;
|
b7aa3c6c2dcc910b7e58c1067cd9a2339c7fab58
|
TypeScript
|
KubiGR/ticket-to-ride
|
/src/model/cards.ts
| 3.140625
| 3
|
import { Connection } from './connection';
import { cardColors } from './trackColor';
export type TC = Map<string, number>[];
export function makeTC(len: number, color1: string, color2 = ''): TC {
if (!cardColors.includes(color1))
throw new Error('makeTC Unknown color1: ' + color1);
if (color2 !== '' && !cardColors.includes(color2))
throw new Error('makeTC Unknown color2: ' + color2);
if (color2 === '') return [new Map([[color1, len]])];
else return [new Map([[color1, len]]), new Map([[color2, len]])];
}
export function add(c1: TC, c2: TC): TC {
const res: TC = [];
if (c1.length === 0) return c2;
c1.forEach((t1) => {
c2.forEach((t2) => {
const t: Map<string, number> = new Map();
cardColors.forEach((c) => {
const total = addMap(t1, t2, c);
if (total != 0) t.set(c, addMap(t1, t2, c));
});
res.push(t);
});
});
return res;
}
function addMap(
t1: Map<string, number>,
t2: Map<string, number>,
c: string,
): number {
let total = 0;
const t1c = t1.get(c);
if (t1c !== undefined) total += t1c;
const t2c = t2.get(c);
if (t2c !== undefined) total += t2c;
return total;
}
export function printTC(tc: TC): string {
let s = '';
cardColors.forEach((c) => {
let min = Infinity;
let max = 0;
tc.forEach((t) => {
const tgc = t.get(c);
if (tgc === undefined) {
min = 0;
} else {
if (tgc < min) {
min = tgc;
}
if (tgc > max) {
max = tgc;
}
}
});
if (min != Infinity)
if (min === max) {
if (min != 0) s += '(' + min + ') ' + c + ' ';
} else s += min + '-' + max + ' ' + c + ' ';
});
return s;
}
export function cardsForConnections(connections: Connection[]): TC {
return connections
.map((c) => {
try {
if (c.color2 !== undefined) return makeTC(c.trains, c.color1, c.color2);
else return makeTC(c.trains, c.color1);
} catch (e) {
console.error(
'ERROR Unknown color, cardsForConnections ' +
c.from +
' to ' +
c.to +
' ' +
c.color1 +
' ' +
c.color2,
);
return [];
}
})
.reduce((pre, cur) => add(pre, cur), []);
}
|
0fbcf847cd72a0862f0e63517d0b5dd8e94b7bc4
|
TypeScript
|
GhostLmm/coder
|
/currentProject/UpdateFlag.ts
| 2.9375
| 3
|
import {DebugConfig} from "../euler/DebugConfig";
/**
* Created by kris on 2017/3/2.
*/
export class UpdateFlag
{
/** 位置和形状标签 **/
public static TAG_POSITION:string = "position";
public static TAG_POLYGON:string = "polygon";
/** 场景中的obj边界 **/
public static TAG_BOUNDARY:string = "boundary";
/** 物体所属房间信息标签 **/
public static TAG_ROOM:string = "room";
constructor()
{
}
private tagPool:Object = {};
// 记录父子关系 {父:[子]}
private relationPool:Object={};
/**
* 添加tag,以及其父tag
* 禁止出现循环标签
*
*/
public addTag(tag:string,parentTag:string=null,...parentTags):void
{
if(this.tagPool.hasOwnProperty(tag))
{
if (DebugConfig.traceLog) {
console.log("添加重复,错误: "+tag );
}
return ;
}
this.tagPool[tag] = true;
let ps:any[]=[];
if(parentTag!=null)
ps.push(parentTag);
ps = ps.concat(parentTags);
for ( let parent of ps)
{
if (!this.relationPool.hasOwnProperty(parent))
{
this.relationPool[parent] = [];
}
let relation:any[] = this.relationPool[parent];
if (relation.indexOf(tag) == -1)
{
relation.push(tag);
}
}
}
public hasTag(tag:string):boolean
{
return this.tagPool.hasOwnProperty(tag);
}
/**
* 获取tag 是否需要更新
*/
public getValue(tag:string):boolean
{
return this.tagPool[tag];
}
/**
* 设置标签, 如果value为true的话,就会设置其子类也都为true
*/
public setValue(tag:string, value:boolean):void
{
if (!this.hasTag(tag))
{
if (DebugConfig.traceLog) {
console.log("没有这个tag : " + tag);
}
return ;
}
this.tagPool[tag] = value;
// 设置child 也为需要更新
if (value && this.relationPool.hasOwnProperty(tag) )
{
for (let childTag of this.relationPool[tag])
{
this.setValue(childTag,value);
}
}
}
}
|
336af46ae5d969e32ca79e4b102cd90ddac84b01
|
TypeScript
|
Nicasiomarques/mochi-test
|
/modules/utils/helper-functions/__tests__/format-geo-code-result.test.ts
| 2.78125
| 3
|
import { formatGeoCodeResult } from '../index';
const makeSut = () => ({ sut: formatGeoCodeResult });
describe(formatGeoCodeResult.name, () => {
it('to returns to formatGeoCodeResult in object with properties street, lat and lng ', () => {
const { sut } = makeSut();
const geoCode: any = {
formatted_address: 'street',
geometry: { location: { lat: () => 1, lng: () => 2 } },
};
const geoCodeResult = sut(geoCode);
expect(geoCodeResult).toHaveProperty('street');
expect(geoCodeResult).toHaveProperty('lat');
expect(geoCodeResult).toHaveProperty('lng');
expect(geoCodeResult.lng).toBe(2);
expect(geoCodeResult.lat).toBe(1);
expect(geoCodeResult.street).toBe('street');
});
});
|
bcea8b616ed9467b44460e1484605104b7525d19
|
TypeScript
|
ReExia/font-demos
|
/ng-use-form/src/app/moel/form-textbox.ts
| 2.546875
| 3
|
import { FormFieldBase } from './form-field-base';
export class FormTextBox extends FormFieldBase<string>{
controlType = "textbox";
type : string;
constructor(options : {} = {}){
super(options);
this.type = options['type'] || '';
}
}
|
41309e523e1677b9d5052ece43b0f7daffda2945
|
TypeScript
|
kushwahashiv/Typescript2xCookbook
|
/chapter_05/src/14_generators.ts
| 3.296875
| 3
|
namespace chapter_04.generators {
// count to 10
function* count() {
let count = 0;
while (count < 10) {
yield count;
count = count + 1;
}
}
console.log('iterator:');
const iterator = count();
let item = null;
do {
item = iterator.next();
console.log(item);
}
while (item.done === false);
// infinite loop with genertors
function* infiniteCount() {
let count = 0;
while (true) {
yield count;
count = count + 1;
}
}
console.log('infiniteIterator:');
const infiniteIterator = infiniteCount();
console.log(infiniteIterator.next());
console.log(infiniteIterator.next());
console.log(infiniteIterator.next());
console.log(infiniteIterator.next());
}
|
644e201eb7cbd5bf3184919b5248f24b937beab9
|
TypeScript
|
henck/tads3js
|
/src/builtin/gen/concat.ts
| 2.734375
| 3
|
import { VmData, VmObject, VmNil } from "../../types";
import { MetaString } from "../../metaimp";
/**
* Returns a string with the concatenation of the argument values, in the order given.
* @param args Values to concatenate
* @returns Concatenated string
*/
export function builtin_concat(...args: VmData[]): VmData {
return new VmObject(new MetaString(args.map((x) => x instanceof(VmNil) ? '' : x.toStr()).join('')));
}
|
93f06c602c7f9f3206e09b247a10e1854fe8ea85
|
TypeScript
|
kuldarim/quiz-homework
|
/react-ui/src/redux/reducers/reducer.ts
| 2.65625
| 3
|
import { GET_ALL_KATAS, CHANGE_STATUS, CHANGE_SOLUTION, CHANGE_USER, SET_ALERTS } from '../constants/action-types';
import { IKata } from '../constants/interfaces';
const initial = {
katas: [],
user: '',
alerts: {},
};
const reducer = (state = initial, action: any) => {
switch (action.type) {
case GET_ALL_KATAS:
return {...state, katas: action.katas };
case CHANGE_STATUS:
(state.katas[action.kataId] as IKata).tests[action.testId].status = action.status;
return { ...state, katas: [...state.katas] };
case CHANGE_SOLUTION:
(state.katas[action.kataId] as IKata).solution = action.solution;
return { ...state, katas: [...state.katas] };
case CHANGE_USER:
return { ...state, user: `${action.user}`};
case SET_ALERTS:
return { ...state, alerts: {...action.alerts}};
default:
return state;
}
};
export default reducer;
|
23b5c5a00ebaf9c618db1b75685eae52c6f3ac98
|
TypeScript
|
gravity2146/teen
|
/src/models/UserProfile.ts
| 3.234375
| 3
|
/**
* Defines a user profile.
*/
export class UserProfile {
userId: string;
username: string;
firstName: string;
lastName: string;
fullName: string;
photoUrl: string;
pk: string;
/**
* Sets the name of the user.
* @param fullName The full name of the user.
*/
public setName(fullName: string) {
const parts = fullName.split(/\s+/);
this.firstName = parts.length > 0 ? parts[0] : "";
this.lastName = parts.length > 1 ? parts[1] : "";
this.fullName = fullName;
}
}
|
30bc0af7f1e633ac64e61fc903afdd5de1a422d2
|
TypeScript
|
96RadhikaJadhav/earl
|
/packages/earljs/src/types.ts
| 2.703125
| 3
|
export interface Newable<T> {
new (...args: any[]): T
}
// @note: don't use BigIntConstructor here to avoid relying on modern node typings being installed
export type BigIntLike = { asIntN: Function; asUintN: Function; (value?: any): any }
export type NewableOrPrimitive<T = any> = Newable<T> | SymbolConstructor | BigIntLike
|
a15ec2ce0144d6ca8221f6fbf377eac32f290d57
|
TypeScript
|
AkshayKulkarni03/customer-app
|
/src/app/shared/services/token/token-storage.service.spec.ts
| 2.546875
| 3
|
import { TestBed } from '@angular/core/testing';
import { TokenStorageService } from './token-storage.service';
describe('TokenStorageService', () => {
let service: TokenStorageService;
const mockSessionStorage = (() => {
let store = {};
return {
getItem: (key) => {
return store[key];
},
setItem: (key, value) => {
store[key] = value + '';
},
removeItem: (key) => {
delete store[key];
},
clear: () => {
store = {};
}
};
})();
beforeAll(() => {
Object.defineProperty(window, 'sessionStorage', { value: mockSessionStorage, writable: true });
});
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(TokenStorageService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should save token for logged in user in session storage', () => {
service.saveToken('test user token');
expect(window.sessionStorage.getItem('auth-token')).toEqual('test user token');
});
it('should get token for logged in user from session storage', () => {
const token = service.getToken();
expect(window.sessionStorage.getItem('auth-token')).toEqual(token);
});
it('should save user in session storage', () => {
const userData = {
accessToken: 'test access token',
userName: 'test 1',
roles: ['ROLE_USER']
};
service.saveUser(userData);
expect(window.sessionStorage.getItem('auth-user')).toEqual(JSON.stringify(userData));
});
it('should get user from session storage', () => {
const userData = {
accessToken: 'test access token',
userName: 'test 1',
roles: ['ROLE_USER']
};
service.saveUser(userData);
const user = service.getUser();
expect(user).toEqual(JSON.parse(window.sessionStorage.getItem('auth-user')));
});
it('should sign out and clear all session storage', () => {
service.signOut();
expect(window.sessionStorage.getItem('auth-user')).toBeUndefined();
});
});
|
b1793889f88699bac17d997b628fb0983a55d89a
|
TypeScript
|
Kellyzhy/MovieShopSPA
|
/src/app/core/services/api.service.ts
| 2.71875
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private headers: HttpHeaders;
constructor(protected http:HttpClient)
{
this.headers = new HttpHeaders();
this.headers.append('Content-Type', 'application/json'); //tell API that send information in JSON format
}
getAll(path: string): Observable<any[]> { //return type is array: any[], input is a string which is part URL:path
return this.http.get(`${environment.apiUrl}${path}`).pipe(
map(resp => resp as any[]),
catchError(this.handleError)
);
}
getOne(path: string): Observable<any> { //return type is array: any[], input is a string which is part URL:path
return this.http.get(`${environment.apiUrl}${path}`).pipe(
map(resp => resp as any),
catchError(this.handleError)
);
}
create(path: string, resource, options?): Observable<any> {
return this.http
.post(`${environment.apiUrl}${path}`, resource, { headers: this.headers })
.pipe(
map(response => response),
catchError(this.handleError)
);
}
// Any non-successfull http status codes such as 400,400,403,404,500,503 etc will be wrapped in HttpErrorResponse
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(error.error.errorMessage);
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.message}`
);
}
// return an observable with a user-facing error message
return throwError(error.error.errorMessage);
}
}
|
c38c487400b463a9bbb00e61a749bad1a1a70345
|
TypeScript
|
lxfly666/TypeScript2021
|
/MySnake/src/modules/Snake.ts
| 3
| 3
|
class Snake{
head:HTMLElement;
bodies:HTMLCollection;
element:HTMLElement;
constructor(){
this.element=document.getElementById('snake')!;
this.head=document.querySelector('#snake>div') as HTMLElement;
this.bodies=this.element.getElementsByTagName('div');
}
get X(){
return this.head.offsetLeft;
}
get Y(){
return this.head.offsetTop;
}
set X(value:number){
if(this.X===value){
return;
}
if(this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetLeft==value ){
if(value>this.X){
value=this.X-10;
}else{
value=this.X+10
}
}
if(value<0 || value>290){
throw new Error("蛇撞墙了!");
}
this.moveBody();
this.head.style.left=value+'px';
}
set Y(value:number){
if(this.Y === value){
return;
}
if(this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetTop==value){
if(value>this.Y){
value=this.Y-10;
}else{
value=this.Y+10;
}
}
if(value<0||value>290){
throw new Error("蛇撞墙了!");
}
this.moveBody();
this.head.style.top=value+'px';
this.checkHeadBody();
}
addBody(){
this.element.insertAdjacentHTML("beforeend","<div></div>");
}
moveBody() {
for (let i = this.bodies.length - 1; i > 0; i--) {
let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
(this.bodies[i] as HTMLElement).style.left = X + 'px';
(this.bodies[i] as HTMLElement).style.top = Y + 'px';
}
}
checkHeadBody(){
for (let i = 1; i < this.bodies.length ; i++) {
let bd = this.bodies[i] as HTMLElement
if(this.X==bd.offsetLeft && this.Y==bd.offsetTop){
throw Error("撞到自己啦!");
}
}
}
}
export default Snake;
|
94eb2b3a0135aaf39e34f01bad530830a2fc7b42
|
TypeScript
|
ricardoham/moviesit-app
|
/src/components/Label/styles.ts
| 2.515625
| 3
|
import styled from '@emotion/styled';
interface StyledProps {
hasError?: boolean;
}
export const StyledLabel = styled.label<StyledProps>`
color: ${(props) => (props.hasError ? '#ff3243' : '#181818')};
`;
|
5652fb98277c979beb196d9a61e64110d600485e
|
TypeScript
|
chang90/seek-ads
|
/src/lib/util/getNormalPrice.ts
| 2.640625
| 3
|
import { ShoppingCartMap } from "../interface/shoppingCartMap";
import { RetailPriceRuleMap } from "../interface/retailPriceRuleMap";
export const getNormalPrice = (shoppingCartMap: ShoppingCartMap, retailPriceMap: RetailPriceRuleMap): number => {
let resultPrice = 0;
for (const productItem in shoppingCartMap) {
resultPrice = resultPrice + shoppingCartMap[productItem] * retailPriceMap[productItem];
}
return resultPrice;
}
|
17d510c6846ef28f2fc36658cc306ce85ee4340c
|
TypeScript
|
gitter-badger/x-forward
|
/packages/app/src/utils/Shell.ts
| 2.53125
| 3
|
import { $, cd, nothrow } from 'zx'
/**
* install nginx
* @param version nginx version need to install
* @param handlerMsg handler system std
*/
export const installNginx = async (version: string, handlerMsg?: (msg: string) => void) => {
handlerMsg && handlerMsg(`$ wget http://nginx.org/download/nginx-${version}.tar.gz\n`)
const downloadRes = $`wget http://nginx.org/download/nginx-${version}.tar.gz`
// let res = $`sleep 1; echo 1; sleep 2; echo 2`
handlerMsg &&
downloadRes.stderr.on('data', msg => {
handlerMsg(msg + '\n')
})
await downloadRes
handlerMsg && handlerMsg(`$ tar zxvf nginx-${version}.tar.gz`)
const unzipRes = $`tar zxvf nginx-${version}.tar.gz`
handlerMsg &&
unzipRes.stdout.on('data', msg => {
handlerMsg(msg + '\n')
})
await unzipRes
handlerMsg && handlerMsg(`$ cd nginx-${version}`)
cd(`nginx-${version}`)
}
const findSomething = async (something: string) => {
const res = await nothrow($`which ${something}`)
return res.exitCode === 0 ? res.stdout : ''
}
const checkCompoileUtil = () => {}
/**
* get infomation of os
* @returns linux release infomation
*/
export const checkOS = async () => {
const lsb = await nothrow($`lsb_release -d`)
if (lsb.stdout) {
return lsb.stdout.replace(/Description:|\t|\n/g, '')
}
const catRedhat = await $`cat /etc/redhat-release`
if (catRedhat.stdout) {
return catRedhat.stdout
}
const catIssue = await $`cat /etc/issue`
if (catIssue) {
return catIssue.stdout.replace(/\n|\l/, '')
}
return ''
}
/**
* return fileName by input url
*/
export const fetchDirectory = async (url: string): Promise<string> => {
const res = await nothrow($`ls -F ${url} | grep "/$"`)
return res.exitCode === 0 ? res.stdout : ''
}
|
a7ed35abeb0d04245bc34ade99d5961daeabe6a5
|
TypeScript
|
Valeriia-Rez/ITA28.09
|
/Valeriia/Movies_database_project/src/store/reducers/MovieReducer.ts
| 2.953125
| 3
|
import { IMovie } from "../../types";
import { MovieAction} from "../actions/movieActions";
import {MovieActionTypes} from '../actions/actionTypes';
export interface IMovieDetailsState {
movie: IMovie | null;
isError: boolean
}
const initialState: IMovieDetailsState = {
movie: null,
isError: false
}
const movieReducer = (state: IMovieDetailsState = initialState, action: MovieAction) => {
switch(action.type){
case MovieActionTypes.ON_REQUEST_MOVIE:{
return {
...state,
}
}
case MovieActionTypes.ON_REQUEST_MOVIE_SUCCESS:{
return {
...state,
movie: action.movie,
}
}
case MovieActionTypes.ON_REQUEST_MOVIE_ERROR:{
return {
...state,
isError: action.error
}
}
default: return state;
}
}
export default movieReducer;
|
a3523b4d7ccb98e0e1204a4dc299a0af237a074b
|
TypeScript
|
nevincoco/vscode-extension
|
/src/snyk/configuration.ts
| 2.546875
| 3
|
import { URL } from 'url';
import * as vscode from 'vscode';
import { IDE_NAME } from './constants/general';
import {
ADVANCED_ADVANCED_CODE_ENABLED_SETTING,
ADVANCED_ADVANCED_MODE_SETTING,
CONFIGURATION_IDENTIFIER,
TOKEN_SETTING,
YES_CRASH_REPORT_SETTING,
YES_TELEMETRY_SETTING,
YES_WELCOME_NOTIFICATION_SETTING,
} from './constants/settings';
export interface IConfiguration {
isDevelopment: boolean;
source: string;
baseURL: string;
authHost: string;
snykCodeUrl: string;
token: string | undefined;
setToken(token: string): Promise<void>;
codeEnabled: boolean | undefined;
shouldReportErrors: boolean;
shouldReportEvents: boolean;
setCodeEnabled(value: boolean): Promise<void>;
}
export class Configuration implements IConfiguration {
// These attributes are used in tests
private staticToken = '';
private defaultBaseURL = 'https://deeproxy.snyk.io';
private defaultAuthHost = 'https://snyk.io';
private staticCodeEnabled = false;
constructor(
private processEnv: NodeJS.ProcessEnv = process.env,
private vscodeWorkspace: typeof vscode.workspace = vscode.workspace,
) {}
get isDevelopment(): boolean {
return !!process.env.SNYK_VSCE_DEVELOPMENT;
}
get baseURL(): string {
return this.isDevelopment ? 'https://deeproxy.dev.snyk.io' : this.defaultBaseURL;
}
get authHost(): string {
return this.isDevelopment ? 'https://dev.snyk.io' : this.defaultAuthHost;
}
get snykCodeUrl(): string {
const authUrl = new URL(this.authHost);
authUrl.host = `app.${authUrl.host}`;
return `${authUrl.toString()}manage/snyk-code?from=vscode`;
}
get token(): string | undefined {
return (
this.staticToken ||
this.vscodeWorkspace.getConfiguration(CONFIGURATION_IDENTIFIER).get(this.getConfigName(TOKEN_SETTING))
);
}
async setToken(token: string): Promise<void> {
this.staticToken = '';
await this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.update(this.getConfigName(TOKEN_SETTING), token, true);
}
get source(): string {
return this.processEnv.GITPOD_WORKSPACE_ID ? 'gitpod' : IDE_NAME;
}
get codeEnabled(): boolean | undefined {
return (
this.staticCodeEnabled ||
this.source !== IDE_NAME ||
this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.get<boolean | undefined>(this.getConfigName(ADVANCED_ADVANCED_CODE_ENABLED_SETTING))
);
}
async setCodeEnabled(value = true): Promise<void> {
await this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.update(this.getConfigName(ADVANCED_ADVANCED_CODE_ENABLED_SETTING), value, true);
}
get shouldReportErrors(): boolean {
return !!this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.get<boolean>(this.getConfigName(YES_CRASH_REPORT_SETTING));
}
get shouldReportEvents(): boolean {
return !!this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.get<boolean>(this.getConfigName(YES_TELEMETRY_SETTING));
}
get shouldShowWelcomeNotification(): boolean {
return !!this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.get<boolean>(this.getConfigName(YES_WELCOME_NOTIFICATION_SETTING));
}
async hideWelcomeNotification(): Promise<void> {
await this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.update(this.getConfigName(YES_WELCOME_NOTIFICATION_SETTING), false, true);
}
get shouldShowAdvancedView(): boolean {
return !!this.vscodeWorkspace
.getConfiguration(CONFIGURATION_IDENTIFIER)
.get<boolean>(this.getConfigName(ADVANCED_ADVANCED_MODE_SETTING));
}
private getConfigName = (setting: string) => setting.replace(`${CONFIGURATION_IDENTIFIER}.`, '');
}
export const configuration = new Configuration();
|
2c2541da01ce09d20e01265b67e3c9e6e796ed4b
|
TypeScript
|
sebasakd86/ts-bc
|
/02-DataTypes/core.ts
| 3.84375
| 4
|
//TS wont check nor provide support for this kind of declaration
const tsDoesntCare: object = {
name: "pablo",
age: 700,
};
//Creates a concrete obj that TS provides support to and checks for errors.
//Its not a good practice, it's better to use TS type inference
const specializedPerson: {
name: string;
age: number;
} = {
name: "sebas",
age: -10,
};
enum Role {
ADMIN = 5, // = 'ADMIN'
READ_ONLY, //6
AUTHOR, //7
}
const person = {
name: "sebas",
age: -10,
hobbies: ["Birra", "Morfar"], //array
// role: [2, "Admin"], //tuple
role: Role.ADMIN,
};
console.log(person.name);
|
c140c6267faa77c65d8c13be19a793fc0efa032a
|
TypeScript
|
bolucat/Archive
|
/unlock-music/src/decrypt/ximalaya.ts
| 2.546875
| 3
|
import { parseBlob as metaParseBlob } from 'music-metadata-browser';
import { AudioMimeType, SniffAudioExt, GetArrayBuffer, GetMetaFromFile } from './utils';
import { DecryptResult } from '@/decrypt/entity';
const HandlerMap: Map<string, (data: Uint8Array) => Uint8Array> = new Map([
['x2m', ProcessX2M],
['x3m', ProcessX3M],
]);
export async function Decrypt(file: File, raw_filename: string, raw_ext: string): Promise<DecryptResult> {
const buffer = new Uint8Array(await GetArrayBuffer(file));
const handler = HandlerMap.get(raw_ext);
if (!handler) throw 'File type is incorrect!';
let musicDecoded: Uint8Array = handler(buffer);
const ext = SniffAudioExt(musicDecoded, 'm4a');
const mime = AudioMimeType[ext];
let musicBlob = new Blob([musicDecoded], { type: mime });
const musicMeta = await metaParseBlob(musicBlob);
const info = GetMetaFromFile(raw_filename, musicMeta.common.title, musicMeta.common.artist);
return {
picture: '',
title: info.title,
artist: info.artist,
ext: ext,
album: musicMeta.common.album,
blob: musicBlob,
file: URL.createObjectURL(musicBlob),
mime: mime,
};
}
function ProcessX2M(data: Uint8Array) {
const x2mHeaderSize = 1024;
const x2mKey = [0x78, 0x6d, 0x6c, 0x79];
let encryptedHeader = data.slice(0, x2mHeaderSize);
for (let idx = 0; idx < x2mHeaderSize; idx++) {
let srcIdx = x2mScrambleTable[idx];
data[idx] = encryptedHeader[srcIdx] ^ x2mKey[idx % x2mKey.length];
}
return data;
}
function ProcessX3M(data: Uint8Array) {
const x3mHeaderSize = 1024;
//prettier-ignore: uint8, size 32(8x4)
const x3mKey = [
0x33, 0x39, 0x38, 0x39, 0x64, 0x31, 0x31, 0x31, 0x61, 0x61, 0x64, 0x35, 0x36, 0x31, 0x33, 0x39, 0x34, 0x30, 0x66,
0x34, 0x66, 0x63, 0x34, 0x34, 0x62, 0x36, 0x33, 0x39, 0x62, 0x32, 0x39, 0x32,
];
let encryptedHeader = data.slice(0, x3mHeaderSize);
for (let dstIdx = 0; dstIdx < x3mHeaderSize; dstIdx++) {
let srcIdx = x3mScrambleTable[dstIdx];
data[dstIdx] = encryptedHeader[srcIdx] ^ x3mKey[dstIdx % x3mKey.length];
}
return data;
}
//prettier-ignore: uint16, size 1024 (64x16)
const x2mScrambleTable = [
0x2a9, 0x2ab, 0x154, 0x2aa, 0x2a8, 0x2ac, 0x153, 0x2a7, 0x2ad, 0x152, 0x2a6, 0x3ff, 0x000, 0x155, 0x2ae, 0x151, 0x2a5,
0x3fe, 0x001, 0x156, 0x2af, 0x150, 0x2a4, 0x3fd, 0x002, 0x157, 0x2b0, 0x14f, 0x2a3, 0x3fc, 0x003, 0x158, 0x2b1, 0x14e,
0x2a2, 0x3fb, 0x004, 0x159, 0x2b2, 0x14d, 0x2a1, 0x3fa, 0x005, 0x15a, 0x2b3, 0x14c, 0x2a0, 0x3f9, 0x006, 0x15b, 0x2b4,
0x14b, 0x29f, 0x3f8, 0x007, 0x15c, 0x2b5, 0x14a, 0x29e, 0x3f7, 0x008, 0x15d, 0x2b6, 0x149, 0x29d, 0x3f6, 0x009, 0x15e,
0x2b7, 0x148, 0x29c, 0x3f5, 0x00a, 0x15f, 0x2b8, 0x147, 0x29b, 0x3f4, 0x00b, 0x160, 0x2b9, 0x146, 0x29a, 0x3f3, 0x00c,
0x161, 0x2ba, 0x145, 0x299, 0x3f2, 0x00d, 0x162, 0x2bb, 0x144, 0x298, 0x3f1, 0x00e, 0x163, 0x2bc, 0x143, 0x297, 0x3f0,
0x00f, 0x164, 0x2bd, 0x142, 0x296, 0x3ef, 0x010, 0x165, 0x2be, 0x141, 0x295, 0x3ee, 0x011, 0x166, 0x2bf, 0x140, 0x294,
0x3ed, 0x012, 0x167, 0x2c0, 0x13f, 0x293, 0x3ec, 0x013, 0x168, 0x2c1, 0x13e, 0x292, 0x3eb, 0x014, 0x169, 0x2c2, 0x13d,
0x291, 0x3ea, 0x015, 0x16a, 0x2c3, 0x13c, 0x290, 0x3e9, 0x016, 0x16b, 0x2c4, 0x13b, 0x28f, 0x3e8, 0x017, 0x16c, 0x2c5,
0x13a, 0x28e, 0x3e7, 0x018, 0x16d, 0x2c6, 0x139, 0x28d, 0x3e6, 0x019, 0x16e, 0x2c7, 0x138, 0x28c, 0x3e5, 0x01a, 0x16f,
0x2c8, 0x137, 0x28b, 0x3e4, 0x01b, 0x170, 0x2c9, 0x136, 0x28a, 0x3e3, 0x01c, 0x171, 0x2ca, 0x135, 0x289, 0x3e2, 0x01d,
0x172, 0x2cb, 0x134, 0x288, 0x3e1, 0x01e, 0x173, 0x2cc, 0x133, 0x287, 0x3e0, 0x01f, 0x174, 0x2cd, 0x0a9, 0x1fe, 0x357,
0x020, 0x175, 0x2ce, 0x0aa, 0x1ff, 0x358, 0x021, 0x176, 0x2cf, 0x0ab, 0x200, 0x359, 0x022, 0x177, 0x2d0, 0x0ac, 0x201,
0x35a, 0x023, 0x178, 0x2d1, 0x0ad, 0x202, 0x35b, 0x024, 0x179, 0x2d2, 0x0ae, 0x203, 0x35c, 0x025, 0x17a, 0x2d3, 0x0af,
0x204, 0x35d, 0x026, 0x17b, 0x2d4, 0x0b0, 0x205, 0x35e, 0x027, 0x17c, 0x2d5, 0x0b1, 0x206, 0x35f, 0x028, 0x17d, 0x2d6,
0x0b2, 0x207, 0x360, 0x029, 0x17e, 0x2d7, 0x0b3, 0x208, 0x361, 0x02a, 0x17f, 0x2d8, 0x0b4, 0x209, 0x362, 0x02b, 0x180,
0x2d9, 0x0b5, 0x20a, 0x363, 0x02c, 0x181, 0x2da, 0x0b6, 0x20b, 0x364, 0x02d, 0x182, 0x2db, 0x0b7, 0x20c, 0x365, 0x02e,
0x183, 0x2dc, 0x0b8, 0x20d, 0x366, 0x02f, 0x184, 0x2dd, 0x0b9, 0x20e, 0x367, 0x030, 0x185, 0x2de, 0x0ba, 0x20f, 0x368,
0x031, 0x186, 0x2df, 0x0bb, 0x210, 0x369, 0x032, 0x187, 0x2e0, 0x0bc, 0x211, 0x36a, 0x033, 0x188, 0x2e1, 0x0bd, 0x212,
0x36b, 0x034, 0x189, 0x2e2, 0x0be, 0x213, 0x36c, 0x035, 0x18a, 0x2e3, 0x0bf, 0x214, 0x36d, 0x036, 0x18b, 0x2e4, 0x0c0,
0x215, 0x36e, 0x037, 0x18c, 0x2e5, 0x0c1, 0x216, 0x36f, 0x038, 0x18d, 0x2e6, 0x0c2, 0x217, 0x370, 0x039, 0x18e, 0x2e7,
0x0c3, 0x218, 0x371, 0x03a, 0x18f, 0x2e8, 0x0c4, 0x219, 0x372, 0x03b, 0x190, 0x2e9, 0x0c5, 0x21a, 0x373, 0x03c, 0x191,
0x2ea, 0x0c6, 0x21b, 0x374, 0x03d, 0x192, 0x2eb, 0x0c7, 0x21c, 0x375, 0x03e, 0x193, 0x2ec, 0x0c8, 0x21d, 0x376, 0x03f,
0x194, 0x2ed, 0x0c9, 0x21e, 0x377, 0x040, 0x195, 0x2ee, 0x0ca, 0x21f, 0x378, 0x041, 0x196, 0x2ef, 0x0cb, 0x220, 0x379,
0x042, 0x197, 0x2f0, 0x0cc, 0x221, 0x37a, 0x043, 0x198, 0x2f1, 0x0cd, 0x222, 0x37b, 0x044, 0x199, 0x2f2, 0x0ce, 0x223,
0x37c, 0x045, 0x19a, 0x2f3, 0x0cf, 0x224, 0x37d, 0x046, 0x19b, 0x2f4, 0x0d0, 0x225, 0x37e, 0x047, 0x19c, 0x2f5, 0x0d1,
0x226, 0x37f, 0x048, 0x19d, 0x2f6, 0x0d2, 0x227, 0x380, 0x049, 0x19e, 0x2f7, 0x0d3, 0x228, 0x381, 0x04a, 0x19f, 0x2f8,
0x0d4, 0x229, 0x382, 0x04b, 0x1a0, 0x2f9, 0x0d5, 0x22a, 0x383, 0x04c, 0x1a1, 0x2fa, 0x0d6, 0x22b, 0x384, 0x04d, 0x1a2,
0x2fb, 0x0d7, 0x22c, 0x385, 0x04e, 0x1a3, 0x2fc, 0x0d8, 0x22d, 0x386, 0x04f, 0x1a4, 0x2fd, 0x0d9, 0x22e, 0x387, 0x050,
0x1a5, 0x2fe, 0x0da, 0x22f, 0x388, 0x051, 0x1a6, 0x2ff, 0x0db, 0x230, 0x389, 0x052, 0x1a7, 0x300, 0x0dc, 0x231, 0x38a,
0x053, 0x1a8, 0x301, 0x0dd, 0x232, 0x38b, 0x054, 0x1a9, 0x302, 0x0de, 0x233, 0x38c, 0x055, 0x1aa, 0x303, 0x0df, 0x234,
0x38d, 0x056, 0x1ab, 0x304, 0x0e0, 0x235, 0x38e, 0x057, 0x1ac, 0x305, 0x0e1, 0x236, 0x38f, 0x058, 0x1ad, 0x306, 0x0e2,
0x237, 0x390, 0x059, 0x1ae, 0x307, 0x0e3, 0x238, 0x391, 0x05a, 0x1af, 0x308, 0x0e4, 0x239, 0x392, 0x05b, 0x1b0, 0x309,
0x0e5, 0x23a, 0x393, 0x05c, 0x1b1, 0x30a, 0x0e6, 0x23b, 0x394, 0x05d, 0x1b2, 0x30b, 0x0e7, 0x23c, 0x395, 0x05e, 0x1b3,
0x30c, 0x0e8, 0x23d, 0x396, 0x05f, 0x1b4, 0x30d, 0x0e9, 0x23e, 0x397, 0x060, 0x1b5, 0x30e, 0x0ea, 0x23f, 0x398, 0x061,
0x1b6, 0x30f, 0x0eb, 0x240, 0x399, 0x062, 0x1b7, 0x310, 0x0ec, 0x241, 0x39a, 0x063, 0x1b8, 0x311, 0x0ed, 0x242, 0x39b,
0x064, 0x1b9, 0x312, 0x0ee, 0x243, 0x39c, 0x065, 0x1ba, 0x313, 0x0ef, 0x244, 0x39d, 0x066, 0x1bb, 0x314, 0x0f0, 0x245,
0x39e, 0x067, 0x1bc, 0x315, 0x0f1, 0x246, 0x39f, 0x068, 0x1bd, 0x316, 0x0f2, 0x247, 0x3a0, 0x069, 0x1be, 0x317, 0x0f3,
0x248, 0x3a1, 0x06a, 0x1bf, 0x318, 0x0f4, 0x249, 0x3a2, 0x06b, 0x1c0, 0x319, 0x0f5, 0x24a, 0x3a3, 0x06c, 0x1c1, 0x31a,
0x0f6, 0x24b, 0x3a4, 0x06d, 0x1c2, 0x31b, 0x0f7, 0x24c, 0x3a5, 0x06e, 0x1c3, 0x31c, 0x0f8, 0x24d, 0x3a6, 0x06f, 0x1c4,
0x31d, 0x0f9, 0x24e, 0x3a7, 0x070, 0x1c5, 0x31e, 0x0fa, 0x24f, 0x3a8, 0x071, 0x1c6, 0x31f, 0x0fb, 0x250, 0x3a9, 0x072,
0x1c7, 0x320, 0x0fc, 0x251, 0x3aa, 0x073, 0x1c8, 0x321, 0x0fd, 0x252, 0x3ab, 0x074, 0x1c9, 0x322, 0x0fe, 0x253, 0x3ac,
0x075, 0x1ca, 0x323, 0x0ff, 0x254, 0x3ad, 0x076, 0x1cb, 0x324, 0x100, 0x255, 0x3ae, 0x077, 0x1cc, 0x325, 0x101, 0x256,
0x3af, 0x078, 0x1cd, 0x326, 0x102, 0x257, 0x3b0, 0x079, 0x1ce, 0x327, 0x103, 0x258, 0x3b1, 0x07a, 0x1cf, 0x328, 0x104,
0x259, 0x3b2, 0x07b, 0x1d0, 0x329, 0x105, 0x25a, 0x3b3, 0x07c, 0x1d1, 0x32a, 0x106, 0x25b, 0x3b4, 0x07d, 0x1d2, 0x32b,
0x107, 0x25c, 0x3b5, 0x07e, 0x1d3, 0x32c, 0x108, 0x25d, 0x3b6, 0x07f, 0x1d4, 0x32d, 0x109, 0x25e, 0x3b7, 0x080, 0x1d5,
0x32e, 0x10a, 0x25f, 0x3b8, 0x081, 0x1d6, 0x32f, 0x10b, 0x260, 0x3b9, 0x082, 0x1d7, 0x330, 0x10c, 0x261, 0x3ba, 0x083,
0x1d8, 0x331, 0x10d, 0x262, 0x3bb, 0x084, 0x1d9, 0x332, 0x10e, 0x263, 0x3bc, 0x085, 0x1da, 0x333, 0x10f, 0x264, 0x3bd,
0x086, 0x1db, 0x334, 0x110, 0x265, 0x3be, 0x087, 0x1dc, 0x335, 0x111, 0x266, 0x3bf, 0x088, 0x1dd, 0x336, 0x112, 0x267,
0x3c0, 0x089, 0x1de, 0x337, 0x113, 0x268, 0x3c1, 0x08a, 0x1df, 0x338, 0x114, 0x269, 0x3c2, 0x08b, 0x1e0, 0x339, 0x115,
0x26a, 0x3c3, 0x08c, 0x1e1, 0x33a, 0x116, 0x26b, 0x3c4, 0x08d, 0x1e2, 0x33b, 0x117, 0x26c, 0x3c5, 0x08e, 0x1e3, 0x33c,
0x118, 0x26d, 0x3c6, 0x08f, 0x1e4, 0x33d, 0x119, 0x26e, 0x3c7, 0x090, 0x1e5, 0x33e, 0x11a, 0x26f, 0x3c8, 0x091, 0x1e6,
0x33f, 0x11b, 0x270, 0x3c9, 0x092, 0x1e7, 0x340, 0x11c, 0x271, 0x3ca, 0x093, 0x1e8, 0x341, 0x11d, 0x272, 0x3cb, 0x094,
0x1e9, 0x342, 0x11e, 0x273, 0x3cc, 0x095, 0x1ea, 0x343, 0x11f, 0x274, 0x3cd, 0x096, 0x1eb, 0x344, 0x120, 0x275, 0x3ce,
0x097, 0x1ec, 0x345, 0x121, 0x276, 0x3cf, 0x098, 0x1ed, 0x346, 0x122, 0x277, 0x3d0, 0x099, 0x1ee, 0x347, 0x123, 0x278,
0x3d1, 0x09a, 0x1ef, 0x348, 0x124, 0x279, 0x3d2, 0x09b, 0x1f0, 0x349, 0x125, 0x27a, 0x3d3, 0x09c, 0x1f1, 0x34a, 0x126,
0x27b, 0x3d4, 0x09d, 0x1f2, 0x34b, 0x127, 0x27c, 0x3d5, 0x09e, 0x1f3, 0x34c, 0x128, 0x27d, 0x3d6, 0x09f, 0x1f4, 0x34d,
0x129, 0x27e, 0x3d7, 0x0a0, 0x1f5, 0x34e, 0x12a, 0x27f, 0x3d8, 0x0a1, 0x1f6, 0x34f, 0x12b, 0x280, 0x3d9, 0x0a2, 0x1f7,
0x350, 0x12c, 0x281, 0x3da, 0x0a3, 0x1f8, 0x351, 0x12d, 0x282, 0x3db, 0x0a4, 0x1f9, 0x352, 0x12e, 0x283, 0x3dc, 0x0a5,
0x1fa, 0x353, 0x12f, 0x284, 0x3dd, 0x0a6, 0x1fb, 0x354, 0x130, 0x285, 0x3de, 0x0a7, 0x1fc, 0x355, 0x131, 0x286, 0x3df,
0x0a8, 0x1fd, 0x356, 0x132,
];
//prettier-ignore: uint16, size 1024 (64x16)
const x3mScrambleTable = [
0x256, 0x28d, 0x213, 0x307, 0x156, 0x39d, 0x062, 0x170, 0x3ca, 0x035, 0x0ed, 0x2a4, 0x1e4, 0x359, 0x0d3, 0x26b, 0x265,
0x274, 0x251, 0x297, 0x202, 0x322, 0x126, 0x32b, 0x117, 0x302, 0x15c, 0x3a8, 0x057, 0x148, 0x380, 0x090, 0x1f6, 0x335,
0x10c, 0x2ee, 0x175, 0x3d4, 0x02b, 0x0cc, 0x260, 0x27b, 0x23d, 0x2bb, 0x1b6, 0x3a1, 0x05e, 0x157, 0x39e, 0x061, 0x16f,
0x3c6, 0x039, 0x0f7, 0x2b9, 0x1b8, 0x39f, 0x060, 0x166, 0x3b9, 0x046, 0x122, 0x31c, 0x12f, 0x33d, 0x0fc, 0x2ca, 0x1a4,
0x3cc, 0x033, 0x0e6, 0x293, 0x209, 0x315, 0x13d, 0x358, 0x0d5, 0x26e, 0x25e, 0x27d, 0x23a, 0x2c0, 0x1b1, 0x3af, 0x050,
0x136, 0x346, 0x0ef, 0x2aa, 0x1ce, 0x376, 0x0a0, 0x210, 0x30c, 0x14c, 0x389, 0x082, 0x1db, 0x367, 0x0b9, 0x23e, 0x2ba,
0x1b7, 0x3a0, 0x05f, 0x164, 0x3b7, 0x048, 0x125, 0x326, 0x11c, 0x30a, 0x14f, 0x38f, 0x070, 0x1a8, 0x3c7, 0x038, 0x0f5,
0x2b5, 0x1bd, 0x393, 0x06c, 0x199, 0x3e1, 0x01e, 0x0b3, 0x22f, 0x2d7, 0x193, 0x3ea, 0x015, 0x09d, 0x20a, 0x314, 0x13e,
0x35a, 0x0d2, 0x26a, 0x267, 0x272, 0x253, 0x294, 0x208, 0x319, 0x137, 0x34c, 0x0e7, 0x295, 0x205, 0x31d, 0x12e, 0x33c,
0x0fe, 0x2cd, 0x1a0, 0x3d5, 0x02a, 0x0c8, 0x258, 0x286, 0x22a, 0x2dc, 0x18e, 0x3f7, 0x008, 0x07c, 0x1d3, 0x370, 0x0a7,
0x21d, 0x2f1, 0x171, 0x3cd, 0x032, 0x0e5, 0x292, 0x20b, 0x313, 0x13f, 0x35c, 0x0d0, 0x266, 0x273, 0x252, 0x296, 0x204,
0x31f, 0x12a, 0x332, 0x10f, 0x2f4, 0x16c, 0x3c3, 0x03c, 0x101, 0x2d2, 0x19a, 0x3e0, 0x01f, 0x0b5, 0x233, 0x2c9, 0x1a6,
0x3c9, 0x036, 0x0f0, 0x2ab, 0x1cb, 0x37c, 0x095, 0x1fd, 0x328, 0x11a, 0x306, 0x158, 0x3a2, 0x05d, 0x155, 0x39c, 0x063,
0x174, 0x3d3, 0x02c, 0x0cf, 0x264, 0x275, 0x24f, 0x299, 0x1fa, 0x32c, 0x115, 0x2ff, 0x15f, 0x3ab, 0x054, 0x143, 0x36c,
0x0ad, 0x225, 0x2e5, 0x181, 0x3ef, 0x010, 0x08c, 0x1f1, 0x344, 0x0f3, 0x2af, 0x1c4, 0x386, 0x088, 0x1e3, 0x35b, 0x0d1,
0x269, 0x268, 0x26d, 0x25f, 0x27c, 0x23b, 0x2bf, 0x1b2, 0x3ae, 0x051, 0x13b, 0x355, 0x0da, 0x278, 0x248, 0x2a6, 0x1dc,
0x365, 0x0c0, 0x246, 0x2a8, 0x1d6, 0x36d, 0x0ac, 0x224, 0x2e8, 0x17e, 0x3eb, 0x014, 0x09c, 0x207, 0x31a, 0x133, 0x341,
0x0f8, 0x2bc, 0x1b5, 0x3a3, 0x05c, 0x152, 0x395, 0x06a, 0x18c, 0x3f9, 0x006, 0x07a, 0x1d1, 0x373, 0x0a4, 0x217, 0x2fe,
0x160, 0x3ad, 0x052, 0x13c, 0x357, 0x0d7, 0x270, 0x25c, 0x281, 0x235, 0x2c6, 0x1aa, 0x3bc, 0x043, 0x11d, 0x30d, 0x14a,
0x384, 0x08a, 0x1e7, 0x353, 0x0dd, 0x284, 0x22e, 0x2d8, 0x192, 0x3ec, 0x013, 0x099, 0x201, 0x323, 0x124, 0x321, 0x127,
0x32d, 0x114, 0x2fd, 0x161, 0x3b0, 0x04f, 0x135, 0x343, 0x0f4, 0x2b4, 0x1be, 0x392, 0x06d, 0x19d, 0x3db, 0x024, 0x0be,
0x244, 0x2b0, 0x1c2, 0x38a, 0x080, 0x1d9, 0x369, 0x0b6, 0x234, 0x2c8, 0x1a7, 0x3c8, 0x037, 0x0f1, 0x2ad, 0x1c6, 0x383,
0x08d, 0x1f2, 0x33b, 0x100, 0x2d1, 0x19b, 0x3de, 0x021, 0x0bb, 0x240, 0x2b6, 0x1bb, 0x399, 0x066, 0x17a, 0x3df, 0x020,
0x0b8, 0x23c, 0x2bd, 0x1b4, 0x3a5, 0x05a, 0x150, 0x390, 0x06f, 0x1a5, 0x3cb, 0x034, 0x0ea, 0x29d, 0x1ee, 0x348, 0x0ec,
0x2a3, 0x1e5, 0x356, 0x0d8, 0x271, 0x257, 0x289, 0x220, 0x2ec, 0x178, 0x3d9, 0x026, 0x0c2, 0x24b, 0x2a1, 0x1ea, 0x34d,
0x0e4, 0x291, 0x20c, 0x312, 0x141, 0x360, 0x0ca, 0x25a, 0x283, 0x230, 0x2d0, 0x19c, 0x3dd, 0x022, 0x0bc, 0x241, 0x2b3,
0x1bf, 0x391, 0x06e, 0x1a2, 0x3d1, 0x02e, 0x0d6, 0x26f, 0x25d, 0x27f, 0x237, 0x2c4, 0x1ac, 0x3ba, 0x045, 0x121, 0x318,
0x138, 0x34e, 0x0e3, 0x28f, 0x211, 0x30b, 0x14d, 0x38c, 0x073, 0x1c3, 0x387, 0x084, 0x1df, 0x362, 0x0c7, 0x255, 0x28e,
0x212, 0x309, 0x153, 0x396, 0x069, 0x18b, 0x3fa, 0x005, 0x079, 0x1d0, 0x374, 0x0a2, 0x215, 0x301, 0x15d, 0x3a9, 0x056,
0x147, 0x37a, 0x098, 0x200, 0x324, 0x11f, 0x316, 0x13a, 0x352, 0x0df, 0x288, 0x223, 0x2e9, 0x17d, 0x3e9, 0x016, 0x09e,
0x20d, 0x310, 0x144, 0x372, 0x0a5, 0x219, 0x2fa, 0x165, 0x3b8, 0x047, 0x123, 0x31e, 0x12d, 0x338, 0x107, 0x2e0, 0x188,
0x3fe, 0x001, 0x075, 0x1c9, 0x37e, 0x093, 0x1f9, 0x32f, 0x112, 0x2f9, 0x167, 0x3be, 0x041, 0x10b, 0x2e7, 0x17f, 0x3ed,
0x012, 0x097, 0x1ff, 0x325, 0x11e, 0x311, 0x142, 0x366, 0x0ba, 0x23f, 0x2b8, 0x1b9, 0x39b, 0x064, 0x176, 0x3d6, 0x029,
0x0c5, 0x250, 0x298, 0x1fc, 0x329, 0x119, 0x304, 0x15a, 0x3a6, 0x059, 0x14e, 0x38e, 0x071, 0x1ad, 0x3b6, 0x049, 0x128,
0x32e, 0x113, 0x2fc, 0x162, 0x3b2, 0x04d, 0x131, 0x33f, 0x0fa, 0x2c2, 0x1af, 0x3b3, 0x04c, 0x130, 0x33e, 0x0fb, 0x2c7,
0x1a9, 0x3bd, 0x042, 0x116, 0x300, 0x15e, 0x3aa, 0x055, 0x146, 0x378, 0x09b, 0x206, 0x31b, 0x132, 0x340, 0x0f9, 0x2be,
0x1b3, 0x3ac, 0x053, 0x140, 0x35d, 0x0ce, 0x262, 0x279, 0x247, 0x2a7, 0x1d7, 0x36b, 0x0ae, 0x226, 0x2e3, 0x185, 0x3f6,
0x009, 0x07d, 0x1d4, 0x36f, 0x0a8, 0x21e, 0x2f0, 0x172, 0x3ce, 0x031, 0x0de, 0x287, 0x228, 0x2df, 0x189, 0x3fd, 0x002,
0x076, 0x1ca, 0x37d, 0x094, 0x1fb, 0x32a, 0x118, 0x303, 0x15b, 0x3a7, 0x058, 0x14b, 0x388, 0x083, 0x1dd, 0x364, 0x0c1,
0x24a, 0x2a2, 0x1e9, 0x350, 0x0e1, 0x28b, 0x21a, 0x2f8, 0x168, 0x3bf, 0x040, 0x10a, 0x2e6, 0x180, 0x3ee, 0x011, 0x091,
0x1f7, 0x334, 0x10d, 0x2ef, 0x173, 0x3cf, 0x030, 0x0dc, 0x280, 0x236, 0x2c5, 0x1ab, 0x3bb, 0x044, 0x120, 0x317, 0x139,
0x34f, 0x0e2, 0x28c, 0x218, 0x2fb, 0x163, 0x3b4, 0x04b, 0x12c, 0x337, 0x108, 0x2e2, 0x186, 0x3fc, 0x003, 0x077, 0x1cc,
0x37b, 0x096, 0x1fe, 0x327, 0x11b, 0x308, 0x154, 0x397, 0x068, 0x183, 0x3f3, 0x00c, 0x085, 0x1e0, 0x361, 0x0c9, 0x259,
0x285, 0x22c, 0x2da, 0x190, 0x3f2, 0x00d, 0x086, 0x1e1, 0x35f, 0x0cb, 0x25b, 0x282, 0x232, 0x2cc, 0x1a1, 0x3d2, 0x02d,
0x0d4, 0x26c, 0x263, 0x277, 0x249, 0x2a5, 0x1de, 0x363, 0x0c6, 0x254, 0x290, 0x20e, 0x30f, 0x145, 0x377, 0x09f, 0x20f,
0x30e, 0x149, 0x382, 0x08e, 0x1f3, 0x33a, 0x102, 0x2d3, 0x198, 0x3e2, 0x01d, 0x0b2, 0x22d, 0x2d9, 0x191, 0x3f1, 0x00e,
0x087, 0x1e2, 0x35e, 0x0cd, 0x261, 0x27a, 0x243, 0x2b1, 0x1c1, 0x38b, 0x07f, 0x1d8, 0x36a, 0x0b4, 0x231, 0x2cf, 0x19e,
0x3da, 0x025, 0x0bf, 0x245, 0x2ac, 0x1c7, 0x381, 0x08f, 0x1f5, 0x336, 0x109, 0x2e4, 0x184, 0x3f4, 0x00b, 0x081, 0x1da,
0x368, 0x0b7, 0x239, 0x2c1, 0x1b0, 0x3b1, 0x04e, 0x134, 0x342, 0x0f6, 0x2b7, 0x1ba, 0x39a, 0x065, 0x179, 0x3dc, 0x023,
0x0bd, 0x242, 0x2b2, 0x1c0, 0x38d, 0x072, 0x1bc, 0x398, 0x067, 0x182, 0x3f0, 0x00f, 0x08b, 0x1e8, 0x351, 0x0e0, 0x28a,
0x21c, 0x2f3, 0x16d, 0x3c4, 0x03b, 0x0ff, 0x2ce, 0x19f, 0x3d7, 0x028, 0x0c4, 0x24e, 0x29b, 0x1f0, 0x345, 0x0f2, 0x2ae,
0x1c5, 0x385, 0x089, 0x1e6, 0x354, 0x0db, 0x27e, 0x238, 0x2c3, 0x1ae, 0x3b5, 0x04a, 0x12b, 0x333, 0x10e, 0x2f2, 0x16e,
0x3c5, 0x03a, 0x0fd, 0x2cb, 0x1a3, 0x3d0, 0x02f, 0x0d9, 0x276, 0x24c, 0x29f, 0x1ec, 0x34a, 0x0e9, 0x29c, 0x1ef, 0x347,
0x0ee, 0x2a9, 0x1cf, 0x375, 0x0a1, 0x214, 0x305, 0x159, 0x3a4, 0x05b, 0x151, 0x394, 0x06b, 0x196, 0x3e6, 0x019, 0x0ab,
0x222, 0x2ea, 0x17c, 0x3e5, 0x01a, 0x0af, 0x227, 0x2e1, 0x187, 0x3ff, 0x000, 0x074, 0x1c8, 0x37f, 0x092, 0x1f8, 0x331,
0x110, 0x2f6, 0x16a, 0x3c1, 0x03e, 0x104, 0x2d5, 0x195, 0x3e7, 0x018, 0x0aa, 0x221, 0x2eb, 0x17b, 0x3e4, 0x01b, 0x0b0,
0x229, 0x2dd, 0x18d, 0x3f8, 0x007, 0x07b, 0x1d2, 0x371, 0x0a6, 0x21b, 0x2f5, 0x16b, 0x3c2, 0x03d, 0x103, 0x2d4, 0x197,
0x3e3, 0x01c, 0x0b1, 0x22b, 0x2db, 0x18f, 0x3f5, 0x00a, 0x07e, 0x1d5, 0x36e, 0x0a9, 0x21f, 0x2ed, 0x177, 0x3d8, 0x027,
0x0c3, 0x24d, 0x29e, 0x1ed, 0x349, 0x0eb, 0x2a0, 0x1eb, 0x34b, 0x0e8, 0x29a, 0x1f4, 0x339, 0x106, 0x2de, 0x18a, 0x3fb,
0x004, 0x078, 0x1cd, 0x379, 0x09a, 0x203, 0x320, 0x129, 0x330, 0x111, 0x2f7, 0x169, 0x3c0, 0x03f, 0x105, 0x2d6, 0x194,
0x3e8, 0x017, 0x0a3, 0x216,
];
|
4f329b4cbcbb7a3cceeae829f4b8e6d78bca7e42
|
TypeScript
|
Financial-Times/dotcom-page-kit
|
/packages/dotcom-server-handlebars/src/helpers/json.ts
| 2.5625
| 3
|
export default function json(...args) {
if (args.length !== 2) {
throw Error('Incorrect number of parameters provided')
}
// The second parameter will always be an instance of HelperOptions
const target = args[0]
// Do not allow users to output the whole @root context
// <https://github.com/Financial-Times/n-handlebars/pull/65>
if (target && target.hasOwnProperty('_locals')) {
throw Error('For security reasons you may not use the JSON helper to output the entire view context')
}
return JSON.stringify(target)
}
|
ff6efd1c841af076ad246351abd6b41288e02011
|
TypeScript
|
thaapasa/simulations
|
/src/util/Colors.test.ts
| 2.796875
| 3
|
import 'jest';
import { hexByte, rgbColor } from './Colors';
describe('Color utils', () => {
it('calculates hex bytes from unit values', () => {
expect(hexByte(0)).toBe('00');
expect(hexByte(1)).toBe('FF');
expect(hexByte(0.5)).toBe('80');
expect(hexByte(0.498)).toBe('7F');
expect(hexByte(0.02)).toBe('05');
});
it('calculates hex bytes', () => {
expect(hexByte(0, false)).toBe('00');
expect(hexByte(1, false)).toBe('01');
expect(hexByte(255, false)).toBe('FF');
expect(hexByte(127, false)).toBe('7F');
});
it('calculates rgb color strings', () => {
expect(rgbColor(7, 125, 250, false)).toBe('#077DFA');
expect(rgbColor(0, 0, 0, false)).toBe('#000000');
expect(rgbColor(255, 255, 255, false)).toBe('#FFFFFF');
});
it('calculates rgb color strings from unit values', () => {
expect(rgbColor(0, 0, 0, true)).toBe('#000000');
expect(rgbColor(1, 1, 1, true)).toBe('#FFFFFF');
expect(rgbColor(0.5, 0.498, 0.02, true)).toBe('#807F05');
});
});
|
3567768cc89115c7b4e78db4dad31f000ec23252
|
TypeScript
|
ianevangelista/next-portfolio
|
/utils/about/education-text.ts
| 2.90625
| 3
|
import getDifferenceDates from "./date-difference";
interface Education {
study: string;
school: string;
duration: string;
}
const vgsStartDate = new Date(2015, 7);
const vgsEndDate = new Date(2018, 5);
const bachelorStartDate = new Date(2018, 7);
const bachelorEndDate = new Date(2021, 5);
const masterStartDate = new Date(2021, 7);
const masterEndDate = new Date();
const Educations: Education[] = [
{
study: "M.Sc Computer Science",
school: "Norwegian University of Science and Technology",
duration: getDifferenceDates(masterStartDate, masterEndDate),
},
{
study: "B.Sc Computer Engineering",
school: "Norwegian University of Science and Technology",
duration: getDifferenceDates(bachelorStartDate, bachelorEndDate),
},
{
study: "General Studies",
school: "Asker Videregående skole",
duration: getDifferenceDates(vgsStartDate, vgsEndDate),
},
];
export default Educations;
|
30a0b7251e714bae81ff56e68b2d750b9214e6e2
|
TypeScript
|
jakewitcher/100_Algorithms_Challenge_course
|
/absoluteValuesSumMinization/absoluteValuesSumMinization.ts
| 3.609375
| 4
|
function absoluteValuesSumMinimization(a: number[]): number {
return a.reduce((x: number, y: number) => {
const absSumX = a.reduce((b: number, c: number) => {
return b + Math.abs(c - x);
}, 0);
const absSumY = a.reduce((d: number, e: number) => {
return d + Math.abs(e - y);
}, 0);
if (absSumX <= absSumY) {
return x;
}
return y;
});
}
console.log(absoluteValuesSumMinimization([2, 4, 7])); // 4
console.log(absoluteValuesSumMinimization([2, 4, 7, 6])); // 4
console.log(absoluteValuesSumMinimization([2, 4, 7, 6, 6])); // 6
console.log(absoluteValuesSumMinimization([2, 4, 7, 6, 6, 8])); // 6
|