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
|
|---|---|---|---|---|---|---|
a424019908f1155cfcab2c44634093b90dbd5c79
|
TypeScript
|
hemantv/ReactNativePaperGalleryProject
|
/src/Assets/Data/Code/Appbar/AppbarCode.ts
| 2.609375
| 3
|
const AppbarCode = () => `import React, {useState} from 'react';
import {Platform, View} from 'react-native';
import {Appbar, Checkbox} from 'react-native-paper';
const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical';
const AppbarDemo = () => {
const [subtitleChecked, setSubtitleChecked] = useState(false);
const [backChecked, setBackChecked] = useState(false);
const [actionChecked, setActionChecked] = useState(false);
return (
<View>
<Appbar.Header>
{backChecked && <Appbar.BackAction />}
<Appbar.Content
title="Title"
subtitle={subtitleChecked && 'Subtitle'}
/>
{actionChecked && <Appbar.Action icon="magnify" />}
{actionChecked && <Appbar.Action icon={MORE_ICON} onPress={() => {}} />}
</Appbar.Header>
<View>
<Checkbox.Item
label={'Subtitle'}
status={subtitleChecked ? 'checked' : 'unchecked'}
onPress={() => {
setSubtitleChecked(!subtitleChecked);
}}
/>
<Checkbox.Item
label={'Back'}
status={backChecked ? 'checked' : 'unchecked'}
onPress={() => {
setBackChecked(!backChecked);
}}
/>
<Checkbox.Item
label={'Action'}
status={actionChecked ? 'checked' : 'unchecked'}
onPress={() => {
setActionChecked(!actionChecked);
}}
/>
</View>
</View>
);
};
export default AppbarDemo;
`;
export default AppbarCode
|
9170180245574eb4715914609fb60d0f0654fb71
|
TypeScript
|
backstage/backstage
|
/packages/config-loader/src/sources/MergedConfigSource.ts
| 2.59375
| 3
|
/*
* Copyright 2023 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AsyncConfigSourceGenerator,
ConfigSource,
ConfigSourceData,
ReadConfigDataOptions,
} from './types';
const sourcesSymbol = Symbol.for(
'@backstage/config-loader#MergedConfigSource.sources',
);
/** @internal */
export class MergedConfigSource implements ConfigSource {
// An optimization to flatten nested merged sources to avid unnecessary microtasks
static #flattenSources(sources: ConfigSource[]): ConfigSource[] {
return sources.flatMap(source => {
if (
sourcesSymbol in source &&
Array.isArray((source as any)[sourcesSymbol])
) {
return this.#flattenSources(
(source as any)[sourcesSymbol] as ConfigSource[],
);
}
return source;
});
}
static from(sources: ConfigSource[]): ConfigSource {
return new MergedConfigSource(this.#flattenSources(sources));
}
[sourcesSymbol]: ConfigSource[];
private constructor(private readonly sources: ConfigSource[]) {
this[sourcesSymbol] = this.sources;
}
async *readConfigData(
options?: ReadConfigDataOptions,
): AsyncConfigSourceGenerator {
const its = this.sources.map(source => source.readConfigData(options));
const initialResults = await Promise.all(its.map(it => it.next()));
const configs = initialResults.map((result, i) => {
if (result.done) {
throw new Error(
`Config source ${String(this.sources[i])} returned no data`,
);
}
return result.value.configs;
});
yield { configs: configs.flat(1) };
const results: Array<
| Promise<
readonly [
number,
IteratorResult<{ configs: ConfigSourceData[] }, void>,
]
>
| undefined
> = its.map((it, i) => nextWithIndex(it, i));
while (results.some(Boolean)) {
try {
const [i, result] = (await Promise.race(results.filter(Boolean)))!;
if (result.done) {
results[i] = undefined;
} else {
results[i] = nextWithIndex(its[i], i);
configs[i] = result.value.configs;
yield { configs: configs.flat(1) };
}
} catch (error) {
const source = this.sources[error.index];
if (source) {
throw new Error(`Config source ${String(source)} failed: ${error}`);
}
throw error;
}
}
}
toString() {
return `MergedConfigSource{${this.sources.map(String).join(', ')}}`;
}
}
// Helper to wait for the next value of the iterator, while decorating the value
// or error with the index of the iterator.
function nextWithIndex<T>(
iterator: AsyncIterator<T, void, void>,
index: number,
): Promise<readonly [index: number, result: IteratorResult<T, void>]> {
return iterator.next().then(
r => [index, r] as const,
e => {
throw Object.assign(e, { index });
},
);
}
|
55621717654fe08369ca9b663b771e4734c1fab2
|
TypeScript
|
seregaa020292/capitalhub
|
/frontend/src/app/store/modules/auth.ts
| 2.921875
| 3
|
import { MutationTree } from 'vuex'
export interface IAuthState {
loggedIn: boolean
expire: number | null
csrf: string
}
/**
******************************
* @State
******************************
*/
export const state = (): IAuthState => ({
loggedIn: false,
expire: null,
csrf: '',
})
/**
******************************
* @Mutation
******************************
*/
export enum Types {
FETCH_AUTH = 'auth/fetch',
CLEAR_AUTH = 'auth/clear',
}
export class FetchAuth implements FluxStandardAction {
public type = Types.FETCH_AUTH
constructor(public payload: IAuthState) {}
}
export class ClearAuth implements FluxStandardAction {
public type = Types.CLEAR_AUTH
}
export const mutations: MutationTree<IAuthState> = {
[Types.FETCH_AUTH]: (state, action: FetchAuth) => {
state.expire = action.payload.expire
state.loggedIn = action.payload.loggedIn
state.csrf = action.payload.csrf
},
[Types.CLEAR_AUTH]: (state) => {
state.expire = null
state.loggedIn = false
state.csrf = ''
},
}
|
2bbc71ff7a38fc67c0b91f7f3588dc23226efee0
|
TypeScript
|
contiamo/restful-react
|
/src/util/processResponse.ts
| 2.578125
| 3
|
export const processResponse = async (response: Response) => {
if (response.status === 204) {
return { data: undefined, responseError: false };
}
if ((response.headers.get("content-type") || "").includes("application/json")) {
try {
return {
data: await response.json(),
responseError: false,
};
} catch (e) {
return {
data: e.message,
responseError: true,
};
}
} else if (
(response.headers.get("content-type") || "").includes("text/plain") ||
(response.headers.get("content-type") || "").includes("text/html")
) {
try {
return {
data: await response.text(),
responseError: false,
};
} catch (e) {
return {
data: e.message,
responseError: true,
};
}
} else {
return {
data: response,
responseError: false,
};
}
};
|
886d34eb41e94b586343385c46b4e1c75bff58f4
|
TypeScript
|
ahmedNY/express-typescript-boilerplate
|
/src/auth/currentUserChecker.ts
| 2.6875
| 3
|
import { Action } from 'routing-controllers';
import { Connection } from 'typeorm';
import { User } from '../api/models/User';
import { Logger } from '../lib/logger';
import { TokenInfoInterface } from './TokenInfoInterface';
export function currentUserChecker(connection: Connection): (action: Action) => Promise<User | undefined> {
const log = new Logger(__filename);
return async function innerCurrentUserChecker(action: Action): Promise<User | undefined> {
// here you can use request/response objects from action
// you need to provide a user object that will be injected in controller actions
// demo code:
const tokeninfo: TokenInfoInterface = action.request.tokeninfo;
const em = connection.createEntityManager();
const user = await em.findOne<User>(User, {
where: { id: tokeninfo.userId },
});
if (user) {
log.info('Current user is ', user.toString());
} else {
log.info('Current user is undefined');
}
return user;
};
}
|
c5a7d29ea5364f03634a3a2badf7578e925329a6
|
TypeScript
|
andrewandzz/my-messages
|
/MyMessages.Api/ClientApp/src/app/shared/services/account.service.ts
| 2.515625
| 3
|
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Token } from '../interfaces/token.interface';
import md5 from 'crypto-js/md5';
import { environment } from 'src/environments/environment';
@Injectable()
export class AccountService {
private readonly http: HttpClient;
private readonly url: string;
public constructor(http: HttpClient) {
this.http = http;
this.url = `${environment.host}/api/accounts`;
}
public isLoggedIn(): Observable<boolean> {
// short circuit
if (!this.isTokenInStorage()) {
return of(false);
}
const url = `${this.url}/verify-token`;
const headers = new HttpHeaders({
'Authorization': `Bearer ${sessionStorage.getItem('token')}`
});
return this.http.head(url, { headers }).pipe(
map(_ => true), // if no error, then the token is valid
catchError(_ => {
// if error, then the token is invalid
// remove token from storage to let
// the short circuit to be done the next time
this.removeTokenFromStorage();
return of(false);
})
);
}
public login(name: string, password: string): Observable<boolean> {
const url = `${this.url}/login`;
const body = {
name,
password: md5(password).toString()
};
return this.http.post<Token>(url, body).pipe(
map(token => {
this.removeTokenFromStorage();
sessionStorage.setItem('token', token.token);
return true;
}),
catchError(_ => {
// remove token from storage to let
// the short circuit to be done the next time
this.removeTokenFromStorage();
return of(false);
})
);
}
public logout(): void {
this.removeTokenFromStorage();
}
public register(name: string, password: string): Observable<any> {
const url = `${this.url}/register`;
const body = {
name,
password
};
return this.http.post(url, body);
}
private isTokenInStorage(): boolean {
return sessionStorage.getItem('token') !== null;
}
private removeTokenFromStorage(): void {
sessionStorage.removeItem('token');
}
}
|
792a260e4992b34520e091a5345a9edf1de2a04f
|
TypeScript
|
alchemist/alchemist-core
|
/src/registries/node-generator-registry.ts
| 2.8125
| 3
|
import {INodeGenerator} from "../generators/inode-generator";
import {INode} from "../models/nodes/inode";
export class NodeGeneratorRegistry
{
private generators: Array<INodeGenerator> = [];
public getGeneratorsFor = (node: INode): Array<INodeGenerator> => {
return this.generators.filter(x => x.canHandleType(node));
};
public addGenerator = (generator: INodeGenerator) => {
if(this.generators.indexOf(generator) >= 0)
{ return; }
this.generators.push(generator);
};
public removeGenerator = (generator: INodeGenerator) => {
const index = this.generators.indexOf(generator);
if(index < 0)
{ return; }
this.generators.splice(index, 1);
};
}
export const nodeGeneratorRegistry = new NodeGeneratorRegistry();
|
33b110970e5374efa7c66bde0b2cfe2a714acfb5
|
TypeScript
|
pankajparkar/ng-rfx
|
/projects/rfx-lib/src/lib/model.ts
| 2.578125
| 3
|
import {AbstractControl, AbstractControlOptions} from '@angular/forms';
import {TypedFormArray, TypedFormControl, TypedFormGroup} from './forms/typed-form-control';
export interface ErrorMessages {
[k: string]: ErrorMessages | string;
}
export type ErrorMessageResolver = (control: AbstractControl, path: string[]) => string[] | null;
export type PrimitiveType = string | number | boolean | null;
export type FormDefinitionTypeLiteral = 'Field' | 'Group' | 'GroupArray' | 'PrimitiveArray';
export interface FormDefinitionBase {
readonly type: FormDefinitionTypeLiteral;
readonly options?: AbstractControlOptions;
readonly alias?: string;
}
export interface FormDefinitionField<T> extends FormDefinitionBase {
readonly type: 'Field';
readonly initialValue: T;
}
export interface FormDefinitionGroup<F> extends FormDefinitionBase {
readonly type: 'Group';
readonly fields: FormDefinitionFields<F>;
}
export interface FormDefinitionPrimitiveArray<T> extends FormDefinitionBase {
readonly type: 'PrimitiveArray';
readonly initialValue?: T[];
}
export interface FormDefinitionGroupArray<F> extends FormDefinitionBase {
readonly type: 'GroupArray';
readonly group: FormDefinitionGroup<F>;
readonly initialItems?: number;
}
export type FormDefinition<T> =
FormDefinitionField<T> |
FormDefinitionGroup<T> |
FormDefinitionPrimitiveArray<T> |
FormDefinitionGroupArray<T>;
export type FormDefinitionType<T> =
T extends PrimitiveType ? FormDefinitionField<T> | T :
T extends (infer E)[] ? E extends PrimitiveType ? FormDefinitionPrimitiveArray<E> | T : FormDefinitionGroupArray<E> :
FormDefinitionGroup<T>;
export type FormDefinitionFields<F> = {
[K in keyof F]: FormDefinitionType<F[K]>;
};
export interface FormStateControlBase {
readonly untouched: boolean;
readonly touched: boolean;
readonly pristine: boolean;
readonly dirty: boolean;
readonly valid: boolean;
readonly invalid: boolean;
readonly pending: boolean;
readonly disabled: boolean;
readonly enabled: boolean;
readonly errors: string[] | null;
}
export type FormStateGroupFields<F> = {
[K in keyof F]: FormState<F[K]>;
};
export interface FormStateGroup<F> extends FormStateControlBase {
readonly value: F;
readonly fields: FormStateGroupFields<F>;
}
export interface FormStateArray<E> extends FormStateControlBase {
readonly value: E[];
readonly items: FormState<E>[];
}
export interface FormStateControl<T> extends FormStateControlBase {
readonly value: T;
}
export type FormState<F> =
F extends PrimitiveType ? FormStateControl<F> :
F extends (infer E)[] ? FormStateArray<E> :
FormStateGroup<F>;
export type TypedFormControlType<T> =
T extends PrimitiveType ? TypedFormControl<T> :
T extends (infer E)[] ? TypedFormArray<E> :
TypedFormGroup<T>;
export interface FormData<T> {
state: FormState<T>;
control: TypedFormControlType<T>;
}
export interface TypedFormRegistryKey<T> {
id: string;
}
export type FormRegistryKey<T> = TypedFormRegistryKey<T> | string;
export type InitialFormData<T> = T extends (infer E)[] ? Partial<E>[] : Partial<T>;
|
3319e978766556d8d246fe9f78c6431d5915cfbc
|
TypeScript
|
shternberga/codelex-prep-course
|
/exercises/00-warm-up/src/31-sum-all.ts
| 4.03125
| 4
|
export {};
/**
* Implement a function which takes two integers and returns the sum of every number between (inclusive), for example:
*
* - 1, 4 will return 1 + 2 + 3 + 4 which is 10
*/
const sumAll = function(a: number, b: number): number {
let sum: number;
for (let i = a; i <= b; i++) {
sum += i;
}
return sum;
};
console.log(sumAll(1, 4)); // Expected output: 10
|
b50e2a274d033a4c82d8c6a09aa8a41ef987e073
|
TypeScript
|
ktt-ol/sgTraffic
|
/app/data.ts
| 3.28125
| 3
|
/// <reference path="typings/tsd.d.ts"/>
require('source-map-support').install();
export interface DataSet {
totalIn:number;
totalOut:number;
detailIn:number[];
detailOut:number[];
}
export class Ring {
private value:number[];
private pointer:number = 0;
private valuesCount:number = 0;
constructor(private size:number) {
this.value = [];
for (var i = 0; i < size; i++) {
this.value[i] = 0;
}
}
add(entry:number) {
if (typeof entry !== 'number') {
entry = 0;
}
this.value[this.pointer] = entry;
this.pointer = (this.pointer + 1) % this.size;
// avoid number overflow ;)
if (this.size > this.valuesCount) {
this.valuesCount++;
}
}
getAvgPerSecond(slots:number, secondsBetweenSlots:number):number {
if (this.size < slots) {
throw new Error('argument must not greater than size of this buffer');
}
if (slots === 0) {
throw new Error('argument must greater than 0');
}
if (this.valuesCount < slots) {
if (this.valuesCount === 0) {
return 0;
}
// we have less values count as requested
slots = this.valuesCount;
}
var index, sum = 0;
for (var s = 1; s <= slots; s++) {
// I want to have always a positive index
index = (this.pointer - s + this.size) % this.size;
sum += this.value[index];
}
return Math.round(sum / slots / secondsBetweenSlots);
}
}
export class Storage {
private tIn:Ring;
private tOut:Ring;
private dIn:Ring[] = [];
private dOut:Ring[] = [];
constructor(private size:number, private secondsBetweenSlots:number) {
this.tIn = new Ring(size);
this.tOut = new Ring(size);
for (var i=0; i<256; i++) {
this.dIn[i] = new Ring(size);
this.dOut[i] = new Ring(size);
}
}
addData(p:DataSet) {
this.tIn.add(p.totalIn);
this.tOut.add(p.totalOut);
for (var i = 0; i < 256; i++) {
this.dIn[i].add(p.detailIn[i]);
this.dOut[i].add(p.detailOut[i]);
}
}
getAvgPerSecond(amount:number):DataSet {
if (this.size < amount) {
throw new Error('entries must not greater than size of this buffer');
}
return {
totalIn: this.tIn.getAvgPerSecond(amount, this.secondsBetweenSlots),
totalOut: this.tOut.getAvgPerSecond(amount, this.secondsBetweenSlots),
detailIn: this.dIn.map(entry => entry.getAvgPerSecond(amount, this.secondsBetweenSlots)),
detailOut: this.dOut.map(entry => entry.getAvgPerSecond(amount, this.secondsBetweenSlots))
};
}
}
|
d3e6ca4f1def0ec10ad7411b69d89722c0e193aa
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/browser/client-opsworks-browser/types/_Volume.ts
| 2.921875
| 3
|
/**
* <p>Describes an instance's Amazon EBS volume.</p>
*/
export interface _Volume {
/**
* <p>The volume ID.</p>
*/
VolumeId?: string;
/**
* <p>The Amazon EC2 volume ID.</p>
*/
Ec2VolumeId?: string;
/**
* <p>The volume name.</p>
*/
Name?: string;
/**
* <p>The RAID array ID.</p>
*/
RaidArrayId?: string;
/**
* <p>The instance ID.</p>
*/
InstanceId?: string;
/**
* <p>The value returned by <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html">DescribeVolumes</a>.</p>
*/
Status?: string;
/**
* <p>The volume size.</p>
*/
Size?: number;
/**
* <p>The device name.</p>
*/
Device?: string;
/**
* <p>The volume mount point. For example, "/mnt/disk1".</p>
*/
MountPoint?: string;
/**
* <p>The AWS region. For more information about AWS regions, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and Endpoints</a>.</p>
*/
Region?: string;
/**
* <p>The volume Availability Zone. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html">Regions and Endpoints</a>.</p>
*/
AvailabilityZone?: string;
/**
* <p>The volume type. For more information, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html"> Amazon EBS Volume Types</a>.</p> <ul> <li> <p> <code>standard</code> - Magnetic. Magnetic volumes must have a minimum size of 1 GiB and a maximum size of 1024 GiB.</p> </li> <li> <p> <code>io1</code> - Provisioned IOPS (SSD). PIOPS volumes must have a minimum size of 4 GiB and a maximum size of 16384 GiB.</p> </li> <li> <p> <code>gp2</code> - General Purpose (SSD). General purpose volumes must have a minimum size of 1 GiB and a maximum size of 16384 GiB.</p> </li> <li> <p> <code>st1</code> - Throughput Optimized hard disk drive (HDD). Throughput optimized HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 GiB.</p> </li> <li> <p> <code>sc1</code> - Cold HDD. Cold HDD volumes must have a minimum size of 500 GiB and a maximum size of 16384 GiB.</p> </li> </ul>
*/
VolumeType?: string;
/**
* <p>For PIOPS volumes, the IOPS per disk.</p>
*/
Iops?: number;
/**
* <p>Specifies whether an Amazon EBS volume is encrypted. For more information, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html">Amazon EBS Encryption</a>.</p>
*/
Encrypted?: boolean;
}
export type _UnmarshalledVolume = _Volume;
|
988c2c9a0ba636f8743ed598a4e8b0555a8cdcf9
|
TypeScript
|
jpwardd/ticket-manager-rails
|
/client/src/store/types.ts
| 2.625
| 3
|
// Auth Types
export type User = {
firstName: string;
lastName: string;
email: string;
owner: boolean;
manager: boolean;
receptionist: boolean;
};
// Services Types
export interface Service {
id: string
name: string
price: string
category: string
user: User
}
export type formElement = React.FormEvent<HTMLFormElement>
export type inputElement = React.ChangeEvent<HTMLInputElement>
|
f6a3f783fe28d37d32d8fd2d9d8156054db105c0
|
TypeScript
|
Bhanukamax/vc-todo-app
|
/api/src/modules/repository/todo.repository.ts
| 2.96875
| 3
|
import { TodoStatus } from "../enums/todo-status.enum";
import TodoModel from "../models/todo.model";
import { ITodoQuery, ITodoQueryInput } from "../types/index.types";
export interface ITodoRepository {
queryTodos(args: ITodoQueryInput): Promise<any>;
toggleAllTodos(status: TodoStatus): Promise<any>;
addTodo(description: string): Promise<any>;
findById(id: string): Promise<any>;
deleteCompleted(): Promise<any>;
toggleCompleted(id: string): Promise<any>;
}
export default class TodoRepository implements ITodoRepository {
private _model: any;
constructor(model: any) {
this._model = model;
}
public async queryTodos(args: ITodoQueryInput) {
const query: ITodoQuery = {};
if (args.ids) {
query._id = { $in: args.ids };
}
if (args.statuses) {
query.status = { $in: args.statuses };
}
return await this._model.find(query);
}
public async toggleAllTodos(status: TodoStatus) {
await this._model.updateMany({}, { $set: { status } });
return status;
}
public async addTodo(description: string) {
const todo = new this._model({ description });
await todo.save();
return todo;
}
public async findById(id: string) {
return this._model.findById(id);
}
public async deleteCompleted() {
await this._model.remove({ status: TodoStatus.COMPLETED });
}
public async toggleCompleted(id: string) {
const todo = await this._model.findOne({ _id: id });
if (todo) {
todo.status =
todo.status === TodoStatus.ACTIVE
? TodoStatus.COMPLETED
: TodoStatus.ACTIVE;
await todo.save();
}
return todo;
}
}
export const todoRepository = new TodoRepository(TodoModel);
|
acb4c76650bfbf2af852a5a07f1c0080ee6ca6f1
|
TypeScript
|
knopkem/dicomweb-proxy
|
/src/dimse/wadoUri.ts
| 2.53125
| 3
|
import { ConfParams, config } from '../utils/config';
import { LoggerSingleton } from '../utils/logger';
import { fileExists } from '../utils/fileHelper';
import { compressFile } from './compressFile';
import { waitOrFetchData } from './fetchData';
import path from 'path';
import fs from 'fs';
import { stringToQueryLevel } from './querLevel';
type WadoUriArgs = {
studyInstanceUid: string;
seriesInstanceUid: string;
sopInstanceUid: string;
};
type WadoUriResponse = {
contentType: string;
buffer: Buffer;
};
export async function doWadoUri({ studyInstanceUid, seriesInstanceUid, sopInstanceUid }: WadoUriArgs): Promise<WadoUriResponse> {
const logger = LoggerSingleton.Instance;
const fetchLevel = config.get(ConfParams.FETCH_LEVEL) as string;
const level = stringToQueryLevel(fetchLevel);
const storagePath = config.get(ConfParams.STORAGE_PATH) as string;
const studyPath = path.join(storagePath, studyInstanceUid);
const pathname = path.join(studyPath, sopInstanceUid);
// fetch if needed
const exists = await fileExists(pathname);
if (!exists) {
try {
await waitOrFetchData(studyInstanceUid, seriesInstanceUid, sopInstanceUid, level);
} catch (err) {
logger.error(`fetch failed for study: ${studyInstanceUid}`);
throw err;
}
}
const postExists = await fileExists(pathname);
if (!postExists) {
const msg = `file not found ${pathname}`;
logger.error(msg);
throw msg;
}
try {
await compressFile(pathname, studyPath);
} catch (error) {
logger.error(error);
const msg = `failed to compress ${pathname}`;
throw msg;
}
// read file from file system
const fsPromise = fs.promises;
try {
return {
contentType: 'application/dicom',
buffer: await fsPromise.readFile(pathname),
};
} catch (error) {
logger.error(error);
const msg = `failed to read ${pathname}`;
throw msg;
}
}
|
fd27ca6c210451365cba7e27917f57d943fdc2a7
|
TypeScript
|
GiovanaNp1/Adoption-For-Love
|
/Back-End/src/services/CreateUserJudge.ts
| 2.546875
| 3
|
import { getRepository } from 'typeorm';
import Judge from '../models/RegisterJudge';
interface Request {
name: string;
id_judge: string;
email: string;
password: string;
}
class CreateUserJudge {
public async execute({
name,
id_judge,
email,
password,
}: Request): Promise<Judge> {
const JudgeRepository = getRepository(Judge);
const userJudge = JudgeRepository.create({
name,
id_judge,
email,
password,
});
await JudgeRepository.save(userJudge);
return userJudge;
}
}
export default CreateUserJudge;
|
b8d72013dd2a4a1f6b48199d13bd14384dbd2ee9
|
TypeScript
|
Dan-Ayettey/catalog-app
|
/src/controller/productController.ts
| 2.71875
| 3
|
import ProductModel from "../model/productModel";
class ProductController{
private productModel: ProductModel;
constructor(productModel:ProductModel) {
this.productModel=productModel
}
setImage=(image:number)=>{
this.productModel.setImage(image);
}
setIsDropable=(isDrop:boolean)=>{
this.productModel.setIsDropable(isDrop);
}
setProductId=(productId:number)=>{
this.productModel.setProductId(productId);
}
setProductCart= (productList: { image: number; price: string; index: number; productDetails: string })=>{
this.productModel.setProductCart(productList);
}
setProductDetails=(productDetails:string)=>{
this.productModel.setProductDetails(productDetails);
}
setPrice=(price:string)=>{
this.productModel.setPrice(price);
}
}
export default ProductController
|
f190be9ea1eff54bf2170af8d15a3822aea7fc74
|
TypeScript
|
coderofsalvation/react-admin
|
/packages/ra-core/src/dataProvider/useGetList.ts
| 2.984375
| 3
|
import { Pagination, Sort, ReduxState } from '../types';
import useQueryWithStore from './useQueryWithStore';
/**
* Call the dataProvider.getList() method and return the resolved result
* as well as the loading state.
*
* The return value updates according to the request state:
*
* - start: { loading: true, loaded: false }
* - success: { data: [data from store], ids: [ids from response], total: [total from response], loading: false, loaded: true }
* - error: { error: [error from response], loading: false, loaded: true }
*
* This hook will return the cached result when called a second time
* with the same parameters, until the response arrives.
*
* @param {string} resource The resource name, e.g. 'posts'
* @param {Object} pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 }
* @param {Object} sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' }
* @param {Object} filter The request filters, e.g. { title: 'hello, world' }
* @param {Object} options Options object to pass to the dataProvider. May include side effects to be executed upon success of failure, e.g. { onSuccess: { refresh: true } }
*
* @returns The current request state. Destructure as { data, total, ids, error, loading, loaded }.
*
* @example
*
* import { useGetList } from 'react-admin';
*
* const LatestNews = () => {
* const { data, ids, loading, error } = useGetList(
* 'posts',
* { page: 1, perPage: 10 },
* { field: 'published_at', order: 'DESC' }
* );
* if (loading) { return <Loading />; }
* if (error) { return <p>ERROR</p>; }
* return <ul>{ids.map(id =>
* <li key={id}>{data[id].title}</li>
* )}</ul>;
* };
*/
const useGetList = (
resource: string,
pagination: Pagination,
sort: Sort,
filter: object,
options?: any
) => {
if (options && options.action) {
throw new Error(
'useGetList() does not support custom action names. Use useQueryWithStore() and your own Redux selectors if you need a custom action name for a getList query'
);
}
const key = JSON.stringify({
type: 'GET_LIST',
resource: resource,
payload: { pagination, sort, filter },
});
const { data, total, error, loading, loaded } = useQueryWithStore(
{ type: 'getList', resource, payload: { pagination, sort, filter } },
options,
(state: ReduxState) =>
state.admin.customQueries[key]
? state.admin.customQueries[key].data
: null,
(state: ReduxState) =>
state.admin.customQueries[key]
? state.admin.customQueries[key].total
: null
);
const ids = data ? data.map(record => record.id) : [];
const dataObject = data
? data.reduce((acc, next) => {
acc[next.id] = next;
return acc;
}, {})
: {};
return { data: dataObject, ids, total, error, loading, loaded };
};
export default useGetList;
|
9ccafd8a9056b97bf6088276ba0ca4c4464b7529
|
TypeScript
|
pdxmholmes/dirty-fingernails
|
/src/bot/commands/handlers/new-group.ts
| 2.625
| 3
|
import * as moment from 'moment';
import {
IBotRequest,
Utils,
log
} from '../../../core';
import {
Group,
IGroup
} from '../../../core/models';
import { IGame } from '../../../core/games';
import { ICommand } from '../command';
import { needsGame } from '../traits';
interface INewGroupArguments {
timeUntilStart: moment.Duration;
numberOfPlayers: number;
campaign: string;
description: string;
}
const newGroup: ICommand = {
id: 'new-group',
match: /new-(.+)/i,
arguments: [
{
name: 'timeUntilStart',
type: 'duration',
options: {
min: 15,
max: 60 * 24
}
},
{
name: 'numberOfPlayers',
type: 'number',
options: {
min: 2,
max: 16
}
},
{
name: 'campaign',
type: 'string'
},
{
name: 'description',
type: 'string'
}
],
traits: [
needsGame
],
handler: async (request: IBotRequest, params: string[], rawArgs: any) => {
const type = request.data.gameType as string;
const game = request.data.game as IGame;
try {
const args = rawArgs as INewGroupArguments;
const fromNow = Utils.friendlyDuration(args.timeUntilStart);
const groupDef: IGroup = {
groupId: Utils.newId(),
name: args.description,
organizer: request.requestor.name,
organizerId: request.requestor.id,
startTime: moment().add(args.timeUntilStart).toDate(),
gameId: game.id,
numberOfPlayers: args.numberOfPlayers,
attributes: [
{ name: 'campaign', value: args.campaign }
]
};
const group = await Group.create(groupDef);
log.info({
requestor: request.requestor,
type
}, `Group created`);
request.replyDirect(`Created ${type} ${group.fullId()}. It will start in ${fromNow}.`);
}
catch (err) {
log.error(err);
request.replyDirect(`An error ocurred creating your ${type}. Please contact an admin.`);
}
}
};
export = newGroup;
|
98fb7edd6f6e650ae10d1107370a89c94841ab3c
|
TypeScript
|
waqas0ahmad/e-com-api
|
/src/models/response.model.ts
| 2.5625
| 3
|
import { UserTypes } from "./account-request.model";
export class ResponseModel<T>{
Status:number | undefined;
Message:string | undefined;
Data:T | undefined;
}
export class AccountResponseModel{
Id:number | 0;
Username:string;
Password?:string;
DisplayName:string;
FirstName:string;
LastName:string;
Type:UserTypes;
Profile:string;
PhoneNumber:string;
Email:string;
Token?:string;
constructor(){
this.Id = 0;
this.Username = "";
this.Password = "";
this.DisplayName = "";
this.FirstName = "";
this.LastName = "";
this.Type = UserTypes.User;
this.Profile = "";
this.PhoneNumber = "";
this.Email = "";
}
}
|
fd6a629188004e7618b1ddc660af487025977bc4
|
TypeScript
|
Sed2295/typescript
|
/typescript/clases.ts
| 3.296875
| 3
|
( () => {
/*
Forma 1 de crear una clase e inicializar las propiedades
class Avenger {
nombre:string;
equipo:string;
nombreReal:string;
//son opcionales por eso el signo y en el constructor no se inicializa
puedePelear?:boolean;
peleasGanadas?:number;
//constructor funcion que se ejecuta cuando se haga la instancia de la clase o creacion del objeto
constructor(nombre:string,equipo:string,nombreReal:string){
this.nombre = nombre;
this.equipo = equipo;
this.nombreReal = nombreReal;
}
} */
class Avenger {
constructor(
public nombre:string,
public equipo:string,
public nombreReal?:string,
//inicializamos opcional
public puedePelear?:boolean,
//inicializamos por valor por defecto
public peleasGanadas:number = 0){
}
}
const antman = new Avenger('Antman','Capi');
console.log(antman);
})(); //función autoinvocada
|
0449c9fffe07ef9b7b8ae31d7eb9e8460bdfb20c
|
TypeScript
|
ankitkarna99/indianspice-admin
|
/src/core/services/LocalStorageService.ts
| 2.78125
| 3
|
export default abstract class LocalStorageService {
private static ACCESS_TOKEN: string = "INDIAN_SPICE_ACCESS_TOKEN";
static clearTokens() {
localStorage.clear();
}
static setAccessToken(token: string): void {
localStorage.setItem(this.ACCESS_TOKEN, token);
}
static getAccessToken(): string | null {
return localStorage.getItem(this.ACCESS_TOKEN);
}
}
|
4912b0480be3b7aa43700b025438ac8fbc87a61a
|
TypeScript
|
iankuratri/learning-reactjs
|
/12-react-query-zustang-router/src/react-query/hooks/usePostsInfinite.ts
| 2.703125
| 3
|
import { useInfiniteQuery } from "@tanstack/react-query";
import axios from "axios";
interface Post {
id: number;
title: string;
body: string;
userId: number;
}
export interface PostQuery {
pageSize: number;
userId?: number;
}
const usePostsInfinite = (query: PostQuery) => {
const { pageSize, userId } = query;
const fetchPosts = ({ pageParam = 1 }) => {
const params: any = {
_start: (pageParam - 1) * pageSize,
_limit: pageSize,
};
if (userId) params["userId"] = userId;
return axios
.get<Post[]>("https://jsonplaceholder.typicode.com/posts", {
params,
})
.then((res) => res.data);
};
return useInfiniteQuery<Post[], Error>({
queryKey: ["posts", query],
queryFn: fetchPosts,
staleTime: 60 * 1000,
keepPreviousData: true,
getNextPageParam: (lastPage, allPages) => {
// 1 -> 2
return lastPage.length > 0 ? allPages.length + 1 : undefined;
},
});
};
export default usePostsInfinite;
|
1f73fae607448efba290fc2f8c4416b8804686dc
|
TypeScript
|
rickmugridge/mismatched
|
/src/matcher/AllOfMatcher.micro.ts
| 2.9375
| 3
|
import {assertThat} from "../assertThat";
import {match} from "../match";
import {MatchResult} from "../MatchResult";
import {Mismatched} from "./Mismatched";
import {AllOfMatcher} from "./AllOfMatcher";
import {validateThat} from "../validateThat";
import {ContextOfValidationError} from "./DiffMatcher";
describe("AllOfMatcher:", () => {
describe("assertThat():", () => {
it("Matches", () => {
assertThat({a: 2}).isAllOf([]);
assertThat({a: 2}).isAllOf([match.instanceOf(Object)]);
assertThat(new Date()).isAllOf([match.instanceOf(Object), match.instanceOf(Date)]);
});
it("Mismatches", () => {
assertThat(3)
.failsWith(match.allOf([match.instanceOf(Date), 3]),
{[MatchResult.was]: 3, [MatchResult.expected]: {instanceOf: "Date"}});
});
it("Mismatches: errors", () => {
const mismatched: Array<Mismatched> = [];
const matcher = AllOfMatcher.make([match.instanceOf(Date), 3]);
matcher.mismatches(new ContextOfValidationError(), mismatched, 4);
assertThat(mismatched).is([
{actual: 4, expected: {instanceOf: "Date"}},
{actual: 4, expected: 3}
])
});
it("Optimise with 1", () => {
const whatever = match.ofType.array();
assertThat(match.allOf([whatever])).is(match.itIs(whatever))
});
it("Optimise with 1 left after removing match.any()s", () => {
const whatever = match.ofType.array();
assertThat(match.allOf([match.any(), whatever, match.any()])).is(match.itIs(whatever))
});
});
describe("validateThat():", () => {
it("succeeds", () => {
const expected = [match.ofType.number()];
const validation = validateThat(3).satisfies(match.allOf(expected));
assertThat(validation.passed()).is(true);
});
it("fails", () => {
const expected = match.allOf([match.instanceOf(Date), match.ofType.number()]);
const validation = validateThat(3).satisfies(expected);
assertThat(validation.passed()).is(false);
assertThat(validation.errors).is([
`{actual: 3, expected: {instanceOf: "Date"}}`
])
});
});
});
|
de4a84b9b5a0b3a9e007cf08ca3bfeb81e64b0db
|
TypeScript
|
filipemerker/pl-util
|
/src/hobbies.spec.ts
| 3.109375
| 3
|
import { getHobby, getHobbies } from './hobbies';
import HOBBIES from './data/hobby.json';
describe('test hobbies.js', () => {
describe('test getHobby function', () => {
let hobby = '';
beforeEach(() => {
hobby = getHobby();
});
it('should return not empty string', () => {
expect(typeof hobby === 'string').toBeTruthy();
expect(hobby.length).toBeGreaterThan(0);
});
it('should return hobby from hobbies list', () => {
expect(HOBBIES.indexOf(hobby) >= 0).toBeTruthy();
});
it('should options works when are passed', () => {
hobby = getHobby({ startsWith: 'A', includes: 'ł' });
expect(hobby[0] === 'A' && hobby.indexOf('ł') >= 0);
});
});
describe('test getHobbies function', () => {
let hobbies: string[] = [];
beforeEach(() => {
hobbies = getHobbies();
});
it('should return array of strings values', () => {
expect(hobbies.every((hobby) => typeof hobby === 'string')).toBeTruthy();
expect(hobbies.length).toBeGreaterThan(0);
});
it('should return array of random hobbies', () => {
const arr = [...new Array(8)].map(() => getHobbies());
arr.forEach((hobbies, index) => expect(hobbies).not.toEqual(arr[index + 1]));
});
it('should return hobbies from hobbies list', () => {
expect(hobbies.every((hobby) => hobbies.indexOf(hobby) >= 0)).toBeTruthy();
});
it('should options works when are passed', () => {
hobbies = getHobbies({
startsWith: 'A',
includes: 'ł',
length: 1,
sort: 'desc',
unique: true,
});
expect(hobbies.every((hobby) => hobby[0] === 'A' && hobby.indexOf('ł') >= 0)).toBeTruthy(); // startsWith && includes
expect(hobbies.length).toBe(1); // length
expect([...hobbies].sort().reverse()).toEqual(hobbies); // sort
expect([...new Set(hobbies)].length).toBe(1); // unique
});
});
});
|
b61401dbb343b378d1cf6ffb18d8839df148c8ba
|
TypeScript
|
lteam18/nosh
|
/src/main.ts
| 2.65625
| 3
|
import fs from "fs"
(function (){
const argv = process.argv
if (argv.length <= 2) {
console.log("nosh <filepath> [...argument]")
return
}
const filepath = process.argv[2]
const str = fs.readFileSync(filepath).toString()
process.argv.shift()
switch (process.env["ENGINE"]) {
case "js": return require("./run/js").run(str)
case "ts": return require("./run/ts").run(str)
default: return require("./run/auto").run(str)
// TODO: why not? require is blocking, but efficient
// case "js": return (await import("./run/js")).run(str)
// case "ts": return (await import("./run/ts")).run(str)
// default: return (await import("./run/auto")).run(str)
}
})()
|
8c1a2aa2b8f34a4aba04a70d791569c211791077
|
TypeScript
|
alevosia/ownit-home-loans
|
/src/typings/form.d.ts
| 2.796875
| 3
|
interface FormState {
index: number
submitted: boolean
submitting: boolean
sent: boolean
error: any
responses: Responses
}
type QuestionType = 'CHOICES' | 'INPUT'
interface Question {
id: string
inquiry: string
description?: string
type: QuestionType
choices?: Choice[]
inputFields?: InputField[]
value?: string
}
interface Choice {
id: string
value: string
}
interface InputField {
id: string
name: string
type: 'text' | 'email' | 'number' | 'password'
money?: boolean
defaultValue?: string | number
placeholder?: string
min?: number
max?: number
incrementBy?: number
required?: boolean
}
interface Responses {
[key: string]: {
inquiry: string
value: string
}
}
|
f02c488750c81c74ffbb17f8b17561c2a559d1a2
|
TypeScript
|
Gaubee/TheLastShip
|
/web-server/class/pixelCollision.ts
| 2.59375
| 3
|
const canvas = document.createElement("canvas");
const canvas2 = document.createElement("canvas");
// canvas.style.background = "blue";
// canvas2.style.background = "red";
// setTimeout(function () {
// document.body.appendChild(canvas);
// document.body.appendChild(canvas2);
// });
const ctx = canvas.getContext("2d");
function drawImageTo(img: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, img_w: number = 0, img_h: number = 0, is_flip_horizontal: boolean, is_flip_vertical: boolean, can?: HTMLCanvasElement) {
can || (can = canvas);
const c_width = can.width = img_w || img.width;
const c_height = can.height = img_h || img.height;
const ctx = can.getContext("2d");
ctx.clearRect(0, 0, c_width, c_height);
ctx.clearRect(0, 0, c_width, c_height);
if (is_flip_horizontal || is_flip_vertical) {
ctx.translate(c_width, 0);
ctx.scale(is_flip_horizontal ? -1 : 1, is_flip_vertical ? -1 : 1);
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, c_width, c_height);
ctx.translate(c_width, 0);
ctx.scale(is_flip_horizontal ? -1 : 1, is_flip_vertical ? -1 : 1);
} else {
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, c_width, c_height);
}
return ctx
}
export default function pixelCollision(sprite_a: PIXI.Sprite | PIXI.extras.MovieClip, sprite_b: PIXI.Sprite | PIXI.extras.MovieClip) {
var bound_a = sprite_a.getBounds();
var bound_b = sprite_b.getBounds();
var w1 = bound_a.width;
var h1 = bound_a.height;
var x1 = bound_a.x;
var y1 = bound_a.y;
var w2 = bound_b.width;
var h2 = bound_b.height;
var x2 = bound_b.x;
var y2 = bound_b.y;
if (isCollisionWithRect(x1, y1, w1, h1, x2, y2, w2, h2)) {
var img_a = sprite_a.texture.source || sprite_a.texture.baseTexture.source;
var img_b = sprite_b.texture.source || sprite_b.texture.baseTexture.source;
// 重叠的矩形区域
var x, y, w, h;
x = Math.max(x1, x2);
y = Math.max(y1, y2);
// w = Math.min(x1 + w1, w2 + h2) - x;
w = Math.min(x1 + w1, x2 + w2) - x;
h = Math.min(y1 + h1, y2 + h2) - y;
var scale_a = sprite_a.scale
var scale_b = sprite_b.scale
var ctx_a = drawImageTo(img_a, w1, h1, scale_a.x < 0, scale_a.y < 0);
var ctx_b = drawImageTo(img_b, w2, h2, scale_b.x < 0, scale_b.y < 0, canvas2);
var rgba_a = ctx_a.getImageData(x - x1, y - y1, w, h).data;
var rgba_b = ctx_b.getImageData(x - x2, y - y2, w, h).data;
var total = w * h * 4;
for (var p = 0; p < total; p += 4) {
if (rgba_a[p + 3] != 0 && rgba_b[p + 3] != 0) {
return true;
}
}
}
return false
}
export function isCollisionWithRect(x1: number, y1: number, w1: number, h1: number,
x2: number, y2: number, w2: number, h2: number) {
if (x1 >= x2 && x1 >= x2 + w2) {
return false;
} else if (x1 <= x2 && x1 + w1 <= x2) {
return false;
} else if (y1 >= y2 && y1 >= y2 + h2) {
return false;
} else if (y1 <= y2 && y1 + h1 <= y2) {
return false;
}
return true;
}
|
eba2d7edead74e6f67c383c55b04e4589cc1a8b8
|
TypeScript
|
mateus-pinheiro/peddi-projects
|
/src/api-core/commons/dto/order.dto.ts
| 2.9375
| 3
|
// const { BaseDTO, fields } = require('dtox')
// Define order mapping
// const ORDER_MAPPING = {
// table: Number(),
// guests: Number(),
// amount_price: Number(),
// status: Number(),
// restaurant_id_cloud: Number(),
// // waiter: fields.WaiterDTO()
// };
// const WAITER_MAPPING = {
// cloud_id: fields.number(),
// mgmt_id: fields.string(),
// name: fields.string()
// };
// // Define a DTO which represents a single order
// export default class OrderDTO extends BaseDTO {
// constructor(data: any) {
// super(data, ORDER_MAPPING);
// }
// }
// class WaiterDTO extends BaseDTO {
// constructor(data: any) {
// super(data, WAITER_MAPPING);
// }
// }
export default class OrderDTO {
public table: Number;
public guests: Number;
public amount_price: Number;
public status: Number;
public restaurant_id_cloud: Number;
public waiter_id_cloud: Number;
public consumers: ConsumerDTO;
// waiter: fields.WaiterDTO()
constructor(incoming: OrderDTO) {
this.table = incoming.table;
this.guests = incoming.guests;
this.amount_price = incoming.amount_price;
this.status = incoming.status;
this.restaurant_id_cloud = incoming.restaurant_id_cloud;
this.waiter_id_cloud = incoming.waiter_id_cloud;
this.consumers = incoming.consumers;
}
}
export class ConsumerDTO {
public cloud_id: Number;
public items: Array<ItemDTO>;
// waiter: fields.WaiterDTO()
constructor(incoming: ConsumerDTO) {
this.cloud_id = incoming.cloud_id;
this.items = incoming.items;
}
}
export class ItemDTO {
public cloud_id: Number;
public ingredients: Array<IngredientDTO>;
// waiter: fields.WaiterDTO()
constructor(incoming: ItemDTO) {
this.cloud_id = incoming.cloud_id;
this.ingredients = incoming.ingredients;
}
}
export class IngredientDTO {
public cloud_id: Array<Number>;
// waiter: fields.WaiterDTO()
constructor(incoming: IngredientDTO) {
this.cloud_id = incoming.cloud_id;
}
}
//Contract
// {
// "table":3,
// "guests":2,
// "amount_price":66.30,
// "status":1,
// "restaurant_id_cloud":1,
// "waiter_id_cloud":1,
// "created_at":"12/02/2018 12:50",
// "updated_at":"12/02/2018 12:51",
// "consumers":[
// {
// "cloud_id":508,
// "items":[
// {
// "cloud_id":33,
// "ingredients":null
// },
// {
// "cloud_id":101,
// "ingredients":null
// }
// ]
// },
// {
// "cloud_id":603,
// "items":[
// {
// "cloud_id":10,
// "ingredients":[
// 1
// ]
// },
// {
// "cloud_id":71,
// "ingredients":[
// 5,
// 14
// ]
// }
// ]
// }
// ]
// }
|
a55985c56dd3e07867e29d460b46702f414458de
|
TypeScript
|
ScriptCamilo/learning-typescript
|
/src/typeAnnotation/aula16.ts
| 3.34375
| 3
|
// STRUCTURAL TYPE SYSTEM
type User = { username: string; password: string };
type VerifyUserFn = (user: User, sentUser: User) => boolean;
const verifyUser: VerifyUserFn = (user, sentUser) => {
return (
user.username === sentUser.username && user.password === sentUser.password
);
};
const dbUser = { username: 'Script', password: '123456' };
const sentUser = { username: 'Script', password: '123456' };
const loggedIn = verifyUser(dbUser, sentUser);
console.log(loggedIn); // true OR false
|
6bd0c99d153e750b337468f169ad336e845f5411
|
TypeScript
|
Eirenliel/node-steamapits
|
/src/utils/fetch.ts
| 2.578125
| 3
|
import { createDeflate, createGunzip } from 'zlib';
import { parse } from 'url';
import https from 'https';
import http from 'http';
const reg = /<h1>(.*)<\/h1>/;
export default (url: string, headers: {} = {}) : Promise<any> => {
const fetch = url.startsWith('https') ? https.get : http.get;
const options = Object.assign(
parse(url),
{ headers: Object.assign({ 'Accept-Encoding': 'gzip, deflate' }, headers) }
);
return new Promise((resolve, reject) => {
fetch(options, res => {
const ce = res.headers['content-encoding'];
let data = '';
let op: any = res;
if (ce === 'deflate') res.pipe(op = createDeflate());
if (ce === 'gzip') res.pipe(op = createGunzip());
op.on('data', chunk => data += chunk);
op.once('error', reject);
op.once('end', () => {
if (res.statusCode === 400) return reject(new Error(reg.test(data) ? data.match(reg)[1] : data));
if (res.statusCode !== 200) return reject(new Error(res.statusMessage));
try {
resolve(JSON.parse(data));
} catch (_) {
reject(new Error(data));
}
});
});
});
};
|
22ddf0b2e3a25ca86c5bcd88fd8caee1fc44f965
|
TypeScript
|
bigcommerce-labs/hello-world-bc
|
/app/import/fn/extract/extract-csv-handler.ts
| 2.765625
| 3
|
'use strict';
const csv = require('csvtojson');
const _ = require('lodash');
import { Handler, Context, Callback } from 'aws-lambda';
import { CsvDataRow } from '../../../types/csvs'
interface ExtractCsvRowJson {
}
interface ExtractCsvResponse {
statusCode: number,
rowCount: number,
rows: any[]
}
// TODO: make this a handler that calls extractCsv, which is testable independently
const extractCsvHandler: Handler = (event: any, context: Context, callback: Callback) => {
console.log(event);
var header: string[] = [];
var rows: CsvDataRow[] = [];
var kind: string = event.queryStringParameters.kind;
var rowCounter: number = 0;
csv({
noheader: false,
output: "csv"
})
.on('header', h => {
header = h;
})
.fromString(event.body)
.then((csvRows) => {
_(csvRows).forEach(element => {
rowCounter += 1;
rows.push(
<CsvDataRow>{
rowId: rowCounter,
columns: element
});
})
// TODO: error handling
})
.then(
v => callback(undefined, {
statusCode: 200,
body: JSON.stringify({
"kind": kind,
"header": header,
"rows": rows
})
}),
callback
);
};
export { extractCsvHandler }
|
e7d1850410052ddb5c8ce2585d3e80c1d0fa7b89
|
TypeScript
|
coolchem/raappid
|
/test/unit/service_system/manager/cli-manager.spec.ts
| 2.5625
| 3
|
/**
* Created by varunreddy on 12/17/15.
*/
import cm = require("../../../../src/lib/service_system/managers/cli-manager");
import chai = require('chai');
describe('cli-manager Test cases', () => {
var expect = chai.expect;
describe("processArguments",()=>{
it("should throw error if less than 2 commands are passed",()=>{
var throws:Function = function(){
cm.processArguments({_:[]});
};
expect(throws).to.throw(cm.ERROR_ARGUMENTS_MISMATCH);
});
it("should reject with error if more than 2 commands are passed",()=>{
var throws:Function = function(){
cm.processArguments({_:["asdad","asdsad","adadad"]})
};
expect(throws).to.throw(cm.ERROR_INVALID_PROJECT_NAME);
});
it("should return null if user requests help",()=>{
expect(cm.processArguments({help:true,_:["asdad","asdsad","adadad"]})).to.be.null;
expect(cm.processArguments({h:true,_:["asdad","asdsad","adadad"]})).to.be.null;
});
it("should return null if user requests version",()=>{
expect(cm.processArguments({v:true,_:["asdad","asdsad","adadad"]})).to.be.null;
expect(cm.processArguments({version:true,_:["asdad","asdsad","adadad"]})).to.be.null;
});
it("should resolve object containing projectName, projectType and templateName",()=>{
var result = cm.processArguments({_:["asdad","asdsad"],using:"sdfsfsf"});
expect(result.projectName).to.equal("asdsad");
expect(result.mainCommand).to.equal("asdad");
expect(result.templateName).to.equal("sdfsfsf");
var result1 = cm.processArguments({_:["asdad","asdsad"],u:"sdfsfsf"});
expect(result.projectName).to.equal("asdsad");
expect(result.mainCommand).to.equal("asdad");
expect(result.templateName).to.equal("sdfsfsf");
});
it("should resolve object containing projectName, projectType and empty template name",()=>{
var result = cm.processArguments({_:["asdad","asdsad"]});
expect(result.projectName).to.equal("asdsad");
expect(result.mainCommand).to.equal("asdad");
expect(result.templateName).to.equal("");
});
})
});
|
c1a7f31830563d66d97221e9e2a1611b38744c5f
|
TypeScript
|
mm7456/MoveableBox
|
/src/app/app.component.ts
| 2.640625
| 3
|
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'BoxDemo';
public widgetIds: Array<number> = [];
public id = 1;
widgetElement = null;
selectedWidgetId: number = null;
isToggleChecked = true;
addWidget() {
this.widgetIds.push(this.id++);
}
toggleControl(event) {
console.log("In toggle control", event.target.checked);
this.isToggleChecked = event.target.checked;
}
onClickWidget(id) {
this.selectedWidgetId = id;
this.widgetElement = document.getElementById(id);
console.log("Widget Clicked", this.widgetElement.offsetLeft);
if (this.widgetElement.style.left == "" && this.widgetElement.style.top == "") {
this.widgetElement.style.left = '10px';
this.widgetElement.style.top = '30px';
}
}
@HostListener('document:keydown', ['$event'])
getKeyAndMove(e: KeyboardEvent) {
if (this.isToggleChecked) {
console.log("Move", e.which);
var key_code = e.which || e.keyCode;
switch (key_code) {
case 37:
case 65: //left arrow key
this.moveLeft();
break;
case 38:
case 87: //Up arrow key
this.moveUp();
break;
case 39:
case 68: //right arrow key
this.moveRight();
break;
case 40:
case 83: //down arrow key
this.moveDown();
break;
case 46:
this.deleteWidget();
break;
}
}
}
moveLeft() {
if (this.widgetElement.offsetLeft > 10)
this.widgetElement.style.left = parseInt(this.widgetElement.style.left) - 5 + 'px';
}
moveUp() {
if (this.widgetElement.offsetTop > 30)
this.widgetElement.style.top = parseInt(this.widgetElement.style.top) - 5 + 'px';
}
moveRight() {
if (this.widgetElement.offsetLeft < 405)
this.widgetElement.style.left = parseInt(this.widgetElement.style.left) + 5 + 'px';
}
moveDown() {
if (this.widgetElement.offsetTop < 430)
this.widgetElement.style.top = parseInt(this.widgetElement.style.top) + 5 + 'px';
}
deleteWidget() {
const index = this.widgetIds.indexOf(this.selectedWidgetId, 0);
if (index > -1) {
this.widgetIds.splice(index, 1); //remove selected element from array
}
}
}
|
db4157ec81743a9a658085922700d17bb0f5f817
|
TypeScript
|
luciotato/create-near-app
|
/templates/angular/src/app/app.component.ts
| 2.546875
| 3
|
import { Component, Inject, OnInit } from '@angular/core'
import { login, logout } from '../utils'
import { WINDOW } from './services/window.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
greeting: string
newGreeting: string
showNotification = false
get accountId(): string {
return this.window.walletConnection.getAccountId()
}
get signedIn(): boolean {
return this.window.walletConnection.isSignedIn()
}
get contractId(): string {
return this.window.contract.contractId
}
get buttonDisabled(): boolean {
const newGreeting = this.newGreeting?.trim()
return !newGreeting || newGreeting === this.greeting
}
constructor(@Inject(WINDOW) private window: Window) {}
ngOnInit(): void {
this.fetchGreeting()
}
login(): void {
login()
}
logout(): void {
logout()
}
async fetchGreeting(): Promise<void> {
if (this.signedIn) {
this.greeting = this.newGreeting = await this.window.contract.getGreeting({ accountId: this.accountId })
}
}
async onSubmit(event): Promise<void> {
event.preventDefault()
// get elements from the form using their id attribute
const { fieldset, greeting } = event.target.elements
// disable the form while the value gets updated on-chain
fieldset.disabled = true
try {
// make an update call to the smart contract
await this.window.contract.setGreeting({ message: greeting.value })
} catch (e) {
alert(
'Something went wrong! ' +
'Maybe you need to sign out and back in? ' +
'Check your browser console for more info.'
)
throw e
} finally {
// re-enable the form, whether the call succeeded or failed
fieldset.disabled = false
}
// update local `greeting` variable to match persisted value
this.greeting = this.newGreeting
// show notification
this.showNotification = true
// remove notification again after css animation completes
// this allows it to be shown again next time the form is submitted
setTimeout(() => {
this.showNotification = false
}, 11000)
}
}
|
75d70e49e7ba95a05f3474115344b88e1ecf746d
|
TypeScript
|
wangtengda0310/liuyao
|
/kanliuyao/build/libs/laya/net/URL.d.ts
| 3.03125
| 3
|
/**
* <p><code>URL</code> 提供URL格式化,URL版本管理的类。</p>
* <p>引擎加载资源的时候,会自动调用formatURL函数格式化URL路径</p>
* <p>通过basePath属性可以设置网络基础路径</p>
* <p>通过设置customFormat函数,可以自定义URL格式化的方式</p>
* <p>除了默认的通过增加后缀的格式化外,通过VersionManager类,可以开启IDE提供的,基于目录的管理方式来替代 "?v=" 的管理方式</p>
* @see laya.net.VersionManager
*/
export declare class URL {
/**URL地址版本映射表,比如{"aaa/bb.png":99,"aaa/bb.png":12},默认情况下,通过formatURL格式化后,会自动生成为"aaa/bb.png?v=99"的一个地址*/
static version: any;
/**@private */
private _url;
/**@private */
private _path;
/**兼容微信不支持加载scene后缀场景,设置为true,则会把scene加载替换为json*/
static exportSceneToJson: boolean;
/**创建一个新的 <code>URL</code> 实例。*/
constructor(url: string);
/**格式化后的地址。*/
readonly url: string;
/**地址的文件夹路径(不包括文件名)。*/
readonly path: string;
/**@internal 基础路径。如果不设置,默认为当前网页的路径。最终地址将被格式化为 basePath+相对URL地址,*/
static _basePath: string;
/**root路径。只针对'~'类型的url路径有效*/
static rootPath: string;
/**基础路径。如果不设置,默认为当前网页的路径。最终地址将被格式化为 basePath+相对URL地址,*/
static basePath: string;
/** 自定义URL格式化的方式。例如: customFormat = function(url:String):String{} */
static customFormat: Function;
/**
* 格式化指定的地址并返回。
* @param url 地址。
* @param base 基础路径,如果没有,则使用basePath。
* @return 格式化处理后的地址。
*/
static formatURL(url: string): string;
/**
* @internal
* 格式化相对路径。
*/
static _formatRelativePath(value: string): string;
/**
* 获取指定 URL 的文件夹路径(不包括文件名)。
* <p><b>注意:</b>末尾有斜杠(/)。</p>
* @param url url地址。
* @return 返回文件夹路径。
*/
static getPath(url: string): string;
/**
* 获取指定 URL 的文件名。
* @param url 地址。
* @return 返回文件名。
*/
static getFileName(url: string): string;
/**
* @private
*/
private static _adpteTypeList;
/**
* @private 兼容微信
*/
static getAdptedFilePath(url: string): string;
}
|
c9236401b8150afe436dad169a37fab2d0b3e3a6
|
TypeScript
|
Lorddoyo/quotes
|
/src/app/quote.ts
| 2.5625
| 3
|
export class Quote {
public showDescription:boolean
constructor(public id:number, public name:string, public description:string){
this.showDescription=false
}
}
|
71062031ced4ffad6f2b6934cc5951d977600798
|
TypeScript
|
NikhilMishra123/Angular_Js
|
/hello-world/src/app/signup-form/custom-validator.ts
| 2.90625
| 3
|
import {AbstractControl, ValidationErrors , } from '@angular/forms'
export class UsernameValidator{
static cannotContainSpace(control : AbstractControl) : ValidationErrors|null{
if( (control.value as string).indexOf(' ')>=0)
return {
cannotContainSpace :'Has space in it' };
}
static shouldBeUnique(control : AbstractControl) : Promise<ValidationErrors | null>
{
return new Promise( ( resolve , reject ) => {
setTimeout( ( )=>
{
if (control.value =='Nikhil')
resolve({ shouldBeUnique : ' Name already taken ' });
else
resolve(null);
}
,2000 );
});
}
}
|
18cfba57a753313132791a7c4ed578f0a8ea176f
|
TypeScript
|
Sanagiig/vue0.2
|
/src/utils/assert/index.ts
| 2.6875
| 3
|
import { makeMap } from "../convert/index";
/**
* Get the raw type string of a value, e.g., [object Object].
*/
const _toString = Object.prototype.toString
// Browser environment sniffing
export const inBrowser = typeof window !== 'undefined'
export const UA = inBrowser && window.navigator.userAgent.toLowerCase()
export const inWeex = false // typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform
export const isIE = UA && /msie|trident/.test(UA)
export const isIE9 = UA && UA.indexOf('msie 9.0') > 0
export const isEdge = UA && UA.indexOf('edge/') > 0
export const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge
export const isIOS = false //(UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios')
export let supportsPassive = false
export function isNative(Ctor: any): boolean {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
export function isRegExp(v: any): boolean {
return _toString.call(v) === '[object RegExp]'
}
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
export function isUndef(v: any): boolean {
return v === undefined || v === null
}
export function isDef(v: any): boolean {
return v !== undefined && v !== null
}
export function isTrue(v: any): boolean {
return v === true
}
export function isFalse(v: any): boolean {
return v === false
}
/**
* Check if value is primitive.
*/
export function isPrimitive(value: any): boolean {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
export function isPlainObject(obj: any): boolean {
return _toString.call(obj) === '[object Object]'
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
export function isObject(obj: any): boolean {
return obj !== null && typeof obj === 'object'
}
export function isPromise(val: any): boolean {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
/**
* Check if val is a valid array index.
*/
export function isValidArrayIndex(val: any): boolean {
const n = parseFloat(String(val))
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
/**
* Check whether an object has the property.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty
export function hasOwn(obj: any, key: string): boolean {
return hasOwnProperty.call(obj, key)
}
/**
* Check if a tag is a built-in tag.
*/
export const isBuiltInTag = makeMap('slot,component', true)
export const isPreTag = (tag: string): boolean => tag === 'pre';
export const isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
)
export const isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr'
)
// Elements that you can, intentionally, leave open
// (and which close themselves)
export const canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'
)
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
export const isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track'
)
export const isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template,blockquote,iframe,tfoot'
)
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
export const isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
)
export const isXlink = (name: string): boolean => {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
}
export const isFalsyAttrValue = (val: any): boolean => {
return val == null || val === false
}
/**
* Check if a string starts with $ or _
*/
export function isReserved(str: string): boolean {
const c = (str + '').charCodeAt(0)
return c === 0x24 || c === 0x5F
}
export const isReservedTag = (tag: string): boolean | void => {
return isHTMLTag(tag) || isSVG(tag)
}
// these are reserved for web because they are directly compiled away
// during template compilation
export const isReservedAttr = makeMap('style,class');
// for script (e.g. type="x/template") or style, do not decode content
export function isTextTag(el: any): boolean {
return el.tag === 'script' || el.tag === 'style'
}
// 非文本tag && type !== text/javascript
export function isForbiddenTag(el: any): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
/**
* Check if an attribute is a reserved attribute.
*/
export const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
// svg && math
export function getTagNamespace(tag: string): string | void {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
const unknownElementCache = Object.create(null)
/**
* 通过保留 tag 以及 该tagName 创建的element 判断是否未知 tag
*/
export function isUnknownElement(tag: string): boolean {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase()
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
const el = document.createElement(tag)
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
export const isTextInputType = makeMap('text,number,password,search,email,tel,url')
export const hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys)
// detect devtools
export const devtools = inBrowser && (<any>window).__VUE_DEVTOOLS_GLOBAL_HOOK__;
// Firefox has a "watch" function on Object.prototype...
export const nativeWatch = (<any>{}).watch
export const emptyObject = Object.freeze({});
// can we use __proto__?
export const hasProto = '__proto__' in {};
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
let _isServer: any
export const isServerRendering = () => {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && !inWeex && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'] && global['process'].env.VUE_ENV === 'server'
} else {
_isServer = false
}
}
return _isServer
}
export interface SimpleSet {
has(key: string | number): boolean;
add(key: string | number): any;
clear(): void;
}
export const isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck')
// check whether current browser encodes a char inside attribute values
let div:Element
function getShouldDecode (href: boolean): boolean {
div = div || document.createElement('div')
div.innerHTML = href ? `<a href="\n"/>` : `<div a="\n"/>`
return div.innerHTML.indexOf(' ') > 0
}
// #3663: IE encodes newlines inside attribute values while other browsers don't
export const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false
// #6828: chrome encodes content in a[href]
export const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false
// attributes that should be using props for binding
const acceptValue = makeMap('input,textarea,option,select,progress')
export const mustUseProp = (tag: string, type: string, attr: string): boolean => {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
}
|
0e1f30ef849109309e127e43637f7b629f3125e3
|
TypeScript
|
gustavowarmling/mestres-da-web
|
/src/services/ProductServices/CreateProductService.ts
| 2.71875
| 3
|
import { getRepository } from 'typeorm'
import Product from '../../models/Product';
interface Request {
name: string,
description: string,
size: number,
price: number,
sku: string;
}
class CreateProductService {
public async execute({ name, description, size, price, sku }: Request): Promise<Product> {
const productsRepository = getRepository(Product);
const product = productsRepository.create({
name,
description,
size,
price,
sku,
});
await productsRepository.save(product);
return product;
};
};
export default CreateProductService;
|
1facedb50f2d4dfc773afc010b9a0c121dd8a2ba
|
TypeScript
|
vikuviku6666/lan-tech_front-dev
|
/src/utils/sortProduct.ts
| 3.328125
| 3
|
import { Dict } from '../types';
/**
* for a given order key/value object, generates a callback function
* @param order
* @returns (item: Dict) => number
*/
const sortProduct =
(order: Dict) =>
(a: Dict, b: Dict): number => {
// todo: implement sort by `price` and `quantity`
// todo: make sort by `name` a case-insensitive
if (!a.hasOwnProperty(order.key) || !b.hasOwnProperty(order.key)) {
return 0;
}
const varA = typeof a[order.key] === 'string' ? a[order.key].toUpperCase() : a[order.key];
const varB = typeof a[order.key] === 'string' ? b[order.key].toUpperCase() : b[order.key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return order.val === 'desc' ? comparison * -1 : comparison;
};
export default sortProduct;
|
ed783813ed7377c68cae474b9f2a441434f5edd0
|
TypeScript
|
inkorcoder/aow
|
/src/render/render.ts
| 2.6875
| 3
|
import { Map } from "./map";
import { Grid } from "./../core/grid";
import { Vector } from "./../math/vector";
import { Texturer } from './../core/texturer';
export class Render {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
width: number;
height: number;
isRunning: boolean;
onRenderCallbacks: Function[];
constructor(canvasSelector?: string){
if (canvasSelector){
this.canvas = document.querySelector(canvasSelector);
} else{
this.canvas = document.querySelector('canvas');
}
this.ctx = this.canvas.getContext("2d");
this.setRects();
this.isRunning = false;
this.onRenderCallbacks = [];
window.addEventListener('resize', (e)=> {
// this.setRects(this.width, this.height);
// this.renderSingleFrame();
});
}
setRects(width?: number, height?: number){
this.canvas.width = width || this.width;
this.canvas.height = height || this.height;
}
clear(){
this.ctx.clearRect(0, 0, this.width, this.height);
}
start(){
this.isRunning = true;
this.render();
}
stop(){
this.isRunning = false;
}
onRender(callback: Function){
if (callback){
this.onRenderCallbacks.push(callback);
} else {
console.warn("Renderer :: no onRender cllback passed!");
}
}
render(){
for (let c = 0; c < this.onRenderCallbacks.length; c++){
if (this.onRenderCallbacks[c]){
this.onRenderCallbacks[c]();
}
}
if (this.isRunning){
requestAnimationFrame(this.render.bind(this));
}
}
renderSingleFrame(){
this.start();
this.stop();
}
renderColoredMap(map: Map){
if (map){
for (let x = 0; x < map.size.x; x++){
for (let y = 0; y < map.size.y; y++){
let key: string = map.colorsArray[map.data[y][x]];
this.ctx.fillStyle = map.colors[key];
this.ctx.fillRect(x*map.cellSize.x, y*map.cellSize.y, map.cellSize.x, map.cellSize.y);
}
}
}
}
renderTexturedMap(map: Map){
if (map){
let mountainsIndexes: any[] = [];
for (let x = 0; x < map.size.x; x++){
for (let y = 0; y < map.size.y; y++){
// console.log(map.data[y][x]);
let tile: any = Texturer.data.ground[map.textures[y][x]];
this.ctx.putImageData(tile, x*map.cellSize.x, y*map.cellSize.y);
// mountain
if (map.data[y][x] === 5){
mountainsIndexes.push({
x: x, y: y
});
// console.log(x, y)
}
}
}
console.log(mountainsIndexes.length)
for (let i = 0; i < mountainsIndexes.length; i++){
let tile: any = Texturer.getRandomMountainSamle();
let x: any = mountainsIndexes[i].x;
let y: any = mountainsIndexes[i].y;
let img = new Image();
img.src = tile;
this.ctx.drawImage(img, x*map.cellSize.x-map.cellSize.x/2, y*map.cellSize.y-map.cellSize.y);
}
return {
subscribe: function(callback?: Function){
if (callback) {
callback();
}
}
}
}
}
renderColoredMapSegment(map: Map, segment: Vector, color: string){
map.data[segment.y][segment.x] = map.colorsKeys[color];
let key: string = map.colorsArray[map.data[segment.y][segment.x]];
this.ctx.fillStyle = map.colors[key];
this.ctx.fillRect(segment.x*map.cellSize.x, segment.y*map.cellSize.y, map.cellSize.x, map.cellSize.y);
}
renderTexturedMapSegment(map: Map, segment: Vector, type: string, directIndex?: number){
let textures = Texturer.data.ground,
indexes = Texturer.groundIndexes,
tile: any,
tileIndex: number;
if (typeof directIndex === "number"){
tile = Texturer.data.ground[directIndex];
tileIndex = directIndex;
} else {
let t = Texturer.getRandomGroundTile(map.colorsKeys[type]);
tile = t.tile;
tileIndex = t.index;
}
if (tile){
this.ctx.putImageData(tile, segment.x*map.cellSize.x, segment.y*map.cellSize.y);
map.textures[segment.y][segment.x] = tileIndex;
} else {
console.log('Render texture: tile is null');
}
return {
subscribe: function(callback?: Function){
if (callback) {
callback(tile, segment, type);
}
}
}
}
renderGrid(map: Grid){
if (map){
this.ctx.fillStyle = "#ddd";
for (let x = 0; x < map.gridSizeX; x++){
for (let y = 0; y < map.gridSizeY; y++){
if (map.walkable[y][x] === 0){
this.ctx.fillStyle = "#555";
} else {
this.ctx.fillStyle = "#ddd";
}
this.ctx.fillRect(x*map.nodeDiameter+1, y*map.nodeRadius+1, map.nodeDiameter-2, map.nodeRadius-2);
}
}
}
}
getSnapshot(scale: number = 1){
let tempCanvas = document.createElement('canvas'),
tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = this.canvas.width * scale;
tempCanvas.height = this.canvas.height * scale;
let data = this.canvas.toDataURL();
let image = new Image();
let callback;
image.src = data;
return {
subscribe: function(callback?: Function){
image.onload = ()=> {
tempCtx.drawImage(image, 0, 0, tempCanvas.width, tempCanvas.height);
if (callback){
callback(tempCanvas.toDataURL());
}
};
}
}
}
}
|
503611b1b74ff62070395efe67fcd78fa41404f7
|
TypeScript
|
U1F30C/liberet-challenge
|
/web/models/service.ts
| 2.59375
| 3
|
export enum ServiceType {
Immediate = "Immediate",
Enableable = "Enableable",
}
export interface Service {
activeServices: { userId: string; serviceId: string }[];
id: string;
name: string;
cost: string;
serviceType: ServiceType;
}
|
dcae4589a8047e39fd0168e10d23ee8652d34422
|
TypeScript
|
ajiekc905/bipWatchFaceEditor
|
/src/Images.ts
| 2.875
| 3
|
import {Reader} from './DataReader';
import {Logging} from './Logging';
export default class RawImage {
// palette: Uint32Array;
public width: number;
public height: number;
public usdedPaletteColors: number;
public name: string;
// private section for stupid linter
private palette: ImageData[]; // colored pixels imagedata
private pos: number;
private rowLengthInBytes: number;
private bitsPerPixel: number;
private hasTransparency: number;
private urlEncodedImage: string;
private rawData: Uint8Array;
constructor(array: Uint8Array, name: string = '000') {
const readWord = new Reader(array, 0, 16);
const magic: string = readWord.stringNt();
if (magic !== 'BMd') {
throw new Error('this is not image!!!');
}
this.name = 'i' + ('000' + name).slice(-3);
readWord.move(4);
this.width = readWord.next(); // 176
this.height = readWord.next(); // 176
this.rowLengthInBytes = readWord.next();
this.bitsPerPixel = readWord.next(); // 04
this.usdedPaletteColors = readWord.next(); // 07
this.hasTransparency = readWord.next();
this.infoToLog();
const rawImageStart = this.paletteReader(array);
const rawByteSize = this.rowLengthInBytes * this.height;
// console.log(`image starts at ${rawImageStart.toString(16)} and size is ${rawByteSize.toString(16)}`)
this.rawData = array.slice(rawImageStart);
this.readImage(this.rawData, 0, rawByteSize);
this.putCanvasToImg();
}
public encode() {
// the output would be Uint8Array ready to merge into binary blob
// steps: write header
// write palette from ours .palette
// just dump image data from .rawData
const header: Uint8Array = new Uint8Array(0x1f);
}
public logger(message: string) {
const log = new Logging();
log.add(message);
console.log(message);
}
public toHex(data32bit) {
const d0 = (data32bit & 0xff).toString(16);
const d1 = ((data32bit >> 8) & 0xff).toString(16);
const d2 = ((data32bit >> 16) & 0xff).toString(16);
const d3 = ((data32bit >> 24) & 0xff).toString(16);
const padder = (datahex: string): string => {
return ('00' + datahex).slice(-2);
};
const text = `${padder(d0)} ${padder(d1)} ${padder(d2)} ${padder(d3)}`;
return text;
}
public infoToLog() {
console.log(
`${this.name}: ${this.width} x ${this.height}, ${
this.bitsPerPixel
}bpp, palette size: ${this.usdedPaletteColors}, t:${
this.hasTransparency
}`,
// , bytes per line: ${
// this.rowLengthInBytes
// }, calculated width:${this.rowLengthInBytes * 8 / this.bitsPerPixel}
);
}
public paletteToImage() {
const height = 32;
const canvas = document.createElement('canvas');
canvas.width = height * this.palette.length;
canvas.height = height;
const context = canvas.getContext('2d');
function drawSquare(color: number, id: number) {
const _canvas = document.createElement('canvas');
_canvas.height = height;
}
const colorValues = this.palette.map(element => {
return new Uint32Array(element.data.buffer);
});
colorValues.forEach(drawSquare);
// const colors = this.palette.length;
// for (let idx = 0; idx < colors; idx++) {
// const imgData = this.palette[idx];
// for (let y = 0; y < height; y++) {
// for (let x = 0; x < height; x++) {
// const posX = (idx << 5) + x;
// context.putImageData(imgData, x, y);
// }
// }
// }
const imgsrc = canvas.toDataURL();
return imgsrc;
}
public putCanvasToImg(imgSrc: string = '') {
const preview = document.getElementsByClassName('preview')[0];
// let canvas = document.getElementById("myCanvas");
// let image = canvas.toDataURL();
const img = document.createElement('img');
img.src = '' === imgSrc ? this.urlEncodedImage : imgSrc;
// img.width = this.width;
// img.height = this.height;
img.id = this.name;
img.title = this.name;
preview.appendChild(img);
}
private readImage(array: Uint8Array, start: number, size: number) {
// let canvas: HTMLCanvasElement = document.createElement("canvas");
// canvas.width = this.rowLengthInBytes * 8 / this.bitsPerPixel
const canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
const context = canvas.getContext('2d');
const imgData = context.getImageData(0, 0, canvas.width, canvas.height);
const readBits = new Reader(array, start, this.bitsPerPixel);
const xBaseShift: number = 8 / this.bitsPerPixel;
// the original picture has width / bitsPerPixel
// image to view has no such restrictions
for (let y: number = 0; y < this.height; y++) {
///// bp = byte pos in raw image data line.
for (let bp: number = 0; bp < this.rowLengthInBytes; bp++) {
const bitData: number[] = readBits.next();
let nibbleShift: number = 0;
const bp_X_xBaseShift: number = bp * xBaseShift;
if (bitData) {
bitData.forEach(
paletteIndex => {
// console.log(paletteIndex);
const x = bp_X_xBaseShift + nibbleShift;
// we expect in palette 1pixel imagedata
const pixelImgData = this.palette[paletteIndex];
// // console.log(pixelImgData)
if (pixelImgData) {
context.putImageData(pixelImgData, x, y);
}
nibbleShift++;
}, // foreach {}
); // foreach
}
} // for bp
} // for y
this.urlEncodedImage = canvas.toDataURL();
// png.
}
private colorTo1pixImgdata(color: number): ImageData {
const onePixCanvas = document.createElement('canvas');
onePixCanvas.width = 1;
onePixCanvas.height = 1;
const onePixContext = onePixCanvas.getContext('2d');
const onePixData = onePixContext.getImageData(0, 0, 1, 1);
const onePix32b = new Uint32Array(onePixData.data.buffer);
onePix32b[0] = color;
return onePixData;
}
private paletteReader(rawImgData: Uint8Array) {
const rawPaletteStart = 0x10;
const colors = new Reader(rawImgData, rawPaletteStart, 8);
this.palette = [];
let color: number = 0;
for (let index = 0; index < this.usdedPaletteColors; index++) {
const red = colors.next();
const green = colors.next();
const blue = colors.next();
const spacer = colors.next();
if (index === 0 && this.hasTransparency) {
color = 0; // transparent
} else {
color = red | (green << 8) | (blue << 16) | 0xff000000;
this.palette[index] = this.colorTo1pixImgdata(color);
this.logger(`palette:${index.toString(16)} : ${this.toHex(color)}`);
}
}
return rawPaletteStart + (this.usdedPaletteColors << 2);
}
}
|
ad772834b05a2fb4af4032e90765d68bce049895
|
TypeScript
|
asvny/formatjs
|
/packages/ecma402-abstract/NumberFormat/ToRawPrecision.ts
| 3.203125
| 3
|
import {RawNumberFormatResult} from '../types/number';
import {repeat, getMagnitude} from '../utils';
export function ToRawPrecision(
x: number,
minPrecision: number,
maxPrecision: number
): RawNumberFormatResult {
const p = maxPrecision;
let m: string;
let e: number;
let xFinal: number;
if (x === 0) {
m = repeat('0', p);
e = 0;
xFinal = 0;
} else {
const xToString = x.toString();
// If xToString is formatted as scientific notation, the number is either very small or very
// large. If the precision of the formatted string is lower that requested max precision, we
// should still infer them from the formatted string, otherwise the formatted result might have
// precision loss (e.g. 1e41 will not have 0 in every trailing digits).
const xToStringExponentIndex = xToString.indexOf('e');
const [xToStringMantissa, xToStringExponent] = xToString.split('e');
const xToStringMantissaWithoutDecimalPoint = xToStringMantissa.replace(
'.',
''
);
if (
xToStringExponentIndex >= 0 &&
xToStringMantissaWithoutDecimalPoint.length <= p
) {
e = +xToStringExponent;
m =
xToStringMantissaWithoutDecimalPoint +
repeat('0', p - xToStringMantissaWithoutDecimalPoint.length);
xFinal = x;
} else {
e = getMagnitude(x);
const decimalPlaceOffset = e - p + 1;
// n is the integer containing the required precision digits. To derive the formatted string,
// we will adjust its decimal place in the logic below.
let n = Math.round(adjustDecimalPlace(x, decimalPlaceOffset));
// The rounding caused the change of magnitude, so we should increment `e` by 1.
if (adjustDecimalPlace(n, p - 1) >= 10) {
e = e + 1;
// Divide n by 10 to swallow one precision.
n = Math.floor(n / 10);
}
m = n.toString();
// Equivalent of n * 10 ** (e - p + 1)
xFinal = adjustDecimalPlace(n, p - 1 - e);
}
}
let int: number;
if (e >= p - 1) {
m = m + repeat('0', e - p + 1);
int = e + 1;
} else if (e >= 0) {
m = `${m.slice(0, e + 1)}.${m.slice(e + 1)}`;
int = e + 1;
} else {
m = `0.${repeat('0', -e - 1)}${m}`;
int = 1;
}
if (m.indexOf('.') >= 0 && maxPrecision > minPrecision) {
let cut = maxPrecision - minPrecision;
while (cut > 0 && m[m.length - 1] === '0') {
m = m.slice(0, -1);
cut--;
}
if (m[m.length - 1] === '.') {
m = m.slice(0, -1);
}
}
return {formattedString: m, roundedNumber: xFinal, integerDigitsCount: int};
// x / (10 ** magnitude), but try to preserve as much floating point precision as possible.
function adjustDecimalPlace(x: number, magnitude: number): number {
return magnitude < 0 ? x * 10 ** -magnitude : x / 10 ** magnitude;
}
}
|
f8abe5aea6862950bdfd0250e85eba0d6e04fd37
|
TypeScript
|
rnaidenov/typescript-design-patterns
|
/observerPattern.ts
| 3.84375
| 4
|
/**
* *** OBSERVER PATTERN *** *
*
* - Subscription model maintaining a one-to-many relationship between a
* a subject and its observers
* - Whenever the subject's state changes, the observers are notified
*
* - Requirements:
*
* * Subject, whose state will be monitored (***BeingLateSubject***)
* * Observer interface (***Observer***)
* * Classes implementing the Observer interface
* Each takes the subject as an argument in their constructors (***DarkJokeObserver / PunJokeObserver***)
*
*/
interface Observer {
update(): any
}
// Tells a dark joke when it gets notified about a state update
class DarkJokeObserver implements Observer {
private jokes: string[]
private count: number
constructor(private subject: BeingLateSubject) {
this.jokes = ['Super Dark Joke 1', 'Awfully Dark Joke 2', 'Hideously Dark Joke 3']
this.count = 0;
subject.attatch(this);
}
update(): void {
console.log("Dark Joke Observer detected an update!\nHere's your latest joke:\n");
console.log(this.jokes[this.count]+"\n\n\n");
++this.count;
}
}
class PunJokeObserver implements Observer {
private jokes: string[]
private count: number
constructor(private subject: BeingLateSubject) {
this.jokes = ['Stupid Pun 1', 'Dumb dumb Pun Joke 2', 'Miserably stupid pun 3'];
this.count = 0;
subject.attatch(this);
}
update(): void {
console.log("Pun Joke Observer detected an update!\nHere's your latest joke:\n");
console.log(this.jokes[this.count]+"\n\n\n");
++this.count;
}
}
class BeingLateSubject {
private listObservers: Observer[]
constructor(private state: number) {
this.listObservers = [];
}
public getState() {
return this.state;
}
public setState(state: number): void {
console.log('\n!---- !STATE UPDATE! ----!\n');
this.state = state;
this.notifyAllObservers();
}
public attatch(obs: Observer): void {
this.listObservers.push(obs);
}
public notifyAllObservers(): void {
for (let obs of this.listObservers) {
obs.update();
}
}
}
const lateSubject = new BeingLateSubject(419);
const darkJokeObserver = new DarkJokeObserver(lateSubject);
const punJokeObserver = new PunJokeObserver(lateSubject);
lateSubject.setState(418);
lateSubject.setState(426546);
lateSubject.setState(420);
|
ea3e816a30bd4fdf920d18ef3452f6e34a99738f
|
TypeScript
|
simondel/core
|
/packages/core/src/exceptions/Exception.ts
| 3.640625
| 4
|
/**
* Represents basic type of exception.
* @author Alex Chugaev
* @since 0.0.1
*/
export abstract class Exception extends Error {
/**
* Gets other error which was the cause of this exception.
* @author Alex Chugaev
* @since 0.14.0
*/
readonly cause: Error | undefined;
/**
* Initializes new instance.
* @param message Exception message
* @param cause Other error which was the cause of this exception
* @author Alex Chugaev
* @since 0.14.0
*/
constructor(message: string, cause?: Error) {
super(message);
this.name = this.constructor.name;
this.cause = cause;
}
toString(): string {
let value: string = '';
if (this.stack != null) {
value = this.stack;
} else {
value = `${this.name} ${this.message}`;
}
if (this.cause != null) {
value += '\r\nCaused by ';
if (this.cause instanceof Exception) {
value += this.cause.toString();
} else {
value += this.cause.stack;
}
}
return value;
}
}
|
5a93071487e87b56636f30329bb429e195dda909
|
TypeScript
|
chouchouxsl/ts-study-notes
|
/02-ts进阶/ts泛型.ts
| 4.125
| 4
|
export {}
/*
泛型的基本使用
*/
function sumArr<T, U>(x: T, y: U): [T, U] {
return [x, y]
}
sumArr(1, 2)
sumArr(1, '2')
sumArr('2', '2')
sumArr('2', false)
/*
泛型接口
*/
interface IsumObj<T, U> {
X: T
Y: U
}
function sumObj<T, U>(x: T, y: U): IsumObj<T, U> {
return {
X: x,
Y: y
}
}
console.log(sumObj('11', 55))
/*
泛型类
*/
interface IGeeger<X, Y> {
value: X
run(name: Y): X
}
class Geeger<T, U> implements IGeeger<T, U> {
constructor(public value: T) {}
run(name: U) {
return this.value
}
}
const geeger = new Geeger<string, number>('hahah')
geeger.run(12)
/*
泛型约束
*/
// 确保属性存在
interface Ilength {
length: number
}
function len<T extends Ilength>(msg: T): number {
return msg.length
}
len('xxxx')
// len(123)
// 检查对象上的key是否存在
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
getProperty(
{
name: '12',
age: 123
},
'age'
)
// ____________________________________
enum Difficulty {
Easy,
Intermediate,
Hard
}
interface Iget {
name: string
difficulty: Difficulty
get?(): void
set?(): void
}
const getObj: Iget = {
name: 'hahah',
difficulty: Difficulty.Easy,
get() {},
set() {}
}
function get<Iget, K extends keyof Iget>(obj: Iget, key: K): Iget[K] {
return obj[key]
}
get(getObj, 'get')
let difficulty: Difficulty = get(getObj, 'difficulty')
/*
泛型参数默认类型
*/
interface Idefault<T = string> {
name: T
}
const strA: Idefault = { name: 'Semlinker' }
const numB: Idefault<number> = { name: 123 }
/*
泛型条件类型
对于 T extends U ? X : Y 来说,还存在一个特性,当 T 是一个联合类型时,会进行条件分发
infer 的作用是让 TypeScript 自己推断,并将推断的结果存储到一个类型变量中,infer 只能用于 extends 语句中
*/
interface Inn<T = any> {
[key: string]: T
}
type Sin = Inn<string>
type StrDictMember = Sin extends Inn<infer U> ? U : never //U: string
// promise
interface XObj {
name: string
age?: number
}
async function hhh() {
return 'hhh'
}
async function xxx() {
return {
name: 'xxx'
} as XObj
}
/*
泛型工具类型
*/
// 1,Partial Partial<T> 的作用就是将某个类型里的属性全部变为可选项 ?
/**
* node_modules/typescript/lib/lib.es5.d.ts
* Make all properties in T optional
*/
// type Partial<T> = {
// [P in keyof T]?: T[P]
// }
interface Todo {
name: string
age: number
}
const obj1: Todo = {
name: '',
age: 1
}
const obj2: Partial<Todo> = { name: 'str' }
// 2.Record Record<K extends keyof any, T> 的作用是将 K 中所有的属性的值转化为 T 类型。
/**
* node_modules/typescript/lib/lib.es5.d.ts
* Construct a type with a set of properties K of type T
*/
// type Record<K extends keyof any, T> = {
// [P in K]: T;
// };
|
8dc7be4156f3c683ba552a673b1125c82a221fa7
|
TypeScript
|
kellerjmrtn/Chess-AI
|
/class/square.ts
| 2.796875
| 3
|
import { Piece } from "./piece.js";
export class Square {
contains: Piece;
currLegalMove: boolean;
rank: number;
file: number;
constructor(rank: number, file: number, contains?: Piece){
this.currLegalMove = false;
this.rank = rank;
this.file = file;
if(typeof contains == "undefined"){
this.contains = null;
} else {
this.contains = contains;
}
}
public getInnerHTML(): string {
if(this.contains == null){
if(this.currLegalMove){
return '<img class="piece" src="./images/legal_move.png"/>';
}
return "";
}
return this.contains.getInnerHTML(this.currLegalMove);
}
}
|
f6f0cd88942478aa26ff3a3d9adeadc7903b6261
|
TypeScript
|
Ice-cor/z-ui-react
|
/lib/_util/classes.ts
| 3.453125
| 3
|
export default function classnames(...names: (string | undefined)[]) { // arguments的解构
return names.filter(value => value).join(' '); // 使用filter去除空值,不留空格
}
// 简化类名的写法
interface Options {
extra: string | undefined;
}
interface ClassToggles {
[K: string]: boolean;
}
function scopedClassMaker(prefix: string) {
return function (name?: string | ClassToggles, options?: Options) {
if(name === undefined) name = '';
const namesObject = (typeof name === 'string') ? {[name]: name} : name;
// 拆分对象,拿到每项value: true的key值字符串数组
const result = Object
.entries(namesObject)
.filter(kv => kv[1] !== false)
.map(kv => kv[0])
// 遍历数组,成员用-连接上前缀
.map(name =>[prefix, name]
.filter(Boolean)
.join('-'))
// 最后用' '组合成字符串
.join(' ');
if (options && options.extra) {
return [result, options && options.extra].filter(Boolean).join(' ');
} else {
return result;
}
};
}
export {
scopedClassMaker
};
|
927e59cfe647e62155eaad24fb2fb7bcb948596b
|
TypeScript
|
DevWouter/thennext-todo
|
/web/src/app/models/task-page-navigation.ts
| 3.078125
| 3
|
/**
* Object that contain settings for the task-page.
* Whenever we leave something to `undefined` we mean it won't be changed.
* Setting values to `null` means set to setting to `undefined` (AKA: remove it).
*/
export class TaskPageNavigation {
/**
* The tasklist where we need to navigate to.
* Set to null to go to primary tasklist.
*/
taskListUuid?: string;
/**
* The task we need to show.
*/
taskUuid?: string;
/**
* Show completed tasks.
*/
showCompleted?: boolean;
/**
* Only show blocked tasks.
*/
showBlocked?: boolean;
/**
* Only show negative tasks.
*/
showNegative?: boolean;
}
|
c90d2a5e1f1a4a2e19232118e22e0f022445ead0
|
TypeScript
|
losi999/Toolset
|
/toolset-react/src/auth/login/propTypes.ts
| 2.734375
| 3
|
export type LoginFormFields = keyof LoginFormValues;
export type LoginFormValues = {
username: string;
password: string;
};
export type LoginFormValidations = {
form?: {
invalidCredentials: boolean,
},
username: {
required: boolean,
} | null,
password: {
required: boolean,
} | null,
};
|
c5538ecf5c51dc82172f7be597b777d6bbd9a0f3
|
TypeScript
|
MrBlenny/event-framework
|
/src/components/HttpRequest/HttpRequest.ts
| 2.625
| 3
|
import { Component } from '../../Component';
import { IMergeComponentSignatures, IOnHttpRequestEvent } from '../../types/events';
import { HttpLambda } from '../HttpLambda';
import { HttpServer } from '../HttpServer';
import { HttpRequestEvent } from './HttpRequestEvent';
/** Responsible for ingesting HttpRequestEvents and emitting them to subscribers */
export class HttpRequest extends Component<
IMergeComponentSignatures<HttpServer, HttpLambda, HttpRequestEvent>,
HttpRequest
> {
Emit: {
(
name: 'HttpRequestEvent',
event: HttpRequestEvent,
);
};
On: (
IOnHttpRequestEvent
);
Declared: 'HttpRequestEvent';
constructor () {
super();
this.declare('HttpRequestEvent');
this.subscribe('HttpServer.request', 'HttpLambda.request');
this.on('HttpLambda.request', this.emitRequest);
this.on('HttpServer.request', this.emitRequest);
}
connectToEvent (getComponents: () => Array<Component<any, any>>) {
return this.connectOn('HttpRequestEvent', getComponents);
}
private emitRequest = async (event: HttpRequestEvent) => {
await this.emit('HttpRequestEvent', event);
await event.broadcast();
return event;
}
}
|
fadc028bb50daeb14e7caf9a288e4f9f51549c93
|
TypeScript
|
carltheperson/same-app-different-design-patterns
|
/mvc-architecture/src/models/pet.ts
| 3.140625
| 3
|
import { Schema, model, Document } from "mongoose";
import { createUid } from "../utils";
const petSchema = new Schema({
id: String,
name: String,
points: Number,
imageUrl: String,
});
const dbModel = model<Pet & Document>("pet", petSchema);
export class Pet {
public id: string;
public name: string;
public points: number;
public imageUrl: string;
constructor(fields: {
name: string;
imageUrl: string;
points?: number;
id?: string;
}) {
const id = fields.id ?? createUid();
const points = fields.points ?? 0;
this.id = id;
this.name = fields.name;
this.points = points;
this.imageUrl = fields.imageUrl;
const isCreated = Boolean(fields.id);
if (!isCreated) {
dbModel.create({
name: this.name,
imageUrl: this.imageUrl,
id: this.id,
points: this.points,
});
}
}
public static async getFromID(id: string) {
const pet = await dbModel.findOne({ id });
if (pet) {
return new Pet({
name: pet.name,
imageUrl: pet.imageUrl,
points: pet.points,
id,
});
}
}
public async save() {
await dbModel.updateOne(
{ id: this.id },
{ name: this.name, points: this.points, imageUrl: this.imageUrl }
);
return;
}
public upvote() {
this.points += 1;
}
public downvote() {
this.points -= 1;
}
}
export class AllPets {
public static async get(): Promise<Pet[]> {
return await dbModel.find({}).lean();
}
public static async getSortedBasedOnPoints(): Promise<Pet[]> {
const pets = await AllPets.get();
return pets.sort((pet1, pet2) => {
return pet2.points - pet1.points;
});
}
}
|
8bd86e02105fb7dfb394684148b75b6baca825c0
|
TypeScript
|
simtechmedia/sacred-geometry
|
/scripts/models/StateModel.ts
| 3.078125
| 3
|
class StateModel
{
public stateChagneSignal : Signal = new Signal();
public static STATE_START : String = "STATE_START";
public static STATE_CREATE : String = "STATE_CREATE";
public static STATE_RESIZING : String = "STATE_RESIZING";
public static MAX_DEPTH : number = 2;
private _currentState : String ;
private _spawnAmount;
private _circlesArray = []; // Multidim Array of the circles
private _circlesNumArray : number[]; // Array of how many circles in each depth
private _currentCircleDepth : number; // How deep the circles go
private _strokeWidth : number ;
constructor() {
}
public init() {
this._currentState = StateModel.STATE_START;
this._spawnAmount = 6;
this._currentCircleDepth = 0;
this._strokeWidth = 3;
this._circlesNumArray = [];
}
public get currentState () : String { return this._currentState; }
public set currentState( state : String )
{
this._currentState = state;
//this.stateChagneSignal.dispatch(this._currentState);
}
public get circlesArray ( ) : any { return this._circlesArray ; }
public get currentCircleDepth() : number { return this._currentCircleDepth }
public set currentCircleDepth( num : number ){ this._currentCircleDepth = num }
public spawnAmountAdd() : void
{
this.spawnAmount = this.spawnAmount + 1;
this.stateChagneSignal.dispatch(this._currentState);
}
public spawnAmountSubtract():void
{
if(this._spawnAmount >= 1)
{
this.spawnAmount = this.spawnAmount-1;
this.stateChagneSignal.dispatch(this._currentState);
}
}
public get spawnAmount() : number { return this._spawnAmount; }
public set spawnAmount( num : number )
{
this._spawnAmount = num;
this.stateChagneSignal.dispatch(this._currentState);
}
public get strokeWidth(): number { return this._strokeWidth }
public set strokeWidth( num : number )
{
this._strokeWidth = num;
}
public get circlesNumArray () : number[]
{
return this._circlesNumArray;
}
public reset() {
console.log( "Reset" );
}
public undo() {
console.log("undo")
}
}
|
bd70f277c37ae187f5ff471f225c8cca51290ebd
|
TypeScript
|
gvr37leo/designerv8
|
/src/widgets/pointerwidget.ts
| 2.625
| 3
|
class PointerWidget extends Widget{
anchorelement: HTMLAnchorElement
newbutton: HTMLButtonElement
selectelement: HTMLSelectElement
// value:string
constructor(public attribute:Attribute, public designer:Designer){
super()
this.rootElement = string2html(`<span><a href="">goto</a> <select></select><input/><span/>`)
this.anchorelement = this.rootElement.querySelector('a')
this.inputelement = this.rootElement.querySelector('input') as HTMLInputElement
this.selectelement = this.rootElement.querySelector('select') as HTMLSelectElement
this.selectelement.addEventListener('change', e => {
this.inputelement.value = this.selectelement.value
this.anchorelement.href = `/data/${this.inputelement.value}`
})
this.inputelement.addEventListener('change',e => {
this.anchorelement.href = `/data/${this.inputelement.value}`
})
this.anchorelement.addEventListener('click', e => {
e.preventDefault()
this.designer.navigateToKnot(this.inputelement.value)
})
//gaat nu fout omdat hier gezocht wordt in de database terwijl data hardcoded is
//misschien een toggle om te kunnen switchen
//of gewoon ook in desigmetadataknots kijken
//of point naar de database id
search(genSimpleQuery('parent',this.attribute.selectKnot)).then(res => {
for(var item of res.data){
this.selectelement.appendChild(string2html(`<option value="${item._id}">${item.name}</option>`))
}
})
// this.anchorelement.addEventListener()
}
get() {
return this.inputelement.value
}
set(val: any) {
// this.value = val
this.anchorelement.href = `/data/${val}`
this.inputelement.value = val
this.selectelement.value = val
}
}
|
b7943fa37789771f61ddbae5b6012b5ca891a208
|
TypeScript
|
stanislavKostenko/decart-accounting-api
|
/src/modules/projects/dto/project.ts
| 2.53125
| 3
|
import { IsNotEmpty, IsNumber, IsString, MaxLength, MinLength } from 'class-validator';
import { Address } from '../../../interfaces/project.interface';
import { messages, ValidationType } from '../../../enums/project.enum';
import { AbstractDto } from '../../../classes/dto.abstract';
export class CreateProjectDto extends AbstractDto {
@IsNotEmpty()
@MinLength(3, { message: messages(ValidationType.MinLength) })
@MaxLength(20, { message: messages(ValidationType.MaxLength) })
readonly title: string;
@IsNotEmpty()
@MinLength(3, { message: messages(ValidationType.MinLength) })
readonly description: string;
readonly address: Address;
public archived: boolean;
@IsNotEmpty()
@IsNumber()
readonly square: number;
}
export class UpdateProjectDto extends CreateProjectDto {
@IsNotEmpty()
@IsString()
readonly id: string;
}
|
dc595115796f20408706179bbad4a3f83b728258
|
TypeScript
|
btzzar/personal_finance_web_app
|
/03-back-end/src/components/expense/dto/AddExpense.ts
| 2.6875
| 3
|
import Ajv from "ajv";
interface IAddExpense {
accountId:number;
category: string;
value: number;
currency: "eur"|"rsd"|"usd"|"gbp";
}
const ajv = new Ajv();
const IAddExpenseValidator = ajv.compile({
type: "object",
properties: {
accountId:{
type: "integer",
minimum: 1,
},
category:{
type: "string",
maxLength: 64
},
value:{
type: "number",
minimum: 0.01,
multipleOf: 0.01
},
currency:{
type: "string",
pattern: "eur|rsd|usd|gbp"
},
},
required: ["accountId", "category","value", "currency"],
additionalProperties: false,
});
export { IAddExpense};
export { IAddExpenseValidator };
|
bfd75e74a1ed336435bcfa203cf121530466a73d
|
TypeScript
|
softm-gerardoponce/prueba-mapa
|
/src/app/roadmap/objects/stage.ts
| 2.828125
| 3
|
export class Stage extends Phaser.GameObjects.Image{
private _scene;
private image;
public label = "";
private status:number = 0;
constructor(scene, x, y, texture){
super(scene, x, y, texture);
this._scene = scene;
this.setInteractive();
this.on('pointerover', function (pointer) {
switch(this.status){
case -1:
this.setTint(0xbbbbbb);
this.setScale(0.95);
break;
default:
this.setTint(0x00ffff);
this.setScale(1.2);
break;
}
});
this.on('pointerout', function (pointer) {
this.clearTint();
this.setScale(1);
});
}
setLabel(value:number | string){
this.label = this._scene.add.text(
this.x -7,
this.y - 25 ,
value,
{
font: '24px Arial',
color: '#000000',
}
);
}
setStatus(value:number){
this.status = value;
this.drawStatus();
}
private drawStatus(){
this.setFrame(this.status + 1);
}
}
|
3ece6b9c222287b6c93e961cc3cf5d945bfc82ff
|
TypeScript
|
the-owl/gleam-backend
|
/src/entity/Appointment.ts
| 2.734375
| 3
|
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import * as moment from 'moment';
import { Clinic } from './Clinic';
const momentTransformer = {
from (date: Date) {
return moment(date);
},
to (m: moment.Moment) {
return m.toDate();
}
};
@Entity()
export class Appointment {
@PrimaryGeneratedColumn()
id?: number;
@Column('text')
name?: string;
@Column('text')
phone?: string;
@Column('text')
email?: string;
@Column('timestamp', { transformer: momentTransformer })
date?: moment.Moment;
@ManyToOne(() => Clinic)
clinic?: Clinic;
}
|
bfdc67d004914653a1d64fbef262f504c414d96e
|
TypeScript
|
danbk88/opora-backend-challenge
|
/src/api/dal/drivers.dal.ts
| 2.578125
| 3
|
import { DriverStatsInSeason } from "../db/models/driverStatsInSeason";
import { BaseDAL } from "./base/base.dal";
import * as _ from 'lodash';
import { DriverInRace } from "../db/models/driverInRace";
export class DriversDAL extends BaseDAL{
private readonly GET_DRIVERS_SP_NAME: string = "get_drivers_of_season_sp";
private readonly GET_ALL_SEASONS_DRIVERS_SP_NAME: string = "get_all_seasons_top_drivers_sp";
private readonly GET_DRIVER_PROFILE_SP_NAME: string = "get_driver_profile_sp";
public async getDriversOfSeason(filters: any) {
const sp = this.getGetDriversOfSeasonStoredProcedure(filters);
return super.accessDB(sp, this.mapDriversOfSeasonResult.bind(this));
}
public async getAllSeasonsTopDrivers() {
const sp = this.getGetAllSeasonsTopDriversStoredProcedure();
return super.accessDB(sp, this.mapAllSeasonsTopDriversResult.bind(this));
}
public async getDriverProfile(driverId: any) {
const sp = this.getDriverProfileStoredProcedure({driverId});
return super.accessDB(sp, this.mapDriverProfileResult.bind(this));
}
// ----------------------------------------------------------- MAPPERS ----------------------------------------------------------------------
protected mapDriverProfileResult(res: any,) {
const items = res[0];
let driverInRaces: DriverInRace[] = [];
items.forEach(item => {
let driverInRace: DriverInRace = this.mapToDriverInRace(item);
driverInRaces.push(driverInRace);
});
return driverInRaces;
}
protected mapDriversOfSeasonResult(res: any,) {
const items = res[0];
let drivers: DriverStatsInSeason[] = [];
items.forEach(item => {
let driverStats: DriverStatsInSeason = this.mapToDriverStats(item);
drivers.push(driverStats);
});
return drivers;
}
protected mapAllSeasonsTopDriversResult(res: any,) {
const items = res[0];
let grouped = _.groupBy(items, 'year');
Object.entries(grouped).forEach((entry:any) => {
let drivers:any[] = [];
entry[1].forEach(item => {
let driverStats: DriverStatsInSeason = this.mapToTopDriverStats(item);
drivers.push(driverStats);
});
grouped[`${entry[0]}`] = {topDrivers: drivers};
});
return grouped;
}
private mapToTopDriverStats(item: any): DriverStatsInSeason {
let topDriverStats = this.mapToDriverStats(item);
return topDriverStats;
}
private mapToDriverStats(item: any): DriverStatsInSeason {
const driverStats = new DriverStatsInSeason();
driverStats.driverId = item.driverId;
driverStats.driverRef = item.driverRef;
driverStats.nationality = item.nationality;
driverStats.number = item.number;
driverStats.forename = item.forename;
driverStats.surname = item.surname;
driverStats.points = item.points;
driverStats.wins = item.wins;
driverStats.url = item.url;
driverStats.code = item.code;
driverStats.dob = item.dob;
driverStats.rank_in_season = item.rnk || null;
return driverStats;
}
private mapToDriverInRace(item: any): DriverInRace {
const driverInRace = new DriverInRace();
driverInRace.driverId = item.driverId;
driverInRace.raceId = item.raceId;
driverInRace.circuitName = item.circuitName;
driverInRace.position = item.position;
driverInRace.points = item.points;
driverInRace.avgPitStop = item.avgPit;
driverInRace.minPitStop = item.minPit;
driverInRace.maxPitStop = item.maxPit;
driverInRace.pitStopsCount = item.pitsCount;
driverInRace.avgLap = item.avgLap;
driverInRace.minLap = item.minLap;
driverInRace.maxLap = item.maxLap;
return driverInRace;
}
// ----------------------------------------------------------- HELPERS ----------------------------------------------------------------------
private getGetDriversOfSeasonStoredProcedure(keys: any) {
const args = `${keys.season}`;
const sp = {
name: this.GET_DRIVERS_SP_NAME,
args
};
return sp
}
private getGetAllSeasonsTopDriversStoredProcedure() {
const args = '';
const sp = {
name: this.GET_ALL_SEASONS_DRIVERS_SP_NAME,
args
};
return sp
}
private getDriverProfileStoredProcedure(keys: any) {
const args = `${keys.driverId}`;
const sp = {
name: this.GET_DRIVER_PROFILE_SP_NAME,
args
};
return sp
}
}
|
567acbaf35e87b7a1bbed64a01c715f8dfe798e0
|
TypeScript
|
wesleyh-dev/sidetree
|
/lib/bitcoin/BitcoinRawDataParser.ts
| 3.140625
| 3
|
import ErrorCode from './ErrorCode';
import SidetreeError from '../common/SidetreeError';
import { Block } from 'bitcore-lib';
/**
* Parser for raw bitcoin block data
*/
export default class BitcoinRawDataParser {
/**
* The beginning of each block contains the magic bytes indicating main or test net
* followed by a 4 byte number indicating how big the block data is
*/
private static magicBytes = {
testnet: Buffer.from('0b110907', 'hex'),
mainnet: Buffer.from('f9beb4d9', 'hex')
};
private static magicBytesLength = 4;
private static sizeBytesLength = 4;
/**
* Parse the given raw block data file. It can throw error if block data is invalid when validating magic bytes,
* creating new Block, or validating size
* @param rawBlockDataFileBuffer The file, in buffer form, to be parsed as blocks
*/
public static parseRawDataFile (rawBlockDataFileBuffer: Buffer): any {
// Expect raw block data to be in the format of
// <MagicBytes 4 bytes><SizeBytes 4 bytes><BlockData n bytes><MagicBytes><SizeBytes><BlockData>...repeating
const blockMapper: any = {};
let count = 0;
let cursor = 0;
// loop through each block within the buffer
while (cursor < rawBlockDataFileBuffer.length) {
// first 4 bytes are magic bytes
const actualMagicBytes = rawBlockDataFileBuffer.subarray(cursor, cursor + BitcoinRawDataParser.magicBytesLength);
if (!actualMagicBytes.equals(BitcoinRawDataParser.magicBytes.mainnet) && !actualMagicBytes.equals(BitcoinRawDataParser.magicBytes.testnet)) {
throw new SidetreeError(ErrorCode.BitcoinRawDataParserInvalidMagicBytes);
}
cursor += BitcoinRawDataParser.magicBytesLength;
// next 4 bytes must be a the size bytes in Uint little endian
// denoting how many bytes worth of block data are after it
const blockSizeInBytes = rawBlockDataFileBuffer.readUInt32LE(cursor);
cursor += BitcoinRawDataParser.sizeBytesLength;
// the next n bytes are the block data
const blockData = rawBlockDataFileBuffer.subarray(cursor, cursor + blockSizeInBytes);
let block: Block;
try {
block = new Block(blockData);
} catch (e) {
console.error(`Bitcore threw error when parsing block data ${e}`);
throw new SidetreeError(ErrorCode.BitcoinRawDataParserInvalidBlockData);
}
blockMapper[block.hash] = block;
cursor += blockSizeInBytes;
count++;
}
console.info(`Finished processing ${count} blocks from raw block file`);
return blockMapper;
}
}
|
06bbc197654b8cb193a9c84b3ab62b34c7f2ba4e
|
TypeScript
|
VugarAhmadov/island.is
|
/libs/shared/utils/src/lib/createXRoadAPIPath.ts
| 2.671875
| 3
|
import { logger } from '@island.is/logging'
export enum XRoadMemberClass {
GovernmentInstitution = 'GOV',
EducationalInstitution = 'EDU',
PrivateCompany = 'COM',
}
/**
* Constructs a valid X-Road API base url from the various parts required
*/
export const createXRoadAPIPath = (
xRoadBasePath: string,
xRoadMemberClass: XRoadMemberClass,
xRoadMemberCode: string,
xRoadMemberAPIPath: string,
) => {
if (!xRoadBasePath) {
logger.error('XRoad XROAD_BASE_PATH_WITH_ENV not provided.')
}
if (!xRoadMemberClass) {
logger.error('XRoad XROAD_VMST_MEMBER_CLASS not provided.')
}
if (!xRoadMemberCode) {
logger.error('XRoad XROAD_VMST_MEMBER_CODE not provided.')
}
if (!xRoadMemberAPIPath) {
logger.error('XRoad XROAD_VMST_API_PATH not provided.')
}
return `${xRoadBasePath}/${xRoadMemberClass}/${xRoadMemberCode}${xRoadMemberAPIPath}`
}
|
243b51f2bbe877ea4da388e3eda283ef5c73107a
|
TypeScript
|
ibrayo1/ScriptMan
|
/public/js/account.ts
| 3.546875
| 4
|
// This class is the basic "Account" class.
export class Account {
username: string
playerId: number
score: number
rotation: number
x: number
y: number
angle: number
color: string
// Basic constructor. On account creation you only need two things:
// 1: the username the account chooses
// 2: the ID number the account will be assigned
// The team color will be chosen later.
constructor(id: number, x: number, y: number,
rotation: number, val: number, name: string, color: string ){
this.playerId = id
this.score = val
this.x = x
this.y = y
this.rotation = rotation
this.username = name
this.color = color;
}
// This function allows for the changing the user color
//set_color(team_color:string) {
// this.team_color = team_color
//}
}
|
8683fd2573f1f104fbdb0894960293fc49af03f6
|
TypeScript
|
dankrajnak/dank.io
|
/src/View/Hooks/useFullScreen.ts
| 2.578125
| 3
|
import { useEffect, useState } from "react";
import useSafeWindow from "./useSafeWindow";
const useFullScreen = (): [number, number, JSX.Element | null] => {
const [window, flash] = useSafeWindow();
const [width, setWidth] = useState(window ? window.innerWidth : 0);
const [height, setHeight] = useState(window ? window.innerHeight : 0);
useEffect(() => {
const resize = () => {
if (window) {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
}
};
resize();
const listener = window && window.addEventListener("resize", resize);
return () => {
window && listener && window.removeEventListener("resize", listener);
};
}, [window]);
return [width, height, flash];
};
export default useFullScreen;
|
5dc7e68d17577e25aa92873ddabce4030a473e0c
|
TypeScript
|
Shotzoom/sportsengine-auth
|
/source/services/AuthService/request.ts
| 3.078125
| 3
|
import * as qs from "../../utils/qs";
import { MessageKind } from "./Message";
import { send } from "./send";
interface IRequestConfig {
id: string;
callback: string;
authorize: string;
}
type RequestCallback = (error: Error, response: IResponse) => void;
enum RequestState {
Idle,
Pending,
Complete
}
interface IResponse {
code: string;
success: boolean;
}
class Request {
private config: IRequestConfig;
private callback: RequestCallback;
private state: RequestState = RequestState.Idle;
public constructor(config: IRequestConfig, callback: RequestCallback) {
if (config == null) {
throw new TypeError("Expected a request config.");
}
if (callback == null) {
throw new TypeError("Expected a request callback.");
}
this.config = config;
this.callback = callback;
}
public get uri(): string {
const query = qs.stringify({
client_id: this.config.id,
redirect_uri: this.config.callback,
response_type: "code"
});
return `${this.config.authorize}?${query}`;
}
public send() {
if (this.state === RequestState.Idle) {
this.state = RequestState.Pending;
send(this.uri, (error, response) => {
if (error != null) {
this.reject(error);
} else {
switch (response.kind) {
case MessageKind.Code:
this.resolve({ success: true, code: response.data });
break;
default:
this.resolve({ success: false, code: "" });
}
}
});
}
}
private reject(error: Error) {
if (this.state !== RequestState.Complete) {
this.state = RequestState.Complete;
this.callback(error, null);
}
}
private resolve(response: IResponse) {
if (this.state !== RequestState.Complete) {
this.state = RequestState.Complete;
this.callback(null, response);
}
}
}
export default function request(config: IRequestConfig, cb: RequestCallback) {
return new Request(config, cb).send();
}
|
097a8dc3b444295ff5aee17e7a33be22fa7858ea
|
TypeScript
|
SphericalWorld/spherical-world
|
/server/components/PlayerData.ts
| 2.6875
| 3
|
import { Component } from '../../common/ecs/Component';
import { THREAD_MAIN, THREAD_PHYSICS } from '../../src/Thread/threadConstants';
import type { Networkable } from '../../common/Networkable';
type Props = { name: string };
export class PlayerData extends Component<Props> implements Networkable {
static threads = [THREAD_MAIN, THREAD_PHYSICS];
static componentName: 'playerData' = 'playerData';
static networkable = true;
name: string;
constructor({ name }: Props) {
super();
this.name = name;
}
serialize(): unknown {
return this;
}
}
|
530053f01692d7012070939c969a833b02d69c97
|
TypeScript
|
maxxyp/assettTracking
|
/wwwsrc/tests/unit/common/ui/converters/limitValueConverter.spec.ts
| 2.59375
| 3
|
/// <reference path="../../../../../typings/app.d.ts" />
import {LimitValueConverter} from "../../../../../app/common/ui/converters/limitValueConverter";
describe("the LimitValueConverter module", () => {
let limitValueConverter: LimitValueConverter;
beforeEach(() => {
limitValueConverter = new LimitValueConverter();
});
it("can be created", () => {
expect(limitValueConverter).toBeDefined();
});
it("can limit an array", () => {
expect(limitValueConverter.toView(
[1, 2, 3, 4, 5], 3).length === 3).toBeTruthy();
});
it("can limit larger than array", () => {
expect(limitValueConverter.toView(
[1, 2, 3, 4, 5], 10).length === 5).toBeTruthy();
});
it("can limit an empty array", () => {
expect(limitValueConverter.toView(
null, 3).length === 0).toBeTruthy();
});
});
|
50db29c99e50a58c12e6aae94fa1269b3d322986
|
TypeScript
|
vishneuski/vishneuski-home-Angular
|
/lesson-14-directives-pipes-reactive-forms/src/app/form/form.component.ts
| 2.515625
| 3
|
import {Component, OnInit} from "@angular/core";
import {
FormControl,
FormGroup,
Validators,
AbstractControl
} from "@angular/forms";
import {Status} from "./model/status";
import {FormService} from "./form.service";
import {of} from "rxjs";
import {map} from "rxjs/operators";
@Component({
selector: "app-form",
templateUrl: "./form.component.html",
styleUrls: ["./form.component.css"]
})
export class FormComponent {
public myForm: FormGroup;
statuses: Status[] = [
{id: 1, name: "Staible"},
{id: 2, name: "Critical"},
{id: 3, name: "Finished"}
];
constructor(private formService: FormService) {
this.myForm = new FormGroup({
projectForm: new FormGroup({
projectName: new FormControl(
"",
[Validators.required, this.nameValidator],
[this.projectNamelValidator.bind(this)]
),
mail: new FormControl("", [Validators.email, Validators.required]),
projectStatus: new FormControl("", Validators.required)
})
});
}
nameValidator(control: AbstractControl) {
const regexp = /\bTest\b/;
const valid = regexp.test(control.value);
if (valid) {
return {projectName: true};
} else {
return null;
}
}
projectNamelValidator(control: AbstractControl) {
return this.formService.checkProjectName(control.value).pipe(
map(res => {
console.log(res);
return res ? null : {isProjectNameAvailable: true};
})
);
}
submit() {
console.log("Submit: ", this.myForm.value);
}
}
|
e24d2dda6965cd0d48dc53bce4886afcab5a167f
|
TypeScript
|
MartinYounghoonKim/vue-typescript-boilerplate
|
/src/constants/env.constants.ts
| 2.796875
| 3
|
function getEnvConstants () {
const { NODE_ENV } = process.env;
const S3_BASE_URI = process.env.S3_BASE_URI;
let API_BASE_URI = '';
if (NODE_ENV === 'production') {
API_BASE_URI = process.env.PRODUCTION_API_BASE_URI;
} else if (NODE_ENV === 'development') {
API_BASE_URI = process.env.DEVELOPMENT_API_BASE_URI;
} else {
API_BASE_URI = process.env.LOCAL_API_BASE_URI;
}
return {
NODE_ENV,
API_BASE_URI: '',
S3_BASE_URI,
}
}
// interface User {
// name: string;
// age?: number;
// }
// function printUserInfo(user: User) {
// console.log(`${user.name}, ${user.age.toString()}`)
// // => error TS2532: Object is possibly 'undefined'.
// console.log(`${user.name}, ${user.age!.toString()}`)
// // => OK, you confirm that you're sure user.age is non-null.
//
// if (user.age != null) {
// console.log(`${user.name}, ${user.age.toString()}`)
// }
// // => OK, the if-condition checked that user.age is non-null.
//
// console.log(user.name + ', ' + user.age != null ? user.age.toString() : 'age unknown');
// // => Unfortunately TypeScript can't infer that age is non-null here.
// }
export const {
NODE_ENV,
API_BASE_URI,
S3_BASE_URI
} = getEnvConstants();
|
473763fcf6022fbb8b23e8a9bec8a8f7df74ba24
|
TypeScript
|
Micro-Incr/micro-upload-express
|
/server/middlewares/multer.ts
| 2.53125
| 3
|
import 'dotenv/config';
import multer from 'multer';
import {Request} from 'express';
import path from 'path';
import {MODE} from '../config/baseConfig';
const uploadFolderName = MODE === 'development' ? 'images/development' : 'images/production';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../../', uploadFolderName));
},
filename: function (req, file, cb) {
cb(null, `${Date.now().toString()}-${file.originalname}`);
}
});
const fileFilter = function (req: Request, file: Express.Multer.File, cb: (Error: Error, filename: boolean) => void) {
if (
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/png'
) {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({storage, fileFilter});
export default upload;
|
f858194f46e808d7aa61977fdaec755939542577
|
TypeScript
|
jorbuedo/react-reactive-var
|
/src/index.test.ts
| 2.828125
| 3
|
import { makeVar, useReactiveVar } from './'
import { renderHook, act } from '@testing-library/react-hooks'
describe('makeVar', () => {
it('creates a ReactiveVariable that can be read and updated', () => {
const testVar = makeVar('TEST_VARIABLE')
expect(testVar()).toBe('TEST_VARIABLE')
testVar('TEST_UPDATED')
expect(testVar()).toBe('TEST_UPDATED')
})
it('creates a ReactiveVariable that can be subscribed for updates', () => {
const testVar = makeVar('TEST_VARIABLE')
const handler = jest.fn()
testVar.subscribe(handler)
testVar('TEST_UPDATED')
expect(handler).toHaveBeenCalledWith('TEST_UPDATED')
})
it('creates a ReactiveVariable that can be subscribed for updates from a function', () => {
const testVar = makeVar('TEST_VARIABLE')
const handler = jest.fn()
testVar.subscribe(handler)
testVar((state) => state + '_UPDATED')
expect(handler).toHaveBeenCalledWith('TEST_VARIABLE_UPDATED')
})
it('creates a ReactiveVariable that can be unsuscribed after subscription', () => {
const testVar = makeVar('TEST_VARIABLE')
const handler = jest.fn()
testVar.subscribe(handler)
testVar.unsubscribe(handler)
testVar('TEST_UPDATED')
expect(handler).not.toHaveBeenCalled()
})
it('creates a ReactiveVariable that can be unsuscribed with subscription return value', () => {
const testVar = makeVar('TEST_VARIABLE')
const handler = jest.fn()
const unsubscribe = testVar.subscribe(handler)
unsubscribe()
testVar('TEST_UPDATED')
expect(handler).not.toHaveBeenCalled()
})
it('creates a ReactiveVariable for an object without an equals function', () => {
const testVar = makeVar({ a: 'TEST_VARIABLE' })
const handler = jest.fn()
testVar.subscribe(handler)
testVar({ a: 'TEST_VARIABLE' })
expect(handler).toHaveBeenCalled()
})
it('creates a ReactiveVariable for an object with an equals function', () => {
const testVar = makeVar({ a: 'TEST_VARIABLE' }, (x, y) => x.a === y.a)
const handler = jest.fn()
testVar.subscribe(handler)
testVar({ a: 'TEST_VARIABLE' })
expect(handler).not.toHaveBeenCalled()
})
})
describe('useReactiveVar', () => {
it('reacts the hooked component to a ReactiveVariable', async () => {
const testVar = makeVar('TEST_VARIABLE')
const hook = jest.fn()
hook.mockImplementation(() => useReactiveVar(testVar))
const { result, unmount } = renderHook(hook)
expect(result.current).toBe('TEST_VARIABLE')
expect(hook).toHaveBeenCalledTimes(1)
act(() => {
testVar('TEST_UPDATED')
})
expect(result.current).toBe('TEST_UPDATED')
expect(hook).toHaveBeenCalledTimes(2)
unmount()
act(() => {
testVar('TEST_FINISHED')
})
expect(hook).toHaveBeenCalledTimes(2)
expect(result.current).toBe('TEST_UPDATED')
expect(result.current).not.toBe('TEST_FINISHED')
expect(testVar()).toBe('TEST_FINISHED')
})
})
|
afd1d7b51c255bbd1daa8544f50a5a9d27c630f2
|
TypeScript
|
Rikon-Li/my-app
|
/src/store/index.ts
| 2.828125
| 3
|
import { createStore, Reducer, compose, Action } from "redux";
enum ActionType {
Add = "Add",
}
enum Status {
All = "all",
Todo = "todo",
Finish = "finished",
}
interface ListItem {
id: number;
value: string;
status: Status.Todo | Status.Finish;
}
interface StoreState {
value: string;
dataSource: ListItem[];
selected: Status;
}
interface InputAction extends Action {
type: ActionType.Add;
value: string;
}
type ReducerAction = InputAction;
const initialState: StoreState = {
value: "",
dataSource: [],
selected: Status.All,
};
const reducer: Reducer<StoreState, ReducerAction> = (state = initialState, action) => {
switch (action.type) {
case ActionType.Add:
return {
...state,
dateSource: [
...state.dataSource,
{
id: new Date().getTime(),
value: action.value,
status: Status.Todo,
},
],
value: "",
};
default:
return state;
}
};
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export default createStore(reducer, composeEnhancers());
|
ad9f6e645123e75e4cc5341163265b3cb797e398
|
TypeScript
|
daomaker/toll-bridge-subgraph
|
/src/utils.ts
| 2.65625
| 3
|
import { BigInt, Address, BigDecimal } from '@graphprotocol/graph-ts'
import { DycoToken } from '../generated/templates/DycoToken/DycoToken'
export let ZERO_INT = BigInt.fromI32(0)
export let ZERO_DEC = BigDecimal.fromString('0')
export let EMPTY_STRING_ARRAY = new Array<string>()
export let ONE_INT = BigInt.fromI32(1)
export let ONE_DEC = BigDecimal.fromString('1')
export let PRECISION = new BigDecimal(tenPow(18))
export let ETH_ADDR = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
export let ZERO_ADDR = '0x0000000000000000000000000000000000000000'
export function tenPow(exponent: number): BigInt {
let result = BigInt.fromI32(1)
for (let i = 0; i < exponent; i++) {
result = result.times(BigInt.fromI32(10))
}
return result
}
export function dycoToken(tokenAddress: Address): DycoToken {
return DycoToken.bind(tokenAddress)
}
export function getArrItem<T>(arr: Array<T>, idx: i32): T {
let a = new Array<T>()
a = a.concat(arr)
return a[idx]
}
export function getTokenDecimals(tokenAddress: Address): i32 {
let token = dycoToken(tokenAddress)
let decimals: i32
if (ETH_ADDR.includes(tokenAddress.toHex())) {
decimals = 18
} else {
decimals = token.decimals()
}
return decimals
}
export function normalize(i: BigInt, decimals: number = 18): BigDecimal {
return i.toBigDecimal().div(tenPow(decimals).toBigDecimal())
}
|
5b0e663f1ccc3d20b0d390ad294372bc108fd202
|
TypeScript
|
tomcoolnl2/sudoku
|
/src/Sudoku.ts
| 3.203125
| 3
|
import {
RegionSettings,
RowSettings,
ColumnSettings,
SeriesIndex,
GridMatrix,
GridMatrixCoörds,
GridMatrixIndex,
GridMatrixRegionSeries,
GridMatrixSeries,
N,
SudokuInputValue,
GridMatrixRegionSelection
} from './typings'
import { shuffle } from './utils'
export class Sudoku {
/** The number a cell has when it's value is hidden: 0 */
public static readonly HIDDEN_CELL_VALUE: N = 0
/** The maximum value a Cell can hold: 9 */
public static readonly SIZE: N = 9
/** The total of a 9x9 Grid: 81 */
public static readonly CELLS: number = Sudoku.SIZE ** 2
/** The solution */
private solutionGrid: GridMatrix = null
/** The start of the game */
private initialGrid: GridMatrix = null
/** The board a user will use */
private workingGrid: GridMatrix = null
/** The board to track mistakes */
private mistakesGrid: GridMatrix = null
/** Counter to validate backtracking */
private trackedUserInput: GridMatrixSeries<SudokuInputValue> = null
/** Counter to validate backtracking */
private backTrackAttempt: number = 0
constructor() {
//always start with a 9x9 grid, filled with 0 as cell values
this.solutionGrid = Sudoku.generateMatrix()
this.createSolution()
// poke some holes in the solution; so we have an actual game
this.setInitialGame()
// clone the initial game so we have something a user can play with
this.workingGrid = Sudoku.cloneGrid(this.initialGrid)
// separate grid to track mistakes
this.mistakesGrid = Sudoku.generateMatrix()
// keep track of inputted values, including clues
this.trackedUserInput = Sudoku.createSeries(Sudoku.HIDDEN_CELL_VALUE)
// assemble clues to keep track of inputted values
this.trackedClues()
}
/**
* Public accessor for the solution
*/
public get solutionMatrix(): GridMatrix {
return this.solutionGrid
}
/**
* Public accessor for the initial game matrix
*/
public get initialGameMatrix(): GridMatrix {
return this.initialGrid
}
/**
* Public accessor for the UI grid
*/
public get workingMatrix(): GridMatrix {
return this.workingGrid
}
/**
* Public accessor for the mistakes grid
*/
public get mistakesMatrix(): GridMatrix {
return this.mistakesGrid
}
/**
* Public accessor to retrieve Clues and User Input values
*/
public get trackedInput(): GridMatrixSeries<SudokuInputValue> {
return this.trackedUserInput
}
/**
* Public accessor to find the first cell to select when initialising a new game
*/
public get initialSelection(): GridMatrixCoörds {
for (let i = 0; i < Sudoku.CELLS; i += 1) {
const row = (i / Sudoku.SIZE) << 0 as GridMatrixIndex
const col = i % Sudoku.SIZE as GridMatrixIndex
if (this.initialGrid[row][col] === Sudoku.HIDDEN_CELL_VALUE) {
return [row, col]
}
}
return [0, 0]
}
/**
* Create a empty 9x9 Grid, filled with zeros (0)
* @returns a 9x9 GridMatrix
*/
public static generateMatrix(): GridMatrix {
return Sudoku.createSeries(() => Sudoku.createSeries(Sudoku.HIDDEN_CELL_VALUE))
}
/**
* Random get a number between 0 and 8
* @returns A random number between 0 and 8
*/
public static getRandomIndex(): number {
return (Math.random() * Sudoku.SIZE) << 0
}
/**
* Clones a 2D matrix without any references
* @param grid GridMatrix
* @returns GridMatrix
*/
public static cloneGrid(grid: GridMatrix): GridMatrix {
return [...grid].map(row => [...row]) as GridMatrix
}
/**
* Create a Series of N length, filled with an Array of Numbers.
* @param argument Either a Number or a Method, both are ways to provide values for a Series.
*/
public static createSeries<T>(index: number): T
public static createSeries<T, R = unknown>(mapFn: SeriesIndex<R>): T
public static createSeries<T, R = unknown>(argument: number | SeriesIndex<R>): T {
let index: number = Sudoku.HIDDEN_CELL_VALUE
let mapFn: SeriesIndex<unknown> = () => index
if (typeof argument === 'number') {
index = argument
} else {
mapFn = argument
}
return Array.from({ length: Sudoku.SIZE }).map(mapFn) as unknown as T
}
/**
* Get the region the current selected cell is in
* @param [row, col] the x, y coordinates of the current selection
* @returns An array of rows for the current region the selection is in, same for cols
*/
public static getSelectedRegion([row, col]: GridMatrixCoörds): GridMatrixRegionSelection {
// Define top left corner of the region for empty cell
const x: number = row - (row % 3)
const y: number = col - (col % 3)
const series: GridMatrixRegionSeries = [0, 1, 2]
const rows: number[] = []
const cols: number[] = []
// Get the region rows by it's indexes
for (const ri of series) {
rows.push((x + ri))
}
// Get the region colums by it's indexes
for (const ci of series) {
cols.push((y + ci))
}
return [ rows, cols ] as GridMatrixRegionSelection
}
/**
* Returns true if the value is already being used in the current grid Region
* @param input Object with 3x3 Region and value
* @returns
*/
private valueExistsInRegion({ grid, row, col, value }: RegionSettings): boolean {
// Define top left corner of the region for empty cell
const x: number = row - (row % 3)
const y: number = col - (col % 3)
const series: GridMatrixRegionSeries = [0, 1, 2]
// Check the 3x3 region
for (const ri of series) {
for (const ci of series) {
if (grid[x + ri][y + ci] === value) {
return true // If number is found, it is not safe to place
}
}
}
return false
}
/**
* Returns true if the value is already being used in the current grid row
* @param input Object with 9x9 Sudoku Grid, Row and Column indexes
* @returns
*/
private valueExistsInRow({ grid, row, value }: RowSettings): boolean {
return grid[row].includes(value)
}
/**
* Returns true if the value is already being used in the current grid column
* @param input Object with 9x9 Sudoku Grid, Row and Column indexes
* @returns
*/
private valueExistsInColumn({ grid, col, value }: ColumnSettings): boolean {
return grid.some(row => row[col] === value)
}
/**
* Combine valueExistsInRegion, valueExistsInRow and valueExistsInColumn to return a boolean
* @param param RegionSettings
* @returns boolean Weather it is safe to place this value into the current cell
*/
private valueIsSafeToPlace({ grid, row, col, value }: RegionSettings): boolean {
return !this.valueExistsInRegion({ grid, row, col, value })
&& !this.valueExistsInRow({ grid, row, value })
&& !this.valueExistsInColumn({ grid, col, value })
}
/**
* Validate if the given grid does not contain any (0)
* @param grid The grid to validate
* @returns boolean
*/
public gameIsSet(grid: GridMatrix): boolean {
return !grid.flat().includes(Sudoku.HIDDEN_CELL_VALUE)
}
/**
* Backtracking recursion to check all the possible combination of numbers
* @param grid
* @returns true if the solution is valid
*/
private createSolution(grid: GridMatrix = this.solutionGrid): boolean {
const series = Sudoku.createSeries<SudokuInputValue[], number>((_, i) => i + 1) // Create [1, 2, 3, 4, 5, 6, 7, 8, 9] to check against
let row: GridMatrixIndex = 0 // we start at [0][0] of the grid
let col: GridMatrixIndex = 0
for (let i = 0; i < Sudoku.CELLS; i += 1) { // label this loop so we can reference to it from inside inner loops
row = (i / Sudoku.SIZE) << 0 as GridMatrixIndex // we gracefully increase row every 9th iteration
col = i % Sudoku.SIZE as GridMatrixIndex // this will count from 0-8 (9 % 9 = 0), and then start over again
if (grid[row][col] === Sudoku.HIDDEN_CELL_VALUE) {
// The range of values 1 to 9 is shuffled at the start of each iteration,
// ensuring the that probability of each new game being similar is low.
// Validate every possible (but shuffled) number
for (const value of shuffle(series) as SudokuInputValue[]) {
// if value does not already exists in region, row or col
if (this.valueIsSafeToPlace({ grid, row, col, value })) {
grid[row][col] = value
if (this.gameIsSet(grid) || this.createSolution(grid)) {
return true
}
}
}
break
}
}
grid[row][col] = 0
}
/**
* Validte if a given grid holds the solution
* @param grid GridMatrix
* @returns boolean
*/
private testSolution(grid: GridMatrix): boolean {
// we start at [0][0] of the grid
let row: GridMatrixIndex = 0
let col: GridMatrixIndex = 0
const series = Sudoku.createSeries<SudokuInputValue[], number>((_, i) => i + 1)
for (let i = 0; i < Sudoku.CELLS; i += 1) {
row = (i / Sudoku.SIZE) << 0 as GridMatrixIndex
col = (i % Sudoku.SIZE) as GridMatrixIndex
if (grid[row][col] === Sudoku.HIDDEN_CELL_VALUE) {
for (const value of series) {
if (this.valueIsSafeToPlace({ grid, row, col, value })) {
grid[row][col] = value
if (this.gameIsSet(grid)) {
this.backTrackAttempt += 1
break
}
else if (this.testSolution(grid)) {
return true
}
}
}
break
}
}
grid[row][col] = 0
}
/**
* Removes numbers from a full grid to set an actual Sudoku Challenge
* @param difficulty Number of attepts to solve (higher means more difficult)
* @returns GridMatrix
*/
private setInitialGame(difficulty = 3) {
const initialGrid: GridMatrix = Sudoku.cloneGrid(this.solutionGrid)
while (difficulty > 0) {
let row = Sudoku.getRandomIndex()
let col = Sudoku.getRandomIndex()
if (initialGrid[row][col] === 0) {
row = Sudoku.getRandomIndex()
col = Sudoku.getRandomIndex()
}
const backup = initialGrid[row][col] // store value to optionally restore it
initialGrid[row][col] = 0 // remove number from the grid
this.backTrackAttempt = 0
this.testSolution(initialGrid) // attempt to solve it
if (this.backTrackAttempt !== 1) {
initialGrid[row][col] = backup // put it back and try again
difficulty -= 1 // step back and try again (backtrack)
}
}
this.initialGrid = initialGrid
return this.initialGrid
}
/**
* Count the number of individual clues
*/
private trackedClues(): void {
const grid = Sudoku.cloneGrid(this.workingGrid)
grid.flat().forEach((value: N) => {
if (value !== Sudoku.HIDDEN_CELL_VALUE) {
this.trackedUserInput[value - 1] += 1
}
})
}
}
|
fb2764bcc7835e958cc0a806149ce0e8a234751d
|
TypeScript
|
Millermiller/subbackend
|
/src/Scandinaver/Asset/Domain/Term.ts
| 2.765625
| 3
|
import { User } from '@/Scandinaver/Core/Domain/User'
import { Entity } from '@/Scandinaver/Core/Domain/Contract/Entity'
import TermDTO from '@/Scandinaver/Asset/Domain/DTO/TermDTO'
export class Term extends Entity {
private _id!: number
private _active!: boolean
private _value!: string
private _user: User
constructor(word: string) {
super()
this.value = word
}
getId(): number | string {
return this.id
}
get id(): number {
return this._id
}
set id(value: number) {
this._id = value
}
get active(): boolean {
return this._active
}
set active(value: boolean) {
this._active = value
}
get value(): string {
return this._value
}
set value(value: string) {
this._value = value
}
get user(): User {
return this._user
}
set user(value: User) {
this._user = value
}
getValue(): string {
return this.value
}
toDTO(): TermDTO {
const dto = new TermDTO()
dto.id = this._id
dto.value = this._value
return dto
}
}
|
54b41b3fc3224d4fb15880f76a3586777c7d97d8
|
TypeScript
|
TreeZhou/paoku
|
/src/Utils/Tool.ts
| 2.734375
| 3
|
/**
*
* @author cxw
*
*/
class Tool {
public constructor() {
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
* Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
*/
public static createBitmapByName(name: string): egret.Bitmap {
var result: egret.Bitmap = new egret.Bitmap();
var texture: egret.Texture = RES.getRes(name);
result.texture = texture;
return result;
}
public static createBitmapBySheet(ruleImgs: egret.SpriteSheet, name: string): egret.Bitmap {
var result: egret.Bitmap = new egret.Bitmap();
var texture: egret.Texture = ruleImgs.getTexture(name);
result.texture = texture;
return result;
}
/**
* 创建按钮方法
* @param name 资源文件名字
* @param x X位置
* @param y Y位置
* @param width 宽度
* @param height 高度
* @param clickFunc 传入方法
* @param anchorX 中心点 默认为0
* @param anchorY 中心点 默认为0
*/
public static createButton(self: any, name: string, x: number, y: number, width: number, height: number, clickFunc: Function, anchorX: number = 0, anchorY: number = 0): egret.Sprite {
var result: egret.Sprite = new egret.Sprite();
var clickF = function () {
result.removeEventListener(egret.TouchEvent.TOUCH_TAP, clickF, self);
egret.Tween.get(result).to({ scaleX: 1.1, scaleY: 1.1 }, 400, egret.Ease.backOut).to({ scaleX: 1, scaleY: 1 }, 400, egret.Ease.backOut).call(function () {
result.addEventListener(egret.TouchEvent.TOUCH_TAP, clickF, self);
}, self);
clickFunc(self);
}
result.addChild(Tool.createBitmapByName(name));
result.x = x; result.y = y; result.width = width; result.height = height;
result.touchEnabled = true; result.anchorOffsetX = anchorX; result.anchorOffsetY = anchorY;
result.addEventListener(egret.TouchEvent.TOUCH_TAP, clickF, self);
return result;
}
//原生图片显示于白鹭对象。(含二维码)
public static displayLikeObject(cloneObj: any, cloneWho: egret.DisplayObject, src?: string): void {
if (cloneWho.width == 0 || cloneWho.height == 0) {
console.warn("The width or height of the cloneWho:(" + cloneWho.hashCode + ") can not be 0");
return;
}
if (src) {
cloneObj["src"] = src;
}
var body = document.body;
var stage = egret.MainContext.instance.stage;
var scaleWidth = body.clientWidth / stage.stageWidth;
var scaleHeight = body.clientHeight / stage.stageHeight;
var x = cloneWho.x;
var y = cloneWho.y;
var width = cloneWho.width;
var height = cloneWho.height;
var style = cloneObj.style;
if (body.clientWidth < body.clientHeight) {
style.width = width * scaleWidth + "px";
style.height = height * scaleHeight + "px";
style.left = x * scaleWidth + "px";
style.top = y * scaleHeight + "px";
} else {
style.width = height * scaleHeight + "px";
style.height = width * scaleWidth + "px";
style.left = y * scaleHeight + "px";
style.top = (stage.stageWidth - x - width) * scaleWidth + "px";
}
}
/**
* 创建纯Sprite
*/
public static createSprite(_width: number, _height: number, color: number = null): egret.Sprite {
var result: egret.Sprite = new egret.Sprite();
if (color == null) {
result.graphics.beginFill(0x000000, 0);
}
else {
result.graphics.beginFill(color, 1);
}
result.graphics.drawRect(0, 0, _width, _height);
result.graphics.endFill();
return result;
}
public static createTextFiled(x: number, y: number, width: number, height: number, str: string = "", size: number = 35, color: number = 0x000000, bold: boolean = false): egret.TextField {
var result: egret.TextField = new egret.TextField();
result.fontFamily = "Microsoft YaHei, Helvetica, sans-serif";
result.x = x; result.y = y; result.width = width; result.height = height;
result.text = str; result.size = size; result.textColor = color; result.bold = bold;
return result;
}
public static setInputTextFiled(obj: egret.TextField, defaultStr: string) {
obj.type = "input";
obj.addEventListener(egret.FocusEvent.FOCUS_IN, () => {
obj.text = "";
obj.textColor = 0x000000;
}, this);
obj.addEventListener(egret.FocusEvent.FOCUS_OUT, () => {
if (obj.text == "") {
obj.text = defaultStr;
obj.textColor = 0xaaaaaa;
}
}, this);
}
/**
* 清除容器中所有东西
* @param sp
*/
public static removeALL(sp: any): void {
while (sp.numChildren > 0) {
sp.removeChildAt(0);
}
}
public static center(obj: egret.DisplayObject, is: Boolean = false): void {
if (obj.anchorOffsetX != obj.width >> 1) {
obj.anchorOffsetX = obj.width >> 1;
obj.anchorOffsetY = obj.height >> 1;
if (is) {
return;
}
obj.x += obj.anchorOffsetX;
obj.y += obj.anchorOffsetY;
}
}
//缓动
public static setPointDown(obj: any, move: number, wait: number, movetime: number, self: any, callback: any = null) {
obj.alpha = 0;
var temp = obj.y;
obj.y = obj.y - move;
egret.Tween.get(obj).wait(wait).to({ y: temp, alpha: 1 }, movetime, egret.Ease.quadInOut).call(() => {
if (callback == null) {
return;
}
callback.call(self);
}, this);
}
public static setPointLeft(obj: any, move: number, wait: number, movetime: number, self: any, callback: any = null) {
obj.alpha = 0;
var temp = obj.x;
obj.x = obj.x - move;
egret.Tween.get(obj).wait(wait).to({ x: temp, alpha: 1 }, movetime, egret.Ease.quadInOut).call(() => {
if (callback == null) {
return;
}
callback.call(self);
}, this);
}
public static setScale(obj: eui.Image, rotation: number, wait: number, movetime: number, self: any, callback: any = null) {
obj.alpha = 0;
obj.scaleX = obj.scaleY = 2;
obj.rotation = rotation;
egret.Tween.get(obj).wait(wait).to({ scaleX: 1, scaleY: 1, rotation: 0, alpha: 1 }, 500, egret.Ease.circOut).call(() => {
if (callback == null) {
return;
}
callback.call(self);
}, this);
}
public static removeObj(obj: any) {
if (!obj) {
return;
}
obj.alpha = 0;
obj.scaleX = obj.scaleY = 1;
egret.Tween.removeTweens(obj);
}
/**
* 获取对应的bitmaptext
*/
public static getBitmapText(bfont: string): egret.BitmapText {
var font = RES.getRes(bfont);
var btxt = new egret.BitmapText;
btxt.font = font;
return btxt;
}
public static createMovieClip(mcName: string, Name: string = ""): egret.MovieClip {
var resJs = RES.getRes(mcName + "_json");
var resPng = RES.getRes(mcName + "_png");
var mcFactory: egret.MovieClipDataFactory = new egret.MovieClipDataFactory(resJs, resPng);
if (Name) {
var movieclipData = mcFactory.generateMovieClipData(Name);
} else {
var movieclipData = mcFactory.generateMovieClipData(mcName);
}
var mc: egret.MovieClip = new egret.MovieClip(movieclipData);
return mc;
}
/**
* 给字体添加描边
* @param lable 文字
* @param color 表示文本的描边颜色
* @param width 描边宽度。
*/
public static addLableStrokeColor(lable: egret.TextField, color: any, width: any): void {
lable.strokeColor = color;
lable.stroke = width;
}
/**
* 从父级移除child
* @param child
*/
public static removeFromParent(child: egret.DisplayObject) {
if (child.parent == null)
return;
child.parent.removeChild(child);
}
/**
* 锁屏
*/
public static lock(): void {
egret.MainContext.instance.stage.touchEnabled = egret.MainContext.instance.stage.touchChildren = false;
}
/**
* 解屏
*/
public static unlock(): void {
egret.MainContext.instance.stage.touchEnabled = egret.MainContext.instance.stage.touchChildren = true;
}
/**
* 文字打字机效果
* obj 文本对象
* content 文字
* interval 打字间隔 毫秒
*/
public static typerEffect(obj, content: string = "", interval: number = 200): void {
var strArr: Array<any> = content.split("");
var len: number = strArr.length;
for (var i = 0; i < len; i++) {
egret.setTimeout(function () {
obj.appendText(strArr[Number(this)]);
}, i, interval * i);
}
}
public static share(_title: string, _conent: string, _url: string, _img: string) {
var shareData = {
title: _title,
desc: _conent,
link: _url,
imgUrl: _img,
success: function (res) {
var context = egret.MainContext.instance;
context.stage.dispatchEventWith("yifenxiang", false);
}
};
var shareData2 = {
title: _conent,
desc: _conent,
link: _url,
imgUrl: _img,
success: function (res) {
var context = egret.MainContext.instance;
context.stage.dispatchEventWith("yifenxiang", false);
}
};
window['wx']['onMenuShareAppMessage'](shareData);
window['wx']['onMenuShareTimeline'](shareData2);
}
//可以改变ios微信端title
public static setTitle(t) {
document.title = t;
var i = document.createElement('iframe');
i.src = '//m.baidu.com/favicon.ico';
i.style.display = 'none';
i.onload = function () {
setTimeout(function () {
i.remove();
}, 9)
}
document.body.appendChild(i);
}
//阻止容器出界
public static checkImage(obj: egret.DisplayObjectContainer): void {
if (obj.x < egret.MainContext.instance.stage.stageWidth - obj.width) {
obj.x = egret.MainContext.instance.stage.stageWidth - obj.width;
} else if (obj.x > 0) {
obj.x = 0;
}
if (obj.y < egret.MainContext.instance.stage.stageHeight - obj.height) {
obj.y = egret.MainContext.instance.stage.stageHeight - obj.height;
} else if (obj.y > 0) {
obj.y = 0;
}
}
/**按钮点击弹一下再执行代码
*使用方法:Tool.ButtonBound(e.target,function(){console.log("执行");},this);
*/
public static ButtonBound(btn: egret.DisplayObjectContainer, callback: Function, self: any) {
btn.touchEnabled = false;
Tool.center(btn);
egret.Tween.get(btn).to({ "scaleX": 1.1, "scaleY": 1.1 }, 100)
.to({ "scaleX": 1, "scaleY": 1 }, 200, egret.Ease.bounceOut).call(() => {
btn.touchEnabled = true;
callback.call(self, [btn]);
}, self);
}
/*根据容器等比缩放 */
public static scale(parent: egret.DisplayObjectContainer, child: egret.Bitmap) {
var bi = child.texture.textureWidth / child.texture.textureHeight;
if (child.texture.textureWidth > child.texture.textureHeight) {
if (child.texture.textureWidth > parent.width) {
child.width = parent.width;
child.height = parent.width / bi;
} else {
child.width = child.texture.textureWidth;
child.height = child.texture.textureHeight;
}
if (child.height > parent.height) {
child.height = parent.height;
child.width = bi * child.height;
}
} else {
if (child.texture.textureHeight > parent.height) {
child.height = parent.height;
child.width = bi * child.height;
} else {
child.width = child.texture.textureWidth;
child.height = child.texture.textureHeight;
}
if (child.width > parent.width) {
child.width = parent.width;
child.height = child.width / bi;
}
}
Tool.center(child);
child.x = parent.width / 2;
child.y = parent.height / 2;
}
/*只管填充满容器*/
public static scale2(parent: egret.DisplayObjectContainer, child: egret.Bitmap) {
var bi = child.texture.textureWidth / child.texture.textureHeight;
if (child.texture.textureWidth > child.texture.textureHeight) {
child.height = parent.height;
child.width = bi * child.height;
} else {
child.width = parent.width;
child.height = child.width / bi;
}
Tool.center(child);
child.x = parent.width / 2;
child.y = parent.height / 2;
}
/**
* @param base64 字符串
*/
public static getTexture(base64: string, callback: any, that: any) {
let img = document.createElement("img");
var texture: egret.Texture = new egret.Texture();
img.src = base64;
img.onload = () => {
let bitmapdata: egret.BitmapData = new egret.BitmapData(img);
texture.bitmapData = bitmapdata;
callback.call(that, texture);
}
}
/**
* @param frame 根据帧频返回偏移量
*/
public static frameRate(frame: number): number {
return (frame / egret.MainContext.instance.stage.frameRate);
}
/**
* 文本数字逐渐到设置的值
* text:文本框 start:开始值 end:结束值 time:持续时间
*/
public static easeTextField(text: any, start: number, end: number, time: number) {
var obj = { value: start };
egret.Tween.get(obj, {
loop: false, onChange: () => {
text.text = String(Math.floor(obj.value));
}, onChangeObj: this
}).to({ value: end }, time, egret.Ease.quadInOut).call(() => {
egret.Tween.removeTweens(text);
}, this);
}
//发光滤镜
public static setFilter(img: egret.Bitmap) {
//颜色矩阵数组增加亮度
var colorMatrix = [
1, 0, 0, 0, 100,
0, 1, 0, 0, 100,
0, 0, 1, 0, 100,
0, 0, 0, 1, 0
];
var colorFlilter = new egret.ColorMatrixFilter(colorMatrix);
img.filters = [colorFlilter];
}
public static playAnimation(target: egret.tween.TweenGroup, isLoop: boolean): void {
if (isLoop) {
for (var key in target.items) {
target.items[key].props = { loop: true };
}
}
target.play();
}
//获得对象长度
public static getPropertyCount(o) {
var n, count = 0;
for (n in o) {
if (o.hasOwnProperty(n)) {
count++;
}
}
return count;
}
//一口气创建圆形遮罩
public static createCircleMask(sp: egret.DisplayObject) {
var p: egret.Sprite = new egret.Sprite;
var w: number = sp.width >> 1;
p.graphics.beginFill(0x000000, 1);
p.graphics.drawCircle(w, w, w);
p.graphics.endFill();
sp.parent.addChild(p);
p.x = sp.x; p.y = sp.y;
sp.mask = p;
}
//选择图片插件 可压缩调节图片大小
/**
* Tool.pickPhoto(640, (img) => {
var texture: egret.Texture = new egret.Texture();
let bitmapdata: egret.BitmapData = new egret.BitmapData(img);
texture.bitmapData = bitmapdata;
let imgReview:egret.Bitmap = new egret.Bitmap;
imgReview.texture = texture;
this.addChild(imgReview);
}, this);
*/
public static pickPhoto(maxWidth: number, callBack: Function, self: any) {
var fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.accept = "image/*";
fileInput.style.display = "none";
document.body.insertBefore(fileInput, document.body.firstChild);
fileInput.addEventListener("change", function (evt) {
var mime = { "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "bmp": "image/bmp" };
var file = evt.target['files'][0];
window['lrz'](file, {
width: maxWidth
})
.then(function (rst) {
let img = document.createElement("img");
img.src = rst.base64;
img.onload = () => {
callBack.call(self, img);
}
});
}, false);
fileInput.click();
}
/**
* 复制到系统剪切板方法 兼容性有待考究
*/
public static copy(message) {
var input = document.createElement("input");
input.value = message;
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, input.value.length),
document.execCommand('Copy');
document.body.removeChild(input);
egret.log("复制成功");
}
}
|
1c1f0f374b2fa7888121486ade3812b7939f7c7d
|
TypeScript
|
aeroheim/midori
|
/src/pipeline/background-pass.ts
| 2.796875
| 3
|
import { WebGLRenderer, WebGLRenderTarget } from 'three';
import { Pass } from 'three/examples/jsm/postprocessing/Pass';
import { Background } from '../background';
class BackgroundPass extends Pass {
private _background: Background;
/**
* Constructs a BackgroundPass.
* @param {Background} background
*/
constructor(background: Background) {
super();
this._background = background;
}
/**
* Sets the current background.
* @param {Background} background
*/
setBackground(background: Background): void {
this._background = background;
}
/**
* Returns the current background.
* @returns Background
*/
get background(): Background {
return this._background;
}
/**
* Sets the size of the current background.
* @param {number} width
* @param {number} height
*/
setSize(width: number, height: number): void {
this._background.setSize(width, height);
}
/**
* Renders the current background.
* @param {WebGLRenderer} renderer - the renderer to use.
* @param {WebGLRenderTarget} writeBuffer - the buffer to render to, or null to render directly to screen.
*/
render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget): void {
this._background.render(renderer, this.renderToScreen ? null : writeBuffer);
}
/**
* Disposes this object. Call when this object is no longer needed, otherwise leaks may occur.
*/
dispose(): void {
this._background.dispose();
}
}
export {
BackgroundPass,
};
export default BackgroundPass;
|
a5c665ab12ce3f8e95c78e8d5b8145b6e4f7a81e
|
TypeScript
|
devcord/devmod-core
|
/src/utils/config/hydrateRoles.ts
| 3.109375
| 3
|
/*
* Gabe Dunn 2020
* Function to take a list of RoleResolvables and turn it into a list of Roles
*/
import { Guild } from 'discord.js'
import {
ConfigRoleInterface,
LiveConfigRoleInterface
} from '../../types/interfaces/ConfigRolesInterface'
import { NullRoleError } from '../../types/errors/NullRoleError'
export const hydrateRoles = (
guild: Guild,
roles: ConfigRoleInterface
): LiveConfigRoleInterface => {
// Initialize the hydrated roles object
const hydrated: LiveConfigRoleInterface = {}
// For each role ID in roles, find the role object in the guild and add it to the hydrated object
for (const role of Object.keys(roles)) {
// Resolve the channel from the guild
hydrated[role] = guild.roles.resolve(roles[role])
// Throw an error if it doesn't exist
if (hydrated[role] == null) {
throw new NullRoleError(
'Hydration',
`A role is null (${role}:${roles[role]})`
)
}
}
return hydrated
}
|
1203f3b93437aed379e42b7699735028bdf87b6b
|
TypeScript
|
nasum/todo-tools
|
/packages/todo-cli/src/commands/archive.ts
| 2.546875
| 3
|
import commander from 'commander'
import { Config } from '../config'
import { ConfigUtil } from '../lib/configUtil'
import { ToDoTextFileOperator } from '../lib/fileOperator'
import { displayTodo } from '../lib/displayTerminal'
export function makeArchiveCommand(config: Config): commander.Command {
const cUtil = new ConfigUtil(config)
const operator = new ToDoTextFileOperator(cUtil)
const archive = commander
.command('archive')
.description('archive todo text')
.action(async () => {
await operator.archive()
const todoList = await operator.getToDoList()
displayTodo(todoList)
})
return archive
}
|
cfeb66e8e36e0cbc9b7fcd1c316688eb53881f0d
|
TypeScript
|
pengyuenhao/EatFoodGame
|
/TypeScriptProject/assets/scripts/project/util/TouchUtil.ts
| 2.953125
| 3
|
import {Singleton} from "./Singleton";
import { IUtil } from "./Util";
export class TouchUtil extends Singleton implements IUtil{
private areaMap;
//全局区域状态
private globalAreaStatus : AreaStatus;
onConstructor(){
this.areaMap = new Map();
}
/**
* 注册一个触摸区域,只有在区域内的触控才会被识别
* @param area 区域
* @param isGlobal 是否设为全局区域
*/
public registerTouchArea(area: cc.Node,isGlobal:boolean = false) {
let areaStatus;
//尝试获取对应的区域状态
if(this.areaMap.has(area)){
areaStatus = this.areaMap.get(area);
}else{
areaStatus = new AreaStatus();
this.areaMap.set(area,areaStatus);
}
//设定全局区域
if(isGlobal)this.globalAreaStatus = areaStatus;
//触摸开始时
area.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventTouch) => {
let touches = event.getTouches();
touches.forEach((touch: cc.Touch) => {
let sPosX = touch.getLocationX();
let sPoxY = touch.getLocationY();
let status = new TouchStatus();
status.direction = TouchDirection.No;
status.touch = touch;
status.sPosX = sPosX;
status.sPosY = sPoxY;
status.totalX = 0;
status.totalY = 0;
status.trendX = 0;
status.trendY = 0;
//绑定触摸ID到状态
areaStatus.touchMap.set(touch.getID(), status)
});
});
//触摸移动时
area.on(cc.Node.EventType.TOUCH_MOVE, (event: cc.Event.EventTouch) => {
let touches = event.getTouches();
touches.forEach((touch: cc.Touch) => {
if (areaStatus.touchMap.has(touch.getID())) {
let status: TouchStatus = areaStatus.touchMap.get(touch.getID());
let mDeltaX = touch.getDelta().x;
let mDeltaY = touch.getDelta().y;
status.totalX += mDeltaX;
status.totalY += mDeltaY;
//如果触摸正在向左移动
if (Math.abs(mDeltaX) > 10) {
status.trendX += status.totalX / mDeltaX;
}
if (Math.abs(mDeltaY) > 10) {
status.trendY += status.totalY / mDeltaY;
}
//如果触摸的长度超过10000则判断划动超长了
if((status.totalX*status.totalX+status.totalY*status.totalY)>10000){
this.disposeTouchResult(areaStatus,touch);
}
}
});
});
//触摸结束时
area.on(cc.Node.EventType.TOUCH_END, (event: cc.Event.EventTouch) => {
let touches = event.getTouches();
touches.forEach((touch: cc.Touch) => {
if (areaStatus.touchMap.has(touch.getID())) {
this.disposeTouchResult(areaStatus,touch);
}
});
});
//触摸取消时
area.on(cc.Node.EventType.TOUCH_CANCEL, (event: cc.Event.EventTouch) => {
let touches = event.getTouches();
touches.forEach((touch: cc.Touch) => {
if (areaStatus.touchMap.has(touch.getID())) {
this.disposeTouchResult(areaStatus,touch);
}
});
});
}
//执行触控结果
disposeTouchResult(areaStatus,touch){
//判断当前触摸正处于什么状态
let result : TouchStatus= areaStatus.touchMoveDetection(touch);
if(result&&areaStatus.touchEvnet[result.direction]){
areaStatus.touchEvnet[result.direction].forEach(event => {
if(event && typeof event ==="function"){
//告知结果和触摸信息
event(result);
}
});
}
//移除结束的触摸
areaStatus.touchMap.delete(touch.getID());
}
/**
* 注册指定的回调函数
* @param direction 方向
* @param callback 返回一个触控事件
*/
public on<T extends Function>(direction: TouchDirection, callback: T, area?: cc.Node) : T{
let areaStatus;
if(area&&this.areaMap.has(area)){
areaStatus = this.areaMap.get(area);
}else{
areaStatus = this.globalAreaStatus;
}
//增加回调函数
if(!areaStatus.touchEvnet[direction]){
areaStatus.touchEvnet[direction] = [];
}
areaStatus.touchEvnet[direction].push(callback);
return callback;
}
}
//区域状态
class AreaStatus{
public touchEvnet;
//触摸状态映射
public touchMap;
constructor(){
this.touchMap = new Map();
this.touchEvnet = [];
}
//触摸移动检测
touchMoveDetection(touch: cc.Touch){
if (this.touchMap.has(touch.getID())) {
let status: TouchStatus = this.touchMap.get(touch.getID());
//检查是否为有效触摸
let isMoveValid = false;
//触摸的方向,按照上下左右的顺序排列
let direction : TouchDirection= TouchDirection.No;
//如果移动的总距离超过10
if (Math.abs(status.totalX) > 10 || Math.abs(status.totalY) > 10) {
//趋势不都为0时
if (status.trendX != 0 || status.trendY != 0) {
//检查移动的趋势
if (status.trendX === 0) {
isMoveValid = true;
//检查总移动距离
if (status.totalY > 0) {
direction = TouchDirection.Up;
} else {
direction = TouchDirection.Down;
}
} else {
let trend = status.totalX / status.totalY;
//在X轴移动趋势不为0的情况下,检查移动趋势是否达到有效判断范围内
if (Math.abs(trend) > 1) {
//有效的触摸轨迹
isMoveValid = true;
//X轴方向向右移动
if (status.totalX > 0) {
direction = TouchDirection.Right;
} else {
direction = TouchDirection.Left;
}
}
}
//如果之前的检查没有通过
if (!isMoveValid) {
if (status.trendY === 0) {
isMoveValid = true;
if (status.totalY > 0) {
direction = TouchDirection.Right;
} else {
direction = TouchDirection.Left;
}
} else {
let trend = status.totalY / status.totalX;
if (Math.abs(trend) > 1) {
//有效的触摸轨迹
isMoveValid = true;
//Y轴方向向上移动
if (status.totalY > 0) {
direction = TouchDirection.Up;
} else {
direction = TouchDirection.Down;
}
}
}
}
}
}
//如果之前的检查判断为无效则表明没有发生移动
if (isMoveValid) {
switch (direction) {
case TouchDirection.No:
status.direction = TouchDirection.No;
return status;
case TouchDirection.Up:
status.direction = TouchDirection.Up;
return status;
case TouchDirection.Down:
status.direction = TouchDirection.Down;
return status;
case TouchDirection.Left:
status.direction = TouchDirection.Left;
return status;
case TouchDirection.Right:
status.direction = TouchDirection.Right;
return status;
}
} else {
status.direction = TouchDirection.No;
return status;
}
}else{
return null;
}
}
}
//传递触摸状态
export class TouchStatus {
//触摸
public touch : cc.Touch;
//方向
public direction : TouchDirection;
/**
* 触摸开始的X坐标
*/
public sPosX: number;
/**
* 触摸开始的Y坐标
*/
public sPosY: number;
/**
* 最后一次的X坐标
*/
public lPosX: number;
/**
* 最后一次的Y坐标
*/
public lPosY: number;
/**
* X轴移动总距离
*/
public totalX: number;
/**
* Y轴移动总距离
*/
public totalY: number;
/**
* 触摸的总时间
*/
public totalTime: number;
/**
* 趋向于X轴方向移动
*/
public trendX;
/**
* 趋向于Y轴方向移动
*/
public trendY;
}
export enum TouchDirection{
No = -1,
Up = 0,
Down = 1,
Left = 2,
Right = 3
}
|
56de4fb087e55253165517897195075083e41341
|
TypeScript
|
wacul/gaxd
|
/src/source.ts
| 2.703125
| 3
|
import {expose} from "./expose";
export interface IframeSourceParams {
element?: HTMLIFrameElement;
selector?: string;
trackingName?: string;
destinationOrigin : string;
}
export interface RedirectSourceParams {
origins : string[];
trackingName?: string;
openOptions?: {
windowName: string;
windowFeature?: string;
}
}
async function wait(ms : number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getClientId(name?: string) {
if (name) {
return ga
.getByName(name)
.get("clientId");
} else {
return new Promise((resolve, reject) => {
ga(tracker => {
if (tracker) {
const clientId = tracker.get("clientId");
clientId && resolve(clientId);
return;
}
reject(new Error("no clientId"));
});
})
}
}
async function sendClientId(destinationWindow : Window, clientId : string, origin : string, timeout = 30000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const intervalId = setInterval(function send() {
destinationWindow.postMessage({
clientId
}, origin);
if (Date.now() - startTime > timeout) {
clearInterval(intervalId);
window.removeEventListener("message", recieve);
reject(new Error("timeout: sendClientId"));
}
}, 100);
function recieve(ev : MessageEvent) {
if (!ev.data || ev.data.clientId !== clientId)
return;
clearInterval(intervalId);
window.removeEventListener("message", recieve);
resolve();
}
window.addEventListener("message", recieve);
});
}
async function findIframe(selector : string, timeout = 5000) {
let time = 0;
while (time < timeout) {
const el = document.querySelector(selector);
if (el)
return el as HTMLIFrameElement;
await wait(100);
time += 100;
}
throw new Error("no iframe");
}
export async function iframe(params : IframeSourceParams) {
let element : HTMLIFrameElement | undefined;
if (params.element instanceof HTMLIFrameElement) {
element = params.element;
} else if (params.selector) {
element = await findIframe(params.selector);
}
if (!element)
throw new Error("no iframe");
return sendClientId(element.contentWindow as Window, await getClientId(params.trackingName), params.destinationOrigin);
}
function getAnchorElement(element?: HTMLElement) : HTMLAnchorElement | undefined {
while(element) {
if (element.nodeName === "A")
return element as HTMLAnchorElement;
element = element.parentElement as HTMLElement;
}
}
function getTargetOrigin(element : HTMLAnchorElement, origins : string[]) {
for (let i = 0; i < origins.length; ++i) {
if (element.href.indexOf(origins[i]) !== -1)
return origins[i];
}
}
export async function redirect(params : RedirectSourceParams) {
const clientId = await getClientId(params.trackingName);
document.addEventListener("click", ev => {
const element = getAnchorElement(ev.target as HTMLElement);
if (!element)
return;
const targetOrigin = getTargetOrigin(element, params.origins);
if (!targetOrigin)
return;
ev.preventDefault();
const w = params.openOptions
? window.open(element.href, params.openOptions.windowName, params.openOptions.windowFeature)
: window.open(element.href);
sendClientId(w as Window, clientId, targetOrigin);
});
}
expose("gaxd.source.iframe", iframe);
expose("gaxd.source.redirect", redirect);
|
6bc3d8ace8769938891491ad7b301f3de94ecc19
|
TypeScript
|
mmcclimon/synergy-js
|
/src/channels/slack.ts
| 2.65625
| 3
|
import BaseChannel from './base';
import SynergyEvent from '../event';
import SlackClient from '../slack-client';
import Logger from '../logger';
export default class SlackChannel extends BaseChannel {
private targetedRegex: RegExp;
slack: SlackClient;
constructor(arg) {
super(arg);
this.slack = new SlackClient(arg.apiToken);
}
async start(): Promise<void> {
await this.slack.connect();
this.slack.ws.on('message', data => this.handleFrame(data));
}
handleFrame(data): void {
if (!data) return;
const slackEvent = JSON.parse(data);
switch (slackEvent.type) {
case 'hello':
this.slack.setUp();
break;
case 'message':
this.handleMessage(slackEvent);
break;
default:
// do nothing
return;
}
}
handleMessage(slackEvent): void {
if (!this.slack.isReady) {
Logger.info('ignoring Slack message; slack client not fully set up');
return;
}
if (slackEvent.subtype) {
// TODO: do respond to /me messages
Logger.info(`ignoring slack event with subtype ${slackEvent.subtype}`);
return;
}
if (slackEvent.bot_id) return;
const event = this.synergyEventFromSlackEvent(slackEvent);
if (!event) {
Logger.warn([
"couldn't convert a %s/%s message to channel %s, dropping it",
slackEvent.type,
slackEvent.subtype ? slackEvent.subType : '[none]',
slackEvent.channel,
]);
return;
}
this.hub.handleEvent(event);
}
synergyEventFromSlackEvent(slackEvent): SynergyEvent {
const privateAddr = slackEvent.channel.startsWith('G')
? slackEvent.channel
: this.slack.dmChannelForAddress(slackEvent.user);
if (!privateAddr) return;
const fromUser = this.hub.userDirectory.userByChannelAndAddress(
this.name,
slackEvent.user
);
let text = this.decodeSlackFormatting(slackEvent.text);
let wasTargeted = false;
if (!this.targetedRegex) {
const me = this.slack.ourName;
this.targetedRegex = new RegExp(`^@?(${me})(?=\\W):?\\s*`, 'i');
}
if (this.targetedRegex.test(text)) {
text = text.replace(this.targetedRegex, '');
wasTargeted = true;
}
// Only public channels public.
// Everything is targeted if it's sent in direct message.
const isPublic = /^C/.test(slackEvent.channel);
if (/^D/.test(slackEvent.channel)) {
wasTargeted = true;
}
return new SynergyEvent({
type: 'message',
text: text,
wasTargeted: wasTargeted,
isPublic: isPublic,
fromChannel: this,
fromAddress: slackEvent.user,
fromUser: fromUser,
transportData: slackEvent,
conversationAddress: slackEvent.channel,
});
}
decodeSlackFormatting(text: string): string {
const usernameFor = (id: string): string => this.slack.username(id);
// Usernames: <@U123ABC>
text = text.replace(/<@(U[A-Z0-9]+)>/g, (_, $1) => '@' + usernameFor($1));
// Channels: <#C123ABC|bottest>
text = text.replace(/<#[CD](?:[A-Z0-9]+)\|(.*?)>/g, (_, $1) => '#' + $1);
// mailto: mailto:foo@bar.com|foo@bar.com (no surrounding brackets)
text = text.replace(/mailto:\S+?\|/g, '');
// "helpful" url formatting: <https://example.com|example.com>; keep what
// user actually typed
text = text.replace(/<([^>]+)>/g, (_, $1) => $1.replace(/^.*\|/, ''));
// Anything with < and > around it is probably a URL at this point so remove
// those
text = text.replace(/[<>]/g, '');
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/&/g, '&');
return text;
}
sendMessage(target, text): void {
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/&/g, '&');
this.slack.sendMessage(target, text);
}
}
|
e4b57f16ee5acdb6b20b3d9cce68310c248b0954
|
TypeScript
|
ubatsukh/ubatsukh.github.io
|
/blendlayer/app/BlendLayer.ts
| 2.65625
| 3
|
// The `///amd-dependency ...` allows us to import AMD modules and provide a name
// for them in the compiled JS. TypeScript relies on some helpers for building
// classes. JS API disabled the option for TypeScript to automatically generate these
// for us. So we import them as we create a class, mainly `__extends` and `__decorate`.
/// <amd-dependency path="esri/core/tsSupport/declareExtendsHelper" name="__extends" />
/// <amd-dependency path="esri/core/tsSupport/decorateHelper" name="__decorate" />
import Deferred = require("dojo/Deferred");
import { subclass, property, declared } from "esri/core/accessorSupport/decorators";
import TileLayer = require("esri/layers/TileLayer");
import BaseTileLayer = require("esri/layers/BaseTileLayer");
@subclass("esri.layers.BlendLayer")
class BlendLayer extends declared(BaseTileLayer) {
// Derived classes that contain constructor functions must call
// super() which will execute the constructor function on the base
// class.
// If you have a constructor in your class then you must call
// the parent constructor from your constructor.
// This ensures that the stuff that it needs to set on this gets set.
// Followed by the call to super you can add any additional stuff you want
// to do in your constructor.
constructor(options: any) {
super();
}
@property()
multiplyLayers: TileLayer[] = [];
load(): any {
// call load method on each tile layer stored in multiple property
this.multiplyLayers.forEach(function (layer) {
// The tile layers must load() prior to the BlendLayer
// resolving and moving to the "loaded" status.
this.addResolvingPromise(layer.load());
}, this);
}
// Fetches the tile(s) visible in the view
fetchTile(level: number, row: number, col: number): IPromise<HTMLCanvasElement> {
const tilePromises = this.multiplyLayers.map(layer => {
// calls fetchTile() on the tile layers returned in multiplyLayers property
// for the tiles visible in the view
return layer.fetchTile(level, row, col, { allowImageDataAccess: true });
});
return all(tilePromises)
.then(images => {
// create a canvas
let width = this.tileInfo.size[0];
let height = this.tileInfo.size[0];
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
// multiply - multiplies the numbers for each pixel of the top layer (nat geo)
// with the corresponding pixel for the bottom layer (hillshade).
context.globalCompositeOperation = "multiply";
images.forEach(function (image) {
context.drawImage(image, 0, 0, width, height);
});
return canvas;
});
}
}
export = BlendLayer;
/***************************************/
/* End of the BlendLayer code */
/***************************************/
// https://searchcode.com/codesearch/view/50023473/
// This function takes multiple promises and returns
// a new promise that is fulfilled when all promises have
// been resolved or one has been rejected.
function all<T>(promises: IPromise<T>[]): IPromise<T[]> {
const dfd = new Deferred();
const results: T[] = [];
promises = promises.slice();
let waiting = promises.length;
promises.forEach(promise => {
promise.then(result => {
const index = promises.indexOf(promise);
results[index] = result;
promises.slice(index, 1);
if (!promises || !promises.length) {
dfd.resolve(results);
}
if (!dfd.isFulfilled()) {
results[index] = result;
if (--waiting === 0) {
dfd.resolve(results);
}
}
else{
dfd.reject();
}
});
});
return dfd.promise as any;
}
|
207fa1d2547a46681c021c5c7ec1c7c7aae0f359
|
TypeScript
|
gatsbyjs/gatsby
|
/packages/gatsby/src/utils/slices/stitching.ts
| 2.9375
| 3
|
import * as path from "path"
import * as fs from "fs-extra"
import { generateHtmlPath } from "gatsby-core-utils/page-html"
interface ISliceBoundaryMatch {
index: number
end: number
syntax: "element" | "comment"
id: string
type: "start" | "end"
}
function ensureExpectedType(maybeType: string): "start" | "end" {
if (maybeType === `start` || maybeType === `end`) {
return maybeType
} else {
throw new Error(`Unexpected type: ${maybeType}. Expected "start" or "end"`)
}
}
async function stitchSlices(
htmlString: string,
publicDir: string
): Promise<string> {
let previousStart: ISliceBoundaryMatch | undefined = undefined
let processedHTML = ``
let cursor = 0
async function getSliceContent(sliceHtmlName: string): Promise<string> {
return fs.readFile(
path.join(publicDir, `_gatsby`, `slices`, `${sliceHtmlName}.html`),
`utf-8`
)
}
for (const match of htmlString.matchAll(
/(<slice-(?<startOrEndElementOpenening>start|end)\s[^>]*id="(?<idElement>[^"]+)"[^>]*><\/slice-(?<startOrEndElementClosing>[^>]+)>|<!-- slice-(?<startOrEndComment>start|end) id="(?<idComment>[^"]+)" -->)/g
)) {
if (!match.groups) {
throw new Error(
`Invariant: [stitching slices] Capturing groups should be defined`
)
}
if (typeof match.index !== `number`) {
throw new Error(
`Invariant: [stitching slices] There is no location of a match when stitching slices`
)
}
if (
match.groups.startOrEndElementOpenening &&
match.groups.startOrEndElementOpenening !==
match.groups.startOrEndElementClosing
) {
throw new Error(
`Invariant: [stitching slices] start and end tags should be the same. Got: Start: ${match.groups.startOrEndElementOpenening} End: ${match.groups.startOrEndElementClosing}`
)
}
const meta: ISliceBoundaryMatch = {
index: match.index,
end: match.index + match[0].length,
...(match.groups.startOrEndElementOpenening
? {
syntax: `element`, // can discard this field
id: match.groups.idElement,
type: ensureExpectedType(match.groups.startOrEndElementOpenening),
}
: {
syntax: `comment`, // can discard this field
id: match.groups.idComment,
type: ensureExpectedType(match.groups.startOrEndComment),
}),
}
if (meta.type === `start`) {
if (previousStart) {
// if we are already in a slice, we will replace everything until the outer slice end
// so we just ignore those
continue
}
const newCursor = meta.end
processedHTML +=
htmlString.substring(cursor, meta.index) +
`<!-- slice-start id="${meta.id}" -->`
cursor = newCursor
previousStart = meta
} else if (meta.type === `end`) {
if (!previousStart) {
throw new Error(
`Invariant: [stitching slices] There was no start tag, but close tag was found`
)
}
if (previousStart.id !== meta.id) {
// it's possible to have nested slices - we want to handle just the most outer slice
// as stitching it in will recursively handle nested slices as well
continue
}
processedHTML += `${await stitchSlices(
await getSliceContent(meta.id),
publicDir
)}<!-- slice-end id="${meta.id}" -->`
cursor = meta.end
previousStart = undefined
}
}
if (previousStart) {
throw new Error(
`Invariant: [stitching slices] There was start tag, but no close tag was found`
)
}
// get rest of the html
processedHTML += htmlString.substring(cursor)
return processedHTML
}
export async function stitchSliceForAPage({
pagePath,
publicDir,
}: {
pagePath: string
publicDir: string
}): Promise<void> {
const htmlFilePath = generateHtmlPath(publicDir, pagePath)
const html = await fs.readFile(htmlFilePath, `utf-8`)
const processedHTML = await stitchSlices(html, publicDir)
if (html !== processedHTML) {
await fs.writeFile(htmlFilePath, processedHTML)
}
}
|
e6bd1268cfee7f584fae9a0ee863d96dd350bbfc
|
TypeScript
|
tmcw/graphql-code-generator
|
/packages/plugins/other/visitor-plugin-common/src/mappers.ts
| 2.796875
| 3
|
import { RawResolversConfig, ParsedResolversConfig } from './base-resolvers-visitor';
export type ParsedMapper = InternalParsedMapper | ExternalParsedMapper;
export interface InternalParsedMapper {
isExternal: false;
type: string;
}
export interface ExternalParsedMapper {
isExternal: true;
type: string;
import: string;
source: string;
default: boolean;
}
export function isExternalMapperType(m: ParsedMapper): m is ExternalParsedMapper {
return !!m['import'];
}
export function parseMapper(mapper: string, gqlTypeName: string | null = null): ParsedMapper {
if (isExternalMapper(mapper)) {
const items = mapper.split('#');
const isNamespace = items.length === 3;
const source = items[0];
let type,
importElement,
asDefault = false;
if (isNamespace) {
const ns = items[1];
type = `${ns}.${items[2]}`;
importElement = ns;
} else {
const namedDefault = items[1].includes('default as');
asDefault = items[1] === 'default';
if (asDefault || namedDefault) {
type = `${gqlTypeName}`;
importElement = namedDefault ? `default as ${gqlTypeName}` : `${gqlTypeName}`;
} else {
if (items[1].includes(' as ')) {
const [importedType, aliasType] = items[1].split(' as ');
type = aliasType;
importElement = `${importedType} as ${aliasType}`;
} else {
type = items[1];
importElement = items[1];
}
}
}
return {
default: asDefault,
isExternal: true,
source,
type,
import: importElement.replace(/<(.*)>/, ''),
};
}
return {
isExternal: false,
type: mapper,
};
}
export function isExternalMapper(value: string): boolean {
return value.includes('#') && !value.includes('"') && !value.includes('\'');
}
export function transformMappers(rawMappers: RawResolversConfig['mappers']): ParsedResolversConfig['mappers'] {
const result: ParsedResolversConfig['mappers'] = {};
Object.keys(rawMappers).forEach(gqlTypeName => {
const mapperDef = rawMappers[gqlTypeName];
const parsedMapper = parseMapper(mapperDef, gqlTypeName);
result[gqlTypeName] = parsedMapper;
});
return result;
}
|
be0247253538a94bdab44c2d75513bd95dcc3083
|
TypeScript
|
smulhall1337/JhipsterCRM
|
/src/main/webapp/app/shared/model/contact-sub-status.model.ts
| 2.6875
| 3
|
export interface IContactSubStatus {
id?: number;
name?: string;
subTypeOfName?: string;
subTypeOfId?: number;
}
export class ContactSubStatus implements IContactSubStatus {
constructor(public id?: number, public name?: string, public subTypeOfName?: string, public subTypeOfId?: number) {}
}
|
2e54290d2374ed55beb58b644829fe8183246366
|
TypeScript
|
input-output-hk/cardano-js-sdk
|
/packages/ogmios/src/Ogmios/TxSubmissionClient.ts
| 2.515625
| 3
|
import { InteractionContext, TxSubmission, ensureSocketIsOpen, safeJSON } from '@cardano-ogmios/client';
import { Ogmios, TxId } from '@cardano-ogmios/schema';
import { WebSocket } from '@cardano-ogmios/client/dist/IsomorphicWebSocket';
import { baseRequest } from '@cardano-ogmios/client/dist/Request';
import { nanoid } from 'nanoid';
/**
* See also {@link createTxSubmissionClient} for creating a client.
*/
export interface TxSubmissionClient {
context: InteractionContext;
submitTx: (bytes: string) => Promise<TxId>;
shutdown: () => Promise<void>;
}
/**
* Waits for a response with the reflection property requestId matching the one we send in the mirror
* property of the request.
*
* @param socket The websocket object.
* @param requestId The requestId, this will be used to filter our response.
* @param resolve The original promise resolve callback.
* @param reject The original promise reject callback.
*/
const waitForResponse =
(
socket: WebSocket,
requestId: string,
resolve: { (value: string | PromiseLike<string>): void; (arg0: string): void },
reject: { (reason?: never): void; (arg0: Error[]): void }
) =>
(message: string) => {
const submitTxRes: Ogmios['SubmitTxResponse'] = safeJSON.parse(message);
if ((submitTxRes.type as string) !== 'jsonwsp/fault' && submitTxRes.methodname !== 'SubmitTx') {
return;
}
if (!submitTxRes.reflection || submitTxRes.reflection.requestId !== requestId) return;
// This is the response we are waiting for, we can unregister our callback from the socket.
socket.removeListener('message', waitForResponse(socket, requestId, resolve, reject));
const response = TxSubmission.handleSubmitTxResponse(submitTxRes);
if (TxSubmission.isTxId(response)) {
resolve(response);
} else {
reject(response);
}
};
/**
* Create a client for submitting signed transactions to underlying Cardano chain.
*/
export const createTxSubmissionClient = async (context: InteractionContext): Promise<TxSubmissionClient> =>
Promise.resolve({
context,
shutdown: () =>
new Promise((resolve) => {
ensureSocketIsOpen(context.socket);
context.socket.once('close', resolve);
context.socket.close();
}),
submitTx: async (bytes) => {
ensureSocketIsOpen(context.socket);
const requestId = nanoid(5);
return new Promise<string>((resolve, reject) => {
context.socket.on('message', waitForResponse(context.socket, requestId, resolve, reject));
context.socket.send(
safeJSON.stringify({
...baseRequest,
args: { submit: bytes },
methodname: 'SubmitTx',
mirror: { requestId }
} as Ogmios['SubmitTx'])
);
});
}
} as TxSubmissionClient);
|
c0d7a049fa1db8150e598f1580ca8bb9568ff5e4
|
TypeScript
|
hota1024/nekochat-server
|
/src/ma/index.ts
| 2.671875
| 3
|
import axios from 'axios'
import xml from 'fast-xml-parser'
export interface MaWord {
surface: string
reading: string
pos: string
baseform: string
}
export interface MaResult {
total_count: number
filltered_count: number
word_list: { word: MaWord | MaWord[] }
}
export interface ParseResult {
ResultSet: {
ma_result: MaResult
}
}
/**
* Ma client.
*/
export class MaClient {
/**
* Ma client consturctor.
*
* @param appId
*/
constructor(private appId: string) {}
/**
* Parse sentence.
*
* @param sentence
*/
async parse(sentence: string): Promise<ParseResult> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data } = await axios.get<any>(
`https://jlp.yahooapis.jp/MAService/V1/parse`,
{
params: {
sentence,
appid: this.appId
}
}
)
const result = xml.parse(data) as ParseResult
return result
}
}
|
8f6a7ca53ed11b24fc983da5d94c99901c6594c9
|
TypeScript
|
suncoast-devs/nexus
|
/src/components/models/Assignment.ts
| 2.765625
| 3
|
import { Attr, Model, BelongsTo, HasMany } from 'spraypaint'
import { AssignmentEvent, Homework, Person, StudentEnrollment } from '.'
import { ApplicationRecord } from './ApplicationRecord'
export type ScoreInfoType = {
generateGif: boolean
title: string
progressReportTitle?: string
style: {
iconColor: string
buttonColor: string
textColor: string
progressReportTextColor?: string
progressReportBackgroundColor?: string
}
}
@Model()
export class Assignment extends ApplicationRecord {
static jsonapiType = 'assignments'
@Attr() score!: number
@Attr() issue!: number
@Attr() personId!: string
@Attr() studentEnrollmentId!: string
@Attr() homeworkId!: string
@Attr() turnedIn!: boolean
@Attr() createdAt!: string
@Attr() overdue!: string
@Attr() completed!: boolean
@BelongsTo() person!: Person
@BelongsTo() studentEnrollment!: StudentEnrollment
@BelongsTo() homework!: Homework
@HasMany() assignmentEvents!: AssignmentEvent[]
scoreInfo() {
return Assignment.scoreInfo(this.score)
}
static minimumAcceptableScore = 2
static graded(score: number) {
return score > 0
}
static needsGrade(score: number) {
return !Assignment.graded(score)
}
static scoreInfo(score: number | string) {
const scoreAsInt = Number(score)
return Assignment.graded(scoreAsInt) ? Assignment.scoreInfos[scoreAsInt] : Assignment.noScore
}
static noScore: ScoreInfoType = {
title: 'Not Graded',
progressReportTitle: 'Not Completed',
style: {
iconColor: 'black',
buttonColor: 'white',
textColor: 'black',
progressReportTextColor: 'white',
progressReportBackgroundColor: 'rgb(217, 83, 79)',
},
generateGif: false,
}
static scoreInfos: ScoreInfoType[] = [
{
title: 'Unacceptable',
style: {
iconColor: 'black',
buttonColor: 'white',
textColor: 'black',
progressReportTextColor: 'white',
progressReportBackgroundColor: 'rgb(217, 83, 79)',
},
generateGif: false,
},
{
title: 'Needs Improvement',
style: {
buttonColor: 'rgb(217, 83, 79)',
iconColor: 'rgb(217, 83, 79)',
textColor: 'white',
},
generateGif: false,
},
{
title: 'Acceptable',
style: {
buttonColor: 'rgb(240, 173, 78)',
iconColor: 'rgb(240, 173, 78)',
textColor: 'white',
},
generateGif: true,
},
{
title: 'Meets Expectation',
style: {
buttonColor: 'rgb(49, 176, 213)',
iconColor: 'rgb(49, 176, 213)',
textColor: 'white',
},
generateGif: true,
},
{
title: 'Exceeds Expectation',
style: {
buttonColor: 'rgb(51, 122, 183)',
iconColor: 'rgb(51, 122, 183)',
textColor: 'white',
},
generateGif: true,
},
]
}
|
d292774188c34e7ff56ac50fbbf2425677134211
|
TypeScript
|
anchan828/typeorm-helpers
|
/packages/transformers/src/utils.ts
| 3.171875
| 3
|
export function isNullOrUndefined<T>(obj: T | null | undefined): obj is null | undefined {
return typeof obj === "undefined" || obj === null;
}
|
630e7b18e5845350e07584e971713ccd379dba4f
|
TypeScript
|
wanghengwei/whitebox
|
/worker/activity.ts
| 3.40625
| 3
|
import { Observable } from "rxjs";
export interface Metadata {
type: string;
name: string;
}
// action 的返回值。
// 有些动作没有返回,比如sleep
// 业务act Result必须要能反映是否失败,如果失败,必须有失败信息;如果成功,需要有数据?。
export class ActionResult {
// // 动作基本信息
// // metadata: Metadata;
// // 错误信息。null表示没有错误
// error: any;
// constructor(public metadata: Metadata, err?: any) {
// // this.metadata = metadata;
// if (!err || err.ok) {
// this.error = null;
// } else {
// this.error = err;
// }
// }
// 一个动作的结果包含3个信息:
// 1. 是哪个动作
// 2. 调用的参数是啥
// 3. 结果是啥
constructor(public result: any, public action: any, public args: any) {}
ok(): boolean {
return !this.result.error;
}
}
export interface Activity {
parse(data: any): void;
// 每个act执行结果不一定是一个结果,因为有类似loop这种act存在。
proceed(ctx: any): Observable<ActionResult>;
}
|
6db086d8a30ce643fd93a252c3e6408d51743b5d
|
TypeScript
|
TimMaa/MA2018Typescript
|
/app/main.ts
| 4.1875
| 4
|
// Interface which implements a format for People
// This can be used just like a string identifier
interface Person {
firstName: string;
lastName: string;
}
class Student {
person: Person;
age: number;
constructor(private _person: Person, private _age: number){
this.person = _person;
this.age = _age;
}
}
// To make sure that the greeting will only be a string, the only type the function can return is a string
// To make sure only strings will be used to fill the greeting, person gets the type string
function generateGreeting(person: string): string {
return `Hello ${person}`;
}
function greet() {
// The same goes for the input field, as it should always be an input element
let input: HTMLInputElement = <HTMLInputElement>document.getElementById('input-username');
// The following line would not work because the Element is not necessarily casted as a Input Element
// input = document.getElementById('input-username');
document.getElementById('greeting').innerHTML = generateGreeting(input.value);
}
function greetWarningWrongType1() {
// The following line is a violation of the type and shows a warning
// the value which is assigned to the input variable is not necessarily a HTMLInputElement and therefore may be wrong
// and cause issues on runtime. TypeScript warns against this.
let input: HTMLInputElement = document.getElementById('input-username');
// This will work anyway, because after compiling to js the types do not matter
document.getElementById('greeting').innerHTML = generateGreeting(input.value);
}
function greetWarningWrongType2() {
let stringArray: string[] = ["1","2","3"];
// The following line is a violation of the type and shows a warning
// the value which is given to the generateGreeting function is not a String and therefore may be wrong
// and cause issues on runtime. TypeScript warns against this.
document.getElementById('greeting').innerHTML = generateGreeting(stringArray);
}
function displayStudent(){
// Get all the values from the InputElements
let iFName: string = (<HTMLInputElement>document.getElementById('input-student-firstname')).value;
let iLName: string = (<HTMLInputElement>document.getElementById('input-student-lastname')).value;
let iAge: number = Number((<HTMLInputElement>document.getElementById('input-student-age')).value);
// Generate a student with the values from the InputElements by using the generateStudent-Method
let nStudent: Student = generateStudent(iFName, iLName, iAge);
// Write the student information in the correct field
document.getElementById('student-info').innerText =
nStudent.person.firstName + " " + nStudent.person.lastName + ", " + nStudent.age;
}
function generateStudent(fName: string, lName: string, sAge: number){
// Use the Person interface to generate a variable in the format for people
let sPerson: Person = {firstName: fName, lastName: lName};
// Create a new Student with the constructor of the class Student
return new Student(sPerson, sAge)
}
|
387c2d39b5a669f20d889168f42b0c2531c46de7
|
TypeScript
|
avadavat/truth-fiddle
|
/src/util/generateUrlFromQuery.ts
| 3.03125
| 3
|
// Given a query string, like 'p and q', returns the url
// 'truthfiddle.com?q=p%20and%20q'.
// Appends the ?q parameter to the base url and then URI encodes the string.
export function generateUrlFromQuery(query: string): string {
const baseURL = window.location.host;
const url = baseURL + '?q=' + query;
return encodeURI(url);
}
|
5b6bf57bc7ed0b853124353fe61fea5f68b0245f
|
TypeScript
|
fetzi/php-file-types
|
/src/extension.ts
| 2.734375
| 3
|
'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { Namespace }from './namespace';
let ns = new Namespace();
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('"php-file-types" is now active!');
context.subscriptions.push(vscode.commands.registerCommand('phpfiletypes.createFile', createFile));
context.subscriptions.push(vscode.commands.registerCommand('phpfiletypes.createClass', createClass));
context.subscriptions.push(vscode.commands.registerCommand('phpfiletypes.createInterface', createInterface));
context.subscriptions.push(vscode.commands.registerCommand('phpfiletypes.createTrait', createTrait));
}
function createFile(args) {
promptForFilename(args, 'file');
}
function createClass(args) {
promptForFilename(args, 'class');
}
function createInterface(args) {
promptForFilename(args, 'interface');
}
function createTrait(args) {
promptForFilename(args, 'trait');
}
function promptForFilename(args, type: string) {
let currentPath: string = vscode.workspace.rootPath;
if (args && args._fsPath) {
currentPath = args._fsPath;
}
if (!fs.lstatSync(currentPath).isDirectory()) {
currentPath = path.dirname(currentPath);
}
currentPath += '/';
vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: 'Please enter the PHP ' + type + ' name',
value: currentPath,
valueSelection: [currentPath.length, currentPath.length]
}).then((filePath) => {
if (!filePath) {
return;
}
if (!filePath.endsWith('.php')) {
filePath += '.php';
}
if (fs.existsSync(filePath)) {
vscode.window.showErrorMessage('The file "' + path.basename(filePath) + '" already exists');
}
path.dirname(filePath).split('/').reduce((currentPath, folder) => {
currentPath += folder + '/';
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
return currentPath;
}, '');
if (type !== 'file') {
let name = path.basename(filePath).replace('.php', '');
ns.getNamespace(filePath, type).then((namespace) => {
createFileByType(type, filePath, namespace, name);
});
} else {
createFileByType(type, filePath);
}
});
}
function createFileByType(type: string, filePath: string, namespace?: string, name?: string) {
let templateFile = type === 'file' ? 'file.tmpl' : 'type.tmpl';
let templateFilePath = vscode.extensions.getExtension('fetzi.php-file-types').extensionPath + '/templates/' + templateFile;
vscode.workspace.openTextDocument(templateFilePath).then((doc: vscode.TextDocument) => {
let template = doc.getText();
template = template.replace('${type}', type);
template = template.replace('${namespace}', namespace);
template = template.replace('${name}', name);
let cursor = findCursor(template);
template = template.replace('${cursor}', '');
fs.writeFileSync(filePath, template);
vscode.workspace.openTextDocument(filePath).then((doc: vscode.TextDocument) => {
vscode.window.showTextDocument(doc).then((editor) => {
editor.selection = new vscode.Selection(cursor, cursor);
});
});
});
}
function findCursor(template: string) {
let beforeCursor = template.substring(0, template.indexOf('${cursor}'));
let line = beforeCursor.match(/\n/g).length;
let char = beforeCursor.substr(beforeCursor.lastIndexOf('\n')).length;
return new vscode.Position(line, char);
}
// this method is called when your extension is deactivated
export function deactivate() {
}
|
c148a242865cacb5d31a1d0ccc25bbccbd96f9d8
|
TypeScript
|
Karin001/ng-series-study
|
/src/app/pages/angular/form/reactive-form/reactive-form.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, FormArray } from '@angular/forms';
@Component({
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.less']
})
export class ReactiveFormComponent implements OnInit {
constructor(private formBuilder: FormBuilder) { }
demo1Group: FormGroup;
userGroup: FormGroup;
userGroup2: FormGroup;
hobbyForm: FormGroup;
ngOnInit() {
this.demo1Group = new FormGroup({
'demo1Value': new FormControl()
});
this.userGroup = new FormGroup({
personalGroup: new FormGroup({
'userName': new FormControl('', [Validators.required])
}),
schoolGroup: new FormGroup({
'collegePlace': new FormControl('', [Validators.required, Validators.minLength(4)])
})
});
this.userGroup2 = new FormGroup({
personalGroup: new FormGroup({
'userName': new FormControl('', [Validators.required])
}),
schoolGroup: new FormGroup({
'collegePlace': new FormControl('', [Validators.required, Validators.minLength(4)])
})
});
this.hobbyForm = this.formBuilder.group({
hobby: this.formBuilder.array([
this.formBuilder.control('', [Validators.required])
])
});
}
get hobbies() {//获取FormArray对象
return this.hobbyForm.get('hobby') as FormArray;
}
addHobby() {//添加新项
this.hobbies.push(this.formBuilder.control('', [Validators.required]));
}
hobbyResult = [];
getHobbies() {
this.hobbyResult = [];
for (let i = 0; i < this.hobbies.length; i++) {
const value = this.hobbies.get(i.toString()).value;
this.hobbyResult.push(value);
}
}
result;
updateDemo1Value() {
this.demo1Group.get('demo1Value').setValue('Eve');
}
getDemo1Value() {
this.result = this.demo1Group.get('demo1Value').value;
}
code1 = `
<form [formGroup]="demo1Group">
<input formControlName="demo1Value" nz-input placeholder="尝试输入值">
<button (click)="updateDemo1Value()" nz-button nzType="primary">设置值</button>
<button (click)="getDemo1Value()" nz-button nzType="primary">取得值</button>
<br/>
你输入的值为:{{result}}
</form>
`;
code2 = `
this.demo1Group = new FormGroup({
'demo1Value': new FormControl()
});
result;
updateDemo1Value() {
this.demo1Group.get('demo1Value').setValue('Eve');
}
getDemo1Value() {
this.result = this.demo1Group.get('demo1Value').value;
}
`;
code3 = `
<form [formGroup]="userGroup">
用户表单(两个小表单合起来)的合法状态:<span>{{userGroup.valid}}</span>
<h2>个人信息</h2>
<div formGroupName="personalGroup">
<input formControlName="userName" nz-input placeholder="用户名,必填项">
</div>
userName的值为:<span>{{userGroup.get('personalGroup').get('userName').value}}</span>
<h2>学籍信息</h2>
<div formGroupName="schoolGroup">
<input formControlName="collegePlace" nz-input placeholder="大学所在地,不少于4个字符">
</div>
collegePlace的值为:<span>{{userGroup.get('schoolGroup').get('collegePlace').value}}</span> <br/>
</form>
`;
code4 = `
userGroup: FormGroup;
this.userGroup = new FormGroup({
personalGroup: new FormGroup({
'userName': new FormControl('', [Validators.required])
}),
schoolGroup: new FormGroup({
'collegePlace': new FormControl('', [Validators.required, Validators.minLength(4)])
})
});
`;
updatePersonalGroup() {
this.userGroup2.patchValue({
personalGroup: {
'userName': 'Eve'
}
});
}
code5 = `
<form [formGroup]="userGroup2">
<!--其他代码和上面的案例一致,注意这里我的分组名userGroup2变化了,为了演示的代码效果互不影响-->
<button (click)="updatePersonalGroup()" nz-button nzType="primary">使用默认用户名</button>
</form>
`;
code6 = `
updatePersonalGroup() {
this.userGroup2.patchValue({
personalGroup: {
'userName':'Eve'
}
});
}
`;
code7 = `
this.userGroup = new FormGroup({
personalGroup: new FormGroup({
'userName': new FormControl('', [Validators.required])
}),
schoolGroup: new FormGroup({
'collegePlace': new FormControl('', [Validators.required, Validators.minLength(4)])
})
});
`;
code8 = `
constructor(private formBuilder: FormBuilder) { }
this.userGroup = this.formBuilder.group({
personalGroup: this.formBuilder.group({
'userName': ['',Validators.required]
}),
schoolGroup: this.formBuilder.group({
'collegePlace': ['',Validators.required]
})
});
`;
code9 = `
<form [formGroup]="hobbyForm">
<div formArrayName="hobby">
<button nzType="primary" (click)="addHobby()" nz-button>新增爱好</button>
<button nzType="primary" (click)="getHobbies()" [disabled]='hobbyForm.invalid' nz-button>显示结果</button>
<div *ngFor="let obj of hobbies.controls; let i=index">
<label>
爱好{{i+1}}:
<input nz-input [formControlName]="i">
</label>
</div>
</div>
</form>
<div *ngFor="let value of hobbyResult; let i=index">
爱好{{i+1}}:{{value}}
</div>
`;
code10 = `
this.hobbyForm = this.formBuilder.group({
hobby: this.formBuilder.array([
this.formBuilder.control('', [Validators.required])
])
});
get hobbies() {//获取FormArray对象
return this.hobbyForm.get('hobby') as FormArray;
}
addHobby() {//添加新项
this.hobbies.push(this.formBuilder.control('', [Validators.required]));
}
hobbyResult = [];
getHobbies() {
this.hobbyResult = [];
for (let i = 0; i < this.hobbies.length; i++) {
const value = this.hobbies.get(i.toString()).value;
this.hobbyResult.push(value);
}
}
`;
}
|
c92238bd3b0004e7d8cb652cd1de190404eeef96
|
TypeScript
|
JMCPuddick/MarsRover
|
/src/controllers/Mission-Controller.spec.ts
| 2.6875
| 3
|
import { readFileSync } from "fs";
import { MissionController } from ".";
import { Vector2 } from "../core";
import { InputParser } from "../services";
const Dummyinput = readFileSync('./src/tests/DummyInput.txt', 'utf8');
describe('Mission Controller', () => {
// Arrange
let mockMissionSize: Vector2 = new Vector2(5, 5);
let mockFleetSize = 3;
let missionCommands = InputParser.SplitCommandLines(Dummyinput);
let mockController: MissionController;
it('Can start a new mission with given grid size', () => {
// Act
mockController = new MissionController(mockMissionSize);
// Assert
expect(mockController.missionSize).toMatchObject(mockMissionSize);
});
it('will run a successful mission given a page of commands', () => {
// Arrange
let expectedPosition = new Vector2(1, 3);
// Act
mockController.RunMission(missionCommands);
//Assert
// MMRMLM should be test input for rover[0] should get it to [3,1]
expect(mockController.rovers[0].position).toEqual(expectedPosition);
});
});
|
2403566c01311e2232be9ff776d82c62ace2d006
|
TypeScript
|
tkryskiewicz/react-airlines
|
/src/payment/PaymentCard.ts
| 2.703125
| 3
|
import * as Moment from "moment";
export class PaymentCard {
constructor(
public cardNumber: string = "",
public cardType: string = "",
public expiryDate?: Moment.Moment,
public securityCode: string = "",
public cardholdersName: string = "",
) {
}
public clone() {
return new PaymentCard(
this.cardNumber,
this.cardType,
this.expiryDate,
this.securityCode,
this.cardholdersName,
);
}
}
|
bb89311fbd2928fd5212bfaf5bb5b86fb588f726
|
TypeScript
|
liandao0815/online_teaching_fe
|
/src/app/config/table-config.ts
| 2.765625
| 3
|
// 表格信息类型
export interface TableInfo<T> {
loading: boolean;
total: number;
data: T[];
pageNum: number;
pageSize: number;
}
// 表格数据请求响应数据类型
export interface ResponseDataOfTable<T> {
code: number;
data: { list: T[]; total: number };
message: string;
}
// 表格数据请求参数类型
export interface RequestParamOfTable {
pageNum: number;
pageSize: number;
[key: string]: any;
}
|
969da5f5950f4743306f1aedc978b8cd23b32388
|
TypeScript
|
retrive123/jhipster-sample-application
|
/src/main/webapp/app/shared/model/authentic-key.model.ts
| 2.59375
| 3
|
import { IProductDetails } from 'app/shared/model//product-details.model';
export interface IAuthenticKey {
id?: number;
uniqueKey?: number;
productId?: number;
assignmentStatus?: boolean;
validStatus?: boolean;
productDetails?: IProductDetails;
}
export class AuthenticKey implements IAuthenticKey {
constructor(
public id?: number,
public uniqueKey?: number,
public productId?: number,
public assignmentStatus?: boolean,
public validStatus?: boolean,
public productDetails?: IProductDetails
) {
this.assignmentStatus = this.assignmentStatus || false;
this.validStatus = this.validStatus || false;
}
}
|
026a173d1c525d994182ba68bf255211c278a5b7
|
TypeScript
|
Sammons/morbid
|
/src/extraction/extraction-interfaces.ts
| 2.578125
| 3
|
export interface ExtractedIndex {
indexname: string;
unique: boolean;
struct: 'BTREE' | 'HASH' | 'GIST' | 'GIN';
cols: string[];
}
export interface ExtractedColumn {
columnname: string;
position: number;
nullable: boolean;
primary_key: boolean;
column_default: string;
type: string;
}
export interface ExtractedTable {
schemaname: string;
tablename: string;
columns: ExtractedColumn[];
indices: ExtractedIndex[];
}
export interface ExtractedView {
schemaname: string;
viewname: string;
columns: ExtractedColumn[];
indices: ExtractedIndex[];
}
export interface ExtractedView {
schema: string;
table: string;
columns: ExtractedColumn[];
}
export interface ExtractedSchema {
schema: string;
tables: ExtractedTable[];
views: ExtractedView[];
}
type TypeCategory = 'A' | 'B' | 'C' | 'D' | 'E' | 'G' | 'I' | 'N' | 'P' | 'S' | 'T' | 'U' | 'V' | 'X';
export interface ExtractedType {
typname: string;
typcategory: TypeCategory;
typlen: number;
typelem: number;
typndims: number | null;
typbyval: boolean;
}
export interface ExtractedFunctions {
proname: string;
numargs: number;
isagg: boolean;
iswindow: boolean;
isvariadic: boolean;
returntype: ExtractedType;
}
export interface FullExtraction {
schemas: Array<{
name: string;
tables: ExtractedTable[];
views: ExtractedView[];
indexes: ExtractedIndex[];
}>;
}
|