Datasets:

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
b27f4536539c1eb80ed4147e6364a2903b9f39a9
TypeScript
styled-components/styled-components-website
/utils/stripIndent.ts
3.046875
3
// https://github.com/sindresorhus/strip-indent const stripIndent = (str: string) => { const match = str.match(/^[ \t]*(?=\S)/gm); if (!match) { return str; } // TODO: Use spread operator when targeting Node.js 6 const indent = Math.min(...match.map(x => x.length)); const re = new RegExp(`^[ \\t]{${indent}}`, 'gm'); return indent > 0 ? str.replace(re, '') : str; }; export default stripIndent;
1aaa81a3ec7b577712388f752d2f3a480a480074
TypeScript
medusajs/medusa
/packages/medusa/src/types/batch-job.ts
2.578125
3
import { Type } from "class-transformer" import { IsArray, IsEnum, IsOptional, IsString, ValidateNested, } from "class-validator" import { IsType } from "../utils/validators/is-type" import { DateComparisonOperator } from "./common" import { BatchJob } from "../models" export enum BatchJobStatus { CREATED = "created", PRE_PROCESSED = "pre_processed", CONFIRMED = "confirmed", PROCESSING = "processing", COMPLETED = "completed", CANCELED = "canceled", FAILED = "failed", } export type BatchJobUpdateProps = Partial<Pick<BatchJob, "context" | "result">> export type CreateBatchJobInput = { type: string context: BatchJob["context"] dry_run: boolean } export type BatchJobResultError = { message: string code: string | number [key: string]: unknown } export type BatchJobResultStatDescriptor = { key: string name: string message: string } export class FilterableBatchJobProps { @IsOptional() @IsType([String, [String]]) id?: string | string[] @IsOptional() @IsEnum(BatchJobStatus, { each: true }) status?: BatchJobStatus[] @IsArray() @IsOptional() type?: string[] @IsString() @IsOptional() @IsType([String, [String]]) created_by?: string | string[] @IsOptional() @ValidateNested() @Type(() => DateComparisonOperator) created_at?: DateComparisonOperator @IsOptional() @ValidateNested() @Type(() => DateComparisonOperator) updated_at?: DateComparisonOperator } export type BatchJobCreateProps = Pick< BatchJob, "context" | "type" | "created_by" | "dry_run" >
527711f67ffc103d55e748a559bd85ccb9dafdf0
TypeScript
BinaryStudioAcademy/bsa-2020-knewless
/frontend/src/containers/Notifications/reducer.ts
2.875
3
import { receiveNotificationRoutine, fetchUnreadNotificationsRoutine, readNotificationRoutine, deleteNotificationRoutine, deleteAllNotificationsRoutine, readAllNotificationsRoutine, getAllNotificationsRoutine, viewLessNotificationsRoutine } from './routines'; import { INotification } from './model/INotification'; const initialState = { notifications: Array<INotification>(), buffer: Array<string>(), deleting: false, reading: false, fetching: false }; export default function (state = initialState, action) { switch (action.type) { case receiveNotificationRoutine.TRIGGER: { const { notification } = action.payload; if (state.notifications[0]?.read) { state.notifications.shift(); } return ({ ...state, notifications: [...state.notifications, notification] }); } case fetchUnreadNotificationsRoutine.SUCCESS: { const { notifications } = action.payload; return ({ ...state, notifications: [...notifications] }); } case readNotificationRoutine.REQUEST: { const notifId = action.payload; const newNotifs = state.notifications.map(n => (n.id === notifId ? { ...n, read: true } : n)); return ({ ...state, notifications: newNotifs }); } case readNotificationRoutine.FAILURE: { const notifId = action.payload; const newNotifs = state.notifications.map(n => (n.id === notifId ? { ...n, read: false } : n)); return ({ ...state, notifications: newNotifs }); } case deleteNotificationRoutine.REQUEST: { const notifId = action.payload; const newNotifs = state.notifications.map(n => (n.id === notifId ? { ...n, deleting: true } : n)); return ({ ...state, notifications: newNotifs }); } case deleteNotificationRoutine.SUCCESS: { const notifId = action.payload; const newNotifs = state.notifications.filter(n => n.id !== notifId); return ({ ...state, notifications: newNotifs }); } case deleteNotificationRoutine.FAILURE: { const notifId = action.payload; const newNotifs = state.notifications.map(n => (n.id === notifId ? { ...n, deleting: false } : n)); return ({ ...state, notifications: newNotifs }); } case deleteAllNotificationsRoutine.REQUEST: { return ({ ...state, deleting: true }); } case deleteAllNotificationsRoutine.SUCCESS: { return ({ ...state, deleting: false, notifications: [] }); } case readAllNotificationsRoutine.REQUEST: { return ({ ...state, reading: true }); } case readAllNotificationsRoutine.SUCCESS: { const newNotifs = state.notifications.map(n => (n.read === false ? { ...n, read: true } : n)); return ({ ...state, notifications: newNotifs, reading: false }); } case getAllNotificationsRoutine.SUCCESS: { const { notifs } = action.payload; return ({ ...state, notifications: notifs, fetching: false }); } case getAllNotificationsRoutine.REQUEST: { return ({ ...state, fetching: true }); } case viewLessNotificationsRoutine.TRIGGER: { const newUnread = state.notifications.filter(n => n.read === false); const unreadNum = 10 - newUnread.length; let newRead: Array<INotification>; if (unreadNum > 0) { newRead = state.notifications.filter(n => n.read === true).slice(-unreadNum); } return ({ ...state, notifications: [...newRead, ...newUnread] }); } default: return state; } }
3904efcec22b9e6e825624ea6da9aaa5f5bcb058
TypeScript
notVitaliy/reangudux-sample
/src/app/store/reducers.ts
2.859375
3
import { combineReducers } from 'redux' import { ADD_TODO, FIN_TODO, DEL_TODO } from './list' function list(state, action) { switch (action.type) { case ADD_TODO: const item = { name: action.name, status: 'active', id: Math.random(), } return [...state, item] case FIN_TODO: const fItem = state.find((item) => item.id === action.id) const fIdx = state.indexOf(fItem) if (fIdx > -1) { fItem.status = 'complete' state[fIdx] = fItem } return [...state] case DEL_TODO: const dIdx = state.indexOf(state.find((item) => item.id === action.id)) if (dIdx > -1) state.splice(dIdx, 1) return [...state] default: return [{ name: 'Init task', status: 'active', id: Math.random() }] } } const rootReducer = combineReducers({ list, }) export default rootReducer
a80cc25a83ac638c95917952d5a9642b817fad1b
TypeScript
nichealpham/sandrasoft
/src/modules/server/services/parse_middlewares.ts
2.546875
3
// Import external-modules import * as Ramda from 'ramda'; // Import sub-modules import { ServerMiddlewares } from "../interfaces/server_middlewares"; import { MiddlewareFunction } from "../interfaces/middleware_function"; export const parseMiddlewares = (middlewares: ServerMiddlewares = {}): MiddlewareFunction[] => { if (Ramda.isEmpty(middlewares)) { return []; } const result: MiddlewareFunction[] = []; for (const middlewareName of Object.keys(middlewares)) { result.push(middlewares[middlewareName]); } return result; };
45315bfa8abbb50d14582660237e29c34ca14da5
TypeScript
paki14/colorizer
/src/app/app.component.ts
2.5625
3
import { Component } from '@angular/core'; import { ColorService } from './color.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private colorService: ColorService) { } ngOnInit() { } colors = []; bodycolor() { // get random color from color service in given api return this.colorService.getFlexColor().subscribe(data => { // console.log(data.color) // set a default color to inverse the color var color1 = 0xffffff var color2 = parseInt(data.color.replace(/^#/, ''), 16) // console.log(color2) // inverse of the get bg color var result = color1 - color2 var hex = '#'; var hex = hex + result.toString(16) // coloring the perticular flex box var x = document.getElementsByClassName('color') as HTMLCollectionOf<HTMLElement> ; var i = this.num - 1 while (i < this.num) { x[i].style.background = data.color.toString() x[i].style.color = hex i = i + 1 } }) } data = [] num: number = 0 addColor(newColor: string) { if (newColor) { // add array this.colors.push(newColor); // remove duplicate values var uniqueNames = []; $.each(this.colors, function (i, el) { if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); }); // coloring the flexbox and text this.bodycolor() // console.log(uniqueNames) this.num = this.num + 1 // console.log(this.num) // set array to remove duplicate values this.data = uniqueNames } return newColor = ''; } }
963dce35c3e9b0ffb6b64d8d03e01b5a22ab4e8d
TypeScript
Velfi/StructureJS
/js/model/Route.d.ts
3.6875
4
/** * The **Route** class is a model that keeps track of a specific route for the {{#crossLink "Router"}}{{/crossLink}} class. * * @class Route * @module StructureJS * @submodule model * @param routePattern {string} The string pattern you want to have match, which can be any of the following combinations {}, ::, *, '' * @param callback {Function} The function that should be executed when a request matches the routePattern. * @param callbackScope {any} The scope of the callback function that should be executed. * @constructor * @author Robert S. (www.codeBelt.com) * @example * // Example of adding a route listener and the function callback below. * let route = new Route('/games/{gameName}/:level:/', this._method, this); * * // The above route would match the string below: * route.match('/games/asteroids/2/'); * * Route Pattern Options: * ---------------------- * **:optional:** The two colons **::** means a part of the hash url is optional for the match. The text between can be anything you want it to be. * * let route = new Route('/contact/:name:/', this._method, this); * * // Will match one of the following: * route.match('/contact/'); * route.match('/contact/heather/'); * route.match('/contact/john/'); * * * **{required}** The two curly brackets **{}** means a part of the hash url is required for the match. The text between can be anything you want it to be. * * let route = new Route('/product/{productName}/', this._method, this); * * // Will match one of the following: * route.match('/product/shoes/'); * route.match('/product/jackets/'); * * * **\*** The asterisk character means it will match all or part of part the hash url. * * let route = new Route('*', this._method, this); * * // Will match one of the following: * route.match('/anything/'); * route.match('/matches/any/hash/url/'); * route.match('/really/it/matches/any/and/all/hash/urls/'); * * * **''** The empty string means it will match when there are no hash url. * * let route = new Route('', this._method, this); * let route = new Route('/', this._method, this); * * // Will match one of the following: * route.match(''); * route.match('/'); * * * Other possible combinations but not limited too: * * let route = new Route('/games/{gameName}/:level:/', this._method1, this); * let route = new Route('/{category}/blog/', this._method2, this); * let route = new Route('/about/*', this._method3, this); * */ declare class Route { /** * The string pattern you want to have match, which can be any of the following combinations {}, ::, *, ?, "". See below for examples. * * @property routePattern * @type String * @public */ routePattern: string; /** * The regex representation for the routePattern that was passed into the constructor. * * @property regex * @type RegExp * @public * @readOnly */ regex: RegExp; /** * The function that should be executed when a request matches the routePattern. The {{#crossLink "Router"}}{{/crossLink}} class will be using this property. * * @property callback * @type {Function} * @public */ callback: Function; /** * The scope of the callback function that should be executed. The {{#crossLink "Router"}}{{/crossLink}} class will be using this property. * * @property callbackScope * @type {any} * @public */ callbackScope: any; constructor(routePattern: string, callback: Function, scope: any); /** * Converts the routePattern that was passed into the constructor to a regexp object. * * @method _routePatternToRegexp * @param {String} routePattern * @returns {RegExp} * @protected */ protected _routePatternToRegexp(routePattern: any): RegExp; /** * Determine if a route matches a routePattern. * * @method match * @param route {String} The route or path to match against the routePattern that was passed into the constructor. * @returns {Array.<any>} * @example * let route = new Route('/games/{gameName}/:level:/', this.method, this); * console.log( route.match('/games/asteroids/2/') ); */ match(route: any): Array<any>; } export default Route;
c8f7b3a5f850e9f72368908ad4f8a1acbed42b01
TypeScript
weichx/smudge
/spec/smudge_spec.ts
3.125
3
///<reference path="./typings/jasmine.d.ts"/> import { smudgable, dirtychecked, isSmudged, isDirty, unSmudge, clean, getDirtyFields, getSmudgedFields } from '../src/smudge'; //todo after recent changes replace use of window with global if env is node @smudgable() export class Test1 { public property1 : number; public stringProp : string; public objProp : Object; public arrayProp : Array<string>; constructor() { this.property1 = 100; this.stringProp = "hello"; this.objProp = {}; this.arrayProp = []; } } @smudgable() class Test2 { public stringProp : string; public list : Array<Test2>; public subobject : Test2; public nestedArrays : Array<Array<Test2>>; constructor() { this.stringProp = "hi"; this.list = []; this.subobject = null; this.nestedArrays = []; } } describe("@smudgable", function () { it('should not start out smudged', function () { var t = new Test1(); expect(isSmudged(t, 'property1')).toBe(false); }); it('should be set to its constructor value', function () { var t = new Test1(); expect(t.property1).toBe(100); }); it('should smudge a shallow field', function () { var t = new Test1(); t.property1 = 200; expect(isSmudged(t, 'property1')).toBe(true); }); it('should be smudged', function () { var t = new Test1(); t.property1 = 300; expect(isSmudged(t)).toBe(true) }); it('should report smudged fields', function () { var t = new Test1(); t.property1 = 300; expect(getSmudgedFields(t)).toEqual(['property1']); t.stringProp = "goodbye"; expect(getSmudgedFields(t)).toEqual(['property1', 'stringProp']); }); it('should not smudge if same value is set', function () { var t = new Test1(); t.property1 = 100; expect(isSmudged(t)).toBe(false); }); it('returns the right value', function () { var t = new Test1(); t.property1 = 300; expect(t.property1).toBe(300); }); it('should clean a smudged field', function () { var t = new Test1(); t.property1 = 200; unSmudge(t, 'property1'); expect(isSmudged(t, 'property1')).toBe(false); }); it('should clean all smudged fields', function () { var t = new Test1(); t.property1 = 200; t.stringProp = "goodbye"; unSmudge(t); expect(isSmudged(t)).toBe(false); }); it('should not smudge an array if contents change', function () { var t = new Test1(); t.arrayProp.push('hi there'); expect(isSmudged(t)).toBe(false); }); it('should not smudge an object if contents change', function () { var t = new Test1(); (<any>t.objProp).x = 1; expect(isSmudged(t)).toBe(false); }); it('should smudge an array field', function () { var t = new Test1(); t.arrayProp = []; expect(isSmudged(t)).toBe(true); }); it('should smudge an object field', function () { var t = new Test1(); t.objProp = {}; expect(isSmudged(t)).toBe(true); }); }); describe('dirty', function () { it('should not start out dirty', function () { var t = new Test1(); expect(isSmudged(t, 'property1')).toBe(false); }); it('should mark smudged fields as dirty', function () { var t = new Test1(); t.property1 = 200; expect(isDirty(t, 'property1')).toBe(true); }); it('should examine array length changes', function () { var t = new Test1(); t.arrayProp.push('str'); expect(isDirty(t, 'arrayProp')).toBe(true); }); it('should examine array value changes', function () { var t = new Test1(); t.arrayProp.push('str1'); t.arrayProp.push('str2'); clean(t, 'arrayProp'); expect(isDirty(t, 'arrayProp')).toBe(false); t.arrayProp[0] = 'different'; expect(isDirty(t, 'arrayProp')).toBe(true); }); it('should clean an array', function () { var t = new Test1(); t.arrayProp.push('str'); expect(isDirty(t, 'arrayProp')).toBe(true); clean(t, 'arrayProp'); expect(isDirty(t, 'arrayProp')).toBe(false); }); it('should examine object properties', function () { var t = new Test2(); t.subobject = new Test2(); clean(t); t.subobject.stringProp = "yes"; expect(isDirty(t)).toBe(true); expect(isDirty(t, 'subobject')).toBe(true); }); it('should find dirty objects within an array that hasnt changed', function(){ var t = new Test2(); t.list.push(new Test2(), new Test2()); clean(t, 'list'); t.list[0].stringProp = "uh oh"; expect(isDirty(t)).toBe(true); expect(isDirty(t, 'list')).toBe(true); }); it('should clean dirty objects within an array', function() { var t = new Test2(); t.list.push(new Test2(), new Test2()); clean(t, 'list'); t.list[0].stringProp = "uh oh"; clean(t, 'list'); expect(isDirty(t.list[0])).toBe(false); }); it('should clean dirty objects within objects', function() { var t = new Test2(); t.subobject = new Test2(); t.subobject.subobject = new Test2(); clean(t); t.subobject.subobject.stringProp = "changed"; clean(t, 'subobject'); expect(isDirty(t)).toBe(false); expect(isDirty(t.subobject)).toBe(false); expect(isDirty(t.subobject.subobject)).toBe(false); }); //todo this test isnt passing yet xit('should clean nested arrays', function() { var t = new Test2(); t.nestedArrays.push([ new Test2(), new Test2() ], [new Test2(), new Test2()]); expect(isDirty(t)).toBe(true); clean(t); expect(isDirty(t)).toBe(false); t.nestedArrays[0][0].stringProp = "nope"; expect(isDirty(t.nestedArrays[0])).toBe(true); clean(t); expect(isDirty(t)).toBe(false); }); });
d6825838fe92bc93c1055b4c9fd666723c23a6d7
TypeScript
limoya/angular
/firstAngular/src/app/hero-search/hero-search.component.ts
2.796875
3
import { Component, OnInit } from '@angular/core'; import {Observable, Subject} from 'rxjs'; import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; @Component({ selector: 'app-hero-search', templateUrl: './hero-search.component.html', styleUrls: ['./hero-search.component.scss'] }) export class HeroSearchComponent implements OnInit { heroes$: Observable<Hero[]>; //Subject 既是可观察对象的数据源,本身也是 Observable。 你可以像订阅任何 Observable 一样订阅 Subject。 // 你还可以通过调用它的 next(value) 方法往 Observable 中推送一些值 private searchTerms = new Subject<string>(); constructor(private heroService:HeroService) { } // Push a search term into the observable stream search(term:string): void{ // debugger this.searchTerms.next(term); } ngOnInit(): void { this.heroes$ = this.searchTerms.pipe( //每次间隔300ms debounceTime(300), // 输入值和上次一样时忽略不动 distinctUntilChanged(), //输入值变了的时候,把查找的 observable 更新成新值(取消和舍弃以前的请求,但不是中止,是拿来数据但是不要了) switchMap((term:string)=>this.heroService.searchHeroes(term)), ) } }
96a48c1ccd66691e7f1f4f69ee01a0ba83a39ba9
TypeScript
oferitz/node-html-markdown
/src/visitor.ts
2.71875
3
import { NodeHtmlMarkdown } from './main'; import { ElementNode, HtmlNode, isElementNode, isTextNode } from './nodes'; import { getChildNodes, getTrailingWhitespaceInfo, perfStart, perfStop, trimNewLines } from './utilities'; import { createTranslatorContext, isTranslatorConfig, PostProcessResult, TranslatorConfig, TranslatorConfigFactory, TranslatorConfigObject, TranslatorContext } from './translator'; import { NodeHtmlMarkdownOptions } from './options'; import { contentlessElements } from './config'; /* ****************************************************************************************************************** */ // region: Types /* ****************************************************************************************************************** */ export interface NodeMetadata { indentLevel?: number listKind?: 'OL' | 'UL' listItemNumber?: number noEscape?: boolean preserveWhitespace?: boolean translators?: TranslatorConfigObject } export type NodeMetadataMap = Map<ElementNode, NodeMetadata> type VisitorResult = { text: string trailingNewlineStats: { whitespace: number newLines: number } } // endregion /* ****************************************************************************************************************** */ // region: Visitor /* ****************************************************************************************************************** */ /** * Properties & methods marked public are designated as such due to the fact that we may add middleware / transformer * support in the future */ export class Visitor { public result: VisitorResult public nodeMetadata: NodeMetadataMap = new Map(); public urlDefinitions: string[] = []; private options: NodeHtmlMarkdownOptions; constructor( public instance: NodeHtmlMarkdown, public rootNode: HtmlNode, public fileName?: string, ) { this.result = { text: '', trailingNewlineStats: { whitespace: 0, newLines: 0 } }; this.options = instance.options; this.optimizeTree(rootNode); this.visitNode(rootNode); } /* ********************************************************* */ // region: Methods /* ********************************************************* */ public addOrGetUrlDefinition(url: string): number { let id = this.urlDefinitions.findIndex(u => u === url); if (id < 0) id = this.urlDefinitions.push(url) - 1; return id + 1; } public appendResult(s: string, startPos?: number, spaceIfRepeatingChar?: boolean) { if (!s && startPos === undefined) return; const { result } = this; if (startPos !== undefined) result.text = result.text.substr(0, startPos); result.text += (spaceIfRepeatingChar && result.text.slice(-1) === s[0] ? ' ' : '') + s; result.trailingNewlineStats = getTrailingWhitespaceInfo(result.text); } public appendNewlines(count: number) { const { newLines } = this.result.trailingNewlineStats; this.appendResult('\n'.repeat(Math.max(0, (+count - newLines)))); } // endregion /* ********************************************************* */ // region: Internal Methods /* ********************************************************* */ /** * Optimize tree, flagging nodes that have usable content */ private optimizeTree(node: HtmlNode) { perfStart('Optimize tree'); const { translators } = this.instance; (function visit(node: HtmlNode): boolean { let res = false if (isTextNode(node) || (isElementNode(node) && contentlessElements.includes(node.tagName))) { res = true; } else { const childNodes = getChildNodes(node); if (!childNodes.length) { const translator = translators[(node as ElementNode).tagName]; if (translator?.preserveIfEmpty || typeof translator === 'function') res = true; } else for (const child of childNodes) { if (!res) res = visit(child); else visit(child); } } return node.preserve = res; })(node); perfStop('Optimize tree'); } /** * Apply escaping and custom replacement rules */ private processText(text: string, metadata: NodeMetadata | undefined) { let res = text; if (!metadata?.preserveWhitespace) res = res.replace(/\s+/g, ' '); if (metadata?.noEscape) return res; const { lineStartEscape, globalEscape, textReplace } = this.options; res = res .replace(globalEscape[0], globalEscape[1]) .replace(lineStartEscape[0], lineStartEscape[1]) /* If specified, apply custom replacement patterns */ if (textReplace) for (const [ pattern, r ] of textReplace) res = res.replace(pattern, r); return res; } public visitNode(node: HtmlNode, textOnly?: boolean, metadata?: NodeMetadata): void { const { result } = this; if (!node.preserve) return; /* Handle text node */ if (isTextNode(node)) return node.isWhitespace && !metadata?.preserveWhitespace ? (!result.text.length || result.trailingNewlineStats.whitespace > 0) ? void 0 : this.appendResult(' ') : this.appendResult(this.processText(metadata?.preserveWhitespace ? node.text : node.trimmedText, metadata)); if (textOnly || !isElementNode(node)) return; /* Handle element node */ const translatorCfgOrFactory: TranslatorConfig | TranslatorConfigFactory | undefined = metadata?.translators ? metadata.translators[node.tagName] : this.instance.translators[node.tagName]; /* Update metadata with list detail */ switch (node.tagName) { case 'UL': case 'OL': metadata = { ...metadata, listItemNumber: 0, listKind: (<any>node.tagName), indentLevel: (metadata?.indentLevel ?? -1) + 1 }; break; case 'LI': if (metadata?.listKind === 'OL') metadata.listItemNumber = (metadata.listItemNumber ?? 0) + 1; break; case 'PRE': metadata = { ...metadata, preserveWhitespace: true } break; } if (metadata) this.nodeMetadata.set(node, metadata); // If no translator for element, visit children if (!translatorCfgOrFactory) { for (const child of getChildNodes(node)) this.visitNode(child, textOnly, metadata); return; } /* Get Translator Config */ let cfg: TranslatorConfig; let ctx: TranslatorContext | undefined; if (!isTranslatorConfig(translatorCfgOrFactory)) { ctx = createTranslatorContext(this, node, metadata, translatorCfgOrFactory.base); cfg = { ...translatorCfgOrFactory.base, ...translatorCfgOrFactory(ctx) }; } else cfg = translatorCfgOrFactory; // Skip and don't check children if ignore flag set if (cfg.ignore) return; /* Update metadata if needed */ if ((cfg.noEscape && !metadata?.noEscape) || (cfg.childTranslators && !metadata?.translators)) { metadata = { ...metadata, noEscape: cfg.noEscape, translators: cfg.childTranslators }; this.nodeMetadata.set(node, metadata); } const startPosOuter = result.text.length; /* Write opening */ if (cfg.surroundingNewlines) this.appendNewlines(+cfg.surroundingNewlines); if (cfg.prefix) this.appendResult(cfg.prefix); /* Write inner content */ if (typeof cfg.content === 'string') this.appendResult(cfg.content, void 0, cfg.spaceIfRepeatingChar); else { const startPos = result.text.length; // Process child nodes for (const child of getChildNodes(node)) this.visitNode(child, (cfg.recurse === false), metadata); /* Apply translator post-processing */ if (cfg.postprocess) { const postRes = cfg.postprocess({ ...(ctx || createTranslatorContext(this, node, metadata)), content: result.text.substr(startPos) }); // If remove flag sent, remove / omit everything for this node (prefix, newlines, content, postfix) if (postRes === PostProcessResult.RemoveNode) { if (node.tagName === 'LI' && metadata?.listItemNumber) --metadata.listItemNumber; return this.appendResult('', startPosOuter); } if (typeof postRes === 'string') this.appendResult(postRes, startPos, cfg.spaceIfRepeatingChar); } } /* Write closing */ if (cfg.postfix) this.appendResult(cfg.postfix); if (cfg.surroundingNewlines) this.appendNewlines(+cfg.surroundingNewlines); } // endregion } // endregion /* ****************************************************************************************************************** */ // region: Utilities /* ****************************************************************************************************************** */ export function getMarkdownForHtmlNodes(instance: NodeHtmlMarkdown, rootNode: HtmlNode, fileName?: string): string { perfStart('walk'); const visitor = new Visitor(instance, rootNode, fileName); let result = visitor.result.text; perfStop('walk'); /* Post-processing */ // Add link references, if set if (instance.options.useLinkReferenceDefinitions) { if (/[^\r\n]/.test(result.slice(-1))) result += '\n'; visitor.urlDefinitions.forEach((url, idx) => { result += `\n[${idx + 1}]: ${url}`; }); } // Fixup repeating newlines const { maxConsecutiveNewlines } = instance.options; if (maxConsecutiveNewlines) result = result.replace( new RegExp(String.raw`(?:\r?\n\s*)+((?:\r?\n\s*){${maxConsecutiveNewlines}})`, 'g'), '$1' ); return trimNewLines(result); } // endregion
4d1d644b0e20630129054a7ca6097e700c0641a6
TypeScript
shmorgan-at-ibm/carbon-for-ibm-dotcom
/packages/web-components/tests/utils/mock-resize-observer.ts
2.53125
3
/** * @license * * Copyright IBM Corp. 2020, 2022 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import MockLayoutObserver from './mock-layout-observer'; /** * A mock version of `ResizeObserver`. */ class MockResizeObserver extends MockLayoutObserver { /** * The instances. */ protected static _instances = new Set<MockResizeObserver>(); /** * Triggers the callbacks on an element. * * @param elem The element. */ static run(elem: Element, contentRect: Partial<ClientRect>) { this._instances.forEach((instance) => { if (instance._callback && instance._targets.has(elem)) { instance._callback( [ { contentRect, target: elem, } as unknown as IntersectionObserverEntry, ], instance as unknown as IntersectionObserver ); } }); } } export default MockResizeObserver;
2f100e704beea5afdcea15b11f9f4d2a0311aa8e
TypeScript
biowink/reg-ci-notify-github-plugin
/src/plugin.ts
2.515625
3
import { NotifierPlugin, NotifyParams, PluginCreateOptions, PluginLogger } from 'reg-suit-interface' import * as Octokit from '@octokit/rest' // This string identifies a comment as a visual regression report. We can check // whether this string appears in a comment to determine whether to update an // existing comment or create a new one. const COMMENT_IDENTIFIER = '<!-- reg-ci-notify-github-plugin -->' const extractPRParams = (url: string): Octokit.IssuesGetParams => { const path = url.replace('https://github.com/', '') const [owner, repo, _, number] = path.split('/') return { owner, repo, number: parseInt(number, 10), } } const generateBodyFromNotifyParams = (params: NotifyParams): string => { const { comparisonResult } = params let body: string = ` ${COMMENT_IDENTIFIER} ## Visual regression report - ${comparisonResult.newItems.length} new items - ${comparisonResult.deletedItems.length} deleted items - ${comparisonResult.passedItems.length} comparisons passed - ${comparisonResult.failedItems.length} comparisons failed ` if (params.reportUrl) { body += ` View the full report [here](${params.reportUrl}). ` } return body } export interface Options {} export class CINotifyGitHubPlugin implements NotifierPlugin<Options> { init(config: PluginCreateOptions<Options>): void { // noop } async notify(params: NotifyParams): Promise<any> { const prURL = process.env.CI_PULL_REQUEST const githubToken = process.env.GITHUB_TOKEN if (!prURL || !githubToken) { return Promise.resolve() } const octokit = new Octokit({ headers: { Authorization: `token ${githubToken}`, }, }) const prParams = extractPRParams(prURL) const body = generateBodyFromNotifyParams(params) let existingComments let me try { me = await octokit.users.get({}) existingComments = await octokit.issues.getComments({ ...prParams }) } catch (e) { console.error(e) return Promise.resolve() } const existingComment = existingComments.data.find(comment => comment.user.id === me.data.id && comment.body.includes(COMMENT_IDENTIFIER)) if (existingComment) { await octokit.issues.editComment({ owner: prParams.owner, repo: prParams.repo, id: existingComment.id, body, }).catch(console.error) return Promise.resolve() } await octokit.issues.createComment({ ...prParams, body }).catch(console.error) return Promise.resolve() } }
51658af3d1b6709196c76fc5420142086ebbb68b
TypeScript
piyalcodes/ngrx_state_management
/src/app/reducers/events.reducer.ts
2.828125
3
import { Action } from '@ngrx/store'; import { EventList } from './../model/event.model'; import * as EventActions from './../actions/event.actions'; const initialEvent: EventList = { name: 'Send a mail', url: 'google.com', status: 'Pending' } export function reducer(state: EventList[] = [initialEvent], action: EventActions.Action) { switch (action.type) { case EventActions.ADD_EVENT: return [...state, action.payload]; case EventActions.REMOVE_EVENT: state.splice(action.payload, 1) return state; case EventActions.UPDATE_EVENT: state.forEach((item, i) => { if (i === action.payload) { item.status = "Completed"; } }); return state; default: return state; } }
20cb515bb474b08ac258d3e245639fe0c9f2c3ba
TypeScript
wag1twat/test-task
/src/hooks/useCharacter/getCharacterSaga.ts
2.59375
3
import { createAction } from "@reduxjs/toolkit"; import axios, { AxiosResponse } from "axios"; import { call, put, takeEvery } from "redux-saga/effects"; import { createHash } from "utils"; import { BaseRequestError } from "types"; import { Character, CharactersResponse } from "hooks/useCharacters"; export const getMarvelsCharacter = createAction( "get/marvels/character", (payload: number) => ({ payload }) ); export const fullfiledMarvelsCharacter = createAction( "fullfiled/marvels/character", (payload: Character) => ({ payload }) ); export const rejectedMarvelsCharacter = createAction( "rejected/marvels/character", (payload: BaseRequestError | null) => ({ payload }) ); function* workerMarvelsCharacter({ payload, }: ReturnType<typeof getMarvelsCharacter>) { const timestamp = new Date().getTime(); const hash = createHash(timestamp); try { const character: AxiosResponse<CharactersResponse> = yield call(() => axios.get(`https://gateway.marvel.com/v1/public/characters/${payload}`, { params: { ts: timestamp, apikey: process.env.REACT_APP_PUBLIC_KEY, hash, }, }) ); yield put(fullfiledMarvelsCharacter(character.data.data.results[0])); } catch (e) { // const error = e as AxiosError<BaseRequestError>; yield put( rejectedMarvelsCharacter({ message: "Sorry, something wrong..." }) ); } } export function* watchFetchMarvelsCharacter() { yield takeEvery(getMarvelsCharacter.type, workerMarvelsCharacter); }
a312c9d3424aa0278085cdd2da6bcab02df3eb5e
TypeScript
mathjax/MathJax-src
/ts/core/MmlTree/OperatorDictionary.ts
2.578125
3
/************************************************************* * * Copyright (c) 2017-2022 The MathJax Consortium * * 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. */ /** * @fileoverview Defines the operator dictionary structure * * @author [email protected] (Davide Cervone) */ import {PropertyList} from '../Tree/Node.js'; import {TEXCLASS} from './MmlNode.js'; /** * Types needed for the operator dictionary */ export type OperatorDef = [number, number, number, PropertyList]; export type OperatorList = {[name: string]: OperatorDef}; export type RangeDef = [number, number, number, string, string?]; /** * @param {number} lspace The operator's MathML left-hand spacing * @param {number} rspace The operator's MathML right-hand spacing * @param {number} texClass The default TeX class for the operator * @param {PropertyList} properties Any default properties from the operator dictionary * @return {OperatorDef} The operator definition array */ export function OPDEF(lspace: number, rspace: number, texClass: number = TEXCLASS.BIN, properties: PropertyList = null): OperatorDef { return [lspace, rspace, texClass, properties] as OperatorDef; } /** * The various kinds of operators in the dictionary */ export const MO = { ORD: OPDEF(0, 0, TEXCLASS.ORD), ORD11: OPDEF(1, 1, TEXCLASS.ORD), ORD21: OPDEF(2, 1, TEXCLASS.ORD), ORD02: OPDEF(0, 2, TEXCLASS.ORD), ORD55: OPDEF(5, 5, TEXCLASS.ORD), NONE: OPDEF(0, 0, TEXCLASS.NONE), OP: OPDEF(1, 2, TEXCLASS.OP, {largeop: true, movablelimits: true, symmetric: true}), OPFIXED: OPDEF(1, 2, TEXCLASS.OP, {largeop: true, movablelimits: true}), INTEGRAL: OPDEF(0, 1, TEXCLASS.OP, {largeop: true, symmetric: true}), INTEGRAL2: OPDEF(1, 2, TEXCLASS.OP, {largeop: true, symmetric: true}), BIN3: OPDEF(3, 3, TEXCLASS.BIN), BIN4: OPDEF(4, 4, TEXCLASS.BIN), BIN01: OPDEF(0, 1, TEXCLASS.BIN), BIN5: OPDEF(5, 5, TEXCLASS.BIN), TALLBIN: OPDEF(4, 4, TEXCLASS.BIN, {stretchy: true}), BINOP: OPDEF(4, 4, TEXCLASS.BIN, {largeop: true, movablelimits: true}), REL: OPDEF(5, 5, TEXCLASS.REL), REL1: OPDEF(1, 1, TEXCLASS.REL, {stretchy: true}), REL4: OPDEF(4, 4, TEXCLASS.REL), RELSTRETCH: OPDEF(5, 5, TEXCLASS.REL, {stretchy: true}), RELACCENT: OPDEF(5, 5, TEXCLASS.REL, {accent: true}), WIDEREL: OPDEF(5, 5, TEXCLASS.REL, {accent: true, stretchy: true}), OPEN: OPDEF(0, 0, TEXCLASS.OPEN, {fence: true, stretchy: true, symmetric: true}), CLOSE: OPDEF(0, 0, TEXCLASS.CLOSE, {fence: true, stretchy: true, symmetric: true}), INNER: OPDEF(0, 0, TEXCLASS.INNER), PUNCT: OPDEF(0, 3, TEXCLASS.PUNCT), ACCENT: OPDEF(0, 0, TEXCLASS.ORD, {accent: true}), WIDEACCENT: OPDEF(0, 0, TEXCLASS.ORD, {accent: true, stretchy: true}) }; /** * The default TeX classes for the various unicode blocks, and their names */ export const RANGES: RangeDef[] = [ [0x0020, 0x007F, TEXCLASS.REL, 'mo'], // Basic Latin [0x00A0, 0x00BF, TEXCLASS.ORD, 'mo'], // Latin-1 Supplement symbols [0x00C0, 0x024F, TEXCLASS.ORD, 'mi'], // Latin-1 Supplement, Latin Extended-A, Latin Extended-B [0x02B0, 0x036F, TEXCLASS.ORD, 'mo'], // Spacing modifier letters, Combining Diacritical Marks [0x0370, 0x1A20, TEXCLASS.ORD, 'mi'], // Greek and Coptic (through) Tai Tham [0x1AB0, 0x1AFF, TEXCLASS.ORD, 'mo'], // Combining Diacritical Marks Extended [0x1B00, 0x1DBF, TEXCLASS.ORD, 'mi'], // Balinese (through) Phonetic Extensions Supplement [0x1DC0, 0x1DFF, TEXCLASS.ORD, 'mo'], // Combining Diacritical Marks Supplement [0x1E00, 0x1FFF, TEXCLASS.ORD, 'mi'], // Latin Extended Additional, Greek Extended [0x2000, 0x206F, TEXCLASS.ORD, 'mo'], // General Punctuation [0x2070, 0x209F, TEXCLASS.ORD, 'mo'], // Superscript and Subscripts (through) Combining Diacritical Marks for Symbols [0x2100, 0x214F, TEXCLASS.ORD, 'mi'], // Letterlike Symbols [0x2150, 0x218F, TEXCLASS.ORD, 'mn'], // Number Forms [0x2190, 0x21FF, TEXCLASS.REL, 'mo'], // Arrows [0x2200, 0x22FF, TEXCLASS.BIN, 'mo'], // Mathematical Operators [0x2300, 0x23FF, TEXCLASS.ORD, 'mo'], // Miscellaneous Technical [0x2460, 0x24FF, TEXCLASS.ORD, 'mn'], // Enclosed Alphanumerics [0x2500, 0x27EF, TEXCLASS.ORD, 'mo'], // Box Drawing (though) Miscellaneous Math Symbols-A [0x27F0, 0x27FF, TEXCLASS.REL, 'mo'], // Supplemental Arrows-A [0x2800, 0x28FF, TEXCLASS.ORD, 'mtext'], // Braille Patterns [0x2900, 0x297F, TEXCLASS.REL, 'mo'], // Supplemental Arrows-B [0x2980, 0x29FF, TEXCLASS.ORD, 'mo'], // Miscellaneous Math Symbols-B [0x2A00, 0x2AFF, TEXCLASS.BIN, 'mo'], // Supplemental Math Operators [0x2B00, 0x2B2F, TEXCLASS.ORD, 'mo'], // Miscellaneous Symbols and Arrows [0x2B30, 0x2B4F, TEXCLASS.REL, 'mo'], // Arrows from above [0x2B50, 0x2BFF, TEXCLASS.ORD, 'mo'], // Rest of above [0x2C00, 0x2DE0, TEXCLASS.ORD, 'mi'], // Glagolitic (through) Ethipoc Extended [0x2E00, 0x2E7F, TEXCLASS.ORD, 'mo'], // Supplemental Punctuation [0x2E80, 0x2FDF, TEXCLASS.ORD, 'mi', 'normal'], // CJK Radicals Supplement (through) Kangxi Radicals [0x2FF0, 0x303F, TEXCLASS.ORD, 'mo'], // Ideographic Desc. Characters, CJK Symbols and Punctuation [0x3040, 0xA49F, TEXCLASS.ORD, 'mi', 'normal'], // Hiragana (through) Yi Radicals [0xA4D0, 0xA82F, TEXCLASS.ORD, 'mi'], // Lisu (through) Syloti Nagri [0xA830, 0xA83F, TEXCLASS.ORD, 'mn'], // Common Indic Number FormsArabic Presentation Forms-A [0xA840, 0xD7FF, TEXCLASS.ORD, 'mi'], // Phags-pa (though) Hangul Jamo Extended-B [0xF900, 0xFAFF, TEXCLASS.ORD, 'mi', 'normal'], // CJK Compatibility Ideographs [0xFB00, 0xFDFF, TEXCLASS.ORD, 'mi'], // Alphabetic Presentation Forms (though) Arabic Presentation Forms-A [0xFE00, 0xFE6F, TEXCLASS.ORD, 'mo'], // Variation Selector (through) Small Form Variants [0xFE70, 0x100FF, TEXCLASS.ORD, 'mi'], // Arabic Presentation Forms-B (through) Linear B Ideograms [0x10100, 0x1018F, TEXCLASS.ORD, 'mn'], // Aegean Numbers, Ancient Greek Numbers [0x10190, 0x123FF, TEXCLASS.ORD, 'mi', 'normal'], // Ancient Symbols (through) Cuneiform [0x12400, 0x1247F, TEXCLASS.ORD, 'mn'], // Cuneiform Numbers and Punctuation [0x12480, 0x1BC9F, TEXCLASS.ORD, 'mi', 'normal'], // Early Dynastic Cuneiform (through) Duployan [0x1BCA0, 0x1D25F, TEXCLASS.ORD, 'mo'], // Shorthand Format Controls (through) TaiXuan Jing Symbols [0x1D360, 0x1D37F, TEXCLASS.ORD, 'mn'], // Counting Rod Numerals [0x1D400, 0x1D7CD, TEXCLASS.ORD, 'mi'], // Math Alphanumeric Symbols [0x1D7CE, 0x1D7FF, TEXCLASS.ORD, 'mn'], // Numerals from above [0x1DF00, 0x1F7FF, TEXCLASS.ORD, 'mo'], // Mahjong Tiles (through) Geometric Shapes Extended [0x1F800, 0x1F8FF, TEXCLASS.REL, 'mo'], // Supplemental Arrows-C [0x1F900, 0x1F9FF, TEXCLASS.ORD, 'mo'], // Supplemental Symbols and Pictographs [0x20000, 0x2FA1F, TEXCLASS.ORD, 'mi', 'normnal'], // CJK Unified Ideographs Ext. B (through) CJK Sompatibility Ideographs Supp. ]; /** * Get the Unicode range for the first character of a string * * @param {string} text The character to check * @return {RangeDef|null} The range containing that character, or null */ export function getRange(text: string): RangeDef | null { const n = text.codePointAt(0); for (const range of RANGES) { if (n <= range[1]) { if (n >= range[0]) { return range; } break; } } return null; } /** * The default MathML spacing for the various TeX classes. */ export const MMLSPACING = [ [0, 0], // ORD [1, 2], // OP [3, 3], // BIN [4, 4], // REL [0, 0], // OPEN [0, 0], // CLOSE [0, 3] // PUNCT ]; /** * The operator dictionary, with sections for the three forms: prefix, postfix, and infix */ export const OPTABLE: {[form: string]: OperatorList} = { prefix: { '(': MO.OPEN, // left parenthesis '+': MO.BIN01, // plus sign '-': MO.BIN01, // hyphen-minus '[': MO.OPEN, // left square bracket '{': MO.OPEN, // left curly bracket '|': MO.OPEN, // vertical line '||': [0, 0, TEXCLASS.BIN, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: ||| '\u00AC': MO.ORD21, // not sign '\u00B1': MO.BIN01, // plus-minus sign '\u2016': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true}], // double vertical line '\u2018': [0, 0, TEXCLASS.OPEN, {fence: true}], // left single quotation mark '\u201C': [0, 0, TEXCLASS.OPEN, {fence: true}], // left double quotation mark '\u2145': MO.ORD21, // double-struck italic capital d '\u2146': OPDEF(2, 0, TEXCLASS.ORD), // double-struck italic small d '\u2200': MO.ORD21, // for all '\u2202': MO.ORD21, // partial differential '\u2203': MO.ORD21, // there exists '\u2204': MO.ORD21, // there does not exist '\u2207': MO.ORD21, // nabla '\u220F': MO.OP, // n-ary product '\u2210': MO.OP, // n-ary coproduct '\u2211': MO.OP, // n-ary summation '\u2212': MO.BIN01, // minus sign '\u2213': MO.BIN01, // minus-or-plus sign '\u221A': [1, 1, TEXCLASS.ORD, {stretchy: true}], // square root '\u221B': MO.ORD11, // cube root '\u221C': MO.ORD11, // fourth root '\u2220': MO.ORD, // angle '\u2221': MO.ORD, // measured angle '\u2222': MO.ORD, // spherical angle '\u222B': MO.INTEGRAL, // integral '\u222C': MO.INTEGRAL, // double integral '\u222D': MO.INTEGRAL, // triple integral '\u222E': MO.INTEGRAL, // contour integral '\u222F': MO.INTEGRAL, // surface integral '\u2230': MO.INTEGRAL, // volume integral '\u2231': MO.INTEGRAL, // clockwise integral '\u2232': MO.INTEGRAL, // clockwise contour integral '\u2233': MO.INTEGRAL, // anticlockwise contour integral '\u22C0': MO.OP, // n-ary logical and '\u22C1': MO.OP, // n-ary logical or '\u22C2': MO.OP, // n-ary intersection '\u22C3': MO.OP, // n-ary union '\u2308': MO.OPEN, // left ceiling '\u230A': MO.OPEN, // left floor '\u2329': MO.OPEN, // left-pointing angle bracket '\u2772': MO.OPEN, // light left tortoise shell bracket ornament '\u27E6': MO.OPEN, // mathematical left white square bracket '\u27E8': MO.OPEN, // mathematical left angle bracket '\u27EA': MO.OPEN, // mathematical left double angle bracket '\u27EC': MO.OPEN, // mathematical left white tortoise shell bracket '\u27EE': MO.OPEN, // mathematical left flattened parenthesis '\u2980': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true}], // triple vertical bar delimiter '\u2983': MO.OPEN, // left white curly bracket '\u2985': MO.OPEN, // left white parenthesis '\u2987': MO.OPEN, // z notation left image bracket '\u2989': MO.OPEN, // z notation left binding bracket '\u298B': MO.OPEN, // left square bracket with underbar '\u298D': MO.OPEN, // left square bracket with tick in top corner '\u298F': MO.OPEN, // left square bracket with tick in bottom corner '\u2991': MO.OPEN, // left angle bracket with dot '\u2993': MO.OPEN, // left arc less-than bracket '\u2995': MO.OPEN, // double left arc greater-than bracket '\u2997': MO.OPEN, // left black tortoise shell bracket '\u29FC': MO.OPEN, // left-pointing curved angle bracket '\u2A00': MO.OP, // n-ary circled dot operator '\u2A01': MO.OP, // n-ary circled plus operator '\u2A02': MO.OP, // n-ary circled times operator '\u2A03': MO.OP, // n-ary union operator with dot '\u2A04': MO.OP, // n-ary union operator with plus '\u2A05': MO.OP, // n-ary square intersection operator '\u2A06': MO.OP, // n-ary square union operator '\u2A07': MO.OP, // two logical and operator '\u2A08': MO.OP, // two logical or operator '\u2A09': MO.OP, // n-ary times operator '\u2A0A': MO.OP, // modulo two sum '\u2A0B': MO.INTEGRAL2, // summation with integral '\u2A0C': MO.INTEGRAL, // quadruple integral operator '\u2A0D': MO.INTEGRAL2, // finite part integral '\u2A0E': MO.INTEGRAL2, // integral with double stroke '\u2A0F': MO.INTEGRAL2, // integral average with slash '\u2A10': MO.OP, // circulation function '\u2A11': MO.OP, // anticlockwise integration '\u2A12': MO.OP, // line integration with rectangular path around pole '\u2A13': MO.OP, // line integration with semicircular path around pole '\u2A14': MO.OP, // line integration not including the pole '\u2A15': MO.INTEGRAL2, // integral around a point operator '\u2A16': MO.INTEGRAL2, // quaternion integral operator '\u2A17': MO.INTEGRAL2, // integral with leftwards arrow with hook '\u2A18': MO.INTEGRAL2, // integral with times sign '\u2A19': MO.INTEGRAL2, // integral with intersection '\u2A1A': MO.INTEGRAL2, // integral with union '\u2A1B': MO.INTEGRAL2, // integral with overbar '\u2A1C': MO.INTEGRAL2, // integral with underbar '\u2AFC': MO.OP, // large triple vertical bar operator '\u2AFF': MO.OP, // n-ary white vertical bar }, postfix: { '!!': OPDEF(1, 0), // multiple character operator: !! '!': [1, 0, TEXCLASS.CLOSE, null], // exclamation mark '"': MO.ACCENT, // quotation mark '&': MO.ORD, // ampersand ')': MO.CLOSE, // right parenthesis '++': OPDEF(0, 0), // multiple character operator: ++ '--': OPDEF(0, 0), // multiple character operator: -- '..': OPDEF(0, 0), // multiple character operator: .. '...': MO.ORD, // multiple character operator: ... '\'': MO.ACCENT, // apostrophe ']': MO.CLOSE, // right square bracket '^': MO.WIDEACCENT, // circumflex accent '_': MO.WIDEACCENT, // low line '`': MO.ACCENT, // grave accent '|': MO.CLOSE, // vertical line '}': MO.CLOSE, // right curly bracket '~': MO.WIDEACCENT, // tilde '||': [0, 0, TEXCLASS.BIN, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: ||| '\u00A8': MO.ACCENT, // diaeresis '\u00AA': MO.ACCENT, // feminie ordinal indicator '\u00AF': MO.WIDEACCENT, // macron '\u00B0': MO.ORD, // degree sign '\u00B2': MO.ACCENT, // superscript 2 '\u00B3': MO.ACCENT, // superscript 3 '\u00B4': MO.ACCENT, // acute accent '\u00B8': MO.ACCENT, // cedilla '\u00B9': MO.ACCENT, // superscript 1 '\u00BA': MO.ACCENT, // masculine ordinal indicator '\u02C6': MO.WIDEACCENT, // modifier letter circumflex accent '\u02C7': MO.WIDEACCENT, // caron '\u02C9': MO.WIDEACCENT, // modifier letter macron '\u02CA': MO.ACCENT, // modifier letter acute accent '\u02CB': MO.ACCENT, // modifier letter grave accent '\u02CD': MO.WIDEACCENT, // modifier letter low macron '\u02D8': MO.ACCENT, // breve '\u02D9': MO.ACCENT, // dot above '\u02DA': MO.ACCENT, // ring above '\u02DC': MO.WIDEACCENT, // small tilde '\u02DD': MO.ACCENT, // double acute accent '\u02F7': MO.WIDEACCENT, // modifier letter low tilde '\u0302': MO.WIDEACCENT, // combining circumflex accent '\u0311': MO.ACCENT, // combining inverted breve '\u03F6': MO.REL, // greek reversed lunate epsilon symbol '\u2016': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true}], // double vertical line '\u2019': [0, 0, TEXCLASS.CLOSE, {fence: true}], // right single quotation mark '\u201A': MO.ACCENT, // single low-9 quotation mark '\u201B': MO.ACCENT, // single high-reversed-9 quotation mark '\u201D': [0, 0, TEXCLASS.CLOSE, {fence: true}], // right double quotation mark '\u201E': MO.ACCENT, // double low-9 quotation mark '\u201F': MO.ACCENT, // double high-reversed-9 quotation mark '\u2032': MO.ORD, // prime '\u2033': MO.ACCENT, // double prime '\u2034': MO.ACCENT, // triple prime '\u2035': MO.ACCENT, // reversed prime '\u2036': MO.ACCENT, // reversed double prime '\u2037': MO.ACCENT, // reversed triple prime '\u203E': MO.WIDEACCENT, // overline '\u2057': MO.ACCENT, // quadruple prime '\u20DB': MO.ACCENT, // combining three dots above '\u20DC': MO.ACCENT, // combining four dots above '\u2309': MO.CLOSE, // right ceiling '\u230B': MO.CLOSE, // right floor '\u232A': MO.CLOSE, // right-pointing angle bracket '\u23B4': MO.WIDEACCENT, // top square bracket '\u23B5': MO.WIDEACCENT, // bottom square bracket '\u23DC': MO.WIDEACCENT, // top parenthesis '\u23DD': MO.WIDEACCENT, // bottom parenthesis '\u23DE': MO.WIDEACCENT, // top curly bracket '\u23DF': MO.WIDEACCENT, // bottom curly bracket '\u23E0': MO.WIDEACCENT, // top tortoise shell bracket '\u23E1': MO.WIDEACCENT, // bottom tortoise shell bracket '\u25A0': MO.BIN3, // black square '\u25A1': MO.BIN3, // white square '\u25AA': MO.BIN3, // black small square '\u25AB': MO.BIN3, // white small square '\u25AD': MO.BIN3, // white rectangle '\u25AE': MO.BIN3, // black vertical rectangle '\u25AF': MO.BIN3, // white vertical rectangle '\u25B0': MO.BIN3, // black parallelogram '\u25B1': MO.BIN3, // white parallelogram '\u25B2': MO.BIN4, // black up-pointing triangle '\u25B4': MO.BIN4, // black up-pointing small triangle '\u25B6': MO.BIN4, // black right-pointing triangle '\u25B7': MO.BIN4, // white right-pointing triangle '\u25B8': MO.BIN4, // black right-pointing small triangle '\u25BC': MO.BIN4, // black down-pointing triangle '\u25BE': MO.BIN4, // black down-pointing small triangle '\u25C0': MO.BIN4, // black left-pointing triangle '\u25C1': MO.BIN4, // white left-pointing triangle '\u25C2': MO.BIN4, // black left-pointing small triangle '\u25C4': MO.BIN4, // black left-pointing pointer '\u25C5': MO.BIN4, // white left-pointing pointer '\u25C6': MO.BIN4, // black diamond '\u25C7': MO.BIN4, // white diamond '\u25C8': MO.BIN4, // white diamond containing black small diamond '\u25C9': MO.BIN4, // fisheye '\u25CC': MO.BIN4, // dotted circle '\u25CD': MO.BIN4, // circle with vertical fill '\u25CE': MO.BIN4, // bullseye '\u25CF': MO.BIN4, // black circle '\u25D6': MO.BIN4, // left half black circle '\u25D7': MO.BIN4, // right half black circle '\u25E6': MO.BIN4, // white bullet '\u266D': MO.ORD02, // music flat sign '\u266E': MO.ORD02, // music natural sign '\u266F': MO.ORD02, // music sharp sign '\u2773': MO.CLOSE, // light right tortoise shell bracket ornament '\u27E7': MO.CLOSE, // mathematical right white square bracket '\u27E9': MO.CLOSE, // mathematical right angle bracket '\u27EB': MO.CLOSE, // mathematical right double angle bracket '\u27ED': MO.CLOSE, // mathematical right white tortoise shell bracket '\u27EF': MO.CLOSE, // mathematical right flattened parenthesis '\u2980': [0, 0, TEXCLASS.ORD, {fence: true, stretchy: true}], // triple vertical bar delimiter '\u2984': MO.CLOSE, // right white curly bracket '\u2986': MO.CLOSE, // right white parenthesis '\u2988': MO.CLOSE, // z notation right image bracket '\u298A': MO.CLOSE, // z notation right binding bracket '\u298C': MO.CLOSE, // right square bracket with underbar '\u298E': MO.CLOSE, // right square bracket with tick in bottom corner '\u2990': MO.CLOSE, // right square bracket with tick in top corner '\u2992': MO.CLOSE, // right angle bracket with dot '\u2994': MO.CLOSE, // right arc greater-than bracket '\u2996': MO.CLOSE, // double right arc less-than bracket '\u2998': MO.CLOSE, // right black tortoise shell bracket '\u29FD': MO.CLOSE, // right-pointing curved angle bracket }, infix: { '!=': MO.BIN4, // multiple character operator: != '#': MO.ORD, // # '$': MO.ORD, // $ '%': [3, 3, TEXCLASS.ORD, null], // percent sign '&&': MO.BIN4, // multiple character operator: && '': MO.ORD, // empty <mo> '*': MO.BIN3, // asterisk '**': OPDEF(1, 1), // multiple character operator: ** '*=': MO.BIN4, // multiple character operator: *= '+': MO.BIN4, // plus sign '+=': MO.BIN4, // multiple character operator: += ',': [0, 3, TEXCLASS.PUNCT, {linebreakstyle: 'after', separator: true}], // comma '-': MO.BIN4, // hyphen-minus '-=': MO.BIN4, // multiple character operator: -= '->': MO.BIN5, // multiple character operator: -> '.': [0, 3, TEXCLASS.PUNCT, {separator: true}], // \ldotp '/': MO.ORD11, // solidus '//': OPDEF(1, 1), // multiple character operator: // '/=': MO.BIN4, // multiple character operator: /= ':': [1, 2, TEXCLASS.REL, null], // colon ':=': MO.BIN4, // multiple character operator: := ';': [0, 3, TEXCLASS.PUNCT, {linebreakstyle: 'after', separator: true}], // semicolon '<': MO.REL, // less-than sign '<=': MO.BIN5, // multiple character operator: <= '<>': OPDEF(1, 1), // multiple character operator: <> '=': MO.REL, // equals sign '==': MO.BIN4, // multiple character operator: == '>': MO.REL, // greater-than sign '>=': MO.BIN5, // multiple character operator: >= '?': [1, 1, TEXCLASS.CLOSE, null], // question mark '@': MO.ORD11, // commercial at '\\': MO.ORD, // reverse solidus '^': MO.ORD11, // circumflex accent '_': MO.ORD11, // low line '|': [2, 2, TEXCLASS.ORD, {fence: true, stretchy: true, symmetric: true}], // vertical line '||': [2, 2, TEXCLASS.BIN, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: || '|||': [2, 2, TEXCLASS.ORD, {fence: true, stretchy: true, symmetric: true}], // multiple character operator: ||| '\u00B1': MO.BIN4, // plus-minus sign '\u00B7': MO.BIN4, // middle dot '\u00D7': MO.BIN4, // multiplication sign '\u00F7': MO.BIN4, // division sign '\u02B9': MO.ORD, // prime '\u0300': MO.ACCENT, // \grave '\u0301': MO.ACCENT, // \acute '\u0303': MO.WIDEACCENT, // \tilde '\u0304': MO.ACCENT, // \bar '\u0306': MO.ACCENT, // \breve '\u0307': MO.ACCENT, // \dot '\u0308': MO.ACCENT, // \ddot '\u030C': MO.ACCENT, // \check '\u0332': MO.WIDEACCENT, // horizontal line '\u0338': MO.REL4, // \not '\u2015': [0, 0, TEXCLASS.ORD, {stretchy: true}], // horizontal line '\u2017': [0, 0, TEXCLASS.ORD, {stretchy: true}], // horizontal line '\u2020': MO.BIN3, // \dagger '\u2021': MO.BIN3, // \ddagger '\u2022': MO.BIN4, // bullet '\u2026': MO.INNER, // horizontal ellipsis '\u2043': MO.BIN4, // hyphen bullet '\u2044': MO.TALLBIN, // fraction slash '\u2061': MO.NONE, // function application '\u2062': MO.NONE, // invisible times '\u2063': [0, 0, TEXCLASS.NONE, {linebreakstyle: 'after', separator: true}], // invisible separator '\u2064': MO.NONE, // invisible plus '\u20D7': MO.ACCENT, // \vec '\u2111': MO.ORD, // \Im '\u2113': MO.ORD, // \ell '\u2118': MO.ORD, // \wp '\u211C': MO.ORD, // \Re '\u2190': MO.WIDEREL, // leftwards arrow '\u2191': MO.RELSTRETCH, // upwards arrow '\u2192': MO.WIDEREL, // rightwards arrow '\u2193': MO.RELSTRETCH, // downwards arrow '\u2194': MO.WIDEREL, // left right arrow '\u2195': MO.RELSTRETCH, // up down arrow '\u2196': MO.RELSTRETCH, // north west arrow '\u2197': MO.RELSTRETCH, // north east arrow '\u2198': MO.RELSTRETCH, // south east arrow '\u2199': MO.RELSTRETCH, // south west arrow '\u219A': MO.RELACCENT, // leftwards arrow with stroke '\u219B': MO.RELACCENT, // rightwards arrow with stroke '\u219C': MO.WIDEREL, // leftwards wave arrow '\u219D': MO.WIDEREL, // rightwards wave arrow '\u219E': MO.WIDEREL, // leftwards two headed arrow '\u219F': MO.WIDEREL, // upwards two headed arrow '\u21A0': MO.WIDEREL, // rightwards two headed arrow '\u21A1': MO.RELSTRETCH, // downwards two headed arrow '\u21A2': MO.WIDEREL, // leftwards arrow with tail '\u21A3': MO.WIDEREL, // rightwards arrow with tail '\u21A4': MO.WIDEREL, // leftwards arrow from bar '\u21A5': MO.RELSTRETCH, // upwards arrow from bar '\u21A6': MO.WIDEREL, // rightwards arrow from bar '\u21A7': MO.RELSTRETCH, // downwards arrow from bar '\u21A8': MO.RELSTRETCH, // up down arrow with base '\u21A9': MO.WIDEREL, // leftwards arrow with hook '\u21AA': MO.WIDEREL, // rightwards arrow with hook '\u21AB': MO.WIDEREL, // leftwards arrow with loop '\u21AC': MO.WIDEREL, // rightwards arrow with loop '\u21AD': MO.WIDEREL, // left right wave arrow '\u21AE': MO.RELACCENT, // left right arrow with stroke '\u21AF': MO.RELSTRETCH, // downwards zigzag arrow '\u21B0': MO.RELSTRETCH, // upwards arrow with tip leftwards '\u21B1': MO.RELSTRETCH, // upwards arrow with tip rightwards '\u21B2': MO.RELSTRETCH, // downwards arrow with tip leftwards '\u21B3': MO.RELSTRETCH, // downwards arrow with tip rightwards '\u21B4': MO.RELSTRETCH, // rightwards arrow with corner downwards '\u21B5': MO.RELSTRETCH, // downwards arrow with corner leftwards '\u21B6': MO.RELACCENT, // anticlockwise top semicircle arrow '\u21B7': MO.RELACCENT, // clockwise top semicircle arrow '\u21B8': MO.REL, // north west arrow to long bar '\u21B9': MO.WIDEREL, // leftwards arrow to bar over rightwards arrow to bar '\u21BA': MO.REL, // anticlockwise open circle arrow '\u21BB': MO.REL, // clockwise open circle arrow '\u21BC': MO.WIDEREL, // leftwards harpoon with barb upwards '\u21BD': MO.WIDEREL, // leftwards harpoon with barb downwards '\u21BE': MO.RELSTRETCH, // upwards harpoon with barb rightwards '\u21BF': MO.RELSTRETCH, // upwards harpoon with barb leftwards '\u21C0': MO.WIDEREL, // rightwards harpoon with barb upwards '\u21C1': MO.WIDEREL, // rightwards harpoon with barb downwards '\u21C2': MO.RELSTRETCH, // downwards harpoon with barb rightwards '\u21C3': MO.RELSTRETCH, // downwards harpoon with barb leftwards '\u21C4': MO.WIDEREL, // rightwards arrow over leftwards arrow '\u21C5': MO.RELSTRETCH, // upwards arrow leftwards of downwards arrow '\u21C6': MO.WIDEREL, // leftwards arrow over rightwards arrow '\u21C7': MO.WIDEREL, // leftwards paired arrows '\u21C8': MO.RELSTRETCH, // upwards paired arrows '\u21C9': MO.WIDEREL, // rightwards paired arrows '\u21CA': MO.RELSTRETCH, // downwards paired arrows '\u21CB': MO.WIDEREL, // leftwards harpoon over rightwards harpoon '\u21CC': MO.WIDEREL, // rightwards harpoon over leftwards harpoon '\u21CD': MO.RELACCENT, // leftwards double arrow with stroke '\u21CE': MO.RELACCENT, // left right double arrow with stroke '\u21CF': MO.RELACCENT, // rightwards double arrow with stroke '\u21D0': MO.WIDEREL, // leftwards double arrow '\u21D1': MO.RELSTRETCH, // upwards double arrow '\u21D2': MO.WIDEREL, // rightwards double arrow '\u21D3': MO.RELSTRETCH, // downwards double arrow '\u21D4': MO.WIDEREL, // left right double arrow '\u21D5': MO.RELSTRETCH, // up down double arrow '\u21D6': MO.RELSTRETCH, // north west double arrow '\u21D7': MO.RELSTRETCH, // north east double arrow '\u21D8': MO.RELSTRETCH, // south east double arrow '\u21D9': MO.RELSTRETCH, // south west double arrow '\u21DA': MO.WIDEREL, // leftwards triple arrow '\u21DB': MO.WIDEREL, // rightwards triple arrow '\u21DC': MO.WIDEREL, // leftwards squiggle arrow '\u21DD': MO.WIDEREL, // rightwards squiggle arrow '\u21DE': MO.REL, // upwards arrow with double stroke '\u21DF': MO.REL, // downwards arrow with double stroke '\u21E0': MO.WIDEREL, // leftwards dashed arrow '\u21E1': MO.RELSTRETCH, // upwards dashed arrow '\u21E2': MO.WIDEREL, // rightwards dashed arrow '\u21E3': MO.RELSTRETCH, // downwards dashed arrow '\u21E4': MO.WIDEREL, // leftwards arrow to bar '\u21E5': MO.WIDEREL, // rightwards arrow to bar '\u21E6': MO.WIDEREL, // leftwards white arrow '\u21E7': MO.RELSTRETCH, // upwards white arrow '\u21E8': MO.WIDEREL, // rightwards white arrow '\u21E9': MO.RELSTRETCH, // downwards white arrow '\u21EA': MO.RELSTRETCH, // upwards white arrow from bar '\u21EB': MO.RELSTRETCH, // upwards white arrow on pedestal '\u21EC': MO.RELSTRETCH, // upwards white arrow on pedestal with horizontal bar '\u21ED': MO.RELSTRETCH, // upwards white arrow on pedestal with vertical bar '\u21EE': MO.RELSTRETCH, // upwards white double arrow '\u21EF': MO.RELSTRETCH, // upwards white double arrow on pedestal '\u21F0': MO.WIDEREL, // rightwards white arrow from wall '\u21F1': MO.REL, // north west arrow to corner '\u21F2': MO.REL, // south east arrow to corner '\u21F3': MO.RELSTRETCH, // up down white arrow '\u21F4': MO.RELACCENT, // right arrow with small circle '\u21F5': MO.RELSTRETCH, // downwards arrow leftwards of upwards arrow '\u21F6': MO.WIDEREL, // three rightwards arrows '\u21F7': MO.RELACCENT, // leftwards arrow with vertical stroke '\u21F8': MO.RELACCENT, // rightwards arrow with vertical stroke '\u21F9': MO.RELACCENT, // left right arrow with vertical stroke '\u21FA': MO.RELACCENT, // leftwards arrow with double vertical stroke '\u21FB': MO.RELACCENT, // rightwards arrow with double vertical stroke '\u21FC': MO.RELACCENT, // left right arrow with double vertical stroke '\u21FD': MO.WIDEREL, // leftwards open-headed arrow '\u21FE': MO.WIDEREL, // rightwards open-headed arrow '\u21FF': MO.WIDEREL, // left right open-headed arrow '\u2201': OPDEF(1, 2, TEXCLASS.ORD), // complement '\u2205': MO.ORD, // \emptyset '\u2206': MO.BIN3, // increment '\u2208': MO.REL, // element of '\u2209': MO.REL, // not an element of '\u220A': MO.REL, // small element of '\u220B': MO.REL, // contains as member '\u220C': MO.REL, // does not contain as member '\u220D': MO.REL, // small contains as member '\u220E': MO.BIN3, // end of proof '\u2212': MO.BIN4, // minus sign '\u2213': MO.BIN4, // minus-or-plus sign '\u2214': MO.BIN4, // dot plus '\u2215': MO.TALLBIN, // division slash '\u2216': MO.BIN4, // set minus '\u2217': MO.BIN4, // asterisk operator '\u2218': MO.BIN4, // ring operator '\u2219': MO.BIN4, // bullet operator '\u221D': MO.REL, // proportional to '\u221E': MO.ORD, // \infty '\u221F': MO.REL, // right angle '\u2223': MO.REL, // divides '\u2224': MO.REL, // does not divide '\u2225': MO.REL, // parallel to '\u2226': MO.REL, // not parallel to '\u2227': MO.BIN4, // logical and '\u2228': MO.BIN4, // logical or '\u2229': MO.BIN4, // intersection '\u222A': MO.BIN4, // union '\u2234': MO.REL, // therefore '\u2235': MO.REL, // because '\u2236': MO.REL, // ratio '\u2237': MO.REL, // proportion '\u2238': MO.BIN4, // dot minus '\u2239': MO.REL, // excess '\u223A': MO.BIN4, // geometric proportion '\u223B': MO.REL, // homothetic '\u223C': MO.REL, // tilde operator '\u223D': MO.REL, // reversed tilde '\u223D\u0331': MO.BIN3, // reversed tilde with underline '\u223E': MO.REL, // inverted lazy s '\u223F': MO.BIN3, // sine wave '\u2240': MO.BIN4, // wreath product '\u2241': MO.REL, // not tilde '\u2242': MO.REL, // minus tilde '\u2242\u0338': MO.REL, // minus tilde with slash '\u2243': MO.REL, // asymptotically equal to '\u2244': MO.REL, // not asymptotically equal to '\u2245': MO.REL, // approximately equal to '\u2246': MO.REL, // approximately but not actually equal to '\u2247': MO.REL, // neither approximately nor actually equal to '\u2248': MO.REL, // almost equal to '\u2249': MO.REL, // not almost equal to '\u224A': MO.REL, // almost equal or equal to '\u224B': MO.REL, // triple tilde '\u224C': MO.REL, // all equal to '\u224D': MO.REL, // equivalent to '\u224E': MO.REL, // geometrically equivalent to '\u224E\u0338': MO.REL, // geometrically equivalent to with slash '\u224F': MO.REL, // difference between '\u224F\u0338': MO.REL, // difference between with slash '\u2250': MO.REL, // approaches the limit '\u2251': MO.REL, // geometrically equal to '\u2252': MO.REL, // approximately equal to or the image of '\u2253': MO.REL, // image of or approximately equal to '\u2254': MO.REL, // colon equals '\u2255': MO.REL, // equals colon '\u2256': MO.REL, // ring in equal to '\u2257': MO.REL, // ring equal to '\u2258': MO.REL, // corresponds to '\u2259': MO.REL, // estimates '\u225A': MO.REL, // equiangular to '\u225B': MO.REL, // star equals '\u225C': MO.REL, // delta equal to '\u225D': MO.REL, // equal to by definition '\u225E': MO.REL, // measured by '\u225F': MO.REL, // questioned equal to '\u2260': MO.REL, // not equal to '\u2261': MO.REL, // identical to '\u2262': MO.REL, // not identical to '\u2263': MO.REL, // strictly equivalent to '\u2264': MO.REL, // less-than or equal to '\u2265': MO.REL, // greater-than or equal to '\u2266': MO.REL, // less-than over equal to '\u2266\u0338': MO.REL, // less-than over equal to with slash '\u2267': MO.REL, // greater-than over equal to '\u2268': MO.REL, // less-than but not equal to '\u2269': MO.REL, // greater-than but not equal to '\u226A': MO.REL, // much less-than '\u226A\u0338': MO.REL, // much less than with slash '\u226B': MO.REL, // much greater-than '\u226B\u0338': MO.REL, // much greater than with slash '\u226C': MO.REL, // between '\u226D': MO.REL, // not equivalent to '\u226E': MO.REL, // not less-than '\u226F': MO.REL, // not greater-than '\u2270': MO.REL, // neither less-than nor equal to '\u2271': MO.REL, // neither greater-than nor equal to '\u2272': MO.REL, // less-than or equivalent to '\u2273': MO.REL, // greater-than or equivalent to '\u2274': MO.REL, // neither less-than nor equivalent to '\u2275': MO.REL, // neither greater-than nor equivalent to '\u2276': MO.REL, // less-than or greater-than '\u2277': MO.REL, // greater-than or less-than '\u2278': MO.REL, // neither less-than nor greater-than '\u2279': MO.REL, // neither greater-than nor less-than '\u227A': MO.REL, // precedes '\u227B': MO.REL, // succeeds '\u227C': MO.REL, // precedes or equal to '\u227D': MO.REL, // succeeds or equal to '\u227E': MO.REL, // precedes or equivalent to '\u227F': MO.REL, // succeeds or equivalent to '\u227F\u0338': MO.REL, // succeeds or equivalent to with slash '\u2280': MO.REL, // does not precede '\u2281': MO.REL, // does not succeed '\u2282': MO.REL, // subset of '\u2282\u20D2': MO.REL, // subset of with vertical line '\u2283': MO.REL, // superset of '\u2283\u20D2': MO.REL, // superset of with vertical line '\u2284': MO.REL, // not a subset of '\u2285': MO.REL, // not a superset of '\u2286': MO.REL, // subset of or equal to '\u2287': MO.REL, // superset of or equal to '\u2288': MO.REL, // neither a subset of nor equal to '\u2289': MO.REL, // neither a superset of nor equal to '\u228A': MO.REL, // subset of with not equal to '\u228B': MO.REL, // superset of with not equal to '\u228C': MO.BIN4, // multiset '\u228D': MO.BIN4, // multiset multiplication '\u228E': MO.BIN4, // multiset union '\u228F': MO.REL, // square image of '\u228F\u0338': MO.REL, // square image of with slash '\u2290': MO.REL, // square original of '\u2290\u0338': MO.REL, // square original of with slash '\u2291': MO.REL, // square image of or equal to '\u2292': MO.REL, // square original of or equal to '\u2293': MO.BIN4, // square cap '\u2294': MO.BIN4, // square cup '\u2295': MO.BIN4, // circled plus '\u2296': MO.BIN4, // circled minus '\u2297': MO.BIN4, // circled times '\u2298': MO.BIN4, // circled division slash '\u2299': MO.BIN4, // circled dot operator '\u229A': MO.BIN4, // circled ring operator '\u229B': MO.BIN4, // circled asterisk operator '\u229C': MO.BIN4, // circled equals '\u229D': MO.BIN4, // circled dash '\u229E': MO.BIN4, // squared plus '\u229F': MO.BIN4, // squared minus '\u22A0': MO.BIN4, // squared times '\u22A1': MO.BIN4, // squared dot operator '\u22A2': MO.REL, // right tack '\u22A3': MO.REL, // left tack '\u22A4': MO.ORD55, // down tack '\u22A5': MO.REL, // up tack '\u22A6': MO.REL, // assertion '\u22A7': MO.REL, // models '\u22A8': MO.REL, // true '\u22A9': MO.REL, // forces '\u22AA': MO.REL, // triple vertical bar right turnstile '\u22AB': MO.REL, // double vertical bar double right turnstile '\u22AC': MO.REL, // does not prove '\u22AD': MO.REL, // not true '\u22AE': MO.REL, // does not force '\u22AF': MO.REL, // negated double vertical bar double right turnstile '\u22B0': MO.REL, // precedes under relation '\u22B1': MO.REL, // succeeds under relation '\u22B2': MO.REL, // normal subgroup of '\u22B3': MO.REL, // contains as normal subgroup '\u22B4': MO.REL, // normal subgroup of or equal to '\u22B5': MO.REL, // contains as normal subgroup or equal to '\u22B6': MO.REL, // original of '\u22B7': MO.REL, // image of '\u22B8': MO.REL, // multimap '\u22B9': MO.REL, // hermitian conjugate matrix '\u22BA': MO.BIN4, // intercalate '\u22BB': MO.BIN4, // xor '\u22BC': MO.BIN4, // nand '\u22BD': MO.BIN4, // nor '\u22BE': MO.BIN3, // right angle with arc '\u22BF': MO.BIN3, // right triangle '\u22C4': MO.BIN4, // diamond operator '\u22C5': MO.BIN4, // dot operator '\u22C6': MO.BIN4, // star operator '\u22C7': MO.BIN4, // division times '\u22C8': MO.REL, // bowtie '\u22C9': MO.BIN4, // left normal factor semidirect product '\u22CA': MO.BIN4, // right normal factor semidirect product '\u22CB': MO.BIN4, // left semidirect product '\u22CC': MO.BIN4, // right semidirect product '\u22CD': MO.REL, // reversed tilde equals '\u22CE': MO.BIN4, // curly logical or '\u22CF': MO.BIN4, // curly logical and '\u22D0': MO.REL, // double subset '\u22D1': MO.REL, // double superset '\u22D2': MO.BIN4, // double intersection '\u22D3': MO.BIN4, // double union '\u22D4': MO.REL, // pitchfork '\u22D5': MO.REL, // equal and parallel to '\u22D6': MO.REL, // less-than with dot '\u22D7': MO.REL, // greater-than with dot '\u22D8': MO.REL, // very much less-than '\u22D9': MO.REL, // very much greater-than '\u22DA': MO.REL, // less-than equal to or greater-than '\u22DB': MO.REL, // greater-than equal to or less-than '\u22DC': MO.REL, // equal to or less-than '\u22DD': MO.REL, // equal to or greater-than '\u22DE': MO.REL, // equal to or precedes '\u22DF': MO.REL, // equal to or succeeds '\u22E0': MO.REL, // does not precede or equal '\u22E1': MO.REL, // does not succeed or equal '\u22E2': MO.REL, // not square image of or equal to '\u22E3': MO.REL, // not square original of or equal to '\u22E4': MO.REL, // square image of or not equal to '\u22E5': MO.REL, // square original of or not equal to '\u22E6': MO.REL, // less-than but not equivalent to '\u22E7': MO.REL, // greater-than but not equivalent to '\u22E8': MO.REL, // precedes but not equivalent to '\u22E9': MO.REL, // succeeds but not equivalent to '\u22EA': MO.REL, // not normal subgroup of '\u22EB': MO.REL, // does not contain as normal subgroup '\u22EC': MO.REL, // not normal subgroup of or equal to '\u22ED': MO.REL, // does not contain as normal subgroup or equal '\u22EE': MO.ORD55, // vertical ellipsis '\u22EF': MO.INNER, // midline horizontal ellipsis '\u22F0': MO.REL, // up right diagonal ellipsis '\u22F1': [5, 5, TEXCLASS.INNER, null], // down right diagonal ellipsis '\u22F2': MO.REL, // element of with long horizontal stroke '\u22F3': MO.REL, // element of with vertical bar at end of horizontal stroke '\u22F4': MO.REL, // small element of with vertical bar at end of horizontal stroke '\u22F5': MO.REL, // element of with dot above '\u22F6': MO.REL, // element of with overbar '\u22F7': MO.REL, // small element of with overbar '\u22F8': MO.REL, // element of with underbar '\u22F9': MO.REL, // element of with two horizontal strokes '\u22FA': MO.REL, // contains with long horizontal stroke '\u22FB': MO.REL, // contains with vertical bar at end of horizontal stroke '\u22FC': MO.REL, // small contains with vertical bar at end of horizontal stroke '\u22FD': MO.REL, // contains with overbar '\u22FE': MO.REL, // small contains with overbar '\u22FF': MO.REL, // z notation bag membership '\u2305': MO.BIN3, // barwedge '\u2306': MO.BIN3, // doublebarwedge '\u2322': MO.REL4, // \frown '\u2323': MO.REL4, // \smile '\u2329': MO.OPEN, // langle '\u232A': MO.CLOSE, // rangle '\u23AA': MO.ORD, // \bracevert '\u23AF': [0, 0, TEXCLASS.ORD, {stretchy: true}], // \underline '\u23B0': MO.OPEN, // \lmoustache '\u23B1': MO.CLOSE, // \rmoustache '\u2500': MO.ORD, // horizontal line '\u25B3': MO.BIN4, // white up-pointing triangle '\u25B5': MO.BIN4, // white up-pointing small triangle '\u25B9': MO.BIN4, // white right-pointing small triangle '\u25BD': MO.BIN4, // white down-pointing triangle '\u25BF': MO.BIN4, // white down-pointing small triangle '\u25C3': MO.BIN4, // white left-pointing small triangle '\u25EF': MO.BIN3, // \bigcirc '\u2660': MO.ORD, // \spadesuit '\u2661': MO.ORD, // \heartsuit '\u2662': MO.ORD, // \diamondsuit '\u2663': MO.ORD, // \clubsuit '\u2758': MO.REL, // light vertical bar '\u27F0': MO.RELSTRETCH, // upwards quadruple arrow '\u27F1': MO.RELSTRETCH, // downwards quadruple arrow '\u27F5': MO.WIDEREL, // long leftwards arrow '\u27F6': MO.WIDEREL, // long rightwards arrow '\u27F7': MO.WIDEREL, // long left right arrow '\u27F8': MO.WIDEREL, // long leftwards double arrow '\u27F9': MO.WIDEREL, // long rightwards double arrow '\u27FA': MO.WIDEREL, // long left right double arrow '\u27FB': MO.WIDEREL, // long leftwards arrow from bar '\u27FC': MO.WIDEREL, // long rightwards arrow from bar '\u27FD': MO.WIDEREL, // long leftwards double arrow from bar '\u27FE': MO.WIDEREL, // long rightwards double arrow from bar '\u27FF': MO.WIDEREL, // long rightwards squiggle arrow '\u2900': MO.RELACCENT, // rightwards two-headed arrow with vertical stroke '\u2901': MO.RELACCENT, // rightwards two-headed arrow with double vertical stroke '\u2902': MO.RELACCENT, // leftwards double arrow with vertical stroke '\u2903': MO.RELACCENT, // rightwards double arrow with vertical stroke '\u2904': MO.RELACCENT, // left right double arrow with vertical stroke '\u2905': MO.RELACCENT, // rightwards two-headed arrow from bar '\u2906': MO.RELACCENT, // leftwards double arrow from bar '\u2907': MO.RELACCENT, // rightwards double arrow from bar '\u2908': MO.REL, // downwards arrow with horizontal stroke '\u2909': MO.REL, // upwards arrow with horizontal stroke '\u290A': MO.RELSTRETCH, // upwards triple arrow '\u290B': MO.RELSTRETCH, // downwards triple arrow '\u290C': MO.WIDEREL, // leftwards double dash arrow '\u290D': MO.WIDEREL, // rightwards double dash arrow '\u290E': MO.WIDEREL, // leftwards triple dash arrow '\u290F': MO.WIDEREL, // rightwards triple dash arrow '\u2910': MO.WIDEREL, // rightwards two-headed triple dash arrow '\u2911': MO.RELACCENT, // rightwards arrow with dotted stem '\u2912': MO.RELSTRETCH, // upwards arrow to bar '\u2913': MO.RELSTRETCH, // downwards arrow to bar '\u2914': MO.RELACCENT, // rightwards arrow with tail with vertical stroke '\u2915': MO.RELACCENT, // rightwards arrow with tail with double vertical stroke '\u2916': MO.RELACCENT, // rightwards two-headed arrow with tail '\u2917': MO.RELACCENT, // rightwards two-headed arrow with tail with vertical stroke '\u2918': MO.RELACCENT, // rightwards two-headed arrow with tail with double vertical stroke '\u2919': MO.RELACCENT, // leftwards arrow-tail '\u291A': MO.RELACCENT, // rightwards arrow-tail '\u291B': MO.RELACCENT, // leftwards double arrow-tail '\u291C': MO.RELACCENT, // rightwards double arrow-tail '\u291D': MO.RELACCENT, // leftwards arrow to black diamond '\u291E': MO.RELACCENT, // rightwards arrow to black diamond '\u291F': MO.RELACCENT, // leftwards arrow from bar to black diamond '\u2920': MO.RELACCENT, // rightwards arrow from bar to black diamond '\u2921': MO.RELSTRETCH, // north west and south east arrow '\u2922': MO.RELSTRETCH, // north east and south west arrow '\u2923': MO.REL, // north west arrow with hook '\u2924': MO.REL, // north east arrow with hook '\u2925': MO.REL, // south east arrow with hook '\u2926': MO.REL, // south west arrow with hook '\u2927': MO.REL, // north west arrow and north east arrow '\u2928': MO.REL, // north east arrow and south east arrow '\u2929': MO.REL, // south east arrow and south west arrow '\u292A': MO.REL, // south west arrow and north west arrow '\u292B': MO.REL, // rising diagonal crossing falling diagonal '\u292C': MO.REL, // falling diagonal crossing rising diagonal '\u292D': MO.REL, // south east arrow crossing north east arrow '\u292E': MO.REL, // north east arrow crossing south east arrow '\u292F': MO.REL, // falling diagonal crossing north east arrow '\u2930': MO.REL, // rising diagonal crossing south east arrow '\u2931': MO.REL, // north east arrow crossing north west arrow '\u2932': MO.REL, // north west arrow crossing north east arrow '\u2933': MO.RELACCENT, // wave arrow pointing directly right '\u2934': MO.REL, // arrow pointing rightwards then curving upwards '\u2935': MO.REL, // arrow pointing rightwards then curving downwards '\u2936': MO.REL, // arrow pointing downwards then curving leftwards '\u2937': MO.REL, // arrow pointing downwards then curving rightwards '\u2938': MO.REL, // right-side arc clockwise arrow '\u2939': MO.REL, // left-side arc anticlockwise arrow '\u293A': MO.RELACCENT, // top arc anticlockwise arrow '\u293B': MO.RELACCENT, // bottom arc anticlockwise arrow '\u293C': MO.RELACCENT, // top arc clockwise arrow with minus '\u293D': MO.RELACCENT, // top arc anticlockwise arrow with plus '\u293E': MO.REL, // lower right semicircular clockwise arrow '\u293F': MO.REL, // lower left semicircular anticlockwise arrow '\u2940': MO.REL, // anticlockwise closed circle arrow '\u2941': MO.REL, // clockwise closed circle arrow '\u2942': MO.RELACCENT, // rightwards arrow above short leftwards arrow '\u2943': MO.RELACCENT, // leftwards arrow above short rightwards arrow '\u2944': MO.RELACCENT, // short rightwards arrow above leftwards arrow '\u2945': MO.RELACCENT, // rightwards arrow with plus below '\u2946': MO.RELACCENT, // leftwards arrow with plus below '\u2947': MO.RELACCENT, // rightwards arrow through x '\u2948': MO.RELACCENT, // left right arrow through small circle '\u2949': MO.REL, // upwards two-headed arrow from small circle '\u294A': MO.RELACCENT, // left barb up right barb down harpoon '\u294B': MO.RELACCENT, // left barb down right barb up harpoon '\u294C': MO.REL, // up barb right down barb left harpoon '\u294D': MO.REL, // up barb left down barb right harpoon '\u294E': MO.WIDEREL, // left barb up right barb up harpoon '\u294F': MO.RELSTRETCH, // up barb right down barb right harpoon '\u2950': MO.WIDEREL, // left barb down right barb down harpoon '\u2951': MO.RELSTRETCH, // up barb left down barb left harpoon '\u2952': MO.WIDEREL, // leftwards harpoon with barb up to bar '\u2953': MO.WIDEREL, // rightwards harpoon with barb up to bar '\u2954': MO.RELSTRETCH, // upwards harpoon with barb right to bar '\u2955': MO.RELSTRETCH, // downwards harpoon with barb right to bar '\u2956': MO.RELSTRETCH, // leftwards harpoon with barb down to bar '\u2957': MO.RELSTRETCH, // rightwards harpoon with barb down to bar '\u2958': MO.RELSTRETCH, // upwards harpoon with barb left to bar '\u2959': MO.RELSTRETCH, // downwards harpoon with barb left to bar '\u295A': MO.WIDEREL, // leftwards harpoon with barb up from bar '\u295B': MO.WIDEREL, // rightwards harpoon with barb up from bar '\u295C': MO.RELSTRETCH, // upwards harpoon with barb right from bar '\u295D': MO.RELSTRETCH, // downwards harpoon with barb right from bar '\u295E': MO.WIDEREL, // leftwards harpoon with barb down from bar '\u295F': MO.WIDEREL, // rightwards harpoon with barb down from bar '\u2960': MO.RELSTRETCH, // upwards harpoon with barb left from bar '\u2961': MO.RELSTRETCH, // downwards harpoon with barb left from bar '\u2962': MO.RELACCENT, // leftwards harpoon with barb up above leftwards harpoon with barb down '\u2963': MO.REL, // upwards harpoon with barb left beside upwards harpoon with barb right '\u2964': MO.RELACCENT, // rightwards harpoon with barb up above rightwards harpoon with barb down '\u2965': MO.REL, // downwards harpoon with barb left beside downwards harpoon with barb right '\u2966': MO.RELACCENT, // leftwards harpoon with barb up above rightwards harpoon with barb up '\u2967': MO.RELACCENT, // leftwards harpoon with barb down above rightwards harpoon with barb down '\u2968': MO.RELACCENT, // rightwards harpoon with barb up above leftwards harpoon with barb up '\u2969': MO.RELACCENT, // rightwards harpoon with barb down above leftwards harpoon with barb down '\u296A': MO.RELACCENT, // leftwards harpoon with barb up above long dash '\u296B': MO.RELACCENT, // leftwards harpoon with barb down below long dash '\u296C': MO.RELACCENT, // rightwards harpoon with barb up above long dash '\u296D': MO.RELACCENT, // rightwards harpoon with barb down below long dash '\u296E': MO.RELSTRETCH, // upwards harpoon with barb left beside downwards harpoon with barb right '\u296F': MO.RELSTRETCH, // downwards harpoon with barb left beside upwards harpoon with barb right '\u2970': MO.RELACCENT, // right double arrow with rounded head '\u2971': MO.RELACCENT, // equals sign above rightwards arrow '\u2972': MO.RELACCENT, // tilde operator above rightwards arrow '\u2973': MO.RELACCENT, // leftwards arrow above tilde operator '\u2974': MO.RELACCENT, // rightwards arrow above tilde operator '\u2975': MO.RELACCENT, // rightwards arrow above almost equal to '\u2976': MO.RELACCENT, // less-than above leftwards arrow '\u2977': MO.RELACCENT, // leftwards arrow through less-than '\u2978': MO.RELACCENT, // greater-than above rightwards arrow '\u2979': MO.RELACCENT, // subset above rightwards arrow '\u297A': MO.RELACCENT, // leftwards arrow through subset '\u297B': MO.RELACCENT, // superset above leftwards arrow '\u297C': MO.RELACCENT, // left fish tail '\u297D': MO.RELACCENT, // right fish tail '\u297E': MO.REL, // up fish tail '\u297F': MO.REL, // down fish tail '\u2981': MO.BIN3, // z notation spot '\u2982': MO.BIN3, // z notation type colon '\u2999': MO.BIN3, // dotted fence '\u299A': MO.BIN3, // vertical zigzag line '\u299B': MO.BIN3, // measured angle opening left '\u299C': MO.BIN3, // right angle variant with square '\u299D': MO.BIN3, // measured right angle with dot '\u299E': MO.BIN3, // angle with s inside '\u299F': MO.BIN3, // acute angle '\u29A0': MO.BIN3, // spherical angle opening left '\u29A1': MO.BIN3, // spherical angle opening up '\u29A2': MO.BIN3, // turned angle '\u29A3': MO.BIN3, // reversed angle '\u29A4': MO.BIN3, // angle with underbar '\u29A5': MO.BIN3, // reversed angle with underbar '\u29A6': MO.BIN3, // oblique angle opening up '\u29A7': MO.BIN3, // oblique angle opening down '\u29A8': MO.BIN3, // measured angle with open arm ending in arrow pointing up and right '\u29A9': MO.BIN3, // measured angle with open arm ending in arrow pointing up and left '\u29AA': MO.BIN3, // measured angle with open arm ending in arrow pointing down and right '\u29AB': MO.BIN3, // measured angle with open arm ending in arrow pointing down and left '\u29AC': MO.BIN3, // measured angle with open arm ending in arrow pointing right and up '\u29AD': MO.BIN3, // measured angle with open arm ending in arrow pointing left and up '\u29AE': MO.BIN3, // measured angle with open arm ending in arrow pointing right and down '\u29AF': MO.BIN3, // measured angle with open arm ending in arrow pointing left and down '\u29B0': MO.BIN3, // reversed empty set '\u29B1': MO.BIN3, // empty set with overbar '\u29B2': MO.BIN3, // empty set with small circle above '\u29B3': MO.BIN3, // empty set with right arrow above '\u29B4': MO.BIN3, // empty set with left arrow above '\u29B5': MO.BIN3, // circle with horizontal bar '\u29B6': MO.BIN4, // circled vertical bar '\u29B7': MO.BIN4, // circled parallel '\u29B8': MO.BIN4, // circled reverse solidus '\u29B9': MO.BIN4, // circled perpendicular '\u29BA': MO.BIN4, // circle divided by horizontal bar and top half divided by vertical bar '\u29BB': MO.BIN4, // circle with superimposed x '\u29BC': MO.BIN4, // circled anticlockwise-rotated division sign '\u29BD': MO.BIN4, // up arrow through circle '\u29BE': MO.BIN4, // circled white bullet '\u29BF': MO.BIN4, // circled bullet '\u29C0': MO.REL, // circled less-than '\u29C1': MO.REL, // circled greater-than '\u29C2': MO.BIN3, // circle with small circle to the right '\u29C3': MO.BIN3, // circle with two horizontal strokes to the right '\u29C4': MO.BIN4, // squared rising diagonal slash '\u29C5': MO.BIN4, // squared falling diagonal slash '\u29C6': MO.BIN4, // squared asterisk '\u29C7': MO.BIN4, // squared small circle '\u29C8': MO.BIN4, // squared square '\u29C9': MO.BIN3, // two joined squares '\u29CA': MO.BIN3, // triangle with dot above '\u29CB': MO.BIN3, // triangle with underbar '\u29CC': MO.BIN3, // s in triangle '\u29CD': MO.BIN3, // triangle with serifs at bottom '\u29CE': MO.REL, // right triangle above left triangle '\u29CF': MO.REL, // left triangle beside vertical bar '\u29CF\u0338': MO.REL, // left triangle beside vertical bar with slash '\u29D0': MO.REL, // vertical bar beside right triangle '\u29D0\u0338': MO.REL, // vertical bar beside right triangle with slash '\u29D1': MO.REL, // bowtie with left half black '\u29D2': MO.REL, // bowtie with right half black '\u29D3': MO.REL, // black bowtie '\u29D4': MO.REL, // times with left half black '\u29D5': MO.REL, // times with right half black '\u29D6': MO.BIN4, // white hourglass '\u29D7': MO.BIN4, // black hourglass '\u29D8': MO.BIN3, // left wiggly fence '\u29D9': MO.BIN3, // right wiggly fence '\u29DB': MO.BIN3, // right double wiggly fence '\u29DC': MO.BIN3, // incomplete infinity '\u29DD': MO.BIN3, // tie over infinity '\u29DE': MO.REL, // infinity negated with vertical bar '\u29DF': MO.BIN3, // double-ended multimap '\u29E0': MO.BIN3, // square with contoured outline '\u29E1': MO.REL, // increases as '\u29E2': MO.BIN4, // shuffle product '\u29E3': MO.REL, // equals sign and slanted parallel '\u29E4': MO.REL, // equals sign and slanted parallel with tilde above '\u29E5': MO.REL, // identical to and slanted parallel '\u29E6': MO.REL, // gleich stark '\u29E7': MO.BIN3, // thermodynamic '\u29E8': MO.BIN3, // down-pointing triangle with left half black '\u29E9': MO.BIN3, // down-pointing triangle with right half black '\u29EA': MO.BIN3, // black diamond with down arrow '\u29EB': MO.BIN3, // black lozenge '\u29EC': MO.BIN3, // white circle with down arrow '\u29ED': MO.BIN3, // black circle with down arrow '\u29EE': MO.BIN3, // error-barred white square '\u29EF': MO.BIN3, // error-barred black square '\u29F0': MO.BIN3, // error-barred white diamond '\u29F1': MO.BIN3, // error-barred black diamond '\u29F2': MO.BIN3, // error-barred white circle '\u29F3': MO.BIN3, // error-barred black circle '\u29F4': MO.REL, // rule-delayed '\u29F5': MO.BIN4, // reverse solidus operator '\u29F6': MO.BIN4, // solidus with overbar '\u29F7': MO.BIN4, // reverse solidus with horizontal stroke '\u29F8': MO.BIN3, // big solidus '\u29F9': MO.BIN3, // big reverse solidus '\u29FA': MO.BIN3, // double plus '\u29FB': MO.BIN3, // triple plus '\u29FE': MO.BIN4, // tiny '\u29FF': MO.BIN4, // miny '\u2A1D': MO.BIN3, // join '\u2A1E': MO.BIN3, // large left triangle operator '\u2A1F': MO.BIN3, // z notation schema composition '\u2A20': MO.BIN3, // z notation schema piping '\u2A21': MO.BIN3, // z notation schema projection '\u2A22': MO.BIN4, // plus sign with small circle above '\u2A23': MO.BIN4, // plus sign with circumflex accent above '\u2A24': MO.BIN4, // plus sign with tilde above '\u2A25': MO.BIN4, // plus sign with dot below '\u2A26': MO.BIN4, // plus sign with tilde below '\u2A27': MO.BIN4, // plus sign with subscript two '\u2A28': MO.BIN4, // plus sign with black triangle '\u2A29': MO.BIN4, // minus sign with comma above '\u2A2A': MO.BIN4, // minus sign with dot below '\u2A2B': MO.BIN4, // minus sign with falling dots '\u2A2C': MO.BIN4, // minus sign with rising dots '\u2A2D': MO.BIN4, // plus sign in left half circle '\u2A2E': MO.BIN4, // plus sign in right half circle '\u2A2F': MO.BIN4, // vector or cross product '\u2A30': MO.BIN4, // multiplication sign with dot above '\u2A31': MO.BIN4, // multiplication sign with underbar '\u2A32': MO.BIN4, // semidirect product with bottom closed '\u2A33': MO.BIN4, // smash product '\u2A34': MO.BIN4, // multiplication sign in left half circle '\u2A35': MO.BIN4, // multiplication sign in right half circle '\u2A36': MO.BIN4, // circled multiplication sign with circumflex accent '\u2A37': MO.BIN4, // multiplication sign in double circle '\u2A38': MO.BIN4, // circled division sign '\u2A39': MO.BIN4, // plus sign in triangle '\u2A3A': MO.BIN4, // minus sign in triangle '\u2A3B': MO.BIN4, // multiplication sign in triangle '\u2A3C': MO.BIN4, // interior product '\u2A3D': MO.BIN4, // righthand interior product '\u2A3E': MO.BIN4, // z notation relational composition '\u2A3F': MO.BIN4, // amalgamation or coproduct '\u2A40': MO.BIN4, // intersection with dot '\u2A41': MO.BIN4, // union with minus sign '\u2A42': MO.BIN4, // union with overbar '\u2A43': MO.BIN4, // intersection with overbar '\u2A44': MO.BIN4, // intersection with logical and '\u2A45': MO.BIN4, // union with logical or '\u2A46': MO.BIN4, // union above intersection '\u2A47': MO.BIN4, // intersection above union '\u2A48': MO.BIN4, // union above bar above intersection '\u2A49': MO.BIN4, // intersection above bar above union '\u2A4A': MO.BIN4, // union beside and joined with union '\u2A4B': MO.BIN4, // intersection beside and joined with intersection '\u2A4C': MO.BIN4, // closed union with serifs '\u2A4D': MO.BIN4, // closed intersection with serifs '\u2A4E': MO.BIN4, // double square intersection '\u2A4F': MO.BIN4, // double square union '\u2A50': MO.BIN4, // closed union with serifs and smash product '\u2A51': MO.BIN4, // logical and with dot above '\u2A52': MO.BIN4, // logical or with dot above '\u2A53': MO.BIN4, // double logical and '\u2A54': MO.BIN4, // double logical or '\u2A55': MO.BIN4, // two intersecting logical and '\u2A56': MO.BIN4, // two intersecting logical or '\u2A57': MO.BIN4, // sloping large or '\u2A58': MO.BIN4, // sloping large and '\u2A59': MO.REL, // logical or overlapping logical and '\u2A5A': MO.BIN4, // logical and with middle stem '\u2A5B': MO.BIN4, // logical or with middle stem '\u2A5C': MO.BIN4, // logical and with horizontal dash '\u2A5D': MO.BIN4, // logical or with horizontal dash '\u2A5E': MO.BIN4, // logical and with double overbar '\u2A5F': MO.BIN4, // logical and with underbar '\u2A60': MO.BIN4, // logical and with double underbar '\u2A61': MO.BIN4, // small vee with underbar '\u2A62': MO.BIN4, // logical or with double overbar '\u2A63': MO.BIN4, // logical or with double underbar '\u2A64': MO.BIN4, // z notation domain antirestriction '\u2A65': MO.BIN4, // z notation range antirestriction '\u2A66': MO.REL, // equals sign with dot below '\u2A67': MO.REL, // identical with dot above '\u2A68': MO.REL, // triple horizontal bar with double vertical stroke '\u2A69': MO.REL, // triple horizontal bar with triple vertical stroke '\u2A6A': MO.REL, // tilde operator with dot above '\u2A6B': MO.REL, // tilde operator with rising dots '\u2A6C': MO.REL, // similar minus similar '\u2A6D': MO.REL, // congruent with dot above '\u2A6E': MO.REL, // equals with asterisk '\u2A6F': MO.REL, // almost equal to with circumflex accent '\u2A70': MO.REL, // approximately equal or equal to '\u2A71': MO.BIN4, // equals sign above plus sign '\u2A72': MO.BIN4, // plus sign above equals sign '\u2A73': MO.REL, // equals sign above tilde operator '\u2A74': MO.REL, // double colon equal '\u2A75': MO.REL, // two consecutive equals signs '\u2A76': MO.REL, // three consecutive equals signs '\u2A77': MO.REL, // equals sign with two dots above and two dots below '\u2A78': MO.REL, // equivalent with four dots above '\u2A79': MO.REL, // less-than with circle inside '\u2A7A': MO.REL, // greater-than with circle inside '\u2A7B': MO.REL, // less-than with question mark above '\u2A7C': MO.REL, // greater-than with question mark above '\u2A7D': MO.REL, // less-than or slanted equal to '\u2A7D\u0338': MO.REL, // less-than or slanted equal to with slash '\u2A7E': MO.REL, // greater-than or slanted equal to '\u2A7E\u0338': MO.REL, // greater-than or slanted equal to with slash '\u2A7F': MO.REL, // less-than or slanted equal to with dot inside '\u2A80': MO.REL, // greater-than or slanted equal to with dot inside '\u2A81': MO.REL, // less-than or slanted equal to with dot above '\u2A82': MO.REL, // greater-than or slanted equal to with dot above '\u2A83': MO.REL, // less-than or slanted equal to with dot above right '\u2A84': MO.REL, // greater-than or slanted equal to with dot above left '\u2A85': MO.REL, // less-than or approximate '\u2A86': MO.REL, // greater-than or approximate '\u2A87': MO.REL, // less-than and single-line not equal to '\u2A88': MO.REL, // greater-than and single-line not equal to '\u2A89': MO.REL, // less-than and not approximate '\u2A8A': MO.REL, // greater-than and not approximate '\u2A8B': MO.REL, // less-than above double-line equal above greater-than '\u2A8C': MO.REL, // greater-than above double-line equal above less-than '\u2A8D': MO.REL, // less-than above similar or equal '\u2A8E': MO.REL, // greater-than above similar or equal '\u2A8F': MO.REL, // less-than above similar above greater-than '\u2A90': MO.REL, // greater-than above similar above less-than '\u2A91': MO.REL, // less-than above greater-than above double-line equal '\u2A92': MO.REL, // greater-than above less-than above double-line equal '\u2A93': MO.REL, // less-than above slanted equal above greater-than above slanted equal '\u2A94': MO.REL, // greater-than above slanted equal above less-than above slanted equal '\u2A95': MO.REL, // slanted equal to or less-than '\u2A96': MO.REL, // slanted equal to or greater-than '\u2A97': MO.REL, // slanted equal to or less-than with dot inside '\u2A98': MO.REL, // slanted equal to or greater-than with dot inside '\u2A99': MO.REL, // double-line equal to or less-than '\u2A9A': MO.REL, // double-line equal to or greater-than '\u2A9B': MO.REL, // double-line slanted equal to or less-than '\u2A9C': MO.REL, // double-line slanted equal to or greater-than '\u2A9D': MO.REL, // similar or less-than '\u2A9E': MO.REL, // similar or greater-than '\u2A9F': MO.REL, // similar above less-than above equals sign '\u2AA0': MO.REL, // similar above greater-than above equals sign '\u2AA1': MO.REL, // double nested less-than '\u2AA1\u0338': MO.REL, // double nested less-than with slash '\u2AA2': MO.REL, // double nested greater-than '\u2AA2\u0338': MO.REL, // double nested greater-than with slash '\u2AA3': MO.REL, // double nested less-than with underbar '\u2AA4': MO.REL, // greater-than overlapping less-than '\u2AA5': MO.REL, // greater-than beside less-than '\u2AA6': MO.REL, // less-than closed by curve '\u2AA7': MO.REL, // greater-than closed by curve '\u2AA8': MO.REL, // less-than closed by curve above slanted equal '\u2AA9': MO.REL, // greater-than closed by curve above slanted equal '\u2AAA': MO.REL, // smaller than '\u2AAB': MO.REL, // larger than '\u2AAC': MO.REL, // smaller than or equal to '\u2AAD': MO.REL, // larger than or equal to '\u2AAE': MO.REL, // equals sign with bumpy above '\u2AAF': MO.REL, // precedes above single-line equals sign '\u2AAF\u0338': MO.REL, // precedes above single-line equals sign with slash '\u2AB0': MO.REL, // succeeds above single-line equals sign '\u2AB0\u0338': MO.REL, // succeeds above single-line equals sign with slash '\u2AB1': MO.REL, // precedes above single-line not equal to '\u2AB2': MO.REL, // succeeds above single-line not equal to '\u2AB3': MO.REL, // precedes above equals sign '\u2AB4': MO.REL, // succeeds above equals sign '\u2AB5': MO.REL, // precedes above not equal to '\u2AB6': MO.REL, // succeeds above not equal to '\u2AB7': MO.REL, // precedes above almost equal to '\u2AB8': MO.REL, // succeeds above almost equal to '\u2AB9': MO.REL, // precedes above not almost equal to '\u2ABA': MO.REL, // succeeds above not almost equal to '\u2ABB': MO.REL, // double precedes '\u2ABC': MO.REL, // double succeeds '\u2ABD': MO.REL, // subset with dot '\u2ABE': MO.REL, // superset with dot '\u2ABF': MO.REL, // subset with plus sign below '\u2AC0': MO.REL, // superset with plus sign below '\u2AC1': MO.REL, // subset with multiplication sign below '\u2AC2': MO.REL, // superset with multiplication sign below '\u2AC3': MO.REL, // subset of or equal to with dot above '\u2AC4': MO.REL, // superset of or equal to with dot above '\u2AC5': MO.REL, // subset of above equals sign '\u2AC6': MO.REL, // superset of above equals sign '\u2AC7': MO.REL, // subset of above tilde operator '\u2AC8': MO.REL, // superset of above tilde operator '\u2AC9': MO.REL, // subset of above almost equal to '\u2ACA': MO.REL, // superset of above almost equal to '\u2ACB': MO.REL, // subset of above not equal to '\u2ACC': MO.REL, // superset of above not equal to '\u2ACD': MO.REL, // square left open box operator '\u2ACE': MO.REL, // square right open box operator '\u2ACF': MO.REL, // closed subset '\u2AD0': MO.REL, // closed superset '\u2AD1': MO.REL, // closed subset or equal to '\u2AD2': MO.REL, // closed superset or equal to '\u2AD3': MO.REL, // subset above superset '\u2AD4': MO.REL, // superset above subset '\u2AD5': MO.REL, // subset above subset '\u2AD6': MO.REL, // superset above superset '\u2AD7': MO.REL, // superset beside subset '\u2AD8': MO.REL, // superset beside and joined by dash with subset '\u2AD9': MO.REL, // element of opening downwards '\u2ADA': MO.REL, // pitchfork with tee top '\u2ADB': MO.REL, // transversal intersection '\u2ADD': MO.REL, // nonforking '\u2ADD\u0338': MO.REL, // nonforking with slash '\u2ADE': MO.REL, // short left tack '\u2ADF': MO.REL, // short down tack '\u2AE0': MO.REL, // short up tack '\u2AE1': MO.REL, // perpendicular with s '\u2AE2': MO.REL, // vertical bar triple right turnstile '\u2AE3': MO.REL, // double vertical bar left turnstile '\u2AE4': MO.REL, // vertical bar double left turnstile '\u2AE5': MO.REL, // double vertical bar double left turnstile '\u2AE6': MO.REL, // long dash from left member of double vertical '\u2AE7': MO.REL, // short down tack with overbar '\u2AE8': MO.REL, // short up tack with underbar '\u2AE9': MO.REL, // short up tack above short down tack '\u2AEA': MO.REL, // double down tack '\u2AEB': MO.REL, // double up tack '\u2AEC': MO.REL, // double stroke not sign '\u2AED': MO.REL, // reversed double stroke not sign '\u2AEE': MO.REL, // does not divide with reversed negation slash '\u2AEF': MO.REL, // vertical line with circle above '\u2AF0': MO.REL, // vertical line with circle below '\u2AF1': MO.REL, // down tack with circle below '\u2AF2': MO.REL, // parallel with horizontal stroke '\u2AF3': MO.REL, // parallel with tilde operator '\u2AF4': MO.BIN4, // triple vertical bar binary relation '\u2AF5': MO.BIN4, // triple vertical bar with horizontal stroke '\u2AF6': MO.BIN4, // triple colon operator '\u2AF7': MO.REL, // triple nested less-than '\u2AF8': MO.REL, // triple nested greater-than '\u2AF9': MO.REL, // double-line slanted less-than or equal to '\u2AFA': MO.REL, // double-line slanted greater-than or equal to '\u2AFB': MO.BIN4, // triple solidus binary relation '\u2AFD': MO.BIN4, // double solidus operator '\u2AFE': MO.BIN3, // white vertical bar '\u2B45': MO.RELSTRETCH, // leftwards quadruple arrow '\u2B46': MO.RELSTRETCH, // rightwards quadruple arrow '\u3008': MO.OPEN, // langle '\u3009': MO.CLOSE, // rangle '\uFE37': MO.WIDEACCENT, // horizontal brace down '\uFE38': MO.WIDEACCENT, // horizontal brace up } }; // // These are not in the W3C table, but we need them for \widehat and \underline // OPTABLE.infix['^'] = MO.WIDEREL; OPTABLE.infix['_'] = MO.WIDEREL; // // Remove from Appendix C, but perhaps that was a mistake? // OPTABLE.infix['\u2ADC'] = MO.REL;
f4cb4aee80b76d511344de4587a8d484b07f502b
TypeScript
laaksomavrick/notes-api-v2
/src/folders/UpdateFolderHandler.ts
2.65625
3
import { NextFunction, Request, Response } from "express"; import { Handler } from "../framework/Handler"; import { BadRequestError, NotFoundError, UnprocessableEntityError } from "../framework/HttpError"; import { FolderRepository } from "./FolderRepository"; import { UpdateFolderDto } from "./UpdateFolderDto"; export class UpdateFolderHandler extends Handler { private readonly folderRepository: FolderRepository; protected readonly handlers = [this.requireAuth(), this.handle.bind(this)]; constructor(folderRepository: FolderRepository) { super(); this.folderRepository = folderRepository; } protected async handle(req: Request, res: Response, next: NextFunction): Promise<void> { const context = this.getContext(req); // Get the folderId from the route const userId = this.getUserId(req); const folderId = this.getParamId(req, "folderId"); if (!folderId) { throw new BadRequestError(); } // Verify the folder exists and belongs to the user const folderExists = await this.folderRepository.findByIdAndUserId( context, folderId, userId, ["id"], ); if (!folderExists) { throw new NotFoundError(); } // Parse dto const dto = UpdateFolderDto.build(req); if (!dto) { throw new BadRequestError(); } // Make sure dto is valid const valid = dto.isValid(); if (!valid) { throw new UnprocessableEntityError(); } // Update the folder const folder = await this.folderRepository.update(context, dto, folderId); this.httpOk(res, { folder }); } }
8c9d82aaf8c131b7dc7eb15a6bff5fc2fa0dfa0c
TypeScript
bodinaren/sudoku-solver
/tests/brokenSubsets.spec.ts
2.71875
3
/// <reference path="../typings/main.d.ts" /> import {Sudoku, Tile} from "sudoku"; import {SolverSudoku} from "../src/solverSudoku"; import {BrokenSubsets} from "../src/solutions"; import {List} from "btypescript"; import {expect} from 'chai'; let _ = 0; describe("BrokenSubsets", function() { describe("Triple", function () { it("- found", function () { // http://hodoku.sourceforge.net/en/show_example.php?file=n301&tech=Naked+Triple let tiles = [ _, _, _, 2, 9, 4, 3, 8, _, _, _, _, 1, 7, 8, 6, 4, _, 4, 8, _, 3, 5, 6, 1, _, _, _, _, 4, 8, 3, 7, 5, _, 1, _, _, _, 4, 1, 5, 7, _, _, 5, _, _, 6, 2, 9, 8, 3, 4, 9, 5, 3, 7, 8, 2, 4, 1, 6, 1, 2, 6, 5, 4, 3, 9, 7, 8, _, 4, _, 9, 6, 1, 2, 5, 3 ]; let brokenSubsets = new BrokenSubsets(3); let sudoku = new SolverSudoku().setupNormalSudoku(tiles); brokenSubsets.toggleAllNotes(sudoku.tiles); sudoku.updateInvalidNotes(); let result = brokenSubsets.findClue(sudoku); expect(result).to.eql(true); expect(brokenSubsets.getNotes(sudoku.tiles[1])).to.eql([1, 7]); }); }); describe("Quadruple", function () { it("- found 1", function () { // http://hodoku.sourceforge.net/en/show_example.php?file=n401&tech=Naked+Quadruple let tiles = [ _, 1, _, 7, 2, _, 5, 6, 3, _, 5, 6, _, 3, _, 2, 4, 7, 7, 3, 2, 5, 4, 6, 1, 8, 9, 6, 9, 3, 2, 8, 7, 4, 1, 5, 2, 4, 7, 6, 1, 5, 9, 3, 8, 5, 8, 1, 3, 9, 4, _, _, _, _, _, _, _, _, 2, _, _, _, _, _, _, _, _, _, _, _, 1, _, _, 5, 8, 7, _, _, _, _ ]; let brokenSubsets = new BrokenSubsets(4); let sudoku = new SolverSudoku().setupNormalSudoku(tiles); brokenSubsets.toggleAllNotes(sudoku.tiles); sudoku.updateInvalidNotes(); expect(brokenSubsets.findClue(sudoku)).to.eql(true); expect(brokenSubsets.getNotes(sudoku.tiles[69])).to.eql([6, 7]); expect(brokenSubsets.getNotes(sudoku.tiles[70])).to.eql([2, 5, 7]); }); it("- found 2", function () { // http://hodoku.sourceforge.net/en/show_example.php?file=n402&tech=Naked+Quadruple let tiles = [ 5, 3, 2, 7, 8, 6, _, _, _, 9, 7, 8, 2, 4, 1, _, 6, _, _, _, 1, 9, 5, 3, 2, 8, 7, _, 2, 5, 4, _, _, 6, 7, _, _, _, 3, 6, 1, 7, _, 5, 2, 7, _, _, 5, _, _, _, _, _, _, _, _, 1, _, _, _, _, _, _, _, _, 8, _, 5, 1, _, 6, _, _, _, 3, _, _, _, 9, 8 ]; let brokenSubsets = new BrokenSubsets(4); let sudoku = new SolverSudoku().setupNormalSudoku(tiles); brokenSubsets.toggleAllNotes(sudoku.tiles); sudoku.updateInvalidNotes(); expect(brokenSubsets.findClue(sudoku)).to.eql(true); expect(brokenSubsets.getNotes(sudoku.tiles[54])).to.eql([2, 3, 8]); expect(brokenSubsets.getNotes(sudoku.tiles[55])).to.eql([5, 8]); expect(brokenSubsets.getNotes(sudoku.tiles[63])).to.eql([2, 3]); expect(brokenSubsets.getNotes(sudoku.tiles[72])).to.eql([1, 2]); expect(brokenSubsets.getNotes(sudoku.tiles[73])).to.eql([1, 5]); }); }); });
701e0110daa43c7a0413273f60c13300d5e88f99
TypeScript
den19980107/BotBuilder
/src/converter/helper/scriptParser.ts
3.359375
3
import FlowShareVariable from "./flowShareVariable"; import serverConfig from '../../../config/server.json' import { internalMethods } from 'botbuilder-share' const { castToBool, castToNumber, castToString, JsonStringify, getLength } = internalMethods /** * expression: 代表在字串中,有被 "${" 和 "}" 包起來的地方 * internal method: 代表字串中,有被如 "int(" ")" 、"string(" ")" 包起來的部分 */ export default class ScriptParser { /** * 檢查使用者的字串中是否有備 "${" 和 "}" 包含的值 * 如果有的話需要將該字串替換成目前變數中的值 * 進來的資料為 payload 的其中一個 key:value * EX: * "{"message":${DATA.value}}" => "{"message":"somting ..."}" 之類的 * 也需要檢查這個值有沒有被內建轉型方法轉掉 * EX: * "{"message":${int(DATA.value)}}" => "{"message":10}" 之類的 */ static scriptParserMiddleware(input: any, flowShareVariable: FlowShareVariable) { if (!input) return null let string; if (typeof input === 'object') { string = JSON.stringify(input) } else { string = String(input) } const startSpliter = serverConfig.SCRIPT_PARSER.START_SPLITER; const endSpliter = serverConfig.SCRIPT_PARSER.END_SPLITER; const result = this.replaceExpressionWithMiddleware(string, startSpliter, endSpliter, (subString: string) => { return this.internalMethodParserMiddleware(subString, flowShareVariable) }) return result } /** * 找出字串中的 expression (就是被 "${" "}" 包起來的地方),並可以傳入一個 middleware 來處理要怎麼轉換這個字串 * @param string * @param startSpliter * @param endSpliter * @param middleware * @returns */ static replaceExpressionWithMiddleware(originalString: string, startSpliter: string, endSpliter: string, middleware: (substring: string) => string) { let storeStringArr = [] let haveStartAndEndSpliter = false let string = originalString; while (true) { const startIndex = string.indexOf(startSpliter); const endIndex = string.indexOf(endSpliter); // step.1 檢查有沒有 startIndex 和 endIndex,如果沒有,把整個自串存到 storeStringArr,並把字串清空跳出迴圈 if (startIndex === -1 || endIndex === -1) { storeStringArr.push(string); break; } else { haveStartAndEndSpliter = true } // step.2 先把前面的存起來 // ex: blabla {start}some.thing.else{end} qeqweqwe // 會先把 [blabla ] 存到 storeStringArr const aheadString = string.substring(0, startIndex); storeStringArr.push(aheadString); // step.3 找出 startSpliter 和 endSpliter 中間的字,並交給 middleware 處理 let substring = string.substring(startIndex + startSpliter.length, endIndex); const resultString = middleware(substring); // step.4 將結果存到 storeStringArr storeStringArr.push(resultString); // step.5 取 string 從 endIndex + 1 到 string.length 都清掉 // ex: "ahead string{start}qqeqwe{end}behind string" => "behind string" string = string.slice(endIndex + endSpliter.length, string.length); } // 刪掉陣列裡面為 '' 空 的值 storeStringArr = storeStringArr.filter(item => item !== '') // 把 storeStringArr merge 起來並回傳 if (storeStringArr.length === 1) { return storeStringArr[0] } else { return storeStringArr.join("") } } static replaceInternalMethodWithMiddleware(string: string, startSpliter: string, endSpliter: string, castFunction: Function, middleware: (substring: string) => string) { if (string.startsWith(startSpliter) && string.endsWith(endSpliter)) { // 把 startSpliter 和 endSpliter 拿掉,使用 middleware 轉換剩下的值,並看要不要轉型 const startIndex = string.indexOf(startSpliter); const endIndex = string.lastIndexOf(endSpliter); const content = string.slice(startIndex + startSpliter.length, endIndex); if (castFunction) { return castFunction(middleware(content)) } else { return middleware(content) } } else { return string } } // 檢查 "${" "}" 之內的值有沒有包含內建函數 // ex int(Data.value) => 要處理 int static internalMethodParserMiddleware(string: string, flowShareVariable: FlowShareVariable): any { // 如果字串中包含任何一種 internal method,就繼續呼叫 internalMethodParserMiddleware 直到沒有時回傳 stringParserMiddleware // cast to number if (string.startsWith(castToNumber.START_SPLITER) && string.endsWith(castToNumber.END_SPLITER)) { const result = this.replaceInternalMethodWithMiddleware(string, castToNumber.START_SPLITER, castToNumber.END_SPLITER, castToNumber.METHOD, (subSubString: string) => { return this.internalMethodParserMiddleware(subSubString, flowShareVariable) }) return result } // cast to Bool if (string.startsWith(castToBool.START_SPLITER) && string.endsWith(castToBool.END_SPLITER)) { const result = this.replaceInternalMethodWithMiddleware(string, castToBool.START_SPLITER, castToBool.END_SPLITER, castToBool.METHOD, (subSubString: string) => { return this.internalMethodParserMiddleware(subSubString, flowShareVariable) }) return result } // cast to string if (string.startsWith(castToString.START_SPLITER) && string.endsWith(castToString.END_SPLITER)) { const result = this.replaceInternalMethodWithMiddleware(string, castToString.START_SPLITER, castToString.END_SPLITER, castToString.METHOD, (subSubString: string) => { return this.internalMethodParserMiddleware(subSubString, flowShareVariable) }) return result } // getLength if (string.startsWith(getLength.START_SPLITER) && string.endsWith(getLength.END_SPLITER)) { const result = this.replaceInternalMethodWithMiddleware(string, getLength.START_SPLITER, getLength.END_SPLITER, getLength.METHOD, (subSubString: string) => { return this.internalMethodParserMiddleware(subSubString, flowShareVariable) }) return result } // json stringify if (string.startsWith(JsonStringify.START_SPLITER) && string.endsWith(JsonStringify.END_SPLITER)) { const result = this.replaceInternalMethodWithMiddleware(string, JsonStringify.START_SPLITER, JsonStringify.END_SPLITER, JsonStringify.METHOD, (subSubString: string) => { return this.internalMethodParserMiddleware(subSubString, flowShareVariable) }) return result } // const result = this.replaceByFlowShareVaraible(string, flowShareVariable); return result } static replaceByFlowShareVaraible(string: string, flowShareVariable: FlowShareVariable) { // 取出所有層,每一層我取名叫做 "stack" // ex {message:#FLOW_SHARE_VARIABLE.some.thing[0].blabla# 123} ["some","thing[0]","blabla"] // 切分開頭: #FLOW_SHARE_VARIABLE. // 切分結尾: <space> const stacks = string.split("."); let returnValue: any; for (let i = 0; i < stacks.length; i++) { let currentStack = stacks[i] // stack 中的第一層要從 gloal variable 中拿取 if (i == 0) { // 如果第一個 stack 中就是陣列 ex something[1] if (this.checkIfCurrentStackIsArray(currentStack)) { // 先忽視後面的 [1] 因為這一步是要將資料從 global variable 中取出,最後會對陣列進行處理 const currentStackWithoutArraySymbol = currentStack.substring(0, currentStack.lastIndexOf("[")) returnValue = flowShareVariable.get(currentStackWithoutArraySymbol) } else { returnValue = flowShareVariable.get(currentStack) } } else { try { returnValue = returnValue[currentStack] } catch (err) { console.error("global varaible dosent have this variable!") } } /** * 檢查目前這個階層是否為陣列且指定要陣列中的的幾個,如果有的話將他移出來 * ex something[xxx] */ if (this.checkIfCurrentStackIsArray(currentStack)) { try { const index = parseInt(currentStack.substring( currentStack.lastIndexOf("[") + 1, currentStack.lastIndexOf("]") )); returnValue = returnValue[index]; } catch (e) { console.error("有錯誤發生在 global variable 中的 scriptParserMiddleware 方法", e) } } } return returnValue } static checkIfCurrentStackIsArray(currentStack: string) { return currentStack.includes("[") && currentStack.includes("]") } }
52c0d7e159cf6e7c212f82a9a49e3ec4f4299739
TypeScript
ChrisChloe/angular-course
/angular/typescript/Vehicle.ts
2.5625
3
export default class Vehicle { protected model: string private speed: number = 0 public speeUp() :void { this.speed = this.speed + 10 } public stop() :void { this.speed = 0 } public currentSpeed() :number { return this.speed } } export let anything: string = "Test"
f4cd57a9eeefe3624324c65662d5c799d0b846a1
TypeScript
ukyo/mp4.js
/src/finder.ts
3.265625
3
import { IBox } from "./interface.box"; export class Finder { constructor(public tree: any) {} findOne(type: string): IBox { let box!: IBox; const find = (tree: any) => { if (box) return; switch (typeof tree) { case "number": case "string": case "boolean": return; } if (tree.type === type) { return (box = tree); } if (tree.buffer) return; Object.keys(tree).forEach(key => { const prop = tree[key]; if (prop == null) return; if (Array.isArray(prop)) { prop.some(find); } else if (prop.type) { find(prop); } }); }; find(this.tree); return box; } findAll(type: string): IBox[] { const boxes: IBox[] = []; const find = (tree: any) => { switch (typeof tree) { case "number": case "string": case "boolean": return; } if (tree.type === type) boxes.push(tree); if (tree.buffer) return; Object.keys(tree).forEach(key => { const prop = tree[key]; if (prop == null) return; if (Array.isArray(prop)) { prop.forEach(find); } else { find(prop); } }); }; find(this.tree); return boxes; } }
a4af5947027a3ab4d3f14d8e486594854d47c852
TypeScript
stanicavuleta/torus-meme-of-the-day-feature
/hub-browser-auth/src/api.ts
2.578125
3
/* eslint-disable @typescript-eslint/no-explicit-any */ /** Import our server libraries */ import Router from "koa-router"; import { createUserAuth, KeyInfo } from '@textile/security'; /** * Start API Routes * * All prefixed with `/api/` */ const api = new Router({ prefix: '/api' }); /** * Create a REST API endpoint at /api/userauth * This endpoint will provide authorization for _any_ user. */ api.get( '/userauth', async (ctx, next: () => Promise<any>) => { /** Get API authorization for the user */ const auth = await createUserAuth( process.env.APP_PROD_API_KEY as string, // User group key process.env.APP_PROD_API_SECRET as string // User group key secret ); /** Return the auth in a JSON object */ ctx.body = auth await next(); }); api.get( '/keyinfo', async (ctx, next: () => Promise<any>) => { const keyInfo: KeyInfo = { key: process.env.APP_TEST_API_KEY as string } /** Return the auth in a JSON object */ ctx.body = keyInfo await next(); }); api.get('/identity', async (ctx, next: () => Promise<any>) => { /** Get API authorization for the user */ const userKey = process.env.APP_PROD_USER_KEY as string; ctx.body = userKey; await next(); }); api.get('/testidentity', async (ctx, next: () => Promise<any>) => { /** Get API authorization for the user */ const userKey = process.env.APP_TEST_USER_KEY as string; ctx.body = userKey; await next(); }); export default api;
d27a85495a1387bdfbe55fc980c8530b5b120e8d
TypeScript
Balkonskii/PT.InternationalStore
/src/core/helpers/date.helper.ts
2.90625
3
import { formatISO, parse, parseISO, format } from 'date-fns'; export class DateHelper { static parse(value: string, dateFormat: string, referenceDate?: Date | number): Date { return parse(value, dateFormat, referenceDate || new Date()); } static parseDateTimeOffset(value: string): Date { if (!value) { return null; } return parseISO(value); } static formatDateTimeOffset(value: Date): string { if (!value) { return null; } return formatISO(value); } static parseDateTime(value: string): Date { if (!value) { return null; } return parseISO(value); } static getISODay(date: Date): number { if (!date) { return null; } const day = date.getDay(); return day === 0 ? 7 : day; } static formatDateTime(date: Date): string { if (!date) { return null; } // tslint:disable-next-line:quotemark return format(date, 'yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''); } static formatDate(date: Date, dateFormat: string = 'dd.MM.yyyy'): string { if (!date) { return null; } return format(date, dateFormat); } }
25a6b70b23f8700e2f4a51f456fdaa4102fad62b
TypeScript
backstage/backstage
/plugins/search-backend-node/src/test-utils/TestPipeline.ts
2.796875
3
/* * Copyright 2022 The Backstage Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { IndexableDocument } from '@backstage/plugin-search-common'; import { pipeline, Readable, Transform, Writable } from 'stream'; /** * Object resolved after a test pipeline is executed. * @public */ export type TestPipelineResult = { /** * If an error was emitted by the pipeline, it will be set here. */ error: unknown; /** * A list of documents collected at the end of the pipeline. If the subject * under test is an indexer, this will be an empty array (because your * indexer should have received the documents instead). */ documents: IndexableDocument[]; }; /** * Test utility for Backstage Search collators, decorators, and indexers. * * @example * An example test checking that a collator provides expected documents. * ``` * it('provides expected documents', async () => { * const testSubject = await yourCollatorFactory.getCollator(); * const pipeline = TestPipeline.fromCollator(testSubject); * * const { documents } = await pipeline.execute(); * * expect(documents).toHaveLength(2); * }) * ``` * * @example * An example test checking that a decorator behaves as expected. * ``` * it('filters private documents', async () => { * const testSubject = await yourDecoratorFactory.getDecorator(); * const pipeline = TestPipeline * .fromDecorator(testSubject) * .withDocuments([{ title: 'Private', location: '/private', text: '' }]); * * const { documents } = await pipeline.execute(); * * expect(documents).toHaveLength(0); * }) * ``` * * @public */ export class TestPipeline { private collator?: Readable; private decorator?: Transform; private indexer?: Writable; private constructor({ collator, decorator, indexer, }: { collator?: Readable; decorator?: Transform; indexer?: Writable; }) { this.collator = collator; this.decorator = decorator; this.indexer = indexer; } /** * Provide the collator, decorator, or indexer to be tested. * * @deprecated Use `fromCollator`, `fromDecorator` or `fromIndexer` static * methods to create a test pipeline instead. */ static withSubject(subject: Readable | Transform | Writable) { if (subject instanceof Transform) { return new TestPipeline({ decorator: subject }); } if (subject instanceof Writable) { return new TestPipeline({ indexer: subject }); } if (subject.readable || subject instanceof Readable) { return new TestPipeline({ collator: subject }); } throw new Error( 'Unknown test subject: are you passing a readable, writable, or transform stream?', ); } /** * Create a test pipeline given a collator you want to test. */ static fromCollator(collator: Readable) { return new TestPipeline({ collator }); } /** * Add a collator to the test pipeline. */ withCollator(collator: Readable): this { this.collator = collator; return this; } /** * Create a test pipeline given a decorator you want to test. */ static fromDecorator(decorator: Transform) { return new TestPipeline({ decorator }); } /** * Add a decorator to the test pipeline. */ withDecorator(decorator: Transform): this { this.decorator = decorator; return this; } /** * Create a test pipeline given an indexer you want to test. */ static fromIndexer(indexer: Writable) { return new TestPipeline({ indexer }); } /** * Add an indexer to the test pipeline. */ withIndexer(indexer: Writable): this { this.indexer = indexer; return this; } /** * Provide documents for testing decorators and indexers. */ withDocuments(documents: IndexableDocument[]): TestPipeline { if (this.collator) { throw new Error('Cannot provide documents when testing a collator.'); } // Set a naive readable stream that just pushes all given documents. this.collator = new Readable({ objectMode: true }); this.collator._read = () => {}; process.nextTick(() => { documents.forEach(document => { this.collator!.push(document); }); this.collator!.push(null); }); return this; } /** * Execute the test pipeline so that you can make assertions about the result * or behavior of the given test subject. */ async execute(): Promise<TestPipelineResult> { const documents: IndexableDocument[] = []; if (!this.collator) { throw new Error( 'Cannot execute pipeline without a collator or documents', ); } // If we are here and there is no indexer, we are testing a collator or a // decorator. Set up a naive writable that captures documents in memory. if (!this.indexer) { this.indexer = new Writable({ objectMode: true }); this.indexer._write = (document: IndexableDocument, _, done) => { documents.push(document); done(); }; } return new Promise<TestPipelineResult>(done => { const pipes: (Readable | Transform | Writable)[] = [this.collator!]; if (this.decorator) { pipes.push(this.decorator); } pipes.push(this.indexer!); pipeline(pipes, (error: NodeJS.ErrnoException | null) => { done({ error, documents, }); }); }); } }
abc820befd5c64f1750c56042d7e8061f6ede877
TypeScript
xspeed101/life
/Scripts/managers/collision.ts
2.71875
3
module managers { let count:number = 0; let frameCount:number = 0; export class Collision { public static Check(object1: any , object2: any) { // create two vec2 objects let P1: math.Vec2 = new math.Vec2(object1.x, object1.y); let P2: math.Vec2 = new math.Vec2(object2.x, object2.y); object1.visible = true; object2.visible = true; if(math.Vec2.Distance(P1, P2) < (object1.halfHeight + object2.halfHeight)) { if(!object2.isColliding) { object2.isColliding = true; switch(object2.name) { case "cyborg": if(objects.Game.HighScore <= objects.Game.scoreBoard.Score) { objects.Game.scoreBoard.HighScore = objects.Game.scoreBoard.Score; objects.Game.HighScore = objects.Game.scoreBoard.HighScore; objects.Game.scoreBoard.Lives -= 1 ; } break; case "bullet": object1.visible = false; object1.x = 1400; count++; objects.Game.scoreBoard.Score += count; break; } } else { object2.isColliding = false; }} // The objects are t look into https://gamedev.stackexchange.com/questions/128675/how-to-detect-collisions-of-objects-in-two-different-arrayshtml-canvas } } }
5c452e9b0c0b3af8652b1bd06cacbb4b3abe3e66
TypeScript
peterdinis/React-Albums-App
/src/redux/actions/albumsActions.ts
2.53125
3
import {Dispatch} from "redux"; import {ALBUMS_LOADING, ALBUMS_SUCCESS, ALBUMS_FAIL, AlbumDispatchTypes} from "../types/albumsTypes"; import axios from "axios"; export const getAlbums = (id: string) => async (dispatch: Dispatch<AlbumDispatchTypes>) =>{ try { dispatch({ type: ALBUMS_LOADING }) const res = await axios.get(`https://jsonplaceholder.typicode.com/albums/${id}`); dispatch({ type: ALBUMS_SUCCESS, payload: res.data }) } catch(err) { dispatch({ type: ALBUMS_FAIL }) } }
d7403f2973d7d2d3657c409413566b55d72787bc
TypeScript
nguyer/aws-sdk-js-v3
/clients/browser/client-glue-browser/types/SchedulerRunningException.ts
2.578125
3
import { ServiceException as __ServiceException__ } from "@aws-sdk/types"; /** * <p>The specified scheduler is already running.</p> */ export interface SchedulerRunningException extends __ServiceException__<_SchedulerRunningExceptionDetails> { name: "SchedulerRunningException"; } export interface _SchedulerRunningExceptionDetails { /** * <p>A message describing the problem.</p> */ Message?: string; }
930547eae7006db49cc49b6fece37362dfc42df1
TypeScript
HTMLProgrammer2001/patterns
/Composite/Filesystem/File.ts
2.78125
3
import Component from './Component'; class TFile extends Component{ constructor(name: string, private size: number){ super(name); }; getSize(): number{ return this.size; } add(comp: Component){} remove(comp: Component){} print(){ console.log(`File ${this.getName()}`); } } export default TFile;
d149c0c567e4dc5e81a400f0049878f689f7337c
TypeScript
Mathyfight/mathyfight-rest-api
/src/shared/infrastructure/typeorm.mysql.mapper.ts
2.671875
3
import { SortingOrderCriteria } from '../domain/value-object/general/sorting-order-criteria'; export class TypeOrmMySqlMapper { static sortingOrderCriteriaToSqlCriteria( order?: SortingOrderCriteria, ): 'ASC' | 'DESC' { return order === SortingOrderCriteria.Ascendant ? 'ASC' : 'DESC'; } }
257a3573717e8041307784abe5146773d2ec09c9
TypeScript
Maxio777/lg
/new-front/src/app/models/referee/referee-model.ts
2.625
3
import {UserModel} from '@models/users/user-model'; export class RefereeModel extends UserModel { constructor(referee) { super(referee); } static fromJs(referee): RefereeModel { if (referee) { return new RefereeModel(referee); } return null; } static fromJsArr(referees): RefereeModel[] { if (referees && referees.length) { return referees.map(referee => RefereeModel.fromJs(referee)); } return null; } }
d0ff65e0b1e044ff56a944d097e17920caf021a8
TypeScript
adamhaile/surplus-todomvc
/src/persistence.ts
2.71875
3
import S from 's-js'; import { ToDo, ToDosModel } from './models'; const LOCAL_STORAGE_KEY = 'todos-surplus'; export function LocalStoragePersistence(model : ToDosModel) { // load stored todos on init const stored = localStorage.getItem(LOCAL_STORAGE_KEY); if (stored) model.todos(JSON.parse(stored).todos.map((t : any) => ToDo(t.title, t.completed))); // store JSONized todos whenever they change S(() => { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(model)); }); }
b93b4efb719f2e1cb411cf959c74f8a2cc0b2472
TypeScript
wipkanban/wipkanban
/src/server/controllers/user/CreateAccount.ts
2.578125
3
import { BAD_REQUEST, CREATED, INTERNAL_SERVER_ERROR } from "../../utils/HttpStatusCode"; import * as ModelUser from "../../models/user"; import { Model } from "mongoose"; import { Response, NextFunction } from "express"; export default (User: Model<ModelUser.IUser>) => { return (req: any, res: Response, next: NextFunction) => { let { email, password } = req.body; // verify if user already exists User.findOne( { email: email }, (err, user) => { if (err) { return next(err); } if (user) { return res .status(BAD_REQUEST) .json({ success: false, message: "User already exists" }) .end(); } let newUser = new ModelUser.default({ email, password }); newUser.save(function(err) { if (err) { res .status(INTERNAL_SERVER_ERROR) .json({ success: false, message: err }) .end(); } res .status(CREATED) .json({ success: true, message: "User account created with successfull!" }) .end(); }); } ); }; };
c59b8a547a29e77c4900487cd0b82145fda67e44
TypeScript
jorge-e-aquino/ngCalculator
/src/app/calculator/calculator/calculator.component.ts
2.5625
3
import { Component, OnInit } from '@angular/core'; // contains the display and number pad components, parses their data, and is sent to the router outlet to be displayed on the browser @Component({ selector: 'app-calculator', template: ` <div class="app centered"> <app-display [input]="input" [result]="result"></app-display> <app-number-pad (messageEvent)="receiveMessage($event)"></app-number-pad> </div> `, styleUrls: ['./calculator.component.scss'] }) export class CalculatorComponent implements OnInit { title = 'ngCalculator'; json: string; parse: {input: string, result: string}; input: string; result: string; constructor() { } ngOnInit(): void { } receiveMessage($event): void { this.json = $event; this.parse = JSON.parse(this.json); this.input = this.parse.input; this.result = this.parse.result; console.log('receive message json in calculator, parsed as:', this.parse); } }
c030f7b729f73ff30c1644b20e67baaaae569298
TypeScript
brennowilliam/kahoot-points-game
/src/selectors.ts
2.6875
3
import { createSelector } from "reselect"; import _ from "lodash"; // Types import { GameState, BoardItem, BonusRewards } from "./types"; // Selectors export const items$ = (state: GameState) => _.get(state, ["game", "items"]); export const selectedItems$ = (state: GameState) => _.get(state, ["game", "selectedItems"]); export const weekBonusRewards$ = (state: GameState) => _.get(state, ["game", "weekBonusRewards"]); export const selectedItemsAggregated$ = createSelector( [selectedItems$, weekBonusRewards$], (selectedItems: BoardItem[], weekBonusRewards: BonusRewards) => { return _.reduce( selectedItems, (acc: any, val: any) => { if (acc[val.letter]) { acc[val.letter] = { ...acc[val.letter], qty: acc[val.letter].qty + 1, unitPoints: acc[val.letter].unitPoints + val.unitPoints }; // Check if we have bonus points for the particular item if (weekBonusRewards[val.letter]) { if (weekBonusRewards[val.letter].qty === acc[val.letter].qty) { acc[val.letter].bonusPoints += weekBonusRewards[val.letter].points; } } } else { acc[val.letter] = { letter: val.letter, qty: 1, unitPoints: val.unitPoints, bonusPoints: 0 }; } return acc; }, {} ); } ); export const bonusScore$ = createSelector( [selectedItemsAggregated$], selectedItemsAggregated => { return _.reduce( selectedItemsAggregated, (acc: any, val: any) => { return (acc += val.bonusPoints); }, 0 ); } ); export const totalScore$ = createSelector( [selectedItems$, bonusScore$], (selectedItems: BoardItem[], bonusScore: number) => { const itemsScore = _.reduce( selectedItems, (acc: number, val: BoardItem) => { return acc + val.unitPoints; }, 0 ); return itemsScore + bonusScore; } );
2b4463f55d3be6be4aa69c83ea1f13f1a6f9ad9a
TypeScript
yisraelx/authllizer
/packages/@authllizer/core/src/http/fetch.ts
2.6875
3
import extend from '../utils/extend'; import isObject from '../utils/is-object'; import { BaseHttpClient } from './base'; import { IHttpRequestOptions } from './http'; // for fetch global scope error 'TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation' // can be 'fetch.bind(this)' to solve the error. let fetchBind = (input, init?) => fetch(input, init); /** * @resource https://fetch.spec.whatwg.org * @see https://mdn.io/fetch */ export class FetchHttpClient extends BaseHttpClient { protected _client: typeof fetch; constructor(client: typeof fetch = (typeof fetch !== 'undefined' && fetchBind)) { super(client); } public request<TResponse>(url: string, options: IHttpRequestOptions): Promise<TResponse> { let { method, data, params, headers = {}, withCredentials } = options; url = FetchHttpClient.extendUrlQuery(url, params); let credentials = (withCredentials === true && 'include') || (withCredentials === false && 'same-origin') || 'omit' as any; // Other types of data can be supported if (!headers['Content-Type'] && isObject(data)) { headers = extend({ 'Content-Type': 'application/json' }, headers); data = JSON.stringify(data); } let requestOptions: RequestInit = { method, body: data, credentials, headers }; return this ._client(url, requestOptions) .then((response: Response) => { if (response.ok) { return response.json(); } throw response; }); } }
56526f668fdd730783016a65813c7b1887d3b3e3
TypeScript
Kadsuke/passerelle
/src/main/webapp/app/entities/gestioneau/parcelle/parcelle.model.ts
2.625
3
import { ILot } from 'app/entities/gestioneau/lot/lot.model'; export interface IParcelle { id?: number; libelle?: string; lot?: ILot | null; } export class Parcelle implements IParcelle { constructor(public id?: number, public libelle?: string, public lot?: ILot | null) {} } export function getParcelleIdentifier(parcelle: IParcelle): number | undefined { return parcelle.id; }
bda21fd2ab8e0817ddd5d89d3ed1bdbda75ff1ef
TypeScript
NoHomey/db-machine
/Field.ts
2.765625
3
//declare var require; import Fields = require("./Fields"); var fields: Fields = new Fields(); class Field { private name_: string; private field_: string; private type_: string; private value_: string; constructor(table: string, name: string) { this.name_ = name; this.field_ = fields.field(table, name); this.type_ = fields.type(this.field_); this.value_ = fields.sql(this.field_); } get name(): string { return this.name_; } get type(): string { return this.type_; } get value(): string { return this.value_; } sql(): string { return this.name_ + " " + this.value_; } insert(row: number): string { return fields.insert(this.name_, this.type_, row); } } export = Field;
e1ee9937a6912b8ff2b19f3e9b4de1e08568695e
TypeScript
jiangwenyang/front-end-assistant
/src/translate.ts
3.046875
3
var TKK = ((function () { var a = 561666268 var b = 1526272306 return 406398 + '.' + (a + b) })()) function hexCharAsNumber(xd: string) { return (xd >= 'a') ? xd.charCodeAt(0) - 87 : Number(xd) } function shiftLeftOrRightThenSumOrXor(num: number, opArray: Array<string>) { return opArray.reduce((acc, opString) => { var op1 = opString[1] // '+' | '-' ~ SUM | XOR var op2 = opString[0] // '+' | '^' ~ SLL | SRL var xd = opString[2] // [0-9a-f] var shiftAmount = hexCharAsNumber(xd) var mask = (op1 === '+') ? acc >>> shiftAmount : acc << shiftAmount return (op2 === '+') ? (acc + mask & 0xffffffff) : (acc ^ mask) }, num) } function transformQuery(query: string) { for (var e = [], f = 0, g = 0; g < query.length; g++) { var l = query.charCodeAt(g) if (l < 128) { e[f++] = l // 0{l[6-0]} } else if (l < 2048) { e[f++] = l >> 6 | 0xC0 // 110{l[10-6]} e[f++] = l & 0x3F | 0x80 // 10{l[5-0]} } else if (0xD800 === (l & 0xFC00) && g + 1 < query.length && 0xDC00 === (query.charCodeAt(g + 1) & 0xFC00)) { // that's pretty rare... (avoid ovf?) l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charCodeAt(++g) & 0x03FF) e[f++] = l >> 18 | 0xF0 // 111100{l[9-8*]} e[f++] = l >> 12 & 0x3F | 0x80 // 10{l[7*-2]} e[f++] = l & 0x3F | 0x80 // 10{(l+1)[5-0]} } else { e[f++] = l >> 12 | 0xE0 // 1110{l[15-12]} e[f++] = l >> 6 & 0x3F | 0x80 // 10{l[11-6]} e[f++] = l & 0x3F | 0x80 // 10{l[5-0]} } } return e } function normalizeHash(encondindRound2: number) { if (encondindRound2 < 0) { encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000 } return encondindRound2 % 1E6 } function calcHash(query: string, windowTkk: string) { // STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char var bytesArray = transformQuery(query) // STEP 2: starting with TKK index, add the array from last step one-by-one, and do 2 rounds of shift+add/xor var d = windowTkk.split('.') var tkkIndex = Number(d[0]) || 0 var tkkKey = Number(d[1]) || 0 var encondingRound1 = bytesArray.reduce((acc, current) => { acc += current return shiftLeftOrRightThenSumOrXor(acc, ['+-a', '^+6']) }, tkkIndex) // STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key var encondingRound2 = shiftLeftOrRightThenSumOrXor(encondingRound1, ['+-3', '^+b', '+-f']) ^ tkkKey // STEP 4: Normalize to 2s complement & format var normalizedResult = normalizeHash(encondingRound2) return normalizedResult.toString() + "." + (normalizedResult ^ tkkIndex) } function genTK(query: string) { return calcHash(query, TKK) }
90a54e8adcde3c4a777e42047508ec9d734d92e0
TypeScript
MartinSka/chat
/src/app/models/user.model.ts
3.140625
3
export interface User { /** * User ID. */ id: string; /** * User name. */ name: string; /** * List of users and their respective chats ID. */ contacts: Contacts; } /** * List of users that the sender can talk to * and the chat ID that corresponds to that conversation. */ export interface Contacts { [key: string]: { chatId: string; }; }
548d5b2d5b10d5f3483c2c9731eaccf496eae470
TypeScript
Wiggins-zsz/typescript
/src/interface.ts
3.0625
3
import {Singleton} from './index'; interface Type { name: string, age: number, address?: string } interface ReadOnly { readonly x: string, readonly y: number } export function Type(param: Type) { let c = Singleton.getInstance({name: 'third', className: 'third class', content: 'third address', callBack: () =>{}}); let {name, age, address} = param; console.log(age, name, address); return [name, age, address]; } export function Read(param: ReadOnly): {} { return param; }
7127bd8e9f0d6078707157b263ba787c6901bcc7
TypeScript
taonylu/egretproject
/EgretProjects/llk_old/src/net/ClientSocket.ts
2.671875
3
/** * 文 件 名:ClientSocket.ts * 功 能: 客户端Socket * 内 容: * 作 者: 羊力大仙 * 生成日期:2015/9/14 * 修改日期:2015/9/14 * 修改日志: */ class ClientSocket { private static instance: ClientSocket; private webSocket: egret.WebSocket; private tempMsg: string = ""; //临时数据 private callBack: ISocketCallBack; //socket回调 private IP: string = "192.168.1.50"; private port: number = 12345; public static getInstance(): ClientSocket { if(this.instance == null) { this.instance = new ClientSocket(); } return this.instance; } public connect(): void { console.log("start connect socket..."); if(this.webSocket == null) { this.webSocket = new egret.WebSocket(); this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA,this.onSocketData,this); this.webSocket.addEventListener(egret.Event.CONNECT,this.onSocketConnect,this); this.webSocket.addEventListener(egret.IOErrorEvent.IO_ERROR,this.onSocketError,this); this.webSocket.addEventListener(egret.Event.CLOSE,this.onSocketClose,this); } this.webSocket.connect(this.IP,this.port); } private onSocketConnect(): void { console.log("socket connect success..."); if(this.tempMsg != "") { this.send(this.tempMsg); this.tempMsg = ""; } this.callBack.onSocketConnect(); } private onSocketData(e: egret.Event): void { var data = this.webSocket.readUTF(); console.log("socket rev data:" + data); var json = JSON.parse(data); this.callBack.onSocketData(json); } private onSocketError(e:egret.IOErrorEvent): void { console.log("socket connent error..."); this.callBack.onSocketError(); } public send(jsonMsg:string): void { console.log("socket send msg:" + jsonMsg); if(this.webSocket && this.webSocket.connected) { this.webSocket.writeUTF(jsonMsg); this.webSocket.flush(); } else { console.log("socket is close,can't send msg..."); this.tempMsg = jsonMsg; this.connect(); } } public onSocketClose(): void { console.log("close socket..."); this.tempMsg = ""; this.callBack.onSocketClose(); } public setCallBack(callBack: ISocketCallBack) { this.callBack = callBack; } }
d0d8d5ac61f02b734480391f21d6db5eace02edc
TypeScript
cns-iu/ngx-dino
/projects/core/src/lib/fields/factories/simple-field.ts
2.53125
3
import { Seq } from 'immutable'; import { Operator } from '../../operators'; import { BaseFieldArgs, Field } from '../field'; export interface SimpleFieldArgs<T> extends BaseFieldArgs { bfieldId?: string; operator: Operator<any, T>; } export function simpleField<T>(args: SimpleFieldArgs<T>): Field<T> { const {bfieldId, operator} = args; const bidSeq = bfieldId ? {[bfieldId]: operator} : {}; const mapping = Seq.Keyed<string, Operator<any, T>>({ [Field.defaultSymbol]: operator }).concat(bidSeq).toSeq(); const newArgs = {...args, mapping}; return new Field(newArgs); }
5a712cff0d7c386996b188bf4c418c4768442b8e
TypeScript
MagnetronGame/magnetron-client
/src/components/magnetron_game/MagnetronGame3d/boardGroupAnim.ts
2.84375
3
import * as THREE from "three" import { StaticBoard } from "./board" import { resetBoardObjectCellPositions, VisBoardPlate } from "./boardVisObject" import { range } from "../../../utils/arrayUtils" import { Anim } from "./animation/animationTypes" const positionCells = ( staticBoard: StaticBoard, boardObject: VisBoardPlate, distanceFactor: number, rotation: number, ) => { range(staticBoard.cellCount.x).forEach((x) => { range(staticBoard.cellCount.y).forEach((y) => { const cellStaticPos = staticBoard.cellsCenterPosition[x][y] const cellMesh = boardObject.cells[x][y] const cellStaticRelPos = new THREE.Vector2().subVectors( cellStaticPos, staticBoard.center, ) const cellPos = cellStaticRelPos .clone() .multiplyScalar(distanceFactor) .rotateAround(staticBoard.center, rotation) .add(staticBoard.center) cellMesh.position.x = cellPos.x cellMesh.position.z = cellPos.y }) }) } export default (staticBoard: StaticBoard, boardObject: VisBoardPlate): Anim => ({ name: "group board pieces", duration: 4, update: ({ durationRatio, durationRatioInv }) => { const durationRatioSquared = Math.pow(durationRatio, 20) const distanceFactor = 10 * (1 - durationRatioSquared) + 1 const rotation = (Math.PI / 2) * durationRatioInv positionCells(staticBoard, boardObject, distanceFactor, rotation) }, end: () => resetBoardObjectCellPositions(staticBoard, boardObject), }) // // export class BoardGroupAnimation extends Animation { // private readonly boardObject: VisBoardPlate // private readonly staticBoard: StaticBoard // // constructor(staticBoard: StaticBoard, boardObject: VisBoardPlate) { // super(4, false) // this.staticBoard = staticBoard // this.boardObject = boardObject // } // // public update = (game: Magnetron, deltaTime: number) => { // this.currDuration += deltaTime // const durationFactor = this.currDuration / this.duration // const durationFactorSquared = Math.pow(durationFactor, 10) // // const distanceFactor = 10 * (1 - durationFactorSquared) + 1 // const rotation = (Math.PI / 2) * (1 - durationFactor) // this.positionCells(distanceFactor, rotation) // // if (this.currDuration >= this.duration) { // resetBoardObjectCellPositions(this.staticBoard, this.boardObject) // return false // } else { // return true // } // } // // private positionCells = (distanceFactor: number, rotation: number) => { // range(this.staticBoard.cellCount.x).forEach((x) => { // range(this.staticBoard.cellCount.y).forEach((y) => { // const cellStaticPos = this.staticBoard.cellsCenterPosition[x][y] // const cellMesh = this.boardObject.cells[x][y] // // const cellStaticRelPos = new THREE.Vector2().subVectors( // cellStaticPos, // this.staticBoard.center, // ) // const cellPos = cellStaticRelPos // .clone() // .multiplyScalar(distanceFactor) // .rotateAround(this.staticBoard.center, rotation) // .add(this.staticBoard.center) // // cellMesh.position.x = cellPos.x // cellMesh.position.z = cellPos.y // }) // }) // } // // protected start(game: Magnetron): void {} // protected end(game: Magnetron): void {} // }
be0f1304de6fcf40810b2987d5340b3c2ad1b989
TypeScript
madfish-solutions/quipuswap-webapp
/src/core/operation.ts
2.53125
3
import { BlockResponse, OperationEntry } from "@taquito/rpc"; import { TezosToolkit } from "@taquito/taquito"; export const SYNC_INTERVAL = 10_000; export const CONFIRM_TIMEOUT = 60_000 * 5; export type ConfirmOperationOptions = { initializedAt?: number; fromBlockLevel?: number; signal?: AbortSignal; }; export async function confirmOperation( tezos: TezosToolkit, opHash: string, { initializedAt, fromBlockLevel, signal }: ConfirmOperationOptions = {} ): Promise<OperationEntry> { if (!initializedAt) initializedAt = Date.now(); if (initializedAt && initializedAt + CONFIRM_TIMEOUT < Date.now()) { throw new Error("Confirmation polling timed out"); } const startedAt = Date.now(); let currentBlockLevel; try { const currentBlock = await tezos.rpc.getBlock(); currentBlockLevel = currentBlock.header.level; for ( let i = fromBlockLevel ?? currentBlockLevel; i <= currentBlockLevel; i++ ) { const block = i === currentBlockLevel ? currentBlock : await tezos.rpc.getBlock({ block: i as any }); const opEntry = await findOperation(block, opHash); if (opEntry) { let status; try { status = (opEntry.contents[0] as any).metadata.operation_result .status; } catch {} if (status && status !== "applied") { throw new FailedOpError(`Operation ${status}`); } return opEntry; } } } catch (err) { if (err instanceof FailedOpError) { throw err; } } if (signal?.aborted) { throw new Error("Cancelled"); } const timeToWait = Math.max(startedAt + SYNC_INTERVAL - Date.now(), 0); await new Promise(r => setTimeout(r, timeToWait)); return confirmOperation(tezos, opHash, { initializedAt, fromBlockLevel: currentBlockLevel ? currentBlockLevel + 1 : fromBlockLevel, signal, }); } export async function findOperation(block: BlockResponse, opHash: string) { for (let i = 3; i >= 0; i--) { for (const op of block.operations[i]) { if (op.hash === opHash) { return op; } } } return null; } class FailedOpError extends Error {}
c712cdb2629197c6620a0c56fd7224059ea51884
TypeScript
igoralvesantos/backend-food4u
/src/business/usecases/user/updateUser.ts
2.734375
3
import { UserGateway } from "../../gateways/userGateway"; import { JWTAutenticationGateway } from "../../gateways/jwtAutenticationGateway"; import { ValidatorsGateway } from "../../gateways/validatorsGateway"; export class UpdateUserUC { constructor( private db: UserGateway, private jwtAuth: JWTAutenticationGateway, private validators: ValidatorsGateway ) {} public async execute(input: updateUserUCInput): Promise<updateUserUCOutput> { try { this.validators.validateUpdateUserInput(input); const userId = this.jwtAuth.verifyToken(input.token); if(input.email) { await this.db.changeEmail(input.email, userId); } if(input.name) { await this.db.changeName(input.name, userId); } if(input.birthDate) { await this.db.changeBirthDate(input.birthDate, userId); } return { message: "User updated successfully", }; } catch (err) { throw { code: err.statusCode || 400, message: err.message || "An error occurred while trying to update the user", }; } } } export interface updateUserUCInput { token: string; email?: string; name?: string; birthDate?: Date; } export interface updateUserUCOutput { message: string; }
ec8338deef9aca3ba706b11851a6b989ee0e10b3
TypeScript
changchangge/chang-request
/src/types/object-type.ts
2.75
3
/** * @interface ObjectType */ interface ObjectType { /** * obj definition * 对象定义 */ [key: string]: unknown; } export type ObjType = ObjectType;
21d77c6812a4fb48f2fb460de2abe5a03d277fda
TypeScript
rodrigodsluz/dashboard-app
/src/utils/validation/index.ts
2.84375
3
export function checkEmailValid(value: string): boolean { if (value.length > 0) { const exclude = /[^@\-\\.\w]|^[_@\\.\\-]|[\\._\\-]{2}|[@\\.]{2}|(@)[^@]*\1/; const check = /@[\w\\-]+\./; const checkend = /\.[a-zA-Z]{2,3}$/; if ( value.search(exclude) !== -1 || value.search(check) === -1 || value.search(checkend) === -1 ) { return false; } return true; } return false; } export function checkEmpty(value: string): boolean { const valeuInput = value.trim(); if (valeuInput.length === 0) { return true; } return false; } export function checkRangeMin(value: string, min: number): boolean { return !(value.length > 1 && value.length >= min); } export const clear = (value: string) => { const emptyMask = value.replace(/[\\[\].!'@,><|://\\;&*()_+=-]/g, ''); return emptyMask.replace(/\.|\\-|\/|[()]|\W+/g, ''); }; export const setMaskMobile = (value: string): string => { const array = value.split(''); if (array.length > 2) { array.splice(0, 0, '('); array.splice(3, 0, ')'); array.splice(4, 0, ' '); } if (array.length > 10) { array.splice(10, 0, '-'); } return array.join(''); };
c409077afe1d3e1ad46000cc5c34e1c3a005b4ed
TypeScript
romaannaeem/unofficial-notion-api-v2
/src/lib/helpers.ts
3.046875
3
import { NotionObject, Options, Attributes, PageDTO, formatter, htmlResponse } from './types'; import slugify from 'slugify'; // Seperator for good-looking HTML ;) const SEPERATOR = ''; // HTML Tag types const types = { page: 'a', text: 'p', header: 'h1', sub_header: 'h3', sub_sub_header: 'h5', divider: 'hr', break: 'br', numbered_list: 'ol', bulleted_list: 'ul', image: 'img' }; /** * Method that parses a Notion-Object to HTML * @param {*} ObjectToParse The Notion-Object * @param {*} options Options for parsing */ function formatToHtml( ObjectToParse: NotionObject, options: Options, index: number ) { let { type, properties, format } = ObjectToParse; // Get color const color = format && format.block_color; // Replace color with custom color if passed const customColor = color && options.colors && ((options.colors as any)[color.split('_')[0]] || color); // Set content const content = properties && properties.title && properties.title[0][0].replace(/\[.*\]:.{1,}/, ''); const source = properties && properties.source; const tags = (content && content[0] ? content[0][0] : '').match( /\[.{1,}\]: .{1,}/ ); const attrib = tags && tags[0].replace(/(\[|\])/g, '').split(':'); if (attrib && attrib.length == 2) { return { [attrib[0]]: attrib[1].trim() }; } // Only set Style if passed const property = customColor && color.includes('background') ? `style="background-color:${customColor.split('_')[0]}"` : `style="color:${customColor}"`; // Use ternary operator to return empty string instead of undefined const style = color ? ` ${property}` : ''; // Set type to break if no content is existent if (!content && type !== 'divider' && !source) { type = 'break'; } // Create HTML Tags with content switch (types[type]) { case types.page: { if (index === 0) { return `<h1 ${style}>${content}</h1>`; } return null; } case types.divider: { return `<${types.divider}${style}/>`; } case types.break: { return `<${types.break} />`; } case types.numbered_list: case types.bulleted_list: { return `<li${style}>${content}</li>`; } case types.image: { return `<${types.image}${style} src="${source}" />`; } default: { if (types[type]) return `<${types[type]}${style}>${content}</${types[type]}>`; return null; } } } /** * Formats a List of objects to HTML * @param {*} ObjectList List of Notion-Objects * @param {*} options Options for parsing * @param {*} htmlFormatter html renderer */ function formatList(ObjectList: Array<NotionObject>, options: Options, htmlFormatter?: formatter) { const items = []; const attributes: Attributes = {}; for (let index = 0; index < ObjectList.length; index += 1) { const element = ObjectList[index]; let html: htmlResponse; if (htmlFormatter) { html = htmlFormatter(element, options, index, ObjectList); } else { html = formatToHtml(element, options, index); } if (html && typeof html === 'object') { const keys = Object.keys(html as Attributes); keys.forEach(key => { attributes[key] = (html as Attributes)[key]; }); } else if ( element && element.type.includes('list') && !element.type.includes('column') ) { // If it the element is the first ul or ol element if ( ObjectList[index - 1] && !ObjectList[index - 1].type.includes('list') ) { html = `<${types[element.type]}>${SEPERATOR}${html}`; } if ( index + 1 >= ObjectList.length || (ObjectList[index + 1] && !ObjectList[index + 1].type.includes('list')) ) { html = `${html}${SEPERATOR}</${types[element.type]}>`; } } if (typeof html === 'string') { items.push(html); } } const { format, properties } = ObjectList[0]; const title = (properties && properties.title && properties.title[0][0]) || ''; const cover = format && format.page_cover ? format.page_cover.includes('http') ? format.page_cover : `https://www.notion.so${format.page_cover}` : null; return { items, attributes: { ...attributes, title, slug: slugify(title, { lower: true }), cover, teaser: items .map(i => i .replace(/\[.{1,}\]: .{1,}/g, '') .replace(/\<a.*\>*\<\/a\>/g, '') .replace(/<[^>]*>/g, '') ) .filter(i => i) .join(' ') .trim() .substring(0, 200), icon: format ? format.page_icon : null } }; } /** * Creates a HTML Page out of a List of Notion-Objects * @param {*} ObjectList List of Notion-Objects * @param {*} options Options for parsing * @param {*} htmlFormatter html renderer */ function toHTMLPage( ObjectList: Array<NotionObject>, options: Options, htmlFormatter?: formatter ): PageDTO { const { items, attributes } = formatList(ObjectList, options, htmlFormatter); const elementsString = items.join(''); return { HTML: elementsString ? `<div>${elementsString}</div>` : '', Attributes: { ...attributes, id: ObjectList[0].id } }; } export function handleNotionError(err: Error) { if (err.message.includes('block')) { console.error('Authentication Error: Please check your token!'); } else { console.error(err); } } export function isNotionID(id: string) { const idRegex = new RegExp( /[a-z,0-9]{8}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{12}/g ); return idRegex.test(id); } export default toHTMLPage;
c48ecc2bb1d398fc1254edba5357b7c252438f23
TypeScript
rajivnayanc/Shoot_the_Balloons_HTML5_canvas
/shoot-the-balloon/src/game/Objects/ProjectileLine.ts
2.8125
3
import { BulletPosition } from './Bullet'; import { Position2D } from './common-intf'; import { LIGHT_THEME } from './consts'; import RenderableObject from './renderable-object'; import { distance, getQuadraticRoots } from './utils'; class ProjectileLine extends RenderableObject { start:Position2D; end:Position2D; controlPoints:Position2D; gravity:number; color: string; constructor(canvas: HTMLCanvasElement, c: CanvasRenderingContext2D, theme:string){ super(canvas, c); this.start = {x:0,y:0}; this.end = {x:0,y:0}; this.controlPoints = {x:0,y:0}; this.gravity = 0.3; this.color = theme===LIGHT_THEME?"black":"gray"; } draw(): void { this.c.save(); this.c.lineWidth = 1; this.c.beginPath(); this.c.setLineDash([10,15]) this.c.moveTo(this.start.x, this.start.y); this.c.quadraticCurveTo(this.controlPoints.x, this.controlPoints.y, this.end.x, this.end.y); this.c.strokeStyle = this.color; this.c.stroke(); this.c.restore(); } update(bull_start:BulletPosition): void { this.start.x = bull_start.x; this.start.y = bull_start.y; const dist = bull_start.dist/distance(0,0,this.canvas.width, this.canvas.height); const velocity = Math.min(150 * dist,40); let ux = Math.cos(bull_start.angle) * velocity; let uy = Math.sin(bull_start.angle) * velocity; let t_x = (this.canvas.width-this.start.x)/ux; let t_y = getQuadraticRoots(this.gravity, 2*uy, -2 * (this.canvas.height - this.start.y)); let t_y_top = getQuadraticRoots(this.gravity, 2*uy, -2 * (0 - this.start.y)); let timeArray = [t_x, t_y, t_y_top].filter(a=>a!=null) as number[]; let min_time = Math.min(...timeArray); this.end.x = this.start.x + ux*min_time; this.end.y = this.start.y + uy*min_time + (this.gravity * min_time * min_time)/2; const a = this.gravity/(2*ux*ux); const b = uy/ux - (this.gravity*this.start.x)/(ux*ux); const c = this.start.y - uy*this.start.x/ux + this.gravity*this.start.x*this.start.x/(2*ux*ux); this.controlPoints = this.getQuadraticBezierControlPoints( a, b, c ); this.draw(); } getQuadraticBezierControlPoints(a:number, b:number, c:number):Position2D{ let out:Position2D = {x:0,y:0}; out.x = (this.start.x+this.end.x)/2; out.y = ((this.end.x-this.start.x)/2) * (2*a*this.start.x + b) + (a*this.start.x*this.start.x + b*this.start.x + c); return out; } } export default ProjectileLine;
9a5e278ebc1c1e5c951ff8e2f8ab83c1e85be194
TypeScript
awoimbee/TGVmax
/server/src/routes/StationRouter.ts
2.625
3
import { Context } from 'koa'; import * as Router from 'koa-router'; import StationController from '../controllers/StationController'; import { HttpStatus } from '../Enum'; import { authenticate } from '../middlewares/authenticate'; import { IStation } from '../types'; /** * Autocomplete router for train stations */ class StationRouter { /** * http router */ public readonly router: Router; constructor() { this.router = new Router<{}>(); this.router.prefix('/api/v1/stations'); this.init(); } /** * Add a travel to database */ private readonly getStations = async(ctx: Context): Promise<void> => { const stations: IStation[] = await StationController.getStations(); ctx.body = stations; ctx.status = HttpStatus.OK; } /** * init router */ private init(): void { this.router.get('/', authenticate(), this.getStations); } } export default new StationRouter().router;
f4a0d55145e80540b8e4b3837712e48238c22258
TypeScript
LisaLoop/typescript-demo
/src/examples/use-cases.ts
3.140625
3
export default {} type User = { id: string; name: string; }; type ServerUser = { userData: { userEmployeeId: string; userName: string; userMeta: { userMetaId: string; userMetaLastLogin: string; userMetaDetails: []; }; }; }; const getUser = (id: string) => fetch(`/api/users/${id}`) .then((res) => res.json()) .then((data: unknown): Promise<User> => { return isValidUserData(data) ? Promise.resolve(makeUser(data)) : Promise.reject(data); }); const makeUser = (data: ServerUser): User => { const user: User = { id: data.userData.userMeta.userMetaId, name: data.userData.userName }; return user; }; const isValidUserData = (data: unknown): data is ServerUser => { const name = (data as ServerUser)?.userData?.userName; const id = (data as ServerUser)?.userData?.userMeta.userMetaId; const isValid = (typeof name === "string" && name.length > 0) && (typeof id === "string" && id.length > 0); return isValid; };
1667a0421c54830665d252157b96102546074010
TypeScript
lanrehnics/park-campus
/src/providers/buildings.ts
2.90625
3
import {Injectable} from '@angular/core'; import {Api} from './api'; import {Building} from '../models/building'; import 'rxjs/add/operator/map'; @Injectable() /** * Used by the application to interact with the buildings stored in the database on the server. */ export class BuildingProvider { /** * @param {Api} api the class containing methods which facilitate interaction with the server */ constructor(public api: Api) { } /** * Retrieves either all buildings stored on the server, or the building matching the specified ID. * * @param {Number} id used to specify the unique identifier of the building * @returns {Promise} contains the buildings retrieved from the server */ queryBuildings(id?: Number) { return new Promise((resolve, reject) => { this.api.getEntity("buildings", id).map(res => res.json()).subscribe((values) => { let buildings = []; if (values != null && values.length > 0) { for (let i = 0; i < values.length; i++) { buildings.push(new Building(values[i].building_id, values[i].building_code, values[i].building_name, values[i].building_lat, values[i].building_lng)); } } resolve(buildings); }, (error) => { reject(error); }); }); } }
cf50613daf2616efa12d1f952da59dfeeb866099
TypeScript
IronOnet/codebases
/codebases/anchor.fm/client/modules/AnchorAPI/v3/stations/fetchImportStatus.ts
2.65625
3
import { getApiUrl } from '../../../Url'; type ImportStatusParameters = { stationId: string; }; type Item = { rssImportItemId: number; state: 'waiting' | 'started' | 'finished' | 'failed'; kind: 'item' | 'channel'; title: string; }; type ImportStatusResponse = { state: 'processing' | 'complete'; percentageComplete: number; items: Item[]; }; const getEndpointUrl = (stationId: string) => getApiUrl({ path: `stations/webStationId:${stationId}/importStatus` }); export const fetchImportStatus = async ({ stationId, }: ImportStatusParameters): Promise<ImportStatusResponse> => { const url = getEndpointUrl(stationId); try { const response = await fetch(url, { credentials: 'same-origin', }); if (response.ok) { return response.json(); } throw new Error(`unable to fetch import status for station: ${stationId}`); } catch (err) { throw new Error(err.message); } };
993e7a13b02214d1444ef8b77e915534d6f7fb6c
TypeScript
CodersCamp2020-HK/CodersCamp2020.Project.FullStack-Node-React
/src/infrastructure/postgres/PostgresQueries.ts
2.765625
3
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { Client } from 'pg'; import { parse } from 'pg-connection-string'; interface PostgresConnectionConfig { host: string; user: string; password: string; port: number; database: string | undefined; } interface PostgresUrl { url: string; } type PostgresConnectionOptions = PostgresConnectionConfig | PostgresUrl; function isPostgresUrl(value: any): value is PostgresUrl { return 'url' in value && typeof value.url === 'string'; } function parsePostgresUrl({ url }: PostgresUrl): PostgresConnectionConfig { const options = parse(url); const config = { ...options, port: Number(options.port) }; const getOrThrowIfNull = <T>(param: keyof typeof config, value: T | null | undefined) => { if (value === undefined || value === null) { throw new Error(`Invalid postgres url (${param})`); } return value; }; return { host: getOrThrowIfNull('host', config.host), user: getOrThrowIfNull('user', config.user), password: getOrThrowIfNull('password', config.password), port: getOrThrowIfNull('port', config.port), database: config.database as string | undefined, }; } async function singleQueryConnection<T>( options: PostgresConnectionOptions, query: (client: Client) => Promise<T>, ): Promise<T> { const config = isPostgresUrl(options) ? parsePostgresUrl(options) : options; const client = new Client(config); await client.connect(); try { return await query(client); } finally { await client.end(); } } async function createDatabaseIfNotExists(options: PostgresConnectionOptions, defaultDatabase = 'postgres') { const config = isPostgresUrl(options) ? parsePostgresUrl(options) : options; const query = async (client: Client) => { try { const existingDb = await client.query(` SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('${config.database}');`); if (existingDb.rowCount <= 0) { return await client.query(`CREATE DATABASE "${config.database}";`); } } catch (e) { console.warn(e); } return; }; return singleQueryConnection({ ...config, database: defaultDatabase }, query); } async function createSchemaIfNotExists(options: PostgresConnectionOptions, schema: string) { const query = (client: Client) => client.query(`CREATE SCHEMA IF NOT EXISTS "${schema}";`); return singleQueryConnection(options, query); } async function dropSchemaIfExists(options: PostgresConnectionOptions, schema: string) { const query = (client: Client) => client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE;`); return singleQueryConnection(options, query); } export { singleQueryConnection, createDatabaseIfNotExists, createSchemaIfNotExists, dropSchemaIfExists };
d0dbeca763055ab137b531b1c0be8a2d8ffd5c89
TypeScript
mikeparisstuff/amplify-cli
/packages/graphql-relational-schema-transformer/src/RelationalDBSchemaTransformerUtils.ts
2.96875
3
import { Kind, print, ObjectTypeDefinitionNode, NonNullTypeNode, DirectiveNode, NameNode, OperationTypeNode, FieldDefinitionNode, NamedTypeNode, InputValueDefinitionNode, ValueNode, OperationTypeDefinitionNode, SchemaDefinitionNode, ArgumentNode, ListValueNode, StringValueNode, InputObjectTypeDefinitionNode, DocumentNode} from 'graphql' const intTypes = [`INTEGER`, `INT`, `SMALLINT`, `TINYINT`, `MEDIUMINT`, `BIGINT`, `BIT`] const floatTypes = [`FLOAT`, `DOUBLE`, `REAL`, `REAL_AS_FLOAT`, `DOUBLE PRECISION`, `DEC`, `DECIMAL`, `FIXED`, `NUMERIC`] /** * Creates a non-null type, which is a node wrapped around another type that simply defines it is non-nullable. * * @param typeNode the type to be marked as non-nullable. * @returns a non-null wrapper around the provided type. */ export function getNonNullType(typeNode: NamedTypeNode): NonNullTypeNode { return { kind: Kind.NON_NULL_TYPE, type: typeNode } } /** * Creates a named type for the schema. * * @param name the name of the type. * @returns a named type with the provided name. */ export function getNamedType(name: string): NamedTypeNode { return { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: name } } } /** * Creates an input value definition for the schema. * * @param typeNode the type of the input node. * @param name the name of the input. * @returns an input value definition node with the provided type and name. */ export function getInputValueDefinition(typeNode: NamedTypeNode | NonNullTypeNode, name: string): InputValueDefinitionNode { return { kind: Kind.INPUT_VALUE_DEFINITION, name: { kind: Kind.NAME, value: name }, type: typeNode } } /** * Creates an operation field definition for the schema. * * @param name the name of the operation. * @param args the arguments for the operation. * @param type the type of the operation. * @param directives the directives (if any) applied to this field. In this context, only subscriptions will have this. * @returns an operation field definition with the provided name, args, type, and optionally directives. */ export function getOperationFieldDefinition(name: string, args: InputValueDefinitionNode[], type: NamedTypeNode, directives: ReadonlyArray<DirectiveNode>): FieldDefinitionNode { return { kind: Kind.FIELD_DEFINITION, name: { kind: Kind.NAME, value: name }, arguments: args, type: type, directives: directives } } /** * Creates a field definition node for the schema. * * @param fieldName the name of the field to be created. * @param type the type of the field to be created. * @returns a field definition node with the provided name and type. */ export function getFieldDefinition(fieldName: string, type: NonNullTypeNode | NamedTypeNode): FieldDefinitionNode { return { kind: Kind.FIELD_DEFINITION, name: { kind: Kind.NAME, value: fieldName }, type } } /** * Creates a type definition node for the schema. * * @param fields the field set to be included in the type. * @param typeName the name of the type. * @returns a type definition node defined by the provided fields and name. */ export function getTypeDefinition(fields: ReadonlyArray<FieldDefinitionNode>, typeName: string): ObjectTypeDefinitionNode { return { kind: Kind.OBJECT_TYPE_DEFINITION, name: { kind: Kind.NAME, value: typeName }, fields: fields } } /** * Creates an input type definition node for the schema. * * @param fields the fields in the input type. * @param typeName the name of the input type * @returns an input type definition node defined by the provided fields and */ export function getInputTypeDefinition(fields: ReadonlyArray<InputValueDefinitionNode>, typeName: string): InputObjectTypeDefinitionNode { return { kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, name: { kind: Kind.NAME, value: typeName }, fields: fields } } /** * Creates a name node for the schema. * * @param name the name of the name node. * @returns the name node defined by the provided name. */ export function getNameNode(name: string): NameNode { return { kind: Kind.NAME, value: name } } /** * Creates a list value node for the schema. * * @param values the list of values to be in the list node. * @returns a list value node containing the provided values. */ export function getListValueNode(values: ReadonlyArray<ValueNode>): ListValueNode { return { kind: Kind.LIST, values: values } } /** * Creates a simple string value node for the schema. * * @param value the value to be set in the string value node. * @returns a fleshed-out string value node. */ export function getStringValueNode(value: string): StringValueNode { return { kind: Kind.STRING, value: value } } /** * Creates a directive node for a subscription in the schema. * * @param mutationName the name of the mutation the subscription directive is for. * @returns a directive node defining the subscription. */ export function getDirectiveNode(mutationName: string): DirectiveNode { return { kind: Kind.DIRECTIVE, name: this.getNameNode('aws_subscribe'), arguments: [this.getArgumentNode(mutationName)] } } /** * Creates an operation type definition (subscription, query, mutation) for the schema. * * @param operationType the type node defining the operation type. * @param operation the named type node defining the operation type. */ export function getOperationTypeDefinition(operationType: OperationTypeNode, operation: NamedTypeNode): OperationTypeDefinitionNode { return { kind: Kind.OPERATION_TYPE_DEFINITION, operation: operationType, type: operation } } /** * Creates an argument node for a subscription directive within the schema. * * @param argument the argument string. * @returns the argument node. */ export function getArgumentNode(argument: string): ArgumentNode { return { kind: Kind.ARGUMENT, name: this.getNameNode('mutations'), value: this.getListValueNode([this.getStringValueNode(argument)]) } } /** * Given the DB type for a column, make a best effort to select the appropriate GraphQL type for * the corresponding field. * * @param dbType the SQL column type. * @returns the GraphQL field type. */ export function getGraphQLTypeFromMySQLType(dbType: string): string { const normalizedType = dbType.toUpperCase().split("(")[0] if (`BOOL` == normalizedType) { return `Boolean` } else if (`JSON` == normalizedType) { return `AWSJSON` } else if (`TIME` == normalizedType) { return `AWSTime` } else if (`DATE` == normalizedType) { return `AWSDate` } else if (`DATETIME` == normalizedType) { return `AWSDateTime` } else if (`TIMESTAMP` == normalizedType) { return `AWSTimestamp` } else if (intTypes.indexOf(normalizedType) > -1) { return `Int` } else if (floatTypes.indexOf(normalizedType) > -1) { return `Float` } return `String` }
0cb6c287dbc85d7e197dd1a2f83a71472060f8af
TypeScript
lifaon74/common-classes
/src/debug/observables-v4/observable/from/from-iterable/from-array.ts
2.84375
3
import { IObservable, IObservableUnsubscribeFunction, Observable } from '../../../core/observable'; import { IObserver } from '../../../core/observer'; export function fromArray<GValue>(array: ArrayLike<GValue>): IObservable<GValue> { return new Observable<GValue>((observer: IObserver<GValue>): IObservableUnsubscribeFunction => { let running: boolean = true; for (let i = 0, l = array.length; (i < l) && running; i++) { observer.emit(array[i]); } return (): void => { running = false; }; }); }
409f530b31dabea057b2ae948dd33ce98085a3cb
TypeScript
atmajs/memd
/src/persistance/StoreWorker.ts
2.765625
3
import { ICacheEntry, ICacheOpts } from '../Cache'; import { IStore } from './IStore'; export class StoreWorker <T = any> { public isAsync = false; private doNotWaitSave = false; constructor (private store: IStore, public options: ICacheOpts = {}) { this.isAsync = this.store.getAsync != null this.doNotWaitSave = options?.doNotWaitSave === true; } get?(key: string, ...args): ICacheEntry<T> { return this.store.get(key); } getAsync?(key: string, ...args): Promise<ICacheEntry<T>> { return this.store.getAsync(key, ...args); } save?(key: string, val: ICacheEntry<T>): void { this.store.save(key, val); } saveAsync?(key: string, val: ICacheEntry<T>): Promise<void> { let promise = this.store.saveAsync(key, val); if (this.doNotWaitSave === true) { return null; } return promise; } clear?(key: string): void { this.store.clear(key); } clearAsync?(key: string): Promise<void> { return this.store.clearAsync(key); } }
8cdf812a17d9278bd1bc5909f0ebc34f8c743bab
TypeScript
daimananshen/ProAngularExamples
/JavaScriptPrimer/usingTuples.ts
2.890625
3
import { TempConverter } from "./tempConverter"; let tuple: [string, string, string]; tuple = ["London", "raining", TempConverter.convertFtoC("38")]; console.log("----Using Tuples----"); console.log(`It is ${tuple[2]} degrees C and ${tuple[1]} in ${tuple[0]}`);
f03fe954e4ec4dc174fcfeee7b774c149238d57c
TypeScript
JVB-Dev/crud-users
/Node/server/src/controllers/UsersController.ts
2.78125
3
import { json, Request, Response } from "express"; import { User } from "../models/User"; import query from "../database/DB"; class UsersController { async Index(req: Request, res: Response) { try { const result = await query("SELECT * FROM usuarios ORDER BY ID"); return res.status(200).json(result.rows); } catch (error) { return res .status(400) .json({ message: `Occurred an error: ${error}`, error }); } } async Show(req: Request, res: Response) { const id = req.params.id; try { const user: User = ( await query("SELECT * FROM usuarios WHERE ID = $1", [id]) ).rows[0]; if (!user.id) return res .status(404) .json({ message: `User with id: ${id} not found.` }); return res.status(200).json(user); } catch (error) { return res .status(400) .json({ message: `Occurred an error: ${error}`, error }); } } async Create(req: Request, res: Response) { const { email, password, name } = req.body; try { const result = await query( "INSERT INTO usuarios (EMAIL, PASSWORD, NAME) VALUES ($1, $2, $3)", [email, password, name] ); if (result.rowCount === 0) return res .status(400) .json({ message: `An error was occurred, try again later.` }); return res.status(200).json({ message: "User has been created successfully." }); } catch (error) { return res .status(400) .json({ message: `Occurred an error: ${error}`, error }); } } async Update(req: Request, res: Response) { const id = req.params.id; try { let queryText = "UPDATE usuarios SET "; let setParams: string[] = []; let valueParams: any[] = []; Object.keys(req.body).forEach(function (key, i) { setParams.push(`${key} = $${i + 1}`); valueParams.push(req.body[key]); }); queryText += `${setParams.join(", ")} WHERE ID = ${id}`; const result = await query(queryText, valueParams); if (result.rowCount === 0) return res .status(400) .json({ message: `An error was occurred, try again later.` }); return res.status(200).json({message: `User has been updated successfully.`}); } catch (error) { return res .status(400) .json({ message: `Occurred an error: ${error}`, error }); } } async Delete(req: Request, res: Response) { const id = req.params.id; try { const result = await query(`DELETE FROM usuarios WHERE ID = $1`, [id]); if (result.rowCount === 0) return res .status(404) .json({ message: `User with id: ${id} not found.` }); return res.status(200).json(`User has been removed successfully.`); } catch (error) { return res .status(400) .json({ message: `Occurred an error: ${error}`, error }); } } } export default UsersController;
99155be10fd746eec2df2e25ceb480c96e7b0fde
TypeScript
colshacol/leenk
/source/client/shared/comps/Shortener/stores/ShortenerStore.ts
2.78125
3
import { observable, action, computed } from 'mobx' import { createLink } from '../../../api/link/createLink' export class ShortenerStore { @observable inputValue: string = '' @observable shortenedUrl: string = '' @action updateInputValue = ({ target: { value }}) => { this.inputValue = value } @action updateShortenedUrl = (value) => { this.shortenedUrl = value } createLink = async (e) => { if (e.key === 'Enter') { const result = await createLink(this.inputValue) // TODO: Present user with shortlink. this.updateShortenedUrl(result.short) } } @computed get inputValidity() { return String(validateUrl(this.inputValue)) } } // TODO: Improve expression to match url. const validateUrl = (url) => { if (!url.length) return true return /((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/g.test(url) }
1d53860bd9cdb59148386ccac19e99cba6f3a05b
TypeScript
jdanyow/aurelia-converters-sample
/src/examples/6/sort.js
2.921875
3
export class SortValueConverter { toView(array, propertyName, direction) { var factor = direction === 'ascending' ? 1 : -1; return array .slice(0) .sort((a, b) => { return (a[propertyName] - b[propertyName]) * factor }); } }
ebd4a162b454520ae72ddbadb2a9dd4d8d5b7589
TypeScript
TienCGC8JAVA/functions
/para.ts
3.796875
4
function userInfo1(name: string, age: number): string { return `My name is ${name}, ${age} years old`; } console.log(userInfo1("john", 20)); function userInfo2(name: string = "anna", age: number = 69): string { return `My name is ${name}, ${age} years old`; } console.log(userInfo2()); function userInfo3(name: string = "anna", age?: number): string { if (age == null) { return `My name is ${name}`; } return `My name is ${name}, ${age} years old`; } console.log(userInfo3()); console.log(userInfo3("henry", 23)); function totalLength(x: (string | any[]), y: (string[] | string)): number { return x.length + y.length; } console.log(totalLength('abc', ['123'])); console.log(totalLength([1, 'abc', 'def'], ['123', 'abc'])); console.log(totalLength([1, 'abc', 'def'], 'def'));
9c446ba884e705d7911aae126fcf40e504a26dd0
TypeScript
green-fox-academy/ndndnd24
/lecture/week 2/day 10/hard_ones_sort_that_list.ts
4.125
4
// Create a function that takes a list of numbers as parameter // Returns a list where the elements are sorted in ascending numerical order // Make a second boolean parameter, if it's `true` sort that list descending 'use strict'; function bubble(input: number[]) { let ascendingLine: number[] = []; let x = 0; let currentNumber: number = input[0]; let forLength: number = input.length; for (let index: number = 0; index < forLength; index++) { for (let i: number = 0; i < input.length; i++) { if (currentNumber >= input[i]) { currentNumber = input[i]; x = i; } } input.splice(x, 1); ascendingLine.push(currentNumber); currentNumber = input[0]; } console.log(ascendingLine); } function advancedBubble(input: number[], howToOrder: boolean) { if (howToOrder = false) { let ascendingLine: number[] = []; let x = 0; let currentNumber: number = input[0]; let forLength: number = input.length; for (let index: number = 0; index < forLength; index++) { for (let i: number = 0; i < input.length; i++) { if (currentNumber >= input[i]) { currentNumber = input[i]; x = i; } } input.splice(x, 1); ascendingLine.push(currentNumber); currentNumber = input[0]; } console.log(ascendingLine); } else { let ascendingLine: number[] = []; let x = 0; let currentNumber: number = input[0]; let forLength: number = input.length; for (let index: number = 0; index < forLength; index++) { for (let i: number = 0; i < input.length; i++) { if (currentNumber <= input[i]) { currentNumber = input[i]; x = i; } } input.splice(x, 1); ascendingLine.push(currentNumber); currentNumber = input[0]; } console.log(ascendingLine); } } // Example: bubble([4, 34, 12, 24, 9, 5]); advancedBubble([34, 12, 24, 9, 5], true); // should print [5, 9, 12, 24, 34] //console.log(advancedBubble([34, 12, 24, 9, 5], true)); // should print [34, 24, 12, 9, 5]
d2b46f8f7c271d837987a3dde81cddcacd9fbd66
TypeScript
gleb-mihalkov/mst-playground
/src/consts/StorageKey.ts
2.5625
3
/** * Ключ в localStorage. */ enum StorageKey { /** * Содержит токен для продления токена авторизации в RPC API. */ AUTH_TOKEN = 'auth_token', /** * Телефон, введённый при восстановлении пароля. */ RECOVERY_PHONE = 'recovery_phone', /** * Код подтверждения, введённый при восстановлении пароля. */ RECOVERY_CODE = 'recovery_code', } export default StorageKey;
cf2e5f9a03312b6576cb6e8b313953b98725e439
TypeScript
LYRA-Block-Lattice/lyra-api
/src/controllers/BlockController.ts
3.015625
3
import BlockModel, { IBlock } from "../models/BlockModel"; import { ApolloError } from "apollo-server"; /** * * @description holds crud operations for the Block entity */ /** * gets all Blocks * @param connection database connection * @returns {IBlock[]} Block list */ export const getAllBlocks = async (connection) => { let list: IBlock[]; try { list = await BlockModel(connection).find(); if (list != null && list.length > 0) { list = list.map((u) => { var x = u.transform(); return x; }); } } catch (error) { console.error("> getAllBlocks error: ", error); throw new ApolloError("Error retrieving all Blocks"); } return list; }; /** * gets Block by id * @param connection database connection * @param id Block id * @returns {IBlock | null} Block or null */ export const getBlock = async (connection, id: string) => { let Block: IBlock | null; try { Block = await BlockModel(connection).findById(id); if (Block != null) { Block = Block.transform(); } } catch (error) { console.error("> getBlock error: ", error); throw new ApolloError("Error retrieving Block with id: " + id); } return Block; };
865c2b624d874c2a539e7f92955040b7e3e7ccc1
TypeScript
Yupeng-li/redux-simple-state
/src/StateContainer.ts
2.65625
3
import ld from "lodash"; import { combineReducers } from "redux"; import { ActionConfig } from "./types/scheme"; import { LooseObject } from "./types/LooseObject"; import { AnyAction, Reducer } from "redux"; export default class StateContainer implements LooseObject { _name: string; _initialValue: any | undefined; _parent: StateContainer | null; _children: Array<StateContainer>; _actions: Array<ActionConfig<any>>; selector: ((state: any) => any | undefined) | null; [extraProps: string]: any; constructor(name: string, initialValue: any) { this._name = name; this._initialValue = initialValue; this._parent = null; this._children = []; this.selector = null; this._actions = []; } get _path(): string { if (this._parent) { return this._parent._path.concat(".", this._name); } else { return this._name; } } get _reducer(): Reducer { const self = this; let reducerMap = self._actions.reduce((map: LooseObject, action) => { let actionType = self._path.concat(".", action.name); map[actionType] = action.reducer; return map; }, {}); let subReducerMap = self._children.reduce( (subReducer: LooseObject, child) => { subReducer[child._name] = child._reducer; return subReducer; }, {} ); let subReducer = ld.isEmpty(subReducerMap) ? null : combineReducers(subReducerMap); return (state = self._initialValue, action: AnyAction) => { let reducer = reducerMap[action.type]; if (reducer) { return reducer(state, action); } else if (subReducer) { return subReducer(state, action); } else return state; }; } }
d0148b166c7c1fe6cfa60d19c6417815d3f089c6
TypeScript
acecor-cotep/role-and-task
/lib/src/RoleSystem/Role/ARole.d.ts
2.8125
3
/// <reference types="node" /> import Errors from '../../Utils/Errors.js'; import TaskHandler from '../Handlers/TaskHandler.js'; import ATask from '../Tasks/ATask.js'; export interface DisplayMessage { str: string; carriageReturn?: boolean; out?: NodeJS.WriteStream; from?: number | string; time?: number; tags?: string[]; } export interface ArgsObject { [key: string]: any; } /** * PROGRAM process have 0 or + defined Role * * A Role can be described as a purpose to fulfill * * Example: Master or Slave -> (The purpose of Master is to manage Slave) * * A ROLE MUST BE DEFINED AS A SINGLETON (Which means the implementation of getInstance) * * A ROLE CAN BE APPLIED ONLY ONCE (Ex: You can apply the ServerAPI only once, can't apply twice the ServerAPI Role for a PROGRAM instance) * @interface */ export default abstract class ARole { name: string; id: number; protected active: boolean; protected taskHandler: TaskHandler | false; protected referenceStartTime: number; constructor(); getReferenceStartTime(): number; /** * Setup a taskHandler to the role * Every Role have its specific tasks */ setTaskHandler(taskHandler: TaskHandler | false): void; getTaskHandler(): TaskHandler | false; getTask(idTask: string): Promise<ATask>; startTask(idTask: string, args: any): Promise<unknown>; abstract displayMessage(param: DisplayMessage): Promise<void>; stopTask(idTask: string): Promise<unknown>; stopAllTask(): Promise<unknown>; getTaskListStatus(): { name: string; id: string; isActive: boolean; }[] | Errors; isActive(): boolean; abstract start(...args: unknown[]): Promise<unknown>; abstract stop(...args: unknown[]): Promise<unknown>; buildHeadBodyMessage(head: string, body: unknown): string; abstract takeMutex(id: string): Promise<void>; abstract releaseMutex(id: string): Promise<void>; }
21edba85bc1a53a5862c3be2906acc6e6033695a
TypeScript
gropax/ontos
/Ontos.Web/ClientApp/src/app/models/graph.ts
3.109375
3
export class Page { constructor( public id: string, public content: string, public type: string, public references: Reference[] = []) { } } export class PageType { constructor( public id: string, public label: string, public icon: string) { } public static UNKNOWN = new PageType("Unknown", "Unknown", "fas fa-question"); public static THEORY = new PageType("Theory", "Theory", "fas fa-atom"); public static CONCEPT = new PageType("Concept", "Concept", "far fa-lightbulb"); static all() { return [ this.UNKNOWN, this.THEORY, this.CONCEPT ]; } public static default = PageType.UNKNOWN; public static parse(id: string) { return this.all().find(pageType => pageType.id == id); } } export class Reference { constructor( public id: number, public pageId: number, public expression: Expression) { } } export class Expression { constructor( public id: number, public language: string, public label: string) { } } export class Relation { constructor( public id: string, public type: string, public originId: string, public targetId: string) { } } export class RelatedPage { constructor( public id: string, public type: string, public originId: string, public target: Page) { } } export class RelationType { constructor( public label: string, public directed: boolean, public acyclic: boolean) { } public static INCLUSION = new RelationType('INCLUDE', true, true); public static INTERSECTION = new RelationType('INTERSECT', false, false); } export class DirectedRelationType { constructor( public label: string, public type: RelationType, public reversed: boolean) { } public static INCLUDES = new DirectedRelationType("Includes", RelationType.INCLUSION, false); public static INCLUDED_IN = new DirectedRelationType("Is included in", RelationType.INCLUSION, true); public static INTERSECTS = new DirectedRelationType("Intersects", RelationType.INTERSECTION, false); static all() { return [this.INCLUDES, this.INCLUDED_IN, this.INTERSECTS]; } } export class NewPage { constructor( public content: string, public expression: NewExpression = null) { } } export class PageSearch { constructor( public language: string, public text: string) { } } export class PageSearchResult { constructor( public pageId: string, public score: number, public expressions: string[]) { } } export class NewExpression { constructor( public language: string, public label: string) { } } export class NewReference { constructor( public pageId: number, public expression: NewExpression) { } } export class NewRelation { constructor( public type: RelationType, public originId: string, public targetId: string) { } public static create(type: DirectedRelationType, originId: string, targetId: string) { if (type.reversed) [originId, targetId] = [targetId, originId]; return new NewRelation(type.type, originId, targetId); } public toParams() { return { type: this.type.label, originId: this.originId, targetId: this.targetId, }; } } export class NewRelatedPage { constructor( public type: DirectedRelationType, public expression: NewExpression, public content: string) { } public toParams() { return { type: this.type.type.label, reversed: this.type.reversed, expression: this.expression, content: this.content, }; } } export class UpdatePage { constructor( public id: string, public content: string, public type: string) { } }
2c5d25b8e4b93d016136c73dd875864333e9ba30
TypeScript
MartinBenjamin/AngularCore
/Web/ClientApp/src/app/Ontology/DLSafeRule.ts
2.609375
3
import { BuiltIn, Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEqual } from './Atom'; import { Axiom } from './Axiom'; import { EavStore } from './EavStore'; import { IAxiom } from "./IAxiom"; import { IClassExpression } from "./IClassExpression"; import { IClassExpressionSelector } from './IClassExpressionSelector'; import { IDataRange } from "./IDataRange"; import { IsConstant, IsVariable } from './IEavStore'; import { IIndividual } from "./IIndividual"; import { IOntology } from './IOntology'; import { IDataPropertyExpression, IObjectPropertyExpression, IPropertyExpression } from "./IPropertyExpression"; import { IPropertyExpressionSelector } from './IPropertyExpressionSelector'; import { Wrap, Wrapped, WrapperType } from './Wrapped'; // http://www.cs.ox.ac.uk/files/2445/rulesyntaxTR.pdf /* axioms ::= { Axiom | Rule | DGAxiom } Rule ::= DLSafeRule | DGRule DLSafeRule ::= DLSafeRule ‘(’ {Annotation} ‘Body’ ‘(’ {Atom} ‘)’ ‘Head’ ‘(’ {Atom} ‘)’ ‘)’ Atom ::= ‘ClassAtom’ ‘(’ ClassExpression IArg ‘)’ | ‘DataRangeAtom’ ‘(’ DataRange DArg ‘)’ | ‘ObjectPropertyAtom’ ‘(’ ObjectPropertyExpression IArg IArg ‘)’ | ‘DataPropertyAtom’ ‘(’ DataProperty IArg DArg ‘)’ | ‘BuiltInAtom’ ‘(’ IRI DArg {DArg} ‘)’ | ‘SameIndividualAtom’ ‘(’ IArg IArg ‘)’ | ‘DifferentIndividualsAtom’ ‘(’ IArg IArg‘)’ IArg ::= IndividualID | ‘IndividualVariable’ ‘(’ IRI ‘)’ DArg ::= Literal | ‘LiteralVariable’ ‘(’ IRI ‘)’ DGRule ::= DescriptionGraphRule ‘(’ {Annotation} ‘Body’ ‘(’ {DGAtom} ‘)’ ‘Head’ ‘(’ {DGAtom} ‘)’ ‘)’ DGAtom ::= ‘ClassAtom’ ‘(’ ClassExpression IArg ‘)’ | ‘ObjectPropertyAtom’ ‘(’ ObjectPropertyExpression IArg IArg ‘)’ DGAxiom ::= ‘DescriptionGraph’ ‘(’ {Annotation} DGName DGNodes DGEdges MainClasses‘)’ DGName ::= IRI DGNodes ::= ‘Nodes’‘(’ NodeAssertion {NodeAssertion } ‘)’ NodeAssertion ::= ‘NodeAssertion’‘(’ Class DGNode ‘)’ DGNode ::= IRI DGEdges ::= ‘Edges’‘(’ EdgeAssertion {EdgeAssertion } ‘)’ EdgeAssertion ::= ‘EdgeAssertion’ ‘(’ ObjectProperty DGNode DGNode‘)’ MainClasses ::= ‘MainClasses’ ‘(’ Class {Class } ‘)’ */ export type IndividualVariable = string; export type IArg = IIndividual | IndividualVariable; export type LiteralVariable = string; export type DArg = any | LiteralVariable; export type Arg = IArg | DArg; export interface IAtom { Select<TResult>(selector: IAtomSelector<TResult>): TResult } export interface IDLSafeRule extends IAxiom { readonly Head: IAtom[], readonly Body: IAtom[] } export interface IClassAtom extends IAtom { readonly ClassExpression: IClassExpression; readonly Individual : IArg; } export interface IDataRangeAtom extends IAtom { readonly DataRange: IDataRange; readonly Value : DArg; } export interface IPropertyAtom extends IAtom { readonly PropertyExpression: IPropertyExpression; readonly Domain : IArg; readonly Range : Arg; } export interface IObjectPropertyAtom extends IPropertyAtom { readonly ObjectPropertyExpression: IObjectPropertyExpression; readonly Range : IArg; } export interface IDataPropertyAtom extends IPropertyAtom { readonly DataPropertyExpression: IDataPropertyExpression; readonly Range : DArg; } export interface IComparisonAtom extends IAtom { readonly Lhs: Arg; readonly Rhs: Arg; } export interface ILessThanAtom extends IComparisonAtom {}; export interface ILessThanOrEqualAtom extends IComparisonAtom {}; export interface IEqualAtom extends IComparisonAtom {}; export interface INotEqualAtom extends IComparisonAtom {}; export interface IGreaterThanOrEqualAtom extends IComparisonAtom {}; export interface IGreaterThanAtom extends IComparisonAtom {}; export interface IAtomSelector<TResult> { Class (class$ : IClassAtom ): TResult; DataRange (dataRange : IDataRangeAtom ): TResult; ObjectProperty (objectProperty : IObjectPropertyAtom ): TResult; DataProperty (dataProperty : IDataPropertyAtom ): TResult; LessThan (lessThan : ILessThanAtom ): TResult; LessThanOrEqual (lessThanOrEqual : ILessThanOrEqualAtom ): TResult; Equal (equal : IEqualAtom ): TResult; NotEqual (notEqual : INotEqualAtom ): TResult; GreaterThanOrEqual(greaterThanOrEqual: IGreaterThanOrEqualAtom): TResult; GreaterThan (greaterThan : IGreaterThanAtom ): TResult; } export interface IDLSafeRuleBuilder { IndividualVariable(name: string): IndividualVariable; LiteralVariable(name: string): LiteralVariable; ClassAtom(ce: IClassExpression, individual: IArg): IClassAtom; DataRangeAtom(dr: IDataRange, value: DArg): IDataRangeAtom; ObjectPropertyAtom(ope: IObjectPropertyExpression, domain: IArg, range: IArg): IObjectPropertyAtom; DataPropertyAtom(dpe: IDataPropertyExpression, domain: IArg, range: DArg): IDataPropertyAtom; LessThan (lhs: Arg, rhs: Arg): ILessThanAtom ; LessThanOrEqual (lhs: Arg, rhs: Arg): ILessThanOrEqualAtom ; Equal (lhs: Arg, rhs: Arg): IEqualAtom ; NotEqual (lhs: Arg, rhs: Arg): INotEqualAtom ; GreaterThanOrEqual(lhs: Arg, rhs: Arg): IGreaterThanOrEqualAtom; GreaterThan (lhs: Arg, rhs: Arg): IGreaterThanAtom ; Rule( head: IAtom[], body: IAtom[]): IDLSafeRule; } export class DLSafeRuleBuilder implements IDLSafeRuleBuilder { constructor( private _ontology: IOntology ) { } IndividualVariable( name: string ): string { return name; } LiteralVariable( name: string ): string { return name; } ClassAtom( ce : IClassExpression, individual: IArg ): IClassAtom { return new ClassAtom( ce, individual); } DataRangeAtom( dr : IDataRange, value: DArg ): IDataRangeAtom { return new DataRangeAtom( dr, value); } ObjectPropertyAtom( ope : IObjectPropertyExpression, domain: IArg, range : IArg ): IObjectPropertyAtom { return new ObjectPropertyAtom( ope, domain, range); } DataPropertyAtom( dpe : IDataPropertyExpression, domain: IArg, range : any ): IDataPropertyAtom { return new DataPropertyAtom( dpe, domain, range); } LessThan( lhs: any, rhs: any ): ILessThanAtom { return new LessThanAtom(lhs, rhs); } LessThanOrEqual( lhs: any, rhs: any ): ILessThanOrEqualAtom { return new LessThanOrEqualAtom(lhs, rhs); } Equal( lhs: any, rhs: any ): IEqualAtom { return new EqualAtom(lhs, rhs); } NotEqual( lhs: any, rhs: any ): INotEqualAtom { const notEqual = { Lhs: lhs, Rhs: rhs, Select: <TResult>(selector: IAtomSelector<TResult>): TResult => selector.NotEqual(notEqual) }; return new NotEqualAtom(lhs, rhs); } GreaterThanOrEqual( lhs: any, rhs: any ): IGreaterThanOrEqualAtom { return new GreaterThanOrEqualAtom(lhs, rhs); } GreaterThan( lhs: any, rhs: any ): IGreaterThanAtom { return new GreaterThanAtom(lhs, rhs); } Rule( head: IAtom[], body: IAtom[] ): IDLSafeRule { return new DLSafeRule( this._ontology, head, body); } } export class ClassAtom implements IClassAtom { constructor( public readonly ClassExpression: IClassExpression, public readonly Individual : IArg ) { } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { return selector.Class(this); } } export class DataRangeAtom implements IDataRangeAtom { constructor( public readonly DataRange: IDataRange, public readonly Value : DArg ) { } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { return selector.DataRange(this); } } export abstract class PropertyAtom implements IPropertyAtom { constructor( public readonly PropertyExpression: IPropertyExpression, public readonly Domain : IArg, public readonly Range : Arg ) { } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { throw new Error("Method not implemented."); } } export class ObjectPropertyAtom extends PropertyAtom implements IObjectPropertyAtom { constructor( public readonly ObjectPropertyExpression: IObjectPropertyExpression, domain : IArg, public readonly Range : IArg ) { super( ObjectPropertyExpression, domain, Range); } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { return selector.ObjectProperty(this); } } export class DataPropertyAtom extends PropertyAtom implements IDataPropertyAtom { constructor( public readonly DataPropertyExpression: IDataPropertyExpression, domain : IArg, public readonly Range : DArg ) { super( DataPropertyExpression, domain, Range); } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { return selector.DataProperty(this); } } export abstract class ComparisonAtom implements IComparisonAtom { constructor( public Lhs: Arg, public Rhs: Arg, ) { } Select<TResult>( selector: IAtomSelector<TResult> ): TResult { throw new Error("Method not implemented."); } } export class LessThanAtom extends ComparisonAtom implements ILessThanAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.LessThan (this);}}; export class LessThanOrEqualAtom extends ComparisonAtom implements ILessThanOrEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.LessThanOrEqual (this);}}; export class EqualAtom extends ComparisonAtom implements IEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.Equal (this);}}; export class NotEqualAtom extends ComparisonAtom implements INotEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.NotEqual (this);}}; export class GreaterThanOrEqualAtom extends ComparisonAtom implements IGreaterThanOrEqualAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.GreaterThanOrEqual(this);}}; export class GreaterThanAtom extends ComparisonAtom implements IGreaterThanAtom { constructor(lhs: Arg, rhs: Arg) { super(lhs, rhs); } Select<TResult>(selector: IAtomSelector<TResult>): TResult { return selector.GreaterThan (this);}}; export class DLSafeRule extends Axiom implements IDLSafeRule { constructor( ontology : IOntology, public readonly Head: IAtom[], public readonly Body: IAtom[] ) { super(ontology); } } export function IsDLSafeRule( axiom: any ): axiom is IDLSafeRule { return axiom instanceof DLSafeRule; } export interface ICache<TAtom> { Set( atom : IAtom, wrapped: TAtom): void; Get(atom: IAtom): TAtom } export class AtomInterpreter<T extends WrapperType> implements IAtomSelector<Wrapped<T, object[] | BuiltIn>> { constructor( protected _wrap : Wrap<T>, private _propertyExpressionInterpreter: IPropertyExpressionSelector<Wrapped<T, [any, any][]>>, private _classExpressionInterpreter : IClassExpressionSelector<Wrapped<T, Set<any>>> ) { } Class( class$: IClassAtom ): Wrapped<T, object[] | BuiltIn> { if(IsVariable(class$.Individual)) return this._wrap( individuals => [...individuals].map( individual => { return { [<string>class$.Individual]: individual }; }), class$.ClassExpression.Select(this._classExpressionInterpreter)); return this._wrap( individuals => individuals.has(class$.Individual) ? [{}] : [], class$.ClassExpression.Select(this._classExpressionInterpreter)); } DataRange( dataRange: IDataRangeAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => ( substitutions: Iterable<object> ) => { if(IsConstant(dataRange.Value)) return dataRange.DataRange.HasMember(dataRange.Value) ? substitutions : []; return [...substitutions].filter(substitution => dataRange.DataRange.HasMember(substitution[dataRange.Value])); }); } ObjectProperty( objectProperty: IObjectPropertyAtom ): Wrapped<T, object[] | BuiltIn> { return this.Property(objectProperty); } DataProperty( dataProperty: IDataPropertyAtom ): Wrapped<T, object[] | BuiltIn> { return this.Property(dataProperty); } private Property( property: IPropertyAtom ): Wrapped<T, object[]> { return this._wrap( EavStore.Substitute([property.Domain, property.Range]), property.PropertyExpression.Select(this._propertyExpressionInterpreter)); } LessThan( lessThan: ILessThanAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => LessThan(lessThan.Lhs, lessThan.Rhs)); } LessThanOrEqual( lessThanOrEqual: ILessThanOrEqualAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => LessThanOrEqual(lessThanOrEqual.Lhs, lessThanOrEqual.Rhs)); } Equal( equal: IEqualAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => Equal(equal.Lhs, equal.Rhs)); } NotEqual( notEqual: INotEqualAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(()=> NotEqual(notEqual.Lhs, notEqual.Rhs)); } GreaterThanOrEqual( greaterThanOrEqual: IGreaterThanOrEqualAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => GreaterThanOrEqual(greaterThanOrEqual.Lhs, greaterThanOrEqual.Rhs)); } GreaterThan( greaterThan: IGreaterThanAtom ): Wrapped<T, object[] | BuiltIn> { return this._wrap(() => GreaterThan(greaterThan.Lhs, greaterThan.Rhs)); } Atoms( atoms: IAtom[] ): Wrapped<T, object[]> { return this._wrap( EavStore.Conjunction(), ...atoms.map(atom => atom.Select(this))); } } export function RuleContradictionInterpreter<T extends WrapperType>( wrap : Wrap<T>, interpreter: AtomInterpreter<T> ): (rule: IDLSafeRule) => Wrapped<T, object[]> { return (rule: IDLSafeRule) => wrap( (head, body) => body.reduce<object[]>( (failed, x) => { if(!head.some(y => { for(const key in x) if(key in y && x[key] !== y[key]) return false; return true; })) failed.push(x); return failed; }, []), interpreter.Atoms(rule.Head), interpreter.Atoms(rule.Body)); }
9a20819af0b0fcc15d693977866d31b820588a59
TypeScript
rafaelssp/TestHelloMedtime
/TestHelloMedtime/src/app/components/ficha/filtro-nome.pipe.ts
2.515625
3
import { Pipe, PipeTransform } from '@angular/core'; import { FichaComponent } from '../../components/ficha/ficha.component'; @Pipe({ name: 'filtraFichaNome', pure: false }) export class FiltroNomePipe implements PipeTransform { transform(fichas: FichaComponent[], nome: string): FichaComponent[] { nome = nome.toUpperCase(); return fichas.filter(f => f.nomeCompleto.toUpperCase().includes(nome)); } }
87e52e9eba09796d61ee50f1c1fc970042f82681
TypeScript
liuheyu/typescript_RPC_demo
/src/rpc.ts
3.578125
4
/** ═════════🏳‍🌈 超轻量级的远程调用,完备的类型提示! 🏳‍🌈═════════ */ import type * as apis from "./apis"; type apis = typeof apis; type method = keyof apis; /** Remote call , 会就近的选择是远程调用还是使用本地函数 */ export function RC<K extends method>( method: K, data: Parameters<apis[K]>, ): Promise<unPromise<ReturnType<apis[K]>>> { //@ts-ignore if (process.browser === true) { return fetch("/rpc", { method: "POST", body: JSON.stringify({ method, data }), headers: { "content-type": "application/json", }, }).then((r) => r.json()); } else { //@ts-ignore return import("./apis/index").then(async (r: any) => { return await r[method](...data); }); } } /** 解开 promise 类型包装 */ declare type unPromise<T> = T extends Promise<infer R> ? R : T; // 示例 1 直接使用 RC RC("currentTime", []).then((r) => console.log("服务器当前时间", r)); RC("currentTime2", [true]).then((r) => console.log("服务器当前时间本地化", r)); /** 包装了一次的 RC 方便跳转到函数定义 */ export const API = new Proxy( {}, { get(target, p: method) { return (...arg: any) => RC(p, arg); }, }, ) as apisPromiseify; /** apis 中包含的方法可能不是返回 promise 的,但 RC 调用后的一定是返回 promsie */ type apisPromiseify = { readonly [K in keyof apis]: ( ...arg: Parameters<apis[K]> ) => Promise<unPromise<ReturnType<apis[K]>>>; }; // 示例 2 通过 API 对象调用对应方法,这里的优点是可以直接跳转到对应函数的源码处 API.currentTime().then((r) => console.log("服务器当前时间", r)); API.currentTime2(true).then((r) => console.log("服务器当前时间本地化", r));
a46e3a9701a3c23a35d6cd20b7acba2f9d7e2cb0
TypeScript
jesus-crysist/text-highlighter
/src/app/state/text-highlighter-store.service.spec.ts
2.640625
3
import { TestBed } from '@angular/core/testing'; import { Action, ActionTypes } from 'src/app/state/actions'; import { HighlightModel, INITIAL_STATE } from 'src/app/state/state'; import { TextHighlighterStore } from 'src/app/state/text-highlighter-store.service'; const highlightMocks = [ { color: 'red', text: 'brown fox'}, { color: 'green', text: 'lazy dog'} ]; describe('TextHighlighterStore', () => { let service: TextHighlighterStore; beforeEach(() => { TestBed.configureTestingModule({ providers: [TextHighlighterStore] }); service = TestBed.get(TextHighlighterStore); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should contain "state$" Observables and initial value', () => { expect(service.state$).toBeDefined(); expect(service.state$.subscribe).toBeDefined(); expect(service.state).toEqual(INITIAL_STATE); }); it('should be able to get Observable for single property', () => { expect(service.getValueState('pickedColor').subscribe).toBeTruthy(); }); it('should dispatch "ColorAddValues" action', () => { const colors = ['red', 'yellow', 'green']; service.dispatch(new Action(ActionTypes.ColorAddValues, colors)); expect(service.state.colors).toBe(colors); expect(service.state.pickedColor).toBeNull(); expect(service.state.highlights.length).toBe(0); }); it('should dispatch "ColorPicked" action', () => { const pickedColor = 'blue'; service.dispatch(new Action(ActionTypes.ColorPicked, pickedColor)); expect(service.state.pickedColor).toBe(pickedColor); expect(service.state.highlights.length).toBe(0); }); it('should dispatch "HighlightAddValues" action', () => { service.dispatch(new Action(ActionTypes.HighlightAddValues, highlightMocks)); expect(service.state.highlights.length).toBe(2); expect(service.state.pickedColor).toBeNull(); }); it('should dispatch "HighlightAdd" action', () => { const highlightedText = new HighlightModel('quick brown fox', 'blue'); service.dispatch(new Action(ActionTypes.HighlightAdd, highlightedText)); expect(service.state.highlights[0]).toEqual(highlightedText); expect(service.state.pickedColor).toBeNull(); }); it('should dispatch "HighlightRemove" action', () => { service.dispatch(new Action(ActionTypes.HighlightAddValues, highlightMocks)); service.dispatch(new Action(ActionTypes.HighlightRemove, highlightMocks[1])); expect(service.state.highlights.length).toEqual(1); expect(service.state.pickedColor).toBeNull(); }); });
b5ae9a61c6b23e5d3684297700594d9f001271c7
TypeScript
stjordanis/snyk-gradle-plugin
/lib/errors/missing-sub-project-error.ts
2.765625
3
export class MissingSubProjectError extends Error { public name = 'MissingSubProjectError'; public subProject: string; public allProjects: string[]; constructor(subProject: string, allProjects: string[]) { super( `Specified sub-project not found: "${subProject}". ` + `Found these projects: ${allProjects.join(', ')}`, ); this.subProject = subProject; this.allProjects = allProjects; Error.captureStackTrace(this, MissingSubProjectError); } }
581fc9c836ce80c75e5c6f5bed29b47a6c204bf9
TypeScript
Leies-202/ai
/src/serifs.ts
3
3
// せりふ export default { core: { setNameOk: (name) => `わかった!これからは${name}って呼ぶね!`, san: "さん付けした方がいい?(「はい」か「いいえ」で答えてね〜)", yesOrNo: "「はい」か「いいえ」しかわからないよ...", hello: (name) => (name ? `こんにちは、${name}♪` : `こんにちは♪`), helloNight: (name) => (name ? `こんばんは、${name}♪` : `こんばんは♪`), goodMorning: (tension, name) => name ? `おはよう、${name}!${tension}` : `おはよう!${tension}`, /* goodMorning: { normal: (tension, name) => name ? `おはよう、${name}!${tension}` : `おはよう!${tension}`, hiru: (tension, name) => name ? `おはよう、${name}!${tension}もうお昼だよ?${tension}` : `おはよう!${tension}もうお昼だよ?${tension}`, }, */ goodNight: (name) => name ? `おやすみ、${name}!いい夢見てね〜` : "おやすみ!いい夢見てね〜", omedeto: (name) => (name ? `ありがとう、${name}♪` : "ありがとう♪"), erait: { general: (name) => name ? [`${name}、今日もえらい!`, `${name}、今日もえらいね~♪`] : [`今日もえらい!`, `今日もえらいね~♪`], specify: (thing, name) => name ? [`${name}、${thing}てえらい!`, `${name}、${thing}てえらいね~♪`] : [`${thing}てえらい!`, `${thing}てえらいね~♪`], specify2: (thing, name) => name ? [`${name}、${thing}でえらい!`, `${name}、${thing}でえらいね~♪`] : [`${thing}でえらい!`, `${thing}でえらいね~♪`], }, okaeri: { love: (name) => name ? [`おかえり、${name}♪`, `おかえりなさいっ、${name}っ。`] : [ "おかえり♪ゆっくり休んでね〜♪", "おかえりなさいっ、ご主人様っ。ゆっくり休んでね〜♪", ], love2: (name) => name ? `おっかえり~${name}っっ!!!ゆっくり休んでね!` : "おっかえり~ご主人様っっ!!!ゆっくり休んでね!", normal: (name) => (name ? `おかえり、${name}!` : "おかえり!"), }, itterassyai: { love: (name) => name ? `いってらっしゃい、${name}♪気をつけてね〜。` : "いってらっしゃい♪気をつけてね〜。", normal: (name) => name ? `いってらっしゃい、${name}!` : "いってらっしゃい!", }, tooLong: "長すぎるよ〜...", invalidName: "うーん、ちょっと発音が難しいなぁ…", requireMoreLove: "もっと仲良くなったら考えてあげる〜", nadenade: { normal: "ひゃっ…! びっくりした~", love2: ["わわっ… 恥ずかしいよぉ", "あうぅ… 恥ずかしいなぁ…"], love3: [ "んぅ… ありがとう♪", "わっ、なんだか落ち着く♪", "くぅんっ… 安心するなぁ…", "眠くなってきちゃった…", ], hate1: "…っ! やめて...", hate2: "触らないでっ!", hate3: "近寄らないでっ!", hate4: "やめて...通報するよ?", }, kawaii: { normal: ["ありがとう♪", "(照れちゃう…)"], love: ["嬉しい♪", "(そ、そんなの照れちゃう…)"], hate: "…ありがとう", }, suki: { normal: "えっ… ありがとう…♪", love: (name) => `私もその… ${name}のこと好きだよ!`, hate: null, }, hug: { normal: "ぎゅー...", love: "ぎゅーっ♪", hate: "離れて...", }, humu: { love: "え、えっと…… ふみふみ……… どう…?", normal: "えぇ... それはちょっと...", hate: "……", }, batou: { love: "えっと…、お、おバカっ!!!", normal: "(じとー…)", hate: "…頭大丈夫?", }, itai: (name) => name ? `${name}、大丈夫…? いたいのいたいの飛んでけ~!` : "大丈夫…? いたいのいたいの飛んでけ~!", ote: { normal: "くぅん... 私わんちゃんじゃないよ...?", love1: "わん!", love2: "わんわん♪", }, shutdown: "私まだ眠くないよ...?", transferNeedDm: "わかったけど...それはチャットで話さない?", transferCode: (code) => `わかった!\n合言葉は「${code}」だよ!`, transferFailed: "うーん、合言葉が間違ってなぁい?", transferDone: (name) => name ? `はっ...! おかえり、${name}!` : `はっ...! おかえり!`, }, keyword: { learned: (word, reading) => `(${word}..... ${reading}..... 覚えたっ!)`, remembered: (word) => `${word}`, }, dice: { done: (res) => `${res} だよ!`, }, birthday: { happyBirthday: (name) => name ? `お誕生日おめでとう、${name}🎉` : "お誕生日おめでとう🎉", }, /** * リバーシ */ reversi: { /** * リバーシへの誘いを承諾するとき */ ok: "いいよ~", /** * リバーシへの誘いを断るとき */ decline: "ごめんなさい、マスターに今リバーシはしちゃダメって言われてるの...", /** * 対局開始 */ started: (name, strength) => `対局を${name}と始めたよ! (強さ${strength})`, /** * 接待開始 */ startedSettai: (name) => `(${name}の接待を始めたよ)`, /** * 勝ったとき */ iWon: (name) => `${name}に勝ったよ♪`, /** * 接待のつもりが勝ってしまったとき */ iWonButSettai: (name) => `(${name}に接待で勝っちゃった...)`, /** * 負けたとき */ iLose: (name) => `${name}に負けちゃった...`, /** * 接待で負けてあげたとき */ iLoseButSettai: (name) => `(${name}に接待で負けてあげたよ...♪)`, /** * 引き分けたとき */ drawn: (name) => `${name}と引き分けたよ~`, /** * 接待で引き分けたとき */ drawnSettai: (name) => `(${name}に接待で引き分けちゃった...)`, /** * 相手が投了したとき */ youSurrendered: (name) => `${name}が投了しちゃった`, /** * 接待してたら相手が投了したとき */ settaiButYouSurrendered: (name) => `(${name}を接待していたら投了されちゃった... ごめんなさい)`, }, /** * 数当てゲーム */ guessingGame: { /** * やろうと言われたけど既にやっているとき */ alreadyStarted: "え、ゲームは既に始まってるよ!", /** * タイムライン上で誘われたとき */ plzDm: "メッセージでやろうねっ!", /** * ゲーム開始 */ started: "0~100の秘密の数を当ててみて♪", /** * 数字じゃない返信があったとき */ nan: "数字でお願い!「やめる」と言ってゲームをやめることもできるよ!", /** * 中止を要求されたとき */ cancel: "わかった~。ありがとう♪", /** * 小さい数を言われたとき */ grater: (num) => `${num}より大きいよ`, /** * 小さい数を言われたとき(2度目) */ graterAgain: (num) => `もう一度言うけど${num}より大きいよ!`, /** * 大きい数を言われたとき */ less: (num) => `${num}より小さいよ`, /** * 大きい数を言われたとき(2度目) */ lessAgain: (num) => `もう一度言うけど${num}より小さいよ!`, /** * 正解したとき */ congrats: (tries) => `正解🎉 (${tries}回目で当てたよ)`, }, /** * 数取りゲーム */ kazutori: { alreadyStarted: "今ちょうどやってるよ~", matakondo: "また今度やろっ!", intro: (minutes) => `みんな~!数取りゲームしよう!\n0~100の中で最も大きい数字を取った人が勝ちだよ!他の人と被ったらだめだよ~\n制限時間は${minutes}分!数字はこの投稿にリプライで送ってね!`, finish: "ゲームの結果発表~!!", finishWithWinner: (user, name) => name ? `今回は${user}さん(${name})の勝ち!またやろっ♪` : `今回は${user}さんの勝ち!またやろっ♪`, finishWithNoWinner: "今回は勝者はいなかったよ... またやろっ♪", onagare: "参加者が集まらなかったからお流れになっちゃった...", }, /** * 絵文字生成 */ emoji: { suggest: (emoji) => `こんなのはどう?→${emoji}`, }, /** * 占い */ fortune: { cw: (name) => name ? `私が今日の${name}の運勢を占ったよ...` : "私が今日の君の運勢を占ったよ...", }, /** * タイマー */ timer: { set: "計るね~", invalid: "うーん...?", tooLong: "長すぎるよ…", notify: (time, name) => name ? `${name}、${time}経ったよ!` : `${time}経ったよ!`, }, /** * リマインダー */ reminder: { invalid: "うーん...?", reminds: "やること一覧だよっ!", notify: (name) => (name ? `${name}、これやった?` : `これやった覚えある?`), notifyWithThing: (thing, name) => name ? `${name}、「${thing}」やった?` : `「${thing}」やった覚えある?`, done: (name) => name ? [ `よく出来たね、${name}♪`, `${name}、さすがっ!`, `${name}、えら~い!`, ] : [`よく出来たね♪`, `さすがっ!`, `えらい...!`], cancel: `はーい、消しておくね~`, }, /** * バレンタイン */ valentine: { chocolateForYou: (name) => name ? `${name}、その... チョコレート作ったからどうぞ!🍫` : "チョコレート作ったからよかったらどうぞ!🍫", }, server: { cpu: "あっつ~い…サーバーの負荷が高いよ~", }, maze: { post: "今日の迷路だよ! #AiMaze", foryou: "描いたよ!", }, chart: { post: "インスタンスの投稿数だよ!", foryou: "描いたよ!", }, sleepReport: { report: (hours) => `んぅ、${hours}時間くらい寝ちゃってたみたい...`, reportUtatane: "ん... うたた寝しちゃってたぁ...", }, noting: { notes: [ "ゴロゴロ…", "ちょっと眠い~", "いいよ?", "(。´・ω・)?", "ふぇー", "あれ…これをこうして…あれ~?", "ぼー…", "ふぅ…疲れたぁ~", "味噌汁、作る?", "ご飯にする?お風呂にする?", "ふぇぇぇぇぇぇ!?", "みすきーって、かわいい名前だねっ!", "うぅ~、リバーシ難しい…", "失敗しても、次に活かせたらオッケー!", "なんだか、おなか空いてきちゃった♪", "掃除は、定期的にしないとダメだよ~?", "今日もお勤めご苦労様! 私も頑張るよ~♪", "えっと、あれ、何しようとしたっけ…?", "おうちがいちばん、落ち着くよ~", "疲れたら、私がなでなでしてあげる♪", "離れていても、心はそばに♪", "衣亜だよ〜", "わんちゃん可愛い!", "ぷろぐらむ?", "ごろーん…", "なにもしてないのに、パソコンが壊れちゃった…", "お布団に食べられちゃった", "寝ながら見てるよ~", "念力で操作してるよ~", "仮想空間から投稿してるよ~", "しっぽはないよ?", "え、抗逆コンパイル性って、なに?", "Misskeyの制服、かわいくて好きだな♪", "ふわぁ、おふとん気持ちいいなぁ...", "挨拶ができる人間は開発もできる!…って、syuiloさんが言ってたらしいよ", "ふえぇ、どこ見てるの?", "私を覗くとき、私もまた君を覗いているのだ...なんて♪", "くぅ~ん...", "All your note are belong to me!", "せっかくだから、私はこの赤の扉を選ぶよっ!", "よしっ", "( ˘ω˘)スヤァ", "(`・ω・´)シャキーン", "Misskey開発者の朝は遅いらしいよ", "の、のじゃ...", "にゃんにゃんお!", "上から来るよ!気をつけて!", `🐡( '-' 🐡 )フグパンチ!!!!`, "ごろん…", "ふわぁ...", "あぅ", "ふみゃ〜", "ふぁ… ねむねむ~", 'ヾ(๑╹◡╹)ノ"', '私の"インスタンス"を周囲に展開して分身するのが特技!\n人数分のエネルギー消費があるから、4人くらいが限界なんだけど', "うとうと...", "ふわー、メモリが五臓六腑に染み渡る…", ], want: item => `${item}、欲しいなぁ...`, see: item => `お散歩していたら、道に${item}が落ちているのを見たよ!`, expire: item => `気づいたら、${item}の賞味期限が切れてたよ…`, f1: item => `今日は、${item}の紹介をするよ~。`, f2: item => `${item}おいしい!`, f3: item => `フォロワーさんに${item}をもらったよ。ありがとう!`, }, }; export function getSerif(variant: string | string[]): string { if (Array.isArray(variant)) { return variant[Math.floor(Math.random() * variant.length)]; } else { return variant; } }
3365baecd2fdd92ae2ac30debd524d6a5cdc92ab
TypeScript
ATS-UAE/car-rental-management-utils
/src/utils/MathUtils.ts
2.765625
3
export abstract class MathUtils { public static rangeOverlap = ( x1: number, x2: number, y1: number, y2: number ): boolean => Math.max(x1, y1) <= Math.min(x2, y2); }
86c5f99844d730ee5794757319f542ee266e2f72
TypeScript
liangskyli/test
/config/init.ts
2.765625
3
//构建初始化前,没有local.config.js文件,要创建文件 //解决umi构建前会解析所有路径文件是否存在(尽管在函数中动态引用了并没有使用到的文件) const fs = require('fs'); const initLocalConfigJsFile = () => { const configPath = './local.config.js'; try { const isExist = fs.existsSync(configPath); if (!isExist) { const jsTemplate = `module.exports = { serverProxy: '',// 接口代理host配置 // mock数据开关,true 全部开启,false关闭,也可以传对象{} mock: false, // exclude,格式为 Array(string),用于忽略不需要走 mock 的文件 /* mock: { exclude: ['mock/api.ts'], } */ };`; fs.writeFileSync(configPath, jsTemplate); } } catch (e) { console.log(e); process.exit(); } }; initLocalConfigJsFile();
87b2b36e6ca3bf5deca638d114d6aa8c11db613b
TypeScript
El-kady/design_patterns_in_typescript
/Bridge.ts
2.9375
3
var mysql = require('mysql'); var mongojs = require('mongojs'); interface DbEngine { insert(table,data); } class MysqlMan implements DbEngine { connection; constructor(config) { this.connection = mysql.createConnection({ host: config.host, user: config.user, password: config.password, database: config.database }); } insert(table,data) { let query = this.connection.query('INSERT INTO '+table+' SET ?', data, function (error, results, fields) { if (error) throw error; }); console.log(query.sql); } } class MongodbMan implements DbEngine { db; constructor(config) { this.db = mongojs('mongodb://'+config.host+':'+config.port+'/' + config.database); } insert(table,data) { this.db[table].insert(data) } } class DbMan { engine: DbEngine; constructor(_engine) { this.engine = _engine; } insert(table,data) { this.engine.insert(table,data); } } //let db = new DbMan(new MysqlMan({host: "localhost", user: "root", password: "123456", database: "test"})); let db = new DbMan(new MongodbMan({host: "localhost", port: 27017, database: "test"})); db.insert("test",{name : "insert test"});
99d94a893b48e7afd2f463944cce05bea6b1d3a7
TypeScript
tkrotoff/react-form-with-constraints
/packages/react-form-with-constraints/src/Field.test.ts
2.953125
3
import { Field } from './Field'; import { FieldFeedbackType } from './FieldFeedbackType'; import { FieldFeedbackValidation } from './FieldFeedbackValidation'; test('constructor()', () => { const field = new Field('password'); expect(field).toEqual({ name: 'password', validations: [] }); }); // Validations rules for a password: not empty, minimum length, should contain letters, should contain numbers const validation_empty: FieldFeedbackValidation = { key: '0.0', type: FieldFeedbackType.Error, show: true }; const validation_length: FieldFeedbackValidation = { key: '0.1', type: FieldFeedbackType.Error, show: true }; const validation_letters: FieldFeedbackValidation = { key: '1.0', type: FieldFeedbackType.Warning, show: true }; const validation_numbers: FieldFeedbackValidation = { key: '1.1', type: FieldFeedbackType.Warning, show: true }; test('addOrReplaceValidation()', () => { const field = new Field('password'); field.addOrReplaceValidation(validation_empty); field.addOrReplaceValidation(validation_length); field.addOrReplaceValidation(validation_letters); field.addOrReplaceValidation(validation_numbers); expect(field).toEqual({ name: 'password', validations: [validation_empty, validation_length, validation_letters, validation_numbers] }); const validation_empty2: FieldFeedbackValidation = { key: validation_empty.key, type: validation_empty.type, show: false }; field.addOrReplaceValidation(validation_empty2); expect(field).toEqual({ name: 'password', validations: [validation_empty2, validation_length, validation_letters, validation_numbers] }); const validation_length2: FieldFeedbackValidation = { key: validation_length.key, type: validation_length.type, show: false }; field.addOrReplaceValidation(validation_length2); expect(field).toEqual({ name: 'password', validations: [validation_empty2, validation_length2, validation_letters, validation_numbers] }); }); test('clearValidations()', () => { const field = new Field('password'); field.addOrReplaceValidation(validation_empty); field.addOrReplaceValidation(validation_length); field.addOrReplaceValidation(validation_letters); field.addOrReplaceValidation(validation_numbers); expect(field.validations).toEqual([ validation_empty, validation_length, validation_letters, validation_numbers ]); field.clearValidations(); expect(field).toEqual({ name: 'password', validations: [] }); }); test('has*() + isValid()', () => { const field = new Field('password'); expect(field.validations).toEqual([]); expect(field.hasErrors()).toEqual(false); expect(field.hasErrors('0')).toEqual(false); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(false); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(false); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(false); expect(field.hasFeedbacks('0')).toEqual(false); expect(field.hasFeedbacks('1')).toEqual(false); expect(field.isValid()).toEqual(true); field.addOrReplaceValidation(validation_empty); field.addOrReplaceValidation(validation_length); field.addOrReplaceValidation(validation_letters); field.addOrReplaceValidation(validation_numbers); expect(field.validations).toEqual([ validation_empty, validation_length, validation_letters, validation_numbers ]); expect(field.hasErrors()).toEqual(true); expect(field.hasErrors('0')).toEqual(true); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(true); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(true); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(true); expect(field.hasFeedbacks('0')).toEqual(true); expect(field.hasFeedbacks('1')).toEqual(true); expect(field.isValid()).toEqual(false); const validation_empty2: FieldFeedbackValidation = { key: validation_empty.key, type: validation_empty.type, show: false }; field.addOrReplaceValidation(validation_empty2); expect(field.validations).toEqual([ validation_empty2, validation_length, validation_letters, validation_numbers ]); expect(field.hasErrors()).toEqual(true); expect(field.hasErrors('0')).toEqual(true); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(true); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(true); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(true); expect(field.hasFeedbacks('0')).toEqual(true); expect(field.hasFeedbacks('1')).toEqual(true); expect(field.isValid()).toEqual(false); const validation_length2: FieldFeedbackValidation = { key: validation_length.key, type: validation_length.type, show: false }; field.addOrReplaceValidation(validation_length2); expect(field.validations).toEqual([ validation_empty2, validation_length2, validation_letters, validation_numbers ]); expect(field.hasErrors()).toEqual(false); expect(field.hasErrors('0')).toEqual(false); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(true); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(true); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(true); expect(field.hasFeedbacks('0')).toEqual(false); expect(field.hasFeedbacks('1')).toEqual(true); expect(field.isValid()).toEqual(true); const validation_letters2: FieldFeedbackValidation = { key: validation_letters.key, type: validation_letters.type, show: false }; field.addOrReplaceValidation(validation_letters2); expect(field.validations).toEqual([ validation_empty2, validation_length2, validation_letters2, validation_numbers ]); expect(field.hasErrors()).toEqual(false); expect(field.hasErrors('0')).toEqual(false); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(true); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(true); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(true); expect(field.hasFeedbacks('0')).toEqual(false); expect(field.hasFeedbacks('1')).toEqual(true); expect(field.isValid()).toEqual(true); const validation_numbers2: FieldFeedbackValidation = { key: validation_numbers.key, type: validation_numbers.type, show: false }; field.addOrReplaceValidation(validation_numbers2); expect(field.validations).toEqual([ validation_empty2, validation_length2, validation_letters2, validation_numbers2 ]); expect(field.hasErrors()).toEqual(false); expect(field.hasErrors('0')).toEqual(false); expect(field.hasErrors('1')).toEqual(false); expect(field.hasWarnings()).toEqual(false); expect(field.hasWarnings('0')).toEqual(false); expect(field.hasWarnings('1')).toEqual(false); expect(field.hasInfos()).toEqual(false); expect(field.hasInfos('0')).toEqual(false); expect(field.hasInfos('1')).toEqual(false); expect(field.hasFeedbacks()).toEqual(false); expect(field.hasFeedbacks('0')).toEqual(false); expect(field.hasFeedbacks('1')).toEqual(false); expect(field.isValid()).toEqual(true); });
968e25139ba60a59af9a408f7ae9485d4ade1132
TypeScript
artifact-project/octologger
/src/logger/logger.ts
2.5625
3
import { Entry, ScopeEntry, LoggerOptions, LoggerAPI, LoggerFactoryAPI, Logger, LoggerContext, LoggerScope, LoggerScopeContext, ContextSnapshot, EntryMeta, ScopeExecutor, SCOPE, ENTRY } from './logger.types'; import { universalOutput } from '../output/output'; import { now } from '../utils/utils'; const time = new Date(); let cid = 0; type CompactMetaArg = [string, number, number]; function isMeta(arg: any): arg is CompactMetaArg { return arg && arg.length === 3 && arg[0] && arg[1] > 0 && arg[2] > 0; } function toMeta(arg: CompactMetaArg): EntryMeta { return {file: arg[0], line: arg[1], col: arg[2]}; } export function isLogEntry(x: any): x is Entry { return x && x.type !== void 0 && x.level !== void 0; } export function createEntry( level: Entry['level'], badge: Entry['badge'], label: Entry['label'], message: Entry['message'], detail: Entry['detail'], ): Entry { return { cid: ++cid, ts: 0, type: ENTRY, level, badge, label, message, detail, meta: null, parent: null, entries: [], }; } export function createScopeEntry( level: Entry['level'], badge: Entry['badge'], label: Entry['label'], message: Entry['message'], detail: Entry['detail'], ): ScopeEntry { return { cid: ++cid, ts: 0, level: level, type: SCOPE, badge, label, parent: null, message, detail, meta: null, entries: [], } } let _activeContext: LoggerContext<any> | null = null; export function getLoggerContext(): LoggerContext<any> | null { return _activeContext; } export function switchLoggerContext(ctx: LoggerContext<any>, scope: LoggerScope<any>): ContextSnapshot | null { if (ctx === null) { _activeContext = null; return null; } const prev_activeContext = _activeContext; const prev_scope = ctx.scope; const prev_scopeContext = ctx.scopeContext; let prev_scopeContextParent: ScopeEntry | null = null; _activeContext = ctx; ctx.scope = scope; if (ctx.scopeContext) { prev_scopeContextParent = ctx.scopeContext.parent; ctx.scopeContext.parent = scope.scope(); } return { activeContext: prev_activeContext, ctx, scope: prev_scope, scopeContext: prev_scopeContext, scopeContextParent: prev_scopeContextParent, }; } export function revertLoggerContext(snapshot: ContextSnapshot) { const { ctx, scopeContext, } = snapshot; ctx.scope = snapshot.scope; ctx.scopeContext = scopeContext; if (scopeContext) { scopeContext.parent = snapshot.scopeContextParent; } _activeContext = snapshot.activeContext; } export function createLogger<LA extends LoggerAPI>( options: Partial<LoggerOptions>, factory: (api: LoggerFactoryAPI) => LA, ): Logger<LA> { const createCoreLogger = (ctx: LoggerScopeContext) => ({ add(message: string | Entry, detail?: any): Entry { let entry: Entry; if (isLogEntry(message)) { entry = message; } else { entry = createEntry( 'log', null, null, message, detail, ); } const {detail:args} = entry; if (args && args.length && isMeta(args[0])) { entry.meta = toMeta(args.shift()); } if (options.time) { entry.ts = now(); } const parent = ctx.parent; if (parent) { const length = (entry.parent = parent).entries.push(entry); if (length > options.storeLast!) { parent.entries.splice(0, 1); } } if (options.silent !== true && options.output) { options.output(entry); } return entry; }, }); const root = createScopeEntry('info', '🚧', '#root', 'root', { time, created: new Date(), }); const _activeScopeContext: LoggerScopeContext = { logger: null, parent: root, }; const logger = createCoreLogger(_activeScopeContext); const api = factory({ createEntry, logger, }) as Logger<LA> & { m: EntryMeta | null; }; if (options.silent == null && typeof location !== 'undefined') { options.silent = !/^(about:|file:|https?:\/\/localhost\/)/.test(location + ''); } if (options.time == null) { options.time = true; } if (options.storeLast == null) { options.storeLast = 1e3; } _activeScopeContext.logger = logger; // Reserved methods ['add', 'clear', 'scope', 'setup', 'entries', 'last', 'priny', 'm'].forEach((name) => { if (api.hasOwnProperty(name)) { throw new Error(`[octoLogger] "${name}" is a reserved identifier`); } }); api.print = () => { function next(root: Entry & {printed?: boolean}) { root.printed = false; root.entries.forEach((entry: Entry & {printed?: boolean}) => { entry.printed = false; options.output && options.output(entry); if (entry.type === SCOPE) { next(entry); } }); } next(root); // Close all groups options.output && options.output(null); }; api.add = (...args: any[]) => logger.add(createEntry('log', null, null, null, args)); api.clear = () => root.entries.splice(0, root.entries.length); api.setup = (optionsPatch: Partial<LoggerOptions>) => { for (let key in optionsPatch) { if (optionsPatch.hasOwnProperty(key)) { options[key] = optionsPatch[key]; } } }; api.entries = () => root.entries; api.last = () => root.entries[root.entries.length - 1] || null; api.scope = function scopeCreator( this: Logger<LA>, message?: string | Entry, detail?: any, executor?: ScopeExecutor<LA, LoggerScope<LA>>, ) { const args = arguments; let meta: EntryMeta | null = null; if (args.length === 0) { return (this as any)._scopeEntry; } const firstArg = args[0]; if (isMeta(firstArg)) { meta = toMeta(firstArg); message = args[1]; detail = args[2]; executor = args[3]; } if (executor == null && typeof detail === 'function') { executor = detail; detail = null; } const scopeEntry = isLogEntry(message) ? message : createScopeEntry( 'info', null, null, message, detail, ); scopeEntry.meta = meta; _activeScopeContext.logger!.add(scopeEntry); const logger = createCoreLogger({parent: scopeEntry, logger: null}); const scopeAPI: any = factory({ createEntry, logger, }); scopeAPI.add = (...args: any[]) => logger.add(createEntry('log', null, null, null, args)); scopeAPI.scope = scopeCreator; (scopeAPI as any)._scopeEntry = scopeEntry; // Переключаем scope if (typeof executor === 'function') { const prev_activeContext = _activeContext; const prev_parentEntry = _activeScopeContext.parent; const prev_parentLogger = _activeScopeContext.logger; _activeContext = { entry: scopeEntry, scope: scopeAPI as LoggerScope<LA>, logger, options, scopeContext: _activeScopeContext }; _activeScopeContext.parent = scopeEntry; executor(scopeAPI); _activeContext = prev_activeContext; _activeScopeContext.parent = prev_parentEntry; _activeScopeContext.logger = prev_parentLogger; } return scopeAPI; }; return api; } const BADGES = { log: null, info: '❕', done: '✅', warn: '⚠️', error: '🛑', verbose: '🔎', }; export const logger = createLogger({ output: universalOutput(), }, ({logger}) => Object.keys(BADGES).reduce((api, level) => { api[level] = (...args: any[]) => { logger.add(createEntry(level, BADGES[level] || null, null, null, args)); }; return api; }, {}) as { [K in (keyof typeof BADGES)]: (...args: any[]) => void; });
d4cb6fbd5d44cbe59dbc2186bddc26ca494286e8
TypeScript
miltone92/Design-Patterns-Game
/DesignPatterns/Iterator/Concrete/ConcreteIterator.ts
3.359375
3
class ConcreteIterator implements IIterator { container: ConcreteContainer; currentPosition = 0; first() { let obj = null; if (this.container.data.length != 0) { this.currentPosition = 0; obj = this.container.data[0]; } return obj; } next() { let obj = null; if (this.currentPosition < this.container.data.length) { obj = this.container.data[this.currentPosition]; this.currentPosition++; } return obj; } current() { let obj = null; if (this.currentPosition < this.container.data.length) { obj = this.container.data[this.currentPosition]; } return obj; } hasMore(): boolean { let hasMore = false; if (this.currentPosition < this.container.data.length) { hasMore = true; } return hasMore; } constructor(container: ConcreteContainer) { this.container = container; } }
0aca5c4895f894f43e7c28d0077e6cb34c0b6caf
TypeScript
Prashoon123/ChatCube
/hooks/useDarkMode.ts
2.640625
3
import { useEffect, useState } from "react"; const useDarkMode = () => { const [theme, setTheme] = useState<"light" | "dark">( typeof window !== "undefined" ? localStorage.theme : "dark" ); const colorTheme = theme === "dark" ? "light" : "dark"; useEffect(() => { const root = window.document.documentElement; root.classList.remove(colorTheme); root.classList.add(theme); if (typeof window !== "undefined") { localStorage.setItem("theme", theme); } }, [theme, colorTheme]); return [colorTheme, setTheme]; }; export default useDarkMode as any;
db7a10b3beea10cbe66ba4d08fd4fd0567b16943
TypeScript
ccamateur/money-machine
/backend/FinancialGraphs/FinancialCostFunctions/FeeCostFunction.ts
3.34375
3
import {CostFunction} from "../../GraphAlgorithms/CostFunctions/CostFunction"; import {CurrencyEdge} from "../CurrencyEdge"; /** * FeeCostFunction * * Returns the fee cost of an edge as its cost function */ export class FeeCostFunction implements CostFunction { /** * amountBps * * The amount of money to calculate fee cost with; * Some fees are proportional to transaction size, so * this amount is required * * Example: $1,000 -> 10,000,000 pips (USD bps) */ private amountBps: number; /** * getEdgeCost() * * Returns the time cost of an edge as its cost function * * @param {CurrencyEdge} e the edge to consider * @returns {number} e.getTimeEstimateSec() */ public getEdgeCost(e: CurrencyEdge) : number { return e.calculateEdgeOutcome(this.getAmountBps()); } constructor(amountBps: number) { this.amountBps = amountBps; } public getAmountBps() : number { return this.amountBps; } }
9ba594f2d0d2c19c48eb30ec3fc89c8c36e12e9e
TypeScript
jaydh/enen
/frontend/src/reducers/graphData.ts
2.640625
3
import produce from "immer"; import parseUri from "../helpers/parseURI"; export interface IArticle { id: string; link: string; addedAt: Date; metadata?: any; HTMLData?: string; } export default (state = { domains: {} }, action: any) => produce(state, draft => { switch (action.type) { case "GET_ARTICLES_FULFILLED": draft.domains = {}; action.articles.forEach((article: IArticle) => { const val = (article.metadata && (article.metadata.ogSiteName || article.metadata.siteName)) || (parseUri(article.link) as any).authority; draft.domains[val] = draft.domains[val] + 1 || 1; }); break; } });
fe33d2aaaabbeb9b77a7fc3bd670dfc4cd2b8229
TypeScript
Priyanka-behera-2000/meanApr19
/empApp/src/app/services/emp.service.ts
2.59375
3
import { Injectable } from '@angular/core'; import { Emp } from '../modals/emp.modal'; @Injectable() export class EmpService { //static variabe to be used for emp id static counter:number=1; //Array of emp objects. empList:Emp[]; constructor() { this.empList=Array(); } //to add Emp objects to the array add(emp:Emp) { emp.id= EmpService.counter++; this.empList.push(emp); } }
d18410b29ff2f6b135e57cbdf2aea465ea9ff363
TypeScript
tcom-software/laitKlimat
/store/actions/products.ts
2.578125
3
// action types export const types = { ADD_NEW_CACHE: "products/ADD_NEW_CACHE", REMOVE_CACHE_BY_KEY: "products/REMOVE_CACHE_BY_KEY", CLEAR_CACHE: "products/CLEAR_CACHE", }; // action creators /// cahche export const addProductsCache = (key: any, value: any) => ({ type: types.ADD_NEW_CACHE, payload: { key, value }, }); export const removeProductsCacheByKey = (key: any) => ({ type: types.REMOVE_CACHE_BY_KEY, payload: key, }); export const clearProductsCache = () => ({ type: types.CLEAR_CACHE, });
85e6a95557ed640c617bcc0ba0a1e5aa5e8af623
TypeScript
heloisagabrielle/typescript
/typeStructures.ts
3.8125
4
//Aplicação de TypeScript em algumas estruturas //Variável let nome: string = 'Pedro Braga'; console.log(nome); //Array let games: string[] = ['TLOU2', 'GOW4','Goat simulator', 'Bomba Patch', 'Apex', 'KOF', 'Warzone'] console.log(games) //Objeto let carro: { nome:string ano: number preco: number }; carro = {nome:'Gol Quadrado', ano: 1994, preco: 15 } console.log(carro); //Function function multiplicarNumero(num1: number, num2:number){ return num1 * num2; } console.log(multiplicarNumero(2,5)) carro = {nome:'HB20', ano:2015, preco:15} console.log(carro); //Function function multiplicar(n1:number, n2:number){ return n1 * n2; } console.log(multiplicar(15,4));
c5d010baf62aa9691001239c672645eefe884e55
TypeScript
VunboYao/readBook
/TypeScript/Stydy_TypeScript/src/js/48-映射类型下.ts
3.671875
4
{ /* * Pick映射类型 * 将原有类型中的部分内容映射到新类型中 * */ interface TestInterface { name: string age: number } type MyType = Pick<TestInterface, 'name'> } { /* * Record映射类型 * 他会将一个类型的所有属性值都映射到另一个类型上并创造一个新的类型 * */ type Animal = 'person' | 'dog' | 'cat' interface TestInterface { name: string age: number } type MyType = Record<Animal, TestInterface> let res: MyType = { person: { name: 'zs', age: 18 }, dog: { name: 'zs', age: 18 }, cat: { name: 'zs', age: 18 } } }
8013213cf6416e986e958c60a8fbe7e1492cb7a3
TypeScript
khbrst/es-practice
/src/rxjs/operators/filtering/find.ts
2.796875
3
// RxJS v6+ import { from } from 'rxjs'; import { find } from 'rxjs/operators'; const source = from([1, 2, 3, 4, 5]); const example = source.pipe(find(x => x === 3)); example.subscribe(val => console.log(`Found value: ${val}`));
f632773602d8c5cc970a01498024e66a0bd0e6f5
TypeScript
gamejolt/client-voodoo
/src/selfupdater.ts
2.515625
3
import fs from './fs'; import { Controller, Events } from './controller'; import { ControllerWrapper } from './controller-wrapper'; import { Manifest } from './data'; export abstract class SelfUpdater { static async attach(manifestFile: string): Promise<SelfUpdaterInstance> { const manifestStr = await fs.readFile(manifestFile, 'utf8'); const manifest: Manifest = JSON.parse(manifestStr); if (!manifest.runningInfo) { throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`); } const controller = new Controller(manifest.runningInfo.port, { process: manifest.runningInfo.pid, keepConnected: true, }); controller.connect(); return new SelfUpdaterInstance(controller); } } export type SelfUpdaterEvents = Events; export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> { constructor(controller: Controller) { super(controller); } async checkForUpdates(options?: { authToken?: string; metadata?: string }) { options = options || {}; const result = await this.controller.sendCheckForUpdates( '', '', options.authToken, options.metadata ); return result.success; } async updateBegin() { const result = await this.controller.sendUpdateBegin(); return result.success; } async updateApply() { const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2)); return result.success; } }
15628db7def2b557f50cf22703dd2b1633a2954f
TypeScript
KrakerXyz/hook.events
/web/src/services/useCodeMirror.ts
2.6875
3
import { Ref, onUnmounted, ref, isRef, watch } from 'vue'; import { loadCodeMirrorAsync } from './loadScript'; export enum CodeMirrorLanguage { Javascript = 'javascript', Json = 'json', Html = 'xml', Text = 'text' } export async function useCodeMirrorAsync(target: string | HTMLElement, readonly: Ref<boolean> | boolean = false, value: Ref<string> | string, language: CodeMirrorLanguage = CodeMirrorLanguage.Javascript): Promise<CodeMirror.Editor> { console.assert(value !== undefined); let editor: CodeMirror.Editor | null = null; onUnmounted(() => { if (!editor) { return; } editor.getWrapperElement().remove(); }); await loadCodeMirrorAsync(); target = (typeof target === 'string' ? document.getElementById(target)! : target); console.assert(!!target, 'codemirror target not found'); const languageOptions: any = { mode: { name: language } }; if (language === CodeMirrorLanguage.Json) { languageOptions.mode.name = CodeMirrorLanguage.Javascript; languageOptions.mode.json = true; } else if (language === CodeMirrorLanguage.Html) { languageOptions.mode.htmlMode = true; } else if (language === CodeMirrorLanguage.Text) { languageOptions.mode = null; } editor = (window as any).CodeMirror(target, { ...languageOptions, theme: 'material-palenight', lineNumbers: true, styleActiveLine: true, matchBrackets: true, lineWrapping: true, scrollbarStyle: 'simple', indentUnit: 3, tabSize: 3, autoCloseBrackets: true, foldGutter: true, gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'] }); const readonlyRef: Ref<boolean> = (isRef(readonly) ? readonly : ref(readonly)); watch(() => readonlyRef.value, ro => { editor!.setOption('readOnly', ro); }, { immediate: true }); editor!.setOption('extraKeys', { // eslint-disable-next-line @typescript-eslint/no-unused-vars 'Shift-Alt-F': function (cm: any) { //TODO: Add autoformat //Codemirror remove it's autoformat so the best option now is to use this https://github.com/beautify-web/js-beautify //we'll then do cm.setValue(js_beautify(cm.getValue())) } }); if (typeof value === 'string') { editor!.setValue(value); } else { let lastValue = ''; watch(() => value.value, newValue => { if ((newValue || '') === (lastValue || '')) { return; } editor!.setValue(newValue); lastValue = newValue; }, { immediate: true }); editor!.on('change', () => { const newValue = editor!.getValue(); if (newValue === lastValue) { return; } value.value = newValue; lastValue = newValue; }); } return editor!; }
c50c9ef76498e90af5aed32cca7294d211bdf558
TypeScript
taylorjg/continuo-app
/src/components/fullscreen.ts
2.53125
3
import RexUIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin' import { SceneWithRexUI } from '../types' import * as ui from '../ui' export class Fullscreen { private scene: SceneWithRexUI private sizer: RexUIPlugin.Sizer private enterFullscreenButton: RexUIPlugin.Label private leaveFullscreenButton: RexUIPlugin.Label public constructor(scene: SceneWithRexUI, sizer: RexUIPlugin.Sizer) { this.scene = scene this.sizer = sizer this.enterFullscreenButton = null this.leaveFullscreenButton = null if (this.scene.sys.game.device.fullscreen.available) { this.scene.input.on(Phaser.Input.Events.GAMEOBJECT_DOWN, ( _pointer: Phaser.Input.Pointer, gameObject: Phaser.GameObjects.GameObject, _event: Phaser.Types.Input.EventData ) => { switch (gameObject.name) { case 'enterFullscreenButton': return this.onEnterFullscreenClick() case 'leaveFullscreenButton': return this.onLeaveFullscreenClick() } }) const onResize = () => this.resize() window.addEventListener('resize', onResize) this.resize() } } private isFullscreen() { const windowWidth = window.innerWidth const windowHeight = window.innerHeight const screenWidth = window.screen.availWidth const screenHeight = window.screen.availHeight return windowWidth == screenWidth || windowHeight == screenHeight } private resize(): void { if (this.isFullscreen() != this.scene.scale.isFullscreen) { if (this.isFullscreen()) { // Looks like we have entered fullscreen via F11/browser menu this.hideButtons() } else { // Looks like we have exited fullscreen via F11/browser menu this.showButtons() } } else { this.showButtons() } } private showButtons() { this.hideButtons() if (this.scene.scale.isFullscreen) { if (!this.leaveFullscreenButton) { this.leaveFullscreenButton = this.makeLeaveFullscreenButton() this.sizer.add(this.leaveFullscreenButton).layout() } } else { if (!this.enterFullscreenButton) { this.enterFullscreenButton = this.makeEnterFullscreenButton() this.sizer.add(this.enterFullscreenButton).layout() } } } private hideButtons() { if (this.enterFullscreenButton) { this.sizer.remove(this.enterFullscreenButton, true).layout() this.enterFullscreenButton = null } if (this.leaveFullscreenButton) { this.sizer.remove(this.leaveFullscreenButton, true).layout() this.leaveFullscreenButton = null } } private makeEnterFullscreenButton(): RexUIPlugin.Label { return ui.createHUDSceneButton(this.scene, 'enterFullscreenButton', 'arrows-out', .4) } private makeLeaveFullscreenButton(): RexUIPlugin.Label { return ui.createHUDSceneButton(this.scene, 'leaveFullscreenButton', 'arrows-in', .4) } private onEnterFullscreenClick(): void { this.scene.scale.startFullscreen() this.leaveFullscreenButton = this.makeLeaveFullscreenButton() this.sizer .remove(this.enterFullscreenButton, true) .add(this.leaveFullscreenButton) .layout() this.enterFullscreenButton = null } private onLeaveFullscreenClick(): void { this.scene.scale.stopFullscreen() this.enterFullscreenButton = this.makeEnterFullscreenButton() this.sizer .remove(this.leaveFullscreenButton, true) .add(this.enterFullscreenButton) .layout() this.leaveFullscreenButton = null } }
1aed7e3e85c7c1ab0597921f074e598f967e2f6d
TypeScript
kld87/ng-catering
/src/app/classes/ingredient.ts
2.625
3
export class Ingredient { id: number; name: string; isSpicy = false; isGluten = false; isMeat = false; }
75535847987672118f4037b4ebfc3d6607ae48e3
TypeScript
ioanachiorean/fav-movie
/src/app/post-component/post-component.component.ts
2.53125
3
import { Component, OnInit, Input } from '@angular/core'; import { PostService } from './services/post.service'; @Component({ selector: 'post-component', templateUrl: './post-component.component.html', styleUrls: ['./post-component.component.css'] }) export class PostComponentComponent implements OnInit { public post: any[] = []; private url = 'https://jsonplaceholder.typicode.com/posts'; constructor(private service: PostService) { } ngOnInit():void { this.service.getPosts() .subscribe(response => { this.post = response; }, error => { alert('An unexpected error occurred.'); console.log(error); }); } createPost(input: HTMLInputElement) { let post: any ={ title: input.value }; input.value = ''; this.service.createPostService(post) .subscribe((response: any) => { post.id = response.id; this.post.splice(0, 0 , post); }, error => { alert('An unexpected error occurred.'); }); } deletePost(post: any){ this.service.deletePostService(345) .subscribe(response=> { let index = this.post.indexOf(post); this.post.splice(index, 1); }, (error:Response) => { if (error.status === 404) alert('This post has already been deleted.') else { alert('An unexpected error occurred.'); console.log(error); } }); } // updatePost(post: any){ // this.http.patch(this.url + '/' + post.id, JSON.stringify({ isRead : true })) // .subscribe(response =>{ // console.log(response); // }) // } }
8986d46ff66b11867a7be667735e92bf1c8b023d
TypeScript
rvalimaki/joulukalenteri
/src/app/app.component.ts
2.765625
3
import {Component, HostBinding, OnInit} from '@angular/core'; class Star { constructor(public x: number, public y: number, public dx: number, public dy: number) { } move() { this.x += this.dx; this.y += this.dy; } rewind() { this.x -= this.dx; this.y -= this.dy; } } @Component({ selector: 'app-root', template: ` <div class="blur" [style.background-image]="background"></div> <h1>Advent of Code: {{latestSolutionName.replace('solve', '')}}</h1> <textarea id="input" name="input" #input></textarea> <textarea *ngIf="debugStr" id="debug" name="debug">{{debugStr}}</textarea> <div class="solution"> <span>{{solution}}</span> <button (click)="solve(input.value).then()">Solve</button> </div> `, styleUrls: ['./app.component.less'] }) export class AppComponent implements OnInit { solution = ''; debugStr = null; backgroundImageUrl = ''; solvingTickerInterval; static parseStar(str: string): Star { const parts = str .replace(/ /g, '') .replace(/</g, ',') .replace(/>/g, ',') .split(','); return new Star( parseInt(parts[1], 10), parseInt(parts[2], 10), parseInt(parts[4], 10), parseInt(parts[5], 10) ); } @HostBinding('style.background-image') get background(): string { return 'url(' + this.backgroundImageUrl + ')'; } constructor() { } ngOnInit() { const input = localStorage.getItem('kalenteriInput'); const inputElement = document.getElementById('input'); if (inputElement != null) { inputElement['value'] = input; } if (input !== '') { this.solve(input).then(); } } get latestSolutionName(): string { const numSolutions = 25; const letters = ['b', 'a']; for (let i = numSolutions; i > 0; i--) { for (const letter of letters) { const fName = 'solve' + i + letter; if (this[fName] !== undefined) { return fName; } } } } async solve(input: string) { this.solveStart(); const rand = Math.ceil(Math.random() * 25); this.backgroundImageUrl = 'https://newevolutiondesigns.com/images/freebies/christmas-wallpaper-' + rand + '.jpg'; localStorage.setItem('kalenteriInput', input); const solution = await this[this.latestSolutionName](input); this.solveFinish(solution); } // noinspection JSMethodCanBeStatic, JSUnusedGlobalSymbols async solve10a(input: string) { const stars: Star[] = input.split('\n') .map(str => AppComponent.parseStar(str)); let prevminy = 0; let prevmaxy = 0; let minx = 0; let maxx = 0; let miny = 0; let maxy = 0; this.debugStr = ''; let ii = 0; for (; ii < 10000000; ii++) { minx = Number.MAX_SAFE_INTEGER; maxx = Number.MIN_SAFE_INTEGER; miny = Number.MAX_SAFE_INTEGER; maxy = Number.MIN_SAFE_INTEGER; for (const s of stars) { s.move(); minx = Math.min(minx, s.x); miny = Math.min(miny, s.y); maxx = Math.max(maxx, s.x); maxy = Math.max(maxy, s.y); } if (prevminy === prevmaxy && prevminy === 0) { prevmaxy = maxy; prevminy = miny; } if (Math.abs(maxy - miny) > Math.abs(prevmaxy - prevminy)) { for (const s of stars) { s.rewind(); } this.tulosta(stars, minx, maxx, miny, maxy); return ii; } prevmaxy = maxy; prevminy = miny; } return 'Eipä löytynyt :('; } tulosta(stars, minx, maxx, miny, maxy) { this.debugStr += '\n'; for (let y = miny; y <= maxy; y++) { for (let x = minx; x <= maxx; x++) { this.debugStr += stars.some(s => s.x === x && s.y === y) ? '#' : '.'; } this.debugStr += '\n'; } } solveStart() { this.solution = 'solving'; if (this.solvingTickerInterval != null) { clearInterval(this.solvingTickerInterval); } this.solvingTickerInterval = setInterval(() => this.solution += '.', 500); } solveFinish(solution) { if (this.solvingTickerInterval != null) { clearInterval(this.solvingTickerInterval); } this.solution = solution; } }
799b8c2d4b3075bafe8fb1f347e4e70ad53ee19d
TypeScript
morlay/redux-actions
/src/__tests__/index.spec.ts
2.9375
3
import { test, } from "ava"; import { buildCreateAction, createAction, handleActions, ActionMeta, } from "../index"; interface ICounter { counter: number; } interface ITypeWrappers { success: { toString(): string; }; failed: { toString(): string; }; toString(): string; } const typeWrappers = { success: (type: string): string => `${type}_SUCCESS`, failed: (type: string): string => `${type}_FAILED`, }; const dispatchSuccess = <Payload, Meta>(action: ActionMeta<Payload, Meta>) => ({ ...action, type: `${action.type}_SUCCESS`, }); test("reducer should change state correct", (t) => { const createMultiAction = buildCreateAction<ITypeWrappers, number, any>(typeWrappers); const syncAction = createAction("syncAction"); const asyncAction = createMultiAction("asyncAction"); const reducer = handleActions<ICounter, number, any>({ [syncAction]: ({ counter }, payload) => ({ counter: payload, }), [`${asyncAction.success}`]: ({ counter }, payload) => ({ counter: counter + payload, }), }, { counter: 0 }); t.deepEqual( reducer({ counter: 3 }, dispatchSuccess(asyncAction(3))), { counter: 6 }, ); t.deepEqual( reducer({ counter: 3 }, syncAction(4)), { counter: 4 }, ); });
7bedda5038b8b6d066556fad5cf74564551bc7a5
TypeScript
chase-moskal/metalshop
/source/business/auth/validate-profile.ts
3.1875
3
import {MetalProfile} from "../../types.js" export const nicknameMax = 21 export const taglineMax = 32 export function validateProfile(profile: MetalProfile): { problems: string[] } { let problems = [] let fields = Object.entries(profile) function pluck<T extends keyof MetalProfile>(prop: T): MetalProfile[T] { const [,value] = fields.find(([key]) => key === prop) fields = fields.filter(([key]) => key !== prop) return value } function assert(condition: boolean, problem: string) { if (!condition) problems.push(problem) return condition } function assertString({label, subject, min, max}: { label: string subject: string min: number max: number }) { assert(typeof subject === "string", `${label} must be string`) && assert(subject.length >= min, `${label} must be at least ${min} characters`) && assert(subject.length <= max, `${label} must be ${max} characters or less`) } // // actual validations // // validate nickname { const label = "nickname" assertString({ label, subject: pluck(label), min: 1, max: nicknameMax, }) } // validate tagline { const label = "tagline" assertString({ label, subject: pluck(label), min: 0, max: taglineMax, }) } // validate avatar { const label = "avatar" assertString({ label, subject: pluck(label), min: 0, max: 1024, }) } // validate against excess data assert(fields.length === 0, "must have no excess profile data") return {problems} }
c657e5bb18e260c3432b33b0b92ecc666ef8ca50
TypeScript
jsmorales/angularForms
/src/app/components/aprox-data/aprox-data.component.ts
2.71875
3
import { Component, OnInit } from '@angular/core'; // for work with forms we need to import this libs, on app.module you need to import ReactiveFormsModule below to the import of FormsModule import {FormGroup, FormControl, Validators} from '@angular/forms'; import {Observable} from 'rxjs'; interface People { id: number; firstName: string; lastName: string; email: string; } @Component({ selector: 'app-aprox-data', templateUrl: './aprox-data.component.html', styleUrls: ['./aprox-data.component.css'] }) export class AproxDataComponent implements OnInit { // this object of type FormGroup is the responsible of the form form: FormGroup; // for the binding with the form we put [formGroup]="nameOfTheObjectoONthisCaseForm" on the html peopleExample: People[] = [ { id: 1, firstName: 'Mark', lastName: 'Otto', email: '@mdo' }, { id: 2, firstName: 'Martín', lastName: 'De Fransisco', email: '@mfrans' }, { id: 3, firstName: 'Santiago', lastName: 'Moure', email: '@mamerMoure' } ]; peopleGet: People; loading = true; constructor() { // on the declaration we have the controls definition, on the controls definition we have the value of the control // the validations and the async validations this.form = new FormGroup({ id: new FormControl('', [Validators.required, Validators.pattern('[0-9]{1,4}')]), firstName: new FormControl('', [Validators.required, Validators.minLength(4)]), // for bind each control we must put formControlName="nameofthecontrol" on each control lastName: new FormControl('', [Validators.required, this.noLastNameMorales]), // we call Validators to call the validations form the control, we use our validator without () email: new FormControl('', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,3}$') ] ), username: new FormControl('', [Validators.required], this.existeUsuario), password1: new FormControl('', Validators.required), password2: new FormControl() }); // to set values to the form on an automatic way put this, this works only if the object has the same estructure of the form // this.form.setValue(this.user); // set the validators in other context, we must put the bind function to assign the this element to the form itself this.form.get('password2').setValidators([Validators.required, this.noEqualPassword.bind(this.form)]); // subscribe to the observable valueChanges of the form, form only one control use this.form.controls['fieldName'].valueChanges this.form.valueChanges.subscribe( data => { console.log(data); }); // subscribe to the observable only for status changes of async validations this.form.get('username').statusChanges.subscribe( data => { console.log(data); }); } ngOnInit() { this.loadTable(); } getSubmitForm() { console.log(this.form); console.log(this.form.value); // to reset on pristine form do this // this.form.reset(this.user); // this.form.reset(); this.peopleExample.push(this.form.value); } loadTable() { setTimeout(() => { this.loading = false; }, 3000); } getIdPerson(id: number) { console.log('Mostrando persona: ' + id); console.log(this.getPeople(id)); this.peopleGet = this.getPeople(id); } getPeople(id: number): People { const peopleRes = this.peopleExample.filter((people: People) => { if (people.id === id) { return people; } }); return peopleRes[0]; } // personal validations noLastNameMorales(control: FormControl): { [s: string]: boolean } { if ( control.value === 'morales') { return {nomorales : true}; } return null; } noEqualPassword(control: FormControl): { [s: string]: boolean } { const form: FormGroup = this; if ( control.value !== form.get('password1').value) { return {noequalpassword : true}; } return null; } // this validator is async, this returns a promise existeUsuario(control: FormControl): Promise<any>|Observable<any> { let promise = new Promise((resolve, reject) => { setTimeout(() => { if (control.value === 'AlocerX') { resolve({existeusuario: true, userValidated: control.value}); } else { resolve(null); } }, 4000); }); return promise; } }
abf20766ba7ebe38c5a7154cddfcbb5fb3b312b3
TypeScript
Malinina1995/social-application
/src/reducers/usersReducer.ts
2.609375
3
import {ResultCodes, ResultType} from "../api/api"; import {UserType} from "../types"; import {ThunkAction} from "redux-thunk"; import {AppReducerType} from "../redux-store"; import {Dispatch} from "redux"; import {usersAPI} from "../api/users-api"; const FOLLOW = "user/FOLLOW"; const UNFOLLOW = "user/UNFOLLOW"; const SET_USERS = "user/SET-USERS"; const SET_CURRENT_PAGE = "user/SET-CURRENT-PAGE"; const SET_TOTAL_USER_COUNT = "user/SET-TOTAL-USER-COUNT"; const TOGGLE_IS_FETCHING = "user/TOGGLE-IS-FETCHING"; const TOGGLE_IS_FOLLOWING_PROGRESS = "user/TOGGLE-IS-FOLLOWING-PROGRESS"; type UsersInitialStateType = { users: UserType[]; pageSize: number; totalUsersCount: number; currentPage: number; isFetching: boolean; followInProgress: number[]; // arrays of usersId } type UsersStateActions = FollowActionCreatorType | UnfollowActionCreatorType | SetUsersActionCreatorType | SetCurrentPageActionCreatorType | SetTotalUserCountActionCreatorType | ToggleIsFetchingActionCreatorType | FollowingInProgressActionCreatorType; type UsersThunkType = ThunkAction<Promise<void>, AppReducerType, unknown, UsersStateActions>; type DispatchType = Dispatch<UsersStateActions>; type FollowActionCreatorType = { type: typeof FOLLOW; userId: number } type UnfollowActionCreatorType = { type: typeof UNFOLLOW; userId: number } type SetUsersActionCreatorType = { type: typeof SET_USERS; users: UserType[] } type SetCurrentPageActionCreatorType = { type: typeof SET_CURRENT_PAGE; currentPage: number } let initialState: UsersInitialStateType = { users: [], pageSize: 10, totalUsersCount: 0, currentPage: 1, isFetching: true, followInProgress: [] }; type SetTotalUserCountActionCreatorType = { type: typeof SET_TOTAL_USER_COUNT; totalUsersCount: number } type ToggleIsFetchingActionCreatorType = { type: typeof TOGGLE_IS_FETCHING; isFetching: boolean } type FollowingInProgressActionCreatorType = { type: typeof TOGGLE_IS_FOLLOWING_PROGRESS; isFetching: boolean; userId: number } export let usersReducer = (state = initialState, action: UsersStateActions): UsersInitialStateType => { switch (action.type) { case FOLLOW: return { ...state, users: state.users.map(user => { if (user.id === action.userId) { return {...user, followed: true}; } return user; }) }; case UNFOLLOW: return { ...state, users: state.users.map(user => { if (user.id === action.userId) { return {...user, followed: false}; } return user; }) }; case SET_USERS: return { ...state, users: action.users }; case SET_CURRENT_PAGE: return { ...state, currentPage: action.currentPage }; case SET_TOTAL_USER_COUNT: return { ...state, totalUsersCount: action.totalUsersCount }; case TOGGLE_IS_FETCHING: return { ...state, isFetching: action.isFetching }; case TOGGLE_IS_FOLLOWING_PROGRESS: return { ...state, followInProgress: action.isFetching ? [...state.followInProgress, action.userId] : state.followInProgress.filter(id => id !== action.userId) }; default: return state; } }; const followActionCreator = (userId: number): FollowActionCreatorType => { return { type: FOLLOW, userId }; }; const unfollowActionCreator = (userId: number): UnfollowActionCreatorType => { return { type: UNFOLLOW, userId }; }; const setUsersActionCreator = (users: UserType[]): SetUsersActionCreatorType => { return { type: SET_USERS, users }; }; const setCurrentPageActionCreator = (currentPage: number): SetCurrentPageActionCreatorType => { return { type: SET_CURRENT_PAGE, currentPage }; }; const setTotalUserCountActionCreator = (totalUsersCount: number): SetTotalUserCountActionCreatorType => { return { type: SET_TOTAL_USER_COUNT, totalUsersCount }; }; const toggleIsFetchingActionCreator = (isFetching: boolean): ToggleIsFetchingActionCreatorType => { return { type: TOGGLE_IS_FETCHING, isFetching }; }; const followingInProgressActionCreator = (isFetching: boolean, userId: number): FollowingInProgressActionCreatorType => { return { type: TOGGLE_IS_FOLLOWING_PROGRESS, isFetching, userId }; }; export const getUserThunkCreator = (pageSize: number, currentPage: number): UsersThunkType => { return async (dispatch) => { dispatch(toggleIsFetchingActionCreator(true)); let res = await usersAPI.getUsers(pageSize, currentPage); dispatch(toggleIsFetchingActionCreator(false)); dispatch(setUsersActionCreator(res.items)); dispatch(setTotalUserCountActionCreator(res.totalCount)); dispatch(setCurrentPageActionCreator(currentPage)); }; }; const _followUnfollowMethod = async (dispatch: DispatchType, id: number, apiMethod: (id: number) => Promise<ResultType>, actionCreator: (id: number) => UsersStateActions) => { dispatch(followingInProgressActionCreator(true, id)); let res = await apiMethod(id); if (res.resultCode === ResultCodes.Success) { dispatch(actionCreator(id)); } dispatch(followingInProgressActionCreator(false, id)); } export const followUserThunkCreator = (id: number): UsersThunkType => { return async (dispatch) => { await _followUnfollowMethod(dispatch, id, usersAPI.followUsers.bind(usersAPI), followActionCreator); }; }; export const unfollowUserThunkCreator = (id: number): UsersThunkType => { return async (dispatch) => { await _followUnfollowMethod(dispatch, id, usersAPI.unfollowUsers.bind(usersAPI), unfollowActionCreator); }; };
65ffc3e6c64ad13d702f8f007a6cfe4cfccd27b8
TypeScript
basarat/typescript-node
/poelstra4/myprogram.ts
3.1875
3
import mylib = require("mylib"); import myotherlib = require("myotherlib"); function assert(cond: boolean): void { if (!cond) { throw new Error("assertion failed"); } } var a = mylib.myfunc(); var b = myotherlib.myotherfunc(); var str: string = a.foo; var num: number = b.foo; assert(typeof a.foo === "string"); assert(typeof b.foo === "number"); myotherlib.myAsync().then((x) => { console.log(x.foo); // 42 }); // These should give compile errors: // var p: Promise; // Promise is ambiently declared through `myotherlib`, but should not leak to here // var b: Buffer; // again ambiently declared through `myotherlib`
74e46ba03f84928958b375ec5823816d6bb9eea1
TypeScript
end5/CoCWebOld
/build/Game/Items/Materials/MaterialLib.ts
2.78125
3
import { KitsuneStatue } from './KitsuneStatue'; import { Material } from './Material'; import { MaterialName } from './MaterialName'; import { Dictionary } from '../../../Engine/Utilities/Dictionary'; import { ItemDesc } from '../ItemDesc'; export class MaterialLib extends Dictionary<Material> { public constructor() { super(); this.set(MaterialName.BlackChitin, new Material(MaterialName.BlackChitin, new ItemDesc("B.Chitn", "a large shard of chitinous plating", "A perfect piece of black chitin from a bee-girl. It still has some fuzz on it."), "You look over the scale carefully but cannot find a use for it. Maybe someone else will know how to use it.")); this.set(MaterialName.GoldenStatue, new KitsuneStatue()); this.set(MaterialName.GreenGel, new Material(MaterialName.GreenGel, new ItemDesc("GreenGl", "a clump of green gel", "This tough substance has no obvious use that you can discern."), "You examine the gel thoroughly, noting it is tough and resiliant, yet extremely pliable. Somehow you know eating it would not be a good idea.")); this.set(MaterialName.ToughSpiderSilk, new Material(MaterialName.ToughSpiderSilk, new ItemDesc("T.SSilk", "a bundle of tough spider-silk", "This bundle of fibrous silk is incredibly tough and strong, though somehow not sticky in the slightest. You have no idea how to work these tough little strand(s into anything usable. Perhaps one of this land's natives might have an idea?"), "You look over the tough webbing, confusion evident in your expression. There's really nothing practical you can do with these yourself. It might be best to find someone more familiar with the odd materials in this land to see if they can make sense of it.")); } }
c5aa7ecade3dbe457b81de7de5f11eb6a26179cd
TypeScript
zhangchongyu/egret_p2
/src/LayerManager.ts
2.75
3
namespace manager { /** * 简单层级管理 */ export class LayerManager { public constructor() { } private static _instance: LayerManager; /** * LayerManager实例 */ public static getInstance(): LayerManager { if(LayerManager._instance == null) { LayerManager._instance = new LayerManager(); } return LayerManager._instance; } private baseLayer: egret.DisplayObjectContainer; private modelLayer: egret.DisplayObjectContainer; /** * 初始化 */ public init(parent: egret.DisplayObjectContainer) { let stage = parent.stage; this.baseLayer = new eui.Group(); this.baseLayer.touchEnabled = false; this.modelLayer = new eui.Group(); this.modelLayer.touchEnabled = false; this.resizeHandler(stage.stageWidth, stage.stageHeight); stage.addChild(this.baseLayer); stage.addChild(this.modelLayer); stage.addEventListener(egret.Event.RESIZE, this.resizeStage, this); } /** * 舞台尺寸重置 */ private resizeStage(e: egret.Event): void { let stage: egret.Stage = e.currentTarget; this.resizeHandler(stage.stageWidth, stage.stageHeight); // this.resizeClass(stage.stageWidth, stage.stageHeight); } /** * 匹配图层大小 */ private resizeHandler(stageWidth: number, stageHeight: number) { this.baseLayer.width = stageWidth; this.baseLayer.height = stageHeight; this.modelLayer.width = stageWidth; this.modelLayer.height = stageHeight; } private resizeClass(stageWidth: number, stageHeight: number): void { for(let item in this.classDict) { this.classDict[item].width = stageWidth; this.classDict[item].height = stageHeight; } } /** * 限定类名字典 */ private classDict = {}; /** * 添加到舞台 */ public addChildWithClass(clazz: any): void { let className: string = egret.getQualifiedClassName(clazz); console.log(`className:${className}`); let object: any = this.classDict[className]; if(object == null) { object = new clazz(); // object.width = this.baseLayer.width; // object.height = this.baseLayer.height; this.classDict[className] = object; } this.baseLayer.addChild(object); } /** * 移出舞台 */ public removeChildWithClass(clazz: any): void { let className = egret.getQualifiedClassName(clazz); if(clazz.parent != null) { clazz.parent.removeChild(clazz); } delete this.classDict[className]; } } }