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
|
|---|---|---|---|---|---|---|
c941a04e1655564640439e9c6694a85e50da5f84
|
TypeScript
|
knenkne/6cities
|
/src/store/reducer/cities/selectors.ts
| 2.65625
| 3
|
import {city} from '../../../common/types';
interface State {
cities: {
current: city;
data: city[];
};
}
export const getCity = (state: State) => {
return state.cities.current;
};
export const getCities = (state: State) => {
return state.cities.data;
};
|
e987f01c238827d140e3ca4708bc72ab41f01228
|
TypeScript
|
jpowersdev/lat_lng_radius
|
/pkg/lat_lng_radius.d.ts
| 2.78125
| 3
|
/* tslint:disable */
/* eslint-disable */
/**
* @param {number} lat
* @param {number} lng
* @param {number} rad
* @returns {Coords}
*/
export function within_radius(lat: number, lng: number, rad: number): Coords;
/**
*/
export class Coords {
free(): void;
lat: Delta;
lng: Delta;
}
/**
*/
export class Delta {
free(): void;
max: number;
min: number;
}
|
f8daf23cd6b93b425eaac261235ee8a76ca05074
|
TypeScript
|
DevelopByTarun/TODAY-HELP
|
/ANGULAR/Angular-2-4-5-6-JavaScriptFramework-master/PipesAndCustomPipes/app/employee.ts
| 2.59375
| 3
|
export class Employee {
constructor(public id:number, public name:string, public age:number, public city:string) {}
}
|
d7892adf6e57527acc3dc4aa3af5b4f7e2604079
|
TypeScript
|
expert-elm/util-extra
|
/base/boolean.test.ts
| 3.28125
| 3
|
import {
to_boolean,
is_boolean,
is_true,
is_false,
is_falsy,
is_truthy,
} from './boolean'
describe(to_boolean, () => {
test('true', () => {
expect(to_boolean(42)).toBe(true)
expect(to_boolean({})).toBe(true)
})
test('false', () => {
expect(to_boolean(0)).toBe(false)
expect(to_boolean('')).toBe(false)
expect(to_boolean(NaN)).toBe(false)
})
})
describe(is_boolean, () => {
test('boolean', () => {
expect(is_boolean(false)).toBe(true)
expect(is_boolean(Boolean())).toBe(true)
})
test('non boolean', () => {
expect(is_boolean(null)).toBe(false)
})
})
describe(is_true, () => {
test('true', () => {
expect(is_true(true)).toBe(true)
expect(is_true(Boolean(Infinity))).toBe(true)
})
test('not true', () => {
expect(is_true(false)).toBe(false)
expect(is_true(Boolean(0))).toBe(false)
})
})
describe(is_false, () => {
test('false', () => {
expect(is_false(false)).toBe(true)
expect(is_false(Boolean(Number.NaN))).toBe(true)
})
test('not false', () => {
expect(is_false(true)).toBe(false)
})
})
describe(is_falsy, () => {
test('falsy', () => {
expect(is_falsy(null)).toBe(true)
expect(is_falsy(NaN)).toBe(true)
expect(is_falsy(-0)).toBe(true)
})
test('not falsy', () => {
expect(is_falsy(42)).toBe(false)
expect(is_falsy({})).toBe(false)
expect(is_falsy([])).toBe(false)
})
})
describe(is_truthy, () => {
test('falsy', () => {
expect(is_truthy(42)).toBe(true)
expect(is_truthy({})).toBe(true)
})
test('not falsy', () => {
expect(is_truthy(null)).toBe(false)
expect(is_truthy(false)).toBe(false)
expect(is_truthy(-0)).toBe(false)
})
})
|
5a12ff9c66d55406ca5c830269c7135c9459e0a5
|
TypeScript
|
davolcu/tfg-app
|
/interfaces/instances.ts
| 2.640625
| 3
|
// Out of the box imports
import { FunctionComponent } from 'react';
import { IconDefinition } from '@fortawesome/free-solid-svg-icons';
// Interface for the User entity
export interface IUser {
[key: string]: string;
}
// Interface for the Header dropdown options
export interface IHeaderDropdownOption {
id: string;
value: string;
icon?: IconDefinition;
callback?: Function;
}
// Interface for the Sidebar item
export interface ISidebarItem {
id: string;
value: string;
link: string;
}
// Interface for the Navigation bar Breadcrumbs
export interface IBreadcrumb {
id: string;
value: string;
link?: string;
image?: string;
}
// Interface for the Parser instance
export interface IParser {
[key: string]: string;
}
// Interface for the Function Component parser instance
export interface IParserFunctionComponent {
[key: string]: FunctionComponent<any>;
}
// Interface for the Strings parser instance
export interface IParserString {
[key: string]: string | Function;
}
// Interface for the Attribute instances of the list
export interface IAttribute {
[key: string]: string;
}
// Interface for the Metadata instance
export interface IMetadata {
name: string;
id: string;
description?: string;
attributeList: IAttribute[];
}
// Interface for the Entity instances
export interface IEntity {
[key: string]: string | number;
}
// Interface for the Entity List data async response
export interface IEntitiesData {
Metadata: IMetadata;
Count: number;
Items: IEntity[];
ScannedCount: number;
}
// Interface for the Entity Instance data async response
export interface IEntityData {
Metadata: IMetadata;
Item: IEntity;
}
// Interface for the Entity List request query
export interface IEntityQuery {
[key: string]: string;
}
// Interface for the Entities of the user's project
export interface IEntities {
[key: string]: IMetadata;
}
|
54e0ed6f443e19ea08fb5e1f6e802dde9a7c5d67
|
TypeScript
|
modegod/newPA
|
/packages/frontend/store/system/actions.ts
| 2.578125
| 3
|
import {
SET_MOBILE_VIEW,
SET_WINDOW_DIMENSIONS,
ISystemState,
ISetMobileViewAction,
ISetWindowDimensionsAction,
WindowDimensions,
} from './types';
export const setMobileView = (
mobileView: ISystemState['mobileView'],
): ISetMobileViewAction => {
return {
type: SET_MOBILE_VIEW,
mobileView,
};
};
export const setWindowDimensions = (
width: WindowDimensions['width'],
height: WindowDimensions['height'],
): ISetWindowDimensionsAction => {
return {
type: SET_WINDOW_DIMENSIONS,
windowDimensions: { width, height },
};
};
|
e86dc06f18107c19085ca6eb6cbfaed20b95d34f
|
TypeScript
|
aws/aws-cdk
|
/packages/aws-cdk-lib/aws-lambda/lib/params-and-secrets-layers.ts
| 2.578125
| 3
|
import { Construct, IConstruct } from 'constructs';
import { IFunction } from './function-base';
import { Token, Stack, Duration } from '../../core';
import { RegionInfo, FactName } from '../../region-info';
/**
* Config returned from `ParamsAndSecretsVersion._bind`
*/
interface ParamsAndSecretsBindConfig {
/**
* ARN of the Parameters and Secrets layer version
*/
readonly arn: string;
/**
* Environment variables for the Parameters and Secrets layer configuration
*/
readonly environmentVars: { [key: string]: string };
}
/**
* Parameters and Secrets Extension versions
*/
export enum ParamsAndSecretsVersions {
/**
* Version 1.0.103
*
* Note: This is the latest version
*/
V1_0_103 = '1.0.103',
}
/**
* Logging levels for the Parametes and Secrets Extension
*/
export enum ParamsAndSecretsLogLevel {
/**
* Debug
*/
DEBUG = 'debug',
/**
* Info
*/
INFO = 'info',
/**
* Warn
*/
WARN = 'warn',
/**
* Error
*/
ERROR = 'error',
/**
* No logging
*/
NONE = 'none',
}
/**
* Parameters and Secrets Extension configuration options
*/
export interface ParamsAndSecretsOptions {
/**
* Whether the Parameters and Secrets Extension will cache parameters and
* secrets.
*
* @default true
*/
readonly cacheEnabled?: boolean;
/**
* The maximum number of secrets and parameters to cache. Must be a value
* from 0 to 1000. A value of 0 means there is no caching.
*
* Note: This variable is ignored if parameterStoreTtl and secretsManagerTtl
* are 0.
*
* @default 1000
*/
readonly cacheSize?: number;
/**
* The port for the local HTTP server. Valid port numbers are 1 - 65535.
*
* @default 2773
*/
readonly httpPort?: number;
/**
* The level of logging provided by the Parameters and Secrets Extension.
*
* Note: Set to debug to see the cache configuration.
*
* @default - Logging level will be `info`
*/
readonly logLevel?: ParamsAndSecretsLogLevel;
/**
* The maximum number of connection for HTTP clients that the Parameters and
* Secrets Extension uses to make requests to Parameter Store or Secrets
* Manager. There is no maximum limit. Minimum is 1.
*
* Note: Every running copy of this Lambda function may open the number of
* connections specified by this property. Thus, the total number of connections
* may exceed this number.
*
* @default 3
*/
readonly maxConnections?: number;
/**
* The timeout for requests to Secrets Manager. A value of 0 means that there is
* no timeout.
*
* @default 0
*/
readonly secretsManagerTimeout?: Duration;
/**
* The time-to-live of a secret in the cache. A value of 0 means there is no caching.
* The maximum time-to-live is 300 seconds.
*
* Note: This variable is ignored if cacheSize is 0.
*
* @default 300 seconds
*/
readonly secretsManagerTtl?: Duration;
/**
* The timeout for requests to Parameter Store. A value of 0 means that there is no
* timeout.
*
* @default 0
*/
readonly parameterStoreTimeout?: Duration;
/**
* The time-to-live of a parameter in the cache. A value of 0 means there is no caching.
* The maximum time-to-live is 300 seconds.
*
* Note: This variable is ignored if cacheSize is 0.
*
* @default 300 seconds
*/
readonly parameterStoreTtl?: Duration;
}
/**
* Parameters and Secrets Extension layer version
*/
export abstract class ParamsAndSecretsLayerVersion {
/**
* Use the Parameters and Secrets Extension associated with the provided ARN. Make sure the ARN is associated
* with the same region and architecture as your function.
*
* @see https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_lambda.html#retrieving-secrets_lambda_ARNs
*/
public static fromVersionArn(arn: string, options: ParamsAndSecretsOptions = {}): ParamsAndSecretsLayerVersion {
return new (class extends ParamsAndSecretsLayerVersion {
public _bind(_scope: Construct, _fn: IFunction): ParamsAndSecretsBindConfig {
return {
arn,
environmentVars: this.environmentVariablesFromOptions,
};
}
})(options);
}
/**
* Use a specific version of the Parameters and Secrets Extension to generate a layer version.
*/
public static fromVersion(version: ParamsAndSecretsVersions, options: ParamsAndSecretsOptions = {}): ParamsAndSecretsLayerVersion {
return new (class extends ParamsAndSecretsLayerVersion {
public _bind(scope: Construct, fn: IFunction): ParamsAndSecretsBindConfig {
return {
arn: this.getVersionArn(scope, version, fn.architecture.name),
environmentVars: this.environmentVariablesFromOptions,
};
}
})(options);
}
private constructor(private readonly options: ParamsAndSecretsOptions) {}
/**
* Returns the ARN of the Parameters and Secrets Extension
*
* @internal
*/
public abstract _bind(scope: Construct, fn: IFunction): ParamsAndSecretsBindConfig;
/**
* Configure environment variables for Parameters and Secrets Extension based on configuration options
*/
private get environmentVariablesFromOptions(): { [key: string]: any } {
if (this.options.cacheSize !== undefined && (this.options.cacheSize < 0 || this.options.cacheSize > 1000)) {
throw new Error(`Cache size must be between 0 and 1000 inclusive - provided: ${this.options.cacheSize}`);
}
if (this.options.httpPort !== undefined && (this.options.httpPort < 1 || this.options.httpPort > 65535)) {
throw new Error(`HTTP port must be between 1 and 65535 inclusive - provided: ${this.options.httpPort}`);
}
// max connections has no maximum limit
if (this.options.maxConnections !== undefined && this.options.maxConnections < 1) {
throw new Error(`Maximum connections must be at least 1 - provided: ${this.options.maxConnections}`);
}
if (this.options.secretsManagerTtl !== undefined && this.options.secretsManagerTtl.toSeconds() > 300) {
throw new Error(`Maximum TTL for a cached secret is 300 seconds - provided: ${this.options.secretsManagerTtl.toSeconds()} seconds`);
}
if (this.options.parameterStoreTtl !== undefined && this.options.parameterStoreTtl.toSeconds() > 300) {
throw new Error(`Maximum TTL for a cached parameter is 300 seconds - provided: ${this.options.parameterStoreTtl.toSeconds()} seconds`);
}
return {
PARAMETERS_SECRETS_EXTENSION_CACHE_ENABLED: this.options.cacheEnabled ?? true,
PARAMETERS_SECRETS_EXTENSION_CACHE_SIZE: this.options.cacheSize ?? 1000,
PARAMETERS_SECRETS_EXTENSION_HTTP_PORT: this.options.httpPort ?? 2773,
PARAMETERS_SECRETS_EXTENSION_LOG_LEVEL: this.options.logLevel ?? ParamsAndSecretsLogLevel.INFO,
PARAMETERS_SECRETS_EXTENSION_MAX_CONNECTIONS: this.options.maxConnections ?? 3,
SECRETS_MANAGER_TIMEOUT_MILLIS: this.options.secretsManagerTimeout?.toMilliseconds() ?? 0,
SECRETS_MANAGER_TTL: this.options.secretsManagerTtl?.toSeconds() ?? 300,
SSM_PARAMETER_STORE_TIMEOUT_MILLIS: this.options.parameterStoreTimeout?.toMilliseconds() ?? 0,
SSM_PARAMETER_STORE_TTL: this.options.parameterStoreTtl?.toSeconds() ?? 300,
};
}
/**
* Retrieve the correct Parameters and Secrets Extension Lambda ARN from RegionInfo,
* or create a mapping to look it up at stack deployment time.
*
* This function is run on CDK synthesis.
*/
private getVersionArn(scope: IConstruct, version: string, architecture: string): string {
const stack = Stack.of(scope);
const region = stack.region;
// region is resolved - look it up directly from table
if (region !== undefined && !Token.isUnresolved(region)) {
const layerArn = RegionInfo.get(region).paramsAndSecretsLambdaLayerArn(version, architecture);
if (layerArn === undefined) {
throw new Error(`Parameters and Secrets Extension is not supported in region ${region} for ${architecture} architecture`);
}
return layerArn;
}
// region is unresolved - create mapping and look up during deployment
return stack.regionalFact(FactName.paramsAndSecretsLambdaLayer(version, architecture));
}
}
|
333aa68487a3bf8663329b5342efd510061a035f
|
TypeScript
|
ToggyO/ts-inversify
|
/services/tsi-service-data/src/modules/v1/sales-flat-order/sales-flat-order.validator.ts
| 2.65625
| 3
|
/**
* Description: Validators for the sales flat order service
*/
import { BaseValidator } from 'modules/common';
import { Validator, ValidatorError } from 'utils/validation';
import { CreateOrderPayload, BookOrderItemsUpdateOrderPayload } from './types';
export class SalesFlatOrderValidator extends BaseValidator {
/**
* Create order with items validator
*/
public static createOrderValidator(dto: CreateOrderPayload): void {
const { userName, userEmail, userPhone } = dto;
const errors: Array<ValidatorError> = [
...new Validator({ value: userName, field: 'userName' }).required().result(),
...new Validator({ value: userEmail, field: 'userEmail' }).required().email().result(),
...new Validator({ value: userPhone, field: 'userPhone' }).required().phone().result(),
];
if (errors.length) {
SalesFlatOrderValidator.throwValidationError(errors);
}
}
/**
* Update order with items validator
*/
public static updateOrderValidator(dto: BookOrderItemsUpdateOrderPayload): void {
const { orderId } = dto;
const errors: Array<ValidatorError> = [
...new Validator({ value: orderId, field: 'orderId' }).required().isNumber().result(),
];
if (errors.length) {
SalesFlatOrderValidator.throwValidationError(errors);
}
}
}
|
65ef33ebfbc687f699485ae0dcbf0531d9a80a19
|
TypeScript
|
storm1er/jsmake-libraries
|
/06_maester/src/lib/exceptions/BaseException.ts
| 2.953125
| 3
|
export class BaseException {
constructor(input, exception = null) {
Object.keys(input).forEach((key) => {
if (key in this) {
return;
}
this[key] = input[key];
});
this.exception = exception;
}
static wrap(input, ex) {
if (ex instanceof this) {
return ex;
}
return new this(input, ex);
}
}
export default BaseException;
|
a8b80ed3c7127292332589e26059b849a02ca057
|
TypeScript
|
eprincev-egor/model-layer
|
/lib/type/Type.ts
| 2.90625
| 3
|
import EqualStack from "../EqualStack";
import {
UnknownTypeError,
ReservedWordForPrimaryKeyError,
InvalidValidationError,
InvalidKeyValidationError
} from "../errors";
import {invalidValuesAsString} from "../utils";
const FORBIDDEN_PRIMARY_KEYS = [
"row",
"primaryKey",
"primaryValue"
];
export type TInstanceOrT<T> = (
T extends new (...args: any) => any ?
InstanceType<T> :
T
);
interface IObjectWithAnyKey {
"*": any;
}
// output
type outputValue<T extends any> = (
TInstanceOrT<T> extends {TOutput: any} ?
TInstanceOrT<T>["TOutput"] :
never
);
type outputData<T> = {
readonly [key in keyof T]?: outputValue< T[key] >;
};
interface IOutputAnyData<T> {
readonly [key: string]: outputValue< T >;
}
export type OutputType<T> = (
T extends IObjectWithAnyKey ?
IOutputAnyData< T["*"] > & outputData< Omit< T, "*" > > :
outputData< T >
);
// input
type inputValue<T extends any> = (
TInstanceOrT<T> extends {TInput: any} ?
TInstanceOrT<T>["TInput"] :
never
);
type inputData<T> = {
[key in keyof T]?: inputValue< T[key] >;
};
interface IInputAnyData<T> {
[key: string]: inputValue< T >;
}
export type InputType<T> = (
T extends IObjectWithAnyKey ?
IInputAnyData< T["*"] > & inputData< Omit< T, "*" > > :
inputData< T >
);
// json
type jsonValue<T extends any> = (
TInstanceOrT<T> extends {TJson: any} ?
TInstanceOrT<T>["TJson"] :
never
);
interface IJsonAnyData<T> {
[key: string]: jsonValue< T >;
}
type jsonData<T> = {
[key in keyof T]?: jsonValue< T[key] >;
};
export type JsonType<T> = (
T extends IObjectWithAnyKey ?
IJsonAnyData< T["*"] > & jsonData< Omit< T, "*" > > :
jsonData< T >
);
export interface IType {
TOutput: any;
TInput: any;
TJson: any;
}
const Types: any = {};
export interface ITypeParams {
key?: ((key: string) => boolean) | RegExp;
type?: string;
required?: boolean;
primary?: boolean;
prepare?: (value: any, key: string, model: any) => any;
toJSON?: (value: any, stack: any) => any;
clone?: (value: any, stack: any) => any;
equal?: (selfValue: any, anotherValue: any, stack: any) => boolean;
validate?:
((value: any, key: string) => boolean) |
RegExp
;
enum?: any[];
default?: any | (() => any);
const?: boolean;
}
export class Type {
static Model: any;
static registerType(name: string, SomeType: (new (...args: any) => Type)) {
Types[name] = SomeType;
}
// create type by params
static create(description: any, key: string) {
const isTypeHelper = (
typeof description === "function" &&
description.isTypeHelper === true
);
if ( isTypeHelper ) {
description = description();
}
const isPlainDescription = (
description &&
description.type
);
// structure: {prop: "number"}
// or
// structure: {prop: ["number"]}
// or
// structure: {prop: SomeModel}
// or
// structure: {prop: {}}
if ( !isPlainDescription ) {
description = {
type: description
};
}
// prepare description: ["string"]
// to { type: "array", element: {type: "string"} }
for (const typeName in Types) {
const SomeType = Types[ typeName ];
// CustomType can use some variations for declare structure
SomeType.prepareDescription( description, key );
}
// find CustomType by name
const CustomType = Types[ description.type ];
if ( !CustomType ) {
throw new UnknownTypeError({
key,
type: description.type
});
}
if ( description.primary ) {
const Model = Type.Model;
const isReserved = (
key in Model.prototype ||
FORBIDDEN_PRIMARY_KEYS.includes( key )
);
if ( isReserved ) {
throw new ReservedWordForPrimaryKeyError({key});
}
}
try {
description = new CustomType( description );
} catch (err) {
err.message = key + ": " + err.message;
throw err;
}
// structure must be static
Object.freeze( description );
return description;
}
// default behavior
static prepareDescription(description: any, key: string) {
// redefine me
return description;
}
primary?: boolean;
required: boolean;
type: string;
const: boolean = false;
enum?: any[];
constructor(params: ITypeParams) {
if ( params.primary ) {
this.primary = true;
}
this.type = params.type as string;
this.required = params.required || params.primary || false;
if ( Array.isArray( params.enum ) ) {
this.enum = params.enum;
}
// default can be: false, 0, or function
if ( "default" in params ) {
if ( typeof params.default === "function" ) {
this.default = params.default;
} else {
this.default = () => params.default;
}
}
// custom prepare not null value, after default prepare
if ( typeof params.prepare === "function" ) {
const prepareByType = this.prepare.bind(this);
const customPrepare = params.prepare;
this.prepare = (value, key, model) => {
value = prepareByType( value, key, model );
if ( value != null ) {
value = customPrepare( value, key, model );
}
return value;
};
}
if ( typeof params.toJSON === "function" ) {
this.toJSON = params.toJSON;
}
// custom validate by RegExp or function
if ( "validate" in params ) {
// validate by required, enum, "unique" (ArrayType)
const validateByType = this.validate.bind(this);
if ( typeof params.validate === "function" ) {
const customValidate = params.validate;
this.validate = (value, modelKey) => {
return (
validateByType( value, modelKey ) &&
(
value == null ||
customValidate( value, modelKey )
)
);
};
}
else if ( params.validate instanceof RegExp ) {
const regExp = params.validate;
this.validate = (value, modelKey) => {
return (
validateByType( value, modelKey ) &&
(
value == null ||
regExp.test( value )
)
);
};
}
else {
throw new InvalidValidationError({
invalidValue: invalidValuesAsString( params.validate )
});
}
}
// validate key for models with "*"
if ( "key" in params ) {
const customValidateKey = params.key;
if ( customValidateKey instanceof RegExp ) {
this.validateKey = (modelKey) => {
return customValidateKey.test( modelKey );
};
}
else if ( typeof customValidateKey === "function" ) {
this.validateKey = customValidateKey;
}
else {
throw new InvalidKeyValidationError({
invalidValue: invalidValuesAsString( customValidateKey )
});
}
}
// don't change value
if ( params.const ) {
this.const = true;
}
if ( params.clone ) {
this.clone = params.clone;
}
if ( params.equal ) {
this.equal = params.equal;
}
}
default() {
return null;
}
validateKey(key: string) {
return true;
}
validate(value: any, key: string): boolean {
if ( this.enum ) {
if ( value != null ) {
return this.enum.includes( value );
}
}
return true;
}
prepare(value: any, key: string, model: any): any {
return value;
}
toJSON(value: any, stack: any): any {
return value;
}
clone(value: any, stack?: EqualStack, parentModel?: any): any {
return this.toJSON( value, stack );
}
typeAsString(): string {
return this.type;
}
equal(selfValue: any, otherValue: any, stack: any): boolean {
return selfValue === otherValue;
}
}
|
e36019f41a20e351926031c5e1c44e4d258c4457
|
TypeScript
|
maechabin/react-native-typescript-sample
|
/src/actions.ts
| 2.765625
| 3
|
export interface Action {
type: ActionType,
payload?: any,
}
export enum ActionType {
CHANGE_HELLO_TO_ABE,
CHANGE_HELLO_TO_KIM,
CHANGE_HELLO_TO_MAEDA,
}
export function changeToAbe(): Action {
return {
type: ActionType.CHANGE_HELLO_TO_ABE,
payload: 'abe',
};
}
export function changeToKim(): Action {
return {
type: ActionType.CHANGE_HELLO_TO_KIM,
payload: 'kim',
};
}
export function changeToMaeda(): Action {
return {
type: ActionType.CHANGE_HELLO_TO_MAEDA,
payload: 'maeda',
};
}
|
88be6ab8f44518fb0c03a4bce260ed46763888bd
|
TypeScript
|
yiwanzhutourou/KeepLightProject
|
/src/utils/reg.ts
| 2.546875
| 3
|
export const pattern = {
'wechat': /^[a-zA-Z\d_]{5,}$/,
'qq': /^[0-9]{4,15}$/,
'email': /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
'mobile': /^1[34578]\d{9}$/,
'smscode': /^\d{6}$/,
}
export const verifyReg = (text: string, patternName: string) => {
let pat = pattern[patternName]
if (pat) {
return pat.test(text)
}
return false
}
|
aa6b63bac481d882a75e7ea368ede98592d790d0
|
TypeScript
|
roma-lukashik/matrix-ts
|
/src/iteration/neach.test.ts
| 2.828125
| 3
|
import { neach } from './neach'
import { reshape } from '../geometry/reshape'
import { arange } from '../creation/arange'
describe('neach', () => {
it('iterates over Matrix0', () => {
const args: [number][] = []
neach(1, (...arg) => args.push(arg))
expect(args).toEqual([[1]])
})
it('iterates over all matrix elements in a proper way', () => {
const m = reshape(arange(12), [3, 2, 2])
const args: [number, number, number, number][] = []
neach(m, (...arg) => args.push(arg))
expect(args).toEqual([
[0, 0, 0, 0],
[1, 0, 0, 1],
[2, 0, 1, 0],
[3, 0, 1, 1],
[4, 1, 0, 0],
[5, 1, 0, 1],
[6, 1, 1, 0],
[7, 1, 1, 1],
[8, 2, 0, 0],
[9, 2, 0, 1],
[10, 2, 1, 0],
[11, 2, 1, 1],
])
})
})
|
dbdbfba5b23918faaf34b27e560ee9fd764c163e
|
TypeScript
|
typeorm/typeorm
|
/test/functional/columns/update-insert/entity/Post.ts
| 2.546875
| 3
|
import { Entity } from "../../../../../src/decorator/entity/Entity"
import { Column } from "../../../../../src/decorator/columns/Column"
import { PrimaryGeneratedColumn } from "../../../../../src/decorator/columns/PrimaryGeneratedColumn"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
@Column({ update: false, default: "Default" })
authorFirstName: string
@Column({ insert: false, default: "Default" })
authorMiddleName: string
@Column({ insert: false, update: false, default: "Default" })
authorLastName: string
}
|
ccab564ab0dacd064c6996444f0d984aca36887d
|
TypeScript
|
Ishadijcks/test
|
/src/ig-template/features/statistics/requirements/NumberStatisticRequirement.ts
| 2.875
| 3
|
import {Requirement} from "@/ig-template/tools/requirements/Requirement";
import {NumberStatistic} from "@/ig-template/features/statistics/NumberStatistic";
export class NumberStatisticRequirement extends Requirement {
statistic: NumberStatistic;
targetValue: number;
constructor(statistic: NumberStatistic, targetValue: number) {
super();
this.statistic = statistic;
this.targetValue = targetValue;
}
get actualValue(): number {
return this.statistic.value;
}
get hint(): string {
return `The statistic ${this.statistic.description} needs to be at least ${this.targetValue}`;
}
}
|
b7f9d8d1b7df648937122f5be3167da8026ab69f
|
TypeScript
|
Lameaux/cloudpass
|
/pages/api/user_data.ts
| 2.6875
| 3
|
import { NextApiRequest, NextApiResponse } from 'next';
import PasswordRowData from '../../types/PasswordRowData';
import SecretNoteRowData from '../../types/SecretNoteRowData';
import FolderRowData from '../../types/FolderRowData';
function createFolder(id, name, description): FolderRowData {
return { id, name, description };
};
function createSecretNote(id, name, content): SecretNoteRowData {
return { id, name, content, folder: null };
};
function createPassword(id, resourceName, resourceLocation, userName, password): PasswordRowData {
return {
id,
resourceName,
resourceLocation,
resourceDescription: null,
userName,
password,
folder: null,
};
};
const result: { folders: FolderRowData[], passwords: PasswordRowData[], secretNotes: SecretNoteRowData[] } = {
folders: [
createFolder('private', 'Private', 'Empty Folder'),
createFolder('business', 'Business', 'Empty Folder'),
createFolder('dev', 'Development', 'Empty Folder'),
createFolder('family', 'Family', 'Empty Folder'),
createFolder('dev1', 'Development 1', 'Empty Folder'),
createFolder('family1', 'Family 1', 'Empty Folder'),
createFolder('dev2', 'Development 2', 'Empty Folder'),
createFolder('family2', 'Family 2', 'Empty Folder'),
],
passwords: [
createPassword('0001', 'Facebook', 'https://facebook.com', 'user@gmail.com', '1234'),
createPassword('0002', 'LinkedIn', 'https://linkedin.com', 'user@gmail.com', '1234'),
createPassword('0003', 'Twitter', 'https://twitter.com', 'user@gmail.com', '1234'),
createPassword('0004', 'GMail', 'https://mail.google.com', 'user@gmail.com', '1234'),
],
secretNotes: [
createSecretNote('0001', 'Office Alarm', '1234'),
createSecretNote('0002', 'Internet Banking', 'login: 1234'),
],
};
export default (_req: NextApiRequest, res: NextApiResponse) => {
res.status(200).json(result);
};
|
244a622e90c92fb542c5ce772610dd6a3fdb3da9
|
TypeScript
|
cydran/cydran
|
/test/error/Errors.spec.ts
| 2.984375
| 3
|
import {
BehaviorError,
ComponentStateError,
AmbiguousMarkupError,
DigestLoopError,
InvalidTypeError,
LockedRegionError,
MalformedOnEventError,
ModuleAffinityError,
NullValueError,
RecursionError,
RegistrationError,
ScopeError,
SelectorError,
SetComponentError,
TemplateError,
UnknownComponentError,
UnknownElementError,
UnknownRegionError,
ValidationError,
UnknownStateError,
InvalidStateError,
UnknownInputError,
IllegalArgumentError
} from "error/Errors";
import CydranError from 'error/CydranError';
class TestError extends CydranError {
constructor(msg: string) {
super(msg);
}
}
const emsg: string = "test error";
test("new TestError()", () => {
const errobj = new TestError(emsg);
expect(errobj).toBeInstanceOf(Error);
});
test("this instanceof Error", () => {
const errobj = new TestError(emsg);
expect(errobj).not.toBeNull();
expect(errobj).toBeInstanceOf(Error);
});
test("provides the correct message", () => {
const errobj = new TestError(emsg);
expect(emsg).toEqual(errobj.message);
});
const errors: any[] = [
BehaviorError,
ComponentStateError,
AmbiguousMarkupError,
DigestLoopError,
InvalidTypeError,
LockedRegionError,
MalformedOnEventError,
ModuleAffinityError,
NullValueError,
RecursionError,
RegistrationError,
ScopeError,
SelectorError,
SetComponentError,
TemplateError,
UnknownComponentError,
UnknownElementError,
UnknownRegionError,
ValidationError,
UnknownStateError,
InvalidStateError,
UnknownInputError,
IllegalArgumentError
];
const message: string = "test error";
errors.forEach((errorClass) => {
const instance = new errorClass(message);
test("new " + instance.name + "() - instantiation", () => {
expect(instance).not.toBeNull();
});
test(errorClass.name + " instanceof Error", () => {
expect(instance).toBeInstanceOf(Error);
});
test(errorClass.name + " correct message", () => {
expect(message).toEqual(instance.message);
});
});
|
c2907333e48c8bbeb8938cc2e4e53ef715c4b2f3
|
TypeScript
|
island-is/island.is
|
/libs/service-portal/petitions/src/lib/utils.ts
| 2.6875
| 3
|
import { Endorsement } from '@island.is/api/schema'
import format from 'date-fns/format'
export const formatDate = (date: string) => {
try {
return format(new Date(date), 'dd.MM.yyyy')
} catch {
return date
}
}
export const PAGE_SIZE = 10
export function paginate(
petitions: Endorsement[],
pageSize: number,
pageNumber: number,
) {
return petitions.slice((pageNumber - 1) * pageSize, pageNumber * pageSize)
}
export function pages(petitionsLength: number) {
return Math.ceil(petitionsLength / PAGE_SIZE)
}
|
df699777a4b0a9d4f2d79c8b5a23a274984bf4a0
|
TypeScript
|
iokononyuk/io-lazy-loader
|
/src/io.lazy-loader.ts
| 2.828125
| 3
|
class IOLazyLoader {
public document: Document = document;
public window: Window = window;
private config: IOLoaderConfig;
constructor(config: IOLoaderConfig) {
this.config = config;
this.initIOLoader();
}
public initIOLoader(): void {
if (this.config.afterInit) {
this.config.afterInit();
}
setTimeout(() => {
this.document.addEventListener('scroll', (event: UIEvent) => {
let images = document.querySelectorAll(`[${this.config.attribute}]`);
images.forEach((img: HTMLElement) => {
if ( img.getAttribute('loaded') == 'true' ) {
return false;
}
if (this.needLoadImage(this.config.loadingOffset, img.offsetTop)) {
img.setAttribute('loaded', 'true');
this.loadImage(img);
}
});
})
}, 0);
}
private needLoadImage(loadingOffset: number | string, offsetTop: number): boolean {
return -(this.window.pageYOffset - offsetTop) < loadingOffset;
}
private loadImage(image: HTMLElement): void {
if ( this.config.beforeLoad ) {
this.config.beforeLoad(image)
}
let src =image.getAttribute(this.config.attribute);
image.setAttribute(this.config.setAttribute, src);
if ( this.config.afterLoad ) {
this.config.afterLoad(image)
}
}
}
interface IOLoaderConfig {
attribute: string;
setAttribute: string;
loadingOffset: number | string;
afterInit?: Function;
beforeLoad?: (image) => {};
afterLoad?: (image) => {};
}
|
fc83f19470c80012c6d151627f49ce1d24d028d2
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/array-binarysearch.closest/array-binarysearch.closest-tests.ts
| 3.65625
| 4
|
import binarySearch = require('array-binarysearch.closest');
// Test with object
class Record {
constructor(
public time: Date,
) {
}
}
binarySearch(
[new Record(new Date(21)), new Record(new Date(42)), new Record(new Date(91)), new Record(new Date(91))],
new Record(new Date(92)),
(a: Record, b: Record) => a.time.getTime() - b.time.getTime(),
null,
0,
4,
);
// Test with primitive types
// Tests below are the examples from the projects README
binarySearch([21, 42, 91, 91], 40);
// 1
binarySearch([21, 42, 91, 91], 42, null, null, 2);
// 2
binarySearch([21, 42, 91, 91], 92, null, null, 2, 4);
// 4
binarySearch([21, 42, 91, 91], 40, (a: number, b: number) => a === b ? 0 : (a < b ? -1 : 1));
// 1
binarySearch(['G', 'KG', 'KG', 'MG'], 'g', (a: string, b: string, i: number) => a.toLowerCase().localeCompare(b.toLowerCase()), null, 1);
// 1
binarySearch(['G', 'KG', 'KG', 'MG'], 'KG', (a: string, b: string, i: number, arr: ReadonlyArray<string>) => a.localeCompare(b), null, 1, 4);
// 2
|
dc4b140327c6302b25b266e402b212a61c389037
|
TypeScript
|
vorfol/vms
|
/src/config_v2/sections/user-password.ts
| 2.828125
| 3
|
import { ConfigSection, ConfigData } from "../config_v2";
import { UserPasswordHostConfig } from "../../host-config";
import { isNumber, isString } from "util";
/**
* ConfigSection implementations
*
*
*
*/
export class UserPasswordSection implements ConfigSection, UserPasswordHostConfig {
host: string = '';
port: number = 22;
username: string = '';
password: string = '';
static is(candidate: any): candidate is UserPasswordHostConfig {
return isString(candidate.host) &&
isNumber(candidate.port) &&
isString(candidate.username) &&
isString(candidate.password);
}
static readonly _section = 'connection';
name(): string {
return UserPasswordSection._section;
}
store(): ConfigData {
//do not store password
return { host: this.host,
port: this.port,
username: this.username
};
}
templateToFillFrom(): ConfigData {
return { host: '',
port: 0,
username: '',
password: ''
};
}
fillFrom(data: ConfigData): boolean {
if (typeof data.host === 'string') {
this.host = data.host;
}
if (typeof data.port === 'number') {
this.port = data.port;
}
if (typeof data.username === 'string') {
this.username = data.username;
}
if (typeof data.password === 'string') {
this.password = data.password;
}
return true;
}
}
|
a809f3fa9f196439e0b11a5c5c19e6cff64584cc
|
TypeScript
|
cooliean/vue3-antd-admin
|
/src/api/system/role/model.d.ts
| 2.5625
| 3
|
declare namespace API {
/** 新增角色 */
type CreateRoleParams = {
name: string;
label: string;
remark: string;
menus: Key[];
depts: number[];
};
/** 更新角色 */
type UpdateRoleParams = CreateRoleParams & {
roleId: number;
};
/** 角色列表项 */
type RoleListResultItem = {
createdAt: string;
updatedAt: string;
id: number;
userId: string;
name: string;
label: string;
remark: string;
};
/** 角色列表 */
type RoleListResult = RoleListResultItem[];
/** 角色详情 */
type RoleInfoResult = {
roleInfo: {
createTime: string;
updateTime: string;
id: number;
userId: string;
name: string;
label: string;
remark: string;
};
menus: {
createTime: string;
updateTime: string;
id: number;
roleId: number;
menuId: number;
}[];
depts: {
createTime: string;
updateTime: string;
id: number;
roleId: number;
departmentId: number;
}[];
};
}
|
c98f21c840221a926fdb471787ffaf78a8d5dc05
|
TypeScript
|
xiao-tiger/svg-drawing-vue
|
/src/util.ts
| 3.234375
| 3
|
/**
* 生成随机码
* @param len 随机码长度
*/
export function createRandomCode(len = 11): string {
const charset = `_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;
const maxLen = charset.length;
let ret = "";
for (let i = 0; i < len; i++) {
const randomIndex = Math.floor(Math.random() * maxLen);
ret += charset[randomIndex];
}
return ret;
}
export type editorName = "pencil" | "marker" | "inkpen" | "eraser" | "chalk";
export function getEditorName(value: editorName): string {
const component = {
pencil: "create-path",
marker: "create-path",
inkpen: "create-path",
eraser: "eraser-path",
chalk: "create-path",
};
return component[value];
}
// 目前这个 demo 级别的项目够用了
export function deepcopy<T>(obj: T): T {
if (typeof obj === "object" && obj !== null) {
return JSON.parse(JSON.stringify(obj));
}
return obj;
}
|
428feea4af5c4f83b3b9d5c1a4f64afcbee81d98
|
TypeScript
|
craigphicks/yamato_daiwa-es_extensions
|
/Source/Logging/Errors/FileWritingFailed/FileWritingFailedError.ts
| 2.765625
| 3
|
import FileWritingFailedErrorLocalization__English from "./FileWritingFailedErrorLocalization__English";
class FileWritingFailedError extends Error {
public static readonly NAME: string = "FileWritingFailedError";
public static get DEFAULT_TITLE(): string {
return FileWritingFailedError.localization.defaultTitle;
}
private static localization: FileWritingFailedError.Localization = FileWritingFailedErrorLocalization__English;
public static setLocalization(localization: FileWritingFailedError.Localization): void {
FileWritingFailedError.localization = localization;
}
public constructor(parametersObject: FileWritingFailedError.ConstructorParametersObject) {
super();
this.name = FileWritingFailedError.NAME;
if ("customMessage" in parametersObject) {
this.message = parametersObject.customMessage;
} else {
this.message = FileWritingFailedError.localization.genericDescriptionPartTemplate(parametersObject);
}
}
}
namespace FileWritingFailedError {
export type ConstructorParametersObject = Localization.GenericDescriptionPartTemplateParameters | { customMessage: string; };
export type Localization = {
readonly defaultTitle: string;
readonly genericDescriptionPartTemplate: (
parametersObject: Localization.GenericDescriptionPartTemplateParameters
) => string;
};
export namespace Localization {
export type GenericDescriptionPartTemplateParameters = {
filePath: string;
};
}
}
export default FileWritingFailedError;
|
0a1f33151d67c6261ebb4519b41e44c6dd3d697a
|
TypeScript
|
AnimeNL/volunteer-portal
|
/src/api/IUser.ts
| 3
| 3
|
// Copyright 2021 Peter Beverloo & AnimeCon. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
/**
* The /api/user API call enables information about the authenticated user to be requested, which
* immediately validates that the given authentication token is still valid as well.
*/
export interface IUser {
request: IUserRequest;
response: IUserResponse;
}
/**
* Request issued to the server when making an /api/user call. The authentication token will be
* shared with the server as an HTTP GET request parameter.
*/
export interface IUserRequest {
/**
* The authentication token through which the user is signed in.
*/
authToken: string;
}
/**
* Response shared by the server following an /api/user call. The user's full name and events they
* participate in are required, other fields are optional.
*/
export interface IUserResponse {
/**
* Whether the authenticated user is an administrator. Additional functionality and visibility
* will be enabled in the frontend, but only when the server provides the required information.
*/
administrator?: boolean;
/**
* URL to the avatar that represents this user.
*/
avatar?: string;
/**
* Dictionary of the events that this volunteer has a role in. The role has a series of fixed
* values, other strings represent a visible position.
*/
events: { [key: string]: IUserResponseEventRole };
/**
* The user's full name. User interface may opt to only display the user's first name.
*/
name: string;
}
/**
* The roles that a volunteer can have during an event.
*/
export type IUserResponseEventRole =
'Unregistered' | 'Cancelled' | 'Registered' | 'Rejected' | string;
|
e2178ddcadd6e06e10e26a7db03ff92e29677187
|
TypeScript
|
Marinammm/SmarttbotTest
|
/src/store/strategy/strategy.reducer.ts
| 2.953125
| 3
|
import {
GET_STRATEGIES,
GET_STRATEGIES_FAILED,
GET_STRATEGIES_SUCCESS,
Strategy,
StrategyActionTypes,
} from './strategy.types';
const initialState: Strategy = {
loading: false,
error: undefined,
data: undefined,
};
const strategyReducer = (
state = initialState,
action: StrategyActionTypes,
): Strategy => {
switch (action.type) {
case GET_STRATEGIES:
return {
...state,
loading: true,
};
case GET_STRATEGIES_SUCCESS:
return {
loading: false,
data: action.payload,
error: undefined,
};
case GET_STRATEGIES_FAILED:
return {
loading: false,
data: undefined,
error: action.error,
};
default: return state;
}
};
export default strategyReducer;
|
33630952c55e655eb200dce2a904c30b5fc6eaa5
|
TypeScript
|
nuclearide/reactor
|
/src/Selection.ts
| 3.203125
| 3
|
export class Selection {
static in(target, a, b) {
let min = Math.min(a.line, b.line);
let max = Math.max(a.line, b.line);
return target >= min && target <= max;
}
static between(target, a, b) {
let min = Math.min(a.line, b.line);
let max = Math.max(a.line, b.line);
return target > min && target < max;
}
}
|
fa1f7197037ed12a5242614c38c5bc74dc717736
|
TypeScript
|
devashreegosavi/angular_demo
|
/demo1.ts
| 3.0625
| 3
|
import { Top } from './oops';
let nm: string = 'android'
let num = 456
function nmNum(): string {
return `android`;
}
let mg: number | string | boolean = true
mg = 'android'
mg = 1235
let an: any = mg
let fn: (nm: number) => void = function (nm: number) { }
let fn1: (nm: number) => void = (nm: number) => console.log('hi')
let v1: { [key: string]: number } = {
one: 1,
two: 2
}
class Car {
}
let cr: Car = new Car()
let dt: Date = new Date()
let tp : Top = new Top()
console.log(tp.center())
|
5cb427fff59adae9855034dc89fc9d89bf815314
|
TypeScript
|
SteffenKn/cloudflare-ddns-sync
|
/src/lib/ip-utils.ts
| 2.703125
| 3
|
import * as wimIp from 'what-is-my-ip-address';
import {publicIpv4, publicIpv6} from 'public-ip';
export default class IPUtils {
private static readonly ipPollingDelay = 10 * 1000;
private static ipChangeEventListeners: Map<string, NodeJS.Timeout> = new Map();
public static async getIpv4(): Promise<string> {
/* c8 ignore start*/
try {
return await publicIpv4();
} catch (error) {
return wimIp.v4();
}
/* c8 ignore stop*/
}
public static async getIpv6(): Promise<string> {
/* c8 ignore start */
try {
return await publicIpv6();
} catch (error) {
return wimIp.v6();
}
/* c8 ignore stop*/
}
public static async addIpChangeListener(callback: Function): Promise<string> {
const eventListenerId = this.getId();
let previousIp = await this.getIpv4();
/* c8 ignore start */
const intervalId = setInterval(async (): Promise<void> => {
const currentIp = await this.getIpv4();
const ipMustBeUpdated = currentIp !== previousIp;
if (ipMustBeUpdated) {
previousIp = currentIp;
callback(currentIp);
}
}, this.ipPollingDelay);
/* c8 ignore stop*/
this.ipChangeEventListeners.set(eventListenerId, intervalId);
return eventListenerId;
}
public static removeIpChangeListener(eventListenerId: string): void {
const eventListenerIntervalId = this.ipChangeEventListeners.get(eventListenerId);
clearInterval(eventListenerIntervalId);
IPUtils.ipChangeEventListeners.delete(eventListenerId);
}
private static getId(): string {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
}
|
95f6e9ec9982ac2de33c7780f5b1a513009ef78f
|
TypeScript
|
JuvenalG/nodebucket
|
/src/app/shared/item.interface.ts
| 2.59375
| 3
|
/**
* Title: item.interface.ts
* Author: Professor Krasso
* Date: 29 March 2021
* Modified By: Juvenal Gonzalez
* Description: defines data fields to be used in an Item object
*/
export interface Item{
_id: string;
title: string;
description: string;
}
|
530934d8fc66db05f03158f894d29e1a64ff6d7c
|
TypeScript
|
kelvinleaves/engine
|
/packages/core/src/shader/state/RenderTargetBlendState.ts
| 2.78125
| 3
|
import { BlendOperation } from "../enums/BlendOperation";
import { BlendFactor } from "../enums/BlendFactor";
import { ColorWriteMask } from "../enums/ColorWriteMask";
/**
* The blend state of the render target.
*/
export class RenderTargetBlendState {
/** Whether to enable blend. */
enabled: boolean = false;
/** color (RGB) blend operation. */
colorBlendOperation: BlendOperation = BlendOperation.Add;
/** alpha (A) blend operation. */
alphaBlendOperation: BlendOperation = BlendOperation.Add;
/** color blend factor (RGB) for source. */
sourceColorBlendFactor: BlendFactor = BlendFactor.One;
/** alpha blend factor (A) for source. */
sourceAlphaBlendFactor: BlendFactor = BlendFactor.One;
/** color blend factor (RGB) for destination. */
destinationColorBlendFactor: BlendFactor = BlendFactor.Zero;
/** alpha blend factor (A) for destination. */
destinationAlphaBlendFactor: BlendFactor = BlendFactor.Zero;
/** color mask. */
colorWriteMask: ColorWriteMask = ColorWriteMask.All;
}
|
d661982b7407444befe933aa6c47611853244e3c
|
TypeScript
|
samaronybarros/data-structures
|
/src/test/binary-search-tree.test.ts
| 3.203125
| 3
|
import * as chai from 'chai'
import { BinarySearchTree } from '../core/binary-search-tree'
const expect = chai.expect
describe('Binary Search Tree', () => {
describe('Insert', () => {
it('Should insert a value to root', () => {
const tree = new BinarySearchTree()
tree.insert(27)
const root = tree.search(27)
expect(root?.element).to.equal(27)
expect(root?.left).to.equal(null)
expect(root?.right).to.equal(null)
expect(tree.getLength()).to.equal(1)
})
it('Should insert a value as left root child', () => {
const tree = new BinarySearchTree()
tree.insert(27)
tree.insert(14)
const root = tree.search(27)
expect(tree.search(14)?.element).to.equal(14)
expect(root?.left?.element).to.equal(14)
expect(root?.right).to.equal(null)
expect(tree.getLength()).to.equal(2)
})
it('Should insert a value as right root child', () => {
const tree = new BinarySearchTree()
tree.insert(27)
tree.insert(14)
tree.insert(35)
const root = tree.search(27)
expect(tree.search(14)?.element).to.equal(14)
expect(root?.left?.element).to.equal(14)
expect(root?.right?.element).to.equal(35)
expect(tree.getLength()).to.equal(3)
})
it('Should insert a value as right if they are equal', () => {
const tree = new BinarySearchTree()
tree.insert(27)
tree.insert(27)
const root = tree.search(27)
expect(root?.element).to.equal(27)
expect(root?.left).to.equal(null)
expect(root?.right?.element).to.equal(27)
expect(tree.getLength()).to.equal(2)
})
})
describe('Delete', () => {
it('Should delete a leaf', () => {
const tree = new BinarySearchTree()
tree.fromArray([27, 14, 35, 10, 19, 31, 42])
tree.delete(19)
const leaf = tree.search(19)
const node = tree.search(14)
expect(leaf).to.be.null
expect(node?.left?.element).to.equal(10)
expect(node?.right).to.equal(null)
expect(tree.getLength()).to.equal(6)
})
it('Should delete a node', () => {
const tree = new BinarySearchTree()
tree.fromArray([27, 14, 35, 10, 19, 31, 42])
tree.delete(14)
const root = tree.search(27)
const node = tree.search(14)
expect(node).to.be.null
expect(root?.element).to.equal(27)
expect(root?.left?.element).to.equal(10)
expect(root?.right?.element).to.equal(35)
expect(tree.getLength()).to.equal(6)
})
it('Should delete the root', () => {
const tree = new BinarySearchTree()
tree.fromArray([27, 14, 35, 10, 19, 31, 42])
tree.delete(27)
const oldRoot = tree.search(27)
const newRoot = tree.search(19)
expect(oldRoot).to.be.null
expect(newRoot?.element).to.equal(19)
expect(newRoot?.left?.element).to.equal(14)
expect(newRoot?.right?.element).to.equal(35)
expect(tree.getLength()).to.equal(6)
})
})
})
|
1dc74944f67157f5a44c9a1eb9bf238fd151b11b
|
TypeScript
|
srestrepoo/backend-homework
|
/src/users/users.controller.spec.ts
| 2.546875
| 3
|
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './interfaces/user.interface';
import { Model } from 'mongoose';
describe('UsersController', () => {
let usersController: UsersController;
let usersService: UsersService;
beforeEach(() => {
usersService = new UsersService(Model);
usersController = new UsersController(usersService);
});
describe('findAll', () => {
it('return a array of users', async () => {
const result = ['test'];
jest.spyOn(usersService, 'findAll').mockImplementation(() => result);
expect(await usersController.findAll()).toBe(result);
});
});
describe('create', () => {
it('return an user created', async () => {
var result;
jest.spyOn(usersService, 'create').mockImplementation(() => result);
const testUser = new CreateUserDto();
expect(await usersController.create(testUser)).toBe(result);
});
});
describe('update', () => {
it('return an user updated', async () => {
var result;
jest.spyOn(usersService, 'update').mockImplementation(() => result);
expect(await usersController.update("srestrepoo",{"name":"Tiago"})).toBe(result);
});
});
describe('delete', () => {
it('user deleted', async () => {
var result;
jest.spyOn(usersService, 'delete').mockImplementation(() => result);
expect(await usersController.delete("srestrepoo")).toBe(result);
});
});
describe('findOne', () => {
it('return an user with nick srestrepoo', async () => {
var result;
jest.spyOn(usersService, 'findOne').mockImplementation(() => result);
expect(await usersController.findOne("srestrepoo")).toBe(result);
});
});
});
|
b2444d1f116b5b65062cf62ca555a669e6cb6f9c
|
TypeScript
|
krybc/budget-app
|
/src/app/categories-data-access/store/categories.reducer.ts
| 2.546875
| 3
|
import {createEntityAdapter, EntityAdapter} from '@ngrx/entity';
import {Action, createReducer, on} from '@ngrx/store';
import * as CategoriesActions from './categories.actions';
import {Categories, Category} from './categories.models';
export const CATEGORIES_FEATURE_KEY = 'categories';
export interface State {
categories: Categories;
categoriesLoaded: boolean;
selectedCategoryId: number;
}
export interface CategoriesPartialState {
readonly [CATEGORIES_FEATURE_KEY]: State;
}
export const categoriesAdapter: EntityAdapter<Category> = createEntityAdapter<Category>();
export const initialState: State = {
categories: categoriesAdapter.getInitialState(),
categoriesLoaded: false,
selectedCategoryId: null,
};
const categoriesReducer = createReducer(
initialState,
on(CategoriesActions.loadCategoriesSuccess, (state, {categories}) => ({
...state,
categories: categoriesAdapter.setAll(categories, state.categories),
categoriesLoaded: true
})),
on(CategoriesActions.selectCategory, (state, {id}) => ({
...state,
selectedCategoryId: id
})),
on(CategoriesActions.createCategorySuccess, (state, {category}) => ({
...state,
categories: categoriesAdapter.addOne(category, state.categories)
})),
on(CategoriesActions.updateCategorySuccess, (state, {category}) => ({
...state,
categories: categoriesAdapter.setOne(category, state.categories)
})),
);
export function reducer(state: State | undefined, action: Action) {
return categoriesReducer(state, action);
}
|
cab37a8eccf949dc26f57a4df8c1fb5ff2a31f3a
|
TypeScript
|
ivanmjartan/gooddata-js
|
/src/util.ts
| 2.671875
| 3
|
// (C) 2007-2017 GoodData Corporation
import { get } from 'lodash';
import { delay } from './utils/promise';
import { name as pkgName, version as pkgVersion } from '../package.json';
/**
* Utility methods. Mostly private
*
* @module util
* @class util
*
*/
/**
* Gooddata-js package signature
* @private
*/
export const thisPackage = { name: pkgName, version: pkgVersion };
/**
* Create getter function for accessing nested objects
*
* @param {String} path Target path to nested object
* @method getIn
* @private
*/
export const getIn = (path: string) => (object: any) => get(object, path);
export interface IPollingOptions {
attempts?: number;
maxAttempts?: number;
pollStep?: number;
}
/**
* Helper for polling
*
* @param {String} uri
* @param {Function} isPollingDone
* @param {Object} options for polling (maxAttempts, pollStep)
* @private
*/
export const handlePolling = (
xhrGet: any,
uri: string,
isPollingDone: Function,
options: IPollingOptions = {}
) => { // TODO
const {
attempts = 0,
maxAttempts = 50,
pollStep = 5000
} = options;
return xhrGet(uri)
.then((r: any) => r.getData())
.then((response: any) => {
if (attempts > maxAttempts) {
return Promise.reject(new Error(response));
}
return isPollingDone(response) ?
Promise.resolve(response) :
delay(pollStep).then(() => {
return handlePolling(xhrGet, uri, isPollingDone, {
...options,
attempts: attempts + 1
});
});
});
};
/**
* Builds query string from plain object
* (Refactored from admin/routes.js)
*
* @param {Object} query parameters possibly including arrays inside
* @returns {string} querystring
*/
export function queryString(query: any) {
function getSingleParam(key: string, value: string) {
return (Array.isArray(value) ?
value.map(item => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join('&') :
`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
return query ? `?${Object.keys(query).map(k => getSingleParam(k, query[k])).join('&')}` : '';
}
|
436eff03f305729d95bddbb95f1e1510ac90e4a8
|
TypeScript
|
gil/noto
|
/src/store.ts
| 2.828125
| 3
|
import * as fs from 'fs-extra'
import * as path from 'path'
let configFile: string
let state: {
currentVault: string;
vaults: {[vault: string]: string};
} = {
currentVault: '',
vaults: {},
}
export default {
async init(configDir: string) {
configFile = path.join(configDir, 'config.json')
if (await fs.pathExists(configFile)) {
state = await fs.readJSON(configFile)
}
},
async save() {
await fs.ensureFile(configFile)
await fs.writeJSON(configFile, state)
},
getCurrentVault: (): string => state.currentVault,
setCurrentVault: (vault: string) => {
state.currentVault = vault
},
getVaults: (): {[vault: string]: string} => state.vaults,
addVault: (name: string, path: string) => {
state.vaults[name] = path
},
removeVault: (name: string) => {
delete state.vaults[name]
},
}
|
aa3009d6637c437d16a22b8514d11940a4dfe050
|
TypeScript
|
datools/dadoc
|
/src/core/Yaml.ts
| 3.125
| 3
|
import * as fs from 'fs-extra';
import * as yaml from 'js-yaml';
/**
* YAML parser and dumper
*/
export class Yaml {
/**
* Load a yaml file
* @param filepath File to read
*/
public static async load(filepath: string) {
const buffer: Buffer = await fs.readFile(filepath);
return yaml.safeLoad(buffer.toString());
}
public static loadSync(filepath: string) {
const buffer: Buffer = fs.readFileSync(filepath);
return yaml.safeDump(buffer.toString());
}
/**
* Dump data in a yaml file
* @param filepath Destination file path
* @param data Data to dump
*/
public static async save(filepath: string, data: any) {
const dump: string = yaml.safeDump(data);
return await fs.writeFile(filepath, dump);
}
public static saveSync(filepath: string, data: any) {
return fs.writeFileSync(filepath, yaml.safeDump(data));
}
}
|
ec5c6822f966b492a2b8145a7969494e2be4ce50
|
TypeScript
|
EmNudge/get-smallest-chars
|
/src/getChars.ts
| 2.9375
| 3
|
const getChars = ({ checkers, range }) => {
const chars = [];
outer:
for (let i = range[0]; i < range[1]; i++) {
// no idea why TS doesn't like this. This is old at this point.
// @ts-ignore
const char = String.fromCodePoint(i);
for (const charChecker of checkers) {
const state = charChecker(char);
// delete arr if we're asked
if (state.killArr) chars.length = 0;
if (state.success) continue;
// if unsuccessful, escape the outer loop (don't push char to arr)
continue outer;
}
chars.push(char);
}
return chars;
}
export default getChars;
|
6c1956ac1b62a12cc64e3aef83c8300ebb5d5ebc
|
TypeScript
|
enkhdari/expressjs-mongoose-ts
|
/src/controllers/base.controller.ts
| 2.5625
| 3
|
export class BaseController {
returnData(data) {
return { success : true , data }
}
returnSuccess(success: boolean) {
return { success }
}
returnError(error) {
return { success: false, error }
}
}
|
9089d43e1fe38c1ff1fed58ede3d067387623d08
|
TypeScript
|
gabliam/gabliam
|
/packages/core/core/src/common/interfaces/type.ts
| 3.359375
| 3
|
/**
*
* Represents a type that a Service or other object is instances of.
*
* An example of a `Type` is `MyCustomService` class, which in JavaScript is be represented by
* the `MyCustomService` constructor function.
*/
export const Type = Function;
export function isType(v: any): v is Type<any> {
return typeof v === 'function';
}
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type Type<T> = new (...args: any[]) => T;
export type Mutable<T extends { [x: string]: any }, K extends string> = {
[P in K]: T[P];
};
|
40e0ef7680b8888431777fe0f4c655a580236449
|
TypeScript
|
robinsl/BennuJs
|
/src/interfaces/cache-engine.interface.ts
| 2.71875
| 3
|
export interface CacheEngineInterface {
get(key: string): Promise<string>;
set(key: string, value: string, ttl: number, grace: number): Promise<string>;
clear(key: string): Promise<string>;
}
|
cdbc1bffdf8a69b047ec854c3c6b35e581dab642
|
TypeScript
|
isaacev/TinyGit
|
/src/plumbing.ts
| 2.71875
| 3
|
import { format as fmt } from 'util'
import * as path from 'path'
import * as fs from 'fs'
import * as io from './io'
import * as resolve from './resolve'
import { ID } from './models/object'
import { Commit } from './models/commit'
import { Tree, TreeChild } from './models/tree'
import { Blob } from './models/blob'
import { Ref } from './models/ref'
export const hashObject = (filepath: string, write: boolean = false): ID => {
if (path.isAbsolute(filepath) === false) {
filepath = path.resolve(filepath)
}
let data = ''
try {
data = fs.readFileSync(filepath, 'utf8')
} catch (err) {
throw new Error(fmt('failed to read %s', filepath))
}
const blob = new Blob(data)
if (write) {
io.writeObject(blob)
}
return blob.id()
}
export const catFile = (prefix: string): string => {
const objects = io.listObjects()
const matches = objects.filter(id => {
return (id.whole().substring(0, prefix.length) === prefix)
})
if (matches.length > 1) {
throw new Error(fmt('ambiguous reference %s', prefix))
} else if (matches.length === 0) {
throw new Error(fmt('no objects matching %s', prefix))
}
const match = matches[0]
const object = io.readObject(match)
return object.toString()
}
export const lsFiles = (): string => {
const index = io.readIndex()
const files = index.getObjects()
return files.map(f => fmt('%s %s', f.id.whole(), f.name)).join('\n')
}
export const addToIndex = (id: ID, name: string): void => {
const index = io.readIndex()
const filepath = path.normalize(name)
if (index.hasObject(filepath)) {
index.replaceObject(filepath, id)
} else {
index.addObject(filepath, id)
}
io.writeIndex(index)
}
export const removeFromIndex = (name: string): void => {
const index = io.readIndex()
if (index.hasObject(name)) {
index.removeObject(name)
io.writeIndex(index)
}
}
export const writeTree = (prefix: string): ID => {
const normal = path.normalize(prefix)
const index = io.readIndex()
const files = index.getObjects()
const knownDirs = []
const children = files.reduce((children, f) => {
const relative = path.relative(normal, f.name)
const dirname = path.dirname(relative)
if (dirname === '.') {
return children.concat({
name: relative,
mode: 'blob',
id: f.id,
})
} else {
const childDir = dirname.split(path.sep)[0]
if (childDir !== '..' && knownDirs.indexOf(childDir) === -1) {
knownDirs.push(childDir)
return children.concat({
name: childDir,
mode: 'tree',
id: writeTree(path.join(normal, childDir)),
})
} else {
return children
}
}
}, [] as TreeChild[])
return io.writeObject(new Tree(children))
}
export const commitTree = (tree: ID, parents: ID[], author: string, message: string): ID => {
const commit = new Commit(tree, parents, author, message)
io.writeObject(commit)
return commit.id()
}
export const updateRef = (name: string, pointer: ID): void => {
io.writeRef(new Ref(name, pointer))
}
export const showRef = (): Ref[] => {
return io.listRefs()
}
export const diffIndex = (treeish: ID): resolve.FileDiff[] => {
const indexFiles = resolve.indexToFiles()
const treeFiles = resolve.treeishToFiles(treeish)
return resolve.fileDiffs(treeFiles, indexFiles)
}
|
49706b2dedbe4950242441638e769949baa3b5ae
|
TypeScript
|
hendrik-scholz/iot-device-information
|
/test/messages/messageGenerator.spec.ts
| 2.546875
| 3
|
import chai from 'chai';
import fs from 'fs';
import waitOn from 'wait-on';
const expect = chai.expect;
import { generateUUIDMessage } from '../../src/messages/messageGenerator';
const waitOnOptions = {
delay: 500,
interval: 500,
resources: ['test/messages/uuid.json'],
timeout: 3000
};
function deleteUuidFile(callback: any) {
fs.unlink('test/messages/uuid.json', (error) => {
if (error && error.errno === -2 && error.code === 'ENOENT') {
console.log('deleteUuidFile: Since the uuid file does not exist there is nothing to delete.');
}
callback();
});
}
describe('iot-device-information', () => {
describe('message generator', function() {
this.timeout(5000);
before('delete uuid file', (done) => {
deleteUuidFile((error: any) => {
if (error) {
done(error);
} else {
done();
}
});
});
it('should test generation of a UUID JSON file with a given ID', (done) => {
const expectedUuidEntry = JSON.stringify({uuid: '42'});
generateUUIDMessage('test/messages/uuid.json', '42');
waitOn(waitOnOptions, (errorWaitOn) => {
if (errorWaitOn) {
done(errorWaitOn);
} else {
fs.readFile('test/messages/uuid.json', (errorFileAccess, content) => {
if (errorFileAccess) {
done(errorFileAccess);
} else {
const uuidEntry = Buffer.from(content).toString();
expect(uuidEntry).to.equal(expectedUuidEntry);
done();
}
});
}
});
});
it('should test that a second call to generate a UUID JSON file does not overwrite it', (done) => {
const expectedUuidEntry = JSON.stringify({uuid: '42'});
generateUUIDMessage('test/messages/uuid.json', '42');
generateUUIDMessage('test/messages/uuid.json', '43');
waitOn(waitOnOptions, (errorWaitOn) => {
if (errorWaitOn) {
done(errorWaitOn);
} else {
fs.readFile('test/messages/uuid.json', (errorFileAccess, content) => {
if (errorFileAccess) {
done(errorFileAccess);
} else {
const uuidEntry = Buffer.from(content).toString();
expect(uuidEntry).to.equal(expectedUuidEntry);
done();
}
});
}
});
});
});
});
|
dc9ff8443098bf5ccfc7608982a5f6341e5a6fc0
|
TypeScript
|
fkopriva/blog-ukol
|
/blog-ukol/backend/src/resolvers/comment.ts
| 2.625
| 3
|
import { Comment } from "../entities/Comment";
import { isAuth } from "../middleware/isAuth";
import {
Arg,
Ctx,
Field,
FieldResolver,
Int,
Mutation,
ObjectType,
Query,
Resolver,
Root,
UseMiddleware
} from "type-graphql";
import { MyContext } from "../types";
import { getConnection } from "typeorm";
import { Updoot } from "../entities/Updoot";
import { User } from "../entities/User";
@ObjectType()
class PaginatedComments {
@Field(() => [Comment])
comments: Comment[];
@Field()
hasMore: boolean;
}
@Resolver(Comment)
export class CommentResolver {
@FieldResolver(() => User)
author (
@Root() comment: Comment,
@Ctx() { userLoader }: MyContext
) {
return userLoader.load(comment.authorId);
}
@FieldResolver(() => Int, { nullable: true })
async voteStatus(
@Root() comment: Comment,
@Ctx() { updootLoader, req }: MyContext
) {
if (!req.session.userId) {
return null;
}
const updoot = await updootLoader.load({
commentId: comment.id,
userId: req.session.userId,
});
return updoot ? updoot.value : null;
}
@Mutation(() => Boolean)
@UseMiddleware(isAuth)
async vote(
@Arg("commentId", () => Int) commentId: number,
@Arg("value", () => Int) value: number,
@Ctx() { req }: MyContext
) {
const isUpdoot = value !== -1;
const realValue = isUpdoot ? 1 : -1;
const { userId } = req.session;
const updoot = await Updoot.findOne({where: {commentId, userId}});
// the user has voted on the post before
// and they are changing their vote
if (updoot && updoot.value !== realValue) {
await getConnection().transaction(async (tm) => {
await tm.query(`
update updoot
set value = $1
where "commentId" = $2 and "userId" = $3
`, [realValue, commentId, userId]);
await tm.query(`
update comment
set points = points + $1
where id = $2
`, [2 * realValue, commentId])
});
} else if (!updoot) {
// has never voted before
await getConnection().transaction(async (tm) => {
tm.query(`
insert into updoot ("userId", "commentId", value)
values ($1, $2, $3)
`, [userId, commentId, realValue]);
await tm.query(`
update comment
set points = points + $1
where id = $2
`, [realValue, commentId]);
})
}
return true;
}
@Query(() => PaginatedComments)
async comments(
@Arg("limit", () => Int) limit: number,
@Arg("postId", () => Int) postId: number,
@Arg("cursor", () => String, { nullable: true }) cursor: string | null,
): Promise<PaginatedComments> {
const realLimit = Math.min(50, limit);
const realLimitPlusOne = realLimit + 1;
const replacements: any[] = [realLimitPlusOne];
if (postId) {
replacements.push(postId);
}
let cursorIdx = 3;
if (cursor) {
replacements.push(new Date(parseInt(cursor)));
cursorIdx = replacements.length;
}
const comments = await getConnection().query(`
select c.*
from comment c
where c."postId" = $2
${cursor ? `and c."createdAt" < ${cursorIdx}` : ""}
order by c."createdAt" DESC
limit $1
`,
replacements
);
return {
comments: comments.slice(0, realLimit),
hasMore: comments.length === realLimitPlusOne
};
}
@Mutation(() => Comment)
@UseMiddleware(isAuth)
async createComment(
@Arg("id", () => Int) postId: number,
@Arg("text") text: string,
@Ctx() { req }: MyContext
): Promise<Comment> {
return Comment.create({
text,
authorId: req.session.userId,
postId: postId,
}).save();
}
}
|
5fd883fc83b38128e957d3e2f87fc854bc3d796d
|
TypeScript
|
BroFred/wp5-and-single-spa
|
/packages/dashboard/src/utils/dataSourceUtils.ts
| 2.796875
| 3
|
// This util convert data fetch function to observable which emits json
/*
input(funtion which returns json)
*/
import {
from,
empty,
Observable,
} from 'rxjs';
import LinkHeader from 'http-link-header';
const toAsync = (fn:Function) => async (...args:any[]) => fn(...args);
export const toObservable = (fn:Function) => {
const asyncFn = toAsync(fn);
return (...args:any[]) => from(asyncFn(...args));
};
// This section is used for uql dataSource
// TODO this is a mock
type ObjectKeyType = string | number
export type DataSourceDefinition = {
[propName in ObjectKeyType]: unknown;
} & {
query: string;
type: string;
};
export const translateDataSourceDefinitionToFetch = (def:DataSourceDefinition) => def.query; //TODO this is mock function
export const uqlPaginationStretagy = (getDataSource: { (...args: any[]): Observable<any>; (arg0: any): any; }, res:Response)=> {
const linkHeader = res.headers.get('Link');
const next = LinkHeader.parse(linkHeader).get('rel', 'next');
if (next.length) {
return getDataSource(next[0].uri);
}
return empty();
}
|
5944d82d42140fe994439bf9db02032ce4df1361
|
TypeScript
|
leonamtv/base-converter
|
/base-conversor/src/app/app.component.ts
| 2.65625
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
base2: string = '0'
base8: string = '0'
base10: string = '0'
base16: string = '0'
base2Only ( event: any ) {
let k = event.charCode
let result = ( k == 48 || k == 49 )
return result
}
base8Only ( event: any ) {
let k = event.charCode
let result = ( k >= 48 && k <= 55 )
return result
}
base10Only ( event: any ) {
let k = event.charCode
let result = ( k >= 97 && k <= 103 ) || ( k >= 65 && k <= 71 ) || ( k >= 48 && k <= 57 )
return result
}
base16Only ( event: any ) {
let k = event.charCode
let result = ( k >= 48 && k <= 57 )
return result
}
fromBase2 () {
this.base10 = ( Number( '0b' + this.base2 )).toString()
this.base8 = ( Number( this.base10 ) >>> 0 ).toString(8)
this.base16 = ( Number( this.base10 ) >>> 0 ).toString(16).toUpperCase()
}
fromBase8 () {
this.base10 = ( Number( '0o' + this.base8 )).toString()
this.base2 = ( Number( this.base10 ) >>> 0 ).toString(2)
this.base16 = ( Number( this.base10 ) >>> 0 ).toString(16).toUpperCase()
}
fromBase16 () {
this.base10 = ( Number( '0x' + this.base16 )).toString()
this.base2 = ( Number( this.base10 ) >>> 0 ).toString(2)
this.base8 = ( Number( this.base10 ) >>> 0 ).toString(8)
}
fromBase10 () {
this.base2 = ( Number( this.base10 ) >>> 0 ).toString(2)
this.base8 = ( Number( this.base10 ) >>> 0 ).toString(8)
this.base16 = ( Number( this.base10 ) >>> 0 ).toString(16).toUpperCase()
}
}
|
ee48d547093dce49cb7d751df84f81f5d52534eb
|
TypeScript
|
guagin/foodies_0321
|
/src/authentication/command/domain/user/service/user-login-service.ts
| 2.71875
| 3
|
import { UserRepository } from "../user-repository"
import { User } from "../model/user"
import { UserEventPublisher } from "../event/user-event-publisher"
import { UserNotFound } from "../error/user-not-found"
import { PasswordNotMatched } from "../error/password-not-matched"
export class UserLoginService {
private userRepository: UserRepository
private encrypt: (value: string) => string
private generateToken: (user: User) => string
private userEventPublisher: UserEventPublisher
constructor(input: {
userRepository: UserRepository
encrypt: (value: string) => string
generateToken: (user: User) => string
userEventPublisher: UserEventPublisher
}) {
this.userRepository = input.userRepository
this.encrypt = input.encrypt
this.generateToken = input.generateToken
this.userEventPublisher = input.userEventPublisher
}
async login(name: string, password: string): Promise<string> {
const user = await this.userRepository.ofName(name)
if (!user) {
throw new UserNotFound()
}
if (!user.isPasswordMatched(this.encrypt(password))) {
throw new PasswordNotMatched("user password not matched.")
}
this.userEventPublisher.userLogined({
id: user.id.toValue(),
name: user.name
})
return this.generateToken(user)
}
}
|
0f3c3a76fd93cf3f6b95e8ace3e6833488c19761
|
TypeScript
|
tylearymf/psd2ugui.ts
|
/src/Factories/NodeFactory.ts
| 2.515625
| 3
|
namespace psd2ugui {
export class NodeFactory {
public static GetInstanceByType(baseLayer: BaseLayer) {
var nodeType = baseLayer.nodeType
Global.GetInstance().mainDoc.activeLayer = baseLayer.layer
let node: BaseNode
switch (nodeType) {
case ComponentType.LABEL:
node = new LabelNode(baseLayer)
break;
case ComponentType.SPRITE:
node = new SpriteNode(baseLayer)
break;
case ComponentType.SLICE:
node = new SliceNode(baseLayer)
break;
case ComponentType.TEXTURE:
node = new TextureNode(baseLayer)
break;
case ComponentType.BUTTON:
node = new ButtonNode(baseLayer)
break;
case ComponentType.PANEL:
node = new PanelNode(baseLayer)
break;
case ComponentType.WINDOW:
node = new WindowNode(baseLayer)
break;
default:
throw new Error(`NodeFactory.GetInstanceByType(). 没有实现该节点类型:: ${nodeType}`);
break;
}
return node
}
}
}
|
828e8fb706f64606d7112f991f0b9c9343ffeea3
|
TypeScript
|
ldh2016/test
|
/testDictionary/src/LayaSample.ts
| 3.71875
| 4
|
// 程序入口
class GameMain {
private dic: Laya.Dictionary;
constructor() {
Laya.init(600, 400);
this.dic = new Laya.Dictionary();
//生成3个玩家信息
for (let i: number = 0; i < 3; i++) {
let roleInfo: RoleInfo = new RoleInfo();
roleInfo.account = "role_" + (i + 1);
this.dic.set(roleInfo.account, roleInfo);//往字典存数据 用键值形式存 key(roleInfo.account) value(roleInfo)
}
Laya.stage.on(Laya.Event.CLICK, this, this.onClick);
}
private onClick(): void {
//数据的获取
//比如我们要获取account为role_2的对象 我们可以这样子获取
let roleInfo: RoleInfo = this.dic.get("role_2"); //通过一个key去获取一个对象 这里的key就是role_2 获取到的value的类型 就是你存进去的类型
console.log(roleInfo);
//判断一个对象是否存在
let ind: number = this.dic.indexOf("role_22");
if (ind == -1) {
console.log("对象不存在");
}
//删除操作
//删除某个指定的key的对象
this.dic.remove("role_2"); //通过键删除对应的value
//全部删除:
this.dic.clear();
//转为数组
let datas: any[] = this.dic.values;
//这样子你可以获得数组长度
console.log(datas.length);
//Dictionary 相对于 数组 有什么好处呢?
//好处的话 存取比较方便 直接采取key_value存数据 取数据 通关key 去获取value 相比之前的for循环遍历的话 肯定是效率和速度上比较好
}
}
new GameMain();
|
b13bc9e073cba20cef7ca204753198af6fcdf250
|
TypeScript
|
studiometa/js-toolkit
|
/packages/js-toolkit/utils/math/clamp.ts
| 3.609375
| 4
|
/**
* Clamp a value in a given range.
*
* @param {number} value
* @param {number} min
* @param {number} max
* @returns {number}
*/
export default function clamp(value: number, min: number, max: number) {
/* eslint-disable no-nested-ternary */
return min < max
? value < min
? min
: value > max
? max
: value
: value < max
? max
: value > min
? min
: value;
/* eslint-enable no-nested-ternary */
}
|
d6eb6c63c1f7fcc853e09631000a62c055cc5168
|
TypeScript
|
Veams/http-service
|
/src/index.ts
| 2.796875
| 3
|
/**
* Represents a simple http service, which returns a promise.
*
* @module http
* @author Sebastian Fitzner
*/
// Imports
import Base from '@veams/base';
export interface RequestObject {
method?: string;
url?: string;
type?: string;
data?: string;
}
export interface ServiceOptions {
url?: string,
type?: string,
method?: string,
fetchOnInit?: boolean,
headers?: object
}
export interface Parser {
type: string,
request: Request
}
export interface Request {
responseText: string;
status: number;
statusText: string;
}
class HttpService extends Base {
data: any;
options: ServiceOptions;
constructor(options: ServiceOptions = {}) {
let namespace = '@veams/http-service';
let defaultOptions = {
url: null,
type: 'text',
method: 'GET',
fetchOnInit: false,
headers: null
};
super({namespace, options}, defaultOptions);
this.data = {};
this.initialize();
};
initialize() {
if (!window['Promise']) {
console.error('@veams/http-service :: You should add a lightweight promise library like promise-polyfill!');
}
if (this.options.fetchOnInit) {
return this.promiseRequest();
}
};
// Request lifecycle
requestWillOpen(request: XMLHttpRequest, obj) {
}
requestDidOpen(request: XMLHttpRequest, obj) {
if (this.options.headers) {
for (let header in this.options.headers) {
if (this.options.headers.hasOwnProperty(header)) {
request.setRequestHeader(header, this.options.headers[header]);
}
}
}
}
requestWillLoad(request: XMLHttpRequest, obj) {
}
requestDidLoad(request: XMLHttpRequest, obj) {
}
requestWillSend(request: XMLHttpRequest, obj) {
}
requestDidSend(request: XMLHttpRequest, obj) {
}
// Request function
promiseRequest(obj?: RequestObject) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
let data = obj.type === 'json' ? JSON.stringify(obj.data) : obj.data;
this.requestWillOpen(request, obj);
request.open(obj.method, obj.url, true);
this.requestDidOpen(request, obj);
this.requestWillLoad(request, obj);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
resolve(this.parser({
request: request,
type: obj.type
}));
this.requestDidLoad(request, obj);
} else {
reject(this.parser({
request: request,
type: obj.type
}));
this.requestDidLoad(request, obj);
}
};
request.onerror = () => {
reject(this.parser({
request: request,
type: obj.type
}));
};
this.requestWillSend(request, obj);
request.send(data);
this.requestDidSend(request, obj);
});
};
get(url = null) {
let requestObject: RequestObject = {};
this.options.method = requestObject.method = 'GET';
this.options.url = requestObject.url = url || this.options.url;
this.options.type = requestObject.type = this.options.type;
return this.promiseRequest(requestObject);
};
delete(url = null) {
let requestObject: RequestObject = {};
requestObject.method = 'DELETE';
requestObject.url = url || this.options.url;
// requestObject.type = this.options.type;
return this.promiseRequest(requestObject);
}
post(url = null, data) {
let requestObject: RequestObject = {};
requestObject.data = data ? data : null;
requestObject.method = 'POST';
requestObject.url = url || this.options.url;
requestObject.type = this.options.type;
if (this.options.type === 'json' && this.options.headers === null) {
this.options.headers = {
'content-type': 'application/json'
};
}
return this.promiseRequest(requestObject);
}
put(url = null, data) {
let requestObject: RequestObject = {};
requestObject.data = data ? data : null;
requestObject.method = 'PUT';
requestObject.url = url || this.options.url;
requestObject.type = this.options.type;
if (this.options.type === 'json' && this.options.headers === null) {
this.options.headers = {
'content-type': 'application/json'
};
}
return this.promiseRequest(requestObject);
}
/**
* The default parser, which returns the response text.
* This method can be overridden.
*
* @param {Object} obj - Generic object.
* @param {Object} obj.request - Request object.
* @param {String} obj.type - Define a type for the response text.
* @param {Object} obj.data - Data object.
*/
parser(obj: Parser): object {
this.data = obj.request.responseText;
if (obj.type === 'json') {
this.data = JSON.parse(this.data);
}
return this.data;
}
}
export default HttpService;
|
05462d891a076b606afb57dd88d6e56afd3d1351
|
TypeScript
|
milkshakeWaves/menu-code-test-react
|
/src/rules/PierreWaiterRule.ts
| 2.875
| 3
|
import { Order } from "../models/Order";
import { Dish } from "../models/Dish";
import { Rule, RuleResult } from "./Rule";
const PRAWN_COCKTAIL_ID = 4;
const SALMON_FILLET_ID = 7;
export default class PierreWaiterRule implements Rule {
check(orders: Order[]): RuleResult {
for (let i = 0; i < orders.length; ++i) {
const orderCheck = orders[i].filter(
(dish: Dish) =>
dish.id === PRAWN_COCKTAIL_ID ||
dish.id === SALMON_FILLET_ID
);
if (orderCheck.length === 2) {
return {
ok: false,
message: `Diner ${
i + 1
}, you cannot choose prawn cocktail and salmon fillet in the same meal!`,
};
}
}
return {
ok: true,
};
}
}
|
d59b2ce78a6f1d90ab0deb3b351bffb4b9e2c237
|
TypeScript
|
NatalyStroynov/techsee
|
/src/app/app.service.ts
| 2.703125
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map,tap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json','Access-Control-Allow-Origin':'*'})
};
export interface Tester {
firstName :string,
lastName :string,
country :string,
device : string,
bugs :any[]
}
@Injectable({
providedIn: 'root'
})
export class AppService {
private testersUrl = "https://test-api.techsee.me/api/ex/";
constructor(
private http:HttpClient
) { }
getAllTesters():Observable<Tester[]>{
console.log("app servers getAllTesters");
return this.http.get<Tester[]>(this.testersUrl+"all")
.pipe(
tap(data => console.log('fetched testers', data),
catchError(this.handleError('getTesters', [])))
);
}
getTester(testerName:string):Observable<Tester>{
console.log("app servers getlTesters");
return this.http.get<Tester>(this.testersUrl+testerName)
.pipe(
tap(data => console.log('fetched tester', testerName),
catchError(this.handleError('getTester', [])))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
/** Log a Testers Service message with the MessageService */
private log(message: string) {
//this.messageService.add(`TestersService: ${message}`);
console.log("testers service",message);
}
}
|
5cce75574032946c4c50e7f0811985054481ecf0
|
TypeScript
|
Algoritm211/painting-market
|
/src/store/paintingsStore.ts
| 2.640625
| 3
|
import {action, makeAutoObservable, observable, runInAction} from "mobx";
import {IPainting} from "../types/types";
import {paintingsTestAPI} from "../api/api";
import Venera from "../assets/paintings/venera_born.png";
import Dinner from "../assets/paintings/dinner.png";
import Adam from "../assets/paintings/adam.png";
import AnatomyLessons from '../assets/paintings/anatomy_lessons.png'
class PaintingsStore {
@observable paintings: Array<IPainting> = [
{
id: 1,
imgURL: Venera,
title: 'Рождение Венеры',
author: 'Сандро Боттичелли',
startPrice: '2 000 000 $',
price: '1 000 000 $',
isInBasket: false,
isLoading: false,
isSold: false
},
{
id: 2,
imgURL: Dinner,
title: 'Тайная вечеря',
author: 'Леонардо да Винчи',
price: '3 000 000 $',
isInBasket: false,
isLoading: false,
isSold: false
},
{
id: 3,
imgURL: Adam,
title: 'Сотворение Адама»',
author: 'Микеланджело',
startPrice: '6 000 000 $',
price: '5 000 000 $',
isInBasket: false,
isLoading: false,
isSold: false
},
{
id: 4,
imgURL: AnatomyLessons,
title: 'Уроки Анатомии',
author: 'Рембрандт',
startPrice: '6 000 000 $',
price: '5 000 000 $',
isInBasket: false,
isLoading: false,
isSold: true
},
]
@observable searchString: string = ''
constructor() {
makeAutoObservable(this)
}
@action
buyPainting = async (id: number) => {
let painting = this.paintings.find(painting => painting.id === id) as IPainting
painting.isLoading = true
await paintingsTestAPI.buyPainting()
runInAction(() => {
painting.isLoading = false
painting.isInBasket = true
})
}
removeFromBasket = async (id: number) => {
let painting = this.paintings.find(painting => painting.id === id) as IPainting
painting.isLoading = true
await paintingsTestAPI.buyPainting()
runInAction(() => {
painting.isLoading = false
painting.isInBasket = false
})
}
@action
setSearchString = (searchStr: string) => {
this.searchString = searchStr
}
}
export default new PaintingsStore()
|
f19b833aebedc304253257d3cbe10f5555b390af
|
TypeScript
|
covertbert/cats-api-graphql
|
/src/mutations/createCat/mutation.ts
| 2.578125
| 3
|
import { UserInputError } from 'apollo-server'
import logger from '../../logger'
import { Cat } from '../../types/Cat'
import { Resolver } from '../../types/GraphQl'
const createCat: Resolver = async (
_,
args: {
cat: Omit<Cat, 'id'>
},
context
) => {
const { cat } = args
const { CatService } = context.services
try {
let catId: number
try {
catId = await CatService.create(args.cat)
} catch (e) {
if (e.code === '23505') {
return new UserInputError(e.detail)
}
throw Error('Unable to insert cat into the database')
}
return {
id: catId,
name: cat.name,
}
} catch (e) {
logger.error({
error: e.message,
message: 'Failed to add cat to database',
})
}
}
export default createCat
|
991b1c8a125a259d55aa5392756b4772da56de6e
|
TypeScript
|
stentorium/stentor
|
/packages/stentor-guards/src/isActionable.ts
| 2.859375
| 3
|
/*! Copyright (c) 2019, XAPPmedia */
import { Actionable } from "stentor-models";
/**
* Guard to check if the object is actionable.
*
* @param {(T | Actionable<T>)} potential
* @returns {potential is Actionable<T>}
*/
export function isActionable(potential: object | Actionable): potential is Actionable {
return !!potential && Array.isArray((potential as Actionable).actions);
}
|
ab58ad146674ad52e82b090b3c37897024506ad2
|
TypeScript
|
samousavih/fullstack-typescript-mono-repo
|
/common/index.ts
| 2.5625
| 3
|
import { isBuffer } from "node:util";
export interface IUser {
id: string;
name: string;
}
export type GetUser = (id: string) => Promise<IUser>;
export interface ICanGetUser {
getUser(id: string): Promise<IUser>;
}
|
f4866897d3e8c30a0a74498ceb8377bc216500b1
|
TypeScript
|
AlexcastroDev/castroclock
|
/__tests__/CastroClock.spec.ts
| 2.734375
| 3
|
import { CastroClock } from '../src/index'
import {
initialCurrentTimeString,
initialCurrentTime,
} from './__mocks__/CastroClock.mocks'
import {
initialTimerProxy,
} from './__mocks__/instance.mocks'
jest.setTimeout(10000);
describe('Chronometer Functions', () => {
beforeEach(() => {
CastroClock.reset()
});
it('Should mount initial status', () => {
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
expect(CastroClock.currentTime).toEqual(initialCurrentTime);
expect(CastroClock.timer).toEqual(initialTimerProxy);
});
it('Should start chronometer and wait 2 seconds and match results', async () => {
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
CastroClock.start();
await new Promise((r) => setTimeout(r, 2000));
expect(CastroClock.currentTimeString).toBe('00:00:02');
});
it('Should start, pause, wait and match results', async () => {
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
CastroClock.start();
await new Promise((r) => setTimeout(r, 2000));
expect(CastroClock.currentTimeString).toBe('00:00:02');
CastroClock.pause();
await new Promise((r) => setTimeout(r, 2000));
expect(CastroClock.currentTimeString).toBe('00:00:02');
});
it('Should start, reset, and mount initial status', async () => {
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
CastroClock.start();
await new Promise((r) => setTimeout(r, 2000));
CastroClock.reset();
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
});
it('Should start, call lap, reset count, and store first lap', async () => {
CastroClock.start();
await new Promise((r) => setTimeout(r, 2000));
CastroClock.lap();
expect(CastroClock.currentTimeString).toBe(initialCurrentTimeString);
expect(CastroClock.timer.stops[0]).toEqual(expect.objectContaining({
ends_at: expect.any(Number),
start_at: expect.any(Number),
period: expect.stringMatching('00:00:02'),
}))
});
})
describe('Chronometer Prevent Errors', () => {
beforeEach(() => {
CastroClock.reset()
});
it('Shouldn\'t call chronometer.start twice', async () => {
CastroClock.start();
const error = CastroClock.start;
expect(error).toThrow(TypeError);
expect(error).toThrow('You already have started chronometer');
});
it('Shouldn\'t call chronometer.pause without start', async () => {
const error = CastroClock.pause
expect(error).toThrow(TypeError);
expect(error).toThrow('You must have to start chronometer before run it');
});
it('Shouldn\'t call chronometer.continue without start', async () => {
const error = CastroClock.pause
expect(error).toThrow(TypeError);
expect(error).toThrow('You must have to start chronometer before run it');
});
it('Shouldn\'t call chronometer.lap without start', async () => {
const error = CastroClock.lap
expect(error).toThrow(TypeError);
expect(error).toThrow('You must have to start chronometer before run it');
});
it('Shouldn\'t set onChange as string, number, object', async () => {
expect(() => CastroClock.onChange('hi')).toThrow(TypeError);
expect(() => CastroClock.onChange(123)).toThrow(TypeError);
expect(() => CastroClock.onChange({})).toThrow(TypeError);
});
})
|
7d023e005c4d72aa5e833066fb86ea3a0cd6bbf6
|
TypeScript
|
k3ith-fowl3r/platform
|
/modules/component-store/src/tap-response.ts
| 3.140625
| 3
|
import { EMPTY, Observable } from 'rxjs';
import { catchError, finalize, tap } from 'rxjs/operators';
type TapResponseObserver<T, E> = {
next: (value: T) => void;
error: (error: E) => void;
complete?: () => void;
finalize?: () => void;
};
export function tapResponse<T, E = unknown>(
observer: TapResponseObserver<T, E>
): (source$: Observable<T>) => Observable<T>;
export function tapResponse<T, E = unknown>(
next: (value: T) => void,
error: (error: E) => void,
complete?: () => void
): (source$: Observable<T>) => Observable<T>;
/**
* Handles the response in ComponentStore effects in a safe way, without
* additional boilerplate. It enforces that the error case is handled and
* that the effect would still be running should an error occur.
*
* Takes optional callbacks for `complete` and `finalize`.
*
* @usageNotes
*
* ```ts
* readonly dismissAlert = this.effect<Alert>((alert$) => {
* return alert$.pipe(
* concatMap(
* (alert) => this.alertsService.dismissAlert(alert).pipe(
* tapResponse(
* (dismissedAlert) => this.alertDismissed(dismissedAlert),
* (error: { message: string }) => this.logError(error.message)
* )
* )
* )
* );
* });
*
* readonly loadUsers = this.effect<void>((trigger$) => {
* return trigger$.pipe(
* tap(() => this.patchState({ loading: true })),
* exhaustMap(() =>
* this.usersService.getAll().pipe(
* tapResponse({
* next: (users) => this.patchState({ users }),
* error: (error: HttpErrorResponse) => this.logError(error.message),
* finalize: () => this.patchState({ loading: false }),
* })
* )
* )
* );
* });
* ```
*/
export function tapResponse<T, E>(
observerOrNext: TapResponseObserver<T, E> | ((value: T) => void),
error?: (error: E) => void,
complete?: () => void
): (source$: Observable<T>) => Observable<T> {
const observer: TapResponseObserver<T, E> =
typeof observerOrNext === 'function'
? {
next: observerOrNext,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
error: error!,
complete,
}
: observerOrNext;
return (source) =>
source.pipe(
tap({ next: observer.next, complete: observer.complete }),
catchError((error) => {
observer.error(error);
return EMPTY;
}),
observer.finalize ? finalize(observer.finalize) : (source$) => source$
);
}
|
eb294feedc3f2a4b9d6c69a12ebcea0e6a812062
|
TypeScript
|
alex-haas/angular-gof2
|
/src/app/gof/gof.component.ts
| 2.59375
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-gof',
templateUrl: './gof.component.html',
styleUrls: ['./gof.component.css']
})
export class GofComponent implements OnInit {
width: number = 16;
height: number = 48;
cellSize: number = 10;
rows: number[] = Array(this.height).fill(0).map((x,i)=>i);
columns: number[] = Array(this.width).fill(0).map((x,i)=>i);
data: boolean[][] = Array(this.height).fill(0).map((x,i)=>Array(this.width));
constructor() { }
ngOnInit() {
}
clicked(x: number, y: number) {
this.data[y][x] = !this.data[y][x];
}
next_state(x: number, y: number) {
var cnt = 0;
if (y > 0) {
cnt += this.data[y - 1][x] ? 1 : 0;
}
if (y < this.height - 1) {
cnt += this.data[y + 1][x] ? 1 : 0;
}
if (x > 0) {
cnt += this.data[y][x - 1] ? 1 : 0;
if (y > 0) {
cnt += this.data[y - 1][x - 1] ? 1 : 0;
}
if (y < this.height - 1) {
cnt += this.data[y + 1][x - 1] ? 1 : 0;
}
}
if (x < this.width - 1) {
cnt += this.data[y][x + 1] ? 1 : 0;
if (y > 0) {
cnt += this.data[y - 1][x + 1] ? 1 : 0;
}
if (y < this.height - 1) {
cnt += this.data[y + 1][x + 1] ? 1 : 0;
}
}
if (this.data[y][x]) {
return cnt == 2 || cnt == 3;
} else {
return cnt == 3;
}
}
next() {
let new_data = Array(this.height).fill(0).map((x,i)=>Array(this.width));
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
new_data[y][x] = this.next_state(x, y);
}
}
this.data = new_data;
}
}
|
d3fece62defecc35ad3545d998850f51a9623645
|
TypeScript
|
green-fox-academy/vis0rka
|
/week-04/day-2/post-it.ts
| 3.453125
| 3
|
class PostIt {
backgroundColor: string;
text: string;
textColor: string;
constructor(message:string,textColor:string,backgroundColor:string) {
this.text = message;
this.backgroundColor = backgroundColor;
this.textColor = textColor;
}
textPostIt():string {
return `post it text: ${this.text} text color: ${this.textColor} backgroundcolor: ${this.backgroundColor}`;
}
}
let postit1 = new PostIt("Idea1","blue","orange");
let postit2 = new PostIt("Awesome","black","pink");
let postit3 = new PostIt("Superb!","green","yellow");
console.log(postit1.textPostIt());
console.log(postit2.textPostIt());
console.log(postit3.textPostIt());
|
dc49392aca6f7cc495c1977f5541f740151ec53a
|
TypeScript
|
ngxs/store
|
/packages/logger-plugin/src/log-writer.ts
| 2.75
| 3
|
import { NgxsLoggerPluginOptions } from './symbols';
export class LogWriter {
private logger: any;
constructor(private options: NgxsLoggerPluginOptions) {
this.options = this.options || <any>{};
this.logger = options.logger || console;
}
startGroup(message: string) {
const startGroupFn = this.options.collapsed
? this.logger.groupCollapsed
: this.logger.group;
try {
startGroupFn.call(this.logger, message);
} catch (e) {
console.log(message);
}
}
endGroup() {
try {
this.logger.groupEnd();
} catch (e) {
this.logger.log('—— log end ——');
}
}
logGrey(title: string, payload: any) {
const greyStyle = 'color: #9E9E9E; font-weight: bold';
this.log(title, greyStyle, payload);
}
logGreen(title: string, payload: any) {
const greenStyle = 'color: #4CAF50; font-weight: bold';
this.log(title, greenStyle, payload);
}
logRedish(title: string, payload: any) {
const redishStyle = 'color: #FD8182; font-weight: bold';
this.log(title, redishStyle, payload);
}
log(title: string, color: string, payload: any) {
if (this.isIE()) {
this.logger.log(title, payload);
} else {
this.logger.log('%c ' + title, color, payload);
}
}
isIE(): boolean {
const ua =
typeof window !== 'undefined' && window.navigator.userAgent
? window.navigator.userAgent
: '';
let msIE = false;
const oldIE = ua.indexOf('MSIE ');
const newIE = ua.indexOf('Trident/');
if (oldIE > -1 || newIE > -1) {
msIE = true;
}
return msIE;
}
}
|
7578fac34f14811851936fba825022f9ecceae95
|
TypeScript
|
ngAnzar/core
|
/src/animation.module/renderer.service.ts
| 2.546875
| 3
|
import { Injectable, ElementRef, Inject, Optional, Renderer2, RendererFactory2, RendererStyleFlags2 } from "@angular/core"
import { memoize } from "../util"
@Injectable()
export class Renderer extends Renderer2 {
@memoize()
public get renderer(): Renderer2 {
if (this._renderer) {
const r = this._renderer
delete this._renderer
return this._renderer
} else {
return this._factory.createRenderer(this._elRef ? this._elRef.nativeElement : null, null)
}
}
private _renderer: any
public constructor(
@Inject(ElementRef) @Optional() private _elRef: ElementRef,
// @Inject(Renderer2) @Optional() private _renderer: Renderer2,
@Inject(RendererFactory2) private _factory: RendererFactory2) {
super()
}
public get data(): { [key: string]: any; } { return this.renderer.data }
public destroy(): void { this.renderer.destroy() }
public createElement(name: string, namespace?: string): any { return this.renderer.createElement(name, namespace) }
public createComment(value: string): any { return this.renderer.createComment(value) }
public createText(value: string): any { return this.renderer.createText(value) }
public appendChild(parent: any, newChild: any): void { this.renderer.appendChild(parent, newChild) }
public insertBefore(parent: any, newChild: any, refChild: any): void { this.renderer.insertBefore(parent, newChild, refChild) }
public removeChild(parent: any, oldChild: any): void { this.renderer.removeChild(parent, oldChild) }
public selectRootElement(selectorOrNode: any): any { return this.renderer.selectRootElement(selectorOrNode) }
public parentNode(node: any): any { return this.renderer.parentNode(node) }
public nextSibling(node: any): any { return this.renderer.nextSibling(node) }
public setAttribute(el: any, name: string, value: string, namespace?: string): void { this.renderer.setAttribute(el, name, value, namespace) }
public removeAttribute(el: any, name: string, namespace?: string): void { this.renderer.removeAttribute(el, name, namespace) }
public addClass(el: any, name: string): void { this.renderer.addClass(el, name) }
public removeClass(el: any, name: string): void { this.renderer.removeClass(el, name) }
public setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void { this.renderer.setStyle(el, style, value, flags) }
public removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void { this.renderer.removeStyle(el, style, flags) }
public setProperty(el: any, name: string, value: any): void { this.renderer.setProperty(el, name, value) }
public setValue(node: any, value: string): void { this.renderer.setValue(node, value) }
public listen(target: any, eventName: string, callback: (event: any) => boolean | void): () => void { return this.renderer.listen(target, eventName, callback) }
}
|
3a16c9151606f87ab03a9f8eb43517c3a81aec0e
|
TypeScript
|
DmitryAstafyev/ceres
|
/server/transports/ws/src/transport.connection.ts
| 2.6875
| 3
|
import * as HTTP from 'http';
import { Tools } from 'ceres.provider';
type THeaders = { [key: string]: string };
export class Connection extends Tools.EventEmitter {
public static EVENTS = {
onAborted: Symbol(),
};
private _request: HTTP.IncomingMessage;
private _response: HTTP.ServerResponse;
private _maxSize: number;
private _CORS: boolean;
private _clientGUID: string | null = null;
private _allowedHeaders: string[];
constructor(request: HTTP.IncomingMessage, response: HTTP.ServerResponse, maxSize: number, CORS: boolean, allowedHeaders: string[] | undefined) {
super({ strict: true });
this._request = request;
this._response = response;
this._maxSize = maxSize;
this._CORS = CORS;
this._onAborted = this._onAborted.bind(this);
this._allowedHeaders = allowedHeaders instanceof Array ? allowedHeaders : [];
this._request.on('aborted', this._onAborted);
}
public setClientGUID(clientGUID: string): null | Error {
if (this._clientGUID !== null) {
return new Error(`Client GUID is already assigned`);
}
this._clientGUID = clientGUID;
return null;
}
public getClientGUID(): string | null {
return this._clientGUID;
}
public getRequest(): Promise<string | Uint8Array> {
return new Promise((resolve, reject) => {
let str: string = '';
const buffer: number[] = [];
let error: Error | null = null;
this._request.on('data', (data) => {
if (error !== null) {
return;
}
if (data instanceof Buffer) {
buffer.push(...data);
} else {
str += data;
}
if (str.length > this._maxSize || buffer.length > this._maxSize) {
error = new Error(`Length of request to big. Maximum length of request is: ${this._maxSize} bytes`);
this._request.destroy(error);
reject(error);
}
});
this._request.on('end', () => {
if (error !== null) {
return;
}
if (buffer.length > 0) {
resolve(new Uint8Array(buffer));
} else {
resolve(str);
}
});
});
}
public close(response: string | Uint8Array): Promise<void> {
return new Promise((resolve, reject) => {
if (typeof response !== 'string' && !(response instanceof Uint8Array)) {
return reject(new Error(`To client can be sent only {string} or {Uint8Array}, but here is attempt to send: ${typeof response}.`));
}
this._setHeaders(response instanceof Uint8Array ? true : false);
this._response.write(
(response instanceof Uint8Array ? new Buffer(response) : response),
(response instanceof Uint8Array ? 'binary' : 'utf8'),
(error: Error | null | undefined) => {
if (error) {
return reject();
}
this._response.end(() => {
resolve();
}, (response instanceof Uint8Array ? 'binary' : 'utf8'));
},
);
});
}
private _onAborted() {
this.emit(Connection.EVENTS.onAborted, this);
}
private _setHeaders(binary: boolean = false) {
const headers: THeaders = {
"Content-Type": binary ? "application/octet-stream" : "text/plain",
};
if (this._allowedHeaders.length > 0) {
headers['Access-Control-Allow-Headers'] = `${this._allowedHeaders.join(',')}`;
}
if (this._CORS) {
headers['Access-Control-Allow-Origin'] = '*';
}
this._response.writeHead(200, headers);
}
}
|
e65e424943d1895d8dd6291bf6bb2196d5ba3256
|
TypeScript
|
abhioshar/meanapp
|
/angular-src/src/app/helper/player.ts
| 3.015625
| 3
|
export class Player {
score: number = 0;
isComputer: boolean = true;
updateScore(increment: number) {
this.score += increment;
}
}
|
126b322edf390566ab672726467710178a73edcd
|
TypeScript
|
textlint/textlint
|
/packages/@textlint/kernel/test/messages/sort-messages-process-test.ts
| 2.59375
| 3
|
// LICENSE : MIT
"use strict";
import * as assert from "assert";
import sortMessages from "../../src/messages/sort-messages-process";
import { TextlintMessage } from "@textlint/types";
const createTextlintMessage = (
message: Partial<TextlintMessage> & { line: number; column: number }
): TextlintMessage => {
return {
// No Used
ruleId: "test",
severity: 1,
index: 0,
range: [0, 1],
loc: {
start: {
line: 1,
column: 0
},
end: {
line: 1,
column: 1
}
},
type: "lint",
message: "test",
...message
};
};
describe("sort-message-test", function () {
context("when empty array", function () {
it("should return empty array", function () {
assert.equal(sortMessages([]).length, 0);
});
});
context("when reverse line", function () {
it("should sort by line and column", function () {
const message = [
createTextlintMessage({ line: 3, column: 1 }),
createTextlintMessage({ line: 1, column: 1 })
];
const expected = [
createTextlintMessage({ line: 1, column: 1 }),
createTextlintMessage({ line: 3, column: 1 })
];
assert.deepEqual(sortMessages(message), expected);
});
});
context("when reverse column", function () {
it("should sort by line and column", function () {
const message = [
createTextlintMessage({ line: 1, column: 3 }),
createTextlintMessage({ line: 1, column: 1 })
];
const expected = [
createTextlintMessage({ line: 1, column: 1 }),
createTextlintMessage({ line: 1, column: 3 })
];
assert.deepEqual(sortMessages(message), expected);
});
});
context("when reverse both", function () {
it("should sort by line and column", function () {
const message = [
createTextlintMessage({ line: 3, column: 3 }),
createTextlintMessage({ line: 1, column: 1 }),
createTextlintMessage({ line: 2, column: 2 })
];
const expected = [
createTextlintMessage({ line: 1, column: 1 }),
createTextlintMessage({ line: 2, column: 2 }),
createTextlintMessage({ line: 3, column: 3 })
];
assert.deepEqual(sortMessages(message), expected);
});
});
});
|
6a5f8618add521fa8e4e35d71709061aaf388732
|
TypeScript
|
shankarganesh1234/BarterUiClient
|
/src/app/models/error-messages.ts
| 2.515625
| 3
|
export class Messages {
user_not_logged_in: string;
orig_user_interested_user_equal: string;
constructor() {
this.user_not_logged_in = "Please log in to facebook to express interests, swap items and more...";
this.orig_user_interested_user_equal = "You cannot express interest for your own items";
}
}
|
c0424296fa79aa962962d680b3e57a152a249c34
|
TypeScript
|
thiscouldbebetter/EconomicsGame
|
/Source/Model/DemoData.ts
| 2.703125
| 3
|
class DemoData
{
world(mapSizeInPixels: Coords): World2
{
var mapSizeInCells = new Coords(16, 16, 1);
var mapCellSizeInPixels = mapSizeInPixels.clone().divide
(
mapSizeInCells
);
var mapTerrains =
[
new MapTerrain
(
"Floor",
".",
1, // costToTraverse
new VisualRectangle
(
mapCellSizeInPixels,
Color.byName("Green"), // colorFill
Color.byName("LightGray"), // colorBorder
null
)
),
new MapTerrain
(
"Wall",
"x",
1000000, // costToTraverse
new VisualRectangle
(
mapCellSizeInPixels,
Color.byName("GrayLight"), // colorFill
Color.byName("White"), // colorBorder
null
)
),
];
var visualPathColor = Color.byName("Tan");
var visualPath = new VisualGroup
([
new VisualPath
(
new Path
([
Coords.fromXY(0, -.5).multiply(mapCellSizeInPixels),
Coords.fromXY(0, .5).multiply(mapCellSizeInPixels),
]),
visualPathColor,
null, null // ?
),
new VisualPath
(
new Path
([
Coords.fromXY(-.5, 0).multiply(mapCellSizeInPixels),
Coords.fromXY(.5, 0).multiply(mapCellSizeInPixels),
]),
visualPathColor,
null, null // ?
),
]);
var mapEmplacementDefns =
[
new MapEmplacementDefn
(
"Path",
"x",
.2, // costToTraverseMultiplier
visualPath
),
];
var map = new MapOfCells2
(
mapSizeInPixels,
mapTerrains,
mapEmplacementDefns,
// cellTerrainsAsStrings
[
"xxxxxxxxxxxxxxxx",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"x..............x",
"xxxxxxxxxxxxxxxx",
],
// cellEmplacementsAsStrings
[
"................",
"................",
"........x.......",
"........x.......",
"........x.......",
"........x.......",
"........x.......",
"....xxxxxxxxx...",
"........x.......",
"........x.......",
"........x.......",
"........x.......",
"........x.......",
"................",
"................",
"................",
]
);
map.terrains = mapTerrains;
var resourceDefns =
[
new ResourceDefn
(
"ResourceDefn0",
new VisualRectangle
(
mapCellSizeInPixels,
null, // colorFill
Color.byName("Red"),
null // ?
)
),
new ResourceDefn
(
"ResourceDefn1",
new VisualRectangle
(
mapCellSizeInPixels,
null, // colorFill
Color.byName("Orange"),
null // ?
)
),
new ResourceDefn
(
"ResourceDefn2",
new VisualRectangle
(
mapCellSizeInPixels,
null, // colorFill
Color.byName("Yellow"),
null // ?
)
)
];
var facilitySize = mapCellSizeInPixels.clone().multiplyScalar(.6);
var facilityDefns = this.world_FacilityDefns(facilitySize)
var agentColor = Color.byName("Gray");
var agentRadius = facilitySize.x / 2;
var agentVisual =
//new VisualCircle(facilitySize.x / 2, agentColor, agentColor);
VisualBuilder.Instance().circleWithEyes
(
agentRadius, agentColor, agentRadius / 2, null
);
var agentDefns =
[
new AgentDefn
(
"AgentDefn0",
agentVisual
)
];
var actions = Action2.Instances2()._All;
var level = new Level
(
"Level0",
map,
new Owner("Owner0"),
// facilities
[
new Facility("House", Coords.fromXY(2, 2)),
new Facility("House", Coords.fromXY(12, 4)),
new Facility("Farm", Coords.fromXY(12, 12)),
new Facility("Marketplace", Coords.fromXY(4, 5)),
],
// agents
[]
);
var world = new World2
(
"World0",
60, // dayNightCyclePeriodInSeconds
resourceDefns,
mapEmplacementDefns,
facilityDefns,
agentDefns,
actions,
level
);
return world;
}
world_FacilityDefns(facilitySize: Coords): FacilityDefn[]
{
var houseColor = Color.byName("GrayDark");
var house = new FacilityDefn
(
"House",
new VisualGroup
([
new VisualPath
(
new Path
([
Coords.fromXY(0, -.5).multiply(facilitySize),
Coords.fromXY(.5, 0).multiply(facilitySize),
Coords.fromXY(.5, .5).multiply(facilitySize),
Coords.fromXY(-.5, .5).multiply(facilitySize),
Coords.fromXY(-.5, 0).multiply(facilitySize)
]),
houseColor,
1, // lineThickness
true, // isClosed
),
VisualText.fromTextAndColor
(
"House", houseColor
)
]),
// resourcesToBuild
[],
// initialize
(world: World2, level: Level, facility: Facility) =>
{
var facilityPosInCells = facility.posInCells;
var agentName = "Agent" + level.facilities.indexOf(facility);
var agent = new Agent(agentName, "AgentDefn0", facilityPosInCells.clone());
level.agents.push(agent);
},
// agentDirect
(world: World2, level: Level, agent: Agent, facility: Facility) =>
{
var isAtGoal = agent.approach
(
world, level, facility
);
if (isAtGoal == true)
{
agent.resourceHolder.resourceTransferToOther
(
new Resource("Food", 1),
facility.resourceHolder
);
}
},
null // interactWith
);
var farmColor = Color.byName("Blue");
var farm = new FacilityDefn
(
"Farm",
new VisualGroup
([
new VisualPath
(
new Path
([
Coords.fromXY(0, -.5).multiply(facilitySize),
Coords.fromXY(.25, -.45).multiply(facilitySize),
Coords.fromXY(.5, 0).multiply(facilitySize),
Coords.fromXY(.5, .5).multiply(facilitySize),
Coords.fromXY(-.5, .5).multiply(facilitySize),
Coords.fromXY(-.5, 0).multiply(facilitySize),
Coords.fromXY(-.25, -.45).multiply(facilitySize),
]),
farmColor,
1, // lineThickness
true // isClosed
),
VisualText.fromTextAndColor
(
"Farm", farmColor
)
]),
// resourcesToBuild
[],
null, // initialize
// agentDirect
(world: World2, level: Level, agent: Agent, facility: Facility) =>
{
var isAtGoal = agent.approach
(
world, level, facility
);
if (isAtGoal == true)
{
facility.resourceHolder.resourceAdd
(
new Resource("Food", 1)
);
}
},
null // interactWith
);
var marketplaceColor = Color.byName("Orange");
var marketplace = new FacilityDefn
(
"Marketplace",
new VisualGroup
([
new VisualRectangle
(
facilitySize,
null, marketplaceColor, // colors
null // ?
),
VisualText.fromTextAndColor
(
"Marketplace", marketplaceColor
)
]),
// resourcesToBuild
[],
null, // initialize
// agentDirect
(world: World2, level: Level, agent: Agent, facility: Facility) =>
{
var isAtGoal = agent.approach
(
world, level, facility
);
if (isAtGoal == true)
{
facility.resourceHolder.resourceTransferToOther
(
new Resource("Food", 1),
agent.resourceHolder
);
}
},
null // interactWith
);
var facilityDefns =
[
house,
farm,
marketplace,
];
return facilityDefns;
}
}
|
968cc76dcd3738394acd65c644d605936b98ce04
|
TypeScript
|
SanjayTalyaOfficial/lab-typescript-string-number-manipulations
|
/started-code/main-service.ts
| 3.109375
| 3
|
//progression 1
export interface StringManipulationService {
print(word:string): void;
printWithSpace(sentence:string) : void;
findVowel(str: string) : void;
}
//progression 3
export interface NumberManipulationService {
findPrime(num:number):void;
findMagic(num:number):void;
}
|
6b6834bcd472673eee260d4b77da5eb7bfbb9e97
|
TypeScript
|
BrennerBatR/nestjs-kafka
|
/src/submission/submission.service.ts
| 2.515625
| 3
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ChallengeService } from '../challenge/challenge.service';
import { Between, FindConditions, Repository } from 'typeorm';
import { Submission, SubmissionStatus } from './entity/submission.entity';
import { CreateSubmissionDTO } from './submission.dto';
@Injectable()
export class SubmissionService {
constructor(
private readonly challengeService: ChallengeService,
@InjectRepository(Submission)
private readonly submissionRepository: Repository<Submission>,
) {}
async find(
take: number,
skip: number,
status?: SubmissionStatus,
dateStart?: string,
dateEnd?: string,
): Promise<Submission[]> {
const findConditions: FindConditions<Submission> = {};
if (status) findConditions.status = status;
if (dateStart) findConditions.createDate = Between(dateStart, dateEnd);
return await this.submissionRepository.find({
where: findConditions,
take,
skip,
order: { createDate: 'DESC' },
});
}
async findOne(id: string): Promise<Submission> {
return await this.submissionRepository.findOne(id);
}
async create(submission: CreateSubmissionDTO): Promise<Submission> {
let status = SubmissionStatus.Pending;
if (!submission.repositoryUrl.match(/github.com/))
status = SubmissionStatus.Error;
else if (
submission.repositoryUrl.split('github.com/')[1].split('/').length !== 2
)
status = SubmissionStatus.Error;
const challenge = await this.challengeService.findOne(
submission.challengeId,
);
if (!challenge) status = SubmissionStatus.Error;
return await this.submissionRepository
.create({ ...submission, status, challenge })
.save();
}
async update(submission: Submission): Promise<Submission> {
return await (await this.submissionRepository.preload(submission)).save();
}
}
|
b0d9b9c441b0035cedb0d525d1654bade3d2485d
|
TypeScript
|
vialab/spatial-abilities-public
|
/frontend/src/js/taskBase/TaskController.ts
| 2.578125
| 3
|
import {Option} from "../ui/Option";
import {TaskDisplay, UserInterface} from "../io";
import {Timer, UnlimitedTimer} from "../metrics";
export abstract class TaskController
{
private promise : Promise<void>;
protected resolve : () => any;
protected reject : (reason : any) => any;
constructor()
{
this.resolve = () => null;
this.reject = (reason : any) => null;
this.promise = new Promise<void>((resolve, reject) =>
{
this.resolve = resolve;
this.reject = reject;
});
}
public async WaitForCompletion() : Promise<void>
{
return this.promise;
}
public Complete() : void
{
this.resolve();
}
Error(reason : any)
{
this.reject(reason);
}
public abstract Submit(selectedOptions : Option | Option[]) : void;
}
class NoDisplay extends TaskDisplay
{
public Display(screen: UserInterface): void
{
}
}
|
d8f87d75525ae9393574a0b7316152cb1d9068ba
|
TypeScript
|
sonuishaq67/tsjs
|
/noobstuff/objInt.ts
| 3.859375
| 4
|
interface ObjectC {
m3: string;
}
interface ObjectB {
m2?: ObjectC;
}
interface ObjectA {
m1?: ObjectB;
}
function print(o: ObjectA): void {
if (o.m1) {
if (o.m1.m2) {
console.log(o.m1.m2.m3);
}
}
}
const obj1: ObjectA = {
m1: undefined,
};
const obj2: ObjectA = {
m1: {
m2: undefined,
},
};
const obj3: ObjectA = {
m1: {
m2: {
m3: "Yeah!",
},
},
};
print(obj1);
print(obj2);
print(obj3);
|
f097871c2c89f3b22582dd00926d64252f0afc16
|
TypeScript
|
Moshiach770/flow-js-sdk
|
/packages/protobuf/src/generated/flow/entities/event.ts
| 2.734375
| 3
|
import * as pb_1 from "google-protobuf";
export namespace entities {
export class Event extends pb_1.Message {
constructor(data?: any[] | {
type?: string;
transaction_id?: Uint8Array;
transaction_index?: number;
event_index?: number;
payload?: Uint8Array;
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) && data, 0, -1, [], null);
if (!Array.isArray(data) && typeof data == "object") {
this.type = data.type;
this.transaction_id = data.transaction_id;
this.transaction_index = data.transaction_index;
this.event_index = data.event_index;
this.payload = data.payload;
}
}
get type(): string | undefined {
return pb_1.Message.getFieldWithDefault(this, 1, undefined) as string | undefined;
}
set type(value: string) {
pb_1.Message.setField(this, 1, value);
}
get transaction_id(): Uint8Array | undefined {
return pb_1.Message.getFieldWithDefault(this, 2, undefined) as Uint8Array | undefined;
}
set transaction_id(value: Uint8Array) {
pb_1.Message.setField(this, 2, value);
}
get transaction_index(): number | undefined {
return pb_1.Message.getFieldWithDefault(this, 3, undefined) as number | undefined;
}
set transaction_index(value: number) {
pb_1.Message.setField(this, 3, value);
}
get event_index(): number | undefined {
return pb_1.Message.getFieldWithDefault(this, 4, undefined) as number | undefined;
}
set event_index(value: number) {
pb_1.Message.setField(this, 4, value);
}
get payload(): Uint8Array | undefined {
return pb_1.Message.getFieldWithDefault(this, 5, undefined) as Uint8Array | undefined;
}
set payload(value: Uint8Array) {
pb_1.Message.setField(this, 5, value);
}
toObject() {
return {
type: this.type,
transaction_id: this.transaction_id,
transaction_index: this.transaction_index,
event_index: this.event_index,
payload: this.payload
};
}
serialize(w?: pb_1.BinaryWriter): Uint8Array | undefined {
const writer = w || new pb_1.BinaryWriter();
if (this.type !== undefined)
writer.writeString(1, this.type);
if (this.transaction_id !== undefined)
writer.writeBytes(2, this.transaction_id);
if (this.transaction_index !== undefined)
writer.writeUint32(3, this.transaction_index);
if (this.event_index !== undefined)
writer.writeUint32(4, this.event_index);
if (this.payload !== undefined)
writer.writeBytes(5, this.payload);
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): Event {
const reader = bytes instanceof Uint8Array ? new pb_1.BinaryReader(bytes) : bytes, message = new Event();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.type = reader.readString();
break;
case 2:
message.transaction_id = reader.readBytes();
break;
case 3:
message.transaction_index = reader.readUint32();
break;
case 4:
message.event_index = reader.readUint32();
break;
case 5:
message.payload = reader.readBytes();
break;
default: reader.skipField();
}
}
return message;
}
}
}
|
5252ca406b53fa8b1e49200d9dc8a34b05d94f58
|
TypeScript
|
PenghaiZhang/openEQUELLA
|
/oeq-ts-rest-api/src/Schema.ts
| 2.625
| 3
|
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you 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 * as Common from './Common';
import { GET } from './AxiosInstance';
import { is } from 'typescript-is';
export interface Citation {
name: string;
transformation: string;
}
export interface Schema extends Common.BaseEntity {
namePath: string;
descriptionPath: string;
/**
* Typically a tree of objects representing an XML schema - so first entry is normally "xml".
*/
definition: Record<string, unknown>;
}
export interface EquellaSchema extends Schema {
citations: Citation[];
exportTransformsMap: Record<string, string>;
importTransformsMap: Record<string, string>;
ownerUuid: string;
serializedDefinition: string;
}
/**
* Helper function for a standard validator for EquellaSchema instances via typescript-is.
*
* @param instance An instance to validate.
*/
export const isEquellaSchema = (instance: unknown): instance is EquellaSchema =>
is<EquellaSchema>(instance);
/**
* Helper function for a standard validator for EquellaSchema instances wrapped in a PagedResult
* via typescript-is.
*
* @param instance An instance to validate.
*/
export const isPagedEquellaSchema = (
instance: unknown
): instance is Common.PagedResult<EquellaSchema> =>
is<Common.PagedResult<EquellaSchema>>(instance);
const SCHEMA_ROOT_PATH = '/schema';
/**
* List all available schemas which the currently authenticated user has access to. Results can
* be customised based on params, and if the `full` param is specified then the return value is
* actually EquellaSchema with all details.
*
* @param apiBasePath Base URI to the oEQ institution and API
* @param params Query parameters to customize (and/or page) result
*/
export const listSchemas = (
apiBasePath: string,
params?: Common.ListCommonParams
): Promise<Common.PagedResult<Common.BaseEntity>> => {
// Only if the `full` param is specified do you get a whole Schema definition, otherwise
// it's the bare minimum of BaseEntity.
const validator = params?.full
? isPagedEquellaSchema
: Common.isPagedBaseEntity;
return GET<Common.PagedResult<Common.BaseEntity>>(
apiBasePath + SCHEMA_ROOT_PATH,
validator,
params
);
};
/**
* Get details of a specific schema as specified by the provided UUID.
*
* @param apiBasePath Base URI to the oEQ institution and API
* @param uuid UUID of the schema to be retrieved.
*/
export const getSchema = (
apiBasePath: string,
uuid: string
): Promise<EquellaSchema> =>
GET<EquellaSchema>(
apiBasePath + `${SCHEMA_ROOT_PATH}/${uuid}`,
isEquellaSchema
);
|
c55f6090342d23333afb6db503065f6fcabee145
|
TypeScript
|
Trebossalol/simple-authentication
|
/src/util.ts
| 2.84375
| 3
|
import * as Express from 'express'
import SimpleAuth from '.'
export interface ApiOnErrorProps {
req: Express.Request
res: Express.Response
}
export interface ViaLoginProps {
username: string
}
export interface ViaUserID {
userID: string | number
}
export interface UserTemplate {
username: string
hashedPassword: string
userID: number | string
roles?: string[]
[key: string]: any
}
export interface RegisterApiResponse {
hashedPassword: string
username: string
email?: string
name?: string
}
export type FindUserViaLogin<User> = (data: ViaLoginProps) => Promise<undefined | User> | undefined | User
export type FindUserViaUserID<User> = (data: ViaUserID) => Promise<undefined | User> | undefined | User
export type CreateUser = (data: RegisterApiResponse) => Promise<void> | void
export type ApiErrorDescriptor = ((props: ApiOnErrorProps) => void) | ((props: ApiOnErrorProps) => string) | string
export type ApiErrorCallback = (req: Express.Request, res: Express.Response) => void
export type ApiErrorController = (simpleAuth: SimpleAuth) => ApiErrorCallback
export const validate = (cb: Function | undefined, val: string) => {
if (cb === undefined) return true
return cb(val)
}
export const throw400: ApiErrorController = (simpleAuth) => (req, res) => {
const on400 = simpleAuth?.options?.errors?.on400 || (({req, res}) => res.sendStatus(400))
if (typeof on400 === 'function') {
const result = on400({ req, res })
if (typeof result !== 'string') return
res
.status(400)
.json({
error: result
})
}
res
.status(400)
.json({
error: on400
})
}
export const throw403: ApiErrorController = (simpleAuth) => (req, res) => {
const on403 = simpleAuth?.options?.errors?.on403 || (({req, res}) => res.sendStatus(403))
if (typeof on403 === 'function') {
const result = on403({ req, res })
if (typeof result !== 'string') return
res
.status(403)
.json({
error: result
})
}
res
.status(403)
.json({
error: on403
})
}
export type SimpleAuthMiddleware<Options> = (options?: Options) => (req: Express.Request, res: Express.Response, next: Express.NextFunction) => void
export type SimpleAuthComponent<Options> = <User extends UserTemplate>(simpleAuth: SimpleAuth<User>) => SimpleAuthMiddleware<Options>
|
1fb7721b1ff4f79bd7e2e0fb054edeaf664a5b4e
|
TypeScript
|
fclebinho/gostack-gobarber-backend
|
/src/modules/users/providers/hash/fakes/hash.ts
| 2.578125
| 3
|
import { IHashProvider } from '@modules/users/providers';
class BCryptHash implements IHashProvider {
public async generate(payload: string): Promise<string> {
return payload;
}
public async compare(payload: string, hashed: string): Promise<boolean> {
return payload === hashed;
}
}
export default BCryptHash;
|
eb0af9c8f27338d14e15cd087a16b0a49057fed7
|
TypeScript
|
bruennijs/sabbat.notes
|
/src/main/sabbat.notes.app/domain/user/UserFactory.ts
| 2.5625
| 3
|
/**
* Created by bruenni on 24.09.15.
*/
import mongodb = require('mongodb');
import _ = require('underscore');
import {IFactory} from "../../common/ddd/factory";
import {Id} from "../../common/ddd/model";
import {ObjectID} from "mongodb";
import {User} from "./User";
export class UserFactory implements IFactory<User> {
public create() {
}
/**
* Serializes domain model to mongodb document.
* primary ids become ObjectID objects (12 byte bson)
* @param obj
* @returns {{_id: "mongodb".ObjectID, name: *, email: string}}
* @constructor
*/
ToMongoDocument(obj: User): any
{
return {
_id: new ObjectID(obj.id.value),
name: obj.name,
email: obj.email.toString()
}
}
/**
* Deserializes from mongodb document.
* @param document
* @returns {User}
* @constructor
*/
CreateFromMongoDocument(document: any): User {
return new User(Id.parse(document._id.toHexString()), document.name, document.email);
}
}
|
e8a23f9055b623c632ad57e061a00e6d4ff7a43b
|
TypeScript
|
mhaligowski/vocally
|
/src/log.ts
| 3.09375
| 3
|
export interface Logger {
debug(...args: any[]): void;
info(...args: any[]): void;
}
// Dummy placeholder for a logging function
export default function getLogger(): Logger {
throw new Error("This is unimplemented.");
}
// Dummy hook implementation.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function useLogger(source?: string): Logger {
throw new Error("This is unimplemented.");
}
|
a9bfff88fe152520ae7b77bafbea1795936375d6
|
TypeScript
|
banksean/patchcab
|
/core/src/state/libraries.ts
| 2.703125
| 3
|
import { get, writable } from 'svelte/store';
class Libraries {
private libraries = writable<{ id: string; loaded: boolean; script: HTMLScriptElement }[]>([]);
public async add(libList: string[]) {
const $libs = get(this.libraries);
return Promise.all(
libList.map((lib) => {
return new Promise((resolve) => {
const exists = $libs.find(($lib) => $lib.id === lib);
let $script = exists?.script;
if (!$script) {
$script = document.createElement('script');
$script.src = lib;
this.libraries.update(($libs) => $libs.concat({ id: lib, loaded: false, script: $script }));
document.body.appendChild($script);
$script.addEventListener('load', () => {
this.libraries.update(($libs) =>
$libs.map(($lib) => ($lib.id === lib ? { ...$lib, loaded: true } : $lib))
);
});
}
if (exists?.loaded) {
resolve(null);
} else {
$script.addEventListener('load', resolve);
}
});
})
);
}
}
const libraries = new Libraries();
export default libraries;
|
f0e625e65f0d92770398684519f1e7a9deed87ba
|
TypeScript
|
LucasTonetto/penguin-adinfo
|
/src/ts/models/Auth.ts
| 3
| 3
|
import { RoutesPermission } from './RoutesPermission';
export class Auth {
private _permission: string;
private _agency: string;
private _company: string;
private _email: string;
constructor(permission: string, company: string, agency = '', email: string) {
this._permission = permission;
this._agency = agency;
this._company = company;
this._email = email;
}
/**
* Verifica se o usuário tem permissão para acessar determinada rota
* @param route Rota que se deseja acessar
* @param method Método de acesso à rota
*/
public hasPermissionFor(route: string, method: string): boolean {
return new RoutesPermission(route, method).validatePermission(this);
}
/**
* Retorna um JSON correspondente ao objeto Auth
*/
public toJson(): { [key: string]: string } {
return {
agency: this._agency,
company: this._company,
permission: this._permission,
email: this._email,
};
}
get permission(): string {
return this._permission;
}
get agency(): string {
return this._agency;
}
get company(): string {
return this._company;
}
get email(): string {
return this._email;
}
}
|
7c90ce705f7b6a92ff996098d5fbe09190d32b3b
|
TypeScript
|
ferdingler/cdk-openapi-example
|
/lib/booksapi-stack.ts
| 2.546875
| 3
|
import * as cdk from "@aws-cdk/core";
import { SpecRestApi, ApiDefinition } from "@aws-cdk/aws-apigateway";
import { Function, Runtime, Code } from "@aws-cdk/aws-lambda";
import * as iam from "@aws-cdk/aws-iam";
import * as yaml from "yamljs";
import * as fs from "fs";
export class BooksApiStack extends cdk.Stack {
private lambdaHandler: Function;
private restApi: SpecRestApi;
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
this.buildLambdaFunction();
this.buildApiGateway();
this.addInvokePermissions();
}
/**
* Creates Lambda Function that will handle requests from API Gateway.
*/
buildLambdaFunction() {
this.lambdaHandler = new Function(this, "BooksApiHandler", {
runtime: Runtime.NODEJS_12_X,
description: "Handles traffic from the Books API",
code: Code.fromAsset("src/"),
handler: "index.handler",
memorySize: 512,
timeout: cdk.Duration.seconds(10),
});
}
buildApiGateway() {
const openApiSpec = this.parseOpenApiSpec();
this.restApi = new SpecRestApi(this, "BooksApi", {
apiDefinition: ApiDefinition.fromInline(openApiSpec),
});
}
/**
* Given that the API is created from an OpenAPI document, CDK doesn't automatically
* give permissions to the Lambda function to be invoked. We need to explicitely add
* a Resource Policy on the Lambda so that API Gateway can invoke it.
*/
addInvokePermissions() {
const stack = cdk.Stack.of(this);
this.lambdaHandler.addPermission("Invoke", {
sourceArn: `arn:${stack.partition}:execute-api:${stack.region}:${stack.account}:${this.restApi.restApiId}/*`,
principal: new iam.ServicePrincipal("apigateway.amazonaws.com"),
});
}
/**
* Reads the local file openapi.yaml, replaces the ${ApiLambda.Arn} string in
* the YAML file with a CDK token that is resolved during synthesis. The OpenAPI
* specification is embedded in CloudFormation as a normal expression that itself
* resolves the LambdaArn during deployment.
*
* This is necessary because CDK does not currently support parametrizing the
* OpenAPI documents. https://github.com/aws/aws-cdk/issues/1461
*/
parseOpenApiSpec() {
const openapiyaml = fs.readFileSync("openapi.yaml", "utf8");
let spec = openapiyaml.replace(
"${ApiLambda.Arn}",
this.lambdaHandler.functionArn
);
const openapi = yaml.parse(spec);
return openapi;
}
}
|
5807a8458b70892e118ff01b402d22903e220b37
|
TypeScript
|
Najdi1996/TS-Labki
|
/Drumkit/src/index.ts
| 2.671875
| 3
|
let boomSound :HTMLAudioElement;
let clapSound : HTMLAudioElement;
let hihatSound :HTMLAudioElement;
let kickSound: HTMLAudioElement;
let operhantSound: HTMLAudioElement;
let rideSound: HTMLAudioElement;
let snareSound: HTMLAudioElement;
let tinkSound: HTMLAudioElement;
let tomSound: HTMLAudioElement;
let channel1:any[] =[];
let channel2:any[] =[];
let channel3:any[] =[];
let channel4:any[] =[];
let isChannel1Record:boolean =false;
let isChannel2Record:boolean =false;
let isChannel3Record:boolean =false;
let isChannel4Record:boolean =false;
let recordStartTime:any;
appStart();
function appStart() :void{
document.body.addEventListener('keypress', onKeyDown);
setChannels();
getSounds();
}
function setChannels():void{
document.querySelector('#chnl1').addEventListener('click', onPlayChannel1)
document.querySelector('#chnl2').addEventListener('click', onPlayChannel2)
document.querySelector('#chnl3').addEventListener('click', onPlayChannel3)
document.querySelector('#chnl4').addEventListener('click', onPlayChannel4)
document.querySelector('#rchnl1').addEventListener('click', onRecordChannel1)
document.querySelector('#rchnl2').addEventListener('click', onRecordChannel2)
document.querySelector('#rchnl3').addEventListener('click', onRecordChannel3)
document.querySelector('#rchnl4').addEventListener('click', onRecordChannel4)
document.querySelector('#stopr').addEventListener('click', onStopRecord)
}
function getSounds() :void{
boomSound =document.querySelector('[data-sound="boom"]');
clapSound=document.querySelector('[data-sound="clap"]');
hihatSound=document.querySelector('[data-sound="hihat"]');
kickSound=document.querySelector('[data-sound="kick"]');
operhantSound=document.querySelector('[data-sound="operhant"]');
rideSound=document.querySelector('[data-sound="ride"]');
snareSound=document.querySelector('[data-sound="snare"]');
tinkSound=document.querySelector('[data-sound="tink"]');
tomSound=document.querySelector('[data-sound="tom"]');
}
function onPlayChannel1() :void{
channel1.forEach(sound=>{
setTimeout(()=>playSound(sound.key),sound.time)
});
}
function onPlayChannel2() :void{
channel2.forEach(sound=>{
setTimeout(()=>playSound(sound.key),sound.time)
});
}
function onPlayChannel3() :void{
channel3.forEach(sound=>{
setTimeout(()=>playSound(sound.key),sound.time)
});
}
function onPlayChannel4() :void{
channel4.forEach(sound=>{
setTimeout(()=>playSound(sound.key),sound.time)
});
}
function onRecordChannel1(ev :Event):void{
channel1 =[];
isChannel1Record =true;
isChannel2Record =false;
isChannel3Record =false;
isChannel4Record =false;
recordStartTime=ev.timeStamp;
}
function onRecordChannel2(ev : Event):void{
channel2=[];
isChannel1Record =false;
isChannel2Record =true;
isChannel3Record =false;
isChannel4Record =false;
recordStartTime=ev.timeStamp;
}
function onRecordChannel3(ev:Event):void{
channel3=[];
isChannel1Record =false;
isChannel2Record =false;
isChannel3Record =true;
isChannel4Record =false;
recordStartTime=ev.timeStamp;
}
function onRecordChannel4(ev:Event):void{
channel4=[];
isChannel1Record =false;
isChannel2Record =false;
isChannel3Record =false;
isChannel4Record =true;
recordStartTime=ev.timeStamp;
}
function onStopRecord():void{
isChannel1Record =false;
isChannel2Record=false;
isChannel3Record =false;
isChannel4Record =false;
}
function RecordChannel(ev: KeyboardEvent):void {
const key=ev.key;
const stampTime =ev.timeStamp;
const time=stampTime-recordStartTime;
if(isChannel1Record==true) {channel1.push({key,time})}
else if(isChannel2Record==true) {channel2.push({key,time})}
else if(isChannel3Record==true) {channel3.push({key,time})}
else if(isChannel4Record==true) {channel4.push({key,time})}
}
function onKeyDown(ev: KeyboardEvent):void {
const key=ev.key;
console.log(ev);
RecordChannel(ev);
playSound(key);
}
function playSound(key:string):void{
switch(key){
case 'a':{hihatSound.currentTime =0;
hihatSound.play();
break;}
case 's':{boomSound.currentTime =0;
boomSound.play();
break;}
case 'd':{clapSound.currentTime =0;
clapSound.play();
break;}
case 'f':{kickSound.currentTime =0;
kickSound.play();
break;}
case 'g':{operhantSound.currentTime =0;
operhantSound.play();
break;}
case 'q':{rideSound.currentTime =0;
rideSound.play();
break;}
case 'w':{snareSound.currentTime =0;
snareSound.play();
break;}
case 'e':{tinkSound.currentTime =0;
tinkSound.play();
break;}
case 'r':{tomSound.currentTime =0;
tomSound.play();
break;}
}
}
|
b2485f8e5f8433d902ce68cacb9356d996f79f63
|
TypeScript
|
ahmad245/Functional-Programming-with-TypeScript
|
/curring.ts
| 3.875
| 4
|
// Currying is a functional programming technique that allows us to partially apply
// a function without having to worry about the way in which we implement our
// functions. Currying is the process of taking a function that takes multiple
// arg(uments and transforming it into a chain of unary functions. The following
// function allows us to transform a function, fn , which takes two arguments, a and
// b , into a function that takes one argument, a , and returns another function that
// takes one argument, b : function
const curry=<T1,T2,T3>(fn:(a:T1,b:T2)=>T3)=>(a:T1)=>(b:T2)=>fn(a,b)
const add2=(a:number,b:number)=>a+b;
const addCurry=curry(add)
const addResult=addCurry(5)
console.log(addResult(5)); // =>
|
e3914320abf1056ff146224344e4e011f312d110
|
TypeScript
|
rapkeb/Principles-of-Programming-Languages
|
/Assignment1/result.ts
| 3.640625
| 4
|
/* Question 3 */
import { useWith } from "ramda";
interface Ok<T> {
tag: "Ok";
value: T;
}
interface Failure {
tag: "Failure";
message: string;
}
export type Result<T> = Ok<T> | Failure;
export const makeOk = <T>(x: T): {tag: "Ok",value: T} => ({ tag: "Ok", value: x});
export const makeFailure = (x: string): {tag: "Failure",message: string} => ({ tag: "Failure",message: x});
export const isOk = <T>(x: Result<T>): x is Ok<T> => x.tag === "Ok";
export const isFailure = <T>(x: Result<T>): x is Failure => x.tag === "Failure";
/* Question 4 */
export const bind = <T> (res : Result<T>, check : (x:T) => Result<T>) : Result<T> =>
{
if(isOk(res))
return check(res.value!);
return makeFailure(res.message!);
}
/* Question 5 */
interface User {
name: string;
email: string;
handle: string;
}
const validateName = (user: User): Result<User> =>
user.name.length === 0 ? makeFailure("Name cannot be empty") :
user.name === "Bananas" ? makeFailure("Bananas is not a name") :
makeOk(user);
const validateEmail = (user: User): Result<User> =>
user.email.length === 0 ? makeFailure("Email cannot be empty") :
user.email.endsWith("bananas.com") ? makeFailure("Domain bananas.com is not allowed") :
makeOk(user);
const validateHandle = (user: User): Result<User> =>
user.handle.length === 0 ? makeFailure("Handle cannot be empty") :
user.handle.startsWith("@") ? makeFailure("This isn't Twitter") :
makeOk(user);
export const naiveValidateUser = (user: User) : Result<User> =>
isFailure(validateName(user)) ? validateName(user) :
isFailure(validateEmail(user)) ? validateEmail(user):
isFailure(validateHandle(user)) ? validateHandle(user):
makeOk(user);
export const monadicValidateUser = (user: User) : Result<User> =>
bind(bind(validateName(user), validateEmail),validateHandle);
|
17cf999dbdb342045fb9bff24d621f5b0ecc2991
|
TypeScript
|
turbobo/Ant-demo
|
/src/models/detaildemo.ts
| 3.171875
| 3
|
// 导入接口文件,并采用解构的方式,
// 将detaildemo.js的文件里面的getDetail赋值给这里的getDetail
import { getDetail } from "@/services/detaildemo";
export default {
namespace: "detaildemo",
// State 是储存数据的地方,收到 Action 以后,会更新数据。
state: {
data: {}
},
effects: {
/**
* @param payload 参数
* @param call 执行异步函数调用接口
* @param put 发出一个 Action,类似于 dispatch 将服务端返回的数据传递给上面的state
* @returns {IterableIterator<*>}
*/
// * fetch({ payload, callback}, { call, put }) {
* fetch({ payload }, { call, put }) {
// 访问之前可以做一些操作
const response = yield call(getDetail, payload);
// console.log('response-------------------------'+response);
// 拿到数据之后可以做一些操作
yield put({
// 这行对应下面的reducers处理函数名字
type: "save",
// 这是将最后的处理数据传递给下面的reducers函数
payload: response
});
// if(callback) callback()
}
},
reducers: {
/**
*
* @param state
* @param action
* @returns {{[p: string]: *}}
*/
save(state, action) {
// console.log('action----------model--------------'+action);
// console.log('action.payload----------model--------------'+action.payload);
return {
...state, // es6三点运算符合,有点模糊解释不清楚
data: action.payload // 上面与服务器交互完的数据赋值给data,这里的data 对应最上面 state 里面的data
};
}
}
};
|
ddb74b07ae9b6ef3dcb641f77642e3bc327f248c
|
TypeScript
|
valex91/maze-gen
|
/src/main-canvas-generator/main-canvas-generator.ts
| 2.5625
| 3
|
import { PIXEL_FIX } from '../maze-renderer/pixel_fix.constant';
import { TILE_SIZE } from '../maze-renderer/tile-size';
export class MainCanvasGenerator {
private static ref: HTMLCanvasElement;
public static generate(size: number): HTMLCanvasElement {
const canvasElement: HTMLCanvasElement = self.document.createElement('canvas'),
necessarySize: number = size * TILE_SIZE + (PIXEL_FIX * size);
canvasElement.width = necessarySize;
canvasElement.height = necessarySize;
this.ref = canvasElement;
const layerElement: HTMLDivElement = (self.document.querySelector('.layerContainer') as HTMLDivElement);
layerElement.appendChild(canvasElement);
layerElement.style.width = `${necessarySize}px`;
layerElement.style.height = `${necessarySize}px`;
return canvasElement;
}
public static remove(): void {
if (this.ref) {
const container: HTMLDivElement = (self.document.querySelector('.layerContainer') as HTMLDivElement);
container.querySelectorAll('canvas').forEach((e: HTMLCanvasElement) => {
container.removeChild(e)
})
}
}
}
|
e745d7d9ba630a4cfc028bdc841e19463aa70124
|
TypeScript
|
dbarczewski/Cashier-Register-App
|
/cypress/integration/app.spec.ts
| 2.75
| 3
|
/// <reference types="cypress" />
import Content from "./../../content.json";
describe("The App", () => {
beforeEach(() => {
cy.visit("http://localhost:8080/");
});
it("should type the same amount", () => {
cy.write("1234").write("{enter}").write("1234").write("{enter}");
cy.get("dialog").should("contain", "0,00");
});
it("should type a a lower amount for given and receive the correct amount", () => {
cy.write("1233").write("{enter}").write("1234").write("{enter}");
cy.get("dialog").should("contain", "0,01");
});
it("should use the numeric pad and receive the correct amount", () => {
cy.clickByLabel("1");
cy.clickByLabel("2");
cy.clickByLabel("3");
cy.clickByLabel("4");
cy.clickByLabel(Content.givenLabel);
cy.clickByLabel("2");
cy.clickByLabel("3");
cy.clickByLabel("4");
cy.clickByLabel("0");
cy.clickByLabel("0");
cy.clickByLabel(Content.payButton);
cy.get("dialog").should("contain", "221,66");
});
it("should use the proposed amounts and pay with it", () => {
cy.write("100").write("{enter}");
cy.findAllByText("1,00 €").should("exist");
cy.findByText("2,00 €").should("exist");
cy.findByText("10,00 €").should("exist");
cy.findByText("20,00 €").should("exist");
cy.findByText("50,00 €").should("exist").click();
cy.clickByLabel(Content.payButton);
cy.get("dialog").should("contain", "49,00");
});
it("should function correctly with backspaces", () => {
cy.write("123").write("{enter}");
cy.clickByLabel("1");
cy.clickByLabel("0");
cy.clickByLabel("1");
cy.findByText("1,01 €").should("exist");
cy.clickByTitle("delete");
cy.findByText("0,10 €").should("exist");
cy.write("{backspace}");
cy.findByText("0,01 €").should("exist");
});
it("should not get over 1000,00€", () => {
cy.write("100000000000").write("{enter}");
cy.findAllByText("1.000,00 €").should("have.length", "2");
cy.clickByLabel(Content.givenLabel);
cy.clickByLabel("1");
for (let i = 0; i < 10; i++) {
cy.clickByLabel("0");
}
cy.findAllByText("1.000,00 €").should("have.length", "3");
});
it("should get an error when given amount is lower that the amount to pay", () => {
cy.write("500").write("{enter}").write("400").write("{enter}");
cy.findByText(Content.error.givenAmountTooLow).should("exist");
});
});
|
13fd60b6713d4291471542c21002adef33f762a7
|
TypeScript
|
kaikai2823/GunnerComing
|
/src/view/gun.ts
| 2.625
| 3
|
/**Created by the LayaAirIDE*/
module view{
export class gun extends ui.gunUI{
public isShootEnemy:boolean = false;
constructor(){
super();
this.addChild(this.gun);
}
//触发条件为,主角射击后
public enemyGunInit(shootRotation:number):void{
this.gun.rotation = 0;
//从水平方向转动到特定位置
Laya.timer.frameLoop(1,this,()=>{
if(shootRotation>0){
if(this.gun.rotation<shootRotation){
this.gun.rotation ++;
}else{
Laya.timer.clearAll(this);
this.shootBullet(2);//自动发射子弹
}
}else{
if(this.gun.rotation>shootRotation){
this.gun.rotation --;
}else{
Laya.timer.clearAll(this);
this.shootBullet(2);//自动发射子弹
}
}
});
}
public init():void{
//清理之前的定时器
//让枪转动
Laya.timer.frameLoop(1,this,this.onLoop);
//检测屏幕点击
Laya.stage.on(Laya.Event.CLICK,this,this.shootBullet,[1]);
}
//转动的速度
private rotationSpeed:number = 0.5;
onLoop():void{
//转动枪
this.gun.rotation -= this.rotationSpeed;
//转动的范围 0 到 -60
if(this.gun.rotation>=0||this.gun.rotation<=-60){
this.rotationSpeed = -this.rotationSpeed;
}
//生成扇形区域
this.drawPie(this.gun.rotation);
}
//停止循环,执行后续动作
outLoop():void{
Laya.timer.clear(this,this.onLoop);
//爆破效果、声音
//后续动作,恢复水平
Laya.timer.frameLoop(1,this,()=>{
if(this.gun.rotation>0){
Laya.timer.clearAll(this);
this.gun.rotation = 0;//恢复到水平
}else{
this.gun.rotation ++;
}
});
}
//主角发射子弹逻辑
shootBullet(_sign:number):void{
//如果不是准备状态不允许发射
// var bullet:Bullet = new Bullet(this.gun.getGunRotation());
//从对象池中创建对象
var bullet:Bullet = Laya.Pool.getItemByClass("bullet",Bullet);
//子弹的初始发射角度
bullet.init(this.gun.rotation,_sign);
//子弹的初始位置
bullet.pos(this.gun.x,this.gun.y);
this.addChild(bullet);
//停止抢的转动
this.outLoop();
//停止监听点击事件
Laya.stage.off(Laya.Event.CLICK,this,this.shootBullet);
}
/**
* 绘制枪口的扇形区域
* @param angle 扇形区域的开合角度
*/
drawPie(angle:number):void{
var sp:Laya.Sprite = new Laya.Sprite();
this.addChild(sp);
sp.graphics.drawPie(this.gun.x,this.gun.y,200,angle-3,1,"#a9aab0");
sp.alpha = 0.5;
Laya.timer.frameLoop(1,this,()=>{
sp.graphics.clear(); //清除之前的绘图痕迹
sp.removeSelf(); //用完之后立即回收
});
}
}
}
|
50d1f310f263e19e1fbe2368313d51fa10783414
|
TypeScript
|
elear-solutions/kibana
|
/x-pack/legacy/plugins/upgrade_assistant/server/lib/query_default_field.ts
| 2.609375
| 3
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import Boom from 'boom';
import { Request } from 'hapi';
import { get } from 'lodash';
import { CallClusterWithRequest } from 'src/legacy/core_plugins/elasticsearch';
import { MappingProperties } from './reindexing/types';
/**
* Adds the index.query.default_field setting, generated from the index's mapping.
*
* @param callWithRequest
* @param request
* @param indexName
* @param fieldTypes - Elasticsearch field types that should be used to generate the default_field from the index mapping
* @param otherFields - Other fields that should be included in the generated default_field that do not match `fieldTypes`
*/
export const addDefaultField = async (
callWithRequest: CallClusterWithRequest,
request: Request,
indexName: string,
fieldTypes: ReadonlySet<string>,
otherFields: ReadonlySet<string> = new Set()
) => {
// Verify index.query.default_field is not already set.
const settings = await callWithRequest(request, 'indices.getSettings', {
index: indexName,
});
if (get(settings, `${indexName}.settings.index.query.default_field`)) {
throw Boom.badRequest(`Index ${indexName} already has index.query.default_field set`);
}
// Get the mapping and generate the default_field based on `fieldTypes`
const mappingResp = await callWithRequest(request, 'indices.getMapping', {
index: indexName,
});
const mapping = mappingResp[indexName].mappings.properties as MappingProperties;
const generatedDefaultFields = new Set(generateDefaultFields(mapping, fieldTypes));
// Update the setting with the generated default_field
return await callWithRequest(request, 'indices.putSettings', {
index: indexName,
body: {
index: { query: { default_field: [...generatedDefaultFields, ...otherFields] } },
},
});
};
/**
* Recursively walks an index mapping and returns a flat array of dot-delimited
* strings represent all fields that are of a type included in `DEFAULT_FIELD_TYPES`
* @param mapping
*/
export const generateDefaultFields = (
mapping: MappingProperties,
fieldTypes: ReadonlySet<string>
): string[] =>
Object.getOwnPropertyNames(mapping).reduce(
(defaultFields, fieldName) => {
const { type, properties } = mapping[fieldName];
if (type && fieldTypes.has(type)) {
defaultFields.push(fieldName);
} else if (properties) {
generateDefaultFields(properties, fieldTypes).forEach(subField =>
defaultFields.push(`${fieldName}.${subField}`)
);
}
return defaultFields;
},
[] as string[]
);
|
6fa75c7be0910f39d332f2edd2972290721f1d4f
|
TypeScript
|
Linjovi/git-repos-manager
|
/pages/store/reducers.ts
| 2.75
| 3
|
import { Action } from 'rxjs/internal/scheduler/Action';
var initialReposState: any[] = [];
export function _repos(state = initialReposState, action: any) {
switch (action.type) {
case 'GET_REPOS':
return action.repos;
case 'GET_STATUS':
let index = state.findIndex(
(item: any) => item.name === action.repo.name,
);
if(!state[index]){
return state;
}
let [...newState] = state;
newState[index].status = action.repo.status;
// console.log("new",newState[0].status)
return newState;
default:
return state;
}
}
export function _selected(state = initialReposState, action: any) {
switch (action.typs) {
case 'GET_SELECT':
return action.repos;
case 'ADD_SELECT':
let [...newState] = state;
newState.push(action.repo);
return newState;
default:
return state;
}
}
|
76c3f9e407a5307971efa865aa91bb57846786c4
|
TypeScript
|
skyformat99/CoSky
|
/cosky-dashboard/src/app/model/RowExpand.ts
| 3.09375
| 3
|
export class RowExpand<Data> {
data: Data;
expand = false;
constructor(data: Data, expand: boolean) {
this.data = data;
this.expand = expand;
}
static of<Data>(data: Data, expand: boolean = false): RowExpand<Data> {
return new RowExpand(data, expand);
}
}
|
236d41c078c40136ca94431974e59409e82a3d6d
|
TypeScript
|
robertomassabr/rakkas-realworld
|
/api-test/form/delete-article.test.ts
| 2.703125
| 3
|
import { Article, SingleArticleResponse } from "lib/api-types";
import {
apiCall,
formSubmit,
registerJaneFoo,
registerJohnDoe,
resetDb,
} from "../api-test-helpers";
describe("Update Article API", () => {
let article: Article;
let johnsToken: string;
beforeEach(async () => {
await resetDb();
const john = await registerJohnDoe();
johnsToken = john.token;
const r = await apiCall<SingleArticleResponse>({
url: "/api/articles",
method: "POST",
token: johnsToken,
data: {
article: {
title: "My article title",
description: "My article description",
body: "My article body",
tagList: ["aaa", "bbb", "ccc"],
},
},
});
if (!r.ok) {
console.error(r.status, r.error);
throw new Error("Could not create article");
}
article = r.data.article;
});
it("deletes article", async () => {
const { location } = await formSubmit({
url: `/api/form/article/${encodeURIComponent(article.slug)}/delete`,
token: johnsToken,
});
expect(location).toBe("/");
const r = await apiCall<SingleArticleResponse>({
url: `/api/articles/${encodeURIComponent(article.slug)}`,
});
expect(r.status).toBe(404);
});
it("rejects unauthenticated", async () => {
const { location } = await formSubmit({
url: `/api/form/article/${encodeURIComponent(article.slug)}/delete`,
});
expect(location).toBe("/register");
});
it("rejects other users", async () => {
const jane = await registerJaneFoo();
const { location } = await formSubmit({
url: `/api/form/article/${encodeURIComponent(article.slug)}/delete`,
token: jane.token,
});
expect(location).toBe(
`/article/${encodeURIComponent(
article.slug,
)}?error=author+should+be+the+same`,
);
});
it("rejects non-existent slug", async () => {
const { location } = await formSubmit({
url: `/api/form/article/invalid-slug-1234/delete`,
token: johnsToken,
});
expect(location).toBe(`/article/invalid-slug-1234`);
});
});
|
e69f2348835f35de0d850c84809cc91364a5207e
|
TypeScript
|
alibaba/G3D
|
/src/mesh/base-mesh.ts
| 2.546875
| 3
|
import Node from "../core/node";
import Scene from "../scene/scene";
import { findIndex } from "../utils/lodash";
import BaseGeometry from "../geometry/base-geometry";
import ShaderMaterial from "../material/shader-material";
class BaseMesh extends Node {
public scene: Scene;
public visibility: boolean = true;
public pickable: boolean = true;
public renderLayerIndex: number = 0;
public geometry: BaseGeometry;
public materials: {
[prop: string]: ShaderMaterial;
};
constructor(scene: Scene) {
super();
if (scene) {
scene.meshes.push(this);
this.scene = scene;
}
}
public getGlobalVisibility(): boolean {
let mesh = this as Node;
while (!!mesh) {
if (mesh instanceof BaseMesh) {
if (!mesh.visibility) {
return false;
}
}
mesh = mesh.parent;
}
return true;
}
public getPickable(): boolean {
return this.pickable;
}
public getRenderLayerIndex(): number {
let mesh = this as Node;
while (!!mesh) {
if (mesh instanceof BaseMesh) {
if (mesh.renderLayerIndex !== 0) {
return mesh.renderLayerIndex;
}
}
mesh = mesh.parent;
}
return 0;
}
public dispose(): void {
if (this.scene) {
const i = findIndex(this.scene.meshes, { id: this.id });
if (i !== -1) {
this.scene.meshes.splice(i, 1);
}
}
}
}
export default BaseMesh;
|
2c651bd1c075b8ee8add4107487107c07fa907aa
|
TypeScript
|
smart-u/shopware-pwa
|
/packages/shopware-6-client/src/interfaces/search/Pagination.ts
| 2.71875
| 3
|
export enum PaginationLimit {
ONE = 1,
FIVE = 5,
TEN = 10,
TWENTY_FIVE = 25,
FIFTY = 50,
SEVENTY_FIVE = 75,
HUNDRED = 100,
FIVE_HUNDRED = 500
}
/**
* @alpha
*/
export interface Pagination {
limit?: PaginationLimit;
page?: number;
}
|
39d9b22b79ac5c0216067062213cd5b339ae4226
|
TypeScript
|
migraf/typescript-rest-api
|
/packages/trapi-metadata/src/resolver/utils/initializer.ts
| 2.796875
| 3
|
/*
* Copyright (c) 2021.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import * as ts from 'typescript';
import {Resolver} from "../type";
import {hasOwnProperty} from "@trapi/metadata-utils";
export function getInitializerValue(
initializer?: ts.Expression,
typeChecker?: ts.TypeChecker,
type?: Resolver.Type
) : unknown {
if (!initializer) {
return undefined;
}
switch (initializer.kind) {
case ts.SyntaxKind.ArrayLiteralExpression:
const arrayLiteral = initializer as ts.ArrayLiteralExpression;
return arrayLiteral.elements.map(element => getInitializerValue(element, typeChecker));
case ts.SyntaxKind.StringLiteral:
return (initializer as ts.StringLiteral).text;
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
case ts.SyntaxKind.NumberKeyword:
case ts.SyntaxKind.FirstLiteralToken:
return Number((initializer as ts.NumericLiteral).text);
case ts.SyntaxKind.NewExpression:
const newExpression = initializer as ts.NewExpression;
const ident = newExpression.expression as ts.Identifier;
if (ident.text === 'Date') {
let date = new Date();
if (newExpression.arguments) {
const newArguments = newExpression.arguments.filter(args => args.kind !== undefined);
const argsValue = newArguments.map(args => getInitializerValue(args, typeChecker));
if (argsValue.length > 0) {
date = new Date(argsValue as any);
}
}
const dateString = date.toISOString();
if (type && type.typeName === 'date') {
return dateString.split('T')[0];
}
return dateString;
}
return;
case ts.SyntaxKind.ObjectLiteralExpression:
const objectLiteral = initializer as ts.ObjectLiteralExpression;
const nestedObject: any = {};
objectLiteral.properties.forEach((p: any) => {
nestedObject[p.name.text] = getInitializerValue(p.initializer, typeChecker);
});
return nestedObject;
default:
if(typeof initializer === 'undefined') {
return undefined;
} else {
if(typeof initializer.parent === 'undefined') {
if(hasOwnProperty(initializer, 'text')) {
return initializer.text;
}
return undefined;
}
const symbol = typeChecker.getSymbolAtLocation(initializer);
const extractedInitializer = symbol && symbol.valueDeclaration && hasInitializer(symbol.valueDeclaration) && (symbol.valueDeclaration.initializer as ts.Expression);
return extractedInitializer ? getInitializerValue(extractedInitializer, typeChecker) : undefined;
}
}
}
export const hasInitializer = (node: ts.Node): node is ts.HasInitializer => node.hasOwnProperty('initializer');
|
aa9556c9c0c3ff28743723ede30381bc53f97651
|
TypeScript
|
ChristopherChudzicki/mathbox
|
/test/primitives/types/types.spec.ts
| 3.171875
| 3
|
import * as MathBox from "../../../src";
import type { Axes, AxesWithZero } from "../../../src/types";
const { Types } = MathBox.Primitives.Types;
describe("primitives.types.types", function () {
it("validates axes", () => {
const axis = Types.axis("y");
let value = axis.make();
expect(value).toBe(2);
for (const i of [1, 2, 3, 4] as const) {
const invalid = jasmine.createSpy();
const x = axis.validate(i, value, invalid);
expect(invalid).not.toHaveBeenCalled();
if (x !== undefined) {
value = x;
}
expect(value).toBe(i);
}
const axisMap = new Map<Axes, number>([
["x", 1],
["y", 2],
["z", 3],
["w", 4],
["W", 1],
["H", 2],
["D", 3],
["I", 4],
["width", 1],
["height", 2],
["depth", 3],
["items", 4],
]);
axisMap.forEach((i, key) => {
const invalid = jasmine.createSpy();
const x = axis.validate(key, value, invalid);
expect(invalid).not.toHaveBeenCalled();
if (x !== undefined) {
value = x;
}
expect(value).toBe(i);
});
const invalid = jasmine.createSpy();
value = 3;
axis.validate(0 as never, value, invalid);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.calls.reset();
axis.validate(5 as never, value, invalid);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.calls.reset();
axis.validate("null" as never, value, invalid);
expect(invalid).toHaveBeenCalledTimes(1);
});
it("validates zero axes", () => {
const axis = Types.axis(3, true);
let value = axis.make();
expect(value).toBe(3);
for (const i of [0, 1, 2, 3, 4] as const) {
const invalid = jasmine.createSpy();
const x = axis.validate(i, value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toBe(i);
expect(invalid).not.toHaveBeenCalled();
}
const axisMap = new Map<AxesWithZero, number>([
["x", 1],
["y", 2],
["z", 3],
["w", 4],
["W", 1],
["H", 2],
["D", 3],
["I", 4],
["width", 1],
["height", 2],
["depth", 3],
["items", 4],
["zero", 0],
["null", 0],
]);
axisMap.forEach((i, key) => {
const invalid = jasmine.createSpy();
const x = axis.validate(key, value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toBe(i);
expect(invalid).not.toHaveBeenCalled();
});
const invalid = jasmine.createSpy();
value = 3;
axis.validate(-1 as never, value, invalid);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.calls.reset();
axis.validate(5 as never, value, invalid);
expect(invalid).toHaveBeenCalledTimes(1);
});
it("validates transpose", () => {
const transpose = Types.transpose();
let value = transpose.make();
expect(value).toEqual([1, 2, 3, 4]);
const invalid = jasmine.createSpy();
value = [1, 2, 3, 4];
let x = transpose.validate("wxyz", value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([4, 1, 2, 3]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [2, 3, 4, 1];
x = transpose.validate("yxz", value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 1, 3, 4]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [3, 4, 1, 2];
x = transpose.validate([2, 4, 1, 3], value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 4, 1, 3]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [4, 1, 2, 3];
x = transpose.validate([2, 4, 1, 2], value, invalid);
if (x !== undefined) {
value = x;
}
expect(invalid).toHaveBeenCalledTimes(1);
invalid.calls.reset();
value = [1, 2, 3, 4];
x = transpose.validate([2, 4, 1], value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 4, 1, 3]);
expect(invalid).not.toHaveBeenCalled();
});
it("validates swizzle", () => {
const swizzle = Types.swizzle();
let value = swizzle.make();
expect(value).toEqual([1, 2, 3, 4]);
const invalid = jasmine.createSpy();
value = [1, 2, 3, 4];
let x = swizzle.validate("wxyz", value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([4, 1, 2, 3]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [2, 3, 4, 1];
x = swizzle.validate("yxz", value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 1, 3, 0]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [3, 4, 1, 2];
x = swizzle.validate([2, 4, 1, 2], value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 4, 1, 2]);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [4, 1, 2, 3];
x = swizzle.validate([2, 4, 1], value, invalid);
if (x !== undefined) {
value = x;
}
expect(value).toEqual([2, 4, 1, 0] as never);
expect(invalid).not.toHaveBeenCalled();
invalid.calls.reset();
value = [1, 2, 3, 4];
x = swizzle.validate([7, 8, 5, 6] as never, value, invalid);
if (x !== undefined) {
value = x;
}
expect(invalid).toHaveBeenCalledTimes(4);
});
});
|
0d27279ba1ec933a8b13aa892184e9020720a288
|
TypeScript
|
dirvine/miscreant
|
/js/src/internal/polyfill/aes_ctr.ts
| 2.984375
| 3
|
// Copyright (C) 2016 Dmitry Chestnykh
// MIT License. See LICENSE file for details.
import { ICtrLike } from "../interfaces";
import { wipe } from "../util";
import PolyfillAes from "./aes";
/**
* Polyfill for the AES-CTR (counter) mode of operation.
*
* Uses a non-constant-time (lookup table-based) AES polyfill.
* See polyfill/aes.ts for more information on the security impact.
*
* Note that CTR mode is malleable and generally should not be used without
* authentication. Instead, use an authenticated encryption mode, like AES-SIV!
*/
export default class PolyfillAesCtr implements ICtrLike {
private _counter: Uint8Array;
private _buffer: Uint8Array;
private _cipher: PolyfillAes;
constructor(cipher: PolyfillAes) {
// Set cipher.
this._cipher = cipher;
// Allocate space for counter.
this._counter = new Uint8Array(cipher.blockSize);
// Allocate buffer for encrypted block.
this._buffer = new Uint8Array(cipher.blockSize);
}
public async encrypt(iv: Uint8Array, plaintext: Uint8Array): Promise<Uint8Array> {
if (iv.length !== this._counter.length) {
throw new Error("CTR: iv length must be equal to cipher block size");
}
// Copy IV to counter, overwriting it.
this._counter.set(iv);
// Set buffer position to length of buffer
// so that the first cipher block is generated.
let bufpos = this._buffer.length;
const result = new Uint8Array(plaintext.length);
for (let i = 0; i < plaintext.length; i++) {
if (bufpos === this._buffer.length) {
this._cipher.encryptBlock(this._counter, this._buffer);
bufpos = 0;
incrementCounter(this._counter);
}
result[i] = plaintext[i] ^ this._buffer[bufpos++];
}
return result;
}
public async decrypt(iv: Uint8Array, ciphertext: Uint8Array): Promise<Uint8Array> {
// AES-CTR decryption is identical to encryption
return this.encrypt(iv, ciphertext);
}
public clean(): this {
wipe(this._buffer);
wipe(this._counter);
this._cipher.clean();
return this;
}
}
function incrementCounter(counter: Uint8Array) {
let carry = 1;
for (let i = counter.length - 1; i >= 0; i--) {
carry += (counter[i] & 0xff) | 0;
counter[i] = carry & 0xff;
carry >>>= 8;
}
if (carry > 0) {
throw new Error("CTR: counter overflow");
}
}
|
3c85b0e12c49f92e932ee3c358a6f4310cb5e375
|
TypeScript
|
osaulenkoUA/VocabularyFront
|
/src/redux/Vocabulary/vocabularyOperation.ts
| 2.609375
| 3
|
import axios from 'axios';
import {addWord, content} from '../../types/types'
import vocabularyActions from './vocabularyActions';
import {AppDispatch} from '../store';
axios.defaults.baseURL = 'https://sleepy-escarpment-78189.herokuapp.com';
type addData = {
data: content;
}
type getData = {
data: content[];
}
const postWord = ({word, translate}: addWord) => async (dispatch: AppDispatch) => {
dispatch(vocabularyActions.addWordRequest());
try {
const {data}: addData = await axios.post('/vocabulary/addword', {word, translate});
dispatch(vocabularyActions.addWordSuccess(data));
} catch (error) {
dispatch(vocabularyActions.addWordError(error));
}
};
const fetchWords= () => async (dispatch: AppDispatch) => {
dispatch(vocabularyActions.fetchWordsRequest());
try {
const {data}: getData = await axios.get('/vocabulary/words');
data.reverse();
dispatch(vocabularyActions.fetchWordsSuccess(data));
} catch (error) {
dispatch(vocabularyActions.fetchWordsError(error));
}
};
const removeWord = (id: string) => async (dispatch: AppDispatch) => {
dispatch(vocabularyActions.removeWordRequest());
try {
axios.delete(`/vocabulary/delete/${id}`);
dispatch(vocabularyActions.removeWordSuccess(id));
} catch (error) {
dispatch(vocabularyActions.removeWordError(error));
}
};
const updateWord = (id: string,newFields:addWord) => async (dispatch: AppDispatch) => {
dispatch(vocabularyActions.updateWordRequest());
try {
const {data}: addData = await axios.patch(`/vocabulary/update/${id}`,newFields);
dispatch(vocabularyActions.updateWordSuccess(data));
} catch (error) {
dispatch(vocabularyActions.updateWordError(error));
}
};
export default {
postWord,
fetchWords,
removeWord,
updateWord
};
|
cd7b125a9b36dc41875efbf1aef1c9802dae1d68
|
TypeScript
|
SamOdin/agile
|
/src/app/store/root-reducer.ts
| 2.53125
| 3
|
import { Action, createReducer, on } from '@ngrx/store';
import * as FileActions from './root-actions';
import { FILE_STATUS } from '../enums';
export interface State {
text: any | undefined;
}
export const initialState: State = {
text: []
};
const fileReducer = createReducer(
initialState,
on(FileActions.LoadTextSuccess, (state, props) => {
const {payload} = props;
return {...state, text: [...payload]};
}),
on(FileActions.MarkText, (state, props) => {
const {payload} = props;
return {...state, text: state.text.map((i) => i.id === payload ?
{...i, options: {...i.options, isSelected: !i.options.isSelected}} : {...i})};
}),
on(FileActions.SetText, (state, props) => {
const {payload} = props;
return {...state, text: state.text.map((i) => i.options.isSelected ?
{...i, options: {...i.options, [payload]: !i.options[payload]}} : {...i})};
}),
on(FileActions.SearchSynonyms, (state, props) => {
const {payload: {id}} = props;
return {...state, text: state.text.map((i) => i.id === id ?
{...i, synonyms: {...i.synonyms, status: FILE_STATUS.LOADING}} : {...i})};
}),
on(FileActions.SearchSynonymsSuccess, (state, props) => {
const {payload: {id, data}} = props;
return {...state, text: state.text.map((i) => i.id === id ?
{...i, synonyms: {...i.synonyms, status: FILE_STATUS.LOADED, data: [...data]}} : {...i})};
}),
on(FileActions.SetSynonymsWord, (state, props) => {
const {payload: {id, text}} = props;
return {...state, text: state.text.map((i) => i.id === id ?
{...i, text, synonyms: {...i.synonyms, status: FILE_STATUS.PENDING, data: []}} : {...i})};
})
);
export function reducer(state: State | undefined, action: Action) {
return fileReducer(state, action);
}
|
fe6ab3560e44f4cb7625a5e7a755a2bfa5e85d34
|
TypeScript
|
nastasya146/web-example
|
/StaffingWebApi/src/app/working-time.pipe.ts
| 2.625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'workingTime'})
export class WorkingTimePipe implements PipeTransform {
transform(minutes: number): string {
return (('0' + (Math.floor(minutes / 60)).toString()).slice(-2) + ':' + (('0' + (minutes % 60)).toString().slice(-2)));
}
}
|