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
|
|---|---|---|---|---|---|---|
957a47c89e69031839fae8404f3b83745cd89aa8
|
TypeScript
|
widmogrod/notepad-app
|
/src/serialiser.ts
| 2.84375
| 3
|
import crdt from 'js-crdt';
import {OrderedOperations} from 'js-crdt/build/text';
type SerialisedOrder = Object
export type SerialisedOrderedOperations = {operations: Array<any>, order: SerialisedOrder}
export function serialiseOperations(oo: OrderedOperations): SerialisedOrderedOperations {
return oo.operations.reduce((result, operation) => {
let value;
if (operation instanceof crdt.text.Insert) {
value = {type: 'insert', args: [operation.at, operation.value]}
}
if (operation instanceof crdt.text.Delete) {
value = {type: 'delete', args: [operation.at, operation.length]}
}
if (operation instanceof crdt.text.Selection) {
value = {type: 'selection', args: [operation.origin, operation.at, operation.length]}
}
if (value) {
result.operations.push(value);
}
return result;
}, {
operations: [],
order: serialiseOrder(oo.order),
});
}
function serialiseOrder(order) {
if (order instanceof crdt.order.VectorClock) {
function serialiseId(id) {
return {
node: id.node,
version: id.version,
}
}
return {
t: 'v2',
id: serialiseId(order.id),
vector: order.vector.reduce((r, item) => {
r.push(serialiseId(item))
return r;
}, []),
}
}
}
function deserialiesOrder(t, id, vector) {
switch(t) {
case 'v2':
const set = new crdt.structures.SortedSetArray(new crdt.structures.NaiveArrayList([]));
return new crdt.order.VectorClock(
new crdt.order.Id(id.node, id.version),
vector.reduce((set, id) => {
return set.add(new crdt.order.Id(id.node, id.version)).result
}, set)
);
}
}
export function deserialiseOperations({order, operations}): OrderedOperations {
const {t, id, vector} = order;
return {
order: deserialiesOrder(t, id, vector),
operations: operations.reduce((operations, {type, args}) => {
let operation;
switch(type) {
case "insert":
operation = new crdt.text.Insert(args[0], args[1]);
break;
case "delete":
operation = new crdt.text.Delete(args[0], args[1]);
break;
case "selection":
operation = new crdt.text.Selection(args[0], args[1], args[2]);
break;
}
if (operation) {
operations.push(operation);
}
return operations;
}, []),
};
}
|
5ccc2c044204f16992d86d5a13eeaed44a39d29e
|
TypeScript
|
justusburger/expensetracker
|
/ExpenseTracker/ExpenseTracker.UI/ExpenseTracker/Services/ApiResource/ApiResourceService.ts
| 2.640625
| 3
|
module ExpenseTracker.Services.ApiResource {
export class ApiResourceService extends Component {
constructor() {
super();
}
public defaultOnError<T>(response: Models.IErrorResponse, defer: ng.IDeferred<T>, expectedErrorsTypes?: string[]): void {
if (angular.isString(response.data))
response.data = JSON.parse(<string>response.data);
if (response.data && !Enumerable.From(expectedErrorsTypes).Contains(response.data.type)) {
if (response.status === 401) {
this.cacheService.profile = undefined;
this.locationService.path('/sign-in/expired');
} else {
this.alertService.error('An unexpected error occured: ' + response.data.message);
}
}
defer.reject(response);
}
public defaultOnSuccess<T>(response: T, defer: ng.IDeferred<T>): void {
defer.resolve(response);
}
public asString(data: string): any {
if(data[0] == '"')
return { content: data.substr(1, data.length - 2) };
return data;
}
public asBoolean(data: string): any {
if(data.toLowerCase() === 'true' || data.toLowerCase() === 'false')
return { content: data === 'true' };
return data;
}
}
}
|
bddda4ce346ea92c8de510cce67fabdc02debf60
|
TypeScript
|
kotov9/webpack-edu
|
/src/analitics.ts
| 2.53125
| 3
|
import * as $ from 'jquery';
const createAnalitics = (): object => {
let counter = 0;
let finished: boolean = false;
const countClicks = (): number => counter++;
$(document).on('click', countClicks);
return {
destroy() {
$(document).off('click', countClicks);
finished = true;
},
getClicks (){
if (finished) {
return 'Analitics has finished.';
}
return counter;
}
}
}
window['analitics'] = createAnalitics();
|
c0c89c607ea1ecfcb822f5c5fd86953e5df0b5cd
|
TypeScript
|
heestand-xyz/texture.js
|
/sources/types/TEXResolution.ts
| 2.65625
| 3
|
class TEXResolution {
width: number
height: number
static fullHD: TEXResolution = new TEXResolution(1920, 1080);
static ultraHD: TEXResolution = new TEXResolution(3840, 2160);
constructor(width: number, height: number) {
this.width = width
this.height = height
}
}
// module.exports = TEXResolution;
|
cdce7afc3a31d09dbf66376c0dc640342724d6e3
|
TypeScript
|
Jellybooks/web
|
/shared/src/publication/epub/Presentation.ts
| 2.828125
| 3
|
import { Link } from '../Link';
import { Presentation } from '../presentation/Presentation';
import { EPUBLayout } from './EPUBLayout';
declare module '../presentation/Presentation' {
export interface Presentation {
layoutOf(link: Link): EPUBLayout;
}
}
/** Determines the layout of the given resource in this publication.
* Default layout is reflowable.
*/
Presentation.prototype.layoutOf = function(link: Link): EPUBLayout {
return link.properties?.getLayout() || this.layout || EPUBLayout.reflowable;
};
|
2fd954e7f7e64aaf0a3916a5219c656343adbb88
|
TypeScript
|
drocha87/euyome-frontend
|
/rules.ts
| 3.0625
| 3
|
import { Rules } from './types';
const rules: Rules = {
required: (v: string) => !!v || 'Campo obrigatório',
text: (v: string) => /[A-zÀ-ú]*/.test(v) || 'Caracteres inválidos no texto',
email: (v: string) => /.+@.+\..+/.test(v) || 'E-mail inválido',
url: (v: string) =>
/^(https:\/\/)?[\w.-]+(?:\.[\w.-]+)+[\w\-._~:/?#[\]@!$&%'()*+,;=.]+$/gm.test(
v
) || 'Url inválida',
phoneNumber: (v: string) =>
/^[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s./0-9]*$/gm.test(v) || 'Telefone inválido',
digits: (v: string) => /^[0-9]*$/gm.test(v) || 'Campo aceita somente números',
password: (v: string) =>
(v && v.length >= 5 && v.length <= 30) ||
'Password precisa ter entre 5 e 30 caracteres',
maxLength: (l: number) => (v: string | undefined) => {
if (!v) {
// iff v is undefined we should do nothing since we are not breaking maxLenght rule
return true;
}
return v.length < l || 'Tamanho máximo excedido';
},
minLength: (l: number) => (v: string) =>
(v && v.length > l) || `Tamanho minímo requerido de ${l} caracteres`,
validate: (reg: RegExp, msg: string) => (v: string) => {
if (!reg) return true;
return reg.test(v) || msg;
},
instagram: (v: string) =>
/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim.test(v) || 'Usuário inválido',
facebook: (v: string) => /^[^\s^\\]+$/gim.test(v) || 'Facebook inválido',
hexColor: (v: string) =>
/^#[0-9a-fA-F]{6}$/.test(v) || 'Código da cor inválido',
};
export default rules;
|
f956d2139131ed1aeaede0a7f5f54de3ab878899
|
TypeScript
|
yuki-tylar/ngx-widgets-form
|
/projects/form/src/lib/textfield-controller.ts
| 3.015625
| 3
|
import { FormItemController, IFormItemController } from "./form-item-controller";
export interface ITextfieldController extends IFormItemController{
value: string;
}
export class TextfieldController extends FormItemController implements ITextfieldController{
private _value: string = '';
get value(){ return this._value; }
constructor(){ super(); }
clearValue(){ this._value = ''; }
setValue(s?: string){ this._value = (s && s.length>0)? s : ''; }
validate(){
const required = this.validators.get('required');
if(required){ required.isValid = this.value? true : false; }
const email = this.validators.get('email');
if(email){
const regEmail = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
email.isValid = this.value.toLowerCase().match(regEmail)? true : false;
}
const min = this.validators.get('min');
if(min){ min.isValid = (min.value && this.value.length >= min.value)? true : false; }
const max = this.validators.get('max');
if(max){ max.isValid = (max.value && this.value.length <= max.value)? true : false; }
}
}
|
f9accc5923c4532de7408c537460a97a193b4a2b
|
TypeScript
|
mikolalysenko/mudb
|
/src/socket/multiplex.ts
| 2.640625
| 3
|
import {
MuSocketServer,
MuSocketServerState,
MuSocketServerSpec,
MuSocket,
MuCloseHandler,
} from './socket';
export class MuMultiSocketServer implements MuSocketServer {
private _state = MuSocketServerState.INIT;
public state () : MuSocketServerState {
return this._state;
}
// currently not in use
public clients:MuSocket[] = [];
private _servers:MuSocketServer[];
private _numLiveServers = 0;
private _onclose:MuCloseHandler = () => { };
constructor (servers:MuSocketServer[]) {
this._servers = servers;
}
public start (spec:MuSocketServerSpec) {
this._onclose = spec.close;
for (let i = 0; i < this._servers.length; ++i) {
this._servers[i].start({
ready: () => ++this._numLiveServers,
connection: spec.connection,
close: () => --this._numLiveServers,
});
}
const startHandle = setInterval(
() => {
if (this._numLiveServers < this._servers.length) {
return;
}
clearInterval(startHandle);
this._state = MuSocketServerState.RUNNING;
spec.ready();
},
300,
);
}
public close () {
for (let i = 0; i < this._servers.length; ++i) {
this._servers[i].close();
}
const closeHandle = setInterval(
() => {
if (this._numLiveServers > 0) {
return;
}
clearInterval(closeHandle);
this._state = MuSocketServerState.SHUTDOWN;
this._onclose();
},
300,
);
}
}
|
23a6b814a2f5b1cfe0eea515a3f7cfa488c3c88f
|
TypeScript
|
HAFDIAHMED/IgniteTraning
|
/app/models/utilisateur/utilisateur.ts
| 2.671875
| 3
|
import { flow, Instance, SnapshotOut, types } from "mobx-state-tree"
import { ProductModel } from ".."
import { Api } from "../../services/api"
/**
* Model description here for TypeScript hints.
*/
export const UtilisateurModel = types
.model("Utilisateur")
.props({
name : types.optional(types.string,"ahmed"),
email : types.optional(types.string,"ahmed@gmail.com"),
token : types.optional(types.string,"token3939393939"),
password : types.optional(types.string,"1111"),
products : types.optional(types.array(ProductModel),[])
})
.views((self) => ({
get getName ( ){
return self.name
},
get getEmail (){
return self.email
},
get getToken(){
return self.token
},
get getPassword(){
return self.password
},
get getProducts (){
return self.products
}
})) // eslint-disable-line @typescript-eslint/no-unused-vars
.actions((self) => ({
setName (value : string){
self.name=value
},
setEmail (value : string){
self.email=value
},
setToken (value : string){
self.token=value
},
setPassword (value : string ){
self.password=value
},
setProducts (value : any){
self.products=value
}
}))
.actions((self)=>({
login : flow(function * (email : string , password : string)
{
const api = new Api()
api.setup()
yield api.Login(email, password).then((response : any)=>{
//console.log(response)
self.setToken(response.token)
})
}
),
GetProd : flow (function * (token : string){
const api= new Api()
api.setup()
yield api.getUtilisateurProd(token).then((response: any)=>{
console.log("response")
//self.setProducts(response)
})
})
}))
// eslint-disable-line @typescript-eslint/no-unused-vars
type UtilisateurType = Instance<typeof UtilisateurModel>
export interface Utilisateur extends UtilisateurType {}
type UtilisateurSnapshotType = SnapshotOut<typeof UtilisateurModel>
export interface UtilisateurSnapshot extends UtilisateurSnapshotType {}
export const createUtilisateurDefaultModel = () => types.optional(UtilisateurModel, {})
|
ef42b848aab6365c830838e723dd35913100bdb5
|
TypeScript
|
3kraft/Knockout-Validation
|
/dist/knockout.validation.d.ts
| 2.546875
| 3
|
import * as ko from "knockout";
declare module "knockout" {
export namespace validation {
export type ValidationObservable<T> = ko.Observable<T> & ObservableValidationExtension;
export type ValidationComputed<T> = ko.Computed<T> & ObservableValidationExtension;
export type ValidationPureComputed<T> = ko.PureComputed<T> & ObservableValidationExtension;
export interface ValidationConfiguration {
/**
* If true validation will insert either a <span> element or the template specified by messageTemplate
* after any element (e.g. <input>)that uses a KO value binding with a validated field.
*/
insertMessages?: boolean;
/**
* Indicates whether to assign an error class to the <input> tag when your property is invalid.
* Note that this was previously called decorateElement, and this config option was renamed 2013-11-21.
*/
decorateInputElement?: boolean;
/** The CSS class assigned to validation error messages inserted when insertMessages is true. */
errorMessageClass?: string;
/** The CSS class assigned to validation error <input> elements, must have decorateInputElement set to true */
errorElementClass?: string;
/** Shows tooltips using input ‘title’ attribute. False hides them. */
errorsAsTitle?: boolean;
/** If defined, the CSS class assigned to both <input> and validation message. */
errorClass?: string;
/** Indicates whether to assign validation rules to your ViewModel using HTML5 validation attributes. */
parseInputAttributes?: boolean;
/** Adds HTML5 input validation attributes to form elements that ko observable’s are bound to. */
writeInputAttributes?: boolean;
/** Indicates whether validation messages are triggered only when properties are modified or at all times. */
messagesOnModified?: boolean;
/** Indicates whether css error classes are added only when properties are modified or at all times. */
decorateElementOnModified?: boolean;
/** The id of the <script type="text/html"></script> that you want to use for all your validation messages. */
messageTemplate?: string;
/** When using the group or validatedObservable functions. */
grouping?: ValidationGroupingOptions;
/** Register custom validation rules defined via ko.validation.rules. */
registerExtenders?: boolean;
}
/** When using the group or validatedObservable functions. */
export interface ValidationGroupingOptions {
/** Indicates whether to walk the ViewModel (or object) recursively, or only walk first-level properties. */
deep?: boolean;
/** Indicates whether the returned errors object is a ko.computed or a simple function. */
observable?: boolean;
/** Indicates whether changes to observableArrays inside the model should cause the validator to re-run. */
live?: boolean;
}
export interface ValidationRule {
/** The rule name. */
rule: string;
/** The rule parameters. */
params: any;
/** The rule message. */
message?: string;
/** The rule condition. */
condition?: () => boolean;
}
export interface ValidationRuleExtenderParams<T = any> {
/** The rule parameters. */
params: T | ko.Subscribable<T>;
/** The rule message. */
message?: string;
/** The rule condition. */
onlyIf?: () => boolean;
}
export interface ObservableValidationExtension {
/** Holds the error message, we only need one since we stop processing validators when one is invalid. */
error: ko.Observable<string | null>;
/** Contains all rules applied to the observable. */
rules: ko.ObservableArray<ValidationRule>;
/** Is the observable modified. */
isModified: ko.Observable<boolean>;
/** In case async validation is occurring. */
isValidating: ko.Observable<boolean>;
/** Indicates whether the observable is valid. */
isValid: ko.Computed<boolean>;
/** Manually set error state. */
setError(error: string): void;
/** Manually clear error state. */
clearError(): void;
/** Dispose validation extension. */
_disposeValidation(): void;
}
export interface ValidationRuleDefinition {
/** The rule message. */
message: string;
/** The rule validator. */
validator(value: any, params: any): boolean;
/** The rule condition. */
condition?: () => boolean;
/** The rule condition. */
onlyIf?: () => boolean;
}
export interface ValidationAsyncRuleDefinition {
/** Indicates that this rule is async. */
async: true;
/** The rule message. */
message: string;
/** The rule async validator. */
validator(value: any, params: any, callback: ValidationAsyncCallback): void;
/** The rule condition. */
condition?: () => boolean;
/** The rule condition. */
onlyIf?: () => boolean;
}
export interface ValidationGroup extends ValidationGroupFunctions {
(): string[];
}
export interface ValidationGroupComputed extends ko.Computed<string[]>, ValidationGroupFunctions { }
export interface ValidationGroupFunctions {
showAllMessages(show?: boolean): void;
isAnyMessageShown(): boolean;
filter(predicate: (obs: ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>) => boolean): Array<ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>>;
find(predicate: (obs: ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>) => boolean): ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>;
forEach(predicate: (obs: ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>) => void): void;
map<U>(predicate: (obs: ko.Observable<any> | ko.ObservableArray<any> | ko.Computed<any>) => U): U[];
}
export type ObjectValidationRuleDefinitions<T = any> = {
[P in keyof T]:
T[P] extends object ? ObjectValidationRuleDefinitions<T[P]> :
T[P] extends Array<infer U> ? ObjectValidationRuleDefinitions<U> :
{ [key: string]: ValidationRuleExtenderParams | ValidationAnonymousRuleDefinition; }
}
export type ValidationAsyncCallback = (result: boolean | { isValid: boolean; message: string; }) => void;
export type ValidationAnonymousRuleDefinition = ValidationRuleDefinition | ValidationAsyncRuleDefinition;
export type ValidationExtendType<T> = T | ko.Subscribable<T> | ValidationRuleExtenderParams<T>;
export type ValidationExtendAccessType<T> = () => T | ValidationExtendType<T>;
export interface ValidationExtendOptions {
validation?: ValidationRule | ValidationRuleDefinition | ValidationAsyncRuleDefinition | Array<ValidationRule | ValidationRuleDefinition | ValidationAsyncRuleDefinition>;
validatable?: boolean | ExtenderValidatableOptions;
required?: ValidationExtendType<boolean>;
min?: ValidationExtendType<number | Date>;
max?: ValidationExtendType<number | Date>;
minLength?: ValidationExtendType<number>;
maxLength?: ValidationExtendType<number>;
pattern?: ValidationExtendType<RegExp>;
step?: ValidationExtendType<number>;
email?: ValidationExtendType<boolean>;
date?: ValidationExtendType<boolean>;
dateISO?: ValidationExtendType<boolean>;
number?: ValidationExtendType<boolean>;
digit?: ValidationExtendType<boolean>;
phoneUS?: ValidationExtendType<boolean>;
equal?: ValidationExtendAccessType<string | number | boolean>;
notEqual?: ValidationExtendAccessType<string | number | boolean>;
unique?: ValidationExtendType<ExtenderUniqueOptions>;
}
export interface ExtenderValidatableOptions {
enable?: boolean;
throttle?: number;
}
export interface ExtenderUniqueOptions {
/** array or function returning (observable) array in which the value has to be unique. */
collection?: ko.MaybeObservableArray<any> | (() => ko.MaybeObservableArray<any>);
/** Function that returns value from an object stored in collection. If it is null the value is compared directly. */
valueAccessor?: (item: any) => any;
/** Set to true when object you are validating is automatically updating collection. */
external?: boolean;
}
/** Call this on startup. Any config can be overridden with the passed in options. */
export function init(options?: ValidationConfiguration, force?: boolean): void;
/** Resets the config back to its original state. */
export function reset(): void;
/**
* Recursively walks a viewModel and creates an object that provides validation information for the entire viewModel.
*
* @param obj The viewModel to walk.
* @param options The grouping options.
*/
export function group(obj: any, options?: ValidationGroupingOptions): ValidationGroup;
/**
* Recursively walks a viewModel and creates an object that provides validation information for the entire viewModel.
*
* @param obj The viewModel to walk.
* @param options The grouping options.
*/
export function group(obj: any, options?: ValidationGroupingOptions & { observable: true }): ValidationGroupComputed;
/**
*
* @param message The message containing replacements.
* @param params The replacement parameters
*/
export function formatMessage(message: string | MessageFunction, params: ko.MaybeSubscribable<string | string[]>, observable?: ko.Observable<any>): string;
export type MessageFunction = (params: ko.MaybeSubscribable<string | string[]>, observable?: ko.Observable<any>) => string;
/**
* This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator.
*
* @example
* ko.validation.addRule(myObservable, {
* rule: "required",
* params: true
* });
*
* @param observable The Observable to extend.
* @param rule The rule configuration.
*/
export function addRule(observable: ko.Observable<any> | ko.Computed<any>, rule: ValidationRule): typeof observable & ObservableValidationExtension;
/**
* Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property
* and developers typically are wanting to add them on the fly or not register a rule with the 'ko.validation.rules' object
*
* @example
* var test = ko.observable("something").extend({
* validation: {
* validator: function (val, someOtherVal) {
* return true;
* },
* message: "Something must be really wrong!",
* params: true
* }
* });
*
* @param observable The Observable to extend.
* @param ruleObj The rule definition object.
*/
export function addAnonymousRule(observable: ko.Observable<any> | ko.Computed<any>, ruleObj: ValidationAnonymousRuleDefinition): void;
/**
* Creates a knockout extender for the specified rule.
*
* @param ruleName The rule to create extender for.
*/
export function addExtender(ruleName: string): void;
/** Loops through all ko.validation.rules and adds them as extenders to ko.extenders. */
export function registerExtenders(): void;
/**
* Creates a span next to the @element with the specified error class.
*
* @param element The HTML Element to insert message after.
*/
export function insertValidationMessage(element: Element): Element;
/**
* If html-5 validation attributes have been specified, this parses the attributes on @element.
*
* @param element The HTML Element to parse attributes on.
* @param valueAccessor The valueAccesor containing the observable to validate.
*/
export function parseInputValidationAttributes(element: Element, valueAccessor: () => any): void;
/**
* Writes html5 validation attributes on the element passed in.
*
* @param element The HTML Element to write attributes on.
* @param valueAccessor The valueAccessor containing the observable to validate.
*/
export function writeInputValidationAttributes(element: Element, valueAccessor: () => any): void;
/**
* Take an existing binding handler and make it cause automatic validations.
*
* @param handlerName The binding handler to make validatable.
*/
export function makeBindingHandlerValidatable(handlerName: string): void;
/**
* Visit an objects properties and apply validation rules from a definition.
*
* @param target The target object to set rules for.
* @param definitions The rules definitions object.
*/
export function setRules<T>(target: T, definitions: ObjectValidationRuleDefinitions<T>): void;
/** Validates specified observable. */
export function validateObservable(observable: ko.Observable<any> | ko.Computed<any>): boolean;
/**
* Applies localization to messages.
*
* @param locale The locale to apply.
*/
export function locale(locale: string): void;
/**
* Defines localization messages.
*
* @param locale The locale to define.
* @param values The messages values.
*/
export function defineLocale(locale: string, values: Object): void;
/**
* Quick function to override rule messages.
*
* @param msgTranslations The messages translations to apply.
*/
export function localize(msgTranslations: any): void;
export const rules: ValidationRules;
export interface ValidationRules {
[name: string]: ValidationRuleDefinition | ValidationAsyncRuleDefinition;
required: ValidationRuleDefinition;
min: ValidationRuleDefinition;
max: ValidationRuleDefinition;
minLength: ValidationRuleDefinition;
maxLength: ValidationRuleDefinition;
pattern: ValidationRuleDefinition;
step: ValidationRuleDefinition;
email: ValidationRuleDefinition;
date: ValidationRuleDefinition;
dateISO: ValidationRuleDefinition;
number: ValidationRuleDefinition;
digit: ValidationRuleDefinition;
phoneUS: ValidationRuleDefinition;
equal: ValidationRuleDefinition;
notEqual: ValidationRuleDefinition;
unique: ValidationRuleDefinition;
}
export namespace utils {
export function isArray<T = any>(o: any): o is Array<T>;
export function isObject(o: any): o is object;
export function isNumber(o: any): o is number;
export function isObservableArray<T = any>(instance: any): instance is ko.ObservableArray<T>;
export function values(o: string): any[];
export function getValue<T>(o: T | (() => T)): T;
export function hasAttribute(node: Element, attr: string): boolean;
export function getAttribute(element: Element, attr: string): string;
export function setAttribute(element: Element, attr: string, value: any): void;
export function isValidatable(o: any): o is ObservableValidationExtension;
export function insertAfter(node: Node, newNode: Node): void;
export function newId(): number;
export function getConfigOptions(element: Element): ValidationConfiguration;
export function setDomData(node: Node, data: any): void;
export function getDomData<T = any>(node: Node): T;
export function contextFor(node: Node): any;
export function isEmptyVal(val: any): val is undefined | null | "";
export function getOriginalElementTitle(element: Element): string;
export function async(expr: () => void): void;
export function forEach<T>(array: T[], callback: (item: T, index: number, list: typeof array) => void): void;
export function forEach<T>(object: T, callback: (key: keyof T, value: any) => void): void;
}
}
/** Creates a validation group observable. */
export function validatedObservable<T extends object | null | undefined>(initialValue?: T, options?: validation.ValidationGroupingOptions & { observable: true }): ko.Observable<T> & { errors: validation.ValidationGroupComputed, isValid: ko.Observable<boolean> };
/** Creates a validation group observable. */
export function validatedObservable<T extends object | null | undefined>(initialValue?: T, options?: validation.ValidationGroupingOptions): ko.Observable<T> & { errors: validation.ValidationGroup, isValid: ko.Observable<boolean> };
/** Creates a new empty Validated Observable. */
export function validatedObservable<T>(initialValue: T): validation.ValidationObservable<T>;
/** Apply Binding with specified validation options. */
export function applyBindingsWithValidation(viewModel: any, options?: validation.ValidationConfiguration): void;
/** Apply Binding with specified validation options. */
export function applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: validation.ValidationConfiguration): void;
export interface BindingHandlers {
validationCore: {
init(element: HTMLElement, valueAccessor: () => ko.MaybeSubscribable<any>, allBindingsAccessor: ko.AllBindings, viewModel: any, bindingContext: ko.BindingContext<any>): void;
};
validationMessage: {
init(element: HTMLElement, valueAccessor: () => ko.MaybeSubscribable<any>): void;
};
validationCovalidationElementre: {
init(element: HTMLElement, valueAccessor: () => ko.MaybeSubscribable<any>, allBindingsAccessor: ko.AllBindings): void;
};
validationOptions: {
init(element: HTMLElement, valueAccessor: () => ko.MaybeSubscribable<validation.ValidationConfiguration>, allBindingsAccessor: ko.AllBindings, viewModel: any, bindingContext: ko.BindingContext<any>): void;
};
}
export interface Extenders<T> {
/**
* This is for creating custom validation logic on the fly.
*
* @example
* var test = ko.observable("something").extend({
* validation: {
* validator: function (val, someOtherVal) {
* return true;
* },
* message: "Something must be really wrong!",
* params: true
* }
* });
*/
validation<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationRule | validation.ValidationRule[]): T & validation.ObservableValidationExtension;
/**
* This is the extender that makes a Knockout Observable also 'Validatable'
*
* @example
* // This will ensure that the Observable object is setup properly to respond to rules
* var test = ko.observable("something").extend({ validatable: true });
*
* // This will remove the validation properties from the Observable object should you need to do that.
* test.extend({ validatable: false });
*/
validatable<T extends ko.Subscribable<any>>(target: T, options: boolean | validation.ExtenderValidatableOptions): T & validation.ObservableValidationExtension;
required<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
min<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<number>): T & validation.ObservableValidationExtension;
max<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<number>): T & validation.ObservableValidationExtension;
minLength<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<number>): T & validation.ObservableValidationExtension;
maxLength<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<number>): T & validation.ObservableValidationExtension;
pattern<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<RegExp>): T & validation.ObservableValidationExtension;
step<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<number>): T & validation.ObservableValidationExtension;
email<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
date<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
dateISO<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
number<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
digit<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
phoneUS<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<boolean>): T & validation.ObservableValidationExtension;
equal<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendAccessType<string | number | boolean>): T & validation.ObservableValidationExtension;
notEqual<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendAccessType<string | number | boolean>): T & validation.ObservableValidationExtension;
unique<T extends ko.Subscribable<any>>(target: T, options: validation.ValidationExtendType<validation.ExtenderUniqueOptions>): T & validation.ObservableValidationExtension;
}
export interface SubscribableFunctions<T> {
extend(requestedExtenders: validation.ValidationExtendOptions): this & validation.ObservableValidationExtension;
}
export interface ObservableExtenderOptions<T> extends validation.ValidationExtendOptions { }
}
export = ko.validation;
|
c230c5653f772e45d720d4925336658e7ae21d7a
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/node/client-ec2-node/types/_KeyPairInfo.ts
| 2.984375
| 3
|
/**
* <p>Describes a key pair.</p>
*/
export interface _KeyPairInfo {
/**
* <p>If you used <a>CreateKeyPair</a> to create the key pair, this is the SHA-1 digest of the DER encoded private key. If you used <a>ImportKeyPair</a> to provide AWS the public key, this is the MD5 public key fingerprint as specified in section 4 of RFC4716.</p>
*/
KeyFingerprint?: string;
/**
* <p>The name of the key pair.</p>
*/
KeyName?: string;
}
export type _UnmarshalledKeyPairInfo = _KeyPairInfo;
|
98b13158836d16a0099c7027a31b44183d881bdd
|
TypeScript
|
damadrigal/TallerAngularGraphql
|
/backend/src/resolvers/Product/ProductResolver.ts
| 2.609375
| 3
|
import { Resolver, Query, Mutation, Arg, Int } from 'type-graphql'
import { Any } from 'typeorm';
import { Product } from '../../entities/Product'
import { ProductInput } from './productInput';
import { ProductUpdateInput } from './productUpdateInput';
@Resolver()
export class ProductResolver {
@Mutation(() => Product)
async createProduct(
@Arg("variables", () => ProductInput) variables: ProductInput
) {
console.log(variables);
const newProduct = await Product.create(variables);
return newProduct.save();
}
@Mutation(() => Boolean)
async deleteProduct(
@Arg("id", () => Int) id: number
) {
await Product.delete(id);
return true;
}
@Mutation(() => Boolean)
async updateProduct(
@Arg("id", () => Int) id: number,
@Arg("fields", () => ProductUpdateInput) fields: ProductUpdateInput
) {
const updateProduct = await Product.update({ id }, fields);
return updateProduct.affected;
}
@Query(() => [Product])
products() {
return Product.find();
}
@Query(() => [Product])
productFilter(
@Arg("name", () => String) name: string,
) {
if (name) {
return Product.find({ where: { name } });
} else {
return Product.find();
}
}
@Query(() => Product)
productById(
@Arg("id", () => Int) id: number
) {
return Product.findOne(
{ where: { id } });
}
}
|
3e60e769c75e7ff95393a7cb5e426b2babd6ffe4
|
TypeScript
|
Vadim-w/TodoList
|
/src/api/todolist-api.ts
| 2.609375
| 3
|
import axios from "axios";
const instance = axios.create({
withCredentials: true,
headers: {
'API-KEY': "0788c074-2a2b-400e-ae91-bcf1a7100923"
},
baseURL: 'https://social-network.samuraijs.com/api/1.1/'
})
//api
export const todoListApi = {
getTodoLists() {
return instance.get<Array<TodoListType>>('todo-lists')
},
createTodoList(title: string) {
return instance.post<CommonResponseType<{item: TodoListType}>>('todo-lists', {title})
},
deleteTodoList(todoId: string) {
return instance.delete<CommonResponseType>(`todo-lists/${todoId}`)
},
updateTodoList(todoId: string, title: string) {
return instance.put<CommonResponseType>(`todo-lists/${todoId}`, {title})
}
}
export const tasksApi = {
getTasks(todoId: string) {
return instance.get<GetTasks>(`/todo-lists/${todoId}/tasks`)
},
createTask(todoId: string, title: string) {
return instance.post<CommonResponseType<{item: TaskType}>>(`/todo-lists/${todoId}/tasks`, {title})
},
deleteTask(todoId: string, taskId: string) {
return instance.delete<CommonResponseType>( `/todo-lists/${todoId}/tasks/${taskId}`)
},
updateTask(todoId: string, taskId: string, model: UpdateTaskModelType) {
return instance.put<CommonResponseType<{item: TaskType}>>( `/todo-lists/${todoId}/tasks/${taskId}`, model)
}
}
export const authAPI = {
login(data: LoginParamsType) {
return instance.post<CommonResponseType<{userId: number}>>( '/auth/login', data)
},
logout() {
return instance.delete<CommonResponseType>( '/auth/login')
},
me() {
return instance.get<CommonResponseType<{item: MeResponseType}>>('/auth/me')
}
}
//types
export type TodoListType= {
id: string
addedDate: string
order: number
title: string
}
export type UpdateTaskModelType = {
title: string
description: string
status: TaskStatuses
priority: TodoTaskPriorities
startDate: string
deadline: string
}
export type TaskType = {
description: string
title: string
status: TaskStatuses
priority: TodoTaskPriorities
startDate: string
deadline: string
id: string
todoListId: string
order: number
addedDate: string
}
export type FieldsErrorType = { field: string, error: string };
export type CommonResponseType<D = {}> = {
resultCode: number
messages: Array<string>
fieldsErrors?: Array<FieldsErrorType>
data: D
}
type GetTasks = {
items: Array<TaskType>
totalCount: number
error: string | null
}
export enum TaskStatuses {
New,
InProgress,
Completed,
Draft
}
export enum TodoTaskPriorities {
Low,
Middle,
Hi,
Urgently,
Later
}
export type LoginParamsType = {
email: string
password: string
rememberMe: boolean
captcha?: boolean
}
export type MeResponseType = {
id: number
email: string
login: string
}
|
fd2a57bd537ba3b9cb08c1a87eb4ca3d0d5a0fd7
|
TypeScript
|
gitter-badger/owge
|
/game-frontend/projects/game-frontend/src/helpers/common-component-test.helper.ts
| 2.875
| 3
|
import { By } from '@angular/platform-browser';
import { AbstractCommonTestHelper, StatePrefix } from './abstract-common-test.helper';
import { ProgrammingError } from './../error/programming.error';
import { TestBed, TestModuleMetadata, ComponentFixture } from '@angular/core/testing';
import { DebugElement, Type, SimpleChanges, SimpleChange } from '@angular/core';
/**
* Represents a component and its HTMLElement
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @export
* @interface ComponentElement
* @template T Component type
*/
export interface ComponentElement<T> {
component: T;
element: HTMLElement;
}
export interface DirectiveNameValue {
name: string;
value: any;
}
/**
* This helper simplifies testing configuration for a <b>component</b><br>
* So one can assign time to the important things <br>
* Test that the things are actually working!
*
* @export
* @class CommonComponentTestHelper
* @template T Component type to test for example AppComponent
* @author Kevin Guanche Darias
*/
export class CommonComponentTestHelper<T> extends AbstractCommonTestHelper<T> {
protected _targetClass: Type<T>;
/**
* Will return readonly reference to component instance
*
* @readonly
* @type {T}
* @memberOf CommonComponentTestHelper
* @throws ProgrammingError When undefined, maybe because <b> called outside an it() or beforeEach() </b>
* @author Kevin Guanche Darias
*/
public get component(): T {
if (!this._component) {
throw new ProgrammingError('Cannot get component, did you call ' + this.constructor.name + '.createComponent() ?');
}
return this._component;
}
private _component: T;
/**
* Will return readonly reference to component's fixture
*
* @readonly
* @type {ComponentFixture<T>}
* @memberOf CommonComponentTestHelper
* @throws ProgrammingError When undefined, maybe because <b> called outside an it() or beforeEach() </b>
* @author Kevin Guanche Darias
*/
public get fixture(): ComponentFixture<T> {
if (!this._fixture) {
throw new ProgrammingError('Cannot get fixture, did you call' + this.constructor.name + '.createComponent() ?');
}
return this._fixture;
}
private _fixture: ComponentFixture<T>;
/**
* Creates an instance of CommonComponentTestHelper.
*
* @param {Type<T>} targetClass target component to test, for example <b>AppComponent</b>
* @param {TestModuleMetadata} [config] Test declarations, providers... , if undefined defaults to app settings
* @param {boolean} [fastSpawn=true] if should configure the test and create the component, just <b>NOW!</b>
* @param {boolean} [runNgOnInit=true] Should start ng life-cycle (calls ngOnInit etc)
* @memberOf CommonComponentTestHelper
* @author Kevin Guanche Darias
*/
public constructor(targetClass: Type<T>, config?: TestModuleMetadata, fastSpawn = true, runNgOnInit = true) {
super(targetClass);
let targetConfig: TestModuleMetadata = config;
if (config && config.declarations instanceof Array) {
targetConfig.declarations = config.declarations.concat([targetClass]);
} else {
targetConfig = {
declarations: [targetClass]
};
}
if (fastSpawn) {
this.configureTestingModule(targetConfig).configureServiceLocator().createComponent(runNgOnInit);
}
}
/**
* Creates the tested component itself, and it's fixture <br>
* <b>IMPORTANT:</b> Does it <b>INSIDE</b> a beforeEach() block
*
* @param {boolean} [runNgOnInit=true] runs ng life-cycle, for example runs ngOnInit() method
* @returns {CommonComponentTestHelper<T>}
* @memberOf CommonComponentTestHelper
* @author Kevin Guanche Darias
*/
public createComponent(runNgOnInit = true): CommonComponentTestHelper<T> {
beforeEach(() => {
this.createComponentNow(runNgOnInit);
});
return this;
}
/**
* Creates the tested component itself, and it's fixture <br>k
*
* @param {boolean} [runNgOnInit=true] runs ng life-cycle, for example runs ngOnInit() method
* @returns {CommonComponentTestHelper<T>}
* @memberOf CommonComponentTestHelper
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
*/
public createComponentNow(runNgOnInit = true): CommonComponentTestHelper<T> {
this._fixture = TestBed.createComponent(this._targetClass);
this._component = this._fixture.componentInstance;
if (runNgOnInit) {
this.startNgLifeCycle();
}
return this;
}
/**
* Starts ng life-cycle, so runs things like ngOnInit() ... ngOnAfterViewInit(), etc <br>
* <b>IMPORTANT:</b> usually is call inside a beforeEach() block, calling from describe() will crash
*
* @returns {CommonComponentTestHelper<T>}
* @memberOf CommonComponentTestHelper
* @author Kevin Guanche Darias
*/
public startNgLifeCycle(): CommonComponentTestHelper<T> {
this._fixture.detectChanges();
return this;
}
public startNgLifeCycleBeforeEach(): CommonComponentTestHelper<T> {
this.beforeEach(() => this.startNgLifeCycle());
return this;
}
/**
* Test the component creates with success
*
* @returns {CommonComponentTestHelper<T>}
* @memberOf CommonComponentTestHelper
* @author Kevin Guanche Darias
*/
public testItCreates(): this {
it('should create', () => {
expect(this._component).toBeTruthy();
});
return this;
}
public testHtmlElementPresent(htmlElementSelector, negate = false, text?: string): this {
const validationBoolean: boolean = !negate;
if (!text) {
text = 'HTML element with selector ' + htmlElementSelector + ' should' + (negate ? ' NOT ' : ' ') + 'exists';
}
expect(!!this._fixture.nativeElement.querySelector(htmlElementSelector)).toBe(validationBoolean, text);
return this;
}
/**
* Test the number of HTML elements with the given CSS selector match the <b>expectedNumber</b>
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector CSS selector
* @param {number} expectedNumber Number of elements that should be matched
* @returns {HTMLElement[]} elements that were found
* @memberof CommonComponentTestHelper
*/
public testHtmlNumberOfElements(htmlElementSelector: string, expectedNumber: number): HTMLElement[] {
const retVal: HTMLElement[] = this.fixture.nativeElement.querySelectorAll(htmlElementSelector);
this.testHtmlElementPresent(htmlElementSelector);
expect(retVal.length).toBe(expectedNumber);
return Array.prototype.slice.call(retVal);
}
/**
* Validates the text node value of the HTML element, if It's an INPUT will validate it't value
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector target HTML element CSS like selector
* @param {string} expectedValue Expected text value
* @param {boolean} [negate=false] If true will test that element text is NOT the same as <i>expectedValue</i>
* @returns {this}
* @memberof CommonComponentTestHelper
*/
public testHtmlElementTextContent(htmlElementSelector: string, expectedValue: string, negate = false): this {
this.testHtmlElementPresent(htmlElementSelector);
const validationBoolean: boolean = !negate;
const element: HTMLElement = this._fixture.nativeElement.querySelector(htmlElementSelector);
const targetProperty: keyof HTMLInputElement = element instanceof HTMLInputElement
? 'value'
: 'innerText';
if (negate) {
expect(element[targetProperty]).not.toBe(expectedValue);
} else {
expect(element[targetProperty]).toBe(expectedValue);
}
return this;
}
/**
* Fires a dom value change event in a input/textarea element, useful for testing that ngModel is specified
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector CSS selector
* @param {string} value Value to assign to the input
* @returns {Promise<void>} Resolves when the view is stable
* @memberof CommonComponentTestHelper
* @throws {ProgrammingError} When element is not an input nor a textarea
*/
public async fireInputValueChangeEvent(htmlElementSelector: string, value: string): Promise<void> {
this.testHtmlElementPresent(htmlElementSelector);
const input: HTMLInputElement | HTMLTextAreaElement = this._fixture.debugElement.query(By.css(htmlElementSelector)).nativeElement;
if (input.tagName !== 'INPUT' && input.tagName !== 'TEXTAREA') {
throw new ProgrammingError('element must be an input, but element tagName is ' + input.tagName);
}
input.value = value;
if (input instanceof HTMLTextAreaElement) {
input.innerText = value;
}
input.dispatchEvent(new Event('input'));
await this.reloadView();
}
/**
* Fires a select event
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector target select element
* @param {string} optionValue target option value
* @param {boolean} [fakeOption=false] if true, option element will be fake, so there is no need for it to exists
* @returns {Promise<void>}
* @memberof CommonComponentTestHelper
*/
public async fireSelectValueChangeEvent(htmlElementSelector: string, optionValue: string, fakeOption = false): Promise<void> {
this.testHtmlElementPresent(htmlElementSelector);
const select: HTMLSelectElement = this._fixture.debugElement.query(By.css(htmlElementSelector)).nativeElement;
if (select.tagName !== 'SELECT') {
throw new ProgrammingError('element MUST be a select, but element tagName is ' + select.tagName);
}
if (fakeOption) {
const fakeOptionEl: HTMLOptionElement = document.createElement('option');
fakeOptionEl.value = optionValue;
select.options.add(fakeOptionEl);
}
const index = Array.prototype.findIndex.call(select.options, (current: HTMLOptionElement) => current.value === optionValue);
if (index === -1) {
throw new ProgrammingError('There is no option with value ' + optionValue);
}
select.value = (<any>select.options[index]).value;
select.selectedIndex = index;
select.dispatchEvent(new Event('change'));
await this.reloadView();
if (fakeOption) {
select.options.remove(select.options.length - 1);
}
}
/**
* Finds the value of a directive
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector
* @param {string} directiveSelector
* @returns {*}
* @memberof CommonComponentTestHelper
*/
public findDirectiveValue(htmlElementSelector: string, directiveSelector: string): any {
const target: DebugElement = this._fixture.debugElement.query(By.css(htmlElementSelector));
if (target) {
return target.properties[directiveSelector];
} else {
console.warn('No component with id ' + htmlElementSelector + ' was found');
}
}
/**
* Test a directive value <br>
* <b>Notice: This must be called when the view is stable <br>
* <b>Seems to work ONLY when the target-selector is a "custom schema" (selector is not in the "declarations" of the TestBed</b> <br>
* <b>If called is a declared component you can use something like </b> <code>
* expect(CommonComponentTestHelper.findComponentInstance(htmlElementSelector)[directiveSelector]).toBe(expectedValue)
* </code>
*
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} htmlElementSelector CSS selector for element having the directive
* @param {string} directiveSelector Directive to test
* @param {*} expectedValue Expected value for the directive
* @returns {CommonComponentTestHelper} this instance
* @memberof CommonComponentTestHelper
*/
public testDirectiveValue(htmlElementSelector: string, directiveSelector: string, expectedValue: any): this {
const actualValue = this.findDirectiveValue(htmlElementSelector, directiveSelector);
expect(actualValue).toBe(
expectedValue,
'directive [' + directiveSelector + '] for CSS selector "' + htmlElementSelector + '" has value: "' + actualValue +
'", but should be "' + expectedValue + '"'
);
return this;
}
public itDirectivesForSelector(selector: string, ...directives: DirectiveNameValue[]): void {
directives.forEach(current => {
it(`Should pass ${current.name} to ${selector}`, () => {
this.testDirectiveValue(selector, current.name, current.value);
});
});
}
/**
* Reloads the view, this method is a shortcut to calling this.startNgLifeCycle() and fixture.whenStable()
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @returns {Promise<void>} Solves when the view is stable
* @memberof CommonComponentTestHelper
*/
public async reloadView(): Promise<void> {
await this.startNgLifeCycle()._fixture.whenStable();
}
/**
* Will trigger an angular event, with specified value
*
* @param {string} htmlElementSelector Using CSS style selector
* @param {any} angularEventName Name of the event for example 'change'
* @param {*} value Value to put as $event
* @returns {Promise<this>} Promise run when fixture is stable!
*
* @memberOf CommonComponentTestHelper
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
*/
public triggerEventOnElement(htmlElementSelector: string, angularEventName: string, value?: any): Promise<this> {
return new Promise((resolve, reject) => {
const element: DebugElement = this._fixture.debugElement.query(By.css(htmlElementSelector));
if (!element) {
throw new ProgrammingError('No element with selector ' + htmlElementSelector + ' in the fixture');
}
this.fixture.whenStable().then(() => {
const eventValue = value || {};
if (!eventValue.target) {
eventValue.target = this._fixture.nativeElement.querySelector(htmlElementSelector);
}
element.triggerEventHandler(angularEventName, eventValue);
this.startNgLifeCycle()._fixture.detectChanges();
this._fixture.whenStable().then(() => resolve());
});
});
}
/**
* Finds a component instance <br>
* <b>IMPORTANT: If the component selector is NOT in the declarations, will have unexpected behavior </b>
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @returns {any} Angular component instance
* @param htmlElementSelector selector of the component
*/
public findComponentInstance(htmlElementSelector: string): any {
return this.fixture.debugElement.query(By.css(htmlElementSelector)).componentInstance;
}
/**
* Finds all component instances for given selector <br>
*
* <b>IMPORTANT: If the component selector is NOT in the declarations, will have unexpected behavior </b>
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param htmlElementSelector CSS selector
* @template C Component type
* @returns {C[]} array of component instances
*/
public findComponentInstances<C>(htmlElementSelector: string): C[] {
return this.fixture.debugElement.queryAllNodes(By.css(htmlElementSelector))
.filter(current => current instanceof DebugElement && !!current.componentInstance)
.map(current => current.componentInstance);
}
/**
* Finds a component instance using Angular id
* <b>IMPORTANT: If the component selector is NOT in the declarations, will have unexpected behavior </b>
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {string} angularId
* @param {boolean} returnElement If defined will return both the element and the component
* @returns {any} If returnElement is true, will look like { component: Type, element: HTMLElement}, else will only return component
* @template C Component
* @memberof CommonComponentTestHelper
*/
public findComponentInstanceByAngularId<C = any>(angularId: string): ComponentElement<C> {
const el: HTMLElement = this.findElementByAngularId(angularId);
const tempId: string = 't' + new Date().getTime().toString();
const oldId = el.id;
el.id = tempId;
const retVal: ComponentElement<C> = {
component: this.findComponentInstance('#' + tempId),
element: el
};
el.id = oldId;
return retVal;
}
public testInstanceOf(expectedClass: Function, state: StatePrefix = '') {
this.testAsync('should be an instance of ' + expectedClass.name, () => {
expect(this.component).toEqual(jasmine.any(expectedClass));
}, state);
}
public findElementByAngularId(angularId): HTMLElement {
return this.fixture.debugElement.query(de => de.references[angularId]).nativeElement;
}
/**
* Fires the ngOnChanges angular life-cycle <br>
* Due to a change in Angular 4, the fixture.detectChanges() doesn't fire the ngOnChanges() method
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {keyof T} property target property
* @param {*} value new value
* @returns {Promise<void>} result, it's a promise to keep an eye to the future, because in the future, will call detectChanges()
* @see https://stackoverflow.com/questions/48086130/ngonchanges-not-called-in-angular-4-unit-test-detectchanges
* @memberof CommonComponentTestHelper
*/
public async fireNgChanges(property: keyof T, value: any): Promise<void> {
const target: SimpleChanges = {};
target[property] = new SimpleChange(this.component[property], value, null);
this.component[property] = value;
await this.component['ngOnChanges'](target);
}
/**
* Test that fields are correctly displayed in the row <br>
* <b>NOTICE:</b> Silently uses input fields to string
*
* @author Kevin Guanche Darias <kevin@kevinguanchedarias.com>
* @param {HTMLElement} row
* @param {any[]} fields Expected field values, sorted from left to right
* @memberof CommonComponentTestHelper
*/
public testTableRowValues(row: HTMLElement, fields: any[]): void {
if (row.tagName !== 'TR') {
throw new ProgrammingError('Input MUST be a row item');
}
const stringFields = fields.map(current => current.toString());
const tds = row.querySelectorAll('td');
for (let i = 0; i < tds.length; i++) {
expect(tds.item(i).textContent).toBe(stringFields[i], 'fatal, in field index ' + i);
}
}
public triggerNgModel(input: HTMLInputElement | string, value: string) {
const targetEl: HTMLInputElement = typeof input === 'string'
? <any>document.querySelector(input)
: input;
targetEl.value = value;
targetEl.dispatchEvent(new Event('input'));
}
}
|
4be4865a70a4dfb1431d98b4125cfeb7706b9913
|
TypeScript
|
talamaska/rxjs-angular2-examples
|
/keyboard-shortcuts/src/app/keyboard-shortcuts/keyboard-shortcuts.service.ts
| 2.609375
| 3
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { default as keyCodeMap } from './keyCodeMap';
@Injectable()
export class KeyboardShortcutsService {
keyDowns: any;
keyUps: any;
keyEvents: any;
constructor() {
this.keyDowns = Observable.fromEvent(document, 'keydown');
this.keyUps = Observable.fromEvent(document, 'keyup');
this.keyEvents = Observable
.merge(this.keyDowns, this.keyUps)
.distinctUntilChanged(
(a: KeyboardEvent, b: KeyboardEvent) => {
return a.keyCode === b.keyCode && a.type === b.type;
}
)
.share();
}
validate = text => {
let arr = text.split('+');
for (let i = 0; i < arr.length; i++) {
if (keyCodeMap[arr[i].toLowerCase()] === undefined) {
return false;
}
}
return true;
}
createKeyPressStream = (charCode) => {
return {
char: charCode,
stream: this.keyEvents
.filter((event) => event.keyCode === charCode)
.map(e => e.type)
};
}
createShortcutStream = (text) => {
return Observable
.from(text.split('+'))
.map(c => {
let code = keyCodeMap[(c as string).toLowerCase()];
if (code === undefined) {
throw new Error('Invalid sequence ' + text);
}
return code;
})
.map(this.createKeyPressStream)
.map(obj => obj.stream)
.toArray()
.flatMap(arr => {
return Observable.combineLatest(arr);
})
.filter(arr => {
let isDown = true;
for (let i = 0; i < arr.length; i++) {
isDown = isDown && (arr[i] === 'keydown');
}
return isDown;
})
.map(x => text);
}
}
|
a2633a98a079c0041a1d15b2634b0186d574ab74
|
TypeScript
|
MrZhouZh/awesome-validator
|
/src/rules/uppercase.ts
| 2.671875
| 3
|
import { AbstractRule } from './abstract-rule';
export class Uppercase extends AbstractRule {
/**
* Validate.
*/
public validate(input: any): boolean {
return input === String(input).toLocaleUpperCase();
}
}
export default Uppercase;
|
d51c0aa90fd52e10a1e9f305caf8516aab8f1591
|
TypeScript
|
bridgecrew-perf7/assignment-deployment-1
|
/src/lib/command.ts
| 3.390625
| 3
|
import process from 'process';
type Args = {
[key: string]: string;
};
const noop = (a: any) => (a)
export default class Command {
private _options: string[];
private _values: string[];
//TODO: change any to specific type
private _args: any;
constructor() {
this._options= [];
const [, , ...rest] = process.argv;
this._values = rest;
this._args = {}
}
addOption(opt: string, typeConverter = noop) {
this._options.push(opt);
this._args[opt] = typeConverter(this._values[Object.keys(this._args).length]);
return this;
}
//TODO: change any to specific type
execute(fn: (arg: any) => void) {
fn(this._args)
return this;
};
}
|
1c23630256900510319424868b75957ca2a7f95f
|
TypeScript
|
riansco14/project-react-1
|
/backend/src/errors/AppError.ts
| 2.734375
| 3
|
class AppError {
public readonly message:string
public readonly statusCode: number
constructor (message:string, statusCode = 400) {
this.message = message
this.statusCode = statusCode
}
}
export default AppError
|
4d611c8cd8000a31f83d4679e9af64d58c357aa1
|
TypeScript
|
suckerp/angular
|
/FrontendToDo/src/app/observabletest.ts
| 3.3125
| 3
|
import * as rx from 'rxjs'
import * as op from 'rxjs/operators'
const myObservable = rx.of(1,2,3)
const myObservable2 = rx.Observable.create((observer)=>{
let wiederhole = 1
while (wiederhole > 0.1){
wiederhole = Math.random()
if (wiederhole<0.75) observer.next(wiederhole)
else observer.error(wiederhole)
}
observer.complete()
//nach dem complete kommt nix mehr
observer.next(55)
}
)
/*
const myObservable2 = rx.Observable.create((observer)=>{
let wiederhole = 1
while (wiederhole > 0.1){
wiederhole = Math.random()
new Promise ((resolve, reject)=>{
setInterval(()=>{
let test = Math.random()
if (test<1){
resolve(observer.next(test))
}
else{
reject(observer.error(test))
}
}, 1000)
})
}
setTimeout(()=>{observer.complete()},6000)
})*/
myObservable
//Manipulation von Daten mit .pipe()
.pipe(
//op.map(function(x){return x+1}),
op.map(x=>x+1),
op.filter(x=>x!=2)
)
.subscribe(
// 1 Callback-Funktion für den Erfolgsfall
result=>{console.log(result)},
// 2 Callback-Funktion für den Fehlerfall
//Beim ersten Fehler ist das Observable geschlossen
error=>{console.log(error)},
// 3. Callback-Funktion wir nach Beendigung ausgeführt (kalt)
()=>{console.log("fertig")}
)
myObservable2
.subscribe(
result=>{console.log(result)},
error=>{console.log(error)},
()=>{console.log("fertig")}
)
.unsubscribe()
|
add6149a24d91bb1833f559c7fdc916036c48f7f
|
TypeScript
|
minofrk/msf-pretty-print.js
|
/src/format/index.ts
| 3.140625
| 3
|
import { Option, some, none } from 'fp-ts/lib/Option';
import { Position, StringArray, Board } from './codecs';
import boardToString from './board-to-string';
export default function format(key: string, value: unknown): Option<string> {
if (typeof value === 'string' && /^\$\d+$/.test(value)) {
return some(value);
}
if (key === 'ele' && Board.is(value)) {
return some(boardToString(value));
}
if (
(key === 'i' || key === 'a') &&
Position.is(value) &&
Object.keys(value).length === 2
) {
return some(`{ "alsia": ${value.alsia}, "soom": ${value.soom} }`);
}
if ((key === 'txifol' || key === 'korol') && StringArray.is(value)) {
return some('[' + value.map((x): string => `"${x}"`).join(', ') + ']');
}
return none;
}
|
d7e370a9b91155e380575fe95cc7e05188d8ee28
|
TypeScript
|
jduehring/opencast-editor
|
/src/redux/mainMenuSlice.ts
| 2.984375
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { MainMenuStateNames} from '../types'
export interface mainMenu {
value: MainMenuStateNames,
}
const initialState: mainMenu = {
value: MainMenuStateNames.cutting,
}
/**
* Slice for the main menu state
*/
export const mainMenuSlice = createSlice({
name: 'mainMenuState',
initialState,
reducers: {
setState: (state, action: PayloadAction<mainMenu["value"]>) => {
state.value = action.payload;
}
}
})
export const { setState, } = mainMenuSlice.actions
// The function below is called a selector and allows us to select a value from
// the state. Selectors can also be defined inline where they're used instead of
// in the slice file. For example: `useSelector((state) => state.counter.value)`
export const selectMainMenuState = (state: { mainMenuState: { value: mainMenu["value"]; }; }) => state.mainMenuState.value
export default mainMenuSlice.reducer
|
7d1cc59ab4662329172e6c81ec5de16a2e268649
|
TypeScript
|
genk1/react-hook
|
/packages/cache/types/lru.d.ts
| 2.828125
| 3
|
export declare const lru: <Key = string, Value = any>(
maxSize: number
) => LRUCache<Key, Value>
export declare type LRUCache<Key = string, Value = any> = {
head: LRUNode<Key, Value> | undefined
size: number
forEach(fn: (key: Key, value: Value) => void): void
search(key: Key): LRUNode<Key, Value> | undefined
read(key: Key): Value | undefined
write(key: Key, value: Value): Value
delete(key: Key): Value | undefined
pop(): Value | undefined
_insertHead(node: LRUNode<Key, Value>): void
_deleteNode(node: LRUNode<Key, Value>): void
}
declare type LRUNode<Key = string, Value = any> = {
next: LRUNode<Key, Value>
prev: LRUNode<Key, Value>
key: Key
value: Value
}
export {}
|
48a3f7366d61500d796a01f643c11110789df7e2
|
TypeScript
|
joshuafairchild1/websocket-chat
|
/src/client/state/reducer.tests.ts
| 2.59375
| 3
|
'use strict'
import { default as reduce } from './reducer'
import { AppState } from './StateStore'
import { Actions, StoreAction } from './Action'
import RoomJoinedPayload from '../../shared/model/RoomJoinedPayload'
import ChatMessage from '../../shared/model/ChatMessage'
import { assert } from 'chai'
import Room from '../../shared/model/Room'
import ConnectPayload from '../../shared/model/ConnectPayload'
const ROOM_ID = 'roomId'
const CLIENT_ID ='clientId'
describe('reducer', function() {
let testRoom: Room
let testMessage: ChatMessage
beforeEach(function () {
testRoom = new Room('my room').withId(ROOM_ID)
testMessage = new ChatMessage(CLIENT_ID, 'Person', 'hello world!')
})
it('reduces undefined to new state instance', function () {
const state = reduce(undefined, <StoreAction>{})
assert.deepEqual(state, new AppState())
})
it('ROOM_JOINED', function () {
const initialState = new AppState()
initialState.rooms = [ testRoom ]
const messages = [ testMessage ]
const payload = new RoomJoinedPayload(ROOM_ID, CLIENT_ID, messages)
const action = { type: Actions.ROOM_JOINED, payload }
const expected = new AppState([ testRoom ])
expected.selectedRoom = <Room>{ ...testRoom, messages }
expected.clientId = CLIENT_ID
assert.deepEqual(reduce(initialState, action), expected)
})
it('LEAVE_ROOM', function () {
const action = { type: Actions.LEAVE_ROOM }
const initialState = new AppState([], 'Joshua', testRoom)
const expected = new AppState()
expected.selectedRoom = null
expected.userName = 'Anonymous'
assert.deepEqual(reduce(initialState, action), expected)
})
it('NEW_MESSAGE', function () {
const action = { type: Actions.NEW_MESSAGE, payload: testMessage }
const initialState = new AppState()
initialState.selectedRoom = testRoom
const expected = new AppState()
expected.selectedRoom = <Room>{ ...testRoom, messages: [ testMessage ] }
assert.deepEqual(reduce(initialState, action), expected)
})
it('NEW_ROOM', function () {
const action = { type: Actions.NEW_ROOM, payload: testRoom }
const expected = new AppState([ testRoom ])
assert.deepEqual(reduce(undefined, action), expected)
})
it('UPDATE_MESSAGES', function () {
const newMessages = [
new ChatMessage(CLIENT_ID, 'Joshua', 'hello other world')
]
const action = { type: Actions.UPDATE_MESSAGES, payload: newMessages }
const room = <Room>{ ...testRoom, messages: [ testMessage ] }
const updatedRoom = <Room>{ ...testRoom, messages: newMessages }
const initialState = new AppState([ room ])
initialState.selectedRoom = room
const expected = new AppState([ updatedRoom ])
expected.selectedRoom = updatedRoom
assert.deepEqual(reduce(initialState, action), expected)
})
it('INITIAL_CONNECTION', function () {
const payload = new ConnectPayload([ testRoom ], CLIENT_ID)
const action = { type: Actions.INITIAL_CONNECTION, payload }
const expected = new AppState([ testRoom ])
expected.subscriptionId = CLIENT_ID
assert.deepEqual(reduce(undefined, action), expected)
})
it('SET_USERNAME', function () {
const name = 'Skippy'
const action = { type: Actions.SET_USERNAME, payload: name }
const expected = new AppState()
expected.userName = name
assert.deepEqual(reduce(undefined, action), expected)
})
})
|
f43f43eafdf87cdcbe2d580188a6ef78d82365e3
|
TypeScript
|
yurialvesbrasil/auth_service_public
|
/src/index.ts
| 2.515625
| 3
|
import 'reflect-metadata';
import { SetupServer } from './server';
import logger from './logger';
enum ExitStatus {
Failure = 1,
Success = 0,
}
process.on('unhandledRejection', (reason, promise) => {
logger.error(
`O aplicativo está saindo devido a uma promessa não tratada: ${promise} em razão de: ${reason}`
);
// lets throw the error and let the uncaughtException handle below handle it
throw reason;
});
process.on('uncaughtException', (error) => {
logger.error(`O aplicativo está saindo devido a uma exceção não detectada: ${error}`);
process.exit(ExitStatus.Failure);
});
(async (): Promise<void> => {
try {
const server = new SetupServer();
await server.init();
server.start();
const exitSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGQUIT'];
for (const exitSignal of exitSignals) {
process.on(exitSignal, async () => {
try {
logger.info(`App exited with success`);
process.exit(ExitStatus.Success);
} catch (error) {
logger.error(`App exited with error: ${error}`);
process.exit(ExitStatus.Failure);
}
});
}
} catch (error) {
logger.error(`App exited with error: ${error}`);
process.exit(ExitStatus.Failure);
}
})();
|
b19501ac1d274e8badbb82243ca3100eea759566
|
TypeScript
|
gu-tum-gun-aeng/med4all-be
|
/tests/unit/services/patient/patient.validator.test.ts
| 2.71875
| 3
|
import { assertEquals } from "../../../../deps.ts";
import { ExternalRoutingDestination } from "../../../../src/models/enum/externalRoutingDestination.ts";
import { colinkValidator } from "../../../../src/models/patient/request/validator/colink.validator.ts";
import { wisibleValidator } from "../../../../src/models/patient/request/validator/wisible.validator.ts";
import {
getCreatePatientValidatorFrom,
getCreatePatientValidatorsFrom,
} from "../../../../src/services/patient/patient.validator.ts";
Deno.test("getCreatePatientValidatorsFrom should return validators when given external destinations", () => {
const destinations = [
ExternalRoutingDestination.Colink,
ExternalRoutingDestination.Wisible,
];
const validator = getCreatePatientValidatorsFrom(destinations);
assertEquals(validator, [colinkValidator, wisibleValidator]);
});
Deno.test("getCreatePatientValidatorsFrom should return validators when given external destinations as array of int", () => {
const destinations: ExternalRoutingDestination[] = [
2,
3,
];
const validator = getCreatePatientValidatorsFrom(destinations);
assertEquals(validator, [colinkValidator, wisibleValidator]);
});
Deno.test("getCreatePatientValidatorFrom should return validator base on specified external destination when given existing external destination", () => {
const validator = getCreatePatientValidatorFrom(
ExternalRoutingDestination.Colink,
);
assertEquals(validator, colinkValidator);
});
|
be7de9618fac25536ba1fda150ab33176739c171
|
TypeScript
|
micheldpcarlos/angular-loader-service
|
/loader.service.ts
| 2.671875
| 3
|
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
@Injectable()
export class LoaderService {
//public subject that controls a personalized loader
public showLoader: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
//counter to control multi calls
private loaderCounter: number = 0;
constructor() {
}
/**
* Include +1 to loader counter
*/
public enable() {
this.loaderCounter++;
this.verifyLoader();
}
/**
* Remove 1 from loader counter
*/
public disable() {
this.loaderCounter--;
this.verifyLoader();
}
/**
* Reset loader conter to 0
*/
public reset() {
this.loaderCounter = 0;
this.verifyLoader();
}
/**
* Verify and emmit loader control subject
*/
private verifyLoader() {
const hasLoader = this.showLoader.getValue();
if (!hasLoader && this.loaderCounter > 0){
this.showLoader.next(true);
}
else if (hasLoader && this.loaderCounter == 0) {
this.showLoader.next(false);
}
}
}
|
a56f561b4dece8243c18b5aff7529fb9695f371a
|
TypeScript
|
romannovojilov/simple-todo-list
|
/src/redux/reducers/todoReducer.ts
| 2.953125
| 3
|
import { ITask, EditableTask, TaskFilterStatus } from "../../types/task";
import { TodoAction } from "../actions/todoActions";
import { CREATE_TASK, SET_EDITABLE_TASK, UPDATE_TASK, REMOVE_TASK, SET_FILTER } from "../types/todoTypes";
export type TodoState = {
list: ITask[],
editableTask: EditableTask,
filter: TaskFilterStatus
}
const initialState: TodoState = {
list: [],
editableTask: null,
filter: 0
}
export function todoReducer(state = initialState, action: TodoAction): TodoState {
switch (action.type) {
case CREATE_TASK:
const newTask: ITask = {
...action.payload,
id: Date.now()
};
return {
...state,
list: [...state.list, newTask]
};
case UPDATE_TASK:
return {
...state,
list: state.list.map(todo => {
if (todo.id === action.payload.id) return { ...action.payload };
return todo;
})
};
case REMOVE_TASK:
return {
...state,
list: state.list.filter(todo => todo.id !== action.payload)
};
case SET_EDITABLE_TASK:
if (action.payload) return { ...state, editableTask: state.list.find(todo => todo.id === action.payload) || null };
return { ...state, editableTask: null };
case SET_FILTER:
return {
...state,
filter: action.payload
};
default: return state;
}
}
|
02d36c9ce4f5e2228096ee1d2a7a625a4d0ad644
|
TypeScript
|
DanielMarcosFuella/OOPReview
|
/Repaso3.1.ts
| 2.859375
| 3
|
import {Mobile} from "./Repaso2"
export class MobileLibrary{
private name:string
private location:string
private mobiles:Mobile[]
private totalPrice: number
constructor(name:string,location:string,mobiles:Mobile[]){
this.name=name
this.location=location
this.mobiles=mobiles
this.totalPriceCalculation()
}
public GetName():string{
return this.name
}
public GetLocation():string{
return this.location
}
public Getmobiles():Mobile[]{
return this.mobiles
}
public SetName(newName:string){
this.name=newName
}
public SetLocation(newLocation:string){
this.location=newLocation
}
public SetMobiles(newMobiles:Mobile[]){
this.mobiles=newMobiles
}
private totalPriceCalculation():number{
this.totalPrice=0
for (let i=0;i<this.mobiles.length;i++){
this.totalPrice+=this.mobiles[i].GetPrice()
}
return this.totalPrice
}
public printLibrary():string{
let mensaje= "This is all my mobiles:" + "\n"
for(let i=0;i<this.mobiles.length;i++){
mensaje+= this.mobiles[i].toStrong()
}
mensaje+="Price overall: " + this.totalPrice
return mensaje
}
}
|
8c2bd68dae56e23cc68b8c08c3fedd9c7d790d0c
|
TypeScript
|
noel-yap/science-test-grading
|
/Grade.ts
| 3.03125
| 3
|
import {Numbers} from './Numbers';
import {Properties} from './Properties';
import {ScientificNotation} from './ScientificNotation';
import {SIParser} from './SIParser';
/**
* @param exactMatch True if exact match only (eg no partial credit).
* @param points Number of full-credit points.
* @param observed Cell or matrix of student answers.
* @param expected Array of cell or matrix of expected answers. A matrix row is treated as a lower-bound, the first element, and upper-bound, the last element, interval.
*
* @return Matrix of earned points along with rationales for points taken off.
**/
function grade(exactMatch: boolean, points: number, observed: any, expected: string[]): number {
const gradingProperties = Properties._getGradingProperties(SpreadsheetApp.getActiveSpreadsheet());
// expected becomes an array of the rest of the arguments
expected = Array.prototype.slice.call(arguments, 2);
console.log(`grade: expected = ${expected}`);
if (!Array.isArray(observed)) {
observed = [[observed]];
}
return observed.map((row: string[]): [number, string][] => {
return row.map((cell: string): [number, string] => {
return expected.map((e: string): [number, string] => {
try {
console.log(`grade: exactMatch = ${exactMatch}, points = ${points}, cell = ${cell}, e = ${e}`);
const gradeResult = Grade._grade(exactMatch, gradingProperties, points, cell, e);
console.log(`grade: points = ${points}, cell = ${cell}, e = ${e}, _grade = ${gradeResult}`);
return gradeResult;
} catch (e) {
return [0.0, `${e.fileName}:${e.lineNumber}:${e.toString()}`];
}
}).reduce((accum: [number, string], cellGradeVsExpected: [number, string]): [number, string] => {
const [maxGrade, maxGradeReason] = accum;
return (maxGradeReason === undefined || maxGradeReason.toString().indexOf('Error:') === 0 || cellGradeVsExpected[0] > maxGrade)
? cellGradeVsExpected
: accum;
}, [-points, undefined]);
});
}).reduce((accum: [number, string][], rowGrades: [number, string]): [number, string][] => {
return accum.concat(rowGrades);
}, []);
}
export module Grade {
/**
* If no magnitude:
* .75 of full credit off
* Else:
* If magnitude off by orders of magnitude:
* .3125 of full credit off
*
* If too few significant figures:
* .25 of full credit off
* Else if too many significant figures:
* .125 of full credit off
* Else if magnitude off within (0%, 1%]:
* .0625 of full credit off
* Else:
* .4375 of full credit off
*
* If no units:
* .25 of full credit off
* Else if incorrect units:
* .1875 of full credit off
**/
export function _grade(exactMatch: boolean, gradingProperties: object, points: number, observed: string, expected: string): [number, string] {
if (Array.isArray(expected[0])) {
expected = expected[0];
}
console.log(`_grade: observed = ${observed}, expected = ${expected}`);
if (observed === '' && expected !== '') {
return [0, ''];
} else if (exactMatch) {
return observed.toString().toLowerCase() !== expected.toString().toLowerCase()
? [0, 'Incorrect answer.']
: [points, ''];
}
const [
minExpectedNormalizedMagnitude,
minExpectedNormalizedUnits,
minExpectedSignificantFigures,
maxExpectedNormalizedMagnitude,
maxExpectedNormalizedUnits,
maxExpectedSignificantFigures] = (Array.isArray(expected)
? (): [number, string, number, number, string, number] => {
const minExpected = expected[0];
const maxExpected = expected[expected.length - 1];
console.log(`_grade: minExpected = ${minExpected}, maxExpected = ${maxExpected}`);
const minExpectedParts = Grade._getParts(minExpected);
const maxExpectedParts = Grade._getParts(maxExpected);
console.log(`_grade: minExpectedParts = ${minExpectedParts.toString(2)}, maxExpectedParts = ${maxExpectedParts.toString(2)}`);
return [
minExpectedParts.result.normalizedMagnitude,
minExpectedParts.result.normalizedUnits,
minExpectedParts.result.significantFigures,
maxExpectedParts.result.normalizedMagnitude,
maxExpectedParts.result.normalizedUnits,
maxExpectedParts.result.significantFigures];
}
: (): [number, string, number, number, string, number] => {
const expectedParts = Grade._getParts(expected);
return [
expectedParts.result.normalizedMagnitude,
expectedParts.result.normalizedUnits,
expectedParts.result.significantFigures,
expectedParts.result.normalizedMagnitude,
expectedParts.result.normalizedUnits,
expectedParts.result.significantFigures];
})();
const observedParts = Grade._getParts(observed);
const observedNormalizedMagnitude = observedParts.result.normalizedMagnitude;
const observedNormalizedUnits = observedParts.result.normalizedUnits;
const observedSignificantFigures = observedParts.result.significantFigures;
if (minExpectedNormalizedUnits !== maxExpectedNormalizedUnits) {
throw new Error(`Normalized expected units must be the same but were '${minExpectedNormalizedUnits}' and '${maxExpectedNormalizedUnits}'.`);
}
const expectedNormalizedUnits = minExpectedNormalizedUnits;
const closestExpectedNormalizedMagnitude = Math.abs(observedNormalizedMagnitude - minExpectedNormalizedMagnitude) < Math.abs(observedNormalizedMagnitude - maxExpectedNormalizedMagnitude)
? minExpectedNormalizedMagnitude
: maxExpectedNormalizedMagnitude;
const minExpectedNormalizedOrderOfMagnitude = Numbers._orderOfMagnitude(minExpectedNormalizedMagnitude);
const maxExpectedNormalizedOrderOfMagnitude = Numbers._orderOfMagnitude(maxExpectedNormalizedMagnitude);
const observedNormalizedOrderOfMagnitude = Numbers._orderOfMagnitude(observedNormalizedMagnitude);
const minExpectedNormalizedMagnitudeAdjusted = Grade._adjustOrderOfMagnitude(minExpectedNormalizedMagnitude, minExpectedNormalizedOrderOfMagnitude);
const maxExpectedNormalizedMagnitudeAdjusted = Grade._adjustOrderOfMagnitude(maxExpectedNormalizedMagnitude, maxExpectedNormalizedOrderOfMagnitude);
const observedNormalizedMagnitudeAdjusted = Grade._adjustOrderOfMagnitude(observedNormalizedMagnitude, observedNormalizedOrderOfMagnitude);
const closestExpectedNormalizedMagnitudeAdjusted = Math.abs(observedNormalizedMagnitudeAdjusted - minExpectedNormalizedMagnitudeAdjusted) < Math.abs(observedNormalizedMagnitudeAdjusted - maxExpectedNormalizedMagnitudeAdjusted)
? minExpectedNormalizedMagnitudeAdjusted
: maxExpectedNormalizedMagnitudeAdjusted;
const expectedSignificantFigures = maxExpectedSignificantFigures > minExpectedSignificantFigures
? maxExpectedSignificantFigures
: minExpectedSignificantFigures;
const significantFiguresCmp = observedSignificantFigures < expectedSignificantFigures
? -1
: observedSignificantFigures > expectedSignificantFigures
? 1
: 0;
console.log(`_grade: expected = ${expected}`);
console.log(`_grade: observed = ${observed}`);
console.log(`_grade: minExpectedNormalizedMagnitude = ${minExpectedNormalizedMagnitude}`);
console.log(`_grade: maxExpectedNormalizedMagnitude = ${maxExpectedNormalizedMagnitude}`);
console.log(`_grade: closestExpectedNormalizedMagnitude = ${closestExpectedNormalizedMagnitude}`);
console.log(`_grade: observedNormalizedMagnitude = ${observedNormalizedMagnitude}`);
console.log(`_grade: minExpectedNormalizedOrderOfMagnitude = ${minExpectedNormalizedOrderOfMagnitude}`);
console.log(`_grade: maxExpectedNormalizedOrderOfMagnitude = ${maxExpectedNormalizedOrderOfMagnitude}`);
console.log(`_grade: observedNormalizedOrderOfMagnitude = ${observedNormalizedOrderOfMagnitude}`);
console.log(`_grade: minExpectedNormalizedMagnitudeAdjusted = ${minExpectedNormalizedMagnitudeAdjusted}`);
console.log(`_grade: maxExpectedNormalizedMagnitudeAdjusted = ${maxExpectedNormalizedMagnitudeAdjusted}`);
console.log(`_grade: closestExpectedNormalizedMagnitudeAdjusted = ${closestExpectedNormalizedMagnitudeAdjusted}`);
console.log(`_grade: observedNormalizedMagnitudeAdjusted = ${observedNormalizedMagnitudeAdjusted}`);
console.log(`_grade: minExpectedSignificantFigures = ${minExpectedSignificantFigures}`);
console.log(`_grade: maxExpectedSignificantFigures = ${maxExpectedSignificantFigures}`);
console.log(`_grade: expectedSignificantFigures = ${expectedSignificantFigures}`);
console.log(`_grade: observedSignificantFigures = ${observedSignificantFigures}`);
console.log(`_grade: significantFiguresCmp = ${significantFiguresCmp}`);
console.log(`_grade: minExpectedNormalizedUnits = ${minExpectedNormalizedUnits}`);
console.log(`_grade: maxExpectedNormalizedUnits = ${maxExpectedNormalizedUnits}`);
console.log(`_grade: expectedNormalizedUnits = ${expectedNormalizedUnits}`);
console.log(`_grade: observedNormalizedUnits = ${observedNormalizedUnits}`);
const correctOrderOfMagnitude = minExpectedNormalizedOrderOfMagnitude <= observedNormalizedOrderOfMagnitude && observedNormalizedOrderOfMagnitude <= maxExpectedNormalizedOrderOfMagnitude;
const withinAdjustedExpectedRange = minExpectedNormalizedMagnitudeAdjusted <= observedNormalizedMagnitudeAdjusted && observedNormalizedMagnitudeAdjusted <= maxExpectedNormalizedMagnitudeAdjusted;
const closeToAdjustedExpected = Math.abs(observedNormalizedMagnitudeAdjusted - closestExpectedNormalizedMagnitudeAdjusted) / closestExpectedNormalizedMagnitudeAdjusted < .01;
console.log(`_grade: correctOrderOfMagnitude = ${correctOrderOfMagnitude}`);
console.log(`_grade: withinAdjustedExpectedRange = ${withinAdjustedExpectedRange}`);
console.log(`_grade: closeToAdjustedExpected = ${closeToAdjustedExpected}`);
const magnitudePortion = gradingProperties['magnitude-portion'];
const magnitudeCredit = Numbers._isNaN(observedNormalizedMagnitude)
? [[gradingProperties['missing-magnitude'], 'No magnitude.']]
: ((correctOrderOfMagnitude
? [[0.0, undefined]]
: [[gradingProperties['incorrect-order-of-magnitude'], 'Incorrect order of magnitude.']])
.concat(withinAdjustedExpectedRange
? (significantFiguresCmp < 0
? [[gradingProperties['too-few-significant-figures'], 'Too few significant figures.']]
: significantFiguresCmp > 0
? [[gradingProperties['too-many-significant-figures'], 'Too many significant figures.']]
: [[0.0, undefined]])
: closeToAdjustedExpected
? [[gradingProperties['order-adjusted-magnitude-off-by-less-than-one-percent'], 'Magnitude close but not exactly correct.']]
: [[gradingProperties['order-adjusted-magnitude-off-by-more-than-one-percent'], 'Incorrect order-of-magnitude-adjusted magnitude.']]));
const unitsPortion = gradingProperties['units-portion'];
const unitsCredit = observedNormalizedUnits === '' && expectedNormalizedUnits !== ''
? [[gradingProperties['missing-units'], 'No units.']]
: observedNormalizedUnits !== expectedNormalizedUnits
? [[gradingProperties['incorrect-units'], 'Incorrect units.']]
: [[0.0, undefined]];
console.log(`_grade: magnitudeCredit = ${magnitudeCredit}`);
console.log(`_grade: unitsCredit = ${unitsCredit}`);
const noExpectedMagnitude = Numbers._isNaN(minExpectedNormalizedMagnitudeAdjusted) && Numbers._isNaN(maxExpectedNormalizedMagnitudeAdjusted);
const noExpectedUnits = expectedNormalizedUnits === '';
const result = []
.concat(noExpectedMagnitude ? [] : magnitudeCredit)
.concat(noExpectedUnits ? [] : unitsCredit)
.filter((elt: [number, string][]): boolean => {
return elt[1] !== undefined;
}).reduce((accum: [number, string], elt: [number, string]): [number, string] => {
return [accum[0] + elt[0], [accum[1], elt[1]].join(' ')];
}, [0.0, '']);
console.log(`_grade: result = ${result}`);
result[0] = points *
(1 - result[0] / (noExpectedMagnitude ? unitsPortion : 1) / (noExpectedUnits ? magnitudePortion : 1));
result[1] = result[1].trim();
return result;
}
export function _getParts(expression: string): SIParser.Result {
try {
return SIParser._normalizeUnits(expression)
.andThen((normalizeExpressionResult: SIParser.Result) => {
const magnitudeProvided = '0' <= expression.charAt(0) && expression.charAt(0) <= '9' || expression.charAt(0) === '.';
const normalizedMagnitude = magnitudeProvided
? ScientificNotation._sciToNum((<SIParser.SuccessResult>normalizeExpressionResult).result.magnitude)
: NaN;
const normalizedUnits = (<SIParser.SuccessResult>normalizeExpressionResult).result.units;
const significantFigures = magnitudeProvided
? Numbers._numberOfSignificantFigures(expression)
: NaN;
console.log(`_getParts: normalizedMagnitude = ${normalizedMagnitude}`);
console.log(`_getParts: normalizedUnits = ${normalizedUnits}`);
console.log(`_getParts: significantFigures = ${significantFigures}`);
return Object.assign(normalizeExpressionResult, {
result: {
significantFigures: significantFigures,
normalizedMagnitude: normalizedMagnitude,
normalizedUnits: normalizedUnits
}
});
})
.orElse((normalizeExpressionResult: SIParser.Result): SIParser.Result => {
throw new Error(`Unable to parse after '${normalizeExpressionResult.consumed}' in '${expression}'. Non-metric units might be being used.`);
});
} catch (e) {
if (e.message.indexOf('must be of type string') !== -1) {
throw new Error(`${expression}' must be entered in as text (ie by starting it with \`'\`)`);
} else {
throw e;
}
}
}
export function _adjustOrderOfMagnitude(input: number, adjustBy: number): number {
const numberOfSignificantFigures = Numbers._numberOfSignificantFigures(input.toString());
const orderOfMagnitude = Numbers._orderOfMagnitude(input);
console.log(`_adjustOrderOfMagnitude: adjustBy = ${adjustBy}, numberOfSignificantFigures = ${numberOfSignificantFigures}, orderOfMagnitude = ${orderOfMagnitude}`);
return Numbers._round(input * Math.pow(10, -adjustBy), -adjustBy - (numberOfSignificantFigures - orderOfMagnitude));
}
}
|
766d025b3299f93753384b2eb535771010b9d410
|
TypeScript
|
lucas-242/Round-Robin
|
/without-interruptions/roundRobin.ts
| 3.5625
| 4
|
/**Classe utilizada para definir os Processos */
class Process {
/**Nome do processo */
name: string;
/**Quantum necessário para a conclusão do processo */
quantum: number;
/**Prioridade do processo
* 0- Alta prioridade
* 1- Média prioridade
* 2- Baixa prioridade
*/
priority: number;
constructor(name: string, quantum: number, priority: number) {
this.name = name;
this.quantum = quantum;
this.priority = priority
}
}
/**Classe de ações utilizadas pelo algoritmo */
class Actions {
/**Total gasto pelo sistema para executar os processos*/
totalTime = 0;
/**
* Move um processo para a fila
* @param row Fila para qual o processo será movido
* @param process Processo que será movido para a fila
*/
moveToRow(row: Array<Process>, process: Process): void {
row.push(process);
}
/**
* Remove o primeiro elemento da fila
* @param row Fila da qual o processo será removido
*/
removeRow(row: Array<Process>): Process {
return row.splice(0, 1)[0];
}
/**
* Executa o primeiro processo da fila de executando
*/
resolveProcess(): number {
let process = EXECUTING_ROW[0];
console.log("Processo, " + process.name + " sendo executado");
this.setTimeToExecute(TIME_TO_EXECUTE);
let timeToFinish = process.quantum - QUANTUM;
//Se executou o processo completamente
if (timeToFinish <= 0) {
this.totalTime += process.quantum;
process.quantum = 0;
return process.quantum;
}
process.quantum = timeToFinish;
this.totalTime += QUANTUM;
return timeToFinish;
}
/**
* Verifica se existe algum processo na fila de espera
*/
verifyAwaitRow(): boolean {
if (AWAIT_ROW.length > 0)
return true;
return false;
}
/**
* Executa uma troca de contexto
*/
changeContext(): void {
this.totalTime += CONTEXT_CHANGE;
}
/**
* Compara dois processo, retornando true caso sejam iguais
* @param process Processo que foi removido da fila de espera
* @param resultProcess Processo que estava sendo executado anteriormente
*/
compareProcesses(process: Process, resultProcess: Process): boolean {
if (resultProcess.name != process.name)
return false;
return true;
}
/**
* Cria um espaço de tempo para simular a execução de um processo
* @param ms Tempo de execução em milisegundos
*/
setTimeToExecute(ms: number) {
let start = Date.now();
let countInterruption = 0;
while (true) {
let clock = (Date.now() - start);
if (clock >= ms)
break;
}
}
/**
* Resolve um processo, verifica se o processo terminou e move para uma determinada fila
* @param resultProcess Instância do processo
*/
execute(resultProcess: Process) {
if (this.resolveProcess() == 0) {
//Caso o processo tenha terminado
resultProcess = this.removeRow(EXECUTING_ROW);
this.moveToRow(READY_ROW, resultProcess);
console.log("Processo " + resultProcess.name + " finalizado e movido para a fila de prontos");
} else {
//Caso o processo não tenha terminado
resultProcess = this.removeRow(EXECUTING_ROW);
this.moveToRow(AWAIT_ROW, resultProcess);
console.log("Processo " + resultProcess.name + " parado e movido para a fila de espera");
}
}
}
/**Quantum máximo gasto por cada processo antes de um troca de contexto*/
const QUANTUM = 2;
/**Quantum gasto pela troca de contexto */
const CONTEXT_CHANGE = 1;
/**Tempo de execução de cada função em milisegundos */
const TIME_TO_EXECUTE = 2000;
/**Processo do teclado */
const KEYBOARD = new Process("keyboard", 5, 1);
/**Processo do monitor */
const MONITOR = new Process("monitor", 8, 0);
/**Processo da rede de comunicação tx */
const COMMUNICATION_TX = new Process("TX communication", 15, 2);
/**Processo da rede de comunicação rx */
const COMMUNICATION_RX = new Process("RX communication", 14, 2);
/**Fila de processos prontos */
const READY_ROW = new Array<Process>();
/**Fila de processos em execução */
const EXECUTING_ROW = new Array<Process>();
/**Fila de processos em espera */
const AWAIT_ROW = new Array<Process>();
/**Instância das ações */
let actions = new Actions();
function Main() {
//Insere na fila de espera
actions.moveToRow(AWAIT_ROW, KEYBOARD);
actions.moveToRow(AWAIT_ROW, MONITOR);
actions.moveToRow(AWAIT_ROW, COMMUNICATION_TX);
actions.moveToRow(AWAIT_ROW, COMMUNICATION_RX);
//Variáveis auxiliares
let process = new Process("", 0, 0);
let resultProcess = new Process("", 0, 0);
//Executa enquanto houver processo na fila de espera
while (actions.verifyAwaitRow()) {
//Remove da fila de Espera e move para fila de execução
process = actions.removeRow(AWAIT_ROW);
actions.moveToRow(EXECUTING_ROW, process);
console.log("Processo " + process.name + " entrou na fila de execução");
//Troca de contexto caso o processo anterior não tenha sido executado
//e seja o único na fila
if (!actions.compareProcesses(process, resultProcess)) {
actions.changeContext();
console.log("Troca de contexto realizada");
}
//Executa um processo e verifica para qual fila irá mandar o processo
actions.execute(resultProcess);
}
console.log("Quantum gasto pelo sistema: " + actions.totalTime);
return '';
}
document.body.innerHTML = Main();
|
bde6a1f428a65219a0fcae63b5b1d73e1ef655a8
|
TypeScript
|
maximopeoficiales/NODETS-CRUD
|
/src/models/Book.ts
| 2.703125
| 3
|
import mongosse, { Schema, model } from "mongoose";
//interfaz para validar los datos
export interface Book extends mongosse.Document {
title: string;
author: string;
isbn: string;
}
//esquema base
const BookSchema = new Schema({
title: String,
author: String,
isbn: String,
});
export default model<Book>("Book", BookSchema);
|
fef97ad8bdf5e5aa95d1e8ad7eb07fb421e2f8e6
|
TypeScript
|
Jumpaku/AsyncResult
|
/dist/Result.d.ts
| 2.953125
| 3
|
import { BaseError } from "make-error-cause";
import { AsyncResult } from "./AsyncResult";
export declare class ResultError<E> extends BaseError {
readonly name: string;
readonly detail: E;
constructor(error: E);
}
interface ResultTry {
<V>(tryFun: () => V): Result<V, unknown>;
<V, E>(tryFun: () => V, catchFun: (error: unknown) => E): Result<V, E>;
}
export declare const Result: {
success: <V>(value: V) => Result<V, never>;
failure: <E>(error: E) => Result<never, E>;
try: ResultTry;
isResult: <V, E>(obj: unknown) => obj is Result<V, E>;
};
declare abstract class AbstractResult<V, E> {
private assertsThisIsResult;
abstract isSuccess(): this is Success<V, E>;
abstract isFailure(): this is Failure<V, E>;
match<X, Y>(onSuccess: (value: V) => X, onFailure: (error: E) => Y): X | Y;
orDefault(value: V): V;
orRecover(f: (error: E) => V): V;
orThrow<F>(f?: (e: E) => F): V;
orNull(): V | null;
orUndefined(): V | undefined;
onSuccess(f: (value: V) => void): Result<V, E>;
onFailure(f: (error: E) => void): Result<V, E>;
and<U, F>(other: Result<U, F>): Result<V | U, E | F>;
or<U, F>(other: Result<U, F>): Result<V | U, E | F>;
map<U>(neverThrowFun: (value: V) => U): Result<U, E>;
mapAsync<U>(tryFun: (value: V) => U | Promise<U>): AsyncResult<U, unknown>;
mapAsync<U, F>(tryFun: (value: V) => U | Promise<U>, catchFun: (error: unknown) => F): AsyncResult<U, F>;
tryMap<U>(tryFun: (value: V) => U): Result<U, unknown>;
tryMap<U, F>(tryFun: (value: V) => U, catchFun: (error: unknown) => F): Result<U, E | F>;
flatMap<U, F>(neverThrowFun: (value: V) => Result<U, F>): Result<U, E | F>;
flatMapAsync<U, F>(tryFun: (value: V) => Result<U, F> | AsyncResult<U, F>): AsyncResult<U, unknown>;
flatMapAsync<U, F, G>(tryFun: (value: V) => Result<U, F> | AsyncResult<U, F>, catchFun: (error: unknown) => G): AsyncResult<U, E | F | G>;
tryFlatMap<U, F>(tryFun: (value: V) => Result<U, F>): Result<U, unknown>;
tryFlatMap<U, F, G>(tryFun: (value: V) => Result<U, F>, catchFun: (error: unknown) => G): Result<U, E | F | G>;
recover(neverThrowFun: (error: E) => V): Result<V, never>;
recoverAsync<F>(tryFun: (error: E) => V | Promise<V>): AsyncResult<V, unknown>;
recoverAsync<F>(tryFun: (error: E) => V | Promise<V>, catchFun: (error: unknown) => F): AsyncResult<V, F>;
tryRecover(tryFun: (error: E) => V): Result<V, unknown>;
tryRecover<F>(tryFun: (error: E) => V, catchFun: (error: unknown) => F): Result<V, F>;
flatRecover<F>(neverThrowFun: (error: E) => Result<V, F>): Result<V, F>;
flatRecoverAsync<F>(tryFun: (error: E) => Result<V, F> | AsyncResult<V, F>): AsyncResult<V, unknown>;
flatRecoverAsync<F, G>(tryFun: (error: E) => Result<V, F> | AsyncResult<V, F>, catchFun: (error: unknown) => G): AsyncResult<V, F | G>;
tryFlatRecover<F>(tryFun: (error: E) => Result<V, F>): Result<V, unknown>;
tryFlatRecover<F, G>(tryFun: (error: E) => Result<V, F>, catchFun: (error: unknown) => G): Result<V, F | G>;
mapError<F>(neverThrowFun: (error: E) => F): Result<V, F>;
tryMapError<F>(tryFun: (error: E) => F): Result<V, unknown>;
tryMapError<F, G>(tryFun: (error: E) => F, catchFun: (error: unknown) => G): Result<V, F | G>;
}
export declare class Success<V, E> extends AbstractResult<V, E> {
readonly value: V;
constructor(value: V);
readonly error: undefined;
isSuccess(): this is Success<V, E>;
isFailure(): this is Failure<V, E>;
castError<F>(): Success<V, F>;
}
export declare class Failure<V, E> extends AbstractResult<V, E> {
readonly error: E;
constructor(error: E);
readonly value: undefined;
isSuccess(): this is Success<V, E>;
isFailure(): this is Failure<V, E>;
castValue<U>(): Failure<U, E>;
}
export declare type Result<V, E> = Success<V, E> | Failure<V, E>;
export {};
|
ac358a5895e63c32064632688da05e5ec21698b6
|
TypeScript
|
davidruiz120/proyectoIonicPMDMulti
|
/src/app/services/garage.service.ts
| 2.734375
| 3
|
import { Vehiculo } from './../model/Vehiculo';
import { environment } from './../../environments/environment';
import { Injectable } from '@angular/core';
import { AngularFirestoreCollection, AngularFirestore } from 'angularfire2/firestore';
import { Observable, Subscription, interval } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class GarageService {
myCollection: AngularFirestoreCollection;
constructor(private fireStore: AngularFirestore) {
this.myCollection = fireStore.collection<any>(environment.collection);
}
/**
* Función que recoge todos los datos de la colección
* previamente establecido en el constructor
*/
readGARAGE():Observable<firebase.firestore.QuerySnapshot>{
return this.myCollection.get();
}
/**
* Función que recoge todos los datos de la colección,
* pero devolviendo un observable con el array de los
* objetos
*
* @param timer
*/
readGARAGE2(timer:number=10000):Observable<Vehiculo[]>{
return new Observable((observer)=>{
//observer.next() para devolver un valor
//observer.error() para devolver un error
//observer.complete() para cortar?
let subscripcion:Subscription;
let tempo = setTimeout(()=>{
subscripcion.unsubscribe();
observer.error("Timeout");
}, timer);
subscripcion = this.readGARAGE().subscribe((lista)=>{
clearTimeout(tempo);
let listado = [];
lista.docs.forEach((vehiculo)=>{
listado.push({id:vehiculo.id,...vehiculo.data()}); // Concatena dos cosas para unirlas en una
})
observer.next(listado);
observer.complete();
})
});
}
/**
* Función que recoge el registro según un identificador
* en específico
*
* @param id Identificador que se utilizará para la búsqueda
*/
readGARAGEByID(id:string):Observable<firebase.firestore.DocumentSnapshot>{
return this.myCollection.doc(id).get();
}
/**
* Función que se encarga de insertar un nuevo
* registro en Firebase
*
* @param nuevovehiculo Objeto que se insertará en Firebase
*/
addGARAGE(nuevovehiculo:Vehiculo):Promise<firebase.firestore.DocumentReference>{
return this.myCollection.add(nuevovehiculo);
}
/**
* Función que se encarga de obtener un registro con su
* identificador y actualizarlo con los nuevos datos
*
* @param id Identificador del registro
* @param data El objeto con los nuevos datos
*/
updateGARAGE(id:string, data:Vehiculo):Promise<void>{
return this.myCollection.doc(id).set(data);
}
/**
* Función que se encarga de eliminar un registro
* según un identificador en específico
*
* @param id Identificador del registro
*/
deleteGARAGE(id:string):Promise<void>{
return this.myCollection.doc(id).delete();
}
}
|
a88246ed2ba08606a359574768c2d9f35d6dd308
|
TypeScript
|
my-open-source-pkg/open-source-tpl
|
/src/index.ts
| 3
| 3
|
function greeter (person: string) {
return 'Hello3, ' + person
}
const user = [0, 1, 2]
console.log(user, greeter('Lyman'))
|
c5c343a138d837c506fbfe22f3890f1a790a94b7
|
TypeScript
|
Amend-Health/loop-development-kit
|
/ldk/javascript/src/whisper/index.ts
| 2.796875
| 3
|
import { mapToExternalWhisper, mapToInternalWhisper } from './mapper';
import { NewWhisper, Whisper } from './types';
export * from './types';
/**
* Whisper aptitude provides the ability to create a whisper.
*/
export interface WhisperAptitude {
/**
* Adds a new whisper to Olive Helps based on the configuration provided.
* Returns a promise which provides a reference to the newly created whisper
*
* @param whisper The configuration for the whisper being created
*/
create(whisper: NewWhisper): Promise<Whisper>;
}
export function create(whisper: NewWhisper): Promise<Whisper> {
const stateMap = new Map();
return new Promise((resolve, reject) => {
try {
oliveHelps.whisper.create(
mapToInternalWhisper(whisper, stateMap),
(error: Error | undefined, internalWhisper: WhisperService.Whisper) => {
if (error) {
reject(error);
}
resolve(mapToExternalWhisper(internalWhisper, stateMap));
},
);
} catch (e) {
reject(e);
}
});
}
|
384923e2ccc1846e95a60f400605c048e7ad3295
|
TypeScript
|
morecchia/discogs-angular2-app
|
/client/app/reducers/release.ts
| 2.90625
| 3
|
import { DiscogsItem, DiscogsRelease } from '../models';
import * as release from '../actions/release';
import * as collection from '../actions/collection';
export interface State {
loaded: boolean;
loading: boolean;
id: number | null;
entity: DiscogsRelease;
};
const initialState: State = {
loaded: false,
loading: false,
id: null,
entity: null,
};
export function reducer(state = initialState, action: release.Actions): State {
switch (action.type) {
case release.ActionTypes.LOAD: {
return {
loaded: false,
loading: true,
id: action.payload,
entity: null,
};
}
case release.ActionTypes.LOAD_COMPLETE: {
const release = action.payload;
return {
loaded: true,
loading: false,
id: release.id,
entity: release,
};
}
default: {
return state;
}
}
}
/**
* Because the data structure is defined within the reducer it is optimal to
* locate our selector functions at this level. If store is to be thought of
* as a database, and reducers the tables, selectors can be considered the
* queries into said database. Remember to keep your selectors small and
* focused so they can be combined and composed to fit each particular
* use-case.
*/
export const getLoaded = (state: State) => state.loaded;
export const getLoading = (state: State) => state.loading;
export const getReleaseEntity = (state: State) => state.entity;
export const getReleaseId = (state: State) => state.id;
|
20fdf5904209b0093c0636c20bf9af1d9fb1b37e
|
TypeScript
|
DoLopes/clean-node-api
|
/Src/Shared/Lib/StrictMonapt/Some.ts
| 2.578125
| 3
|
import { Option } from "Shared/Lib/StrictMonapt/Option";
export class Some<A> extends Option<A> {
public get(): A {
return this.option.get();
}
}
|
2fb087f117bdd5aa2c9f272a2795982aa8e30917
|
TypeScript
|
Jvvillasb/ds-sales
|
/front-web/src/core/utils/types.ts
| 2.75
| 3
|
export type Gender = 'MALE' | 'FEMALE' | 'OTHER';
export type SalesByDate = {
date: string;
sum: number;
};
export type ChartSeriesData = {
x: string;
y: number;
};
export type FilterData = {
dates?: Date[];
gender?: Gender;
};
export type SalesSummaryData = {
sum?: number;
min: number;
max: number;
avg: number;
count: number;
};
export type SalesByStore = {
storeName: string;
sum: number;
};
export type SalesByPaymentMethod = {
description: string;
sum: number;
};
export type PieChartConfig = {
labels: string[];
series: number[];
};
export type SalesResponse = {
content: Sale[];
};
export type Sale = {
id: number;
date: string;
volume: number;
total: number;
gender: Gender;
categoryName: string;
paymentMethod: string;
storeName: string;
};
|
cd4c1aa37e239fe8c33891498e5b8f3a4bdce4ba
|
TypeScript
|
MauricioLudwig/philippides-server
|
/src/utils/message.ts
| 2.90625
| 3
|
import { v4 as uuid } from 'uuid';
import { IMessage } from './definitions';
export class Message {
id: string;
created: number;
constructor() {
this.id = uuid();
this.created = this.getTimestamp();
}
new(user: string, text: string): IMessage {
return {
id: this.id,
admin: false,
user,
text,
created: this.created,
};
}
userConnected(user: string): IMessage {
return {
id: this.id,
admin: true,
user: null,
text: `${user} connected to the chat. Say hello!`,
created: this.created,
};
}
userInactive(user: string): IMessage {
return {
id: this.id,
admin: true,
user: null,
text: `${user} was disconnected due to inactivity.`,
created: this.created,
};
}
userDisconnected(user: string): IMessage {
return {
id: this.id,
admin: true,
user: null,
text: `${user} left the chat, connection lost.`,
created: this.created,
};
}
private getTimestamp(): number {
return new Date().getTime();
}
}
|
d713f1596fedabf94421deb74faf63a087187798
|
TypeScript
|
ManiukIvan/ui-diploma
|
/src/app/components/signup/signup.component.ts
| 2.75
| 3
|
import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {
message: any;
registerForm: FormGroup;
hidePassword: boolean;
hideConfirmPassword: boolean;
constructor() {
this.registerForm = new FormGroup({
login: new FormControl('', [ Validators.required, Validators.email]),
firstName: new FormControl('', [ Validators.required, Validators.maxLength(25)]),
lastName: new FormControl('', [ Validators.required, Validators.maxLength(25)]),
password: new FormControl('', [ Validators.required, Validators.minLength(6), Validators.maxLength(25),
Validators.pattern('^[\\w]*$')]),
confirmPassword: new FormControl('', [ Validators.required, Validators.minLength(6), Validators.maxLength(25)]),
}, MustMatch('password', 'confirmPassword')
);
this.hidePassword = true;
this.hideConfirmPassword = true;
}
ngOnInit(): void {
}
public registerNow(): void {
// clear field
this.message = null;
}
changeHidePasswordValue(): void {
this.hidePassword = !this.hidePassword;
}
changeHideConfirmPasswordValue(): void {
this.hideConfirmPassword = !this.hideConfirmPassword;
}
}
// return null or set error if passwords don't match
function MustMatch(controlName: string, matchingControlName: string): any {
// @ts-ignore
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return null;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
};
}
|
2eab1a7bc5e351c7d07e70fec47f0899895f5298
|
TypeScript
|
martinavesela/bachelors
|
/src/store.ts
| 3.125
| 3
|
import {configureStore} from '@reduxjs/toolkit'
export interface State {
userId: number
userName: string
}
const initialState: State = {
userId: 0,
userName: ""
}
export const appReducer = (state: State = initialState, action: any) => {
switch (action.type) {
case "setUserId":
return {...state, userId: action.payload}
case "setUserName":
return {...state, userName: action.payload}
default:
return state
}
}
export function setUserId(id: number) {
return {
type: "setUserId",
payload: id
}
}
export function setUserName(name: string) {
return {
type: "setUserName",
payload: name
}
}
export const store = configureStore({
reducer: appReducer
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
|
5f156a42816e8f28fabf713e12a8067230301a51
|
TypeScript
|
acsl2r/acsl2r
|
/acsl2r/src/component/acslscript/pulseexpression.ts
| 2.734375
| 3
|
import { AcslType, Prec } from '../../enum';
import { IExpression } from '../../interface';
import { applyAcslTypesToExpression } from './objectmodel';
import { ExpressionBase } from './expressionbase';
export default class PulseExpression extends ExpressionBase
{
constructor(tz: IExpression, p: IExpression, w: IExpression)
{
super();
this.set("tz", tz);
this.set("p", p);
this.set("w", w);
}
toCode(lang: string, prec: Prec): string
{
return "pulse(t, " + this.get("tz").toCode("R", Prec.Pulse) + ", " + this.get("p").toCode("R", Prec.Pulse) + ", " + this.get("w").toCode("R", Prec.Pulse) + ")";
}
get symbols()
{
return this.get("tz").symbols.concat(this.get("p").symbols, this.get("w").symbols);
}
applyAcslTypes(typeDictionary: Map<string, AcslType>)
{
let replacement = applyAcslTypesToExpression(this.get("tz"), typeDictionary);
if (!!replacement) this.set("tz", replacement);
replacement = applyAcslTypesToExpression(this.get("p"), typeDictionary);
if (!!replacement) this.set("p", replacement);
replacement = applyAcslTypesToExpression(this.get("w"), typeDictionary);
if (!!replacement) this.set("w", replacement);
}
clone()
{
let expression = new PulseExpression(null, null, null);
expression.cloneExpressionsFrom(this);
return expression;
}
}
|
ea2f5c48174ed846d5f61768630b8c4d69681362
|
TypeScript
|
DakotaLarson/BattleTanks-Client
|
/src/DomEventHandler.ts
| 3.15625
| 3
|
type eventCallback = (data?: any) => any;
export default class DomEventHandler {
private static listeners: Map<any, eventCallback> = new Map();
public static addListener(context: any, obj: HTMLElement | WebSocket, event: string, callback: eventCallback, options?: AddEventListenerOptions) {
const listenerKey = {
context,
obj,
event,
callback,
};
if (!DomEventHandler.listeners.has(listenerKey)) {
const boundCallback = callback.bind(context);
obj.addEventListener(event, boundCallback, options);
this.listeners.set(listenerKey, boundCallback);
}
}
public static removeListener(context: any, obj: HTMLElement | WebSocket, event: string, callback: eventCallback, options?: AddEventListenerOptions) {
const listenerKey = {
context,
obj,
event,
callback,
};
const key = DomEventHandler.getListener(listenerKey);
if (key) {
const boundCallback = this.listeners.get(key);
obj.removeEventListener(event, boundCallback!, options);
this.listeners.delete(key);
} else {
console.warn("Attempt to remove DOM event listener was unsuccessful.");
}
}
private static getListener(listenerKey: any) {
const keys = this.listeners.keys();
let next = keys.next();
while (!next.done) {
const key = next.value;
if (key.context === listenerKey.context && key.obj === listenerKey.obj && key.event === listenerKey.event && key.callback === listenerKey.callback) {
return key;
}
next = keys.next();
}
return undefined;
}
}
|
29ab09d2c3ee2652cd8d31589c948999a3371210
|
TypeScript
|
date-fns/date-fns
|
/src/getWeekOfMonth/index.ts
| 3.515625
| 4
|
import getDate from '../getDate/index'
import getDay from '../getDay/index'
import startOfMonth from '../startOfMonth/index'
import type { LocaleOptions, WeekStartOptions } from '../types'
import { getDefaultOptions } from '../_lib/defaultOptions/index'
/**
* The {@link getWeekOfMonth} function options.
*/
export interface GetWeekOfMonthOptions
extends LocaleOptions,
WeekStartOptions {}
/**
* @name getWeekOfMonth
* @category Week Helpers
* @summary Get the week of the month of the given date.
*
* @description
* Get the week of the month of the given date.
*
* @param date - the given date
* @param options - an object with options.
* @returns the week of month
*
* @example
* // Which week of the month is 9 November 2017?
* const result = getWeekOfMonth(new Date(2017, 10, 9))
* //=> 2
*/
export default function getWeekOfMonth<DateType extends Date>(
date: DateType | number,
options?: GetWeekOfMonthOptions
): number {
const defaultOptions = getDefaultOptions()
const weekStartsOn =
options?.weekStartsOn ??
options?.locale?.options?.weekStartsOn ??
defaultOptions.weekStartsOn ??
defaultOptions.locale?.options?.weekStartsOn ??
0
const currentDayOfMonth = getDate(date)
if (isNaN(currentDayOfMonth)) return NaN
const startWeekDay = getDay(startOfMonth(date))
let lastDayOfFirstWeek = weekStartsOn - startWeekDay
if (lastDayOfFirstWeek <= 0) lastDayOfFirstWeek += 7
const remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek
return Math.ceil(remainingDaysAfterFirstWeek / 7) + 1
}
|
602df15145930c35c4fad588195d23100108984e
|
TypeScript
|
bal200/Space-Taxi
|
/src/dashboard.ts
| 2.765625
| 3
|
import { Person } from './person';
import { SpaceTaxiGame } from './app';
export interface Slot {
p: Person,
text?: Phaser.GameObjects.Text,
}
export class Dashboard extends Phaser.Scene {
info :Phaser.GameObjects.Text;
game: SpaceTaxiGame;
slots: Slot[] = [];
constructor( config ) {
super(config);
}
init() {
const h = this.cameras.main.height;
const w = this.cameras.main.width;
this.info = this.add.text(10, h - 25, 'Text', { font: '24px Arial Bold', fill: '#FBFBAC' });
this.info.setScrollFactor(0);
}
preload(): void {}
create(): void {}
public pickUp( p: Person ) {
//this.info.destroy();
let slotNo = this.getFreeSlot();
let slot:Slot = this.slots[slotNo] = {p:p};
const w = this.cameras.main.width;
const h = this.cameras.main.height;
const x = w - (210 * (slotNo+1));
slot.text = this.add.text(x, h - 25, 'Passenger '+p.id+' to pad '+p.toPad,
{ font: '24px Arial Bold', fill: '#FBFBAC' });
slot.text.setScrollFactor(0);
}
public alight( person: Person ) {
let slotNo = this.findSlot(person)
let slot = this.slots[slotNo]
slot.text.destroy();
this.slots[slotNo] = null;
}
public kickOut( person: Person ) {
let slotNo = this.findSlot(person)
this.slots[slotNo].text.destroy();
this.slots[slotNo] = null;
}
private getFreeSlot() {
for (let n=0; n<5; n++) {
if ( ! this.slots[n] ) return n;
}
}
private findSlot(p:Person) {
//let slot = (this.slots as any).find( slot => slot.p.id == p.id );
//return slot
for (let n=0; n<5; n++) {
const slot = this.slots[n]
if ( slot && slot.p.id == p.id ) return n;
}
}
shutdown() {}
}
|
fd580992eaca5081f3d532165e491226b6c86c0a
|
TypeScript
|
mientjan/EaselTS
|
/src/easelts/filters/Filter.ts
| 2.9375
| 3
|
/*
* Filter
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
import Rectangle from "../geom/Rectangle";
/**
* @module EaselJS
*/
/**
* Base class that all filters should inherit from. Filters need to be applied to objects that have been cached using
* the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method. If an object changes, please cache it again, or use
* {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}. Note that the filters must be applied before caching.
*
* <h4>Example</h4>
*
* myInstance.filters = [
* new createjs.ColorFilter(0, 0, 0, 1, 255, 0, 0),
* new createjs.BlurFilter(5, 5, 10)
* ];
* myInstance.cache(0,0, 100, 100);
*
* Note that each filter can implement a {{#crossLink "Filter/getBounds"}}{{/crossLink}} method, which returns the
* margins that need to be applied in order to fully display the filter. For example, the {{#crossLink "BlurFilter"}}{{/crossLink}}
* will cause an object to feather outwards, resulting in a margin around the shape.
*
* <h4>EaselJS Filters</h4>
* EaselJS comes with a number of pre-built filters. Note that individual filters are not compiled into the minified
* version of EaselJS. To use them, you must include them manually in the HTML.
* <ul><li>{{#crossLink "AlphaMapFilter"}}{{/crossLink}} : Map a greyscale image to the alpha channel of a display object</li>
* <li>{{#crossLink "AlphaMaskFilter"}}{{/crossLink}}: Map an image's alpha channel to the alpha channel of a display object</li>
* <li>{{#crossLink "BlurFilter"}}{{/crossLink}}: Apply vertical and horizontal blur to a display object</li>
* <li>{{#crossLink "ColorFilter"}}{{/crossLink}}: Color transform a display object</li>
* <li>{{#crossLink "ColorMatrixFilter"}}{{/crossLink}}: Transform an image using a {{#crossLink "ColorMatrix"}}{{/crossLink}}</li>
* </ul>
*
* @class Filter
* @constructor
**/
class Filter
{
/**
* Initialization method.
* @method initialize
* @protected
**/
// public methods:
/**
* Returns a rectangle with values indicating the margins required to draw the filter or null.
* For example, a filter that will extend the drawing area 4 pixels to the left, and 7 pixels to the right
* (but no pixels up or down) would return a rectangle with (x=-4, y=0, width=11, height=0).
* @method getBounds
* @return {Rectangle} a rectangle object indicating the margins required to draw the filter or null if the filter does not effect bounds.
**/
public getBounds():Rectangle
{
return null;
}
/**
* Applies the filter to the specified context.
* @method applyFilter
* @param {CanvasRenderingContext2D} ctx The 2D context to use as the source.
* @param {Number} x The x position to use for the source rect.
* @param {Number} y The y position to use for the source rect.
* @param {Number} width The width to use for the source rect.
* @param {Number} height The height to use for the source rect.
* @param {CanvasRenderingContext2D} [targetCtx] The 2D context to draw the result to. Defaults to the context passed to ctx.
* @param {Number} [targetX] The x position to draw the result to. Defaults to the value passed to x.
* @param {Number} [targetY] The y position to draw the result to. Defaults to the value passed to y.
* @return {Boolean} If the filter was applied successfully.
**/
public applyFilter(ctx:CanvasRenderingContext2D, x:number, y:number, width:number, height:number, targetCtx?:CanvasRenderingContext2D, targetX?:number, targetY?:number):boolean
{
return false;
}
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
public toString():string
{
return "[Filter]";
}
/**
* Returns a clone of this Filter instance.
* @method clone
* @return {Filter} A clone of the current Filter instance.
**/
public clone():Filter
{
return new Filter();
}
}
export default Filter;
|
5139064b347e3d0b8f480c3cfe63260e6bb2b64e
|
TypeScript
|
931-ChristinaRuss-Chronicle/chronicle-front
|
/chronicle-front/src/app/components/login/login.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
import firebase from 'firebase/app';
import 'firebase/auth';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
/**
* The Login Component uses FirebaseUI for logging in
* Configuration for FirebaseUI can be found in appmodule.ts
*
* */
export class LoginComponent implements OnInit {
constructor(private router: Router, private authService: AuthService) {
}
ngOnInit(): void {}
/**
* The success callback is invoked on a successful login
* Calls a login function in the authservice for added functionality post login
*
* */
successCallback(): void {
let user = firebase.auth().currentUser;
// currently can not find a suitable way to call an on register method without changing
// the current code base. I found a way to write an onRegister function but it is on the firebase console.
// For now we are just checking if the user has any claims set. If not then we know they are a new user
// Then we call the onRegister
firebase.auth().currentUser?.getIdTokenResult()
.then(tokenResults => {
if(!tokenResults.claims.role && user)
this.onRegister(user.uid);
})
this.authService.login();
}
/**
* This function is called on a login error
* Console logs an error
*
* */
errorCallback(): void {
console.log('LoginComponent:: emailPasswordLogin:: login failed:');
}
/**
* onRegister
* Need a function added to the firebase console that can handle this more elegantly
* Makes call to API /firebase/register/{uid} to add ROLE_USER claim
*/
onRegister(id: string) {
this.authService.register(id);
}
}
|
966068713f5825f27f31540f3e901035d1b1c938
|
TypeScript
|
hoaipeter/react-dnd-task
|
/src/store/app-store.ts
| 2.640625
| 3
|
import { combineReducers, createStore, EmptyObject } from 'redux';
import throttle from 'lodash.throttle';
import seed from './initialize-store';
// Import reducers
import { boardReducers } from '../reducers/board-reducer';
import { cardReducers } from '../reducers/card-reducer';
import { listsReducers } from '../reducers/column-reducer';
const reducers = combineReducers({
board: boardReducers,
listsById: listsReducers,
cardsById: cardReducers
});
const saveState = (state: EmptyObject & { board: never; listsById: {}; cardsById: {} }) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
} catch {
// ignore write errors
}
};
const loadState = () => {
try {
const serializedState = localStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
const persistedState = loadState();
const store = createStore(reducers, persistedState);
store.subscribe(
throttle(() => {
saveState(store.getState());
}, 1000)
);
console.log(store.getState());
// @ts-ignore
if (!store.getState().board.lists.length) {
console.log('SEED');
seed(store);
}
export default store;
|
631aa2bdd65d93781c6eccf0897e418dce2d49dd
|
TypeScript
|
harry502/CardGame
|
/client/src/core/controller/ViewController.ts
| 2.625
| 3
|
module core {
export class ViewController extends Controller {
private parent: egret.DisplayObjectContainer;
private viewLayerType: ViewLayerType;
private argList: Array<any>;
public constructor() {
super();
}
public destroy() {
this.parent = null;
this.argList = null;
this.viewLayerType = null;
super.destroy();
}
public open(): void {
Log.error("所有继承 ViewController 的子类都必须重写 open() 方法,该方法在控制器被添加到显示列表时调用");
}
public close(): void {
Log.error("所有继承 ViewController 的子类都必须重写 close() 方法,该方法在控制器被移出显示列表时调用");
}
public getParams(): any[] {
return this.argList;
}
public setParams(...list): void {
this.argList = list;
}
public getParam<T>(index: number): T {
let obj: T = null;
if (this.argList != null && this.argList.length > index) {
obj = this.argList[index] as T;
}
return obj;
}
public getParamCount(): number {
if (this.argList == null) {
return 0;
} else {
return this.argList.length;
}
}
public setParent(parent: egret.DisplayObjectContainer, viewType: ViewLayerType): void {
this.parent = parent;
this.viewLayerType = viewType;
}
public getParent(): egret.DisplayObjectContainer {
return this.parent;
}
public getViewLayerType(): ViewLayerType {
return this.viewLayerType;
}
public getModel<T extends Model>(modelClass: { new (): T; }): T {
return ModelManage.getInstance().getModel(modelClass);
}
}
}
|
15110fcac56190d6376edbc7fa09cd66c862e5b9
|
TypeScript
|
guardian/liveblog-rendering
|
/src/liveBlock.ts
| 2.609375
| 3
|
// ----- Imports ----- //
import { Option, fromNullable } from '@guardian/types/option';
import { BlockElement } from '@guardian/content-api-models/v1/blockElement';
import { Block } from '@guardian/content-api-models/v1/block';
import { maybeCapiDate } from './capi';
// ----- Types ----- //
type LiveBlock = {
id: string;
title: Option<string>;
firstPublished: Option<Date>;
lastModified: Option<Date>;
body: BlockElement[];
}
// ----- Functions ----- //
const parse = (block: Block): LiveBlock =>
({
id: block.id,
title: fromNullable(block?.title),
firstPublished: maybeCapiDate(block?.firstPublishedDate),
lastModified: maybeCapiDate(block?.lastModifiedDate),
body: block.elements,
});
// ----- Exports ----- //
export type {
LiveBlock,
}
export {
parse,
}
|
da94b270c026c44f286413dab2afec24a57e6185
|
TypeScript
|
sergio222-dev/nestjs-ddd-practice
|
/test/libs/First-aprox-lib/Courses/Domain/Events/CourseCreatedEventMother.ts
| 2.734375
| 3
|
import { CourseCreatedEvent } from "@libs/First-aprox-lib/Courses/Domain/events/CourseCreated.event";
import { UuidMother } from "../../../../Shared/Domain/UuidMother";
import { WordMother } from "../../../../Shared/Domain/WordMother";
import { Course } from "@libs/First-aprox-lib/Courses/Domain/Models/Course";
export class CourseCreatedEventMother {
public static create(
id: string,
name: string,
duration: string,
): CourseCreatedEvent {
return new CourseCreatedEvent(id, name, duration);
}
public static fromCourse(course: Course): CourseCreatedEvent {
const {id, name, duration} = course;
return new CourseCreatedEvent(id.value, name.value, duration.value);
}
public static random(): CourseCreatedEvent {
return new CourseCreatedEvent(UuidMother.random(), WordMother.random(), WordMother.random());
}
}
|
42bcaea7f51d929adb2034fb68af0db4cd8ddde0
|
TypeScript
|
xmano/TypeScriptCourse
|
/app/main.ts
| 3.0625
| 3
|
import { AppComponent } from './app.component';
let c = new AppComponent();
console.log(c.string);
interface product {
id?: any;
desc: string;
price: number;
}
let item: product = {
desc: "iPhone",
price: 60000
}
let anotherItem = {
id: '100',
desc: 'Merc C5',
price: 2000000
}
item = anotherItem;
console.log(item);
|
787b6928d007431c5df6299eb688051bbfb6b1db
|
TypeScript
|
harsilspatel/pong-breakout
|
/src/svgelement.ts
| 3.671875
| 4
|
/**
* a little wrapper for creating SVG elements and getting/setting their attributes
* and observing their events.
* inspired by d3.js (http://d3js.org)
*/
class Elem {
elem: Element;
/**
* @param svg is the parent SVG object that will host the new element
* @param tag could be "rect", "line", "ellipse", etc.
*/
constructor(svg: HTMLElement, tag: string) {
this.elem = document.createElementNS(svg.namespaceURI, tag);
svg.appendChild(this.elem);
}
/**
* all purpose attribute getter/setter
* @param name attribute name
* @param value value to assign to the attribute
* @returns called with just the name of the attribute it returns the attribute's current value as a string, called with the name and a new value it sets the attribute and returns this object
* so subsequent calls can be chained
*/
attr(name: string): string;
attr(name: string, value: string | number): this;
attr(name: string, value?: string | number): this | string {
if (typeof value === "undefined") {
return this.elem.getAttribute(name)!;
}
this.elem.setAttribute(name, value.toString());
return this;
}
/**
* @returns an Observable for the specified event on this element
*/
observe<T extends Event>(event: string): Observable<T> {
return Observable.fromEvent<T>(this.elem, event);
}
}
|
27146ac5ef8f2eeaa34ba5942ffd6caaa685f910
|
TypeScript
|
dariki1/Pong
|
/Client/Comm.ts
| 2.765625
| 3
|
class Comm {
public static send(type, message) : void{
jsSend(type, message);
}
public static addMessageListener(type, callback) : void {
jsAddMessageListener(type, callback);
}
public static init() {
this.addMessageListener('gameUpdate', function(msg) {
if (msg[0] == 'newGame') {
Main.newGame();
} else if (msg[0] == 'moveUpdate') {
Main.game.paddleTwo.down = msg[1][1];
Main.game.paddleTwo.up = msg[1][0];
} else if (msg[0] == 'gameDone') {
Main.game.running = false;
GUI.message("GAME OVER! Winner; " + msg[1][0], 180);
}
});
}
//Should probably move this to another class
public static update() {
let msg = [];
msg[0] = 'moveUpdate';
msg[1] = [];
msg[1][1] = Main.game.paddleOne.down;
msg[1][0] = Main.game.paddleOne.up;
this.send('gameUpdate',msg);
}
}
|
6af1ed0959ceace56ead5b670beb423ebd5242fd
|
TypeScript
|
DNIStream/dni.website
|
/src/DNI.Web/src/app/components/shared/uriHelper.ts
| 2.984375
| 3
|
export class UriHelper {
public static getUri(path: string, parameters: { [key: string]: string } = null): string {
let uri = path.trim();
if (parameters) {
// Add other parameters
for (const p in parameters) {
if (parameters.hasOwnProperty(p) && parameters[p]) {
if (uri.indexOf('?') > -1) {
uri += '&';
} else {
uri += '?';
}
uri += p + '=' + parameters[p];
}
}
}
return uri;
}
}
|
4282538c10e20c1540d93661b590e529e2f4d7c2
|
TypeScript
|
tpohl/flights
|
/functions/src/util/defaulttime.ts
| 2.625
| 3
|
import { Flight } from '../models/flight';
const defaultTimes = function(flight: Flight){
// if arrival and desitnation are empty
if (flight.departureTime === undefined && flight.date !== undefined) {
flight.departureTime = flight.date + 'T12:00:00Z' ;
}
if (flight.arrivalTime === undefined && flight.date !== undefined) {
flight.arrivalTime = flight.date + 'T13:00:00Z' ;
}
return flight;
}
export default defaultTimes;
|
0b97bdd789614f2fd3713fb1216c07cd4c202235
|
TypeScript
|
shokfake/SMS_Service
|
/src/module/student/repository/student.repository.ts
| 2.59375
| 3
|
import { InternalServerErrorException, Logger } from "@nestjs/common";
import { Repository, EntityRepository } from "typeorm";
import { CredentialDto, UserEntity } from "../../../auth/model/auth.model";
import { StudentEntity } from "../../../entities/EsPreadmission";
import { AdmissionDto } from "../dto/admission.dto";
@EntityRepository(StudentEntity)
export class StudentRepository extends Repository<StudentEntity>{
logger = new Logger(this.constructor.name)
async createAdmission(data: AdmissionDto): Promise<StudentEntity> {
const dto: Omit<AdmissionDto, 'id'> = data
const entity = this.create(dto)
return this.save(entity)
}
async getStudentWithCredential(
credential: { username: string, password: string },
): Promise<StudentEntity> {
const { username, password } = credential;
return this.findOne({ username, password })
}
async getStudentById(id: number): Promise<StudentEntity> {
return this.findOne({ id });
}
async getProfile(id: number): Promise<StudentEntity> {
return this.getStudentById(id)
}
}
|
d4c0e6d94fd8c623259fdbd782a7913284dc5fb8
|
TypeScript
|
real-marshal/binance-hotkeys
|
/src/hooks/useHotkeys.ts
| 2.703125
| 3
|
import { useCallback, useEffect, useState } from 'react'
import { Optional } from '../common/utils'
import { v4 as uuidv4 } from 'uuid'
export interface HotkeyData {
id: string
key: string
handler: () => unknown
}
export default function useHotkeys(
node?: HTMLElement,
defaultHotkeys: HotkeyData[] = []
) {
const [hotkeys, setHotkeys] = useState(defaultHotkeys)
const eventListener = useCallback(
(e: KeyboardEvent) => {
hotkeys.forEach(({ key, handler }) => e.key === key && handler())
},
[hotkeys]
)
const set = useCallback(
(hotkeyData: Optional<HotkeyData, 'id'>) => {
const { id = uuidv4() } = hotkeyData
setHotkeys([...hotkeys, { ...hotkeyData, id }])
},
[setHotkeys, hotkeys]
)
const unset = useCallback(
(id: string) => {
setHotkeys(hotkeys.filter((hotkey) => hotkey.id !== id))
},
[setHotkeys, hotkeys]
)
useEffect(() => {
node?.addEventListener('keypress', eventListener)
return node?.removeEventListener('keypress', eventListener)
}, [node, eventListener])
return { set, unset, hotkeys }
}
|
debfc32f71eb1ee491e7a9e4df25d50e50e9b61f
|
TypeScript
|
saiqulhaq/techcal.dev
|
/web/src/functions/getCalendarEvents.ts
| 2.515625
| 3
|
import type { Dayjs } from 'dayjs'
import type { GoogleCalendar } from '$types/GoogleCalendar'
export const getCalendarEvents = async (begin: Dayjs, end: Dayjs) => {
let resp: GoogleCalendar = await fetch(
`https://www.googleapis.com/calendar/v3/calendars/${
import.meta.env.VITE_CALENDAR_EMAIL
}/events?${new URLSearchParams({
key: 'AIzaSyBpmxgK9dbso4pEYWvg47SOoIqIBB83Pno',
timeMin: begin.toISOString(),
timeMax: end.endOf('day').toISOString(),
singleEvents: 'true',
maxResults: '999',
}).toString()}`
).then(o => {
if (o.ok) return o.json()
else throw o
})
return resp.items
}
|
036dbbbfdb149990ec8ebad0b89a97ab8724e4dc
|
TypeScript
|
eschelkunov/crud_react_redux_saga_typescript
|
/src/saga/sagas.ts
| 2.609375
| 3
|
import { takeLatest, put, all, call, takeEvery } from "redux-saga/effects";
import {
fetchData,
addSinglePost,
editSinglePost,
removeSinglePost
} from "../api";
import {
ADD_POST_ASYNC,
IPostsActionType,
ISinglePostActionType,
REMOVE_POST_ASYNC,
IRemovePostActionType,
removePost,
EDIT_POST_ASYNC,
editPost,
addPost,
fetchPosts,
FETCH_POSTS_ASYNC
} from "../actions/entityActions";
export const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
// Fetch posts
export function* fetchPostsAsync(action: IPostsActionType) {
try {
const data = yield call(fetchData);
yield put(fetchPosts(data));
} catch (error) {
console.log("There was an error in getApiData method", error);
}
}
function* watchFetchPostsData() {
yield takeLatest(FETCH_POSTS_ASYNC, fetchPostsAsync);
}
// Add post
export function* addPostAsync(action: ISinglePostActionType) {
try {
const data = yield call(addSinglePost, action.data);
yield put(addPost(data));
} catch (error) {
console.log("There was an error in addPostData method", error);
}
}
function* watchAddPostAsync() {
yield takeEvery(ADD_POST_ASYNC, addPostAsync);
}
// Edit post
export function* editPostAsync(action: ISinglePostActionType) {
try {
const data = yield call(editSinglePost, action.data);
yield put(editPost(data));
} catch (error) {
console.log("There was an error in addPostData method", error);
}
}
function* watchEditPostAsync() {
yield takeEvery(EDIT_POST_ASYNC, editPostAsync);
}
// Remove post
export function* removePostAsync(action: IRemovePostActionType) {
try {
const response = yield call(removeSinglePost, action.id);
if (response.status === 200) {
yield put(removePost({ id: action.id }));
}
} catch (error) {
console.log("There was an error in addPostData method", error);
}
}
function* watchRemovePostAsync() {
yield takeEvery(REMOVE_POST_ASYNC, removePostAsync);
}
export default function* rootSaga() {
yield all([
watchFetchPostsData(),
watchAddPostAsync(),
watchEditPostAsync(),
watchRemovePostAsync()
]);
}
|
3c9f5a1f764e71dbb80b07175d42900e0eb2db50
|
TypeScript
|
derkaczda/Kouky
|
/src/core/rendering/buffer/IndexBuffer.ts
| 3.0625
| 3
|
namespace Kouky {
export class Index implements IBufferDataElement {
public index: number;
public constructor(index: number) {
this.index = index;
}
public toArray(): number[] {
return [this.index];
}
public toFloat32Array(): Float32Array {
return new Float32Array(this.toArray());
}
public toUint26Array(): Uint16Array {
return new Uint16Array(this.toArray());
}
}
export class IndexBufferData implements IBufferData {
private _elements: Index[] = [];
public addElement(element: Index): void {
this._elements.push(element);
}
public addElements(elements: Index[]): void {
for(let e of elements) {
this._elements.push(e);
}
}
public toArray(): number[] {
let array: number[] = [];
for(let index of this._elements) {
array = array.concat(index.toArray());
}
return array;
}
public toFloat32Array(): Float32Array {
return new Float32Array(this.toArray());
}
public toUint16Array(): Uint16Array {
return new Uint16Array(this.toArray());
}
}
export class IndexBuffer implements IBuffer {
private _buffer: WebGLBuffer;
private _bufferData: IndexBufferData;
public constructor() {
this._buffer = WebGLContext.createBuffer();
}
public bind(): void {
WebGLContext.bindElementArrayBuffer(this._buffer);
}
public unbind(): void {
WebGLContext.bindElementArrayBuffer(undefined);
}
public addData(data: IndexBufferData): void {
this._bufferData = data;
}
public deleteData(): void {
this._bufferData = undefined;
}
public loadData(): void {
if(this._bufferData !== undefined) {
this.bind();
WebGLContext.uploadElementArrayData(this._bufferData.toUint16Array());
this.unbind();
}
}
public addDataAndLoad(data: IndexBufferData): void {
this.addData(data);
this.loadData();
}
public toString(): string {
return "IndexBuffer";
}
}
}
|
c0cd45f2f1f051c2caf9af71601063946c26ada9
|
TypeScript
|
cornelg7/tippymaze
|
/src/app/utils/node.ts
| 3.03125
| 3
|
export default class Node {
id: string;
placement: string;
text: string;
onClick: () => void;
onClickInt: () => void;
constructor(id: string, placement: string, text: string = id, onClick?: () => void, onClickInt?: () => void) {
this.id = id;
this.placement = placement;
this.text = text;
this.onClick = onClick;
this.onClickInt = onClickInt;
}
}
|
16ad2ccc486c4328f33b9ccb1eef4ffe654d6bd9
|
TypeScript
|
blanck1945/React-control-form
|
/src/funcs.ts
| 2.859375
| 3
|
export const getEventMonth = (date: string) => {
const day = date.slice(5, 7);
const monthName = returnMontName(parseInt(day));
return monthName.toString();
};
const returnMontName = (num: number) => {
const months = [
"Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre",
];
return months.filter((el: string, index: number) =>
index + 1 === num ? [el] : null
);
};
export const formatHour = (hour: string) => {
if (hour.length === 2) {
return hour + ":00";
}
return hour.slice(0, 1) + ":" + hour.slice(2, 3);
};
export const getEventDay = (date: string) => {
return getDayName(date, undefined);
};
export const getDayName = (dateStr: string, locale: string) => {
var date = new Date(dateStr);
return date.toLocaleDateString(locale, { weekday: "long" });
};
export const formatData = (arr: any, filter: string) => {
const formatArr: any = [];
for (const key in arr) {
if (key.substr(0, key.length - 1) === filter) {
formatArr.push(arr[key]);
}
}
return formatArr;
};
export const cleanData = (arr: any) => {
for (const key in arr) {
const lastCaracter = key.substr(-1);
if (
lastCaracter === "0" ||
lastCaracter === "1" ||
lastCaracter === "2" ||
lastCaracter === "3" ||
lastCaracter === "4"
) {
delete arr[key];
}
}
return arr;
};
export const getToday = () => {
const today = new Date();
return (
today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate()
);
};
export const checkBoolValue = (value: string) => {
if (value === "Si") {
return true;
}
return false;
};
export const initialValues = {
event_name: "",
event_desc: "",
event_category: "Derecho",
event_type: "Conferencia",
event_start: "",
event_free: true,
event_discount: "No",
event_discount_per: 0,
event_img: "",
terms: false,
};
|
a07b4a565e7af6487aca5c60a1eac59b0e15f17f
|
TypeScript
|
ddotx/rxjs-state
|
/libs/rxjs-state/src/lib/core/operators/coalesce.ts
| 3
| 3
|
import {
MonoTypeOperatorFunction,
Observable,
Operator,
SubscribableOrPromise,
Subscriber,
Subscription,
TeardownLogic
} from 'rxjs';
import {InnerSubscriber, OuterSubscriber, subscribeToResult} from 'rxjs/internal-compatibility';
import {generateFrames} from '../projections';
export interface CoalescingContext {
isCoalescing: any | undefined;
}
export interface CoalesceConfig {
context?: CoalescingContext;
leading?: boolean;
trailing?: boolean;
}
export const defaultCoalesceConfig: CoalesceConfig = {
// @TODO consiger getGlobalThis aas default
context: {isCoalescing: false},
leading: false,
trailing: true
};
export function getCoalesceConfig(config: CoalesceConfig = defaultCoalesceConfig): CoalesceConfig {
return {
...defaultCoalesceConfig,
...config,
};
}
export const defaultCoalesceDurationSelector = <T>(value: T) => generateFrames();
/**
* Emits a value from the source Observable, then ignores subsequent source
* values for a duration determined by another Observable, then repeats this
* process.
*
* <span class="informal">It's like {@link throttle}, but providing a way to configure scoping.</span>
*
* 
*
* `coalesce` emits the source Observable values on the output Observable
* when its internal timer is disabled, and ignores source values when the timer
* is enabled. Initially, the timer is disabled. As soon as the first source
* value arrives, it is forwarded to the output Observable, and then the timer
* is enabled by calling the `durationSelector` function with the source value,
* which returns the "duration" Observable. When the duration Observable emits a
* value or completes, the timer is disabled, and this process repeats for the
* next source value.
*
* ## Example
* Emit clicks at a rate of at most one click per second
* ```ts
* import { fromEvent, interval } from 'rxjs';
* import { coalesce } from 'rxjs/operators';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(coalesce(ev => interval(1000)));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link debounce}
* @see {@link delayWhen}
* @see {@link sample}
* @see {@link throttle}
* @see {@link throttleTime}
*
* @param {function(value: T): SubscribableOrPromise} durationSelector A function
* that receives a value from the source Observable, for computing the silencing
* duration for each source value, returned as an Observable or a Promise.
* @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
* to `{ leading: true, trailing: false }`.
* @return {Observable<T>} An Observable that performs the coalesce operation to
* limit the rate of emissions from the source.
* @name coalesce
*/
export function coalesce<T>(durationSelector: (value: T) => SubscribableOrPromise<any> = defaultCoalesceDurationSelector,
config?: CoalesceConfig): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => source.lift(new CoalesceOperator(durationSelector, getCoalesceConfig(config)));
}
class CoalesceOperator<T> implements Operator<T, T> {
constructor(private durationSelector: (value: T) => SubscribableOrPromise<any>,
private config: CoalesceConfig) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(
new CoalesceSubscriber(subscriber, this.durationSelector, this.config)
);
}
}
class CoalesceSubscriber<T, R> extends OuterSubscriber<T, R> {
private _coalesced: Subscription | null | undefined;
private _sendValue: T | null = null;
private _hasValue = false;
private _leading: boolean;
private _trailing: boolean;
private _context: CoalescingContext;
constructor(protected destination: Subscriber<T>,
private durationSelector: (value: T) => SubscribableOrPromise<number>,
config: CoalesceConfig) {
super(destination);
this._leading = config.leading;
this._trailing = config.trailing;
this._context = config.context;
if (!this._context) {
this._context = {} as any;
}
}
protected _next(value: T): void {
this._hasValue = true;
this._sendValue = value;
if (!this._coalesced) {
this.send();
}
}
protected _complete(): void {
this.coalescingDone();
super._complete();
}
private send() {
const {_hasValue, _sendValue, _leading} = this;
if (_hasValue) {
if (_leading) {
this.destination.next(_sendValue!);
this._hasValue = false;
this._sendValue = null;
}
this.startCoalesceDuration(_sendValue!);
}
}
private exhaustLastValue() {
const {_hasValue, _sendValue} = this;
if (_hasValue && _sendValue) {
this.destination.next(_sendValue!);
this._hasValue = false;
this._sendValue = null;
}
}
private startCoalesceDuration(value: T): void {
const duration = this.tryDurationSelector(value);
if (!!duration) {
this.add(this._coalesced = subscribeToResult(this, duration));
this._context.isCoalescing = true;
}
}
private coalescingDone() {
const {_coalesced, _trailing, _context} = this;
if (_coalesced) {
_coalesced.unsubscribe();
}
this._coalesced = null;
if (_context.isCoalescing) {
if (_trailing) {
this.exhaustLastValue();
}
this._context.isCoalescing = false;
}
;
}
private tryDurationSelector(value: T): SubscribableOrPromise<any> | null {
try {
return this.durationSelector(value);
} catch (err) {
this.destination.error(err);
return null;
}
}
notifyNext(outerValue: T, innerValue: R,
outerIndex: number, innerIndex: number,
innerSub: InnerSubscriber<T, R>): void {
this.coalescingDone();
}
notifyComplete(): void {
this.coalescingDone();
}
}
|
2b931bd31a7d3b255168b8139317ec9b7c9fd4c2
|
TypeScript
|
muhadbk0/file-storage-application
|
/server/src/middlewares/isAdmin.ts
| 2.5625
| 3
|
import {Request,Response,NextFunction} from 'express'
const isAdmin = (req:Request,res:Response,next:NextFunction )=>{
if( req.currentUser.role !=='admin' ){
const error = new Error('You not an admin user');
error["status"]=404;
throw error
}
next()
};
export default isAdmin;
|
5260de2fffd952d2f54825832502b340d1034341
|
TypeScript
|
fabien-h/url
|
/src/parseURL.ts
| 2.921875
| 3
|
import urlTestRegex from './urlTestRegex';
import { IURLParsed } from './types';
/**
* Parse an url to give an object
*
* @param url
*/
const parse = (url: string): IURLParsed | false => {
/**
* Manual check
*/
if (!url || typeof url !== 'string') {
return false;
}
/**
* Test if we have a valid url
*/
const isValidURL = urlTestRegex.test(url);
/**
* Init the variables
*/
let baseURL: string | Array<string> = decodeURIComponent(url);
let auth: { [key: string]: string } = {};
let domain: string | null = null;
let domainChain: Array<string> | null = null;
let hash: string | null = null;
let host: string | null = null;
let hostname: string | null = null;
let href = url;
let origin: string | null = null;
let path: string | null = null;
let pathname: string | null = null;
let port: string | null = null;
let protocol: string | null = null;
let query: string | null = null;
let queryParams: { [key: string]: string | Array<string> } = {};
let search: string | null = null;
let tld: string | null = null;
/**
* Build the protocol
*/
baseURL = baseURL.split('//');
if (baseURL.length > 1) {
protocol = baseURL[0] || null;
baseURL = baseURL[1];
} else {
baseURL = baseURL[0];
}
/**
* Build the auth
*/
baseURL = baseURL.split('@');
if (baseURL.length > 1) {
const authData = baseURL[0].split(':');
auth = {
password: authData[1] || '',
username: authData[0] || '',
};
baseURL = baseURL[1];
} else {
baseURL = baseURL[0];
}
/**
* Build the hash
*/
baseURL = baseURL.split('#');
if (baseURL.length > 1) {
hash = `${baseURL[1]}`;
}
baseURL = baseURL[0];
/**
* Build the search
*/
baseURL = baseURL.split('?');
if (baseURL.length > 2) {
console.error('Malformed URL: multiple searches.');
} else if (baseURL.length === 2) {
search = `?${baseURL[1]}`;
query = baseURL[1];
query.split('&').forEach(query => {
const queryData = query.split('=');
const key = String(queryData[0]);
const value = String(queryData[1]);
if (!queryParams[key]) {
queryParams[key] = value;
} else if (typeof queryParams[key] === 'string') {
queryParams[key] = [queryParams[key] as string, value];
} else {
queryParams[key] = [...(queryParams[key] as Array<string>), value];
}
});
}
baseURL = baseURL[0];
/**
* Build the path
*/
baseURL = baseURL.split('/');
if (baseURL.length === 1) {
pathname = '/';
} else {
pathname = '/' + baseURL.slice(1).join('/');
}
path = (pathname || '') + (search || '');
baseURL = baseURL[0] || '';
/**
* Build the host, domain
*/
baseURL = baseURL.split('/');
host = baseURL[0] || '';
const hostData = host.split(':');
if (hostData.length === 2) {
port = hostData[1] || null;
}
hostname = hostData[0];
domainChain = hostData[0].split('.').reverse();
tld = domainChain[0] || null;
domain = domainChain[1] || null;
baseURL = baseURL[1];
/**
* Build the origin
*/
origin = host || '';
if (protocol) {
if (
protocol === 'http:' ||
protocol === 'https:' ||
protocol === 'ftp:' ||
protocol === 'file:'
) {
origin = protocol + '//' + host;
} else {
protocol = protocol + host;
}
}
return {
auth,
domain,
domainChain,
hash,
host,
hostname,
href,
isValidURL,
origin,
path,
pathname,
port,
protocol,
query,
queryParams,
search,
tld,
};
};
export default parse;
|
3a93dc4f052c49426fbad794258f896ba3a2f04b
|
TypeScript
|
vishalmhatre56/Angular7TrainingDemos
|
/demo/angular7-demo/src/app/sizer/sizer.component.ts
| 2.640625
| 3
|
import { Component, EventEmitter, Input, Output, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-sizer',
templateUrl: './sizer.component.html',
styleUrls: ['./sizer.component.scss']
})
export class SizerComponent {
@Input() size: number | string;
@Output() sizeChange = new EventEmitter<number>();
dec() { this.resize(-1); }
inc() { this.resize(+1); }
ngOnInit(){
console.log("on init")
}
resize(delta: number) {
this.size = Math.min(70, Math.max(8, +this.size + delta));
this.sizeChange.emit(this.size);
}
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
let chng = changes[propName];
let cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue);
console.log(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
}
}
}
|
b1af36e0ca50799ecfcd84a625245dc6437f1e52
|
TypeScript
|
sldsrg/chesspector
|
/spec/moverecord.spec.ts
| 3.078125
| 3
|
import 'mocha'
import { expect } from 'chai'
import { MoveRecord, MoveFlags, Position } from '../src'
describe(`MoveRecord`, () => {
describe(`when constructed with LAN`, () => {
it('correct handle check sign', () => {
const rec = new MoveRecord(1, true, 'Qd8-d3+')
expect(rec.toString()).to.be.equal('1.Qd8-d3+')
})
it('correct handle checkmate sign', () => {
const rec = new MoveRecord(1, true, 'Qd8-d3#')
expect(rec.toString()).to.be.equal('1.Qd8-d3#')
})
describe(`and evaluated in positional context`, () => {
let position: Position
before(() => {
position = new Position('4k2r/4p3/R7/2B3B1/8/8/4P3/R3K1N1 w Qk -')
})
it(`return valid MoveData object for pawn move`, () => {
const rec = new MoveRecord(1, true, 'e2-e4')
const data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 6, column: 4})
expect(data!.to).to.deep.equal({row: 4, column: 4})
expect(data!.capturedPiece).to.be.undefined
})
it(`return valid MoveData object for knight move`, () => {
const rec = new MoveRecord(1, true, 'Ng1-f3')
const data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 7, column: 6})
expect(data!.to).to.deep.equal({row: 5, column: 5})
expect(data!.capturedPiece).to.be.undefined
})
it(`return valid MoveData object for long castling`, () => {
const rec = new MoveRecord(1, true, 'O-O-O')
const data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.CastlingLong)
expect(data!.from).to.deep.equal({row: 7, column: 4})
expect(data!.to).to.deep.equal({row: 7, column: 2})
expect(data!.capturedPiece).to.be.undefined
})
})
})
describe(`when constructed with SAN`, () => {
it('correct handle check sign', () => {
const rec = new MoveRecord(1, true, 'Qd3+')
expect(rec.toString()).to.be.equal('1.Qd3+')
})
it('correct handle checkmate sign', () => {
const rec = new MoveRecord(1, true, 'Qd3#')
expect(rec.toString()).to.be.equal('1.Qd3#')
})
describe(`and evaluated in positional context`, () => {
let position: Position
let recPawn: MoveRecord
let recKnight: MoveRecord
before(() => {
recPawn = new MoveRecord(1, true, 'e4')
recKnight = new MoveRecord(1, true, 'Nf3')
})
before(() => {
position = new Position('4k2r/4p3/R7/2B3B1/8/8/4P3/R3K1N1 w Qk -')
})
it(`return valid MoveData object for pawn move`, () => {
const data = recPawn.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 6, column: 4})
expect(data!.to).to.deep.equal({row: 4, column: 4})
expect(data!.capturedPiece).to.be.undefined
})
it(`return valid MoveData object for knight move`, () => {
const data = recKnight.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 7, column: 6})
expect(data!.to).to.deep.equal({row: 5, column: 5})
expect(data!.capturedPiece).to.be.undefined
})
it(`can distinct between two rook moves with different rank`, () => {
let rec = new MoveRecord(1, true, 'R1a3')
let data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 7, column: 0})
expect(data!.to).to.deep.equal({row: 5, column: 0})
expect(data!.capturedPiece).to.be.undefined
rec = new MoveRecord(1, true, 'R6a3')
data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Quiet)
expect(data!.from).to.deep.equal({row: 2, column: 0})
expect(data!.to).to.deep.equal({row: 5, column: 0})
expect(data!.capturedPiece).to.be.undefined
})
it(`can distinct between two bishop moves with different file`, () => {
let rec = new MoveRecord(1, true, 'Bcxe7')
let data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Capture)
expect(data!.from).to.deep.equal({row: 3, column: 2})
expect(data!.to).to.deep.equal({row: 1, column: 4})
expect(data!.capturedPiece).not.to.be.undefined
rec = new MoveRecord(1, true, 'Bgxe7')
data = rec.eval(position)
expect(data!.flags).to.equal(MoveFlags.Capture)
expect(data!.from).to.deep.equal({row: 3, column: 6})
expect(data!.to).to.deep.equal({row: 1, column: 4})
expect(data!.capturedPiece).not.to.be.undefined
})
})
})
})
|
7de21057e351c956f51494efc4693440260af6c0
|
TypeScript
|
JordyBaylac/js-analyzer
|
/lib/analysis/analyzer/file_analyzer.ts
| 2.78125
| 3
|
import { IStrategy, IStrategyResult } from '../strategies/i_strategy';
import * as esprima from 'esprima';
import * as fs from 'fs';
import * as path from 'path';
export interface IFileAnalysis {
filePath: string,
strategiesResults: IStrategyResult[]
}
export class FileAnalyzer {
private fileToProcess: string;
private strategies: IStrategy[];
private analysisResult: IFileAnalysis;
constructor(filePath: string, strategies: IStrategy[]) {
this.fileToProcess = filePath;
this.strategies = strategies || [];
this.analysisResult = <IFileAnalysis>{ filePath: this.fileToProcess, strategiesResults: [] };
}
async run() {
if (this.fileToProcess) {
let program = fs.readFileSync(this.fileToProcess, 'utf8');
program = program.replace(/#include\s+\"(.*)\"/g, '_include ("asd")');
try {
const ast = esprima.parseScript(program, { loc: true });
for (var strategy of this.strategies) {
let strategyResult = strategy.process(ast);
this.analysisResult.strategiesResults.push(strategyResult);
}
} catch (err) {
console.error('>>> Pss!! Error processing file ' + this.fileToProcess, ' err = ', err);
}
}
else
console.error('>>> Pss!! I do not have a file to analyze');
}
getResult(): IFileAnalysis {
return this.analysisResult;
}
}
|
c73ebe354125bfeb13ef4cd7465582f5cbb2a3eb
|
TypeScript
|
PacktPublishing/Angular-2-Application-Development
|
/Learning Angular 2/chapter_02/examples/example_27.ts
| 2.5625
| 3
|
interface Vehicle {
make: string;
}
class Car implements Vehicle {
// Compiler will raise a warning if this property is not declared
make: string;
}
|
b49223f6435b1175c36ccec7fe4d773d8be69ba6
|
TypeScript
|
stungkit/ignite
|
/boilerplate/app/models/helpers/withSetPropAction.ts
| 3.703125
| 4
|
import { IStateTreeNode, SnapshotIn } from "mobx-state-tree"
/**
* If you include this in your model in an action() block just under your props,
* it'll allow you to set property values directly while retaining type safety
* and also is executed in an action. This is useful because often you find yourself
* making a lot of repetitive setter actions that only update one prop.
*
* E.g.:
*
* const UserModel = types.model("User")
* .props({
* name: types.string,
* age: types.number
* })
* .actions(withSetPropAction)
*
* const user = UserModel.create({ name: "Jamon", age: 40 })
*
* user.setProp("name", "John") // no type error
* user.setProp("age", 30) // no type error
* user.setProp("age", "30") // type error -- must be number
*/
export const withSetPropAction = <T extends IStateTreeNode>(mstInstance: T) => ({
// generic setter for all properties
setProp<K extends keyof SnapshotIn<T>, V extends SnapshotIn<T>[K]>(field: K, newValue: V) {
// @ts-ignore - for some reason TS complains about this, but it still works fine
mstInstance[field] = newValue
},
})
|
665bb564ab9a8a3db310fa8adc84b86692e5362b
|
TypeScript
|
Gharaibeh/lazy-web-app
|
/server/models/user.model.ts
| 2.59375
| 3
|
import * as mongoose from 'mongoose';
(<any>mongoose).Promise = Promise;
const Schema = mongoose.Schema;
const UserSchema = new Schema({
givenName: {type: String},
familyName: {type: String},
email: {type: String},
emailConfirmed: {type: Boolean, default: false},
timeRegistered: {type: Date, default: Date.now},
isAdmin: {type: Boolean, default: false},
profileImage: {type: String},
}
);
UserSchema.index({displayUsername: 1});
UserSchema.index({email: 1});
/**
* removes secret data we don't want to send to the front-end
* @return {*}
*/
UserSchema.methods.frontendData = function() {
return {
id: this._id,
givenName: this.givenName,
familyName: this.familyName,
email: this.email,
emailConfirmed: this.emailConfirmed,
timeRegistered: this.timeRegistered,
isAdmin: this.isAdmin,
profileImage: this.profileImage,
};
};
module.exports = mongoose.model('User', UserSchema);
|
98d97a1febcb1420a7957d0224717fe02b22f850
|
TypeScript
|
Sienkiewicz/launch_graphs
|
/helpers/useResizeObserver.ts
| 2.6875
| 3
|
import { useEffect, useState } from "react"
export const useResizeObserver = ref => {
const [dimensions, setDimensions] = useState<{
width: number
height: number
}>({ width: 500, height: 500 })
useEffect(() => {
const observeTarget = ref.current
const resizeObserver = new ResizeObserver(entries => {
entries.forEach(entire => {
const path = entire.contentRect
setDimensions({ width: path.width, height: path.height })
})
})
resizeObserver.observe(observeTarget)
return () => {
resizeObserver.unobserve(observeTarget)
}
}, [ref])
return dimensions
}
|
88b6963604b5cb7f03eed689e3f8acc2bd38befd
|
TypeScript
|
gingermusketeer/toy-robot
|
/src/robot.ts
| 3.671875
| 4
|
// Table is 5x5 so we limit the x and y to be between 0 and 4
const MAX_INDEX = 4;
const HEADINGS = ["NORTH", "EAST", "SOUTH", "WEST"];
enum Command {
MOVE = "MOVE",
LEFT = "LEFT",
RIGHT = "RIGHT",
REPORT = "REPORT",
PLACE = "PLACE",
}
enum Heading {
NORTH,
EAST,
SOUTH,
WEST,
}
type Position = [number, number, Heading];
export default class Robot {
#position: Position | null = null;
perform(task: string): string | null {
const [command, args] = this.#parseTask(task);
const ignoreCommand = this.#position == null && command != Command.PLACE;
if (command == null || ignoreCommand) {
return null;
}
// Now we have a valid command but the args may be invalid.
return this[command.toLowerCase()](args);
}
place(args: string | null): void {
const [x, y, directionStr] = args.split(",");
const direction = HEADINGS.indexOf(directionStr);
if (direction < 0) {
return;
}
this.#position = [Number.parseInt(x), Number.parseInt(y), direction];
}
move(): void {
const [x, y, direction] = this.#position;
let yModifier = 0;
let xModifier = 0;
if (direction % 2 === 0) {
// Heading north or south
yModifier = direction == Heading.NORTH ? 1 : -1;
} else {
// Heading east or west
xModifier = direction == Heading.EAST ? 1 : -1;
}
let newPosition: Position = [x + xModifier, y + yModifier, direction];
const [newX, newY] = newPosition;
if (this.#validatePosition(newX, newY)) {
this.#position = newPosition;
}
}
left(): void {
const [x, y, direction] = this.#position;
const newDirection = direction === 0 ? HEADINGS.length - 1 : direction - 1;
this.#position = [x, y, newDirection];
}
right(): void {
const [x, y, direction] = this.#position;
const newDirection = (direction + 1) % HEADINGS.length;
this.#position = [x, y, newDirection];
}
report(): string {
if (this.#position == null) {
return "";
}
const [x, y, direction] = this.#position;
return `${x},${y},${HEADINGS[direction]}`;
}
#parseTask(task): [Command | null, string | null] {
const [commandStr, args] = task.split(" ");
return [Command[commandStr], args];
}
#validatePosition(x: number, y: number): boolean {
return x >= 0 && x <= MAX_INDEX && y >= 0 && y <= MAX_INDEX;
}
}
|
e6f4c452e83e83477234c6f8523bee181fdebf1b
|
TypeScript
|
Viktor19931/football-teams
|
/src/app/country/country.service.ts
| 2.59375
| 3
|
import { ICountry } from './country.interface';
export class CountryService {
countries: { [key: string]: ICountry };
constructor() {
console.log(this.getCountriesMetaData());
this.countries = this.getCountriesMetaData();
}
getCountriesMetaData(): {[key: string]: ICountry } {
return JSON.parse((<HTMLMetaElement>document.getElementsByName('countries')[0]).content);
}
getCountries(): { [key: string]: ICountry } {
return this.countries;
}
}
|
83a5dade9b5dfc895978b059eacf2f33a0c01f7c
|
TypeScript
|
Chunwol/Ts_NoticeBoard_API
|
/database/models/User.ts
| 2.765625
| 3
|
import { Model, DataTypes, Sequelize } from 'sequelize';
import Board from './Board';
import Comment from './Comment'
class User extends Model {
public pk!: string;
public id!: string;
public password!: string;
public name!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
public readonly boards?: Board[];
public readonly comments?: Comment[];
}
export const initUser = (sequelize: Sequelize) => {
User.init({
pk: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
unique: true,
primaryKey: true
},
id: {
type: DataTypes.STRING(20),
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING(50),
allowNull: false
},
name: {
type: DataTypes.STRING(10),
allowNull: false
}
}, {
tableName: 'users',
sequelize: sequelize,
timestamps : true
});
}
export function associateUser(): void {
User.hasMany(Board, {
foreignKey: "user_pk",
sourceKey: "pk",
});
User.hasMany(Comment, {
foreignKey: "user_pk",
sourceKey: "pk"
});
}
export default User;
|
bd86646b480230e4f41110a2e745fae5946a1ac6
|
TypeScript
|
sa77/exercism
|
/typescript/robot-name/robot-name.ts
| 3.515625
| 4
|
export default class RobotName {
private static CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
private static NUMBERS = '0123456789';
private takenNames: string[] = [];
public name: string;
constructor() {
this.name = this.getRobotName();
}
resetName = (): string => this.name = this.getRobotName()
getRobotName = (): string => {
const randomChar = (): string => RobotName.CHARACTERS[Math.floor(Math.random() * 25)]
const randomNum = (): string => RobotName.NUMBERS[Math.floor(Math.random() * 9)]
const repeat = (f: () => string, n: number): string[] => Array(n).fill('').map(() => f())
let tmpName = '';
while(true) {
tmpName = repeat(() => randomChar(), 2).join('') +
repeat(() => randomNum(), 3).join('')
if (!this.takenNames.includes(tmpName)) break;
}
this.takenNames.push(tmpName);
return tmpName;
}
}
|
639474d8622701e46e9d734ba895270f53f4853c
|
TypeScript
|
markusbohl/fluent-ts-validator
|
/src/regression/Issue4.spec.ts
| 3.46875
| 3
|
/*
* Regression tests for https://github.com/markusbohl/fluent-ts-validator/issues/4
*/
import {AbstractValidator} from "../AbstractValidator";
describe("Issue 4", () => {
let validator: AbstractValidator<ClassA>;
beforeEach(() => {
validator = new ClassAValidator();
});
describe("AbstractValidator.validate()", () => {
it("should fail when name is too long", () => {
const dto = new ClassA();
dto.name = "01234567891";
const result = validator.validate(dto);
expect(result.isInvalid()).toBe(true);
expect(result.getFailureMessages()).toContain("name must be 1 to 10 characters");
});
it("should not fail when name is empty due to whenNotEmpty-option", () => {
const dto = new ClassA();
const result = validator.validate(dto);
expect(result.isValid()).toBe(true);
});
it("should fail when number array contains numbers less than 6", () => {
const dto = new ClassA();
dto.nbrs = [1];
const result = validator.validate(dto);
expect(result.isInvalid()).toBe(true);
expect(result.getFailureMessages()).toContain("must have 2 elements");
});
it("should not fail when number array is empty due to whenNotEmpty-option", () => {
const dto = new ClassA();
const result = validator.validate(dto);
expect(result.isValid()).toBe(true);
});
it("should fail when string array contains elements which are not completely uppercase", () => {
const dto = new ClassA();
dto.strArray = ["ABC", "xyz"];
const result = validator.validate(dto);
expect(result.isInvalid()).toBe(true);
expect(result.getFailureMessages()).toContain("string must be all uppercase");
});
it("should fail when string array contains elements which are not completely uppercase next to empty element", () => {
const dto = new ClassA();
dto.strArray = ["", "xyz"];
const result = validator.validate(dto);
expect(result.isInvalid()).toBe(true);
expect(result.getFailureMessages()).toContain("string must be all uppercase");
});
it("should not fail when string array is empty due to whenNotEmpty-option", () => {
const dto = new ClassA();
dto.strArray = ["ABC", ""];
const result = validator.validate(dto);
expect(result.isValid()).toBe(true);
});
});
});
class ClassA {
name: string = "";
nbrs: number[] = [];
strArray: string[] = [];
}
export class ClassAValidator extends AbstractValidator<ClassA> {
constructor() {
super();
this.validateIfString(dto => dto.name)
.hasLengthBetween(1, 10)
.whenNotEmpty()
.withFailureMessage("name must be 1 to 10 characters");
this.validateIfIterable(dto => dto.nbrs)
.hasNumberOfElements(2)
.whenNotEmpty()
.withFailureMessage("must have 2 elements");
this.validateIfEachString(dto => dto.strArray)
.isUppercase()
.whenNotEmpty()
.withFailureMessage("string must be all uppercase");
}
}
|
555e3bcb77bb754ecc3743d1bb8710344e29cef4
|
TypeScript
|
colapiombo/link-station
|
/src/linkstation.ts
| 3.546875
| 4
|
/**
* Class use to calculate the suitable link station for a device at given point [x,y]
* @class
* @classdesc Class used to find the best link station for a device at given point in n-dimensional space
*/
export default class LinkPowerCalculator {
/**
* private variabile use to store the station
* @private
* @type {Object}
*/
private stations: Station[];
/**
* private variabile use to store the device
* @private
* @type {Object}
*/
private devices: Device[];
/**
* private variabile use to store the costum formula
* @private
* @type {function}
*/
private costumFormula:any;
/**
* @constructor
*/
constructor(){
this.stations = [];
this.devices = [];
this.costumFormula = null;
}
/**
* function use to set station
* @function setStation
* @throws {ValidationError} If the dataset is not a array
* @param {[]} stations array of values
*/
setStation(stations:[]){
if(stations && Array.isArray(stations)){
stations.forEach((stationData, index)=>{
this.stations[index] = new Station(stationData);
});
}else{
throw new ValidationError('the stations dataset must be an array');
}
}
/**
* function use to get station
* @function getStation
* @return {Station[]} - return all stations
*/
getStation(){
return this.stations;
}
/**
* function use to set device
* @function setDevice
* @throws {ValidationError} If the dataset is not a array
* @param {[]} devices array of values
*/
setDevice(devices) {
if (devices && Array.isArray(devices)) {
devices.forEach((deviceData, index)=>{
this.devices[index] = new Device(deviceData);
});
}else{
throw new ValidationError('the devices dataset must be an array');
}
}
/**
* function use to get station
* @function getDevice
* @return {Device[]} - return all devices
*/
getDevice(){
return this.devices;
}
/**
* function use to set custom formula a link station
* @function setCustomFormula
* @throws {ValidationError} If the input is not a function
* @return {function}costumFormula - new formula
*/
setCustomFormula(costumFormula){
if(this.checkCostumFormula(costumFormula)) {
this.costumFormula = costumFormula;
}
return true;
}
/**
* function use to reset the formula
* @function resetFormula
* @return {boolean} true value for the correct execution
*/
resetFormula(){
this.costumFormula = null;
return true;
}
/**
* main function called for calculate the link station
* @function bestLinkStation
*/
bestLinkStation(){
if(this.stations.length == 0 || this.devices.length == 0){
console.log('dataset incomplete check device/station');
}else{
if(this.costumFormula===null) {
this.devices.forEach((device) =>{
this.defaultFormula(device);
});
}else{
this.costumFormula(this);
}
}
}
/**
* function used for calculate the link station
* @function defaultFormula
* @param {Device} device device object
*/
defaultFormula(device) {
let stationDistance = this.calculateBestStationDistance(device);
if (stationDistance == null || stationDistance.distance >= this.stations[stationDistance.id].reach) {
console.log('No link station within reach for point');
} else {
let power = this.calculatePower(this.stations[stationDistance.id].reach, stationDistance.distance );
console.log("Best link station for point (" + (<any>Object).values(device) + ") is " + "(" + (<any>Object).values(this.stations[stationDistance.id]) + ") with power =" + power);
}
}
/**
* function used for calculate the best distance for the selected device
* @function defaultFormula
* @param {Device} device device object
* @return {object| null}
*/
calculateBestStationDistance(device){
var distance = [];
var stationId;
var euclideanDistance;
this.stations.forEach((station, index) => {
if(station.reach !== 0) {
distance[index] = this.squaredEuclideanDistance(station, device);
}
});
if(distance.length == 0){
return null;
}else{
stationId = this.stationWithLessDistance(distance);
euclideanDistance = this.euclideanDistance(distance[stationId]);
}
return {'id':stationId,'distance':euclideanDistance};
}
/**
* function used for calculate the best distance for the selected device
* @function calculatePower
* @param {number} reach value of station's reach
* @param {number} euclideanDistance value of euclidean distance
* @return {string} A string representing the power number using fixed-point notation.
*/
calculatePower(reach,euclideanDistance ){
let power = reach - euclideanDistance;
return (power*power).toFixed(4);
}
/**
* function used to find the station with the less distance
* @function stationWithLessDistance
* @param {[]} distance value of station's reach
* @return {number} station index
*/
stationWithLessDistance(distance) {
var stationId = null;
distance.forEach((value, index) => {
if(typeof value !== 'undefined' ){
if(stationId == null ){
stationId = index;
}else if (value < distance[stationId] ) {
stationId = index;
}
}
});
return stationId;
}
/**
* function used to calculate the euclidean Distance
* @function euclideanDistance
* @param {[]} squaredEuclideanDistance squared euclidean distance
* @return {number} euclidean Distance
*/
euclideanDistance(squaredEuclideanDistance){
return Math.sqrt(squaredEuclideanDistance);
}
/**
* function used to calculate the euclidean Distance
* @function euclideanDistance
* @param {Station} station station value
* @param {Device} device device value
* @return {number} squared euclidean distance
*/
squaredEuclideanDistance(station:Station,device:Device){
// if the two dataset have a different dimension the sistem choose the minimum value
let dimension = Math.min(station.dimension, device.dimension);
var distance = 0;
for (let coordinate = 0; coordinate < dimension; coordinate++) {
let diff = station[coordinate] - device[coordinate];
// avoid Math.Pow() function call to decrease computing time and improve performance
distance += (diff * diff);
}
return distance;
}
/**
* function use to check if the callback function is a function
* @function subscriptionFunction
* @param {function} callback - Function to call when the event name is triggered
* @return {boolean} - return true if everything is ok
* @throws {ValidationError} If the function is not a function data type.
*/
checkCostumFormula(callback?:any) {
if (callback && typeof callback !== 'function'){
throw new ValidationError("custom formula is not a function");
}
return true;
}
}
/**
* Class use to display a message error
* @class
* @classdesc Class use to validate the error that extends a Error class.
*/
class ValidationError extends Error {
name:string;
constructor(public message: string) {
super(message);
this.name = "Validation Error";
}
}
/**
* Class use save the point [x,y,z...ecc ]
* @class
* @classdesc Class use store points
*/
class DataSet{
/**
* value use to store the dimension of a mathematical space
* @type {number}
*/
dimension:number;
/**
* function use to check if the input value is an array of number
* @function checkInputIsArray
* @param {[]} input - Function to call when the event name is triggered
* @return {boolean} - return true if everything is ok
* @throws {ValidationError} If the input is not an array of number.
*/
checkInputIsArray(input){
if(!Array.isArray(input)) {
throw new ValidationError('the dataset must be an array');
}
let notNumber = input.filter(item => typeof item !== 'number');
if(notNumber.length!==0){
throw new ValidationError('the dataset data must be an array of number');
}
return true;
}
}
/**
* Class use save the station
* @class
* @classdesc Class use store station's points
* @implements DataSet
*/
class Station extends DataSet{
/**
* value of the station's reach
* @type {number}
*/
reach:number;
constructor(stationData :[]){
super();
if(this.checkInputIsArray(stationData)&&this.checkIsStation(stationData)){
this.dimension = stationData.length-1;
stationData.forEach((value, index) => {
if(this.dimension == index ){
this.reach = value;
}else{
this[index] = value;
}
});
}
this.reachability();
}
/**
* function use to check if the input value is an array of number
* @function checkInputIsArray
* @param {[]} input - Function to call when the event name is triggered
* @return {boolean} - return true if everything is ok
* @throws {ValidationError} If the input is not an array of number.
*/
checkIsStation(input){
if(input.length<2) {
throw new ValidationError('the array must contain at least level 2 values (coordinate,reach)');
}
return true;
}
/**
* function use to verify the reachability of the station
* @function reachability
* @throws {ValidationError} If the value of reach is zero
*/
reachability(){
if(this.reach == 0){
throw new ValidationError('this station is not reachable because the value is = 0');
}
}
}
/**
* Class use save the device
* @class
* @classdesc Class use store device's points
* @implements DataSet
*/
class Device extends DataSet{
constructor(deviceData :[]){
super();
if(this.checkInputIsArray(deviceData)){
this.dimension = deviceData.length;
deviceData.forEach((value, index) => {
this[index] = value;
});
}
}
}
|
39c4f922f19b8cb9817d7f19f6578c41aaa0e75f
|
TypeScript
|
fortil/get-users-github
|
/src/store/epics.ts
| 2.578125
| 3
|
import { combineEpics, ofType } from 'redux-observable';
import { of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { Action } from 'redux';
import { mergeMap, map, catchError } from 'rxjs/operators';
import { Types, UserTypes } from './actions';
const gitHubUrl = 'https://api.github.com/users/';
interface IAction extends Action {
type: UserTypes.GET_USER;
userName: string;
}
const getJSON = (userName: string) =>
ajax
.getJSON(`${gitHubUrl}${userName}`)
.pipe(
catchError<any, any>((error) => {
console.error(error);
return of([]);
})
);
const getUsers = (action$: any, $state: any) => action$.pipe(
ofType(Types.GET_USER),
mergeMap((action: IAction) => {
const user = $state.value.API.USERS.filter(({ login }: { login: string }) => login === action.userName);
if (user && user.length) {
return of({ type: Types.SET_USER, user: user[0] })
} else {
return getJSON(action.userName).pipe(
map((user) => ({ type: Types.SET_USER, user }))
);
}
})
);;
export default combineEpics(getUsers);
|
e4e834148feaa3bb8b25b0fe729b6406627b10b7
|
TypeScript
|
colyseus/schema
|
/test-external/MapSchemaMoveNullifyType.ts
| 2.828125
| 3
|
import { Schema, type, MapSchema } from "../src";
class State extends Schema {
@type({ map: "number" }) previous: MapSchema<number>;
@type({ map: "number" }) current: MapSchema<number>;
}
const state = new State();
let bytes: number[];
state.current = new MapSchema<number>();
state.current.set("0", 0);
state.previous = null;
bytes = Array.from(Uint8Array.from(Buffer.from(state.encode())));
console.log("MapSchemaMoveNullifyType =>");
console.log(`{ ${bytes.join(", ")} }`);
state.previous = state.current;
state.current = null;
bytes = Array.from(Uint8Array.from(Buffer.from(state.encode())));
console.log("MapSchemaMoveNullifyType =>");
console.log(`{ ${bytes.join(", ")} }`);
|
cd4f9740b48cccd8b938b5b1de5ac7dd5177450a
|
TypeScript
|
DimitarGaydardzhiev/EmployeeSystem-Angular
|
/front-end/src/app/core/store/reducers/employee.reducers.ts
| 2.9375
| 3
|
import * as employee from '../actions/employee.actions'
import { Employee } from '../../models/employee/employee.model';
import { ProfileInfo } from '../../models/employee/profile-info';
export interface State {
currentEmployees: Employee[],
formerEmployees: Employee[],
profileInfo: ProfileInfo
}
const initialState: State = {
currentEmployees: [],
formerEmployees: [],
profileInfo: new ProfileInfo()
}
export function reducer(state = initialState, action: employee.Actions): State {
switch (action.type) {
case employee.ActionTypes.GET_ALL_CURRENT_EMPLOYEES_SUCCESS: {
return Object.assign({}, state, {
currentEmployees: [...action.payload]
});
}
case employee.ActionTypes.GET_ALL_CURRENT_EMPLOYEES_FAIL: {
return Object.assign({}, state, {
currentEmployees: initialState.currentEmployees
});
}
case employee.ActionTypes.GET_ALL_FORMER_EMPLOYEES_SUCCESS: {
return Object.assign({}, state, {
formerEmployees: [...action.payload]
});
}
case employee.ActionTypes.GET_ALL_FORMER_EMPLOYEES_FAIL: {
return Object.assign({}, state, {
formerEmployees: initialState.formerEmployees
});
}
case employee.ActionTypes.GET_PROFILE_INFO_SUCCESS: {
return Object.assign({}, state, {
profileInfo: action.payload
});
}
case employee.ActionTypes.GET_PROFILE_INFO_FAIL: {
return Object.assign({}, state, {
profileInfo: initialState.profileInfo
});
}
default: {
return state;
}
}
}
export const getCurrentEmployees = (state: State) => state.currentEmployees
export const getFormerEmployees = (state: State) => state.formerEmployees
export const getProfileInfo = (state: State) => state.profileInfo
|
0a5628672e770571bb7c4ef17f7945f2c62f48a2
|
TypeScript
|
makutamoto/online-judging-web-client
|
/src/actions/index.ts
| 2.515625
| 3
|
import axios from 'axios';
import { DispatchType } from '../';
import { StateType } from '../reducers';
export const StatusAC = 0;
export const StatusWA = 1;
export const StatusRE = 2;
export const StatusTLE = 3;
export const StatusCE = 4;
export type Page = 'home' | 'contest_list' | 'contest' | 'task' | 'explanation';
export interface SetCurrentPageAction {
type: string,
page: Page,
}
export const setCurrentPage = (page: Page) => ({
type: 'SET_CURRENT_PAGE',
page,
});
export interface SetEditStateAction {
type: string,
state: boolean,
}
export const setEditState = (state: boolean) => ({
type: 'SET_EDIT_STATE',
state,
});
export interface SetEditBufferAction {
type: string,
buffer: any,
}
export const setEditBuffer = (buffer: any) => ({
type: 'SET_EDIT_BUFFER',
buffer,
});
export interface SetEditCallbackAction {
type: string,
callback: ((dispatch: DispatchType) => void) | null,
}
export const setEditCallback = (callback: ((dispatch: DispatchType) => void) | null) => ({
type: 'SET_EDIT_CALLBACK',
callback,
});
export const callEditCallback = () => (dispatch: DispatchType, getState: () => StateType) => {
return new Promise((resolve) => {
let state = getState();
if(state.edit.buffer !== null && state.edit.callback !== null) state.edit.callback(dispatch);
resolve();
});
};
export interface SystemOverview {
overview: string,
}
export interface RequestSystemOverviewAction {
type: string,
}
export const requestSystemOverview = () => ({
type: 'REQUEST_SYSTEM_OVERVIEW',
});
export interface ReceiveSystemOverviewAction {
type: string,
data: SystemOverview,
}
export const receiveSystemOverview = (data: SystemOverview) => ({
type: 'RECEIVE_SYSTEM_OVERVIEW',
data,
});
export const fetchSystemOverview = () => (dispatch: DispatchType) => {
dispatch(requestSystemOverview());
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8080/api/`)
.then((response) => {
dispatch(receiveSystemOverview(response.data));
resolve();
})
.catch(reject);
});
};
export const updateSystemOverview = () => (dispatch: DispatchType, getState: () => StateType) => {
return new Promise((resolve, reject) => {
let state = getState();
axios.put(`http://localhost:8080/api/`, { overview: state.edit.buffer })
.then(() => {
dispatch(fetchSystemOverview() as any);
resolve();
})
.catch(reject);
});
};
export interface ContestListRow {
id: string,
title: string,
}
export interface RequestContestListAction {
type: string,
}
export const requestContestList = () => ({
type: 'REQUEST_CONTEST_LIST',
});
export interface ReceiveContestListAction {
type: string,
list: ContestListRow[],
}
export const receiveContestList = (list: ContestListRow[]) => ({
type: 'RECEIVE_CONTEST_LIST',
list,
});
export const fetchContestList = () => (dispatch: DispatchType) => {
dispatch(requestContestList());
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8080/api/contests/`)
.then((response) => {
dispatch(receiveContestList(response.data));
resolve();
})
.catch(reject);
});
};
export interface ContestInfo {
title: string,
description: string,
explanation: string,
}
export interface RequestContestInfoAction {
type: string,
}
export const requestContestInfo = () => ({
type: 'REQUEST_CONTEST_INFO',
});
export interface ReceiveContestInfoAction {
type: string,
data: ContestInfo,
}
export const receiveContestInfo = (data: ContestInfo) => ({
type: 'RECEIVE_CONTEST_INFO',
data,
});
export const fetchContestInfo = (contest: string) => (dispatch: DispatchType) => {
dispatch(requestContestInfo());
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8080/api/contests/${contest}`)
.then((response) => {
dispatch(receiveContestInfo(response.data));
resolve();
})
.catch(reject);
});
};
export const updateContestOverview = (contest: string) => (dispatch: DispatchType, getState: () => StateType) => {
return new Promise((resolve, reject) => {
let state = getState();
axios.put(`http://localhost:8080/api/contests/${contest}`, { description: state.edit.buffer })
.then(() => {
dispatch(fetchContestInfo(contest) as any);
resolve();
})
.catch(reject);
});
};
export const updateContestExplanation = (contest: string) => (dispatch: DispatchType, getState: () => StateType) => {
return new Promise((resolve, reject) => {
let state = getState();
axios.put(`http://localhost:8080/api/contests/${contest}/explanation`, { explanation: state.edit.buffer })
.then(() => {
dispatch(fetchContestInfo(contest) as any);
resolve();
})
.catch(reject);
});
};
export interface TaskListRow {
title: string,
time_limit: number,
}
export interface RequestTaskListAction {
type: string,
}
export const requestTaskList = () => ({
type: "REQUEST_TASK_LIST",
});
export interface ReceiveTaskListAction {
type: string,
data: TaskListRow[],
}
export const receiveTaskList = (data: TaskListRow[]) => ({
type: 'RECEIVE_TASK_LIST',
data,
});
export const fetchTaskList = (contest: string) => (dispatch: DispatchType) => {
dispatch(requestTaskData());
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8080/api/contests/${contest}/tasks/`)
.then((response) => {
let data: TaskListRow[] = response.data;
data.forEach((row, i) => row.title = `${String.fromCharCode('A'.charCodeAt(0) + i)}. ${row.title}`);
dispatch(receiveTaskList(response.data));
resolve();
})
.catch(reject);
});
};
export interface RequestCodeSubmissionAction {
type: string,
}
export const requestCodeSubmission = () => ({
type: 'REQUEST_CODE_SUBMISSION',
});
export interface ReceiveCodeSubmissionAction {
type: string,
}
export const receiveCodeSubmission = () => ({
type: 'RECEIVE_CODE_SUBMISSION',
});
export interface SetCodeLangAction {
type: string,
lang: string,
}
export const setCodeLang = (lang: string) => ({
type: 'SET_CODE_LANG',
lang,
});
export interface SetCodeAction {
type: string,
code: string,
}
export const setCode = (code: string) => ({
type: 'SET_CODE',
code,
});
export interface TaskData {
problem: string,
time_limit: number,
}
export interface RequestTaskDataAction {
type: string,
}
export const requestTaskData = () => ({
type: 'REQUEST_TASK_DATA',
});
export interface ReceiveTaskDataAction {
type: string,
data: TaskData,
}
export const receiveTaskData = (data: TaskData) => ({
type: 'RECEIVE_TASK_DATA',
data,
});
export const fetchTaskData = (contest: string, task: number) => (dispatch: DispatchType) => {
dispatch(requestTaskData());
return new Promise((resolve, reject) => {
axios.get(`http://localhost:8080/api/contests/${contest}/tasks/${task}`)
.then((response) => {
dispatch(receiveTaskData(response.data));
resolve();
})
.catch(reject);
});
};
export const updateTaskData = (contest: string, task: number) => (dispatch: DispatchType, getState: () => StateType) => {
return new Promise((resolve, reject) => {
let state = getState();
axios.put(`http://localhost:8080/api/contests/${contest}/tasks/${task}`, { problem: state.edit.buffer })
.then(() => {
dispatch(fetchTaskData(contest, task) as any);
resolve();
})
.catch(reject);
});
};
export interface ResultData {
whole_result: number,
result: number,
time: number,
memory: number,
current_case: number,
whole_case: number,
}
export interface Result {
isFetching: boolean,
id: string,
contest: string,
task: string,
data: ResultData | null,
details: Detail | null,
}
export interface DetailRow {
title: string,
result: number,
time: number,
memory: number,
}
export interface Detail {
max_time: number,
max_memory: number,
lang: string,
code: string,
compile_error: string,
details: DetailRow[] | null,
}
export interface RequestResultAction {
type: string,
id: string,
}
export const requestResult = (id: string) => ({
type: 'REQUEST_RESULT',
id,
});
export interface UpdateResultAction {
type: string,
id: string,
data: ResultData,
}
export const updateResult = (id: string, data: ResultData) => ({
type: 'UPDATE_RESULT',
id, data,
});
export interface ReceiveResultAction {
type: string,
id: string,
}
export const receiveResult = (id: string) => ({
type: 'RECEIVE_RESULT',
id,
});
export interface ReceiveResultDetailsAction {
type: string,
id: string,
details: Detail,
}
export const receiveResultDetails = (id: string, details: Detail) => ({
type: 'RECEIVE_RESULT_DETAILS',
id, details,
});
export const fetchResult = (id: string) => (dispatch: DispatchType, getState: any) => (
new Promise((resolve, reject) => {
let socket: WebSocket;
dispatch(requestResult(id));
socket = new WebSocket(`ws://localhost:8080/api/submissions/realtime/${id}`);
socket.addEventListener('message', (e) => {
dispatch(updateResult(id, JSON.parse(e.data)));
});
socket.addEventListener('error', reject);
socket.addEventListener('close', () => {
axios.get(`http://localhost:8080/api/submissions/details/${id}`)
.then((response) => {
dispatch(receiveResultDetails(id, response.data));
dispatch(receiveResult(id));
resolve();
})
.catch(reject);
});
})
);
export interface Submission {
lang: string,
code: string,
}
export const submitResult = (contest: string, task: number, submission: Submission) => (dispatch: DispatchType) => {
dispatch(requestCodeSubmission());
return axios.post(`http://localhost:8080/api/contests/${contest}/tasks/${task}`, submission)
.then((response) => {
dispatch(receiveCodeSubmission());
dispatch(fetchResult(response.data.id) as any);
});
};
|
22e24243dc5184a0dea10fb8f1112fe4532207fb
|
TypeScript
|
lexdevel/PostFX
|
/src/platform/Buffer.ts
| 2.8125
| 3
|
import { AbstractPlatformEntity } from "./AbstractPlatformEntity";
import { GL } from "../core/GL";
/**
* The buffer class.
*/
export abstract class Buffer extends AbstractPlatformEntity<WebGLBuffer> {
protected target: number;
/**
* Constructor.
* @param target The buffer target
*/
public constructor(target: number) {
super(GL.createBuffer());
this.target = target;
}
/**
* Write the specified buffer data to the buffer.
* @param bufferData The buffer data
*/
public abstract bufferData(bufferData: number[]);
public attach(): void { GL.bindBuffer(this.target, this.instance); }
public detach(): void { GL.bindBuffer(this.target, null); }
}
|
f20614ec7d774fb2d610bdaa4a8d37c8fa74f4b8
|
TypeScript
|
stupidsongshu/chat
|
/src/utils/http.ts
| 2.609375
| 3
|
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'
import qs from 'qs'
import { Message, Loading } from 'element-ui'
import { ElLoadingComponent } from 'element-ui/types/loading'
import router from '@/router'
import { baseURL, getTokenKey } from '@/utils'
type Headers = {
[key: string]: string
}
interface IHttpOptions {
method?: Method;
loading?: boolean;
headers?: Headers;
type?: string;
[index: string]: unknown;
}
interface IParams {
[key: string]: any
}
interface IHttpConfig {
url: string;
params?: IParams;
options?: IHttpOptions;
}
const axiosInstance = axios.create({
baseURL
})
const awaitWrap = (promise: Promise<any>) => promise.then((res: any) => [null, res]).catch((err: any) => [err, null])
const http = (httpConfig: IHttpConfig) => new Promise((resolve, reject) => {
const { url, params = {}, options } = httpConfig
const method = options?.method || 'POST'
const loading = options?.loading !== undefined ? options.loading : false
let loadingInstance: ElLoadingComponent
if (loading) {
loadingInstance = Loading.service({
fullscreen: true
})
}
const userName = router.currentRoute.query.user
const token = window.localStorage.getItem(getTokenKey(userName as string))
if (token) {
params['token'] = token
}
const requestConfig: AxiosRequestConfig = {
method,
url,
headers: options?.headers,
data: options?.type === 'upload' ? params : qs.stringify(params)
}
axiosInstance(requestConfig).then((res: AxiosResponse) => {
// console.log('==res==', url, res)
if (res.status === 200) {
if (res.data.code === 0) {
resolve(res.data)
} else {
Message({
message: res.data.msg || '服务异常,请稍后再试',
type: 'warning'
})
reject(res.data)
}
} else {
Message({
message: '服务异常,请稍后再试~',
type: 'error'
})
reject(res)
}
}).catch((err) => {
Message({
message: '服务异常,请稍后再试!',
type: 'error'
})
reject(err)
}).finally(() => {
if (loadingInstance) {
loadingInstance.close()
}
})
})
export default (config: IHttpConfig): Promise<any[]> => awaitWrap(http(config))
|
09caa2c0a880a206df7f6dd0b8f55ecc7cff0165
|
TypeScript
|
vanelo/hospital-backend-nestjs
|
/src/auth/user.entity.ts
| 2.625
| 3
|
import { Expose } from "class-transformer";
import { ClinicalSpecialty } from "src/clinical-specialty/clinical-specialty.entity";
import { Consultation } from "src/consultation/consultation.entity";
import { Exam } from "src/exam/exam.entity";
import { Column, Entity, ManyToMany, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { PaginationResult } from "src/pagination/paginator";
export enum SexEnum{
Other=1,
Male,
Female
}
@Entity()
export class User {
constructor(partial?: Partial<User>) {
Object.assign(this, partial);
}
@PrimaryGeneratedColumn()
@Expose()
id: number;
@Column({unique: true})
@Expose()
username: string;
@Column()
password: string;
@Column()
@Expose()
firstName: string;
@Column()
@Expose()
lastName: string;
@Column({
nullable: true
})
@Expose()
dni: string;
@Column({unique: true})
@Expose()
email: string;
@Column({
nullable: true
})
@Expose()
phone: string;
@Column('enum', {
enum: SexEnum,
default: SexEnum.Other
})
@Expose()
sex: SexEnum;
@Column({
nullable: true
})
@Expose()
birthdate: Date;
@Column({
nullable: true
})
@Expose()
address: string;
@Column({
nullable: true
})
@Expose()
profesionalRegisterNumber: string;
@ManyToMany(()=> ClinicalSpecialty, (clinicalSpecialty)=> clinicalSpecialty.users)
@Expose()
clinicalSpecialties: ClinicalSpecialty[];
@OneToMany(() => Consultation, (consultation) => consultation.patient, {
cascade: true
})
@Expose()
patientConsultations: Consultation[]
@OneToMany(() => Consultation, (consultation) => consultation.doctor, {
cascade: true
})
@Expose()
doctorConsultations: User[]
@OneToMany(() => Exam, (exam) => exam.patient, {
cascade: true
})
@Expose()
patientExams: Consultation[]
@OneToMany(() => Exam, (exam) => exam.doctor, {
cascade: true
})
@Expose()
doctorExams: User[]
}
export type PaginatedUsers = PaginationResult<User>;
|
79d1ff8d890df6161caf305f2cfb59bdaa241bae
|
TypeScript
|
comett2/ngDetect
|
/src/app/leftsidebar/delay/DelayComponent.ts
| 2.515625
| 3
|
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { DelayService } from './DelayService';
import { DelayType } from './DelayType';
@Component({
selector: 'sp-delay',
templateUrl: `DelayComponent.html`,
styleUrls: [`DelayComponent.css`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DelayComponent implements OnInit {
label = 'delay';
form: any;
type: DelayType;
constructor(private formBuilder: FormBuilder,
private delayService: DelayService,
private changeDetectorRef: ChangeDetectorRef) {
}
ngOnInit() {
this.form = this.formBuilder.group({
'delay': [this.delayService.getDelay(), [Validators.required, Validators.max(10), Validators.min(0)]]
});
this.form.valueChanges
.subscribe(form => {
this.delayService.setDelay(form.delay);
});
this.delayService
.getDelayType()
.subscribe((type: DelayType) => {
this.type = type;
console.log(this.isDelayTime())
console.log(this.isDelayStepByStep())
this.changeDetectorRef.detectChanges();
});
}
selectTimeType(type: DelayType): void {
this.delayService.setDelayType(DelayType.TIME);
}
selectStepByStep(type: DelayType): void {
this.delayService.setDelayType(DelayType.STEP_BY_STEP);
}
isDelayTime(): boolean {
console.log('istoime')
console.log(this.type === DelayType.TIME)
return this.type === DelayType.TIME;
}
isDelayStepByStep(): boolean {
return this.type === DelayType.STEP_BY_STEP;
}
}
|
25a9448ef8aff19d41e00c76ca1e9d030d070089
|
TypeScript
|
AndersonKV/react-typescript-instagram-clone
|
/backend/src/controllers/SearchController.ts
| 2.5625
| 3
|
import { Request, Response } from "express";
import { currentDate, hoursFormated } from "../utils/util";
import User, { UserInterface } from "../models/User";
import Post from "../models/Post";
import Following, { FollowingInterface } from "../models/Following";
import Like from "../models/Like";
import {
GET_ALL_USER_AND_FOLLOWERS_WITH_POSTS,
formatedStringWithHashtag,
} from "../utils/util";
import Comment, { CommentInterface } from "../models/Comment";
export default {
async searchWord(req: Request, res: Response): Promise<Response> {
const { word } = req.body.params;
if (word[0] === "#") {
const posts = await Post.find({ post_text: new RegExp(word, "g") });
const initArr: any = [];
for (let i = 0; i < posts.length; i++) {
const hash = posts[i].post_text.split(" ");
for (let t = 0; t < hash.length; t++) {
if (hash[t][0] === "#") {
const str = hash[t].substring(1);
const obj = str;
initArr.push(obj);
}
}
}
const counts: any = {};
initArr.forEach(function (x: any) {
counts[x] = (counts[x] || 0) + 1;
});
const entries = Object.entries(counts);
const arrFinal: any = [];
entries.forEach((element: any) => {
arrFinal.push({ name: element[0], quantity: element[1] });
});
return res.status(200).json({ posts: arrFinal });
} else {
const users = await User.find({ user: new RegExp(word, "i") });
return res.status(200).json({ users: users });
}
// } else {
// const users = await User.find({ user: new RegExp(word, "i") });
// console.log("users");
// console.log(users);
// return res.status(200).json({ users: users });
// }
},
async searchPosts(req: Request, res: Response): Promise<Response> {
const { hashWord } = req.body.params;
if (Boolean(hashWord) === true) {
const posts = await Post.find({ post_text: new RegExp(hashWord, "i") });
const sortedPost = posts.sort(function (p1, p2) {
if (p1.created_at < p2.created_at) {
return 1;
} else {
return -1;
}
});
const arr = [];
for (let i = 0; i < sortedPost.length; i++) {
const likes = await Like.find({ id_post: sortedPost[i]._id });
const comments = await Comment.find({ id_post: sortedPost[i]._id });
const users = await User.find({ _id: sortedPost[i].id_user });
let path = sortedPost[i].post_image as any;
arr.push({
post_image: path[0],
likes: likes.length,
comments: comments.length,
user: users[0].user,
_id: sortedPost[i]._id,
});
}
return res.status(200).json({ posts: arr });
}
// } else {
// const users = await User.find({ user: new RegExp(word, "i") });
// console.log("users");
// console.log(users);
// return res.status(200).json({ users: users });
// }
},
async AllPosts(req: Request, res: Response): Promise<Response> {
const posts = await Post.find();
const sortedPost = posts.sort(function (p1, p2) {
if (p1.created_at < p2.created_at) {
return 1;
} else {
return -1;
}
});
const arr = [];
for (let i = 0; i < sortedPost.length; i++) {
const likes = await Like.find({ id_post: sortedPost[i]._id });
const comments = await Comment.find({ id_post: sortedPost[i]._id });
const users = await User.find({ _id: sortedPost[i].id_user });
let path = sortedPost[i].post_image as any;
arr.push({
post_image: path[0],
likes: likes.length,
comments: comments.length,
user: users[0].user,
_id: sortedPost[i]._id,
});
}
return res.status(200).json({ posts: arr });
},
};
|
bb722f215b89eb4c5b02515ffa82fd6b90ec1b12
|
TypeScript
|
SinghDigamber/angular-template-driven-form
|
/src/app/app.component.ts
| 2.625
| 3
|
import { Component } from '@angular/core';
export class User {
public name!: string;
public email!: string;
public password!: string;
public hobbies!: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
model = new User();
Hobbies: string[] = [
'Acrobatics',
'Acting',
'Animation',
'Astronomy',
'Baking',
];
constructor() {}
onSubmit(form: any) {
console.log(form.value);
}
}
|
07299333cc3ece45bf80975f196426b2f6d2422b
|
TypeScript
|
silviuaavram/leetcode-puzzles
|
/src/puzzles/strings/add-strings.ts
| 3.78125
| 4
|
/**
* https://leetcode.com/problems/add-strings/
*/
export function addStrings(num1: string, num2: string): string {
if (!num1.length) {
return num2
}
if (!num2.length) {
return num1
}
const input1 = num1
.split('')
.reverse()
.join('')
const input2 = num2
.split('')
.reverse()
.join('')
const minLength = Math.min(input1.length, input2.length)
const maxLength = Math.max(input1.length, input2.length)
const maxInput = input1.length > input2.length ? input1 : input2
let carryOver = false
const result: string[] = []
for (let index = 0; index < minLength; index++) {
const digit1 = Number(input1[index])
const digit2 = Number(input2[index])
const sum = digit1 + digit2 + (carryOver ? 1 : 0)
if (sum > 9) {
carryOver = true
result.push(String(sum % 10))
} else {
carryOver = false
result.push(String(sum))
}
}
for (let index = minLength; index < maxLength; index++) {
if (carryOver) {
if (maxInput[index] === '9') {
result.push('0')
} else {
result.push(String(Number(maxInput[index]) + 1))
carryOver = false
}
} else {
result.push(maxInput[index])
}
}
if (carryOver) {
result.push('1')
}
return result.reverse().join('')
}
|
18012e44232ca67635dd3ef3865424932bec5d9c
|
TypeScript
|
galileopy/programando_con_react
|
/src/redux/reducers/tarea.ts
| 2.515625
| 3
|
import { Acciones } from "../actions";
import { IdsAcciones } from "../actionTypes";
import { EstadoLista, Estados } from "../../types/Tarea";
import { merge } from "remeda";
import { v1 as uuid } from "uuid";
import {
agregarTarea,
actualizarEstado,
actualizarDescripcion,
moverTarea,
eliminarFinalizadas,
eliminarTarea,
marcarTodas,
} from "../../state/Tarea";
const init: EstadoLista = {
filtro: Estados.Hecho | Estados.Pendiente,
lista: [],
marcador: Estados.Pendiente,
};
export default (estado = init, accion: Acciones.Tareas): EstadoLista => {
switch (accion.type) {
case IdsAcciones.TAREAS_AGREGAR:
return merge(estado, {
lista: agregarTarea(estado.lista, uuid(), accion.contenido.descripcion),
});
case IdsAcciones.TAREAS_FILTRAR:
return merge(estado, { filtro: accion.contenido.filtro });
case IdsAcciones.TAREAS_MARCAR_TODAS:
return merge(estado, {
marcador: accion.contenido.estado,
lista: marcarTodas(estado.lista, accion.contenido.estado),
});
case IdsAcciones.TAREA_CAMBIAR_ESTADO: {
let lista = actualizarEstado(estado.lista, accion.contenido.tarea);
return merge(estado, {
lista,
marcador: lista.every((tarea) => tarea.estado === Estados.Pendiente)
? Estados.Pendiente
: lista.every((tarea) => tarea.estado === Estados.Hecho)
? Estados.Hecho
: estado.marcador,
});
}
case IdsAcciones.TAREA_EDITAR:
return merge(estado, {
lista: actualizarDescripcion(
estado.lista,
accion.contenido.tarea,
accion.contenido.descripcion
),
});
case IdsAcciones.TAREAS_ELIMINAR_FINALIZADAS: {
const lista = eliminarFinalizadas(estado.lista);
return merge(estado, {
lista,
marcador: lista.length === 0 ? Estados.Pendiente : estado.marcador,
});
}
case IdsAcciones.TAREA_ELIMINAR:
const lista = eliminarTarea(estado.lista, accion.contenido.tarea);
return merge(estado, {
lista,
marcador: lista.length === 0 ? Estados.Pendiente : estado.marcador,
});
case IdsAcciones.TAREA_MOVER:
return merge(estado, {
lista: moverTarea(
estado.lista,
accion.contenido.tarea,
accion.contenido.posicion
),
});
default:
return estado;
}
};
|
cfe48c36408fdb3f5c368a97332e0b41421da060
|
TypeScript
|
kk0917/javascript-design-patterns
|
/src/ConstructorPattern/Model.ts
| 3.140625
| 3
|
export type AddPropsType = {
obj: object;
}
export interface KeyIF {
value: string;
writable?: boolean;
enumerable?: boolean;
configurable?: boolean;
}
export interface CarIF {
model: string;
year: number;
miles: number;
}
export class Car implements CarIF {
model: string;
year: number;
miles: number;
constructor(_model, _year, _miles) {
this.model = _model;
this.year = _year;
this.miles = _miles;
this.toString = function() {
return this.model + " has done " + this.miles + "miles";
}
}
}
export class CarExtension implements CarIF {
model: string;
year: number;
miles: number;
constructor(model: string, year: number, miles: number) {
this.model = model;
this.year = year;
this.miles = miles;
}
}
|
2b3a698e81e5960420a73fe2699d0fc6e893ad94
|
TypeScript
|
anatoly-spb/ionic2-localdb
|
/src/providers/log-provider.ts
| 2.78125
| 3
|
import { Injectable } from '@angular/core';
import { DBProvider } from './db-provider';
import 'rxjs/add/operator/map';
enum LogLevel {
TRACE,
DEBUG,
INFO,
WARN,
ERROR
}
export class LogRecord {
id: number;
datetime: Date;
level: LogLevel;
msg: string;
}
@Injectable()
export class LogProvider {
constructor(private db: DBProvider) {
console.info(`LogProvider: Поставщик службы логирования успешно сконструирован.`);
console.debug(`LogProvider: Старт асинхронной инициализации структуры хранения лога.`);
db.query(`
CREATE TABLE IF NOT EXISTS log(
id INTEGER PRIMARY KEY AUTOINCREMENT,
datetime TEXT NOT NULL,
level INTEGER NOT NULL,
msg TEXT NOT NULL
)
`)
.then(data => {
console.debug(`LogProvider: Финиш асинхронной инициализации структуры хранения лога.`);
console.info(`LogProvider: Структура хранения лога инициализирована успешно.`);
this.log(LogLevel.INFO, "Служба логирования запущена успешно");
}).catch(error => {
console.debug(`LogProvider: Финиш асинхронной инициализации структуры хранения лога.`);
console.error(`LogProvider: Ошибка инициализации структуры хранения лога: ${JSON.stringify(error)}`);
});
}
log(level: LogLevel, msg: string) {
let date = new Date();
this.db.query(`INSERT INTO log (datetime, level, msg) VALUES (?, ?, ?)`, [date.toISOString(), level, msg])
.then(data => {
console.trace(`LogProvider: Сообщение "${msg}" успешно записано в лог.`);
}).catch(error => {
console.error(`LogProvider: Ошибка записи сообщения "${msg}" в лог: ${error}`);
});
}
findAll(): Promise<LogRecord[]> {
return new Promise( (resolve, reject)=>{
this.db.query(`SELECT id, datetime, level, msg FROM log`)
.then(data => {
let result : LogRecord[] = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
let r : any = data.rows.item(i);
let o = new LogRecord();
o.id = r.id;
o.datetime = new Date(Date.parse(r.datetime));
o.level = r.level;
o.msg = r.msg;
result.push(o);
}
resolve(result);
}
}).catch(error => {
reject(error);
});
});
}
}
|
6a4deb59631d7592d410878d835f338e6ca46890
|
TypeScript
|
meow-study/JavaScript-test
|
/src/Example/lib/ArrayRepeatedNumber.ts
| 4.15625
| 4
|
import { Sort } from "../../SortingArithmetic/Sort/lib/Sort.ts";
import { HashMap } from "../../DictionaryTest/lib/HashMap.ts";
/**
* 寻找数组中的重复数字
*
* 规则:
* 1. 给定一个长度为n的数组,数组中每个元素的取值范围为:0~n-1
* 2. 数组中某些数字是重复的,但是不知道有哪些数字重复了,也不知道每个数字重复了几次
* 3. 求数组中任意一个重复的数字
*/
export class ArrayRepeatedNumber {
private sort: Sort<number>;
private readonly isTrue: boolean;
constructor(private array: number[]) {
this.isTrue = true;
// 判断参数是否满足规则
if (array == null || array.length <= 0) {
this.isTrue = false;
console.log("数组不能为空");
}
for (let i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > array.length - 1) {
this.isTrue = false;
console.log("数组中元素的取值范围为0~n-1");
}
}
this.sort = new Sort(array);
}
/**
* 使用排序的方法解决
*
* 实现思路:
* 1. 对数组进行排序
* 2. 从头到尾遍历排序好的数组,只要有相邻的两个数字相等就返回
*
* 时间复杂度分析:调用快速排序其时间复杂度为O(nlog(n)),数组排序完成后只需遍历数组找到相邻的就退出,因此总的时间复杂度为O(nlog(n))
* 空间复杂度分析:由于没有声明新的空间,因此空间复杂度为O(1)
*/
getRepeatedToSort(): number | void {
if (this.isTrue) {
// 排序数组
const sortArray = this.sort.quickSort();
// 重复的数字
let val = -1;
for (let i = 0; i < sortArray.length; i++) {
// 排序完成后,相邻的两个数字相等就代表数组中有重复数字,将其返回
if (sortArray[i] == sortArray[i + 1]) {
val = sortArray[i];
break;
}
}
return val;
}
}
/**
* 使用哈希表解决
*
* 实现思路:
* 1. 声明一个空的哈希表
* 2. 从头到尾遍历数组,如果当前遍历到的元素不存在与哈希表中,就把它加入哈希表,否则就返回这个元素
*
* 时间复杂度分析:遍历数组,判断哈希表中是否包含当前遍历到的元素时,都可以用O(1)的时间复杂度完成,所有元素遍历完就需要n个O(1),因此总的时间复杂度为O(n)
* 空间复杂度分析:由于需要一个额外的哈希表来存储数据,情况最坏时数组的所有元素都会放进哈希表中,因此总的空间复杂度为:O(n)
*/
getRepeatedToHashMap(): number | void {
if (this.isTrue) {
const hashMap = new HashMap();
let val = -1;
for (let i = 0; i < this.array.length; i++) {
// 如果哈希表中存在当前元素就将其返回
if (hashMap.get(this.array[i]) != null) {
val = this.array[i];
break;
}
// 不存在,将其加入哈希表
hashMap.put(this.array[i], 0);
}
return val;
}
}
/**
* 动态排序法(最优解法)
*
* 根据题意可知,数组中元素的取值范围在0~n-1,那么就可以得到如下结论:
* 1. 如果数组中没有重复元素,那么第i号元素的值一定是当前下标(i)
* 2. 如果数组中有重复元素,那么有些位置可能存在多个数字,有些位置可能没有数字
*
* 根据上述结论,我们可以得出下述实现思路:
* 1. 从头到尾遍历数组,存储第i号位置的元素,用m表示
* 2. 如果m的值等于当前下标(i),则继续遍历。
* 否则就判断m的值是否等于数组下标为m处的值。
* 如果等于代表重复将其返回。
* 如果不等于,就交换数组i号位置的元素和m号位置的元素,更新m的值。
* 继续判断m的值是否等于数组下标为m处的元素
*
* 举例说明:
* [8, 1, 2, 3, 4, 3, 3, 4, 5]
* 当下标为0时,m = 8。
* 8 != 0
* 数组8号位置的元素为5,8 != 5。
* 则交换位置,更新m的值。交换位置后的数组为:[5, 1, 2, 3, 4, 3, 3, 4, 8]
* 5 != 0
* 数组5号位置的元素为3,3 != 5。
* 则交换位置,更新m的值。交换位置后的数组为:[3, 1, 2, 3, 4, 5, 3, 4, 8]
* 3 == 3
* 元素重复,返回m
* 问题解决,重复数字为3。
*
* 时间复杂度分析:每个数字最多只要交换2次就能找到它的位置,因此总的时间复杂度为O(n)
* 空间复杂度分析:所有操作都在原数组进行,没有用到额外的空间,所以空间复杂度为O(1)
*/
getRepeated(): number | void {
if (this.isTrue) {
for (let i = 0; i < this.array.length; i++) {
// 存储数组i号位置的元素
let m = this.array[i];
// 判断m的值是否与当前下标一样,一样则继续下一轮循环
while (m !== i) {
// 判断m的值是否等于数组m号位置的元素
if (m === this.array[m]) {
// 如果相等,代表重复,返回这个元素
return m;
}
// 交换数组的i号位置的元素和m号位置的元素
[this.array[i], this.array[m]] = [this.array[m], this.array[i]];
// 交换完毕,更新m的值
m = this.array[i];
}
}
// 未找到
return -1;
}
}
/**
* 消除数组中的重复元素
*
* 规则:
* 1. 数组中元素类型为数字、字符串时,直接取出
* 2. 数组中元素类型为数组时,递归遍历查找数据类型为数字、字符串的元素
* 3. 丢弃其他类型的元素
* @param array 需要进行筛选的数组
* @param result 筛选出来的结果数组
*/
delRepeatedElement<T>(array: T[] | T[][], result: Set<T> = new Set<T>()): T[] {
// 从头到尾遍历数组,根据规则筛选我们需要的数据
for (let i = 0; i < array.length; i++) {
// 数组中元素类型为数字或者字符串时就将其放进结果数组中
if (typeof array[i] === "number" || typeof array[i] === "string") {
result.add(<T>array[i]);
}
// 数组中元素类型为数组时,将其取出,然后递归
if (array[i] instanceof Array) {
// 以当前取出的数组元素为参数递归取出我们需要的数据
this.delRepeatedElement(<T[]>array[i], result);
}
}
// 将筛选出来的set集合解构为数组返回给调用者
return <T[]>[...result];
}
/**
* 不修改数组找到重复的数字
*
* 规则:
* 1. 数组的长度为n+1
* 2. 数组内元素范围:1~n
* 3. 在不修改数组的前提下,找到数组内任意一个重复的数字
*/
// 解法1:使用辅助数组解决
// 实现思路:
// 1. 创建一个数组长度为待处理数组长度+1的辅助数组
// 2. 遍历数组,以原数组i号位置的元素为下标,判断其辅助数组中的值是否为空
// 空间复杂度分析:需要多创建一个辅助数组,因此空间复杂度为O(n)
findRepeatedWithArray(): number {
// 创建一个数组长度为待处理数组长度+1的辅助数组
const result = new Array<number>(this.array.length + 1);
// 数组中的重复元素
let repeated = -1;
// 将待处理数组的每个元素按规则填充进辅助数组
for (let i = 0; i < this.array.length; i++) {
// 获取原数组i号位置的元素
const m = this.array[i];
// 如果辅助数组的m号位置的元素不为空就填充m进去
if (result[m] == null) {
result[m] = m;
} else {
// 重复元素被找到
repeated = this.array[i];
break;
}
}
// 返回找到的重复数字
return repeated;
}
// 解法2:用二分查找实现
/**
* 由于数组的长度是n+1,且其元素的取值范围又在1~n,那么数组中一定会有一个重复的元素
* 根据上述结论,我们可得出如下结论:
* 1. 把1~n的数字,从中间m处分开。
* 2. 分开后,前面一半为1~m,后面一半为m+1~n
* 3. 如果1~m的数字的数目超过m,那么这一半的区间里一定包含了重复的数字,否则另一个区间里一定包含了重复的数字
* 4. 继续把重复的区间一分为二,直到找到一个重复的数字
*
* 举例说明:
* [1, 5, 2, 3, 4, 5, 7]
* 声明3个辅助变量:length = 7, start = 0, end = length - 1 = 6
* 第1轮次分割,如果end >= start就执行下述过程:
* 1. middle = (start + end) / 2 // 6 / 2 = 3
* 2. count = 3
* 3. end !== start // 6 !==0
* 4. count > (middle - start + 1) // 3 - 0 + 1 = 3 false
* 5. start = middle + 1 // 4
* 第2次分割,start = 4, end = 6
* 1. middle = 5
* 2. count = 3
* 3. end !== start // 6 !== 4
* 4. count > (middle - start + 1) / 2 // 5 - 4 + 1 = 2 true
* 5. end = middle // 5
* 第3次分割,start = 4, end = 5
* 1. middle = 4
* 2. count = 1
* 3. end !== start // 5 !== 4
* 4. count > (middle - start + 1) / 2 // 4 - 4 + 1 = 1 false
* 5. start = middle + 1 // 5
* 第4次分割,start = 5, end = 5
* 1. middle = 5
* 2. count = 2
* 3. end == start, count = 2 // return start
*
* 时间复杂度分析:假设输入长度为n的数组,那么计算出现次数的函数需要被调用O(logn)次,每次需要O(n)的空间,因此总的时间复杂度为O(nlogn)
* 空间复杂度分析:没有声明额外的辅助变量,因此空间复杂度为O(1)
*
* 这种解法由于二分查找的缘故,他只能找到数组中的某一个重复数字,不能找到所有的重复数字。
* 相比解法1而言,它的空间复杂度降低了,但是时间复杂度却提高了。
*/
findRepeated(): number {
const length = this.array.length;
let start = 0;
let end = length - 1;
while (end >= start) {
// 计算中间值
const middle = Math.floor((start + end) / 2);
// 计算start~middle的出现次数
const count = ArrayRepeatedNumber.countRange(this.array, length, start, middle);
if (end === start) {
// 基数的值大于1,代表找到了重复的值,将其返回
if (count > 1) {
// 重复值找到,将其返回
return start;
} else {
// 跳出本次循环
break;
}
}
if (count > middle - start + 1) {
// 重复的元素在中间值的左侧
end = middle;
} else {
// 重复的元素在中间值的右侧
start = middle + 1;
}
}
return -1;
}
/**
* 计算出现次数
* @param numbers 要计算的数组
* @param length 要计算数组的长度
* @param start 开始位置
* @param end 结束位置
* @private
*/
private static countRange(numbers: number[], length: number, start: number, end: number) {
if (numbers == null) {
return 0;
}
let count = 0;
for (let i = 0; i < length; i++) {
// 数组的元素必须在start~end的区间内
if (numbers[i] >= start && numbers[i] <= end) {
count++;
}
}
return count;
}
/**
* 二维数组中的查找
*
* 规则:
* 1. 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
* 2. 输入一个整数,判断其是否在二维素组中
*
* 例子:
* [
* [1, 2, 8, 9],
* [2, 4, 9, 12],
* [4, 7, 10, 13]
* [6, 8, 11, 15]
* ]
* 7在二维数组的中的索引:[2][1]
*
* 实现思路:
* 1. 从数组的右上角开始选数字,比较选中的数字与要查找的数字的大小。
* 2. 如果选中的数字等于要查找的数字,表示值已找到,返回true
* 3. 如果选中的数字大于要查找的数字,表示要查找的数字在选中的数字的左方,将当前列从查找范围内移除
* 4. 如果选中的数字小于要查找的数字,表示要查找的数字在选中的数字的下方,将当前行从查找范围内移除
*
* 举例说明:
* 1. 上述例子中,查找范围的右上角数字为9
* 2. 9 > 7,将其所在列从查找范围内移除,剩余的查找范围:
* [
* [1, 2, 8],
* [2, 4, 9],
* [4, 7, 10],
* [6, 8, 11]
* ]
* [
* [1, 2, 4, 6],
* [2, 4, 7, 8],
* [8, 9, 10, 11]
* ]
* 剩余查找范围中,其右上角的数字为8
* 8 > 7,将其所在列从查找范围内移除,剩余的查找范围:
* [
* [1, 2],
* [2, 4],
* [4, 7],
* [6, 8]
* ]
* 剩余查找范围中,其右上角的数字为2
* 2 < 7,将其所在行从查找范围内移除,剩余的查找范围:
* [
* [2, 4],
* [4, 7],
* [6, 8]
* ]
* 剩余的查找范围中,其右上角的数字为4
* 4 < 7,将其所在行从查找范围内移除,剩余的查找范围:
* [
* [4, 7],
* [6, 8]
* ]
* 剩余的查找范围中,其右上角的数字为7
* 7 = 7,返回true。
*
*/
findNumberWithTDM(array: number[][], findValue: number): number | boolean {
// 判断参数是否满足规则
if (!Array.isArray(array[0])) {
return -1;
}
// 列二维数组,用于接收当前二维数组行与列互换后的结果
const colValArray: number[][] = [];
// 获取二维数组的列数据
for (let i = 0; i < array[0].length; i++) {
// 获取当前遍历到的列,将其放进新的二维数组中
colValArray.push(this.getColVal(array, i));
}
// 判断传入的数组和列数据二维数组是否满足题目要求
if (!ArrayRepeatedNumber.isFindTDMArray(array) || !ArrayRepeatedNumber.isFindTDMArray(colValArray)) {
// 不满足
return -1;
}
// 寻找右上角的值并判断。
// row为行默认为二维数组的第0行,
// col为列默认为二维数组第0行的最后一列
let row = 0;
let col = array[0].length - 1;
// 辅助变量,告知调用者要找的值是否找到
let found = false;
// 如果当前查找范围有效就执行下述代码
while (row < array.length && col >= 0) {
// 如果右上角的值等于要找的值,代表元素被找到,将其返回,终止循环
if (array[row][col] === findValue) {
found = true;
break;
} else if (array[row][col] > findValue) {
// 如果右上角的值大于要找的值,代表要找的值在当前值的左侧,将列自减1
col--;
} else {
// 否则,代表要找的值在当前值的右侧,将行自增1
row++;
}
}
// 未找到
return found;
}
/**
* 判断参数是否满足二维数组查找的条件
* @param array 需要进行判断的数组
*/
private static isFindTDMArray(array: number[][]): boolean {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length - 1; j++) {
if (array[i][j + 1] < array[i][j]) {
// 传入的数组不满足条件:每一行必须按照从左到右递增的顺序排序
return false;
}
}
}
// 满足
return true;
}
/**
* 获取二维数组的指定列数据
* @param array 被获取的数组
* @param index 要获取的列
*/
getColVal(array: number[][], index: number): number[] {
const colVal: number[] = [];
for (let i = 0; i < array.length; i++) {
colVal.push(array[i][index]);
}
return colVal;
}
/**
* 字符串或数组相邻元素去重
* @param str 需要执行操作的字符串或数组
*
* @return 执行去重后操作后数组
*/
uniqueInOrder(str: string | number[]): string[] | number[] {
// 结果数组,存放去重后的字符串
const strResult: string[] = [];
const numResult: number[] = [];
// 比对相邻元素,如果不相等就将其放进结果数组中
for (let i = 0; i < str.length; i++) {
// 参数为number类型数组
if (typeof str[i] === "number" && str[i] !== str[i + 1]) {
numResult.push(<number>str[i]);
}
// 参数为字符串数组
if (typeof str[i] === "string" && str[i] !== str[i + 1]) {
strResult.push(<string>str[i]);
}
}
// 根据参数类型返回对应的结果数组
if (typeof str === "string") {
return strResult;
}
return numResult;
}
}
|
9b12f53d089c07b383e4ea0af7124c4fb317f86c
|
TypeScript
|
huaweicloud/huaweicloud-sdk-nodejs-v3
|
/services/config/v1/model/AggregateComplianceDetailRequest.ts
| 2.78125
| 3
|
export class AggregateComplianceDetailRequest {
private 'aggregator_id'?: string;
private 'account_id'?: string;
private 'compliance_state'?: AggregateComplianceDetailRequestComplianceStateEnum | string;
private 'policy_assignment_name'?: string;
private 'resource_name'?: string;
private 'resource_id'?: string;
public constructor(aggregatorId?: string) {
this['aggregator_id'] = aggregatorId;
}
public withAggregatorId(aggregatorId: string): AggregateComplianceDetailRequest {
this['aggregator_id'] = aggregatorId;
return this;
}
public set aggregatorId(aggregatorId: string | undefined) {
this['aggregator_id'] = aggregatorId;
}
public get aggregatorId(): string | undefined {
return this['aggregator_id'];
}
public withAccountId(accountId: string): AggregateComplianceDetailRequest {
this['account_id'] = accountId;
return this;
}
public set accountId(accountId: string | undefined) {
this['account_id'] = accountId;
}
public get accountId(): string | undefined {
return this['account_id'];
}
public withComplianceState(complianceState: AggregateComplianceDetailRequestComplianceStateEnum | string): AggregateComplianceDetailRequest {
this['compliance_state'] = complianceState;
return this;
}
public set complianceState(complianceState: AggregateComplianceDetailRequestComplianceStateEnum | string | undefined) {
this['compliance_state'] = complianceState;
}
public get complianceState(): AggregateComplianceDetailRequestComplianceStateEnum | string | undefined {
return this['compliance_state'];
}
public withPolicyAssignmentName(policyAssignmentName: string): AggregateComplianceDetailRequest {
this['policy_assignment_name'] = policyAssignmentName;
return this;
}
public set policyAssignmentName(policyAssignmentName: string | undefined) {
this['policy_assignment_name'] = policyAssignmentName;
}
public get policyAssignmentName(): string | undefined {
return this['policy_assignment_name'];
}
public withResourceName(resourceName: string): AggregateComplianceDetailRequest {
this['resource_name'] = resourceName;
return this;
}
public set resourceName(resourceName: string | undefined) {
this['resource_name'] = resourceName;
}
public get resourceName(): string | undefined {
return this['resource_name'];
}
public withResourceId(resourceId: string): AggregateComplianceDetailRequest {
this['resource_id'] = resourceId;
return this;
}
public set resourceId(resourceId: string | undefined) {
this['resource_id'] = resourceId;
}
public get resourceId(): string | undefined {
return this['resource_id'];
}
}
/**
* @export
* @enum {string}
*/
export enum AggregateComplianceDetailRequestComplianceStateEnum {
NONCOMPLIANT = 'NonCompliant',
COMPLIANT = 'Compliant'
}
|
45803df507b7c1e66d03342723241a9427050fde
|
TypeScript
|
deepakparamesh/Drello
|
/frontend/src/app/app.service.ts
| 2.546875
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class AppService {
username: string = localStorage.getItem('username');
private usernameSource = new BehaviorSubject(this.username);
currentUsername = this.usernameSource.asObservable();
constructor() { }
setUsername(username) {
localStorage.setItem('username', username)
this.usernameSource.next(username);
}
getUsername() {
this.username = localStorage.getItem('username');
this.usernameSource.next(this.username);
return this.username;
}
changeUsername(username) {
this.usernameSource.next(username);
}
// usernameUpdate() {
// this.usernameSource.next()
// }
}
|
5245ada57f87633165750b6d4cd0828afbb1d79f
|
TypeScript
|
jreyes72/Fanfilm
|
/src/app/Mock-Movies.ts
| 2.75
| 3
|
import {Movie} from './Movie'
export const MOVIES: Movie[] = [
{
id: 1,
title: "Joker",
plot: "Arthur Fleck works as a clown and is an aspiring stand-up comic. He has mental health issues, part of which involves uncontrollable laughter. Times are tough and, due to his issues and occupation, Arthur has an even worse time than most. Over time these issues bear down on him, shaping his actions, making him ultimately take on the persona he is more known as...Joker.",
director: "Todd Phillips",
cast: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
poster: "https://images-na.ssl-images-amazon.com/images/I/71jKxPAMFbL._AC_SL1500_.jpg"
},
{
id: 2,
title: "Black Panther",
plot: "After the events of Captain America: Civil War, Prince T'Challa returns home to the reclusive, technologically advanced African nation of Wakanda to serve as his country's new king. However, T'Challa soon finds that he is challenged for the throne from factions within his own country. When two foes conspire to destroy Wakanda, the hero known as Black Panther must team up with C.I.A. agent Everett K. Ross and members of the Dora Milaje, Wakandan special forces, to prevent Wakanda from being dragged into a world war.",
director: "Ryan Coogler",
cast: "Chadwick Boseman, Michael B. Jordan, Lupita Nyong'o, Danai Gurira" ,
poster: "https://images-na.ssl-images-amazon.com/images/I/A1PaCX4oXjL._AC_SL1500_.jpg"
},
{
id: 3,
title: "Baby Driver",
plot: "Baby is a young and partially hearing impaired getaway driver who can make any wild move while in motion with the right track playing. It's a critical talent he needs to survive his indentured servitude to the crime boss, Doc, who values his role in his meticulously planned robberies. However, just when Baby thinks he is finally free and clear to have his own life with his new girlfriend, Debora, Doc coerces him back for another job. Now saddled with a crew of thugs too violently unstable to keep to Doc's plans, Baby finds himself and everything he cares for in terrible danger. To survive and escape the coming maelstrom,it will take all of Baby's skill, wits and daring, but even on the best track, can he make it when life is forcing him to face the music?",
director: "Edgar Wright",
cast: "Ansel Elgort, Jon Bernthal, Jon Hamm, Eiza González",
poster: "https://m.media-amazon.com/images/I/717QDxYBkbL._AC_.jpg"
}
]
|
35b9fea0d420ea0501f9c06aadbe6e8096359e92
|
TypeScript
|
sakuli/sakuli
|
/packages/sakuli-legacy/src/loader/legacy-project-properties.class.spec.ts
| 2.734375
| 3
|
import { LegacyProjectProperties } from "./legacy-project-properties.class";
describe("LegacyProjectProperties", () => {
let props: LegacyProjectProperties;
beforeEach(() => {
props = new LegacyProjectProperties();
});
describe("getBrowser", () => {
it("should return browser value if set", () => {
props.browser = "chrome";
expect(props.getBrowser()).toEqual("chrome");
});
it("should return browser value if set", () => {
props.testsuiteBrowser = "chrome";
expect(props.getBrowser()).toEqual("chrome");
});
it("should return browser value if set regardless of testsuiteBrowser value", () => {
props.browser = "chrome";
props.testsuiteBrowser = "ie";
expect(props.getBrowser()).toEqual("chrome");
});
it("should return firefox as default", () => {
expect(props.getBrowser()).toEqual("firefox");
});
});
describe("isUiOnly", () => {
it("should return false by default", () => {
expect(props.isUiOnly()).toBe(false);
});
it("should return uiOnly when set", () => {
props.uiOnly = true;
expect(props.isUiOnly()).toBe(true);
});
it("should return uiOnly if set even testsuiteUiOnly is set", () => {
props.uiOnly = false;
props.testSuiteUiOnly = true;
expect(props.isUiOnly()).toBe(false);
});
it("should return testSuiteUiOnly", () => {
props.testSuiteUiOnly = true;
expect(props.isUiOnly()).toBe(true);
});
});
describe("isBrowserReuse", () => {
it("should return true by default", () => {
expect(props.isReuseBrowser()).toBe(true);
});
it("should return browserReuse when set", () => {
props.reuseBrowser = true;
expect(props.isReuseBrowser()).toBe(true);
});
it("should return browserReuse if set even testsuiteBrowserReuse is set", () => {
props.reuseBrowser = false;
props.testsuiteReuseBrowser = true;
expect(props.isReuseBrowser()).toBe(false);
});
it("should return testsuiteBrowserReuse", () => {
props.reuseBrowser = true;
expect(props.isReuseBrowser()).toBe(true);
});
});
});
|
fa9c07fac860edc0757e3407dc1eb411f675deec
|
TypeScript
|
geetchoubey/bd-backend-ts
|
/src/utils/helpers.ts
| 2.671875
| 3
|
import * as bcrypt from "bcrypt";
import {SNS} from 'aws-sdk';
export const encrypt = async (str: string | number): Promise<string> => {
const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(str, salt);
}
export const compare = (source: string | number, encryptedString: string): Promise<boolean> => {
return bcrypt.compare(source, encryptedString);
}
export const match = (str: string, length: number = 10): boolean => !!str.match(new RegExp(`^\\d{${length}}`, 'g'));
export const sendSms = (message: string, phone: string, countryCode: string = '+91') => {
return new SNS().publish({
PhoneNumber: countryCode + phone,
Message: message,
MessageAttributes: {
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': 'BLDBNK'
}
}
}).promise();
}
|
f085afd60eca47ac4797fc4cceb739022e883e31
|
TypeScript
|
guardian/frontend
|
/static/src/javascripts/projects/common/modules/identity/cookierefresh.ts
| 2.6875
| 3
|
/**
* Once the Okta migration is complete and in front of 100% of users, we can delete this module.
*/
import { storage } from '@guardian/libs';
import {
isUserLoggedIn,
refreshOktaSession,
} from 'common/modules/identity/api';
const days30InMillis: number = 1000 * 60 * 60 * 24 * 30;
const shouldRefreshCookie: (
lastRefresh: unknown | null,
currentTime: number,
) => boolean = (lastRefresh: unknown | null, currentTime: number) => {
// !!Number() returns false for false, null, undefined, 0, and non-numeric strings.
// We do this because lastRefresh can be any type or value and we only want to proceed with
// the rest of the check if it's a number.
const lastRefreshIsValid = !!Number(lastRefresh);
if (!lastRefreshIsValid) {
// We should refresh if we don't have a valid lastRefresh value.
return true;
}
// We should refresh if the lastRefresh value is older than 30 days.
return currentTime - Number(lastRefresh) > days30InMillis;
};
const init: () => Promise<void> = async () => {
const lastRefreshKey = 'identity.lastRefresh';
if (storage.local.isAvailable() && (await isUserLoggedIn())) {
const currentTime: number = new Date().getTime();
// The storage API could return any type handled by JSON.parse, so
// we will assume the type is 'unknown' and attempt to parse the value into
// a number in the shouldRefreshCookie function.
// storage.local.get will return null in two cases: if the key is missing,
// or if the value has expired.
const lastRefresh: unknown | null = storage.local.get(lastRefreshKey);
if (shouldRefreshCookie(lastRefresh, currentTime)) {
// Set the value in localStorage to expire in 30 days.
const newExpiry = currentTime + days30InMillis;
storage.local.set(lastRefreshKey, currentTime, newExpiry);
// we only refresh the okta session, users with only an IDAPI session will
// eventually be logged out by the IDAPI cookie expiry
refreshOktaSession(encodeURIComponent(document.location.href));
}
}
};
export { shouldRefreshCookie, init };
|