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
|
|---|---|---|---|---|---|---|
fe7e2bc40a7de9149e7759766cdba6f4ccea2c95
|
TypeScript
|
TGuoW/awesome-lab
|
/src/renderer/mainBrowserWindow/components/2048/ts/MatrixContainer.ts
| 3
| 3
|
let deepClone = (matrix) => matrix.map((ele) => ele.slice(0))
class MatrixContainer {
matrix
constructor (matrix) {
this.matrix = deepClone(matrix)
return this
}
push () {
this.matrix = this.matrix.map((ele) => ele.filter((item) => !item.value)
.concat(ele.filter((item) => item.value)))
return this
}
add () {
this.matrix = this.matrix.map((arr) => {
for (let i = arr.length - 1; i > 0; i--) {
if (arr[i].value === arr[i - 1].value) {
arr[i].combine()
arr[i - 1].zero(arr[i])
i--
}
}
return arr
})
return this
}
reverseArr () {
this.matrix = this.matrix.map((ele) => ele.reverse())
return this
}
reverseMatrix () {
let newMartrix = deepClone(this.matrix)
for (let i = 0; i < newMartrix.length; i++) {
for (let j = 0; j < newMartrix[i].length; j++) {
this.matrix[j][i] = newMartrix[i][j]
}
}
return this
}
end () {
return this.matrix
}
}
export default MatrixContainer
|
7f4f386d9fe4a7e145bf6134a0f007c836130c46
|
TypeScript
|
LupodeLupis/Angular
|
/Hooks/src/app/cockpit/cockpit.component.ts
| 2.578125
| 3
|
import { Component, OnInit, EventEmitter, Output, ViewChild, ElementRef } from '@angular/core';
import { stringify } from '@angular/compiler/src/util';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
@Output() nameEmitter = new EventEmitter<{serverName:string, serverContent:string}>();
@Output() nameEmitter1 = new EventEmitter<{serverName:string, serverContent:string}>();
// {static: true} = if you want access the selector inside the ngOnInit()
// {static: false} = if you do not want access the selector inside the ngOnInit()
// ViewChild fetch local reference from the HTM template and van be used to access a value through its ElementRef object
// anotherInputReference is passed as parameter to @ViewChild()
@ViewChild('anotherInputReference',{static: false}) serverContentInput : ElementRef;
constructor() { }
ngOnInit() {
}
onAddServer(inputValueFromHtml:HTMLInputElement) {
console.log(this.serverContentInput)
//this.serverContentInput.nativeElement.value = 'anyvalue' DO NOT DO THIS!!! - you should not access the DOM passing a value to @ViewChild()--
this.nameEmitter.emit({
serverName:inputValueFromHtml.value,
serverContent:this.serverContentInput.nativeElement.value
});
}
onAddBlueprint(inputValueFromHtml:HTMLInputElement) {
this.nameEmitter1.emit({
serverName:inputValueFromHtml.value,
serverContent:this.serverContentInput.nativeElement.value
})
}
}
|
154783d2f8c32e214b29c61b6f0757711d140661
|
TypeScript
|
clinwiki-org/clinwiki
|
/front/src/utils/siteViewHelpers.ts
| 2.546875
| 3
|
import { FilterKind} from '../services/site/model/InputTypes';
import { AggFilterInput } from 'types/globalTypes';
import {
reject,
filter,
sortBy,
isEmpty,
indexOf,
} from 'ramda';
import { SiteViewFragment } from 'services/site/model/SiteViewFragment';
export const preselectedFilters = (
view: SiteViewFragment
): { aggFilters: AggFilterInput[]; crowdAggFilters: AggFilterInput[] } => {
let aggFilters = reject(
field => isEmpty(field.preselected.values),
view.search.aggs.fields
).map(field => ({
field: field.name,
values: field.preselected.values,
gte: null,
includeMissingFields: null,
lte: null,
zipcode: null,
radius: null,
lat: null,
long: null,
}));
const presearchAggFilters = reject(
field => isEmpty(field.preselected.values),
view.search.presearch.aggs.fields
).map(field => ({
field: field.name,
values: field.preselected.values,
gte: null,
includeMissingFields: null,
lte: null,
zipcode: null,
radius: null,
lat: null,
long: null,
}));
// console.log("Prepre Aggs", presearchAggFilters)
let crowdAggFilters = reject(
field => isEmpty(field.preselected.values),
view.search.crowdAggs.fields
).map(field => ({
field: field.name,
values: field.preselected.values,
gte: null,
includeMissingFields: null,
lte: null,
zipcode: null,
radius: null,
lat: null,
long: null,
}));
const presearchCrowdAggFilters = reject(
field => isEmpty(field.preselected.values),
view.search.presearch.crowdAggs.fields
).map(field => ({
field: field.name,
values: field.preselected.values,
gte: null,
includeMissingFields: null,
lte: null,
zipcode: null,
radius: null,
lat: null,
long: null,
}));
aggFilters = aggFilters.concat(presearchAggFilters);
crowdAggFilters = crowdAggFilters.concat(presearchCrowdAggFilters);
return {
aggFilters,
crowdAggFilters,
};
};
export const displayFields = <
T extends { name: string; rank: number | string | null }
>(
kind: FilterKind,
filterValues: string[],
fields: T[],
sortByValues?: boolean
): T[] => {
const fieldFilterFn = kind === FilterKind.BLACKLIST ? reject : filter;
const filtered = fieldFilterFn(
(field: T) => filterValues.includes(field.name),
fields
);
const sortF = sortByValues ? x => indexOf(x.name, filterValues) : getRank;
return sortBy(sortF, filtered);
};
const getRank = <T extends { name: string; rank: number | string | null }>(
field: T
): number => {
if (field.rank == null) return Number.POSITIVE_INFINITY;
return typeof field.rank === 'number' ? field.rank : parseInt(field.rank, 10);
};
|
fc885792328a8ac85d3214afb21b1d8de21c1dee
|
TypeScript
|
chrisbreiding/proxy
|
/lib/notion/weather.ts
| 2.875
| 3
|
import { compact } from '../util/collections'
import { DayWeather, getWeatherIcon } from '../weather'
import { makeTextPart } from './util'
export function makePrecipPart (condition: boolean, info: string) {
return condition ? makeTextPart(`(${info}) `, 'gray') : undefined
}
export function makeConditionParts (weather: DayWeather) {
return compact([
makeTextPart(`${getWeatherIcon(weather.icon)} `),
makePrecipPart(weather.icon === 'rain' && weather.precipProbability >= 0.01, `${Math.round(weather.precipProbability * 100)}%`),
makePrecipPart(weather.icon === 'snow' && weather.precipAccumulation >= 0.1, `${(weather.precipAccumulation || 0).toFixed(2)}in`),
])
}
export function makeTemperatureParts (weather: DayWeather) {
return compact([
makeTextPart(`${Math.round(weather.temperatureLow)}°`, 'blue'),
makeTextPart(' / ', 'gray'),
makeTextPart(`${Math.round(weather.temperatureHigh)}°`, 'orange'),
])
}
|
8f6f43d0af9c04122d0cf98430c92453577bb5d5
|
TypeScript
|
dukov777/timeseries
|
/app/Student.ts
| 3.140625
| 3
|
export class Student {
full_name: string;
constructor(public name:string) {
this.full_name = name;
}
getName() : string {
return this.full_name;
}
}
|
ac9f60d2e8d2d79785c428d93b371fe20e778587
|
TypeScript
|
kaaninel/TruthStack
|
/Truth/Core/Phases/File/Statement.ts
| 2.65625
| 3
|
import * as X from "../../X";
/**
*
*/
export class Statement
{
/**
* @internal
* Logical clock value used to make chronological
* creation-time comparisons between Statements.
*/
readonly stamp = X.VersionStamp.next();
/**
* @internal
*/
constructor(document: X.Document, text: string)
{
const line = X.LineParser.parse(text);
this.document = document;
this.sourceText = line.sourceText;
this.sum = line.sum;
this.indent = line.indent;
this.flags = line.flags;
this.jointPosition = line.jointPosition;
this.allDeclarations = Object.freeze(Array.from(line.declarations)
.map(boundary => new X.Span(this, boundary)));
this.allAnnotations = Object.freeze(Array.from(line.annotations)
.map(boundary => new X.Span(this, boundary)));
const faults: X.Fault[] = [];
const cruftObjects = new Set<X.Statement | X.Span | X.InfixSpan>();
if (line.faultType !== null)
faults.push(new X.Fault(line.faultType, this));
for (const fault of this.eachParseFault())
{
if (fault.type.severity === X.FaultSeverity.error)
cruftObjects.add(fault.source);
faults.push(fault);
}
for (const fault of faults)
// Check needed to support the unit tests, the feed
// fake document objects into the statement constructor.
if (document.program && document.program.faults)
document.program.faults.report(fault);
this.cruftObjects = cruftObjects;
this.faults = Object.freeze(faults);
this.programStamp = document.program ?
document.program.version :
X.VersionStamp.next();
}
readonly programStamp: X.VersionStamp;
/**
*
*/
private *eachParseFault(): IterableIterator<Readonly<X.Fault<X.TFaultSource>>>
{
// Check for tabs and spaces mixture
if (this.indent > 0)
{
let hasTabs = false;
let hasSpaces = false;
for (let i = -1; ++i < this.indent;)
{
const chr = this.sourceText[i];
if (chr === X.Syntax.tab)
hasTabs = true;
if (chr === X.Syntax.space)
hasSpaces = true;
}
if (hasTabs && hasSpaces)
yield new X.Fault(X.Faults.TabsAndSpaces, this);
}
if (this.allDeclarations.length > 1)
{
const subjects: string[] = [];
for (const span of this.allDeclarations)
{
const subText = span.toString();
if (subjects.includes(subText))
yield new X.Fault(X.Faults.DuplicateDeclaration, span);
else
subjects.push(subText);
}
}
if (this.allAnnotations.length > 0)
{
// This performs an expedient check for "ListIntrinsicExtendingList",
// however, full type analysis is required to cover all cases where
// this fault may be reported.
const getListSpans = (spans: ReadonlyArray<X.Span>) => spans.filter(span =>
{
const sub = span.boundary.subject;
return sub instanceof X.Identifier && sub.isList;
});
const lhsListSpans = getListSpans(this.allDeclarations);
const rhsListSpans = getListSpans(this.allAnnotations);
if (lhsListSpans.length > 0 && rhsListSpans.length > 0)
for (const span of rhsListSpans)
yield new X.Fault(X.Faults.ListIntrinsicExtendingList, span);
}
const pattern = (() =>
{
if (this.allDeclarations.length === 0)
return null;
const hp = X.LineFlags.hasPattern;
if ((this.flags & hp) !== hp)
return null;
const subject = this.allDeclarations[0].boundary.subject;
return subject instanceof X.Pattern ?
subject :
null;
})();
if (pattern === null)
return;
if (!pattern.isValid)
{
yield new X.Fault(X.Faults.PatternInvalid, this);
return;
}
if (this.allAnnotations.length === 0)
yield new X.Fault(X.Faults.PatternWithoutAnnotation, this);
if (pattern.test(""))
yield new X.Fault(X.Faults.PatternCanMatchEmpty, this);
if (!pattern.isTotal)
for (const unit of pattern.eachUnit())
if (unit instanceof X.RegexGrapheme)
if (unit.grapheme === X.Syntax.combinator)
{
yield new X.Fault(X.Faults.PatternPartialWithCombinator, this);
break;
}
const patternSpan = this.allDeclarations[0];
if (patternSpan.infixes.length === 0)
return;
const infixSpans: X.InfixSpan[] = [];
for (const infix of patternSpan.infixes)
{
const lhs = Array.from(patternSpan.eachDeclarationForInfix(infix));
const rhs = Array.from(patternSpan.eachAnnotationForInfix(infix));
const all = lhs.concat(rhs);
// This is a bit out of place ... but we need to populate the
// infixSpans array and this is probably the most efficient
// place to do that.
infixSpans.push(...all);
for (const infixSpan of all)
if (infixSpan.boundary.subject.isList)
yield new X.Fault(X.Faults.InfixUsingListOperator, infixSpan);
yield *dedupInfixSubjects(lhs);
yield *dedupInfixSubjects(rhs);
const lhsIdentifiers = lhs.map(nfxSpan =>
nfxSpan.boundary.subject.toString());
for (const infixSpan of rhs)
if (lhsIdentifiers.includes(infixSpan.boundary.subject.toString()))
yield new X.Fault(X.Faults.InfixHasSelfReferentialType, infixSpan);
if (infix.isPopulation)
for (let idx = 1; idx < lhs.length; idx++)
yield new X.Fault(X.Faults.InfixPopulationChaining, lhs[idx]);
yield *expedientListCheck(lhs);
yield *expedientListCheck(rhs);
}
for (const infixSpan of dedupInfixesAcrossInfixes(
patternSpan,
infix => patternSpan.eachDeclarationForInfix(infix)))
{
if (infixSpan.containingInfix.isPopulation)
yield new X.Fault(
X.Faults.PopulationInfixHasMultipleDefinitions,
infixSpan);
}
for (const infixSpan of dedupInfixesAcrossInfixes(
patternSpan,
infix => patternSpan.eachAnnotationForInfix(infix)))
{
if (infixSpan.containingInfix.isPortability)
yield new X.Fault(
X.Faults.PortabilityInfixHasMultipleDefinitions,
infixSpan);
}
this._infixSpans = Object.freeze(infixSpans);
}
/**
* Gets whether the joint operator exists at the
* end of the statement, forcing the statement's
* declarations to be "refresh types".
*/
get isRefresh()
{
const f = X.LineFlags.isRefresh;
return (this.flags & f) === f;
}
/**
* Gets whether the statement contains nothing
* other than a single joint operator.
*/
get isVacuous()
{
const f = X.LineFlags.isVacuous;
return (this.flags & f) === f;
}
/**
* Gets whether the statement is a comment.
*/
get isComment()
{
const f = X.LineFlags.isComment;
return (this.flags & f) === f;
}
/**
* Gets whether the statement contains
* no non-whitespace characters.
*/
get isWhitespace()
{
const f = X.LineFlags.isWhitespace;
return (this.flags & f) === f;
}
/**
* Gets whether the statement is a comment or whitespace.
*/
get isNoop()
{
return this.isComment || this.isWhitespace;
}
/**
* Gets whether the statement has been removed from it's
* containing document. Removal occurs after the statement
* has been invalidated. Therefore, this property will be false
* before the invalidation phase has occured, even if it will be
* disposed in the current edit transaction.
*/
get isDisposed()
{
const f = X.LineFlags.isDisposed;
return (this.flags & f) === f;
}
/**
*
*/
get isCruft()
{
const f = X.LineFlags.isCruft;
return (this.flags & f) === f;
}
/** @internal */
private flags = X.LineFlags.none;
/** */
readonly faults: ReadonlyArray<X.Fault>;
/** Stores a reference to the document that contains this statement. */
readonly document: X.Document;
/** Stores the indent level of the statement. */
readonly indent: number;
/**
* Stores the set of objects that are contained by this Statement,
* and are marked as cruft. Note that the only Statement object
* that may be located in this set is this Statement object itself.
*/
readonly cruftObjects: ReadonlySet<X.Statement | X.Span | X.InfixSpan>;
/**
* Gets the line number of this statement in it's containing
* document, or -1 if the statement is disposed and/or is not
* in the document.
*/
get index()
{
if (this.isDisposed)
return -1;
return this.document instanceof X.Document ?
this.document.getLineNumber(this) :
-1;
}
/**
* Gets an array of spans in that represent the declarations
* of this statement, excluding those that have been marked
* as object-level cruft.
*/
get declarations()
{
if (this.cruftObjects.size === 0)
return this.allDeclarations;
const out: X.Span[] = [];
for (const span of this.allDeclarations)
if (!this.cruftObjects.has(span))
out.push(span);
return Object.freeze(out);
}
/**
* Stores the array of spans that represent the declarations
* of this statement, including those that have been marked
* as object-level cruft.
*/
readonly allDeclarations: ReadonlyArray<X.Span>;
/**
* Gets a list of all infixes defined in the pattern of this statement.
*/
get infixSpans()
{
return this._infixSpans;
}
private _infixSpans: ReadonlyArray<X.InfixSpan> = Object.freeze([]);
/**
* Gets an array of spans in that represent the annotations
* of this statement, from left to right, excluding those that
* have been marked as object-level cruft.
*/
get annotations()
{
if (this.cruftObjects.size === 0)
return this.allAnnotations;
const out: X.Span[] = [];
for (const span of this.allAnnotations)
if (!this.cruftObjects.has(span))
out.push(span);
return Object.freeze(out);
}
/**
* Stores the array of spans that represent the annotations
* of this statement, including those that have been marked
* as object-level cruft.
*/
readonly allAnnotations: ReadonlyArray<X.Span>;
/**
* Gets an array of spans in that represent both the declarations
* and the annotations of this statement, excluding those that have
* been marked as object-level cruft.
*/
get spans()
{
return this.isCruft ?
[] :
this.declarations.concat(this.annotations);
}
/**
*
*/
get allSpans()
{
return this.declarations.concat(this.annotations);
}
/**
* Stores the position at which the joint operator exists
* in the statement. A negative number indicates that
* the joint operator does not exist in the statement.
*/
readonly jointPosition: number;
/**
* Stores the unprocessed text content of the statement,
* as it appears in the document.
*/
readonly sourceText: string;
/**
* Stores the statement's textual *sum*, which is the
* raw text of the statement's annotations, with whitespace
* trimmed. The sum is suitable as an input to a total
* pattern.
*/
readonly sum: string;
/**
* Gets a boolean value indicating whether or not the
* statement contains a declaration of a pattern.
*/
get hasPattern()
{
const d = this.allDeclarations;
return d.length === 1 && d[0].boundary.subject instanceof X.Pattern;
}
/**
* @internal
* Marks the statement as being removed from it's containing document.
*/
dispose()
{
this.flags = this.flags | X.LineFlags.isDisposed;
}
/**
* @returns The kind of StatementRegion that exists
* at the given character offset within the Statement.
*/
getRegion(offset: number)
{
if (this.isComment || offset < this.indent || this.isCruft)
return StatementRegion.void;
if (this.isWhitespace)
return StatementRegion.whitespace;
if (this.hasPattern)
{
const bnd = this.allDeclarations[0].boundary;
if (offset >= bnd.offsetStart && offset <= bnd.offsetEnd)
return StatementRegion.pattern;
}
if (offset <= this.jointPosition || this.jointPosition < 0)
{
for (const span of this.allDeclarations)
{
const bnd = span.boundary;
if (offset >= bnd.offsetStart && offset <= bnd.offsetEnd)
return StatementRegion.declaration;
}
return StatementRegion.declarationVoid;
}
for (const span of this.allAnnotations)
{
const bnd = span.boundary;
if (offset >= bnd.offsetStart && offset <= bnd.offsetEnd)
return StatementRegion.annotation;
}
return StatementRegion.annotationVoid;
}
/**
*
*/
getSubject(offset: number)
{
return this.getDeclaration(offset) || this.getAnnotation(offset);
}
/**
* @returns A span to the declaration subject at the
* specified offset, or null if there is none was found.
*/
getDeclaration(offset: number)
{
for (const span of this.declarations)
{
const bnd = span.boundary;
if (offset >= bnd.offsetStart && offset <= bnd.offsetEnd)
return span;
}
return null;
}
/**
* @returns A span to the annotation subject at the
* specified offset, or null if there is none was found.
*/
getAnnotation(offset: number)
{
for (const span of this.annotations)
{
const bnd = span.boundary;
if (offset >= bnd.offsetStart && offset <= bnd.offsetEnd)
return span;
}
return null;
}
/**
* @returns A string containing the inner comment text of
* this statement, excluding the comment syntax token.
* If the statement isn't a comment, an empty string is returned.
*/
getCommentText()
{
return this.isComment ?
this.sourceText.slice(this.indent + X.Syntax.comment.length).trim() :
"";
}
/**
* Converts the statement to a formatted string representation.
*/
toString(includeIndent = false)
{
const serializeSpans = (
spans: ReadonlyArray<X.Span>,
escStyle: X.IdentifierEscapeKind) =>
{
return spans
.filter(sp => !(sp.boundary.subject instanceof X.Anon))
.map(sp => X.SubjectSerializer.forExternal(sp, escStyle))
.join(X.Syntax.combinator + X.Syntax.space);
};
const indent = includeIndent ? X.Syntax.tab.repeat(this.indent) : "";
if (this.isCruft)
return indent + "(cruft)";
if (this.isWhitespace)
return indent;
if (this.isVacuous)
return indent + X.Syntax.joint;
const decls = serializeSpans(this.allDeclarations, X.IdentifierEscapeKind.declaration);
const annos = serializeSpans(this.allAnnotations, X.IdentifierEscapeKind.annotation);
const joint = annos.length > 0 || this.isRefresh ? X.Syntax.joint : "";
const jointL = decls.length > 0 && joint !== "" ? X.Syntax.space : "";
const jointR = annos.length > 0 ? X.Syntax.space : "";
return indent + decls + jointL + joint + jointR + annos;
}
}
/**
* Defines the areas of a statement that are significantly
* different when performing inspection.
*/
export enum StatementRegion
{
/**
* Refers to the area within a comment statement,
* or the whitespace preceeding a non-no-op.
*/
void,
/**
* Refers to the area in the indentation area.
*/
whitespace,
/**
* Refers to the
*/
pattern,
/** */
declaration,
/** */
annotation,
/** */
declarationVoid,
/** */
annotationVoid
}
/**
* Yields faults on infix spans in the case when an identifier
* has been re-declared multiple times within the same infix.
*/
function *dedupInfixSubjects(side: X.InfixSpan[])
{
if (side.length === 0)
return;
const subjects: string[] = [];
for (const nfxSpan of side)
{
const subText = nfxSpan.boundary.subject.toString();
if (subjects.includes(subText))
{
yield new X.Fault(X.Faults.InfixHasDuplicateIdentifier, nfxSpan);
}
else subjects.push(subText);
}
}
/**
* Yields faults on infix spans in the case when an identifier
* has been re-declared multiple times across the infixes.
*/
function *dedupInfixesAcrossInfixes(
span: X.Span,
infixFn: (nfx: X.Infix) => IterableIterator<X.InfixSpan>)
{
const identifiers: string[] = [];
for (const infix of span.infixes)
{
const infixSpans = Array.from(infixFn(infix));
for (const infixSpan of infixSpans)
{
const text = infixSpan.boundary.subject.toString();
if (identifiers.includes(text))
{
yield infixSpan;
}
else identifiers.push(text);
}
}
}
/**
* Yields when successive equivalent instances are discovered
* in the specified iterator.
*/
function *dedup<T>(
iterator: IterableIterator<T>,
equalityFn: (a: T, b: T) => boolean)
{
const yielded: T[] = [];
for (const item of iterator)
{
if (yielded.includes(item))
yield item;
else
yielded.push(item);
}
}
/**
* Performs a quick and dirty check to see if the infix is referencing
* a list, by looking to see if it has the list operator. A full check needs
* to perform type inspection to see if any of the types that correspond
* to the identifiers specified are actually lists.
*/
function *expedientListCheck(side: X.InfixSpan[])
{
if (side.length === 0)
return;
for (const nfxSpan of side)
if (nfxSpan.boundary.subject.isList)
yield new X.Fault(X.Faults.InfixUsingListOperator, nfxSpan);
}
|
aa6d1b98f856e82aca00a820a553ae1ea8e421e2
|
TypeScript
|
LeLuxNet/Wholesome
|
/src/error/base.ts
| 2.703125
| 3
|
/** The error class representing errors thrown by Wholesome */
export class WholesomeError extends Error {
/** @internal */
constructor(name: string, message: string) {
super(message);
this.name = name;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
|
501e04de7794630ba5ae81c1ab5c2ca6e937631f
|
TypeScript
|
vith/sample-chat-app
|
/src/mock/entities/conversations.ts
| 2.609375
| 3
|
import slugify from "@sindresorhus/slugify";
import faker from "faker";
import getRange from "get-range";
import randomInt from "random-int";
import randomItem from "random-item";
import randomN from "random-n";
import { ConversationType } from "../../entities/ConversationRecord";
import { createMessages, InMemoryMessageRecord } from "./messages";
import { getUsers, InMemoryUserRecord } from "./users";
let mockConversations = [];
export type InMemoryConversationRecord = {
id: string;
type: ConversationType;
name: string;
slug: string;
members: InMemoryUserRecord[];
messages: InMemoryMessageRecord[];
};
export function getConversations(): InMemoryConversationRecord[] {
if (mockConversations.length > 0) {
return mockConversations;
}
const count = randomInt(3, 5);
for (const _ of getRange({ end: count })) {
createConversation();
}
return mockConversations;
}
export function createConversation(): InMemoryConversationRecord {
const allUsers = getUsers();
const numUsers = allUsers.length;
const numMembers = randomInt(Math.min(3, numUsers), numUsers);
const id = faker.random.uuid();
const type = randomItem<ConversationType>(["group", "dm"]);
const name = faker.random.words();
const slug = slugify(name);
const members = randomN(allUsers, numMembers);
const messages = createMessages(id, members);
const conversation = { id, type, name, slug, members, messages };
mockConversations.push(conversation);
return conversation;
}
|
e98be23494fbb31a93276c1e15c33b698ef3d1e9
|
TypeScript
|
ayalakvo/hackaton21_gidon_group
|
/server/src/user/user.service.ts
| 2.59375
| 3
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) { }
findAll(): Promise<User[]> {
return this.usersRepository.find();
}
findOne(password: string, firstName: string): boolean {
const res = this.usersRepository.findOne({ password, firstName});
if (res) {
return true
}
else return false
}
async remove(id: string): Promise<void> {
await this.usersRepository.delete(id);
}
async addUser(userInfo: User) {
console.log("in service");
const user = await this.usersRepository.save(userInfo);
console.log('user: ', user);
return user
}
}
|
c216a3c97e237ebfcc4e7dbe81c03d005ea3627c
|
TypeScript
|
gitter-badger/typescript-spy-decorator
|
/test/spy_decorator.spec.ts
| 2.859375
| 3
|
///<reference path="../typings/tsd.d.ts" />
import Spy = require("../source/spy");
import FunctionCall = require("../source/function_call");
import spy = require("../source/spy_decorator");
var expect = chai.expect;
class Calculator {
public sume(a : number, b : number) : number {
return a + b;
}
public multiply(a : number, b : number) : number {
return a * b;
}
}
class CalculatorSpy extends Calculator {
public spies: any; // Set by decorator
@spy
public sume(a : number, b : number) : number {
return super.sume(a, b);
}
@spy
public multiply(a : number, b : number) : number {
return super.multiply(a, b);
}
}
describe("Spy Class \n", () => {
it('should log a function call when decorated method is invoked \n', () => {
var tester = new CalculatorSpy();
var result1 = tester.multiply(2, 3);
var result2 = tester.multiply(5, 5);
var multiplySpy : SpyInterface = tester.spies.multiply;
expect(multiplySpy.calls.length).to.equal(2);
expect(multiplySpy.calls[0].returnValue).to.equal(result1);
expect(multiplySpy.calls[1].returnValue).to.equal(result2);
expect(multiplySpy.calls[0].thisValue).to.equal(tester);
expect(multiplySpy.calls[1].thisValue).to.equal(tester);
});
// Work in progress (Contributions are wellcome)
});
|
8f57ab6d144dc5ce56b36a5c447cdf172739fa80
|
TypeScript
|
HrvojeBumber/SpaceBalls
|
/ProjectOne/Scripts/managers/playerBulletManager.ts
| 2.609375
| 3
|
/// <reference path="../objects/playerbullet.ts" />
/// <reference path="../objects/player.ts" />
/*FileName: playerBulletManager.ts
Authors: Kevin Donkers and Hrvoje Bumber
Last Modified by: Kevin Donkers
Description: This is the bullet manager that handles the player firing
*/
module managers {
export class BulletManager {
game: createjs.Container;
player: objects.Player;
bullet: objects.PlayerBullet;
bulletOnScreen: boolean = false;
firing: boolean = false;
constructor(player: objects.Player, game: createjs.Container) {
this.game = game;
this.player = player;
}
fire() {
// create a bullet
this.bullet = new objects.PlayerBullet(this.game);
this.game.addChild(this.bullet);
this.bullet.x = this.player.x;
this.bullet.y = 570;
this.bulletOnScreen = true;
if (bossCollision != null) {
bossCollision.setPlayerBullet(this.bullet);
} else {
collision.setPlayerBullet(this.bullet);
}
// Play Bullet Sound
createjs.Sound.play("shoot");
} // end fire
update() {
this.firing = controls.LASER;
if (this.bulletOnScreen == true) {
// move the bullet up stage
this.bullet.y -= 7;
// check to see if the bullet has left the stage
if (this.bullet.y < 0) {
this.destroyBullet();
}
}
// fire bullet if space bar is clicked
if ((this.firing == true) && (this.bulletOnScreen == false)) {
if (this.player.onStage == true) {
this.fire();
}
}
} // end update
destroyBullet() {
this.game.removeChild(this.bullet);
this.bulletOnScreen = false;
} // end destroyBullet
}
}
|
af24d63b8424e021807959e03f49601d2c62a620
|
TypeScript
|
Sage/ez-streams
|
/src/devices/generic.ts
| 2.875
| 3
|
"use strict";
import { _ } from 'streamline-runtime';
import { Reader } from '../reader';
import { Writer } from '../writer';
/// ## Special streams
///
/// * `ez.devices.generic.empty`
/// The empty stream. `empty.read(_)` returns `undefined`.
/// It is also a null sink. It just discards anything you would write to it.
export const empty = {
reader: new Reader(function (this: Reader<any>, _: _) { }),
writer: new Writer(function (this: Writer<any>, _: _, value: any) { }),
};
/// !doc
/// ## Generic stream constructors
///
/// `import * as ez from 'ez-streams'`
///
/// * `reader = ez.devices.generic.reader(read[, stop])`
/// creates an EZ reader from a given `read(_)` function and an optional `stop(_, [arg])` function.
export function reader<T>(read: (_: _) => T, stop?: (_: _, arg?: any) => void) {
return new Reader(read, stop);
}
/// * `writer = ez.devices.generic.writer(write)`
/// creates an ES writer from a given `write(_, val)` function.
export function writer<T>(write: (_: _, value: T) => void, stop?: (_: _, arg?: any) => void) {
return new Writer(write, stop);
}
|
574e09a00d9507a5e7f8acddfd45fbadbcac9a10
|
TypeScript
|
Robertcl795/AuthEx
|
/server/models/User.ts
| 3.046875
| 3
|
import { Schema, model, Document } from 'mongoose'
import brypt from 'bcryptjs'
interface User extends Document {
method: 'local' | 'google' | 'facebook',
local: {
email: string,
password: string
},
google: {
id: string,
email: string
},
facebook: {
id: string,
email: string
},
isValidPasword(password: string): boolean
}
const userSchema = new Schema({
method: {
type: String,
enum: ['local', 'google', 'facebook'],
required: true
},
local: {
email: {
type: String,
unique: true,
lowercase: true
},
password: {
type: String,
}
},
google: {
id: {
type: String
},
email: {
type: String,
lowercase: true
}
},
facebook: {
id: {
type: String
},
email: {
type: String,
lowercase: true
}
}
})
userSchema.pre<User>('save', async function(next) {
try {
if(this.method !== 'local') next()
const salt = await brypt.genSalt(10)
const hashedPass = await brypt.hash(this.local.password, salt)
this.local.password = hashedPass
next()
} catch(err) {
next(err)
}
})
userSchema.methods.isValidPassword = async function(newPassword) {
try {
return await brypt.compare(newPassword, this.local.password)
} catch(err) {
throw new Error(err)
}
}
export default model('user', userSchema)
|
1f52cde2a018b1f542841ccc3fd0af430dabe726
|
TypeScript
|
beverts312/node-azure-face-sdk
|
/src/models/verify-res.ts
| 2.546875
| 3
|
/**
* @class VerifyRes
*/
class VerifyRes {
public isIdentical: boolean;
public confidence: number;
constructor(isIdentical: boolean, confidence: number) {
this.isIdentical = isIdentical;
this.confidence = confidence;
}
}
export = VerifyRes;
|
de6ecae33b6627b23ec3d0d8d6e13e9e68ee49a4
|
TypeScript
|
calebfrieze/vanillas
|
/src/forIn.d.ts
| 3.15625
| 3
|
/**
* A light wrapper around native `for .. in`, but will only iterate over an Object's own properties.
* @param fn - A function to execute iteratively, which will receive the `key`, `value`, and `object` (respectively)
* @param obj - An object whose keys will be iterated over
*/
export default function forIn(fn: (...params: any[]) => any, obj: object): void
|
0befa463b84617edcb35fa774a2f854b9a0c99a6
|
TypeScript
|
swatikiran123/AngularSeedProject
|
/assets/app/messages/message.service.ts
| 2.671875
| 3
|
import { Message } from './message.model';
export class MessageService{
private messages: Message[] = [];
addMessage(message: Message){
this.messages.push(message);
console.log(this.messages);
}
getMessages(){
return this.messages;
}
deleteMessage(){
this.message.splice(this.message.indexOf(message),1);
}
}
|
020d0bbdba4f9e413bf3791f89d10e02ae2bbe55
|
TypeScript
|
QuentinNev/GlouGlou
|
/src/app/settings/settings.page.ts
| 2.546875
| 3
|
import { Component, OnInit } from '@angular/core';
import { SettingsService } from '../_services/settings.service';
import { ThemeService } from '../_services/theme.service';
@Component({
selector: 'app-settings',
templateUrl: './settings.page.html',
styleUrls: ['./settings.page.scss'],
})
export class SettingsPage implements OnInit {
public apiUrl: string
public theme: string
constructor(private settingsService: SettingsService, private themeService: ThemeService) {
}
ngOnInit() {
// Set default settings if none have been set yet
this.settingsService.getSettings().then(settings => {
if (settings) {
this.apiUrl = settings['apiUrl']
this.theme = settings['theme']
} else {
this.apiUrl = "http://localhost:8000/api/qns/"
this.theme = "neon"
}
})
}
public onApiUrlChanged(apiUrl) {
this.settingsService.setApiUrl(apiUrl)
}
public onThemeChanged(theme) {
this.settingsService.setTheme(theme)
this.themeService.setTheme(themes[theme])
}
}
/**
* Here are stored theme parameters
* themeService.setTheme creates the theme on the fly
*/
const themes = {
autumn: {
primary: '#F78154',
secondary: '#4D9078',
tertiary: '#B4436C',
light: '#FDE8DF',
medium: '#FCD0A2',
dark: '#B89876'
},
night: {
primary: '#8CBA80',
secondary: '#FCFF6C',
tertiary: '#FE5F55',
medium: '#BCC2C7',
dark: '#F7F7FF',
light: '#495867'
},
neon: {
primary: '#39BFBD',
secondary: '#4CE0B3',
tertiary: '#FF5E79',
light: '#F4EDF2',
medium: '#B682A5',
dark: '#34162A'
}
};
|
1a7dafbde8a82850e59b83fbe60213fe3faa5032
|
TypeScript
|
robertopinho/Youtube-codes
|
/src/repositories/ProductRepository.ts
| 3
| 3
|
import Product from '../models/Product';
export default class ProductRepository {
private products: Array<Product>;
constructor() {
this.products = [];
}
public findAll(): Array<Product> {
return this.products;
}
public findByCode(code: number): Product | undefined {
return this.products.find(v => v.code === code);
}
public findById(id: string): Product | undefined {
return this.products.find(v => v.id === id);
}
public delete(code: number): Product | undefined {
const product = this.findByCode(code)
if (!product) {
throw Error('Produto não encontrado')
}
const index = this.products.findIndex((v) => v.code == code)
this.products.splice(index, 1)
return product
}
public update({ id, buyPrice, code, description, sellPrice, tags}: Product): Product | undefined {
const product = this.findById(id)
if (!product) {
throw Error('Produto não encontrado')
}
product.buyPrice = buyPrice;
product.code = code;
product.description = description;
product.sellPrice = sellPrice;
product.tags = tags;
return product
}
public save({
buyPrice,
code,
description,
lovers,
sellPrice,
tags,
}: Product): Product {
const product = new Product({
buyPrice,
code,
description,
lovers,
sellPrice,
tags,
});
this.products.push(product);
return product;
}
}
|
3f62568e15f7151fc90966f1f7370e6aa0e1010a
|
TypeScript
|
kildevaeld/stickjs
|
/src/state.ts
| 2.5625
| 3
|
declare var require: any;
import {NestedModel, NestedModelSetOptions} from 'collection';
import {DIContainer} from 'stick.di';
import * as utils from 'orange';
import * as decorators from './decorators';
const debug = require('debug')('stick:state');
function isObject(a: any): a is Object {
return a === Object(a);
}
export const get_atributes = function (attributes: any) {
let keys = Object.keys(attributes),
deferred = {},
attr = {};
keys.map(key => {
return { key: key, value: attributes[key] };
}).filter(pair => {
if (!utils.has(attributes, pair.key)) return false
if (pair.value && utils.isPromise(pair.value)) {
deferred[pair.key] = pair.value;
delete attributes[pair.key];
return false;
}
return true;
}).forEach((a) => {
attr[a.key] = a.value;
});
return { attr, deferred };
};
@decorators.inject('$container')
export class State extends NestedModel {
private _parent: State;
private _container: DIContainer;
get parent(): State {
return this._parent;
}
get container(): DIContainer {
return this._container;
}
constructor(container: DIContainer, values?: any) {
super(values);
this._container = container;
debug('%s: State created', this.uid);
}
/*public pick(attr:string|string[], ...attrs:string[]): any {
if (arguments.length === 1) {
if (!Array.isArray(attr)) {
attrs = [attr];
} else {
attrs = <string[]>attr;
}
} else {
attrs = [<string>attr].concat(attrs);
}
let out = {};
for (let i = 0, ii = attrs.length; i < ii; i++ ) {
if (this.has(attrs[i])) out[attrs[i]] = this.get(attrs[i]);
}
return out;
}*/
public get(key: string): any {
let data = super.get(key);
debug("%s: Get attribute: %s", this.uid, key, data);
return data;
}
public set(key: string | Object, val?: any): this {
let opts: NestedModelSetOptions = { array: false },
value = {},
unset = {};
if (typeof key === 'string') {
if (val == null) {
unset[key] = val;
} else {
value[key] = val;
}
} else if (isObject(key)) {
value = key;
}
let {attr, deferred} = get_atributes(value);
if (!utils.isEmpty(deferred)) {
debug("%s: Resolve deferred values: %j", this.uid, Object.keys(deferred));
utils.objectToPromise(deferred)
.then(obj => {
this.set(obj)
});
}
if (!utils.isEmpty(attr)) {
debug("%s: Set attributes: ", this.uid, attr);
super.set(attr, opts);
}
if (!utils.isEmpty(unset)) {
// Should unset
debug("%s: Unset attributes: %j", this.uid, Object.keys(unset));
super.set(unset)
}
return this;
}
public createChild(container?: DIContainer, values?: any): State {
if (!container) container = this.container.createChild();
let state = new State(container, values);
state._parent = state;
debug("%s: Create child %s", this.uid, state.uid);
return state;
}
$destroy() {
super.destroy();
debug("%s: State destroyed", this.uid);
}
}
|
11424506dbacb7fe0edceae667cac15c2f3883b1
|
TypeScript
|
fiuba-laboral-v2/validations
|
/test/validateCareerYear.test.ts
| 3.015625
| 3
|
import { NumberIsTooLargeError, validateCareerYear } from "../src";
import { NumberIsNaNError, NumberIsNotIntegerError, NumberIsTooSmallError } from "../src/Errors";
describe("validateCareerYear", () => {
it("raises an error for negative numbers", () =>
expect(() => validateCareerYear(-23)).toThrow(NumberIsTooSmallError)
);
it("raises an error for NaN", () =>
expect(() => validateCareerYear(NaN)).toThrow(NumberIsNaNError)
);
it("raises an error for float values", () =>
expect(() => validateCareerYear(23.33)).toThrow(NumberIsNotIntegerError)
);
it("raises an error for zero", () =>
expect(() => validateCareerYear(0)).toThrow(NumberIsTooSmallError)
);
it("raises an error for values higher than 5", () => {
expect(() => validateCareerYear(6)).toThrow(NumberIsTooLargeError);
expect(() => validateCareerYear(15)).toThrow(NumberIsTooLargeError);
});
it("does not raise an error for values between 1 and 5", () => {
expect(() => validateCareerYear(1)).not.toThrow();
expect(() => validateCareerYear(2)).not.toThrow();
expect(() => validateCareerYear(3)).not.toThrow();
expect(() => validateCareerYear(4)).not.toThrow();
expect(() => validateCareerYear(5)).not.toThrow();
});
});
|
679ee44764906d1615fef739f9135d5c5d44f5dd
|
TypeScript
|
Sherbet339/TypeScript
|
/New folder/src/assign.ts
| 3.890625
| 4
|
interface employeeConfig {
firstname?: string;
lastname?: string;
code?: number;
age?: number;
salary?: number;
bonus?: boolean;
}
function createEmployee(config:employeeConfig): {firstname: string, lastname: string, code:number, age:number, salary:number, bonus:boolean,totalBonus: number} {
let newEmployee = {firstname: 'Default firstname' ,lastname: 'Default lastname', code:12345, age: 0, salary: 15000, bonus:true, totalBonus:1000}
if(config.firstname) {
newEmployee.firstname = config.firstname
}
if(config.lastname) {
newEmployee.lastname = config.lastname
}
if(config.code) {
newEmployee.code = config.code
}
if(config.age) {
newEmployee.age = config.age
}
if(config.salary) {
newEmployee.salary = config.salary
}
if (config.salary) {
newEmployee.totalBonus = config.salary * 2.5;
}
return newEmployee
}
let myEmployee = createEmployee({firstname: "Thamonwan",lastname:"Asawawongmethee", code:12345, age:19, salary:15000, bonus: true})
console.log(`myEmployee`,myEmployee)
|
28ee8538f03202eb6f435cf3a41acb7e06dc1bc8
|
TypeScript
|
marcushultman/advent-of-code-2020
|
/7/1.ts
| 2.765625
| 3
|
import puzzle from '../util/puzzle.ts';
const lines = await puzzle(import.meta).strings();
const tree = {} as { [bag: string]: string[] };
function go(bag: string): boolean {
return bag === 'shiny gold' || tree[bag].some(go);
}
if (import.meta.main) {
lines.forEach(line => {
const [_, bag, match] = line.match(/(.*) bags contain (.*)./) as string[];
tree[bag] = [];
if (match !== 'no other bags') {
tree[bag] = [...match.matchAll(/\d+ (.*?) bags?/g)].map(([a, b]) => b);
}
});
const found = Object.keys(tree).reduce((set, bag) => go(bag) ? set.add(bag) : set, new Set());
console.log(found.size - 1);
}
|
5d0c322cf8125dc67a377f7aff489c7bb0146785
|
TypeScript
|
werthdavid/zxing-typescript
|
/src/core/common/reedsolomon/ReedSolomonDecoder.ts
| 2.640625
| 3
|
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*namespace com.google.zxing.common.reedsolomon {*/
import GenericGF from './GenericGF'
import GenericGFPoly from './GenericGFPoly'
import Exception from './../../Exception'
/**
* <p>Implements Reed-Solomon decoding, as the name implies.</p>
*
* <p>The algorithm will not be explained here, but the following references were helpful
* in creating this implementation:</p>
*
* <ul>
* <li>Bruce Maggs.
* <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
* "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
* <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
* "Chapter 5. Generalized Reed-Solomon Codes"</a>
* (see discussion of Euclidean algorithm)</li>
* </ul>
*
* <p>Much credit is due to William Rucklidge since portions of this code are an indirect
* port of his C++ Reed-Solomon implementation.</p>
*
* @author Sean Owen
* @author William Rucklidge
* @author sanfordsquires
*/
export default class ReedSolomonDecoder {
public constructor(private field: GenericGF) {}
/**
* <p>Decodes given set of received codewords, which include both data and error-correction
* codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
* in the input.</p>
*
* @param received data and error-correction codewords
* @param twoS number of error-correction codewords available
* @throws ReedSolomonException if decoding fails for any reason
*/
public decode(received: Int32Array, twoS: number/*int*/): void /*throws ReedSolomonException*/ {
const field = this.field
const poly = new GenericGFPoly(field, received)
const syndromeCoefficients = new Int32Array(twoS)
let noError: boolean = true
for (let i = 0; i < twoS; i++) {
const evalResult = poly.evaluateAt(field.exp(i + field.getGeneratorBase()))
syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalResult
if (evalResult !== 0) {
noError = false
}
}
if (noError) {
return
}
const syndrome = new GenericGFPoly(field, syndromeCoefficients)
const sigmaOmega = this.runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS)
const sigma = sigmaOmega[0]
const omega = sigmaOmega[1]
const errorLocations = this.findErrorLocations(sigma)
const errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations)
for (let i = 0; i < errorLocations.length; i++) {
const position = received.length - 1 - field.log(errorLocations[i])
if (position < 0) {
throw new Exception(Exception.ReedSolomonException, "Bad error location")
}
received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i])
}
}
private runEuclideanAlgorithm(a: GenericGFPoly, b: GenericGFPoly, R: number/*int*/): GenericGFPoly[]
/*throws ReedSolomonException*/ {
// Assume a's degree is >= b's
if (a.getDegree() < b.getDegree()) {
const temp = a
a = b
b = temp
}
const field = this.field
let rLast = a
let r = b
let tLast = field.getZero()
let t = field.getOne()
// Run Euclidean algorithm until r's degree is less than R/2
while (r.getDegree() >= R / 2) {
let rLastLast = rLast
let tLastLast = tLast
rLast = r
tLast = t
// Divide rLastLast by rLast, with quotient in q and remainder in r
if (rLast.isZero()) {
// Oops, Euclidean algorithm already terminated?
throw new Exception(Exception.ReedSolomonException, "r_{i-1} was zero")
}
r = rLastLast
let q = field.getZero()
const denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree())
const dltInverse = field.inverse(denominatorLeadingTerm)
while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
const degreeDiff = r.getDegree() - rLast.getDegree()
const scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse)
q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale))
r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale))
}
t = q.multiply(tLast).addOrSubtract(tLastLast)
if (r.getDegree() >= rLast.getDegree()) {
throw new Exception(Exception.IllegalStateException, "Division algorithm failed to reduce polynomial?")
}
}
const sigmaTildeAtZero = t.getCoefficient(0)
if (sigmaTildeAtZero === 0) {
throw new Exception(Exception.ReedSolomonException, "sigmaTilde(0) was zero")
}
const inverse = field.inverse(sigmaTildeAtZero)
const sigma = t.multiplyScalar(inverse)
const omega = r.multiplyScalar(inverse)
return [sigma, omega]
}
private findErrorLocations(errorLocator: GenericGFPoly): Int32Array /*throws ReedSolomonException*/ {
// This is a direct application of Chien's search
const numErrors = errorLocator.getDegree()
if (numErrors === 1) { // shortcut
return Int32Array.from([errorLocator.getCoefficient(1)])
}
const result = new Int32Array(numErrors)
let e = 0
const field = this.field
for (let i = 1; i < field.getSize() && e < numErrors; i++) {
if (errorLocator.evaluateAt(i) === 0) {
result[e] = field.inverse(i)
e++
}
}
if (e !== numErrors) {
throw new Exception(Exception.ReedSolomonException, "Error locator degree does not match number of roots")
}
return result
}
private findErrorMagnitudes(errorEvaluator: GenericGFPoly, errorLocations: Int32Array): Int32Array {
// This is directly applying Forney's Formula
const s = errorLocations.length
const result = new Int32Array(s)
const field = this.field
for (let i = 0; i < s; i++) {
const xiInverse = field.inverse(errorLocations[i])
let denominator = 1
for (let j = 0; j < s; j++) {
if (i !== j) {
//denominator = field.multiply(denominator,
// GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)))
// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
// Below is a funny-looking workaround from Steven Parkes
const term = field.multiply(errorLocations[j], xiInverse)
const termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1
denominator = field.multiply(denominator, termPlus1)
}
}
result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
field.inverse(denominator))
if (field.getGeneratorBase() != 0) {
result[i] = field.multiply(result[i], xiInverse)
}
}
return result
}
}
|
ee2f1e62579cf691f840550d56b7eae84760673d
|
TypeScript
|
MichaelKintscher/angular-material-table-demo
|
/demo-app/src/types/table-data.interface.ts
| 3.109375
| 3
|
// Create an interface for your data, so TypeScript knows what datatype to work with when
// putting your data in the table.
export interface TableDataInterface {
Id: string;
ColumnIndex: number;
ColumnSpan: number;
RowIndex: number;
RowSpan: number;
Cell: string;
}
|
c7eaa35ff7bb69cc00d7af6318048f745e117f99
|
TypeScript
|
twy30/netizen-musou-original-ip-crowdfunding
|
/src/Abstracts/BackerCard.ts
| 2.671875
| 3
|
/// <reference path="Card.ts" />
abstract class BackerCard extends Card {
constructor(name: string, description: string, savingThrows: DiceFace[], fund: number, progress: number) {
super(name, description);
this.savingThrows = savingThrows;
this.fund = fund;
this.progress = progress;
}
savingThrows: DiceFace[];
fund: number;
progress: number;
}
|
a0bc713a92dba412ba442d93a2a15dd80211b121
|
TypeScript
|
noru/utils
|
/lib/math.d.ts
| 3.421875
| 3
|
/**
* Math.PI * 2, a whole radiant circle
*
* @export
* @constant
*/
export declare const TAU: number;
/**
* Golden ratio
*
* @export
* @constant
*/
export declare const PHI = 1.618033988749895;
export interface Vector2D {
x: number;
y: number;
}
/**
* Rotate a 2D vector by given angle, returns a new vector
*
* @export
* @param {Vector2D} vector2D
* @param {number} angle
* @returns {Vector2D}
*/
export declare function rotate2D(v: Vector2D, angle: number): Vector2D;
|
cd6381508f787bdb0ab64a45e6bda0914768efd8
|
TypeScript
|
Khan/wonder-blocks
|
/packages/wonder-blocks-data/src/components/data.ts
| 3.0625
| 3
|
import * as React from "react";
import {
useHydratableEffect,
WhenClientSide,
} from "../hooks/use-hydratable-effect";
import type {Result, ValidCacheData} from "../util/types";
type Props<
/**
* The type of data resolved by the handler's fulfillRequest method.
*/
TData extends ValidCacheData,
> = {
/**
* A unique identifier for the request.
*
* This should not be shared by other uses of this component.
*/
requestId: string;
/**
* This defines how the request is fulfilled.
*
* If this is changed without changing the ID, there are cases where the
* old handler result may be given. This is not a supported mode of
* operation.
*/
handler: () => Promise<TData>;
/**
* How the hook should behave when rendering client-side for the first time.
*
* This controls how the hook hydrates and executes when client-side.
*
* Default is `OnClientRender.ExecuteWhenNoSuccessResult`.
*/
clientBehavior?: typeof WhenClientSide[keyof typeof WhenClientSide];
/**
* When true, the children will be rendered with the existing result
* until the pending load is completed. Otherwise, the children will be
* given a loading state until the request is fulfilled.
*
* Defaults to false.
*/
retainResultOnChange?: boolean;
/**
* A function that will render the content of this component using the
* loading state and data or error that gets retrieved from cache or loaded
* via the request if no cached value is available.
*/
children: (result: Result<TData>) => React.ReactElement | null;
};
/**
* This component is the main component of Wonder Blocks Data. With this, data
* requirements can be placed in a React application in a manner that will
* support server-side rendering and efficient caching.
*/
const Data = <TData extends ValidCacheData>({
requestId,
handler,
children,
retainResultOnChange = false,
clientBehavior = WhenClientSide.ExecuteWhenNoSuccessResult,
}: Props<TData>): React.ReactElement | null => {
const result = useHydratableEffect(requestId, handler, {
retainResultOnChange,
clientBehavior,
});
return children(result);
};
export default Data;
|
15561d9e3800925d0234123ad45fd365cc843a69
|
TypeScript
|
rabelloo/tamda
|
/src/set/union.spec.ts
| 3.15625
| 3
|
import { union } from './union';
describe('union', () => {
it('should return an unique concatenation of arrayA and arrayB', () => {
const arrayA = [1, 2, 3];
const arrayB = [2, 3, 4];
const fn = (n: number) => n;
const results = [
union(arrayA, arrayB),
union (arrayB) (arrayA),
union(arrayA, arrayB, fn),
union (arrayB, fn) (arrayA),
];
results.forEach(result => {
expect(result).toEqual([1, 2, 3, 4]);
});
});
});
|
3006a2299ad4f3063e0cc93d7c7291c81e1efe61
|
TypeScript
|
klazizpro/uproxy-lib
|
/src/arraybuffers/arraybuffers.d.ts
| 3.53125
| 4
|
declare module ArrayBuffers {
// Byte-wise comparison.
function byteEquality(b1:ArrayBuffer, b2:ArrayBuffer) : boolean;
// String-to-array buffer conversion by character code. Does not behave well
// with strings with high-valued character codes.
function arrayBufferToString(buffer:ArrayBuffer) : string;
function stringToArrayBuffer(s:string) : ArrayBuffer;
// Converts a HexString of the regexp form /(hh\.)*hh/ (where `h` is a
// hex-character) to/from an ArrayBuffer.
function arrayBufferToHexString(buffer:ArrayBuffer) : string;
function hexStringToArrayBuffer(hexString:string) : ArrayBuffer;
// Converts arrayBuffer which has a string encoded in UTF8 to/from Javascript
// strings. Note: the array buffer should be a valid string with no zeros
// inside.
function arrayBufferDecodedAsUtf8String(buffer:ArrayBuffer) : string;
function stringToUtf8EncodedArrayBuffer(str:string) : ArrayBuffer;
// Concat |ArrayBuffer|s into a single ArrayBuffer. If size is given, then
// the destination array buffer is of the given size. If size is not given or
// zero, the size of all buffers is summed to make the new array buffer.
function concat(buffers:ArrayBuffer[]) : ArrayBuffer;
// Break an array buffer into multiple array buffers that are at most |size|
// types long. Returns 'chunked' array buffers. The array buffers are in
// order such that |byteEquality(concat(chunk(a, n)),a)===true|
function chunk(buffer:ArrayBuffer, size:number) : ArrayBuffer[]
}
|
03369e2af63856f3b820d2419a8264b0ecdf7154
|
TypeScript
|
OrganizeRooms/NEW-FrontEnd-OrganizeRooms
|
/src/app/shared/_models/agendamento.ts
| 2.578125
| 3
|
import { Pessoa } from './pessoa';
import { Sala } from './sala';
import { Participante } from './participante';
import { ReservaEquipamento } from './reservaEquipamento';
export interface Agendamento {
ageId: number,
ageAssunto: string,
ageDescricao: string,
ageSala: Sala,
agePesResponsavel: Pessoa,
ageStatus: string,
ageData: Date,
ageHoraInicio: Date,
ageHoraFim: Date,
agePesCadastro: number,
agePesAtualizacao: number,
ageDtCadastro: Date,
ageDtAtualizacao: Date,
ageEquipamentos: ReservaEquipamento[],
ageParticipantes: Participante[]
}
export function montarAgendamentoComId(id: number): Agendamento {
return {
ageId: id,
ageAssunto: '',
ageDescricao: '',
ageSala: null,
agePesResponsavel: null,
ageStatus: '',
ageData: new Date(),
ageHoraInicio: new Date(),
ageHoraFim: new Date(),
agePesCadastro: 0,
agePesAtualizacao: 0,
ageDtCadastro: new Date(),
ageDtAtualizacao: new Date(),
ageEquipamentos: new Array<ReservaEquipamento>(),
ageParticipantes: new Array<Participante>()
};
}
/*
constructor(
public ageId: number,
public ageAssunto: string,
public ageDescricao: string,
public ageSala: Sala,
public agePesResponsavel: Pessoa,
public ageStatus: string,
public ageData: Date,
public ageHoraInicio: Date,
public ageHoraFim: Date,
public agePesCadastro: number,
public agePesAtualizacao: number,
public ageDtCadastro: Date,
public ageDtAtualizacao: Date,
public ageEquipamentos?: ReservaEquipamento[],
public ageParticipantes?: Participante[]
) { }
static montarAgendamentoComId(id: number): Agendamento {
return new Agendamento(
id,
'',
'',
null,
null,
'',
new Date(),
new Date(),
new Date(),
0,
0,
new Date(),
new Date()
);
}
get msgEmailPadrao(): string {
return `Você possui uma nova reunião na data ${DateHelper.montarStringData(this.ageData)}
no período das ${DateHelper.montarStringHoraMinuto(this.ageHoraInicio)}
às ${DateHelper.montarStringHoraMinuto(this.ageHoraFim)} marcada por ${this.agePesResponsavel}.`
}
get msgEmailPartObrigatorio(): string {
return `Você é uma pessoa Obrigatória na nova reunião marcada por ${this.agePesResponsavel}
na data ${DateHelper.montarStringData(this.ageData)} no período das ${DateHelper.montarStringHoraMinuto(this.ageHoraInicio)}
às ${DateHelper.montarStringHoraMinuto(this.ageHoraFim)}.`;
}
get assuntoEmailPadrao(): string {
return `Nova Reunião Marcada por ${this.agePesResponsavel}`;
}*/
/*static msgEmailPadrao(data: Date, horaInicio: Date, horaFim: Date, responsavel: string): string {
return `Você possui uma nova reunião na data ${DateHelper.montarStringData(data)}
no período das ${DateHelper.montarStringHoraMinuto(horaInicio)}
às ${DateHelper.montarStringHoraMinuto(horaFim)} marcada por ${responsavel}.`
}
static msgEmailPartObrigatorio(data: Date, horaInicio: Date, horaFim: Date, responsavel: string): string {
return `Você é uma pessoa Obrigatória na nova reunião marcada por ${responsavel}
na data ${DateHelper.montarStringData(data)} no período das ${DateHelper.montarStringHoraMinuto(horaInicio)}
às ${DateHelper.montarStringHoraMinuto(horaFim)}.`;
}
static assuntoEmailPadrao(responsavel: string): string {
return `Nova Reunião Marcada por ${responsavel}`;
}*/
|
ceb2443a89b378f0ad8bf2722f7a4be980de8973
|
TypeScript
|
prhegde/AngularJS_SampleApp
|
/app-workspace/projects/sample-app/src/app/main/counter/counter.actions.ts
| 3.375
| 3
|
import { Action } from "@ngrx/store";
export const ACTION_TYPES = {
ADD: '[counter] increment',
REMOVE: '[counter] decrement',
RESET: '[counter] reset',
};
/**
* Every action is comprised of at least a type and an optional payload. Expressing actions as
* classes enables powerful type checking in reducer functions.
*/
export class AddHostAction implements Action {
readonly type = ACTION_TYPES.ADD;
constructor( public payload?: any) {}
}
export class RemoveHostAction implements Action {
readonly type = ACTION_TYPES.REMOVE;
constructor( public payload?: any) {}
}
export class ResetHostAction implements Action {
readonly type = ACTION_TYPES.RESET;
constructor( public payload?: any) {}
}
/**
* Export a type alias of all actions in this action group so that reducers
* can easily compose action types
*/
export type Actions
= AddHostAction
| RemoveHostAction
| ResetHostAction;
|
41352cb2a3e313f3240a18542e3101dabdbb27ae
|
TypeScript
|
ak2ie/yodobashi-teikibin
|
/__tests__/background.spec.ts
| 2.515625
| 3
|
import { TeikiKonyu } from '../app/scripts/background';
import * as moment from 'moment';
import * as COMMON from '../app/scripts/common';
import * as storage from '../app/scripts/storage';
import { advanceTo, clear } from 'jest-date-mock';
const s = jest.mock('../app/scripts/storage');
describe('バックグラウンド', () => {
afterEach(() => {
clear();
});
xit('定期購入商品チェック', async () => {
const dataFromStorage = {
ProductData: [{
id: 9999,
name: 'test',
buyNum: 3,
buyInterval: 1,
nextBuyDate: moment(new Date('2018-10-11T21:09:10')).toISOString(true), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false
}]
};
chrome.storage.sync.get.mockImplementation((key, callback) => {
callback(dataFromStorage);
});
const teikiKonyu = new TeikiKonyu();
await teikiKonyu.order();
// expect(chrome.tabs.sendMessage.mock.calls[0][0]).toBe(9999);
});
it('カート投入商品更新', async () => {
// 次回購入日 当日
advanceTo(new Date(2018, 9, 11, 21, 9, 0));
const dataFromStorage = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 3,
buyInterval: 1,
nextBuyDate: moment(new Date('2018-10-11T21:09:10+09:00')).toDate(),
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('2018-09-11T21:09:10+09:00')).toDate()
}]
};
const expectedData = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 3,
buyInterval: 1,
nextBuyDate: moment(new Date('2018-11-11T21:09:00')).toDate(), // 今日 + buyInterval後に更新
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: new Date() // 今日に更新
}]
};
jest.spyOn(storage, 'getDataFromStorage').mockImplementation(() => {
return dataFromStorage;
});
jest.spyOn(storage, 'saveDataToStorage').mockImplementation((arg) => {
if ('ProductData' in arg) {
expect(arg).toEqual(expectedData);
}
});
const teikiKonyu = new TeikiKonyu();
const product = new COMMON.PutInCartProductData('https://www.yodobashi.com/product/9999/', true);
await teikiKonyu.updatePutInCartProduct(product);
});
it('既存データ更新(前回購入日 設定済)', async () => {
const dataFromStorage = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 3,
buyInterval: 1,
nextBuyDate: moment(new Date('2018-10-11T21:09:10+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('2018-09-11T21:09:10+09:00'))
}]
};
const expectedData = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 1,
buyInterval: 2,
// 今日 + buyInterval 月後ではなく、lastBuyDate + buyInterval月後の日付
nextBuyDate: moment(new Date('2018-11-11T21:09:10+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('2018-09-11T21:09:10+09:00'))
}]
};
advanceTo(new Date('2018-10-12T09:00:00+09:00'));
jest.spyOn(storage, 'getDataFromStorage').mockImplementation(() => {
return dataFromStorage;
});
jest.spyOn(storage, 'saveDataToStorage').mockImplementation((arg) => {
expect(arg).toEqual(expectedData);
});
const teikiKonyu = new TeikiKonyu();
// 購入個数(3 -> 1)、購入頻度(1ヶ月 -> 2ヶ月)、次回購入日を更新
await teikiKonyu.register(new COMMON.ProductDataForMessage(
'9999',
'test',
1,
2,
'2018-10-11T21:09:10+09:00',
COMMON.BuyType.Indivisual,
false,
false,
'2018-09-11T21:09:10+09:00'
));
});
it('既存データ更新(前回購入日 未設定)', async () => {
const dataFromStorage = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 3,
buyInterval: 1,
nextBuyDate: moment(new Date('2018-10-11T21:09:10+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('9999-12-31T00:00:00+09:00'))
}]
};
const expectedData = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 1,
buyInterval: 2,
// 前回購入日未設定のため、今日 + buyInterval 月後
nextBuyDate: moment(new Date('2018-12-12T09:00:00+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('9999-12-31T00:00:00+09:00'))
}]
};
advanceTo(new Date('2018-10-12T09:00:00+09:00'));
jest.spyOn(storage, 'getDataFromStorage').mockImplementation(() => {
return dataFromStorage;
});
jest.spyOn(storage, 'saveDataToStorage').mockImplementation((arg) => {
expect(arg).toEqual(expectedData);
});
const teikiKonyu = new TeikiKonyu();
// 購入個数(3 -> 1)、購入頻度(1ヶ月 -> 2ヶ月)、次回購入日を更新
await teikiKonyu.register(new COMMON.ProductDataForMessage(
'9999',
'test',
1,
2,
'2018-10-11T21:09:10+09:00',
COMMON.BuyType.Indivisual,
false,
false,
'9999-12-31T00:00:00+09:00'
));
});
xit('カート投入指示', async () => {
const dataFromStorage = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 1,
buyInterval: 3,
nextBuyDate: moment(new Date('2018-10-11T21:09:10+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('9999-12-31T00:00:00+09:00'))
}]
};
const expectedData = {
type: COMMON.PUT_IN_CART,
data: {
buyNum: 1
}
};
jest.spyOn(storage, 'getDataFromStorage').mockImplementation(() => {
return dataFromStorage;
});
const teikiKonyu = new TeikiKonyu();
await teikiKonyu.putInCart({
url: 'http://www.yodobashi.com/product/9999/?teikibin=true'
});
// expect(chrome.tabs.sendMessage.mock.calls[0][1]).toEqual(expectedData);
});
xit('カート投入通知', async () => {
const dataFromStorage = {
ProductData: [{
id: '9999',
name: 'test',
buyNum: 1,
buyInterval: 3,
nextBuyDate: moment(new Date('2018-10-11T21:09:10+09:00')).toDate(), // Storageには文字列で保存されている
buyType: COMMON.BuyType.Indivisual,
isSellEnded: false,
isPutInCartFailure: false,
lastBuyDate: moment(new Date('9999-12-31T00:00:00+09:00'))
}]
};
const expectedData = {
type: COMMON.PUT_IN_CART,
data: {
buyNum: 1
}
};
jest.spyOn(storage, 'getDataFromStorage').mockImplementation(() => {
return dataFromStorage;
});
const teikiKonyu = new TeikiKonyu();
await teikiKonyu.order();
expect(chrome.storage.sync.set.mock.calls[0][0]).toEqual(expectedData);
});
});
|
b8d68df59fdeb975152b3f15f001c26ca82871b9
|
TypeScript
|
pixelbar/slackbridge
|
/src/custom_replies/foodorder.ts
| 2.84375
| 3
|
import { ICustomReply } from "./interfaces";
import { IMessage, IChatInterface } from "../chat_connectors/interfaces";
import Manager from "../manager";
import * as fs from "fs";
export default class FoodOrder implements ICustomReply {
private orders: IFoodOrder[];
constructor() {
try {
this.orders = JSON.parse(fs.readFileSync("data/foodorder.json", { encoding: "utf8" })) || [];
} catch(e) {
this.orders = [];
}
}
public accept(message: IMessage, manager: Manager): boolean {
var index = message.message.indexOf('#foodorder');
if(index != 0) return false;
var order = message.message.substring('#foodorder'.length).trim();
// const split: string[] = message.message.split(" ", 2);
if (order === "list" || order === "") {
manager.send(this.getFoodOrders());
} else if (order === "clear") {
manager.send(this.clearFoodOrders());
} else {
manager.send(this.addFoodOrder(message, order));
}
return true;
}
private getFoodOrders(): IMessage {
let text: string;
if(this.orders.length > 0) {
text = this.orders.map((o: IFoodOrder) => o.user + " wants " + o.food).join(", ");
} else {
text = "No orders placed";
}
return {
message: text,
time: new Date(),
sender: {
display_name: "Foodorder",
unique_name: "Foodorder",
is_bot: true
},
source: null
};
}
private clearFoodOrders(): IMessage {
this.orders = [];
this.save();
return {
message: "Orders cleared",
time: new Date(),
sender: {
display_name: "Foodorder",
unique_name: "Foodorder",
is_bot: true
},
source: null
};
}
private addFoodOrder(message: IMessage, food: string): IMessage {
this.orders = this.orders.filter((o: IFoodOrder) => o.user !== message.sender.display_name);
this.orders.push({
food: food,
user: message.sender.display_name
});
this.save();
return {
message: message.sender.display_name + " wants " + food,
time: new Date(),
sender: {
display_name: "Foodorder",
unique_name: "Foodorder",
is_bot: true
},
source: null
};
}
private save(): void {
fs.writeFile("data/foodorder.json", JSON.stringify(this.orders), () => {/*ignored*/});
}
}
interface IFoodOrder {
user: string;
food: string;
}
|
6f1c592f532ae9debe820f1886a7ac581cdd8494
|
TypeScript
|
CharlesYerts/meta
|
/src/0088.merge-sorted-array.88/0088.merge-sorted-array.88.ts
| 3.421875
| 3
|
/**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
let index1:number = m-1;
let index2:number = nums1.length-1;
while(index1>-1){
nums1[index2--] = nums1[index1--];
}
index1 = nums1.length-m;
index2 = 0;
let index = 0;
while(index1<nums1.length && index2<nums2.length){
if(nums1[index1]>nums2[index2]){
nums1[index++] = nums2[index2++];
}else{
nums1[index++] = nums1[index1++];
}
}
while(index2<nums2.length){
nums1[index++] = nums2[index2++];
}
};
|
648e7741a80ebefb77f3da86be93e320ba037e97
|
TypeScript
|
strblr/mongoe
|
/src/utility.ts
| 2.875
| 3
|
import { ObjectId } from "mongodb";
export { ObjectId };
export function idify(str: null | undefined): null;
export function idify(str: string): ObjectId;
export function idify(str: string | null | undefined): ObjectId | null;
export function idify(str: string | null | undefined): ObjectId | null {
if (str === null || str === undefined) return null;
if (!ObjectId.isValid(str))
throw new Error(`Invalid hex value <${str}> passed to idify`);
return ObjectId.createFromHexString(str);
}
export function substractKeys<T>(keys: Array<T>, alreadyDeleted: Array<T>) {
const normalizedKey = (key: T) =>
key instanceof ObjectId ? key.toHexString() : key;
const set = new Set(alreadyDeleted.map(normalizedKey));
return keys.filter(key => !set.has(normalizedKey(key)));
}
|
a9ad5a2322d33c08b10f9d43dec3e23eedef16c6
|
TypeScript
|
integreat-io/integreat-adapter-form
|
/src/adapter/serialize.test.ts
| 2.921875
| 3
|
import test from 'ava'
import serialize from './serialize'
test('should serialize simple data object', async (t) => {
const request = {
method: 'MUTATION',
data: {
value: 1,
text: 'Several words here'
}
}
const expectedData = 'value=1&text=Several+words+here'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should serialize uri', async (t) => {
const request = {
method: 'MUTATION',
data: {
value: 1,
redirect_uri: 'http://redirect.com/to/this.html'
}
}
const expectedData = 'value=1&redirect_uri=http%3A%2F%2Fredirect.com%2Fto%2Fthis.html'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should serialize object', async (t) => {
const request = {
method: 'MUTATION',
data: {
value: 1,
object: { id: 'ent1', type: 'entry' }
}
}
const expectedData = 'value=1&object=%7B%22id%22%3A%22ent1%22%2C%22type%22%3A%22entry%22%7D'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should serialize object with one key', async (t) => {
const request = {
method: 'MUTATION',
data: {
text: 'Several words here'
}
}
const expectedData = 'text=Several+words+here'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should serialize first object in array', async (t) => {
const request = {
method: 'MUTATION',
data: [{ value: 1 }, { value: 2 }]
}
const expectedData = 'value=1'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should serialize keys with empty values', async (t) => {
const request = {
method: 'MUTATION',
data: {
none: undefined,
nil: null,
empty: '',
zero: 0
}
}
const expectedData = 'none&nil=null&empty=&zero=0'
const ret = await serialize(request)
t.is(ret.data, expectedData)
})
test('should return null when not an object', async (t) => {
const request = {
method: 'MUTATION',
data: null
}
const expectedData = null
const ret = await serialize(request)
t.deepEqual(ret.data, expectedData)
})
|
fde9e6b1bf22d67b2f7411f5a7d04ceade82b0dd
|
TypeScript
|
geraldobraz/web-template-project
|
/backend/src/modules/examples/repositories/ExampleRepository.ts
| 2.953125
| 3
|
import Example from './entities/Example';
import IExampleRepository from './IExampleRepository'
class ExampleRepository implements IExampleRepository {
private _examples: Example[] = [
{
id: '1',
name: 'example1',
age: 10,
email: 'email1@email.com'
},
{
id: '2',
name: 'example2',
age: 20,
email: 'email2@email.com'
},
{
id: '3',
name: 'example3',
age: 30,
email: 'email3@email.com'
},
];
findById(id: string): Example | undefined {
return this._examples.find(example => example.id === id);
}
findByEmail(email: string): Example | undefined {
return this._examples.find(example => example.email === email);
}
save(example: Example): Example {
this._examples.push(example);
return example;
}
}
export default ExampleRepository;
|
1fd5eb2580f4c47431c04685a431e91b1f6e10f9
|
TypeScript
|
Ayzrian/e-shop
|
/shop-api/src/product/models/characteristic-descriptor.model.ts
| 2.578125
| 3
|
import {
AllowNull,
BelongsTo,
Column,
ForeignKey,
Model,
Table,
} from 'sequelize-typescript';
import { ProductType } from './product-type.model';
@Table
export class CharacteristicDescriptor extends Model<CharacteristicDescriptor> {
@AllowNull(false)
@Column
name: string;
@AllowNull(true)
@Column
description?: string;
@BelongsTo(() => ProductType)
productType: ProductType;
@ForeignKey(() => ProductType)
@AllowNull(false)
@Column
productTypeId: number;
}
|
5e75a029d2ae904200fcfc03f74806f3ebc4d811
|
TypeScript
|
Julien-rtg/angular-php
|
/src/app/user.directive.ts
| 2.640625
| 3
|
import { Component, ElementRef, HostBinding, HostListener, Input } from '@angular/core';
@Component({
selector: 'user',
template: `
<h3> {{firstName}} {{lastName}} </h3>
<ng-content></ng-content>
<p> {{age}} </p>
<button (click)="onClickDelete()" >Delete</button>
<input #newName type="text" placeholder="New Name"/>
<button (click)="onClickUpdate(newName.value)"> Update </button>
`,
// templateUrl : path // for html files instead of write here
})
export class UserDirective {
private element: HTMLDivElement;
@Input('first-name')
firstName?: string;
@Input('last-name')
lastName?: string;
@Input()
age?: number;
constructor(element: ElementRef) {
this.element = element.nativeElement;
}
ngOnInit(){}
onClickDelete(){
this.element.remove();
}
onClickUpdate(newName: string){
this.lastName = newName;
}
}
|
943ec136c41bbbc4d64e8b8bebcc828f5281ee4a
|
TypeScript
|
meireliezer/memory-game
|
/src/app/core/memory-data.service.ts
| 2.6875
| 3
|
import { Injectable } from '@angular/core';
export interface ICardData {
color: string;
symbol:string;
}
export interface IPair {
id: number;
data: ICardData;
}
@Injectable({
providedIn: 'root'
})
export class MemoryDataService {
private _dataList: Array<ICardData> = [
{color: '#222222', symbol: '☀'},
{color: '#FF0000', symbol: '☂'},
{color: '#ff9933', symbol: '☆'},
{color: '#FFFF00', symbol: '☎'},
{color: '#33ff33', symbol: '☢'},
{color: '#009800', symbol: '☮'},
{color: '#33ffff', symbol: '☯'},
{color: '#1292ff', symbol: '☺'},
{color: '#0000FF', symbol: '☼'},
{color: '#9933ff', symbol: '♛'},
{color: '#ff00ff', symbol: '♨'},
{color: '#ff3366', symbol: '♻'},
{color: '#fceabf', symbol: '⚇'},
];
constructor() {
}
public getRandomPairs(num: number): Array<IPair>{
let randomData = this.randomize(this._dataList);
randomData.length = num;
let pairs = [];
randomData.map((data, index) => {
pairs.push({id:index, data: data});
pairs.push({id:index, data: data});
});
let randomPairs = this.randomize(pairs);
return randomPairs;
}
private randomize(list: Array<any>){
let newList = [...list];
let len = newList.length;
for(let i=0; i< len ; ++i){
let rnd = Math.floor(Math.random()*len);
let tmp = newList[i];
newList[i] = newList[rnd];
newList[rnd] = tmp;
}
return newList;
}
}
|
25def7711d059e65ea01b35907b1c08cb81928c7
|
TypeScript
|
dtoloto/devires
|
/src/modules/types/repositories/ITypeRepository.ts
| 2.5625
| 3
|
import Type from '../infra/typeorm/entities/Type';
import ICreateTypeDTO from '../dtos/ICreateTypeDTO';
export default interface ITypesRepository {
findAll(): Promise<Type[]>;
findById(id: string): Promise<Type | undefined>;
findByName(name: string): Promise<Type | undefined>;
create(data: ICreateTypeDTO): Promise<Type>;
save(type: Type): Promise<Type>;
}
|
5269903646d644f86f7c16b704d89ef337362209
|
TypeScript
|
acdibble/aoc
|
/2020/ts/day22/part1.ts
| 3.21875
| 3
|
import { readFile } from "../utils.ts";
const [deck1, deck2] = (await readFile(import.meta.url)).split("\n\n")
.map((deck) => deck.split("\n").slice(1).map(Number));
const calculateScore = (deck: number[]): number => {
let result = 0;
const { length } = deck;
for (let i = 0; i < length; i++) {
result += (deck[i] * (length - i));
}
return result;
};
while (deck1.length !== 0 && deck2.length !== 0) {
const card1 = deck1.shift()!;
const card2 = deck2.shift()!;
if (card1 > card2) {
deck1.push(card1, card2);
} else {
deck2.push(card2, card1);
}
}
console.log(Math.max(calculateScore(deck1), calculateScore(deck2)));
|
0efd74327adff9697bb4d6a041e7683ef8ce3c5e
|
TypeScript
|
amourlanne/ent
|
/api/src/middlewares/AuthenticationInfoFromCookieMiddleware.ts
| 2.515625
| 3
|
import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers';
import { NextFunction, Request, Response } from 'express';
import globalConfig from '../../config';
@Middleware({ type: "before", priority: 10 })
export class AuthenticationInfoFromCookieMiddleware implements ExpressMiddlewareInterface {
async use(request: Request, response: Response, next: NextFunction) {
const tokenPayload = request.cookies[globalConfig.tokenPayloadCookieName];
const tokenSignature = request.cookies[globalConfig.tokenSignatureCookieName];
request.authInfo = {
tokenPayload,
tokenSignature,
};
if(tokenPayload && tokenSignature) {
const token = tokenPayload.concat('.', tokenSignature);
// request.headers.authorization = `JWT ${token}`;
request.authInfo.token = token;
}
next();
}
}
|
625774b8c93e47549e1d8086a0e92e9cee6ce496
|
TypeScript
|
Sevdariel/ANF
|
/PRECourse/TypeScript/Handbook/TypeManipulation/Conditional Types/inferring-within-conditional-types.ts
| 3.28125
| 3
|
type FlattenI<Type> = Type extends Array<infer Item> ? Item : Type;
type GetReturnType<Type> = Type extends (...args: never[]) => infer Return ? Return : never;
type NumI = GetReturnType<() => number>;
type StrI = GetReturnType<(x: string) => string>;
type Bools = GetReturnType<(a: boolean, b: boolean) => boolean[]>;
declare function stringOrNum(x: string): number;
declare function stringOrNum(x: number): string;
declare function stringOrNum(x: string | number): string | number;
type T1 = ReturnType<typeof stringOrNum>;
|
fdce8dbe89a23e66418b613e4cc078c1c54fe528
|
TypeScript
|
ftonato/graphql-node-api
|
/src/interfaces/User.interface.ts
| 2.671875
| 3
|
import * as Sequelize from 'sequelize';
export interface UserAttributes {
id?: number;
name?: string;
email?: string;
password?: string;
}
export interface UserInstance extends Sequelize.Instance<UserAttributes>, UserAttributes {
isPassword(encodedPassword: string, password: string): boolean;
}
|
b58fc7e5318771bd0d4e7acd12ce68650d9b567f
|
TypeScript
|
gopendrajangir/howdoising
|
/src/actions/types.ts
| 2.53125
| 3
|
export interface NotificationUser {
_id: string;
name: string;
photo: string;
}
export interface NotificationRecording {
_id: string;
title: string;
}
export interface RatingNotification {
id: string;
rating: number;
recording: NotificationRecording;
user: NotificationUser;
}
export interface CommentNotification {
id: string;
recording: {
_id: string;
title: string;
};
user: {
_id: string;
name: string;
photo: string;
};
textComment?: string;
voiceComment?: string;
}
export interface AnswerNotification {
id: string;
question: {
_id: string,
title: string,
},
user: {
_id: string,
name: string,
photo: string,
},
textAnswer?: string,
voiceAnswer?: string,
}
export interface Notification {
_id: string;
createdAt: Date;
updatedAt: Date;
rating?: RatingNotification;
comment?: CommentNotification;
answer?: AnswerNotification;
}
export interface LoggedInUser {
id: string;
_id: string;
email: string;
name: string;
photo: string;
unreadNotifications: number;
notifications: Notification[];
}
export interface User {
_id: string;
name: string;
photo: string;
id: string;
}
export interface UserMeRating extends Omit<Rating, 'recording'> {
recording: {
_id: string,
id: string
title: string,
description: string,
user: User,
},
}
export interface UserMeComment extends Omit<Comment, 'recording'> {
recording: {
_id: string,
id: string
title: string,
description: string,
user: User,
},
}
export interface UserMe {
id: string;
_id: string;
email: string;
name: string;
photo: string;
recordings: HomeRecording[];
ratings: UserMeRating[],
comments: UserMeComment[]
}
export interface HomeRecording {
id: string;
_id: string;
title: string;
description: string;
user: User;
commentsQuantity: number;
createdAt: Date;
ratingsAverage: number;
ratingsQuantity: number;
recording: string;
updatedAt: Date;
userCommented: boolean;
userRated: number | false;
}
export interface Rating {
_id: string;
id: string;
rating: number;
recording: string;
user: User;
updatedAt: Date;
}
export interface Comment {
_id: string;
id: string;
textComment?: string;
voiceComment?: string;
recording: string;
user: User;
createdAt: Date;
}
export interface Recording {
id: string;
_id: string;
title: string;
description: string;
user: User;
comments: Comment[],
ratings: Rating[],
commentsQuantity: number;
createdAt: Date;
ratingsAverage: number;
ratingsQuantity: number;
recording: string;
updatedAt: Date;
}
export interface LoginRequestBody {
email: string,
password: string,
}
export interface SetPasswordRequestBody {
password: string,
passwordConfirm: string
}
export interface RatingRequestBody {
rating: number
}
export enum MessageTypes {
danger,
success
}
export interface Message {
message: string,
type: MessageTypes
}
export enum ActionTypes {
loggingIn,
loginSuccess,
loginFailed,
signingUp,
signupSuccess,
signupFailed,
loggingOut,
logoutSuccess,
logoutFailed,
settingPassword,
setPasswordSuccess,
setPasswordFailed,
resettingPassword,
resetPasswordSuccess,
resetPasswordFailed,
fetchRecordingsLoading,
fetchRecordingsSuccess,
fetchRecordingsFailed,
fetchRecordingLoading,
fetchRecordingSuccess,
fetchRecordingFailed,
searchRecordingsLoading,
searchRecordingsSuccess,
searchRecordingsFailed,
fetchMeLoading,
fetchMeSuccess,
fetchMeFailed,
setMessage
}
|
aba563339fe016c1d42acc0a632a1ffefed4ed68
|
TypeScript
|
aaronng91/rockPaperScissors
|
/src/app/player/player.component.spec.ts
| 2.546875
| 3
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PlayerComponent } from './player.component';
import { SimpleChange } from '@angular/core';
describe('PlayerComponent', () => {
let component: PlayerComponent;
let element: any;
let fixture: ComponentFixture<PlayerComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PlayerComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PlayerComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
component.playerName = '1';
fixture.detectChanges();
});
it('should display player name', () => {
expect(element.querySelector('.player-name').innerText)
.toEqual(`Player ${component.playerName}`, 'Player name should be \'Player 1\'');
});
it('should allow player to select an action between rock, paper and scissors', () => {
expect(element.querySelector('.rock')).not.toBeNull('Rock button should be present');
expect(element.querySelector('.paper')).not.toBeNull('Paper button should be present');
expect(element.querySelector('.scissors')).not.toBeNull('Scissors button should be present');
});
it('should emit an event when user chooses an action', done => {
component.actionSelected.subscribe((action: string) => {
expect(action).toEqual('rock', 'Action should be \'rock\'');
done();
});
element.querySelector('.rock').click();
});
it('should disable other actions and highlight selected action when user chooses an action', () => {
element.querySelector('.rock').click();
fixture.detectChanges();
expect(element.querySelector('.rock').disabled).toBeTruthy('Rock button should be disabled');
expect(element.querySelector('.paper').disabled).toBeTruthy('Paper button should be disabled');
expect(element.querySelector('.scissors').disabled).toBeTruthy('Scissors button should be disabled');
expect(element.querySelector('.rock').className).toContain('btn-success', 'Rock button should be selected');
});
it('should re-enable other actions and un-highlight selected action when game resets', () => {
component.ngOnChanges({'reset': {previousValue: false, currentValue: true} as SimpleChange});
fixture.detectChanges();
expect(element.querySelector('.rock').disabled).toBeFalsy('Rock button should be re-enabled');
expect(element.querySelector('.paper').disabled).toBeFalsy('Paper button should be re-enabled');
expect(element.querySelector('.scissors').disabled).toBeFalsy('Scissors button should be re-enabled');
expect(element.querySelector('.rock').className).not.toContain('btn-success', 'Rock button should be un-highlighted');
});
});
|
df014b2e23538972730336e1d7950e987a956a9a
|
TypeScript
|
forJihye/design-patterns
|
/assets/ts/facade.ts
| 3.390625
| 3
|
// 퍼사드패턴으로 전자레인지 만들기
/**
* 만약 퍼사드패턴을 쓰지 않는다면, 우리는 직접 전원 스위치를 on 시켜야 합니다.
* 먼저 쿨러를 작동시키고.. 마그네트론을 작동시키고.. 턴테이블을 돌린 다음에 타이머를 원하는 시간만큼 작동시킵니다.
* 또 만약 정지시키려면 하나하나씩 모두 손수 스위치를 내려 줘야하죠.
*/
interface Switch {
on(): void,
off(): void
}
class Cooler implements Switch {
on(): void {
console.log('쿨러 작동 시작!')
}
off(): void {
console.log('쿨러 작동 종료!')
}
}
class Magnetron implements Switch {
on(): void {
console.log('마이크로파 발생기 켜짐.. 작동 중 !')
}
off(): void {
console.log('마이크로파 발생기 꺼짐')
}
}
class Turntable implements Switch {
on(): void {
console.log('턴테이블이 움직입니다.')
}
off(): void {
console.log('턴테이블이 멈췄습니다.')
}
}
class TimerChecker implements Switch {
static TIME_INTERVAL: number = 1000;
private EXPIRED_TIME: number;
microwave: MicrowaveFacade;
count: number = 0;
timer: any;
constructor(milsec: number, microwave: MicrowaveFacade){
this.EXPIRED_TIME = milsec;
this.count = this.EXPIRED_TIME/1000;
this.microwave = microwave;
this.timer = setInterval(() => {
if(this.count > 0){
console.log('Timer...' + this.count-- + "초")
}else{
clearInterval(this.timer);
this.off();
this.microwave.off();
}
}, 1000);
}
on(): void {
console.log('조리 시작!')
}
off(): void {
console.log('조리가 완료!');
}
}
export default class MicrowaveFacade {
cooler: Cooler;
magentron: Magnetron;
turntable: Turntable;
timerCheck: TimerChecker;
switchs: Set<any> = new Set();
isActive: Boolean = false;
constructor(milsec: number){
this.cooler = new Cooler();
this.magentron = new Magnetron();
this.turntable = new Turntable();
this.timerCheck = new TimerChecker(milsec, this);
this.switchs = new Set([this.cooler, this.magentron, this.timerCheck, this.turntable]);
this.on();
}
on(): void {
for (let item of this.switchs) item.on()
this.isActive = true;
}
off(): void {
for (let item of this.switchs) item.off();
this.isActive = false;
}
}
|
1ac93c1676db237edac445332d93b8b6f9dd1930
|
TypeScript
|
Keimeno/segno
|
/tests/validations/isMultibyte.test.ts
| 2.515625
| 3
|
import { test } from '../index.ts';
Deno.test('should validate multibyte strings', () => {
test({
validator: 'isMultibyte',
valid: [
'ひらがな・カタカナ、.漢字',
'あいうえお foobar',
'test@example.com',
'1234abcDExyz',
'カタカナ',
'中文',
],
invalid: ['abc', 'abc123', '<>@" *.'],
});
});
|
2bdc0c00a2be318e66608b35e696d0b5b54883ac
|
TypeScript
|
Turfjs/turf
|
/packages/turf-boolean-parallel/index.ts
| 3.5
| 4
|
import { Feature, Geometry, LineString, Position } from "geojson";
import cleanCoords from "@turf/clean-coords";
import lineSegment from "@turf/line-segment";
import rhumbBearing from "@turf/rhumb-bearing";
import { bearingToAzimuth } from "@turf/helpers";
/**
* Boolean-Parallel returns True if each segment of `line1` is parallel to the correspondent segment of `line2`
*
* @name booleanParallel
* @param {Geometry|Feature<LineString>} line1 GeoJSON Feature or Geometry
* @param {Geometry|Feature<LineString>} line2 GeoJSON Feature or Geometry
* @returns {boolean} true/false if the lines are parallel
* @example
* var line1 = turf.lineString([[0, 0], [0, 1]]);
* var line2 = turf.lineString([[1, 0], [1, 1]]);
*
* turf.booleanParallel(line1, line2);
* //=true
*/
function booleanParallel(
line1: Feature<LineString> | LineString,
line2: Feature<LineString> | LineString
): boolean {
// validation
if (!line1) throw new Error("line1 is required");
if (!line2) throw new Error("line2 is required");
var type1 = getType(line1, "line1");
if (type1 !== "LineString") throw new Error("line1 must be a LineString");
var type2 = getType(line2, "line2");
if (type2 !== "LineString") throw new Error("line2 must be a LineString");
var segments1 = lineSegment(cleanCoords(line1)).features;
var segments2 = lineSegment(cleanCoords(line2)).features;
for (var i = 0; i < segments1.length; i++) {
var segment1 = segments1[i].geometry.coordinates;
if (!segments2[i]) break;
var segment2 = segments2[i].geometry.coordinates;
if (!isParallel(segment1, segment2)) return false;
}
return true;
}
/**
* Compares slopes and return result
*
* @private
* @param {Geometry|Feature<LineString>} segment1 Geometry or Feature
* @param {Geometry|Feature<LineString>} segment2 Geometry or Feature
* @returns {boolean} if slopes are equal
*/
function isParallel(segment1: Position[], segment2: Position[]) {
var slope1 = bearingToAzimuth(rhumbBearing(segment1[0], segment1[1]));
var slope2 = bearingToAzimuth(rhumbBearing(segment2[0], segment2[1]));
return slope1 === slope2;
}
/**
* Returns Feature's type
*
* @private
* @param {Geometry|Feature<any>} geojson Geometry or Feature
* @param {string} name of the variable
* @returns {string} Feature's type
*/
function getType(geojson: Geometry | Feature<any>, name: string) {
if ((geojson as Feature).geometry && (geojson as Feature).geometry.type)
return (geojson as Feature).geometry.type;
if (geojson.type) return geojson.type; // if GeoJSON geometry
throw new Error("Invalid GeoJSON object for " + name);
}
export default booleanParallel;
|
f2152962157aa82845675d0d9a9a4df15e0d7265
|
TypeScript
|
WaywardGame/tars
|
/src/objectives/other/EmptyWaterContainer.ts
| 2.71875
| 3
|
/*!
* Copyright 2011-2023 Unlok
* https://www.unlok.ca
*
* Credits & Thanks:
* https://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide:
* https://github.com/WaywardGame/types/wiki
*/
import Pour from "game/entity/action/actions/Pour";
import type Item from "game/item/Item";
import type Context from "../../core/context/Context";
import type { IObjective, ObjectiveExecutionResult } from "../../core/objective/IObjective";
import { anyWaterTileLocation } from "../../core/navigation/INavigation";
import Objective from "../../core/objective/Objective";
import MoveToTarget from "../core/MoveToTarget";
import UseItem from "./item/UseItem";
/**
* Emptys a water container into the ocean
*/
export default class EmptyWaterContainer extends Objective {
constructor(private readonly item: Item) {
super();
}
public getIdentifier(): string {
return `EmptyWaterContainer:${this.item}`;
}
public getStatus(): string | undefined {
return `Emptying ${this.item?.getName()}`;
}
public async execute(context: Context): Promise<ObjectiveExecutionResult> {
const objectivePipelines: IObjective[][] = [];
const targets = context.utilities.tile.getNearestTileLocation(context, anyWaterTileLocation);
for (const { tile } of targets) {
const objectives: IObjective[] = [];
objectives.push(new MoveToTarget(tile, true));
objectives.push(new UseItem(Pour, this.item));
objectivePipelines.push(objectives);
}
return objectivePipelines;
}
}
|
ac95a21b3860589754e6e47fc80e2838175b100b
|
TypeScript
|
bodinsamuel/konveyor
|
/src/Command.ts
| 2.8125
| 3
|
import type {
CallbackBefore,
Callback,
CallbackAll,
DependenciesPlan,
} from './@types/command';
import type { ConfigDefault } from './@types/config';
import { Option } from './Option';
import { CommandUndefinedError } from './errors';
export interface CommandArgs<TConf extends ConfigDefault> {
name: string;
description?: string;
isPrivate?: boolean;
options?: Option[];
dependencies?: Command<TConf>[] | DependenciesPlan<TConf>;
before?: Callback<TConf>;
exec?: Callback<TConf>;
after?: Callback<TConf>;
afterAll?: CallbackAll<TConf>;
}
let i = 0;
export class Command<TConf extends ConfigDefault> {
readonly __Command = true;
readonly name: string;
#description: string;
#isPrivate: boolean = false;
#options: Option[] = [];
#id: number = i++;
// state
#executed: boolean = false;
#dependencies: Set<Command<TConf>> = new Set();
#dependenciesPlan?: DependenciesPlan<TConf>;
// actual commands
#before?: Callback<TConf>;
#exec?: Callback<TConf>;
#after?: Callback<TConf>;
#afterAll?: CallbackAll<TConf>;
constructor(args: CommandArgs<TConf>) {
this.name = args.name;
this.#description = args.description || '';
this.#isPrivate = args.isPrivate === true;
this.#before = args.before;
this.#exec = args.exec;
this.#after = args.after;
this.#afterAll = args.afterAll;
if (args.options) {
this.#options = args.options;
}
// Check dependencies
if (args.dependencies && Array.isArray(args.dependencies)) {
this.#dependencies = new Set(args.dependencies);
this.#dependencies.forEach((dep) => {
if (typeof dep === 'undefined') {
throw new CommandUndefinedError(this.name);
}
});
} else if (args.dependencies) {
this.#dependenciesPlan = args.dependencies;
}
}
get description(): string {
return this.#description;
}
get id(): number {
return this.#id;
}
get isPrivate(): boolean {
return this.#isPrivate;
}
static option(long: string, short?: string): Option {
return new Option(long, short);
}
get options(): Option[] {
return this.#options;
}
get dependencies(): Set<Command<TConf>> {
return this.#dependencies;
}
get dependenciesPlan(): DependenciesPlan<TConf> | undefined {
return this.#dependenciesPlan;
}
executed(is: boolean): void {
this.#executed = is;
}
get isExecuted(): boolean {
return this.#executed;
}
get before(): CallbackBefore<TConf> | undefined {
return this.#before;
}
hasBefore(): boolean {
return Boolean(this.#before);
}
get exec(): Callback<TConf> | undefined {
return this.#exec;
}
set exec(e: Callback<TConf> | undefined) {
this.#exec = e;
}
hasExec(): boolean {
return Boolean(this.#exec);
}
get after(): Callback<TConf> | undefined {
return this.#after;
}
hasAfter(): boolean {
return Boolean(this.#after);
}
get afterAll(): CallbackAll<TConf> | undefined {
return this.#afterAll;
}
hasAfterAll(): boolean {
return Boolean(this.#afterAll);
}
}
|
58fbacdaf58591f3a3ee257b507c3df1f3369ff6
|
TypeScript
|
dan-sic/snake_game
|
/src/models/SnakeHead.ts
| 3.15625
| 3
|
import SnakeBlock from "./SnakeBlock";
import Cell from "./Cell";
import Direction from "./enums/Direction";
import Grid from "./Grid";
import Snake from "./Snake";
export default class SnakeHead extends SnakeBlock {
private nextCell: Cell | null = null;
constructor(cell: Cell, snake: Snake) {
super(cell, snake);
this.currentCell = cell;
}
public goToNextCell(direction: Direction, gridInstance: Grid): void {
if (this.nextCell!.getFlyBlock()) {
this.snakeInstance.eatFly(this.nextCell!);
}
if (this.nextCell!.getSnakeBlock()) {
this.snakeInstance.crashIntoTail();
}
this.nextCell!.setSnakeBlock(this);
this.previousCell = this.currentCell;
this.currentCell.removeSnakeBlockFromCell();
this.currentCell = this.nextCell!;
this.setNextCellForHeadBasedOnDirection(direction, gridInstance);
}
public setNextCellForHeadBasedOnDirection(
direction: Direction,
gridInstance: Grid
): void {
const currentHeadPosX: number = this.currentCell.getX();
const currentHeadPosY: number = this.currentCell.getY();
let nextCellPosX: number;
let nextCellPosY: number;
switch (direction) {
case Direction.RIGHT: {
nextCellPosX = currentHeadPosX + 1;
if (nextCellPosX > gridInstance.getWidth() - 1) {
nextCellPosX = currentHeadPosX - gridInstance.getWidth() + 1;
}
nextCellPosY = currentHeadPosY;
break;
}
case Direction.DOWN: {
nextCellPosX = currentHeadPosX;
nextCellPosY = currentHeadPosY + 1;
if (nextCellPosY > gridInstance.getHeight() - 1) {
nextCellPosY = currentHeadPosY - gridInstance.getHeight() + 1;
}
break;
}
case Direction.LEFT: {
nextCellPosX = currentHeadPosX - 1;
if (nextCellPosX < 0) {
nextCellPosX = currentHeadPosX + gridInstance.getWidth() - 1;
}
nextCellPosY = currentHeadPosY;
break;
}
case Direction.UP: {
nextCellPosX = currentHeadPosX;
nextCellPosY = currentHeadPosY - 1;
if (nextCellPosY < 0) {
nextCellPosY = currentHeadPosY + gridInstance.getHeight() - 1;
}
break;
}
default: {
nextCellPosX = currentHeadPosX;
nextCellPosY = currentHeadPosY;
break;
}
}
const nextCell = gridInstance.getCell(nextCellPosX, nextCellPosY);
this.nextCell = nextCell;
}
}
|
891b0aef0b2d5a4e2197eb26cfe77c88ad438fea
|
TypeScript
|
toxic-johann/toxic-decorators
|
/src/watch.ts
| 2.515625
| 3
|
import { bind, isArray, isFunction, isObject, isPlainObject, isString } from 'lodash-es';
import { getDeepProperty } from 'toxic-utils';
import accessor from './accessor';
import applyDecorators from './helper/apply-decorators';
import { compressMultipleDecorators, getOwnKeys, warn } from './helper/utils';
import initialize from './initialize';
import nonenumerable from './nonenumerable';
import { AccessorDescriptor } from './typings/base';
const arrayChangeMethod = [ 'push', 'pop', 'unshift', 'shift', 'splice', 'sort', 'reverse' ];
function deepProxy(
value: object | any[],
hook: (...args: any[]) => any,
// tslint:disable-next-line: trailing-comma
{ diff, operationPrefix }: { diff: boolean, operationPrefix: string }
): object | any[] {
const mapStore: { [x: string]: boolean | any[] | object } = {};
let arrayChanging = false;
const proxyValue = new Proxy(value, {
get(target: any, property: string, receiver: any) {
const value = target[property];
if (isArray(target) && arrayChangeMethod.indexOf(property) > -1) {
return (...args: any[]) => {
arrayChanging = true;
bind(value, receiver)(...args);
arrayChanging = false;
hook();
};
}
if (mapStore[property] === true) { return value; }
if (isPlainObject(value) || isArray(value)) {
const proxyValue = mapStore[property] || deepProxy(value, hook, { diff, operationPrefix });
mapStore[property] = proxyValue;
return proxyValue;
}
mapStore[property] = true;
return value;
},
set(target: any, property: string, value: any) {
const oldVal = target[property];
const newVal = (isPlainObject(value) || isArray(value))
? deepProxy(value, hook, { diff, operationPrefix })
: value;
target[property] = newVal;
mapStore[property] = true;
if (arrayChanging || (diff && oldVal === newVal)) { return true; }
hook();
return true;
},
deleteProperty(target: any, property: string) {
delete target[property];
delete mapStore[property];
if (arrayChanging) { return true; }
hook();
return true;
},
});
const operateProps = {
[operationPrefix + 'set']: [
initialize(() => {
return (property: string, val: any) => {
proxyValue[property] = val;
};
}),
nonenumerable,
],
[operationPrefix + 'del']: [
initialize(() => {
return (property: string) => {
delete proxyValue[property];
};
}),
nonenumerable,
],
};
applyDecorators(proxyValue, operateProps, { self: true });
return proxyValue;
}
function deepObserve(
value: object | any[],
hook: (...args: any[]) => any,
// tslint:disable-next-line: trailing-comma
{ operationPrefix, diff }: { diff: boolean, operationPrefix: string}
): object | any[] {
const mapStore: { [x: string]: boolean | any[] | object } = {};
let arrayChanging = false;
function getPropertyDecorators(keys: string[]): {
[x: string]: PropertyDecorator
| MethodDecorator
| Array<PropertyDecorator | MethodDecorator>,
} {
let oldVal: any;
return keys.reduce((
props: {
[x: string]: PropertyDecorator
| MethodDecorator
| Array<PropertyDecorator | MethodDecorator>,
},
key: string) => {
props[key] = [
accessor({
set(value) {
oldVal = this[key];
return value;
},
}),
accessor({
get(val) {
if (mapStore[key]) { return val; }
if (isPlainObject(val) || isArray(val)) {
deepObserve(val, hook, { operationPrefix, diff });
}
mapStore[key] = true;
return val;
},
set(val) {
if (isPlainObject(val) || isArray(val)) { deepObserve(val, hook, { operationPrefix, diff }); }
mapStore[key] = true;
if (!arrayChanging && (!diff || oldVal !== val)) { hook(); }
return val;
},
}, { preSet: false }),
];
return props;
}, {});
}
// @ts-ignore: symbol[] is the same to string[]
const props = getPropertyDecorators(getOwnKeys(value));
applyDecorators(value, props, { self: true, omit: true });
if (isArray(value)) {
const methodProps = arrayChangeMethod.reduce((
props: { [x: string]: Array<MethodDecorator | PropertyDecorator>},
key) => {
props[key] = [
initialize((method) => {
method = isFunction(method)
? method
: Array.prototype[(key as any)];
return (...args: any[]) => {
const originLength = value.length;
arrayChanging = true;
bind(method, value)(...args);
arrayChanging = false;
if (originLength < value.length) {
const keys = new Array(value.length - originLength)
.fill(1)
.map((value, index) => (index + originLength).toString());
const props = getPropertyDecorators(keys);
applyDecorators(value, props, { self: true, omit: true });
}
hook();
};
}),
nonenumerable,
];
return props;
}, {});
applyDecorators(value, methodProps, { self: true });
}
const operateProps = {
[operationPrefix + 'set']: [
initialize((method) => {
return (
property: string,
val: any,
{ disable, isNewVal }: { disable?: boolean, isNewVal?: boolean } = {}) => {
isNewVal = isNewVal || getOwnKeys(value).indexOf(property) === -1;
if (isFunction(method)) {
bind(method, this)(property, val, { disable: true, isNewVal });
}
if (isNewVal) {
const props = getPropertyDecorators([ property ]);
applyDecorators(value, props, { self: true, omit: true });
}
if (!disable) {
// @ts-ignore: omit index error
value[property] = val;
}
};
}),
nonenumerable,
],
[operationPrefix + 'del']: [
initialize((method) => {
return (property: string) => {
if (isFunction(method)) {
bind(method, this)(property);
} else {
// @ts-ignore: omit index error
delete value[property];
}
hook();
};
}),
nonenumerable,
],
};
applyDecorators(value, operateProps, { self: true });
return value;
}
export default function watch(...args: Array<string | ((...args: any[]) => any) | {
deep?: boolean,
diff?: boolean,
omit?: boolean,
proxy?: boolean,
other?: any,
operationPrefix?: string,
}>): PropertyDecorator {
// @ts-ignore: type is narrow down to object here
const option: {
deep?: boolean,
diff?: boolean,
omit?: boolean,
proxy?: boolean,
other?: any,
operationPrefix?: string,
} = isPlainObject(args[args.length - 1])
? args[args.length - 1]
: {};
const {
deep,
omit,
other,
operationPrefix = '__',
diff = true,
} = option;
let { proxy } = option;
if (typeof Proxy !== 'function') {
proxy = false;
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
warn('You browser do not support Proxy, we will fall back into observe mode.');
}
}
if (!args.length) { throw new TypeError('You must pass a function or a string to find the hanlder function.'); }
if (other !== undefined && !isObject(other)) {
throw new TypeError('If you want us to trigger function on the other instance, you must pass in a legal instance');
}
if (!isString(operationPrefix)) { throw new TypeError('operationPrefix must be an string'); }
// @ts-ignore: this is a propertydecorator
return function(obj: any, prop: string, descriptor: void | PropertyDescriptor): AccessorDescriptor {
const fns = args.reduce((fns, keyOrFn, index) => {
if (!isString(keyOrFn) && !isFunction(keyOrFn)) {
if (!index || index !== args.length - 1) {
throw new TypeError('You can only pass function or string as handler');
}
return fns;
}
fns.push(isString(keyOrFn)
? function(newVal: any, oldVal: any) {
const target = other || obj;
const fn = getDeepProperty(target, keyOrFn);
if (!isFunction(fn)) {
if (!omit) {
// tslint:disable-next-line max-line-length
throw new Error('You pass in a function for us to trigger, please ensure the property to be a function or set omit flag true');
}
return;
}
return bind(fn, this)(newVal, oldVal);
}
: keyOrFn);
return fns;
}, []);
const handler = function(newVal: any, oldVal: any) {
fns.forEach((fn) => bind(fn, this)(newVal, oldVal));
};
let inited = false;
let oldVal: any;
let newVal: any;
let proxyValue: any;
// @ts-ignore: docorator can call in JavaScript
return compressMultipleDecorators(
accessor({
set(value) {
oldVal = this[prop];
proxyValue = undefined;
const hook = () => bind(handler, this)(newVal, oldVal);
return (deep && (isPlainObject(value) || isArray(value)))
? proxy
? deepProxy(value, hook, { diff, operationPrefix })
: deepObserve(value, hook, { operationPrefix, diff })
: value;
},
get(value) {
if (proxyValue) { return proxyValue; }
if (!inited) {
inited = true;
const hook = () => bind(handler, this)(newVal, oldVal);
if (deep && (isPlainObject(value) || isArray(value))) {
if (proxy) {
proxyValue = deepProxy(value, hook, { diff, operationPrefix });
oldVal = proxyValue;
newVal = proxyValue;
return proxyValue;
}
deepObserve(value, hook, { operationPrefix, diff });
}
oldVal = value;
newVal = value;
}
return value;
},
}, { preSet: true }),
accessor({
set(value) {
newVal = value;
if (!diff || oldVal !== value) { bind(handler, this)(newVal, oldVal); }
oldVal = value;
return value;
},
}, { preSet: false }))(obj, prop, descriptor);
};
}
|
18415cf4c8fef405bdee877cde3b4cbbfffabe54
|
TypeScript
|
uxdm/uxdm
|
/packages/model-sketch/src/functions/fromSketchJSON.ts
| 2.59375
| 3
|
import { SketchFormat } from '../types';
import { Rectangle, Group } from '../layers';
/**
* 将 单个 SketchJSON 对象 转换为 UXDM Sketch Model
*/
export const fromSingleSketchFormat = (json: SketchFormat.AnyLayer) => {
switch (json._class) {
case 'group':
return Group.fromSketchJSON(json);
// default:
case 'rectangle':
return Rectangle.fromSketchJSON(json);
// case 'symbolMaster':
// break;
// case 'artboard':
// break;
// case 'oval':
// break;
// case 'polygon':
// break;
// case 'shapePath':
// break;
// case 'star':
// break;
// case 'triangle':
// break;
// case 'shapeGroup':
// break;
// case 'text':
// break;
// case 'symbolInstance':
// break;
// case 'slice':
// break;
// case 'MSImmutableHotspotLayer':
// break;
// case 'bitmap':
// break;
// case 'page':
// break;
default:
throw Error('不符合 Sketch JSON Format');
}
};
/**
* 将 SketchJSON 转换为 UXDM Sketch Model
* @param json
*/
export const fromSketchJSON = (
json: SketchFormat.AnyLayer | SketchFormat.AnyLayer[],
) => {
if (json instanceof Array) {
return json.map(fromSingleSketchFormat);
}
return fromSingleSketchFormat(json);
};
|
881ab4063d69f11c818658c0b513a6e4c6e32af6
|
TypeScript
|
phtn/i3
|
/src/observables/data.ts
| 2.578125
| 3
|
import { observable, action } from "mobx";
import { createContext } from "react";
import firebase, { provider, db } from "../firebase";
provider.addScope("repo");
class AppData {
@observable uid: any = ""
@observable user: any = "";
@observable photoURL: any;
@observable connectionStatus: string = 'Continue with Github'
version: string = '1.0.1'
@observable devs: any = []
@observable userData: any = []
@action
fetchDevs() {
db.collection('devs').get()
.then(this.fetchDevsSuccess).catch(error => window.console.log(error.message))
}
@action.bound
fetchDevsSuccess(snapshot: any) {
let d: any = []
return snapshot.forEach((doc: { data: () => void; }) => {
d.push(doc.data())
this.devs = d
})
}
checkAuthState() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.uid = user.uid
this.user = user.displayName;
this.photoURL = user.photoURL;
this.connectionStatus = 'Connecting...'
// this.fetchUserData(user.uid)
// window.console.log(user.uid)
}
});
}
@action // SIGN IN WITH GITHUB
signInWithGithub() {
firebase
.auth()
.signInWithPopup(provider)
.then(result => {
if (result.user) {
window.console.log(result.user.uid)
const docRef = db.collection('users').doc(result.user.uid)
const userId = result.user.uid
const userDisplayName = result.user.displayName
docRef.get().then(userDoc => {
if (!userDoc.exists) { // ✨ NEW USER ✨
db.collection('users').doc(userId)
.set({
name: userDisplayName,
coins: 0,
level: 1,
createdAt: new Date(),
devs: [{ name: 'Dan Abramov', income: 400, id: '01' }, { name: 'Emma Wedekind', income: 600, id: '02' }],
})
.then(() => {
// TODO: PASS DATA TO OBSERVABLE
window.console.log(userDisplayName)
})
.catch(error => window.console.warn(error));
}
// 🌟 EXISTING USER 🌟
// TODO: PASS DATA TO OBSERVABLE
db.collection('users').doc(userId).get().then( (doc: { data: () => void; } ) => {
// if (doc.exists){
window.console.log('user exists: ', doc.data())
// }
})
})
// db.runTransaction(async transaction => {
// const userDoc = await transaction.get(docRef);
// if (!userDoc.exists) { // NEW USER
// db.collection('users').doc(userId)
// .set({
// devs: [{ dan: 'Dan Abramov' }, { emma: 'Emma Wedekind' }],
// name: userDisplayName,
// coins: 0
// }, { merge: true })
// .then(() => window.console.log('data is set'))
// .catch(error => window.console.warn(error));
// }
// docRef.get().then( userDoc => {
// if (userDoc.exists){
// window.console.log(userDoc.data())
// }
// })
// }) // TRANSACTION
}
})
.catch(error => window.console.log(error));
}
@action
fetchUserData() {
if (this.uid){
db.collection('users').doc(this.uid).get().then(userDoc => {
if (userDoc.exists) {
// window.console.log(userDoc.data())
this.userData = userDoc.data()
}
})
}
}
signOut() {
firebase
.auth()
.signOut()
.then(() => {
window.console.log('Signed out.');
})
.catch(error => window.console.log(error));
}
}
export const AppStore = createContext(new AppData());
|
1c6087a9aa6d93263c35b3ae0e5b15d0fb9afcef
|
TypeScript
|
SerhiiShvets/AngularApp
|
/src/app/shared/articles-data.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
export interface Article {
id: number;
heading: string;
date: Date;
author: string;
shortDescription: string;
content: string;
sourceUrl: string;
}
@Injectable({
providedIn: 'root'
})
export class ArticlesDataService {
newId: number;
newHeading: string;
newDate: string;
newAuthor: string;
newShortDescription: string;
newContent: string;
newSourceUrl: string;
newArticle: Article;
constructor() { }
getData(): Article[] {
return this.articles;
}
public articles: Article[] = [
{id: 0, heading: 'Reuters', date: new Date(2020,20,2), author: 'Arthur Conan Doyle', shortDescription: 'Description', content: 'Some content', sourceUrl: 'http://someurl.com'},
{id: 1, heading: 'Associated Press', date: new Date(2020,20,2), author: 'Jack London', shortDescription: 'Description', content: 'Some content', sourceUrl: 'http://someurl.com'},
{id: 2, heading: 'Agence France-Presse', date: new Date(2020,20,2), author: 'Jules Verne', shortDescription: 'Description', content: 'Some content', sourceUrl: 'http://someurl.com'}
];
}
|
0012b9b39413ce4271d823fe4b3f7eb7ccd1f81e
|
TypeScript
|
nwt-team/nwt-back
|
/src/user/dto/create-user.dto.ts
| 2.6875
| 3
|
import {
IsArray,
IsDate, IsDateString, IsEmail, IsHash,
IsMongoId,
IsOptional,
IsString,
IsUrl, Matches,
} from 'class-validator';
export class CreateUserDto {
@IsUrl()
@IsOptional()
avatar?: string
@IsString()
@IsOptional()
firstname?: string
@IsString()
@IsOptional()
lastname?: string
@IsString()
login: string
@Matches(/^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/gm)
password: string
@IsDateString()
@IsOptional()
birthDate?: string
@IsEmail()
email: string
@IsArray()
@IsString({each:true})
@IsMongoId({each:true})
@IsOptional()
playlists?: string[]
}
|
982cced11e7314d12bae441c35bcf7137185eed1
|
TypeScript
|
gargigoyal-9602/okyd-pim-project
|
/packages/components/dist/components/src/CustomCheckBox.d.ts
| 2.578125
| 3
|
import PropTypes from 'prop-types';
import { Component } from 'react';
declare type MyProps = {
testID: string;
isChecked: boolean;
onChangeValue?: (value: boolean) => void;
};
declare type MyState = {
isChecked: boolean;
onChangeValue?: (value: boolean) => void;
};
export default class CustomCheckBox extends Component<MyProps, MyState> {
static propTypes: {
testID: PropTypes.Requireable<string>;
isChecked: PropTypes.Validator<boolean>;
onChangeValue: PropTypes.Validator<(...args: any[]) => any>;
};
constructor(props: any);
render(): JSX.Element;
componentWillReceiveProps(nextProps: any): void;
handleValueChange(value: boolean): void;
}
export {};
|
457f506bbdfded447a4e34acac1df3487562275c
|
TypeScript
|
techoi/typescript-next
|
/interfaces/index.ts
| 3
| 3
|
// You can include shared interfaces/types in a separate file
// and then use them in any component by importing them. For
// example, to import the interface below do:
//
// import User from 'path/to/interfaces';
export type User = {
id: number
name: string
}
export interface ICounterState {
count: number;
}
export interface IReducerAction {
type: string;
payload: any;
error: string;
}
export interface IReducerStates {
counter: ICounterState;
}
|
1ac9268bd8dd8df5d657342f031781ceba4fab46
|
TypeScript
|
zjayers/nest-dependency-injection-example
|
/src/cpu/cpu.service.ts
| 2.78125
| 3
|
import { Injectable, Logger } from '@nestjs/common';
import { PowerService } from '../power/power.service';
@Injectable()
export class CpuService {
private readonly WATTS: number = 15;
private readonly logger = new Logger(CpuService.name);
constructor(private readonly powerService: PowerService) {}
public computeSumOf(a: number, b: number): number {
this.logger.log(`CPU: Requesting ${this.WATTS} watts of power...`);
this.powerService.supplyPower(this.WATTS);
return a + b;
}
}
|
df45babfa1657a20f92c42d011c8c7d1f0875fb8
|
TypeScript
|
higharc91/arc_udacity_nanodegree_prj2
|
/src/server.ts
| 2.828125
| 3
|
import express from 'express';
import bodyParser from 'body-parser';
import { Request, Response } from "express"
import {filterImageFromURL, deleteLocalFiles} from './util/util';
type ImageReqQuery = {
image_url: string;
}
(async () => {
// Init the Express application
const app = express();
// Set the network port
const port = process.env.PORT || 8082;
// Use the body parser middleware for post requests
app.use(bodyParser.json());
app.get('/filteredimage', async (req: Request<any, any, any, ImageReqQuery>, res) => {
if(!req.query.image_url) {
res.status(400).send({response: 'query parameter image_url required.'})
}
try {
const localPath = await filterImageFromURL(req.query.image_url);
res.sendFile(localPath, {}, err => {
if(err) {
throw new Error('File send error')
}
// clean up files if any.
deleteLocalFiles([localPath]);
})
}
catch (e) {
res.status(500).send({response: 'unable to filter image from provided URL'})
}
})
// Root Endpoint
// Displays a simple message to the user
app.get( "/", async ( req, res ) => {
res.send("try GET /filteredimage?image_url={{}}")
} );
// Start the Server
app.listen( port, () => {
console.log( `server running http://localhost:${ port }` );
console.log( `press CTRL+C to stop server` );
} );
})();
|
45f09a3a0c9b6a0e9ef385f3dd638192a45912d8
|
TypeScript
|
shnning/vue-cooler-lazyload
|
/src/types.ts
| 2.5625
| 3
|
export interface Border {
top?: number;
bottom?: number;
left?: number;
right?: number;
}
export interface LazyloadOptions {
border?: Border;
threshold?: number;
cacheImage?: boolean
beforeLoad?: LazyloadCallback;
afterLoad?: LazyloadCallback;
}
export interface IntersectionObserverConfig {
rootMargin: string;
threshold: number;
}
export interface LazyloadCallback {
(el: HTMLElement): void
}
|
1752a41a6ddf5e9cbebb58e2f79d26da73cd62d2
|
TypeScript
|
euliveiras/myformapp-backend
|
/src/modules/users/infra/typeorm/repositories/UserRepository.ts
| 2.78125
| 3
|
import { getRepository, Repository } from "typeorm";
//
import User from "../entities/User";
import IUserRepository from "../../../repositories/IUserRepository";
interface ICreateDTO {
user: string;
email: string;
password: string;
}
export default class UserRepository implements IUserRepository {
private ormRepository: Repository<User>;
constructor() {
this.ormRepository = getRepository(User);
}
public async create({
user,
email,
password,
}: ICreateDTO): Promise<User> {
const newUser = this.ormRepository.create({
user,
email,
password,
});
await this.ormRepository.save(newUser);
return newUser;
}
public async findByEmail(email: string): Promise<User | undefined> {
const findUser = await this.ormRepository.findOne({ where: { email } });
return findUser;
}
}
|
ab2351b27d652e7b7cbabf57dae28ba76fe4bbd7
|
TypeScript
|
SR2k/leetcode
|
/6/283.移动零.ts
| 3.65625
| 4
|
/*
* @lc app=leetcode.cn id=283 lang=typescript
*
* [283] 移动零
*
* https://leetcode.cn/problems/move-zeroes/description/
*
* algorithms
* Easy (64.03%)
* Likes: 1633
* Dislikes: 0
* Total Accepted: 788.6K
* Total Submissions: 1.2M
* Testcase Example: '[0,1,0,3,12]'
*
* 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
*
* 请注意 ,必须在不复制数组的情况下原地对数组进行操作。
*
*
*
* 示例 1:
*
*
* 输入: nums = [0,1,0,3,12]
* 输出: [1,3,12,0,0]
*
*
* 示例 2:
*
*
* 输入: nums = [0]
* 输出: [0]
*
*
*
* 提示:
*
*
*
* 1 <= nums.length <= 10^4
* -2^31 <= nums[i] <= 2^31 - 1
*
*
*
*
* 进阶:你能尽量减少完成的操作次数吗?
*
*/
export
// @lc code=start
function moveZeroes(nums: number[]): void {
let p = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) {
continue
}
nums[p++] = nums[i]
}
while (p < nums.length) {
nums[p++] = 0
}
}
// @lc code=end
|
e518e4c6810b75b621ced4e238f87fc190ba681d
|
TypeScript
|
FrederikWillem/mex-game
|
/angular2-front-end/app/successive-advice.pipe.ts
| 2.734375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { MEX } from './mex';
@Pipe({
name: 'successiveAdvice'
})
export class SuccessiveAdvicePipe implements PipeTransform {
/**
* Transforms given amount of advice into the obvious follow up amount of advice.
* @param value current given advice
* @param passedValue current passed value
*/
transform(value: number, passedValue: number): number {
if (value == 0 || passedValue == MEX) {
return 0;
} else if (value > 0) {
return value - 1;
} else {
return 0;
}
}
}
|
9e175b0be3322c03103e52a0e285cfb1126f712c
|
TypeScript
|
danutzcodrescu/angular4-firebase
|
/src/app/shared/pipes/sentance-case.pipe.ts
| 2.75
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sentanceCase'
})
export class SentanceCasePipe implements PipeTransform {
transform(value: string, args: string): string {
const array = value.split(' ');
if (array.length === 1 || args === "sentance") {
return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
} else {
return array.map(elem => elem.charAt(0).toUpperCase() + elem.slice(1).toLowerCase()).join(' ');
}
}
}
|
ea8ecb5d398fae688ec7b92748d43fb32d6b00ea
|
TypeScript
|
pwdrysdale/typeorm_typegraphql
|
/entities/Books.ts
| 2.578125
| 3
|
import { Field, ID, ObjectType } from "type-graphql";
import {
BaseEntity,
Column,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
} from "typeorm";
import { Author } from "./Author";
import { Lazy } from "../types/Lazy";
@ObjectType()
@Entity()
export class Book extends BaseEntity {
@Field(() => ID)
@PrimaryGeneratedColumn()
id: number;
@Field()
@Column()
title: string;
@Field(() => Author, { nullable: true })
@ManyToOne(() => Author, { lazy: true, nullable: true })
author?: Lazy<Author>;
}
|
82ba46cadd6d2eac52857e04cd93f25cee619e51
|
TypeScript
|
origin1tech/facile-core
|
/dist/core/components.d.ts
| 3.40625
| 3
|
/**
* Components Collection
* @desc stores collection of components.
*
* @export
* @class Components
* @template T
*/
export declare class Collection<T> {
/**
* _components
*
* @desc contains map of components.
* @member _components;
* @private
* @type {{ [name: string]: T }}
* @methodOf Components
*/
private _components;
/**
* _name
*
* @desc stores the collection name.
* @member _name;
* @private
* @type {string}
* @memberOf Components
*/
private _name;
/**
* Creates an instance of Components.
*
* @param {string} name
* @constructor
* @memberOf Components
*/
constructor(name: string);
/**
* _get
*
* @method _get
* @desc gets a component anonymously.
* @private
* @param {string} name
* @returns {*}
*
* @methodOf Components
*/
private _get(name);
/**
* name
*
* @desc returns the name of the collection.
* @method name
* @returns {string}
* @memberOf Components
*/
name(): string;
/**
* get<T>
*
* @desc gets a component by type.
* @method get<T>
* @template T
* @param {string} name
* @returns {T}
*
* @methodOf Components
*/
get<T>(name: string): T;
/**
* add
*
* @desc adds a component to the collection
* @method add
* @param {string} name
* @param {T} item
* @returns
*
* @methodOf Components
*/
add(name: string, item: T): this;
/**
* initialize
*
* @desc initializes component instance.
* @method initialize
* @param {string} name
* @param {...any[]} args
* @returns {*}
*
* @methodOf Components
*/
init(name: string, ...args: any[]): any;
/**
* activate
*
* @desc activates a class as instance.
* @method activate
* @param {{ new (): T }} Type
* @param {any[]} [args]
* @returns {T}
*
* @methodOf Components
*/
activate(Type: {
new (): T;
}, args?: any[]): T;
/**
* remove
*
* @desc removes a component from the collection.
* @method remove
* @param {string} name
* @returns
*
* @methodOf Components
*/
remove(name: string): this;
}
|
b0d4331e318abee3e8ef3d86e7b962b0e25d45b4
|
TypeScript
|
RKRohk/videostream_frontend
|
/src/hooks/useVideoPlayer.ts
| 2.75
| 3
|
import { useContext, useEffect, useLayoutEffect, useRef } from "react";
import { io } from "socket.io-client";
import { NickNameContext } from "../context/namecontext";
import { ActionTypes, Message } from "../reducers/messageReducer";
type ArgType = { timestamp?: Number };
let lock = false;
function unlock() {
setTimeout(() => {
lock = false;
}, 500);
}
export const useVideoPlayer = (owner: boolean|null, id: string) => {
const videoRef = useRef<HTMLVideoElement>(null);
const {name} = useContext(NickNameContext)
const socket = io("http://152.67.11.148:5000", {
reconnectionDelayMax: 10000,
query: {
room: id,
name: name
},
});
socket.connect();
useLayoutEffect(() => {
console.log("in effect",owner)
if (owner === true) {
videoRef.current?.addEventListener("pause", (event) => {
const videoPlayer = document.getElementById("videoElement") as any;
const currentTime = videoPlayer.currentTime;
socket.emit("pause", { timestamp: currentTime });
const message:Message = {by:name,message:`${name} paused the video`,type:ActionTypes.ACTION}
socket.emit("message",message)
console.log("paused");
});
videoRef.current?.addEventListener("play", (event) => {
const videoPlayer = document.getElementById("videoElement") as any;
const currentTime = videoPlayer.currentTime;
const s = socket.emit("play", { timestamp: currentTime });
const message:Message = {by:name,message:`${name} played the video`,type:ActionTypes.ACTION}
socket.emit("message",message)
console.log("played");
});
videoRef.current?.addEventListener("seeked", (event) => {
if (lock) return;
const videoPlayer = document.getElementById("videoElement") as any;
const currentTime = videoPlayer.currentTime;
socket.emit("seeked", { timestamp: currentTime });
const message:Message = {by:name,message:`${name} seeked the video`,type:ActionTypes.ACTION}
socket.emit("message",message)
});
}
socket.onAny(() => {
// lock = true
// console.log("lock")
});
socket.on("pause", (args: ArgType) => {
console.log("got pause");
const { timestamp } = args;
const videoPlayer = document.getElementById("videoElement") as any;
videoPlayer.currentTime = timestamp;
videoRef.current?.pause();
console.log();
});
socket.on("play", (args: ArgType) => {
console.log("got play");
const { timestamp } = args;
const videoPlayer = document.getElementById("videoElement") as any;
videoPlayer.currentTime = timestamp;
videoRef.current?.play();
});
socket.on("seeked", (args: ArgType) => {
const { timestamp } = args;
const videoPlayer = document.getElementById("videoElement") as any;
videoPlayer.currentTime = timestamp;
unlock();
});
return () => {
socket.disconnect();
};
});
return {videoRef,socket};
};
|
5230fc6314fff391b78a0ba2d400d59a80280b4c
|
TypeScript
|
nymtech/nym
|
/ts-packages/mui-theme/src/theme/common.ts
| 3.015625
| 3
|
import { PaletteMode } from '@mui/material';
import { PaletteOptions } from '@mui/material/styles';
/**
* This interface defines a palette used across Nym for branding
*/
export interface NymPalette {
highlight: string;
status: {
success: string;
info: string;
};
light: string;
dark: string;
muted: {
onDarkBg: string;
};
linkHover: string;
}
/**
* This interface defines the palette for a light or dark mode variant
*/
export interface NymPaletteVariant {
mode: PaletteMode;
background: {
main: string;
paper: string;
};
text: {
main: string;
};
topNav: {
background: string;
};
nav: {
text: string;
background: string;
hover: string;
};
mixnodes: {
status: {
active: string;
standby: string;
};
};
selectionChance: {
overModerate: string;
moderate: string;
underModerate: string;
};
}
// -------------------------------------------------------------------------------------------------------------------
/**
* The Nym palette.
*
* IMPORTANT: do not export this constant, always use the MUI `useTheme` hook to get the correct
* colours for dark/light mode.
*/
export const nymPalette: NymPalette = {
/** emphasises important elements */
highlight: '#FB6E4E',
/** statuses */
status: {
success: '#21D073',
info: '#60D7EF',
},
/** light and dark base values */
light: '#F4F6F8',
dark: '#121726',
/** muted on backgrounds */
muted: {
onDarkBg: '#666B77',
},
linkHover: '#AF4D36',
};
// -------------------------------------------------------------------------------------------------------------------
/**
* Dark mode variant
*/
export const darkMode: NymPaletteVariant = {
mode: 'dark',
background: {
main: nymPalette.dark,
paper: '#242C3D',
},
text: {
main: '#F2F2F2',
},
topNav: {
background: '#111826',
},
nav: {
text: '#F2F2F2',
background: '#242C3D',
hover: '#111826',
},
mixnodes: {
status: {
active: '#20D073',
standby: '#5FD7EF',
},
},
selectionChance: {
overModerate: '#20D073',
moderate: '#EBA53D',
underModerate: '#DA465B',
},
};
/**
* Light mode variant
*/
export const lightMode: NymPaletteVariant = {
mode: 'light',
background: {
main: '#F2F2F2',
paper: '#FFFFFF',
},
text: {
main: '#121726',
},
topNav: {
background: '#111826',
},
nav: {
text: '#F2F2F2',
background: '#242C3D',
hover: '#111826',
},
mixnodes: {
status: {
active: '#1CBB67',
standby: '#55C1D7',
},
},
selectionChance: {
overModerate: '#20D073',
moderate: '#EBA53D',
underModerate: '#DA465B',
},
};
/**
* Map a Nym palette variant onto the MUI palette
*/
export const variantToMUIPalette = (variant: NymPaletteVariant): PaletteOptions => ({
text: {
primary: variant.text.main,
},
primary: {
main: nymPalette.highlight,
contrastText: '#fff',
},
background: {
default: variant.background.main,
paper: variant.background.paper,
},
});
|
9edb599e239bd1f468c5e0b5f974cdf631958243
|
TypeScript
|
racarlosdavid/MatrioshTS
|
/src/assets/MatrioshTS/src/TypeScript/Interpreter/Instruccion/Bloque.ts
| 2.6875
| 3
|
import { Instruccion } from "../Abstract/Instruccion";
import { Entorno } from "../TablaSimbolos/Entorno";
import { ErrorManager } from "../Reportes/ErrorManager";
import { StringBuilder } from "../Edd/StringBuilder";
import { NodoError, TipoError } from "../Reportes/NodoError";
import { Funcion } from "./Funcion";
import { TSCollector } from "../TablaSimbolos/TSCollector";
import { R_TS } from "../Reportes/R_TS";
import { Incremento } from "../FuncionesNativas/Incremento";
import { Manager } from "../Reportes/Manager";
export class Bloque extends Instruccion{
instrucciones:Array<Instruccion>;
constructor(instrucciones:Array<Instruccion>, linea:number, columna:number){
super(linea, columna);
this.instrucciones = instrucciones;
}
ejecutar(ent:Entorno, er:ErrorManager, consola:StringBuilder, tsCollector:TSCollector, reporte_ts:R_TS, ambito:string, padre:string) {
let nuevo = new Entorno(ent);
reporte_ts.addEntorno(nuevo);
for(const instr of this.instrucciones){
try {
let element = instr.ejecutar(nuevo,er,consola,tsCollector,reporte_ts,ambito,padre);
if(element != undefined || element != null){
/*Si no hay recursividad agrego la tabla del entorno al colector para el reporte de todos los entorno
Si hay recursividad no agrego nada porque se encicla ya que son muchos valores */
if (Manager.getManager().getBanderaRecursividad() == false) {
reporte_ts.addLista(nuevo.getReporte(ambito, padre));
}
return element;
}
} catch (error) {
er.addError(new NodoError(TipoError.SEMANTICO, ""+error+"", this.fila, this.columna,ambito));
}
}
reporte_ts.addLista(nuevo.getReporte(ambito, padre));
return null;
}
getDot(builder: StringBuilder, parent: string, cont: number): number {
let nodo:string = "nodo" + ++cont;
builder.append(nodo+" [label=\"Instrucciones\"];\n");
builder.append(parent+" -> "+nodo+";\n");
for (const instr of this.instrucciones) {
cont = instr.getDot(builder, nodo, cont);
}
return cont;
}
traducir(builder: StringBuilder, parent: string) {
let nuevo = new StringBuilder();
for(const instr of this.instrucciones){
try {
//if (instr instanceof Funcion) {
// builder.append(instr.traducir(builder,parent));
//} else {
nuevo.append(instr.traducir(builder,parent)+"\n");
//}
} catch (error) {
console.log(`Error en la traduccion Bloque: ${error}`);
//er.addError(new NodoError(TipoError.SEMANTICO, ""+error+"", this.fila, this.columna));
}
}
return nuevo.toString();
}
}
|
7cc5046418c76fb50c10190f8c7eabddfb1ab939
|
TypeScript
|
nextools/metarepo
|
/packages/auto/core/src/prompt/prompt-log.ts
| 2.609375
| 3
|
import type { TReadonly } from 'tsfn'
import type { TPackageBumpMap, TPackageBump } from '../bump/types'
import type { TMessage, TLogReleaseType, TRequiredPrefixes, TGitMessageMap } from '../types'
import { isResolvedReleaseType } from '../utils'
import { log } from './log'
export const promptLog = (packages: TReadonly<TPackageBumpMap>, gitBumps: TReadonly<TGitMessageMap>, prefixes: TReadonly<TRequiredPrefixes>): void => {
const compileMessages = (name: string, pkg: TReadonly<TPackageBump>): string => {
let result = (gitBumps.get(name) ?? []) as TMessage<TLogReleaseType>[]
if (pkg.deps !== null && pkg.type !== 'initial') {
const depNames = Object.keys(pkg.deps)
.filter((name) => isResolvedReleaseType(packages.get(name)?.type))
if (depNames.length > 0) {
result = result.concat({
type: 'dependencies',
message: `update dependencies \`${depNames.join('`, `')}\``,
})
}
}
return result
.map((message) => `* ${prefixes[message.type]} ${message.message}`)
.join('\n')
}
for (const [name, pkg] of packages) {
if (pkg.type === null || pkg.version === null) {
continue
}
log('')
log(`${name} → ${pkg.type} → v${pkg.version}`)
log(compileMessages(name, pkg))
}
log('')
}
|
f56d62045f1593ed9663dee67eed642a01bde435
|
TypeScript
|
chadoh/autark-challenge-fe-only
|
/app/utils/auth.ts
| 2.515625
| 3
|
const AUTH_CHANGE = 'AuthenticationChangeEvent';
// A "good enough" URL query parser;
// can pull in an external lib later if needed,
// but will replace auth logic with blockchain-based approach before then
const parseUrlParams = (str: string): object => (
str.replace(/^\?/, "").split("&").reduce(
(query, str): object => {
const [key, val] = str.split("=")
query[key] = val
return query
},
{}
)
)
export const getCurrentUser = () => (
parseUrlParams(window.location.search)["as"]
)
export const isMod = user => {
return user === "mod"
}
export const login = () => {
const asWho = window.prompt("Sign in as who?")
window.history.pushState({}, "", `?as=${asWho}`)
window.document.title = "Our DAO • Edit"
window.dispatchEvent(new CustomEvent(AUTH_CHANGE))
}
export const logout = () => {
window.history.pushState({}, "", "/")
window.document.title = "Our DAO"
window.dispatchEvent(new CustomEvent(AUTH_CHANGE))
}
export const addListener = func => {
window.addEventListener(AUTH_CHANGE, func, false);
}
export const removeListener = func => {
window.removeEventListener(AUTH_CHANGE, func, false);
}
|
fc23fa5080047df43ef3b2a61185d06feb9bd19b
|
TypeScript
|
varunamachi/sparrow
|
/src/app/entity/entity.model.ts
| 2.71875
| 3
|
export interface Entity {
_id?: string
name: string
type: string
location: string
ownerID: string
variables?: Param[]
readers?: string[]
writers?: string[]
tags?: string[]
createdAt?: Date
modifiedAt?: Date
createdBy?: string
modifiedBy?: string
}
interface Pair {
key: string
value: string
}
//Range - integer range
interface ParamRange {
min: number
max: number
}
enum ParamType {
Boolean,
NumberRange,
Choice,
Text,
}
export interface Param {
name: string
type: ParamType
desc: string
value: boolean | ParamRange | string[] | string
range: ParamRange
choices: Pair[]
default: any
}
|
1f55243e360618b9b945fc973d46c6aa10c6ff78
|
TypeScript
|
SerhatyiSerhii/contact-book-angular
|
/src/app/components/contact-form/contact-form.component.ts
| 2.734375
| 3
|
import { AbstractControl, FormGroup } from "@angular/forms";
import { ContactItem } from "src/app/models/contac-item";
export abstract class ContactFormComponent {
public updateForm: FormGroup;
protected pattern: string = '^(?=.*[0-9])[- +()0-9]+$';
public contactFields: {
name: keyof ContactItem;
title: string;
}[] = [
{ name: 'name', title: 'Name' },
{ name: 'surname', title: 'Surname' },
{ name: 'phone', title: 'Phone' },
{ name: 'email', title: 'Email' }
];
protected getFormControl(formControl: string): AbstractControl {
return this.updateForm.get(formControl)!;
}
public isFormInvalid(): boolean {
return ((this.getFormControl('phone').value?.trim() === '' && this.getFormControl('email').value?.trim() === '')
|| this.getFormControl('phone').invalid
|| this.getFormControl('email').invalid
)
}
public isAbstractControlInvalid(formControl: string): boolean {
const abstractControl = this.getFormControl(formControl);
return abstractControl.invalid && (abstractControl.touched || abstractControl.dirty);
}
public showBtnTitle(): string {
if (this.getFormControl('name').value === '') {
return 'Enter new name';
}
if (this.getFormControl('surname').value === '') {
return 'Enter new surname';
}
if (this.getFormControl('phone').value === '' && this.getFormControl('email').value === '') {
return 'Enter new phone number or new email address';
}
if (this.getFormControl('phone').invalid) {
return 'Phone number is invalid'
}
if (this.getFormControl('email').invalid) {
return 'Email address is invalid'
}
return '';
}
}
|
dc2217bf700d83beae224b5c41845fd8e319ad17
|
TypeScript
|
igv7/CouponSystemAngularProj
|
/src/app/components/pipes/customer-filter.pipe.ts
| 2.640625
| 3
|
import { Pipe, PipeTransform} from "@angular/core";
import { Customer } from 'src/app/models/customer';
@Pipe({
name: 'customerFilter'
})
export class CustomerFilterPipe implements PipeTransform {
transform(value: Customer[], filterBy: string) : Customer[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((customer : Customer) => customer.name.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
}
|
efad7b2f30a999b2a7df212d2e38d1dda5131883
|
TypeScript
|
arnodt001/simple-dashboard
|
/dashboard-ui/src/app/components/pipes/byte-unit.pipe.ts
| 3.21875
| 3
|
import {Pipe, PipeTransform} from "@angular/core";
import {isNumeric} from "rxjs/internal-compatibility";
import {ByteUnitEnum} from "../../enums/byte-unit.enum";
@Pipe({
name: 'byteUnitConvertor'
})
export class ByteUnitPipe implements PipeTransform {
/**
* This pipe transform the input value in bytes and transform it to
* the specified unit.
* Output: String contain the transformed value and unit.
* Otherwise the given value is return without any changes.
* @param value - numeric value in bytes
* @param unit - string value containing the unit.
* Valid value: 'B','KB','MB' and 'GB'
*/
transform(value: any, unit: string): any {
if (isNumeric(value)) {
switch (unit.toUpperCase()) {
case 'B':
return ((<number>value) * ByteUnitEnum.B) + " B";
case 'KB':
return ((<number>value) * ByteUnitEnum.KB) + " KB";
case 'MB':
return ((<number>value) * ByteUnitEnum.MB) + " MB";
case 'GB':
return ((<number>value) * ByteUnitEnum.GB) + " GB";
}
}
return value;
}
}
|
8d62b2f58fc21babf94e76613e475b5672db78d9
|
TypeScript
|
CaesiumY/typescript-textbook
|
/src/chapter10/practice.ts
| 3.484375
| 3
|
/* eslint-disable @typescript-eslint/no-namespace */
// 1. 선언 합치기를 가지고 놀아보자
// 1-a. 6.3.4 컴패니언 객체 패턴에서 소개한 컴패니언 객체를 값과 타입대신
// 네임스페이스와 인터페이스로 재구현하자
interface Currency {
unit: "EUR" | "GBP" | "JPY" | "USD";
value: number;
}
namespace Currency {
export const DEFAULT: Currency["unit"] = "USD";
export function from(value: number, unit = Currency.DEFAULT): Currency {
return { unit, value };
}
}
const amountDue: Currency = {
unit: "JPY",
value: 83733.1,
};
const otherAmountDue = Currency.from(330, "EUR");
// 1-b. 열거형에 정적 메서드를 추가하자
enum State {
TODO = "todo",
IN_PROGRESS = "in progress",
DONE = "done",
}
namespace State {
export function setProjectState(state: State, id: number): void {
console.log(state, id);
}
}
State.setProjectState(State.TODO, 0);
|
c87bc6c3de8786aaebb8cf4e24431d3849df3adc
|
TypeScript
|
lifaon74/routes
|
/src/misc/helpers/is/IsObject.ts
| 2.984375
| 3
|
export function IsObject<T extends object = object>(value: any): value is T {
return (typeof value === 'object') && (value !== null);
}
|
141595f5e819873074afaf1bfbed7055aa870ec4
|
TypeScript
|
trufflesuite/truffle
|
/packages/codec/lib/format/types.ts
| 3.03125
| 3
|
/**
* Contains the types for type objects, and some
* functions for working with them.
*
* @category Main Format
*
* @packageDocumentation
*/
import debugModule from "debug";
const debug = debugModule("codec:format:types");
//type objects for Solidity types
//these will just be defined as interfaces; there's not any particular need for
//classes here (at least for now)
//Note: This is NOT intended to represent every possible type representable by
//a Solidity type identifier! Only possible types the decoder might need to
//output, not all possible values.
//NOTE: not all of these optional fields are actually implemented. Some are
//just intended for the future.
//ALSO NOTE: IDs are strings even though they're currently numeric because
//that might change in the future.
import type BN from "bn.js";
import type { ContractKind, Location, Mutability } from "@truffle/codec/common";
import type { CompilerVersion } from "@truffle/codec/compiler";
/**
* Object representing a type
*
* @Category General categories
*/
export type Type =
| UintType
| IntType
| BoolType
| BytesType
| AddressType
| FixedType
| UfixedType
| StringType
| ArrayType
| MappingType
| FunctionType
| StructType
| EnumType
| UserDefinedValueTypeType
| ContractType
| MagicType
| TypeType
| TupleType
| OptionsType;
/**
* Type of an unsigned integer
*
* @Category Elementary types
*/
export interface UintType {
typeClass: "uint";
bits: number;
typeHint?: string;
}
/**
* Type of a signed integer
*
* @Category Elementary types
*/
export interface IntType {
typeClass: "int";
bits: number;
typeHint?: string;
}
/**
* Type of a boolean
*
* @Category Elementary types
*/
export interface BoolType {
typeClass: "bool";
typeHint?: string;
}
/**
* Type of a bytestring (static or dynamic)
*
* @Category Elementary types
*/
export type BytesType = BytesTypeStatic | BytesTypeDynamic;
/**
* Type of a static-length bytestring
*
* @Category Elementary types
*/
export interface BytesTypeStatic {
typeClass: "bytes";
kind: "static";
length: number;
typeHint?: string;
}
/**
* Type of a dynamic-length bytestring
*
* @Category Elementary types
*/
export interface BytesTypeDynamic {
typeClass: "bytes";
kind: "dynamic";
location?: Location;
typeHint?: string;
}
/**
* Type of an address
*
* @Category Elementary types
*/
export type AddressType = AddressTypeSpecific | AddressTypeGeneral;
/**
* Type of an address (with payability specified)
*
* @Category Elementary types
*/
export interface AddressTypeSpecific {
typeClass: "address";
kind: "specific";
payable: boolean;
}
/**
* Type of an address (with payability unspecified)
*
* @Category Elementary types
*/
export interface AddressTypeGeneral {
typeClass: "address";
kind: "general";
typeHint?: string;
}
/**
* Type of a string
*
* @Category Elementary types
*/
export interface StringType {
typeClass: "string";
location?: Location;
typeHint?: string;
}
/**
* Type of a signed fixed-point number
*
* @Category Elementary types
*/
export interface FixedType {
typeClass: "fixed";
bits: number;
places: number;
typeHint?: string;
}
/**
* Type of an unsigned fixed-point number
*
* @Category Elementary types
*/
export interface UfixedType {
typeClass: "ufixed";
bits: number;
places: number;
typeHint?: string;
}
/**
* Type of an array
*
* @Category Container types
*/
export type ArrayType = ArrayTypeStatic | ArrayTypeDynamic;
/**
* Type of a static-length array
*
* @Category Container types
*/
export interface ArrayTypeStatic {
typeClass: "array";
kind: "static";
baseType: Type;
length: BN;
location?: Location;
typeHint?: string;
}
/**
* Type of a dynamic-length array
*
* @Category Container types
*/
export interface ArrayTypeDynamic {
typeClass: "array";
kind: "dynamic";
baseType: Type;
location?: Location;
typeHint?: string;
}
/**
* Type of an elementary value
*
* @Category General categories
*/
export type ElementaryType =
| UintType
| IntType
| BoolType
| BytesType
| FixedType
| UfixedType
| AddressType
| StringType
| EnumType
| UserDefinedValueTypeType
| ContractType;
/**
* Types that can underlie a user-defined value type
*
* @Category General categories
*/
export type BuiltInValueType =
| UintType
| IntType
| BoolType
| BytesTypeStatic
| FixedType
| UfixedType
| AddressTypeSpecific; //UDVTs only exist on 0.8.8 and later
/**
* Types that can go in the ABI
*
* @Category General categories
*/
export type AbiType =
| UintType
| IntType
| BoolType
| BytesType
| AddressTypeGeneral
| FixedType
| UfixedType
| StringType
| ArrayType
| FunctionExternalTypeGeneral
| TupleType;
/**
* Type of a mapping
*
* @Category Container types
*/
export interface MappingType {
typeClass: "mapping";
keyType: ElementaryType;
valueType: Type;
location?: "storage";
}
/**
* Type of a function pointer (internal or external)
*
* @Category Function types
*/
export type FunctionType = FunctionInternalType | FunctionExternalType;
/**
* Type of an internal function pointer
*
* @Category Function types
*/
export interface FunctionInternalType {
typeClass: "function";
visibility: "internal";
mutability: Mutability;
inputParameterTypes: Type[];
outputParameterTypes: Type[];
//we do not presently support bound functions
}
/**
* Type of an external function pointer
*
* @Category Function types
*/
export type FunctionExternalType =
| FunctionExternalTypeSpecific
| FunctionExternalTypeGeneral;
/**
* Type of an external function pointer (full Solidity type)
*
* @Category Function types
*/
export interface FunctionExternalTypeSpecific {
typeClass: "function";
visibility: "external";
kind: "specific";
mutability: Mutability;
inputParameterTypes: Type[];
outputParameterTypes: Type[];
//we do not presently support bound functions
}
/**
* Type of an external function pointer (general ABI type)
*
* @Category Function types
*/
export interface FunctionExternalTypeGeneral {
typeClass: "function";
visibility: "external";
kind: "general";
//we do not presently support bound functions
typeHint?: string;
}
/**
* Types defined inside contracts
*
* @Category General categories
*/
export type ContractDefinedType =
| StructTypeLocal
| EnumTypeLocal
| UserDefinedValueTypeTypeLocal;
/**
* User-defined types
*
* @Category General categories
*/
export type UserDefinedType =
| ContractDefinedType
| ContractTypeNative
| StructTypeGlobal
| EnumTypeGlobal
| UserDefinedValueTypeTypeGlobal;
/**
* Type of a struct
*
* Structs may be local (defined in a contract) or global (defined outside of any contract)
*
* @Category Container types
*/
export type StructType = StructTypeLocal | StructTypeGlobal;
export interface NameTypePair {
name: string;
type: Type;
}
/**
* Local structs (defined in contracts)
*
* @Category Container types
*/
export interface StructTypeLocal {
typeClass: "struct";
kind: "local";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
definingContractName: string;
definingContract?: ContractTypeNative;
/**
* these must be in order
*/
memberTypes?: NameTypePair[];
location?: Location;
}
/**
* Global structs
*
* @Category Container types
*/
export interface StructTypeGlobal {
typeClass: "struct";
kind: "global";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
/**
* these must be in order
*/
memberTypes?: NameTypePair[];
location?: Location;
}
export interface OptionallyNamedType {
name?: string;
type: Type;
}
/**
* Type of a tuple (for use in ABI)
*
* @Category Container types
*/
export interface TupleType {
typeClass: "tuple";
memberTypes: OptionallyNamedType[];
typeHint?: string;
}
/**
* Type of an enum
*
* Enums may be local (defined in a contract) or global (defined outside of any contract)
*
* @Category User-defined elementary types
*/
export type EnumType = EnumTypeLocal | EnumTypeGlobal;
/**
* Local enum (defined in a contract)
*
* @Category User-defined elementary types
*/
export interface EnumTypeLocal {
typeClass: "enum";
kind: "local";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
definingContractName: string;
definingContract?: ContractTypeNative;
/**
* these must be in order
*/
options?: string[];
}
/**
* Global enum
*
* @Category User-defined elementary types
*/
export interface EnumTypeGlobal {
typeClass: "enum";
kind: "global";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
/**
* these must be in order
*/
options?: string[];
}
/**
* Type of a contract; used not just for actual values but wherever a contract type
* is needed
*
* Contract types may be native (has Solidity info) or foreign (lacking Solidity info).
*
* @Category User-defined elementary types
*/
export type ContractType = ContractTypeNative | ContractTypeForeign;
/**
* Type of a contract with full Solidity info -- may be used for actual variables
*
* @Category User-defined elementary types
*/
export interface ContractTypeNative {
typeClass: "contract";
kind: "native";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
contractKind?: ContractKind;
/**
* Indicates whether contract has payable fallback function
*/
payable?: boolean; //will be useful in the future
//may have more optional members defined later, but I'll leave these out for
//now
}
/**
* Type of a contract w/o full Solidity info -- not used for actual variables
*
* @Category User-defined elementary types
*/
export interface ContractTypeForeign {
typeClass: "contract";
kind: "foreign";
typeName: string;
contractKind?: ContractKind;
/**
* Indicates whether contract has payable fallback function
*/
payable?: boolean; //will be useful in the future
//may have more optional members defined later, but I'll leave these out for
//now
}
/**
* Type of a user-defined value type
*
* These may be local (defined in a contract) or global (defined outside of any contract)
*
* @Category User-defined elementary types
*/
export type UserDefinedValueTypeType =
| UserDefinedValueTypeTypeLocal
| UserDefinedValueTypeTypeGlobal;
/**
* Local UDVT (defined in a contract)
*
* @Category User-defined elementary types
*/
export interface UserDefinedValueTypeTypeLocal {
typeClass: "userDefinedValueType";
kind: "local";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
definingContractName: string;
definingContract?: ContractTypeNative;
underlyingType?: BuiltInValueType;
}
/**
* Global UDVT (defined outside a contract)
*
* @Category User-defined elementary types
*/
export interface UserDefinedValueTypeTypeGlobal {
typeClass: "userDefinedValueType";
kind: "global";
/**
* Internal ID. Format may change in future.
*/
id: string;
typeName: string;
underlyingType?: BuiltInValueType;
}
export type MagicVariableName = "message" | "block" | "transaction";
/**
* Type of a magic variable
*
* @Category Special container types (debugger-only)
*/
export interface MagicType {
typeClass: "magic";
variable: MagicVariableName;
//really, I could do this as a tagged union, but I don't see a reason to
//introduce such complexity here, especially as this type is basically just
//for the debugger
memberTypes?: {
[field: string]: Type;
};
//may have more optional fields defined in the future
}
/**
* Type of a type! This is currently only used for contract types and enum
* types, but may expand in the future.
* @Category Special container types (debugger-only)
*/
export type TypeType = TypeTypeContract | TypeTypeEnum;
/**
* Type of a contract type
* @Category Special container types (debugger-only)
*/
export interface TypeTypeContract {
typeClass: "type";
type: ContractTypeNative;
/**
* these must be in order, and must only include
* **non-inherited** state variables
*/
stateVariableTypes?: NameTypePair[];
}
/**
* Type of an enum type
* @Category Special container types (debugger-only)
*/
export interface TypeTypeEnum {
typeClass: "type";
type: EnumType;
}
/**
* Fictitious type used for a transaction options argument
* (e.g. value, from, etc).
*
* @Category Special types (encoder-only)
*/
export interface OptionsType {
typeClass: "options";
}
/**
* Reference types
*
* @Category General categories
*/
export type ReferenceType =
| ArrayType
| MappingType
| StructType
| StringType
| BytesTypeDynamic;
export interface TypesById {
[id: string]: UserDefinedType;
}
export interface TypesByCompilationAndId {
[compilationId: string]: {
compiler: CompilerVersion;
types: TypesById;
};
}
export function forgetCompilations(
typesByCompilation: TypesByCompilationAndId
): TypesById {
return Object.assign(
{},
...Object.values(typesByCompilation).map(({ types }) => types)
);
}
function isUserDefinedType(anyType: Type): anyType is UserDefinedType {
const userDefinedTypes = [
"contract",
"enum",
"struct",
"userDefinedValueType"
];
return userDefinedTypes.includes(anyType.typeClass);
}
export function isReferenceType(anyType: Type): anyType is ReferenceType {
const alwaysReferenceTypes = ["array", "mapping", "struct", "string"];
if (alwaysReferenceTypes.includes(anyType.typeClass)) {
return true;
} else if (anyType.typeClass === "bytes") {
return anyType.kind === "dynamic";
} else {
return false;
}
}
//one could define a counterpart function that stripped all unnecessary information
//from the type object, but at the moment I see no need for that
export function fullType(basicType: Type, userDefinedTypes: TypesById): Type {
if (!isUserDefinedType(basicType)) {
return basicType;
}
let id = basicType.id;
let storedType = userDefinedTypes[id];
if (!storedType) {
return basicType;
}
let returnType: Type = { ...basicType, ...storedType };
if (isReferenceType(basicType) && basicType.location !== undefined) {
returnType = specifyLocation(returnType, basicType.location);
}
return returnType;
}
//the location argument here always forces, so passing undefined *will* force undefined
export function specifyLocation(
dataType: Type,
location: Location | undefined
): Type {
if (isReferenceType(dataType)) {
switch (dataType.typeClass) {
case "string":
case "bytes":
return { ...dataType, location };
case "array":
return {
...dataType,
location,
baseType: specifyLocation(dataType.baseType, location)
};
case "mapping":
let newLocation =
location === "storage" ? ("storage" as "storage") : undefined;
return {
...dataType,
location: newLocation,
valueType: specifyLocation(dataType.valueType, newLocation)
};
case "struct":
let returnType = { ...dataType, location };
if (returnType.memberTypes) {
returnType.memberTypes = returnType.memberTypes.map(
({ name: memberName, type: memberType }) => ({
name: memberName,
type: specifyLocation(memberType, location)
})
);
}
return returnType;
}
} else {
return dataType;
}
}
//NOTE: the following two functions might not be exactly right for weird internal stuff,
//or for ABI-only stuff. (E.g. for internal stuff sometimes it records whether things
//are pointers or not?? we don't track that so we can't recreate that)
//But what can you do.
export function typeString(dataType: Type): string {
let baseString = typeStringWithoutLocation(dataType);
if (isReferenceType(dataType) && dataType.location) {
return baseString + " " + dataType.location;
} else {
return baseString;
}
}
export function typeStringWithoutLocation(dataType: Type): string {
switch (dataType.typeClass) {
case "uint":
return dataType.typeHint || `uint${dataType.bits}`;
case "int":
return dataType.typeHint || `int${dataType.bits}`;
case "bool":
return dataType.typeHint || "bool";
case "bytes":
if (dataType.typeHint) {
return dataType.typeHint;
}
switch (dataType.kind) {
case "dynamic":
return "bytes";
case "static":
return `bytes${dataType.length}`;
}
case "address":
switch (dataType.kind) {
case "general":
return dataType.typeHint || "address"; //I guess?
case "specific":
return dataType.payable ? "address payable" : "address";
}
case "string":
return dataType.typeHint || "string";
case "fixed":
return dataType.typeHint || `fixed${dataType.bits}x${dataType.places}`;
case "ufixed":
return dataType.typeHint || `ufixed${dataType.bits}x${dataType.places}`;
case "array":
if (dataType.typeHint) {
return dataType.typeHint;
}
switch (dataType.kind) {
case "dynamic":
return `${typeStringWithoutLocation(dataType.baseType)}[]`;
case "static":
return `${typeStringWithoutLocation(dataType.baseType)}[${
dataType.length
}]`;
}
case "mapping":
return `mapping(${typeStringWithoutLocation(
dataType.keyType
)} => ${typeStringWithoutLocation(dataType.valueType)})`;
case "struct":
case "enum":
//combining these cases for simplicity
switch (dataType.kind) {
case "local":
return `${dataType.typeClass} ${dataType.definingContractName}.${dataType.typeName}`;
case "global":
return `${dataType.typeClass} ${dataType.typeName}`;
}
break; //to satisfy TS :P
case "userDefinedValueType":
//differs from struct & enum in that typeClass is omitted
switch (dataType.kind) {
case "local":
return `${dataType.definingContractName}.${dataType.typeName}`;
case "global":
return `${dataType.typeName}`;
}
break; //to satisfy TS :P
case "tuple":
return (
dataType.typeHint ||
"tuple(" +
dataType.memberTypes
.map(memberType => typeString(memberType.type))
.join(",") +
")"
); //note that we do include location and do not put spaces
case "contract":
return dataType.contractKind + " " + dataType.typeName;
case "magic":
//no, this is not transposed!
const variableNames = {
message: "msg",
transaction: "tx",
block: "block"
};
return variableNames[dataType.variable];
case "type":
return `type(${typeString(dataType.type)})`;
case "function":
let visibilityString: string;
switch (dataType.visibility) {
case "external":
if (dataType.kind === "general") {
if (dataType.typeHint) {
return dataType.typeHint;
} else {
return "function external"; //I guess???
}
}
visibilityString = " external"; //note the deliberate space!
break;
case "internal":
visibilityString = "";
break;
}
let mutabilityString =
dataType.mutability === "nonpayable" ? "" : " " + dataType.mutability; //again, note the deliberate space
let inputList = dataType.inputParameterTypes.map(typeString).join(","); //note that we do include location, and do not put spaces
let outputList = dataType.outputParameterTypes.map(typeString).join(",");
let inputString = `function(${inputList})`;
let outputString = outputList === "" ? "" : ` returns (${outputList})`; //again, note the deliberate space
return inputString + mutabilityString + visibilityString + outputString;
case "options":
//note: not a real Solidity type! just for error messaging!
return "options";
}
}
export function isContractDefinedType(
anyType: Type
): anyType is ContractDefinedType {
const contractDefinedTypes = ["enum", "struct", "userDefinedValueType"];
return (
contractDefinedTypes.includes(anyType.typeClass) &&
(<EnumType | StructType | UserDefinedValueTypeType>anyType).kind === "local"
);
}
|
2e8a2dc06a61f3115020b802511db1a93114c6e8
|
TypeScript
|
qlonik-forks/matechs-effect-legacy
|
/packages/core/demo/demo23.ts
| 2.78125
| 3
|
import * as A from "../src/Array"
import { pipe } from "../src/Function"
import * as T from "../src/next/Effect"
import * as S from "../src/next/Stream"
const cancel = pipe(
S.effectAsyncInterrupt<unknown, never, number>((cb) => {
let i = 0
const timer = setInterval(() => {
cb(T.succeed(A.range(0, i)))
i++
}, 500)
return T.effectTotal(() => {
clearInterval(timer)
console.log("cleared")
})
}),
S.mapMPar(3)((n) =>
T.delay(250)(
T.effectTotal(() => {
console.log(`process: ${n}`)
return n
})
)
),
S.runDrain,
T.runMain
)
setTimeout(() => {
cancel()
}, 10000)
|
5ee88919c0ee577ab890e65a96041134b35c2c64
|
TypeScript
|
sjovanovic974/100AlgorithmsChallenge
|
/alphabeticShift/alphabeticShift.ts
| 3.796875
| 4
|
// My solution of the problem using String methodes
function alphabeticShift(inputString: string): string {
return inputString
.split('')
.map(l => {
if (l === 'z') {
return 'a';
} else if (l === 'Z') {
return 'A';
} else {
return String.fromCharCode(l.charCodeAt(0) + 1);
}
})
.join('');
}
console.log(alphabeticShift('crazy'));
console.log(alphabeticShift('AAZZZ'));
|
428127f9a59fbc4b58d1da1366b00625cbd5be91
|
TypeScript
|
MarcosSpessatto/Rocket.Chat
|
/apps/meteor/app/federation/server/lib/context.ts
| 2.546875
| 3
|
export const contextDefinitions = {
ROOM: {
type: 'room' as const,
isRoom(event: { context: { roomId?: string } }): boolean {
return !!event.context.roomId;
},
contextQuery(roomId: string) {
return { roomId };
},
},
defineType(event: { context: { roomId?: string } }): 'room' | 'undefined' {
if (this.ROOM.isRoom(event)) {
return this.ROOM.type;
}
return 'undefined';
},
};
|
cd2b0042c0ec65514372e119b5e34ad606b648ca
|
TypeScript
|
snayan/algorithm-demo
|
/Algorithm/排序-桶排序/index.ts
| 3.9375
| 4
|
/* 题目,对于一组0到5000之间的数,进行桶排序 */
import { quickSortOnArray } from '../排序-快速排序';
/* 思路:1. 将0到5000之间的数划分到100个桶里,
2. 0号桶里存[0,50]之间的数据,1号桶里存[51,100]之间的数据,2号桶里存[151,200]之间的数据。。。
3. 类似的,99号桶里存[4951,5000]之间的数据
4. 然后针对每个桶里数据单独使用快速排序进行排序,
5. 依次从0号桶,1号桶。。。99号桶取出数据,则数据就是有序的了
时间复杂度:O(n) ,当桶的数量接近数组长度时,就接近O(n)了
空间复杂度:O(n)
*/
export function bucketSort(arr: number[]) {
const len = arr.length;
debugger;
/* 数组为空,或者只有一个数据,则直接返回 */
if (len < 2) {
return;
}
let min = Number.MAX_SAFE_INTEGER;
let max = Number.MIN_SAFE_INTEGER;
// 先取出数据范围
for (let i of arr) {
min = Math.min(min, i);
max = Math.max(max, i);
}
// 如果全都一样大,则直接返回
if (min === max) {
return;
}
let count = 1 + Math.ceil(len / 100); // 桶个数,最小2个桶
count = Math.min(100, count); // 最大100个桶
let range = (max - min) / (count - 1);
let buckets = new Array<number[]>(count);
// 划分到桶里
for (let value of arr) {
let index = Math.floor((value - min) / range);
let bucket = buckets[index];
if (!Array.isArray(bucket)) {
buckets[index] = [];
bucket = buckets[index];
}
bucket.push(value);
}
// 过滤调空的桶
buckets = buckets.filter(Boolean);
// 对每个桶单独排序
for (let bucket of buckets) {
quickSortOnArray(bucket);
}
// 再把各个桶按照顺序输出
arr.length = 0;
for (let bucket of buckets) {
for (let value of bucket) {
arr.push(value);
}
}
}
|
5448e9b482ee2d731dd3d7a08f4716ef3d2b5705
|
TypeScript
|
JohnVUgonabo/communication-ui-library
|
/packages/react-composites/tests/server/server.ts
| 2.515625
| 3
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import express from 'express';
import { Server } from 'http';
import path from 'path';
let server: Server;
const app = express();
export const createTestServer =
(props: { appDir: string; serverUrl: string }) =>
// eslint-disable-next-line no-empty-pattern, @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
async ({}, use: (r: string) => Promise<void>) => {
await startServer(props.appDir);
try {
await use(props.serverUrl);
} finally {
await stopServer();
}
};
const startServer = (appDir: string): Promise<void> => {
app.use(express.static(path.resolve(appDir, 'dist')));
return new Promise((resolve) => {
server = app.listen(3000, () => {
resolve();
});
});
};
const stopServer = (): Promise<void> =>
new Promise((resolve, reject) => {
if (!server) reject(false);
server.close(() => {
resolve();
});
});
|
2afb8a6534c6f9fa5a5c615c229ebd810d879eaf
|
TypeScript
|
xDveGax/exo-frontend
|
/custom-elements/exo-exq/src/app/model/question.model.ts
| 2.671875
| 3
|
export interface Step {
section: string;
questions: Question[];
}
export interface Question {
name: string;
options: Answers[];
section: string;
pk: number;
}
export interface Answers {
pk: number;
value: string;
}
export interface Industry {
pk: number;
name: string;
}
|
70899cd83a9dbe7b0645948407c04fb0096e0d45
|
TypeScript
|
nguoianphu/fra-phaser
|
/src/game/events.ts
| 3.0625
| 3
|
export class EventBus implements IEventDispatcher
{
private handlers: { type: GameEvent; func: Function }[] = []
public on(type:GameEvent,call:Function)
{ this.handlers.push({type:type,func:call}) }
public raise( type: GameEvent, ...rest:any )
{
// console.log(type,...rest)
for ( let handler of this.handlers )
if ( handler.type === type )
handler.func(...rest)
else
if ( handler.type === GameEvent.ANY )
handler.func( type, ...rest )
}
}
export interface IEventDispatcher { raise( type: GameEvent, ...rest:any ):void; }
export enum GameEvent
{
ANY,
GAMESTART,
GAMEOVER,
CHANGE,
TURNEND,
BOTSPAWN, // to
BOTMOVE, // from, to
BOTDIE, // collision/fall
PLAYERSPAWN, // to
PLAYERMOVE, // from, to
PLAYERSPECIAL, // skill
PLAYERDIE, // collision/fall
DECOYDIE, // collision/fall
TILEBUST, // tile
}
|
48085741891e41140211b7a188315b2b593898dd
|
TypeScript
|
derozn/management-sdk
|
/src/field.ts
| 2.640625
| 3
|
import { ChangeItem, MigrationChange } from "./migration";
import { MutationMode } from "./util";
import {
GraphQLBatchMigrationCreateEnumerableFieldInput,
GraphQLBatchMigrationCreateRelationalFieldInput,
GraphQLBatchMigrationCreateRemoteFieldInput,
GraphQLBatchMigrationCreateSimpleFieldInput,
GraphQLBatchMigrationCreateUnionFieldInput,
GraphQLBatchMigrationUpdateRelationalFieldInput,
GraphQLBatchMigrationUpdateSimpleFieldInput,
GraphQLBatchMigrationUpdateUnionFieldInput,
} from "./generated/schema";
type FieldArgs =
| GraphQLBatchMigrationCreateSimpleFieldInput
| GraphQLBatchMigrationUpdateSimpleFieldInput
| GraphQLBatchMigrationCreateRelationalFieldInput
| GraphQLBatchMigrationUpdateRelationalFieldInput
| GraphQLBatchMigrationCreateEnumerableFieldInput
| GraphQLBatchMigrationCreateUnionFieldInput
| GraphQLBatchMigrationUpdateUnionFieldInput
| GraphQLBatchMigrationCreateRemoteFieldInput;
enum FieldType {
SimpleField = 1,
RelationalField,
EnumerableField,
UnionField,
RemoteField,
}
/**
* @ignore
*/
class Field implements ChangeItem {
constructor(
private args: FieldArgs,
private mode: MutationMode,
private type: FieldType = FieldType.SimpleField
) {}
generateChange(): MigrationChange {
let action: string;
const typeStr = FieldType[this.type];
switch (this.mode) {
case MutationMode.Create:
action = `create${typeStr}`;
break;
case MutationMode.Update:
action = `update${typeStr}`;
break;
case MutationMode.Delete:
// delete is generic
action = `deleteField`;
break;
}
const change: { [key: string]: any } = {};
change[action] = this.args;
return change;
}
}
export { Field, FieldType };
|
71e33cf59498ad3996e35afbecc682412ef4fab5
|
TypeScript
|
AlessioVinci/Softwaredesign_NodeJS
|
/src/classes/Question.ts
| 2.734375
| 3
|
import { QuestionBuilder } from "./QuestionBuilder.ts";
import { Answer } from "./Answer.ts";
export class Question {
title: string;
answers: Answer[];
constructor(questionBuilder: QuestionBuilder) {
this.title = questionBuilder.getTitle;
this.answers = questionBuilder.getAnswers;
}
}
|
ef466a8f8484499154bfc3a8feef9e3fab85a93e
|
TypeScript
|
Splidejs/splide
|
/src/js/components/Layout/Layout.ts
| 2.671875
| 3
|
import { TTB } from '../../constants/directions';
import { EVENT_OVERFLOW, EVENT_REFRESH, EVENT_RESIZE, EVENT_RESIZED, EVENT_UPDATED } from '../../constants/events';
import { EventInterface, Throttle } from '../../constructors';
import { Splide } from '../../core/Splide/Splide';
import { BaseComponent, Components, Options } from '../../types';
import { abs, apply, assert, isObject, rect, style, toggleClass, unit } from '../../utils';
import { FADE } from '../../constants/types';
import { CLASS_OVERFLOW } from '../../constants/classes';
/**
* The interface for the Layout component.
*
* @since 3.0.0
*/
export interface LayoutComponent extends BaseComponent {
listSize(): number;
slideSize( index: number, withoutGap?: boolean ): number;
sliderSize( withoutGap?: boolean ): number;
totalSize( index?: number, withoutGap?: boolean ): number;
getPadding( right: boolean ): number;
isOverflow(): boolean;
/** @internal */
resize( force?: boolean ): void;
}
/**
* The component that adjusts slider styles and provides methods for dimensions.
*
* @since 3.0.0
*
* @param Splide - A Splide instance.
* @param Components - A collection of components.
* @param options - Options.
*
* @return An Layout component object.
*/
export function Layout( Splide: Splide, Components: Components, options: Options ): LayoutComponent {
const { on, bind, emit } = EventInterface( Splide );
const { Slides } = Components;
const { resolve } = Components.Direction;
const { root, track, list } = Components.Elements;
const { getAt, style: styleSlides } = Slides;
/**
* Indicates whether the slider direction is vertical or not.
*/
let vertical: boolean;
/**
* Keeps the DOMRect object of the root element.
*/
let rootRect: DOMRect;
/**
* Turns into `true` when the carousel is wider than the list.
*/
let overflow: boolean;
/**
* Called when the component is mounted.
*/
function mount(): void {
init();
bind( window, 'resize load', Throttle( apply( emit, EVENT_RESIZE ) ) );
on( [ EVENT_UPDATED, EVENT_REFRESH ], init );
on( EVENT_RESIZE, resize );
}
/**
* Initializes the component on `mount` or `updated`.
* Uses `max-width` for the root to prevent the slider from exceeding the parent element.
*/
function init(): void {
vertical = options.direction === TTB;
style( root, 'maxWidth', unit( options.width ) );
style( track, resolve( 'paddingLeft' ), cssPadding( false ) );
style( track, resolve( 'paddingRight' ), cssPadding( true ) );
resize( true );
}
/**
* Updates dimensions of some elements when the carousel is resized.
* Also checks the carousel size and emits `overflow` events when it exceeds the list width.
*
* @param force - Skips checking the root dimension change and always performs the resizing process.
*/
function resize( force?: boolean ): void {
const newRect = rect( root );
if ( force || rootRect.width !== newRect.width || rootRect.height !== newRect.height ) {
style( track, 'height', cssTrackHeight() );
styleSlides( resolve( 'marginRight' ), unit( options.gap ) );
styleSlides( 'width', cssSlideWidth() );
styleSlides( 'height', cssSlideHeight(), true );
rootRect = newRect;
emit( EVENT_RESIZED );
if ( overflow !== ( overflow = isOverflow() ) ) {
toggleClass( root, CLASS_OVERFLOW, overflow );
emit( EVENT_OVERFLOW, overflow );
}
}
}
/**
* Parses the padding option and returns the value for each side.
* This method returns `paddingTop` or `paddingBottom` for the vertical slider.
*
* @param right - Determines whether to get `paddingRight/Bottom` or `paddingLeft/Top`.
*
* @return The padding value as a CSS string.
*/
function cssPadding( right: boolean ): string {
const { padding } = options;
const prop = resolve( right ? 'right' : 'left' );
return padding
&& unit( padding[ prop ] || ( isObject( padding ) ? 0 : padding ) )
|| '0px';
}
/**
* Returns the height of the track element as a CSS string.
*
* @return The height of the track.
*/
function cssTrackHeight(): string {
let height = '';
if ( vertical ) {
height = cssHeight();
assert( height, 'height or heightRatio is missing.' );
height = `calc(${ height } - ${ cssPadding( false ) } - ${ cssPadding( true ) })`;
}
return height;
}
/**
* Converts options related with height to a CSS string.
*
* @return The height as a CSS string if available, or otherwise an empty string.
*/
function cssHeight(): string {
return unit( options.height || rect( list ).width * options.heightRatio );
}
/**
* Returns the width of the slide as a CSS string.
*
* @return The width of the slide.
*/
function cssSlideWidth(): string | null {
return options.autoWidth
? null
: unit( options.fixedWidth ) || ( vertical ? '' : cssSlideSize() );
}
/**
* Returns the height of the slide as a CSS string.
*
* @return The height of the slide.
*/
function cssSlideHeight(): string | null {
return unit( options.fixedHeight )
|| ( vertical ? ( options.autoHeight ? null : cssSlideSize() ) : cssHeight() );
}
/**
* Returns the CSS string for slide width or height without gap.
*
* @return The CSS string for slide width or height.
*/
function cssSlideSize(): string {
const gap = unit( options.gap );
return `calc((100%${ gap && ` + ${ gap }` })/${ options.perPage || 1 }${ gap && ` - ${ gap }` })`;
}
/**
* Returns the list width for the horizontal slider, or the height for the vertical slider.
*
* @return The size of the list element in pixel.
*/
function listSize(): number {
return rect( list )[ resolve( 'width' ) ];
}
/**
* Returns the slide width for the horizontal slider, or the height for the vertical slider.
*
* @param index - Optional. A slide index.
* @param withoutGap - Optional. Determines whether to exclude the gap amount or not.
*
* @return The size of the specified slide element in pixel.
*/
function slideSize( index?: number, withoutGap?: boolean ): number {
const Slide = getAt( index || 0 );
return Slide
? rect( Slide.slide )[ resolve( 'width' ) ] + ( withoutGap ? 0 : getGap() )
: 0;
}
/**
* Returns the total width or height of slides from the head of the slider to the specified index.
* This includes sizes of clones before the first slide.
*
* @param index - A slide index. If omitted, uses the last index.
* @param withoutGap - Optional. Determines whether to exclude the last gap or not.
*
* @return The total width of slides in the horizontal slider, or the height in the vertical one.
*/
function totalSize( index: number, withoutGap?: boolean ): number {
const Slide = getAt( index );
if ( Slide ) {
const right = rect( Slide.slide )[ resolve( 'right' ) ];
const left = rect( list )[ resolve( 'left' ) ];
return abs( right - left ) + ( withoutGap ? 0 : getGap() );
}
return 0;
}
/**
* Returns the slider size without clones before the first slide.
* Do not use the clone's size because it's unstable while initializing and refreshing process.
*
* @param withoutGap - Optional. Determines whether to exclude the last gap or not.
*
* @return The width or height of the slider without clones.
*/
function sliderSize( withoutGap?: boolean ): number {
return totalSize( Splide.length - 1 ) - totalSize( 0 ) + slideSize( 0, withoutGap );
}
/**
* Returns the gap value in pixel by using the computed style of the first slide.
*
* @return The gap value in pixel.
*/
function getGap(): number {
const Slide = getAt( 0 );
return Slide && parseFloat( style( Slide.slide, resolve( 'marginRight' ) ) ) || 0;
}
/**
* Returns the padding value.
* This method resolves the difference of the direction.
*
* @param right - Determines whether to get `paddingRight/Bottom` or `paddingLeft/Top`.
*
* @return The padding value in pixel.
*/
function getPadding( right: boolean ): number {
return parseFloat( style( track, resolve( `padding${ right ? 'Right' : 'Left' }` ) ) ) || 0;
}
/**
* Checks if the carousel is wider than the list.
* This method always returns `true` for a fade carousel.
*
* @return `true` if the carousel is wider than the list, or otherwise `false`.
*/
function isOverflow(): boolean {
return Splide.is( FADE ) || sliderSize( true ) > listSize();
}
return {
mount,
resize,
listSize,
slideSize,
sliderSize,
totalSize,
getPadding,
isOverflow,
};
}
|
ee73f7c1278a4d077842d7adf1d74ed586798bbf
|
TypeScript
|
rui-watanabe/ts-second-app
|
/src/interface.ts
| 4.25
| 4
|
type addFunc = (num1: number, num2: number) => number;
// interface addFunc {
// (num1: number, num2: number): number;
// }
let addFunc: addFunc;
addFunc = (n1: number, n2: number) => n1 + n2;
interface NameAble {
name?: string;
nickName?: string;
}
const nameAble: NameAble = {
name: 'Max',
nickName: 'Ma'
}
// interface is only use object
interface Human extends NameAble {
age: number;
// greeting: (message: string) => void;
// only use method
greeting(message: string): void;
}
// type is can use all
// type Human = {
// name: string;
// age: number;
// } | string
class Developer implements Human {
constructor(public age: number, public experience: number, public name?: string){
};
greeting(message: string){
console.log(message);
}
}
const tmpDeveloper = {
name: 'Max',
age: 38,
experience: 5,
greeting(message: string){
console.log(message);
}
}
const user: Human = tmpDeveloper;
// const human: Human = {
// name: 'Max',
// age: 44,
// greeting(message: string){
// console.log(message);
// }
// }
// let tmpFunction: (message: string) => void;
|
aa73f9d0a9013feafb5bb4d420cb47f89f27775c
|
TypeScript
|
btoll/logger-ts
|
/src/interfaces.ts
| 2.53125
| 3
|
interface AbstractLog {
prelog(name?: string): string;
postlog(name?: string): string;
}
interface DefaultLogger {
clear?(): void;
debug?(...a: Array<any>): string;
error?(...a: Array<any>): string;
fatal?(...a: Array<any>): string;
info?(...a: Array<any>): string;
log?(...a: Array<any>): string;
raw?(...a: Array<any>): string;
table?(...a: Array<any>): string;
success?(...a: Array<any>): string;
warn?(...a: Array<any>): string;
}
interface Logger extends DefaultLogger {
__get(): any;
format: Object;
setLogLevel(level: any): void;
wrap(target: any): void;
}
export { AbstractLog, Logger };
|
42604167f96906724439ab86b9cc7c88c6007f79
|
TypeScript
|
adriancarriger/pv-site
|
/src/app/packages/filter/filter-options.ts
| 3.125
| 3
|
/**
* @module HomeModule
*/ /** */
/**
* Options used by the {@link FilterComponent}.
*/
export interface FilterOptions {
items: FilterItems;
searchFields: Array<string>;
}
/**
* Supported filtering types
*/
export type FilterType = 'search' | 'select';
/**
* Items used to filter
* - Items can contain differernt ordering priorities if needed. For example, if the order for mobile
* should be different.
* - Type sepcifies what kind of input should be show for this filter item.
*/
export interface FilterItems {
[index: number]: FilterItem;
}
export interface FilterItem {
name?: string; // used for labels and not required for search
options: Array<string>; // select boxes available options
order?: { // optional: if no order is given, the array order will be used
default: Number; // default order this item should appear on the filter
mobile?: Number; // optional different order for mobile break point
};
type: FilterType; // supported types: search, select
}
|
80db3382621334eff1911b0726f845edbe2814fd
|
TypeScript
|
stephaneerard/shots-analysis.ts
|
/src/controllers/hello.controller.ts
| 2.671875
| 3
|
import {get, Request, ResponseObject, RestBindings} from '@loopback/rest';
import {inject} from '@loopback/context';
/**
* OpenAPI response for hello()
*/
const HELLO_RESPONSE: ResponseObject = {
description: 'Hello Response',
content: {
'application/json': {
schema: {
type: 'object',
title: 'HelloResponse',
properties: {
hello: {type: 'string'},
date: {type: 'string'},
url: {type: 'string'},
headers: {
type: 'object',
properties: {
'Content-Type': {type: 'string'},
},
additionalProperties: true,
},
},
},
},
},
};
/**
* OpenAPI response for ping()
*/
const HEY_RESPONSE: ResponseObject = {
description: 'Hey Response',
content: {
'application/json': {
schema: {
type: 'object',
title: 'HeyResponse',
properties: {
hello: {type: 'string'},
date: {type: 'string'},
url: {type: 'string'},
headers: {
type: 'object',
properties: {
'Content-Type': {type: 'string'},
},
additionalProperties: true,
},
},
},
},
},
};
/**
* A simple controller to bounce back http requests
*/
export class HelloController {
constructor(@inject(RestBindings.Http.REQUEST) private req: Request) {
}
@get('/hello', {
responses: {
'200': HELLO_RESPONSE,
},
})
async hello(): Promise<object> {
return {}
}
@get('/hey', {
responses: {
'200': HEY_RESPONSE,
},
})
async hey(): Promise<object> {
// Reply with a greeting, the current time, the url, and request headers
return {
hello: await greetin(),
date: new Date(),
url: this.req.url,
headers: Object.assign({}, this.req.headers),
};
}
}
async function greetin(): Promise<string> {
return 'Hello from LoopBack @' + (new Date()).toISOString() + " " + (new Date()).toISOString() + (new Date()).toISOString();
}
|
960c5aa50d78846a1934e65d47d74ee155f7527d
|
TypeScript
|
maria-machine/mariamachine.io
|
/src/actionCreators/lang.ts
| 2.515625
| 3
|
export interface ISetLangLocale {
type: 'SET_LANG_LOCALE';
payload: string;
}
export const setLangLocale = (locale: string): ISetLangLocale => ({
type: 'SET_LANG_LOCALE',
payload: locale
});
|
ba64eea8aa80819276afbf1ae8a2a663dfd9197c
|
TypeScript
|
guaiwola/secret
|
/server/middlewares/catchError.ts
| 2.890625
| 3
|
import assert from 'assert';
import { KoaContext } from '../../types/koa';
/**
* 全局异常捕获
* 如果是通过 assert 主动抛出的异常, 则向客户端返回该异常消息
* 如果是其它异常, 则打印异常信息, 并返回 Server Error
*/
export default function catchError() {
return async (ctx: KoaContext, next: Function) => {
try {
await next();
} catch (err) {
if (err instanceof assert.AssertionError) {
ctx.res = err.message;
return;
}
ctx.res = `Server Error: ${err.message}`;
console.error('Unhandled Error\n', err);
}
};
}
|
236fda99a380429b11800c528bf5039eb2fb9b7a
|
TypeScript
|
comassky/vuejs-typescript-template
|
/src/services/AlbumsApiServices.ts
| 2.546875
| 3
|
import { AlbumInterface } from '@/Interfaces/AlbumInterface';
import Axios, { AxiosInstance } from 'axios';
export default abstract class AlbumsApiServices {
private static rest: AxiosInstance = Axios.create();
static async getAllAlbumsOfUser(userId: number): Promise<AlbumInterface[]> {
const response = await this.rest.get<AlbumInterface[]>('https://jsonplaceholder.typicode.com/users/' + userId + '/albums');
return response.data;
}
static async getAllAlbums(): Promise<AlbumInterface[]> {
const response = await this.rest.get<AlbumInterface[]>('https://jsonplaceholder.typicode.com/albums')
return response.data;
}
}
|
981e0f1c3518d9225d7bd28b1174dd986e1d6395
|
TypeScript
|
PixelRPG/javelin
|
/packages/ecs/src/topic.spec.ts
| 2.84375
| 3
|
import { Topic, createTopic } from "./topic"
describe("createTopic", () => {
it("adds events to its list of events", () => {
const topic: Topic = createTopic()
topic.push({ inputs: [] })
expect(Array.from(topic).length).toBe(0)
})
it("transitions messages to ready state when flush is called", () => {
const topic: Topic = createTopic()
topic.push({ inputs: [] })
topic.flush()
expect(Array.from(topic)[0]).toEqual({ inputs: [] })
})
it("adds events to be consumed immediately when the immediate flag is true", () => {
const topic: Topic = createTopic()
topic.pushImmediate({ inputs: [] })
expect(Array.from(topic).length).toBe(1)
})
})
|
2db39ebc28fae6948841b51682b8aece03ef16e1
|
TypeScript
|
leenakh/Fullstack2021Osa9
|
/health-app/src/bmiCalculator.ts
| 3.625
| 4
|
type Message = 'Underweight (unhealthy weigth)' | 'Normal (healthy weight)' | 'Overweight (unhealthy weight)' | 'Obese (very unhealthy weight)';
/* interface CalculateValues {
value1: number;
value2: number;
} */
/* const parseArguments = (args: Array<string>): CalculateValues => {
if (args.length < 4) throw new Error('not enough arguments');
if (args.length > 4) throw new Error('too many arguments');
if (!isNaN(Number(args[2])) && !isNaN(Number(args[3]))) {
return {
value1: Number(args[2]),
value2: Number(args[3])
}
} else {
throw new Error('provided values were not numbers');
}
} */
const calculateBmi = (weight: number, height: number): Message => {
const size: number = height * height / 10000;
const result: number = Math.floor(weight / size);
switch (true) {
case height <= 0 || weight <= 0:
throw new Error('invalid arguments');
case result < 18:
return 'Underweight (unhealthy weigth)';
case result < 25 && result >= 18:
return 'Normal (healthy weight)';
case result >= 25 && result < 30:
return 'Overweight (unhealthy weight)';
case result >= 30:
return 'Obese (very unhealthy weight)';
default:
throw new Error('malformatted parameters');
}
};
/* try {
console.log('processed')
} catch (error) {
console.log('something went wrong:', error.message);
} */
/* try {
const { value1, value2 } = parseArguments(process.argv);
console.log(calculateBmi(value1, value2));
} catch (error) {
console.log('Something went wrong:', error.message);
} */
export default calculateBmi;
|