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
|
|---|---|---|---|---|---|---|
ac4cb5d5131cfd826d70985fc8086e2012a23efc
|
TypeScript
|
sangecz/swagger-angular-generator
|
/src/generate.ts
| 2.671875
| 3
|
/** Generator of API models (interfaces) from BE API json */
import * as fs from 'fs';
import * as conf from './conf';
import {processDefinitions} from './definitions';
import {processPaths} from './requests/process-paths';
import {out, processHeader} from './utils';
export interface Config {
header: string;
dest: string;
}
/**
* Generates API layer for the project based on src to dest
* @param src source swagger json schema
* @param dest destination directory
*/
export function generate(src: string = conf.apiFile, dest: string = conf.outDir) {
let schema: any;
try {
const content = fs.readFileSync(src);
schema = JSON.parse(content.toString());
} catch (e) {
if (e instanceof SyntaxError) {
out(`${src} is either not a valid JSON scheme or contains non-printable characters`, 'red');
} else out(`JSON scheme file '${src}' does not exist`, 'red');
out(`${e}`);
return;
}
const header = processHeader(schema);
const config: Config = {header, dest};
if (!fs.existsSync(dest)) fs.mkdirSync(dest);
processPaths(schema.paths, `http://${schema.host}${schema.basePath}${conf.swaggerFile}`, config);
processDefinitions(schema.definitions, config);
}
|
d876843f2d98ab4795aa84e680aef54eb1e32119
|
TypeScript
|
sgnatonski/tortitle
|
/tortitle/backend/torrent.ts
| 2.703125
| 3
|
import { ISubtitle } from "./subtitle";
export interface ITorrent {
name: string;
torrentLink: string;
magnetLink: string;
magnetLink64: string;
imdbId: string;
quality: string;
files: ITorrentFile[];
subtitle: ISubtitle;
addedAt: Date;
isNew: boolean;
isStreamable: boolean;
}
export interface ITorrentFile {
File: string;
Size: string;
}
export interface ITorrentEntity {
PartitionKey: string;
RowKey: string;
ImdbId: string;
Quality: string;
TorrentLink: string;
MagnetLink: string;
Files: string;
AdddedAt: Date;
}
export function map(m: ITorrentEntity) {
const files = JSON.parse(m.Files || "null") as ITorrentFile[];
return {
name: (m.RowKey || "").trim(),
imdbId: m.ImdbId,
quality: m.Quality,
torrentLink: m.TorrentLink,
magnetLink: m.MagnetLink,
files: files,
addedAt: m.AdddedAt || new Date(2017, 0),
isStreamable: (files || []).findIndex(x => x.File.endsWith('.mkv') || x.File.endsWith('.mp4')) >= 0 || files === null
} as ITorrent;
}
|
d2c8ef488781aa18d08cf312d5ad2162ef99b96d
|
TypeScript
|
anthonny/domifa
|
/packages/frontend/src/app/shared/store/usagersSearchCache.service.spec.ts
| 2.796875
| 3
|
import { UsagerLight } from "../../../_common/model";
import { usagersSearchCache } from "./usagersSearchCache.service";
const initialState: Partial<UsagerLight>[] = [
{
uuid: "1",
prenom: "John",
nom: "Smith",
},
{
uuid: "2",
prenom: "Marie",
nom: "Smith",
},
{
uuid: "3",
prenom: "Claire",
nom: "Meunier",
},
];
it("usagersSearchCache: set initial state", () => {
expect(usagersSearchCache.getUsagersSnapshot()).toBeUndefined();
usagersSearchCache.setUsagers(initialState as UsagerLight[]);
expect(usagersSearchCache.getUsagersSnapshot()).toEqual(initialState);
});
it("usagersSearchCache: update", () => {
usagersSearchCache.setUsagers(initialState as UsagerLight[]);
usagersSearchCache.updateUsager({
uuid: "2",
prenom: "Maria",
nom: "Smith",
} as UsagerLight);
expect(usagersSearchCache.getUsagersSnapshot()).toEqual([
{
uuid: "1",
prenom: "John",
nom: "Smith",
},
{
uuid: "2",
prenom: "Maria",
nom: "Smith",
},
{
uuid: "3",
prenom: "Claire",
nom: "Meunier",
},
]);
});
it("usagersSearchCache: create", () => {
usagersSearchCache.setUsagers(initialState as UsagerLight[]);
usagersSearchCache.createUsager({
uuid: "4",
prenom: "Jo",
nom: "Ker",
} as UsagerLight);
expect(usagersSearchCache.getUsagersSnapshot()).toEqual([
{
uuid: "1",
prenom: "John",
nom: "Smith",
},
{
uuid: "2",
prenom: "Marie",
nom: "Smith",
},
{
uuid: "3",
prenom: "Claire",
nom: "Meunier",
},
{
uuid: "4",
prenom: "Jo",
nom: "Ker",
},
]);
});
it("usagersSearchCache: remove by uuid", () => {
usagersSearchCache.setUsagers(initialState as UsagerLight[]);
usagersSearchCache.removeUsagersByCriteria({
uuid: "2",
});
expect(usagersSearchCache.getUsagersSnapshot()).toEqual([
{
uuid: "1",
prenom: "John",
nom: "Smith",
},
{
uuid: "3",
prenom: "Claire",
nom: "Meunier",
},
]);
});
it("usagersSearchCache: remove by prenom", () => {
usagersSearchCache.setUsagers(initialState as UsagerLight[]);
usagersSearchCache.removeUsagersByCriteria({
prenom: "Claire",
});
expect(usagersSearchCache.getUsagersSnapshot()).toEqual([
{
uuid: "1",
prenom: "John",
nom: "Smith",
},
{
uuid: "2",
prenom: "Marie",
nom: "Smith",
},
]);
});
|
661aeadaec0feb66ec642a313ac4af3783765b87
|
TypeScript
|
darshgun/atlaskit
|
/build/utils/guards.ts
| 3.1875
| 3
|
/** Typescript type guards */
/* A simple defined check with type guard that works well with Array.prototype.filter */
export function isDefined<T>(arg: T | undefined | null): arg is T {
return arg != null;
}
|
4f3cc9c9784981b97196b2a3e3e6d3beea7ac8d3
|
TypeScript
|
andrey0902/project_firebase
|
/src/app/users/user-list/ExampleDataSource.ts
| 2.515625
| 3
|
import { Observable } from 'rxjs/Observable';
import { DataSource } from '@angular/cdk/collections';
export class ExampleDataSource extends DataSource<any> {
public users;
/** Connect function called by the table to retrieve one stream containing the data to render. */
constructor(users: any) {
super();
this.users = users;
}
public connect() {
return Observable.of(this.users);
}
public disconnect() {
}
}
|
e433e8645e947c3c4c64d794f50fc8b9f24c5b15
|
TypeScript
|
jacoubbondre/QualifierCMS
|
/app/pipes/encodeClassName.pipe.ts
| 2.53125
| 3
|
import {Pipe, PipeTransform, Injectable} from '@angular/core'
@Pipe({
name: 'encodeClassName'
})
@Injectable()
export class EncodeClassNamePipe implements PipeTransform {
transform(item:string) {
return item.replace(/ /g, '-').replace(/[^\w\s]/g, '').toLowerCase()
}
}
|
c59d02237dbb5c7858fb875b01c601a14697da18
|
TypeScript
|
ARedondoVilla/GifsApp
|
/src/app/gifs/busqueda/busqueda.component.ts
| 2.609375
| 3
|
import { Component, ElementRef, ViewChild } from '@angular/core';
import { GifsService } from '../services/gifs.service';
@Component({
selector: 'app-busqueda',
templateUrl: './busqueda.component.html',
styles: [
]
})
export class BusquedaComponent {
@ViewChild('txtBuscar') txtBuscar!: ElementRef<HTMLInputElement>;// Toma referencia local #txtBuscar en el html y la asigna a la variable txtBuscar
// asegura de que txtBuscar no sera null, evitando el error de que da TypeScript
constructor(private gifsServices: GifsService){} // mediante el constructor genero una variable tipo servicio y me traigo sus metodos
buscar() {
let valor = this.txtBuscar.nativeElement.value;
// Se le da el valor generico HTMLInputElement para que aparezcan en el autocompletado todas las claves del native element
if (valor.trim() == "") { // Para evitar que se agreguen valores vacios
return;
}
this.gifsServices.buscarGifs(valor)
this.txtBuscar.nativeElement.value = "";
}
// Esto genera en consola el elemento native element de tipo ElementRef
}
|
5b9c4a5460022f73a940663c8412d8f7d8d861f9
|
TypeScript
|
andrewthauer/ts-monorepo
|
/packages/core/src/index.ts
| 2.921875
| 3
|
export const map = <T, O>(iteratee: (i: T) => O, data: T[]): O[] =>
data.map((i: T) => iteratee(i));
|
c313558af0ce8ad14d07915f775370e806467db1
|
TypeScript
|
var-bin/ng-events
|
/src/app/events/shared/duration.pipe.ts
| 2.875
| 3
|
import {
Pipe,
PipeTransform,
} from "@angular/core";
@Pipe({
name: "duration",
})
export class DurationPipe implements PipeTransform {
transform(value: number): string {
const durations = {
1: "Half Hour",
2: "1 Hour",
3: "Half Day",
4: "Full Day",
defaultValue: value.toString()
};
return durations[value] || durations.defaultValue;
}
}
|
ddd07ea82b12a6c46acb6f7cc279a883083b4607
|
TypeScript
|
DaniloFnds/TimerWork
|
/src/app/timer/timer.component.ts
| 2.515625
| 3
|
import { Timer } from './../shared/models/timer';
import { TimerService } from './services/timer.service';
import { Component, OnInit } from '@angular/core';
import { Observable, interval, Subscription } from 'rxjs';
import { map } from 'rxjs/operators'
import * as moment from 'moment';
import 'moment/locale/pt-br';
@Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.css']
})
export class TimerComponent implements OnInit {
timerList: Timer[] = [];
totalHorasDiaria: string = ''
dataTimer: string;
contadorSubs: Subscription;
momDateTimer: moment.Moment;
dataDiferenteAtual: boolean = true;
constructor(private timerService: TimerService) { }
atualizaContador(timer: Timer) {
let entradaTimer = timer.contador.toLowerCase();
const regex = /[0-9]{1,2}[hms]{1,2}/g
let regMatch = entradaTimer.match(regex);
if (regMatch != null) {
regMatch.forEach((value) => {
console.log(value)
if (value.includes("h")) {
console.log(value)
}
})
} else {
const regexSoDigitos = /[0-9]{1,6}/g
let regMatchDigito = entradaTimer.match(regexSoDigitos);
if (regMatchDigito != null) {
regMatchDigito.forEach(e => {
let momentConvert = moment(e, 'hmm')
if (momentConvert.isValid()) {
timer.contador = momentConvert.format("HH[h ]mm[m]")
} else {
if (e.length === 1) {
timer.contador = moment.utc(moment.duration(Number(e), 'hours').asMilliseconds()).format("HH[h ]mm[m]");
} else {
if (e.length === 2) {
timer.contador = moment.utc(moment.duration(Number(e), 'minutes').asMilliseconds()).format("HH[h ]mm[m]");
} else {
timer.contador = moment.utc(moment.duration(Number(e), 'minutes').asMilliseconds()).format("HH[h ]mm[m]");
}
}
}
});
}
}
this.timerService.atualiza(timer).subscribe()
}
startTarefa(timer: Timer) {
if(timer.tempoCorrendo) {
timer.tempoCorrendo = false;
timer.fim = new Date();
this.timerService.atualiza(timer).subscribe();
this.contadorSubs.unsubscribe();
return;
}
let timerNovo = new Timer(timer.descricao, timer.nota, '0s', this.momDateTimer.format('DD-MM-YYYY'), new Date(), null, true );
this.timerService.gravar(timerNovo)
.pipe().subscribe((timerSalvo) => {
timerNovo.id = timerSalvo.id;
});
this.timerList.push(timerNovo);
console.log(this.timerList);
this.contadorSubs = interval(1000).pipe(
map((x) => {
let seconds = x;
if (x <= 60) {
timerNovo.contador = String(x) + 's';
} else {
seconds %= 3600;
if (x >= 3600) {
timerNovo.contador = String(Math.floor(x / 3600)) + 'h ' + String(Math.floor(seconds / 60)) + 'm ' + seconds % 60 + 's'
} else {
timerNovo.contador = String(Math.floor(seconds / 60)) + 'm ' + seconds % 60 + 's'
}
}
})
).subscribe();
}
private registrarTimerCorrendo(timer: Timer) {
const inico = moment(timer.inicio);
const fim = moment(new Date());
let registrouTempoCorrendo: boolean = timer.tempoCorrendo;
let cron: number = 0;
this.contadorSubs = interval(1000).pipe(
map((x) => {
if(registrouTempoCorrendo) {
cron = fim.diff(inico, 'seconds');
registrouTempoCorrendo = false;
}
cron = cron + x;
let seconds = cron;
if (cron <= 60) {
timer.contador = String(cron) + 's';
} else {
seconds %= 3600;
if (cron >= 3600) {
timer.contador = String(Math.floor(cron / 3600)) + 'h ' + String(Math.floor(seconds / 60)) + 'm ' + seconds % 60 + 's'
} else {
timer.contador = String(Math.floor(seconds / 60)) + 'm ' + seconds % 60 + 's'
}
}
})
).subscribe();
}
ngOnInit() {
this.dataTimer = moment().format("ddd[,] D MMMM");
this.momDateTimer = moment();
this.pesquisar(null, false);
}
private pesquisar(data: string, comData: boolean) {
this.timerService.listPorData(data, comData).pipe(
map((item) => {
let result:Array<Timer> = [];
item.forEach((t) => {
if(t.tempoCorrendo) {
let timer = new Timer(t.descricao, t.nota, t.contador, t.dataLancamento, t.inicio, t.fim, t.tempoCorrendo);
timer.id = t.id;
this.registrarTimerCorrendo(timer);
result.push(timer)
} else {
let timer = new Timer(t.descricao, t.nota, t.contador, t.dataLancamento, t.inicio, t.fim, t.tempoCorrendo);
timer.id = t.id;
result.push(timer)
}
});
return result;
})
).subscribe(timers => this.timerList = timers)
}
totalHorasDiario() {
let totalFinal = moment.duration();
const regex = /[0-9]{1,2}[hms]{1,2}/g
const regDigito = /[0-9]{1,2}/g
this.timerList.forEach((tempo) => {
const regMatch = tempo.contador.match(regex);
if (regMatch != null) {
regMatch.forEach((value) => {
const resultado = value.match(regDigito)[0];
if (value.includes("h")) {
totalFinal.add(Number(resultado), 'hours')
}
if (value.includes("m")) {
totalFinal.add(Number(resultado), 'minutes')
}
})
}
})
return moment.utc(totalFinal.asMilliseconds()).format("HH[h ]mm[m ]");
}
onTimerNovo(timer: Timer) {
timer.dataLancamento = this.momDateTimer.format('DD-MM-YYYY')
this.timerService.gravar(timer).subscribe();
this.timerList.push(timer);
}
diasAnteriores() {
let data = this.momDateTimer.subtract(1, 'days');
this.dataTimer = data.format("ddd[,] D MMMM");
this.pesquisar(data.format('DD-MM-YYYY'), true);
this.dataDiferenteAtual = moment(data.format('YYYY-MM-DD')).isSame(moment(moment().format('YYYY-MM-DD')));
console.log(!this.dataDiferenteAtual)
}
proximosDias() {
let data = this.momDateTimer.add(1, 'days');
this.dataTimer = data.format("ddd[,] D MMMM");
this.pesquisar(data.format('DD-MM-YYYY'), true);
this.dataDiferenteAtual = moment(data.format('YYYY-MM-DD')).isSame(moment(moment().format('YYYY-MM-DD')));
console.log(!this.dataDiferenteAtual)
}
irDiaAtual() {
let data = this.momDateTimer = moment();
this.dataTimer = data.format("ddd[,] D MMMM");
this.pesquisar(data.format('DD-MM-YYYY'), true);
this.dataDiferenteAtual = true;
}
ngOnDestroy() {
this.contadorSubs.unsubscribe();
}
}
|
60b37527979e51278333d66ca37d3fb259f82b13
|
TypeScript
|
KazumasaYasui/riakuto3.1
|
/04-typescript/05-advanced/index-access.ts
| 2.5625
| 3
|
{
const permissions = {
r: 0b100 as const,
w: 0b010 as const,
x: 0b001 as const,
};
type PermsChar = keyof typeof permissions;
type PermsNum = typeof permissions[PermsChar];
const readable: PermsNum = 4;
// const writeable: PermsNum = 99;
console.log(readable);
}
|
70fb65697915de9e9a91050f72ec7f90b3482bb0
|
TypeScript
|
bobbyhiom/AtariJam
|
/src/entity/scene.ts
| 2.625
| 3
|
export class Scene extends Entity {
static MODEL: string = "models/Scene.gltf"
gltfShape: GLTFShape
direction: Vector3 = Vector3.Right()
constructor(x: number, y: number, z: number, scale: number, rotation: number) {
super()
this.gltfShape = new GLTFShape(Scene.MODEL)
this.addComponent(this.gltfShape)
let baseTransform = new Transform()
baseTransform.position.x = x
baseTransform.position.y = y
baseTransform.position.z = z
baseTransform.rotate(Vector3.Up(), rotation )
baseTransform.scale.set(scale, scale, scale)
this.addComponent(baseTransform)
engine.addEntity(this)
}
}
|
5546d4b95446b990d857037790336b4f5bb26e13
|
TypeScript
|
ezekielchentnik/fuco
|
/src/fuco/define-element.ts
| 2.53125
| 3
|
import { render } from "../html";
import { isBrowser } from "./env";
import { adoptCssStyle, HasCSSSymbol } from "./css";
import { Component, AttributeConverter } from "./component";
import { __scope__, defaultHooks, EffectFn } from "./hook";
import {
enqueueEffects,
enqueueLayoutEffects,
enqueueUpdate
} from "./reconciler";
export type FunctionalComponent = () => unknown;
export const __def__: { [name: string]: FunctionalComponent } = {};
export function defineElement(name: string, fn: FunctionalComponent) {
if (isBrowser) {
customElements.define(
name,
class extends HTMLElement implements Component {
private _dirty = false;
private _connected = false;
private _container = this.attachShadow({ mode: "open" });
public _hooks = defaultHooks();
protected connectedCallback() {
this._connected = true;
this.update();
}
protected disconnectedCallback() {
this._connected = false;
const cleanups = this._hooks._cleanup;
for (let i = 0; i < cleanups.length; i++) {
if (cleanups[i]) {
cleanups[i]();
delete cleanups[i];
}
}
}
public update() {
if (this._dirty) return;
this._dirty = true;
enqueueUpdate(this);
}
public _performUpdate() {
if (!this._connected) return;
try {
__scope__(this);
render(fn(), this._container);
enqueueLayoutEffects(this);
enqueueEffects(this);
} catch (e) {
console.error(e);
}
this._dirty = false;
}
public _flushEffects(effects: EffectFn[]) {
const cleanups = this._hooks._cleanup;
for (let i = 0, len = effects.length; i < len; i++) {
if (effects[i]) {
cleanups[i] && cleanups[i]();
const cleanup = effects[i]();
if (typeof cleanup === "function") {
cleanups[i] = cleanup;
}
delete effects[i];
}
}
}
public _attr<T>(name: string, converter?: AttributeConverter<T>) {
return converter
? converter(this.getAttribute(name))
: this.getAttribute(name);
}
public _observeAttr(name: string, callback: () => void) {
const m = new MutationObserver(callback);
m.observe(this, { attributes: true, attributeFilter: [name] });
return () => m.disconnect();
}
public _dispatch<T>(name: string, init: CustomEventInit<T>) {
this.dispatchEvent(new CustomEvent<T>(name, init));
}
public _adoptStyle(css: HasCSSSymbol) {
adoptCssStyle(this._container, css);
}
}
);
} else {
__def__[name] = fn;
}
}
|
3f9ef34b91043a7544e2e183d22cb329ad4bb26e
|
TypeScript
|
derv82/ion-js
|
/src/IonLongInt.ts
| 3.125
| 3
|
/*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
// Ion Value Support class. This class offers the
// additional semantics necessary for long integers
//
// ION.LongInt supports:
//
// numberValue()
// byteValue() - returns the bytes of the
// signum() - return -1, 0, or +1
// isZero()
// isNull()
// isNegativeZero()
// toString()
// ION.LongInt.parse(string)
// ION.LongInt.fromBytes(bytes, sign)
// ION.LongInt.fromNumber(number)
// ION.LongInt.ZERO
import { is_digit } from "./IonText";
import { isNullOrUndefined } from "./IonUtilities";
export class LongInt {
private static readonly zero_bytes: number[] = [0];
private static readonly zero_string = "0";
private static readonly byte_base = 256;
private static readonly byte_mask = 0xff;
private static readonly byte_shift = 8;
private static readonly string_base = 10;
private static readonly char_plus = '+'.charCodeAt(0);
private static readonly char_minus = '-'.charCodeAt(0);
private static readonly char_zero = '0'.charCodeAt(0);
private static readonly char_little_n = 'n'.charCodeAt(0);
static NULL: LongInt = new LongInt(undefined, undefined, 0);
static ZERO: LongInt = new LongInt(LongInt.zero_string, LongInt.zero_bytes, 0);
private s: number;
private d: string;
private b: number[];
constructor(str: string, bytes: number[], signum: number) {
this.s = signum;
this.d = str;
this.b = bytes;
}
private static _make_zero_array(len: number) : number[] {
let bytes = [];
for (let ii = len; ii > 0; ) {
ii--;
bytes[ii] = 0;
}
return bytes;
}
private static _make_copy(bytes: number[]) : number[] {
let copy = [];
for (let idx = bytes.length; idx > 0; ) {
idx--;
copy[idx] = bytes[idx];
}
return copy;
}
isNull() : boolean {
return (this.b === undefined && this.d === undefined);
}
private static _div_d(bytes: number[], digit: number) {
// destructive in place divide by digit
// returns the remainder if any (or 0)
let tmp: number;
let nd: number;
let r: number = 0;
let len: number = bytes.length;
let idx: number = 0;
if (digit >= LongInt.byte_base) {
throw new Error("div_d can't divide by " + digit + ", max is one base " + LongInt.byte_base + " digit");
}
while (idx < len) {
nd = bytes[idx] + (r * LongInt.byte_base);
tmp = Math.floor( nd / digit);
bytes[idx] = tmp;
r = nd - (tmp * digit);
idx++
}
return r;
}
private static _is_zero_bytes = function(bytes) {
var ii, len = bytes.length;
for (ii=len; ii>0; ) {
ii--;
if (bytes[ii] > 0) return false;
}
return true;
}
isZero() : boolean {
if (this.isNull()) return false;
if (this.s === 0) return true;
if (!isNullOrUndefined(this.b)) {
return LongInt._is_zero_bytes(this.b);
}
if (!isNullOrUndefined(this.d)) {
return this.d == '0';
}
return undefined;
}
isNegativeZero() : boolean {
return (this.isZero() && (this.s === -1));
}
private _d() : void { // forces creation of base 10 string
var dec, str, bytes, len, dg, src, dst;
if (isNullOrUndefined(this.d)) {
if (this.isZero()) {
this.d = LongInt.zero_string;
} else {
bytes = LongInt._make_copy(this.b); // make a copy
len = bytes.length;
dec = LongInt._make_zero_array(len * 3);
dst = 0;
for (;;) {
if (LongInt._is_zero_bytes(bytes)) break;
dg = LongInt._div_d(bytes, LongInt.string_base);
dec[dst++] = dg;
}
for (src = dst; src >= 0; src--) {
if (dec[src] > 0) break;
}
str = ""; // remember this version is for "time to market" not speed !
for (; src >= 0; src--) {
str = str + dec[src].toString();
}
this.d = str;
}
}
}
private static _add(bytes: number[], v: number) : void {
var l = bytes.length, dst, c, t;
if (v >= LongInt.byte_base) {
throw new Error("_add can't add " + v + ", max is one base " + LongInt.byte_base + " digit");
}
for (dst = l; dst >= 0; ) { // we do all digits
dst--;
t = bytes[dst] + v;
bytes[dst] = t & LongInt.byte_mask; // bottom 8 bits are the new digit
v = t >> LongInt.byte_shift; // bits above 8 are carry
if (v === 0) break; // add until there's nothing left to carry
}
if (v !== 0) {
throw new Error("this add doesn't support increasing the number of digits");
}
}
private static _mult(bytes: number[], v: number) : void {
var l = bytes.length, dst, c, t;
if (v >= LongInt.byte_base) {
throw new Error("_mult can't add " + v + ", max is one base " + LongInt.byte_base + " digit");
}
c = 0;
for (dst = l; dst >= 0; ) { // we do all digits
dst--;
t = (bytes[dst] * v) + c;
bytes[dst] = t & LongInt.byte_mask;
c = t >> LongInt.byte_shift;
}
if (c !== 0) {
throw new Error("this mult doesn't support increasing the number of digits");
}
}
private _b() : void { // forces creation of base 256 byte array
if (isNullOrUndefined(this.b)) {
if (this.isZero()) {
this.b = LongInt.zero_bytes;
return;
}
let dec: string = this.d;
let len: number = dec.length;
let bytes: number[] = LongInt._make_zero_array(len);
let src: number = 0;
for (;;) {
let dg: number = dec.charCodeAt(src) - LongInt.char_zero;
LongInt._add(bytes, dg);
src++;
if (src >= len) {
break;
}
LongInt._mult(bytes, LongInt.string_base);
}
// We end at length - 1 because we always want at least 1 byte in the array
let firstNonzeroDigitIndex: number = 0;
for (; firstNonzeroDigitIndex < len; firstNonzeroDigitIndex++) {
if (bytes[firstNonzeroDigitIndex] > 0) break;
}
this.b = bytes.slice(firstNonzeroDigitIndex);
}
}
numberValue() : number {
var ii, bytes, n, len;
if (this.isNull()) {
return undefined;
}
this._b();
n = 0;
bytes = this.b;
len = bytes.length;
for (ii=0; ii<len; ii++) {
n = (n * LongInt.byte_base) + bytes[ii]; // not shift so that floating point will work
}
return n * this.s; // apply the sign
}
toString() : string {
if (this.isNull()) {
return undefined;
}
this._d();
return ((this.s < 0) ? "-" : "") + this.d;
}
digits() : string { // used by decimal
this._d();
return this.d;
}
stringValue() : string {
return this.toString();
}
byteValue() : number[] {
if (this.isNull()) {
return undefined;
}
this._b();
// need to address sign !!!
return LongInt._make_copy(this.b);
}
signum() : number {
return this.s;
}
static parse(str: string) : LongInt {
var t, ii,
signum = 1,
dec = str.trim();
switch(dec.charCodeAt(0)) {
case LongInt.char_little_n:
if (dec !== "null" && dec !== "null.int") {
throw new Error("invalid integer format");
}
dec = undefined;
signum = 0;
break;
case LongInt.char_minus:
signum = -1;
// fall through to plus, then to default
case LongInt.char_plus:
dec = dec.slice(1);
// fall through
default:
for (ii=0; ii<dec.length; ii++) { // strip leading zero's
if (dec.charCodeAt(ii) !== LongInt.char_zero) break; // '0'
}
if (ii < dec.length) { // first trim the leading zero's
dec = dec.slice(ii);
}
for (ii=dec.length; ii>0;) {
ii--;
if (is_digit(dec.charCodeAt(ii)) === false) {
throw new Error("invalid integer");
}
}
if (dec.length < 1) {
throw new Error("invalid integer");
}
}
t = new LongInt(dec, undefined, signum);
return t;
}
static fromBytes(bytes: number[], signum: number) : LongInt {
var t, ii, len = bytes.length;
// input array is in order of high to low
for (ii=0; ii < len; ii++) {
if (bytes[ii] !== 0) break;
}
if (ii >= len) {
if (signum === 1) signum = 0; // we don't convert a -0, just a +something
bytes = LongInt.zero_bytes;
}
else {
bytes = bytes.slice(ii);
}
t = new LongInt(undefined, bytes, signum);
return t;
}
static fromNumber(n: number) : LongInt {
var signum, d, t;
if (isNaN(n)) {
signum = 0;
}
else if (n === 0) {
signum = (1/n === 1/-0.0) ? -1 : 0;
d = LongInt.zero_string;
}
else {
if (n < 0) {
signum = -1;
n = -n;
}
else {
signum = 1;
}
n = Math.floor(n);
d = n.toString();
}
t = new LongInt(d, undefined, signum);
return t;
}
}
|
db9bc0474861a9e620766c638cb1ac00703f2dea
|
TypeScript
|
mzx/angular-mhthhc
|
/src/app/tree1/models.ts
| 2.6875
| 3
|
export type ValueOf<T> = T[keyof T];
export type Data = {id: string, widget: WidgetsEnumType, children: Data[], value: any}; // TODO
export class TreeNode<D> {
data: D;
children: TreeNode<D>[];
}
export class FlatTreeNode<D> extends TreeNode<D> {
level: number;
expandable: boolean;
}
export const WidgetsEnum = {
plus_placeholder: 'plus_placeholder',
group: 'group',
criterion: 'criterion'
};
export type WidgetsEnumType = ValueOf<typeof WidgetsEnum>;
|
8fb21c8078f41a68523766e12bdc68aee58af89a
|
TypeScript
|
mratmartinez/ese-pedidos
|
/client/src/shared/environment.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { ToastController } from 'ionic-angular';
@Injectable()
export class EnvironmentService {
private token: string;
private static readonly ip: string = "127.0.0.1"
private static readonly port: number = 1337
constructor(
private toast: ToastController
) {}
getApiURL(partialURL: string) : string {
return EnvironmentService.getServerURL() + partialURL
}
toPlainHttpParams(args: {}) {
return { headers: new HttpHeaders(args) }
}
toAuthHttpParams(args: {} = {}) {
args["token"] = this.getToken()
return { headers: new HttpHeaders(args) }
}
getDefaultErrorMessage(error: HttpErrorResponse) : string {
if (error.error instanceof Error)
return "Unknown error: " + error.message
else
return "Unknown server error (Code " + error.status + ")"
}
setToken(token: string) {
this.token = token
}
getToken() {
return this.token
}
static getServerURL() : string {
return "http://" + EnvironmentService.ip + ":" + EnvironmentService.port
}
makeToast(message: string, duration: number = 2000) {
let toastParams = {
message: message,
duration: 2000
};
this.toast.create(toastParams).present();
}
makeToastFromError(error: HttpErrorResponse, duration: number = 2000) {
this.makeToast(this.getDefaultErrorMessage(error), duration)
}
}
|
b497706df04e7cd6486cb62f2896b3ee1abaa282
|
TypeScript
|
GeVa2072/ng6-go
|
/client/src/app/shared/services/user.service.ts
| 2.53125
| 3
|
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from "rxjs";
import {NamespaceService} from "./namespace.service";
import {filter, take} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class UserService {
private usernameSource = new BehaviorSubject<string>(null);
public username = this.usernameSource.asObservable();
constructor(private nsService: NamespaceService) {
}
/**
* @param username
*/
public updateUsername(username: string | null): void {
if (typeof window.localStorage !== 'undefined' && username !== window.localStorage.getItem('username')) {
window.localStorage.setItem('username', username);
}
this.usernameSource.next(username);
}
public initUsername(): void {
if (typeof window.localStorage !== 'undefined' && null !== window.localStorage.getItem('username')) {
this.usernameSource.next(window.localStorage.getItem('username'));
} else {
this.nsService.socket.emit('get_username');
this.onNewUsername().pipe(
take(1),
filter((username: string) => (new RegExp('^(player_){1}([a-zA-Z0-9]{9})$')).test(username))
).subscribe((username: string) => {
this.usernameSource.next(username);
})
}
}
private onNewUsername() {
return Observable.create((observer) => {
this.nsService.socket.on('get_username', (username: string) => {
observer.next(username);
});
});
}
}
|
dcf054de441bb27908f9abb45a253f0c776bebe6
|
TypeScript
|
PScottZero/MNISTPlayground
|
/image-generator-experiment/src/app/classes/NeuralNetwork.ts
| 2.71875
| 3
|
import { Layer } from './Layer';
import { math } from './mathjs';
export class NeuralNetwork {
size: number[];
layers: Layer[];
epochCount: number;
eta: number;
accuracy: number;
constructor(size: number[], epochCount: number, eta: number) {
this.configureNetwork(size);
this.size = size;
this.epochCount = epochCount;
this.eta = eta;
this.accuracy = 0;
}
configureNetwork(size: number[]): void {
let prevLayer;
let isOutput = false;
this.layers = [];
size.forEach((layerSize, index) => {
if (index === size.length - 1) {
isOutput = true;
}
const newLayer = new Layer(layerSize, prevLayer, isOutput);
this.layers.push(newLayer);
prevLayer = newLayer;
});
}
configureNetworkFromJSON(networkJSON: any): void {
this.layers = [];
for (const layer of networkJSON.layers) {
const newLayer = new Layer(0, undefined, false);
newLayer.weights = layer.weights;
newLayer.biases = layer.biases;
newLayer.isOutput = layer.isOutput;
newLayer.size = layer.size;
newLayer.activValues = math.zeros(layer.size);
this.layers.push(newLayer);
}
this.size = networkJSON.size;
this.epochCount = networkJSON.epochCount;
this.eta = networkJSON.eta;
this.accuracy = networkJSON.accuracy;
this.restorePrevLayers();
}
removePrevLayers(): void {
for (const layer of this.layers) {
layer.prevLayer = undefined;
}
}
restorePrevLayers(): void {
for (let layerNo = 1; layerNo < this.layers.length; layerNo++) {
this.layers[layerNo].prevLayer = this.layers[layerNo - 1];
}
}
}
|
7dc1674093785081b3b990e12c1b86f10ad046db
|
TypeScript
|
Polvista/ng2-seed
|
/app/store/mutations/ProxyMutationManager.ts
| 2.59375
| 3
|
import {MutationManager} from "./MutationManager";
import {AppState} from "../AppState";
import {Immutable} from "./MutationManager";
export class ProxyMutationManager extends MutationManager {
protected enhanceMutableObject(mutableObject: any, origObject: any, path: string[]): any {
return new Proxy(mutableObject, this.createMutationHandler(path, origObject));
}
private createMutationHandler(path, immutableOriginalObject) {
const manager = this;
return {
set(target, name: string, val) {
manager.changes.push({
type: 'update',
path: [...path, name],
val
});
target[MutationManager.CHANGE_WATCHER_PROPERTY].notifyAboutChange();
manager.invalidateCacheForObject(immutableOriginalObject);
target[name] = val;
return true;
},
deleteProperty(target, name: string) {
manager.changes.push({
type: 'delete',
path: [...path, name]
});
target[MutationManager.CHANGE_WATCHER_PROPERTY].notifyAboutChange();
manager.invalidateCacheForObject(immutableOriginalObject);
return true;
}
}
}
synchronizeState(state: AppState, mutatedState: AppState): AppState {
return super.applyChangesToState(state);
}
}
|
a83c8205bbb42a99b46f6f2e8d63b176603d021a
|
TypeScript
|
ErickSaito/ecommerce
|
/backend/src/middlewares/Handler.ts
| 2.515625
| 3
|
import axios from 'axios';
import { Options } from './Types';
export const CLIENT_TIMEOUT = 5 * 60 * 1000;
export const axiosClient = (baseURL?: string, options?: Options) => {
if (!options?.axiosInstance) {
return axios.create({
baseURL,
timeout: CLIENT_TIMEOUT,
withCredentials: true,
...parseOptions(options),
});
} else {
return options.axiosInstance;
}
};
export function parseOptions(options: Options) {
if (options) {
const { cacheControl } = options;
return {
...options,
...(!!cacheControl && {
params: {
'cache-control': cacheControl,
},
}),
};
}
}
|
48857f739ee9a221210c7030a738de1c7d637509
|
TypeScript
|
lhcopetti/AlgebraicNotationChess
|
/src/chess/core/ChessSquare.ts
| 3.609375
| 4
|
class ChessSquare {
private _file: string;
private _rank: string;
private constructor(file: string, rank: string) {
this._file = file;
this._rank = rank;
}
public static fromString(square: string) {
const file = square[0];
const rank = Number(square[1]);
if (files.indexOf(file) < 0 || ranks.indexOf(rank) < 0) return null;
return new ChessSquare(file, `${rank}`);
}
public toString(): string {
return this.file + this.rank;
}
public get file() {
return this._file;
}
public get rank() {
return this._rank;
}
public get down(): ChessSquare | null {
const newRank = Number(this.rank) - 1;
return ChessSquare.fromString(this.file + newRank);
}
public get up(): ChessSquare | null {
const newRank = 1 + Number(this.rank);
return ChessSquare.fromString(this.file + newRank);
}
public get left(): ChessSquare | null {
const leftFile = files[files.indexOf(this.file) - 1];
return ChessSquare.fromString(leftFile + this.rank);
}
public get right(): ChessSquare | null {
const rightFile = files[files.indexOf(this.file) + 1];
return ChessSquare.fromString(rightFile + this.rank);
}
public equals(otherSquare: ChessSquare) {
return this.file == otherSquare.file && this.rank == otherSquare.rank;
}
}
const files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
const ranks = [1, 2, 3, 4, 5, 6, 7, 8];
const initialRankForWhite = 2;
const initialRankForBlack = 7;
export {
ChessSquare, files, ranks, initialRankForWhite, initialRankForBlack,
};
|
4b38a225a155524330a9bbcc66f4d408ce97a8dc
|
TypeScript
|
kubarozycki/conecta
|
/AngularClient/webApp/src/app/pipes/height.pipe.ts
| 2.53125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'height'
})
export class HeightPipe implements PipeTransform {
readonly Unit:string;
constructor(){
this.Unit="cm"
}
transform(value: any, args?: any): any {
return `${value} ${this.Unit}`;
}
}
|
40c98926e9b12ca4620d8c8d4cd838147127a8bb
|
TypeScript
|
skydy/angular
|
/src/app/components/news/news.component.ts
| 2.71875
| 3
|
/* 引入核心模块里面的Component */
import { Component, OnInit } from '@angular/core';
//引入并且配置服务
import { StorageService } from '../../services/storage.service'
// 不推荐
// var storage =new StorageService();
// console.log(storage)
// 请求服务
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router'
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
public title:string = "这是新闻msg";
public arr:number[] = [111,222,333];
public binding:string = "";
public base:string;
constructor(
public storage:StorageService,
public http:HttpClient,
public route:ActivatedRoute
){
this.title = "这个是修改后的msg";
}
btn(e:number){
alert(e)
}
ac(){
this.binding = "996"
}
bas(){
this.storage.set("base",this.base)
console.log('this.storage.get("base")',this.storage.get("base"))
}
ngOnInit() {
let streem = this.storage.getRxjsData()
/* 发布订阅 */
let d = streem.subscribe((data)=>{
console.log(data)
})
/* 取消订阅 */
setTimeout(()=>{
d.unsubscribe();
},1000)
// get请求
let api = 'http://a.itying.com/api/productlist'
this.http.get(api).subscribe(res=>{
console.log(res)
},
error=>{
console.log(error)
})
// post请求
const httpOptions = {header:new HttpHeaders({"Content-Type": "application/json"})}
// let data={info:"info"}
// this.http.post(api,data,httpOptions).subscribe((res)=>{
// console.log(res)
// })
// 获取路由传值
this.route.queryParams.subscribe((data)=>{
console.log('路由值为:',data);
})
}
}
|
80075f565227bd33b7216167ab410318a34c0536
|
TypeScript
|
pilpod/FactoriaF5-CRUD-ApiMovies-Frontend
|
/src/ts/Domain/Services/MovieController.ts
| 2.640625
| 3
|
///<reference path="../Models/Movie.ts" />
///<reference path="../Contracts/IApiService.ts" />
///<reference path="../../Infrastructure/Api/Api.ts" />
namespace Controller {
export class MovieController implements Contract.ExternalApiData {
tmdb:Api.ApiMovie;
constructor(tmdb:Api.ApiMovie)
{
this.tmdb = tmdb;
}
public ListPopularMovies(): any
{
this.tmdb.PopularMovies()
.then(data => this.ShowAllPopularMovies(data));
}
public ShowAllPopularMovies(data:any)
{
const popularMovies = document.getElementById('popularMovies_section') as HTMLInputElement;
for (let i = 0; i < data['results'].length; i++) {
let poster:any = data['results'][i]['poster_path']
let title:string = data['results'][i]['title']
let id:number = data['results'][i]['id']
popularMovies.innerHTML += `
<div class="col-sm-12 col-md-6 col-lg-4 col-xl-3">
<div class="card mr-3 mt-3" style="width: 16rem;">
<img id="movie_img" src="https://image.tmdb.org/t/p/w500/${poster}" class="card-img-top" alt="...">
<div class="card-body">
<h5 id="movie_title" class="card-title"><a href="${id}">${title}</a></h5>
</div>
</div>
</div>`;
}
}
}
}
|
7c77c40c750932ee4fc09c639549516e6cfc48bb
|
TypeScript
|
san-nat/prime-simplereport
|
/frontend/src/app/admin/Organization/facilityAdminSchema.ts
| 2.90625
| 3
|
import * as yup from "yup";
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type RequiredAdminFields = PartialBy<FacilityAdmin, "middleName" | "suffix">;
export const facilityAdminSchema: yup.SchemaOf<RequiredAdminFields> = yup.object(
{
firstName: yup.string().required(),
middleName: yup.string().nullable(),
lastName: yup.string().required(),
suffix: yup.string().nullable(),
email: yup.string().email().required(),
}
);
type FacilityAdminErrorKeys = keyof FacilityAdmin;
export type FacilityAdminErrors = Partial<
Record<FacilityAdminErrorKeys, string>
>;
export const allFacilityAdminErrors: Required<FacilityAdminErrors> = {
firstName: "First name is missing",
middleName: "Middle name is missing",
lastName: "Last name is missing",
suffix: "Suffix is missing",
email: "Email is incorrectly formatted",
};
|
11fa98d37bc113770b12b557e118abbe8d6c9a3e
|
TypeScript
|
heuristicAL/fullstack-ts-react-nest
|
/shared/entities/entityBase.ts
| 3.359375
| 3
|
import { CreateDateColumn, PrimaryGeneratedColumn, UpdateDateColumn, VersionColumn } from 'typeorm';
/**
* Abstract class to define the base fields and columns for an Entity.
* @param T The type of the child class inheriting from {@link BaseEntity}
*/
export abstract class EntityBase<T> {
@PrimaryGeneratedColumn()
id: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@VersionColumn()
version: number;
/**
* @param {T} init The initialization parameters for the entity.
* @returns {T} New instance of type {@link T}.
*/
constructor(init?: Partial<T>) {
Object.assign(this, init);
}
}
|
2d7c586dfa808e90b009cefd740b77acd6f385db
|
TypeScript
|
jayarjo/jamp3
|
/src/lib/common/stream-writer.ts
| 3
| 3
|
import fs from 'fs';
import {BufferUtils} from './buffer';
import {synchsafe, unbitarray} from './utils';
import {ascii, IEncoding} from './encodings';
const MemoryStream = require('memory-stream'); // TODO: type Memorystream
export class WriterStream {
protected wstream: fs.WriteStream;
constructor() {
this.wstream = new MemoryStream();
}
writeByte(byte: number) {
const buf = BufferUtils.zeroBuffer(1);
buf.writeUInt8(byte, 0);
this.wstream.write(buf);
}
writeBytes(bytes: Array<number>) {
this.wstream.write(BufferUtils.fromArray(bytes));
}
writeBitsByte(bits: Array<number>) {
while (bits.length < 8) {
bits.push(0);
}
this.writeByte(unbitarray(bits));
}
writeBuffer(buffer: Buffer) {
this.wstream.write(buffer);
}
writeSyncSafeInt(int: number) {
this.writeUInt(synchsafe(int), 4);
}
writeUInt(int: number, byteLength: number) {
const buf = BufferUtils.zeroBuffer(byteLength);
buf.writeUIntBE(int, 0, byteLength);
this.wstream.write(buf);
}
writeUInt2Byte(int: number) {
this.writeUInt(int, 2);
}
writeUInt3Byte(int: number) {
this.writeUInt(int, 3);
}
writeUInt4Byte(int: number) {
this.writeUInt(int, 4);
}
writeSInt(int: number, byteLength: number) {
const buf = BufferUtils.zeroBuffer(byteLength);
buf.writeIntBE(int, 0, byteLength);
this.wstream.write(buf);
}
writeSInt2Byte(int: number) {
this.writeSInt(int, 2);
}
writeEncoding(enc: IEncoding) {
this.writeByte(enc.byte);
}
writeString(val: string, enc: IEncoding) {
if (enc.bom) {
this.writeBytes(enc.bom);
}
this.wstream.write(enc.encode(val));
}
writeStringTerminated(val: string, enc: IEncoding) {
if (enc.bom) {
this.writeBytes(enc.bom);
}
this.wstream.write(enc.encode(val));
this.writeTerminator(enc);
}
writeAsciiString(val: string, length: number) {
while (val.length < length) {
val += ' ';
}
this.wstream.write(val.slice(0, length), 'ascii');
}
writeAscii(val: string) {
this.wstream.write(val, 'ascii');
}
writeTerminator(enc: IEncoding) {
this.writeBuffer(enc.terminator);
}
writeFixedBuffer(buffer: Buffer, size: number) {
const padding = size - buffer.length;
if (padding > 0) {
const pad = BufferUtils.zeroBuffer(padding);
buffer = BufferUtils.concatBuffer(buffer, pad);
}
this.writeBuffer(buffer);
}
writeFixedAsciiString(val: string, size: number) {
const buf = ascii.encode(val.slice(0, size)).slice(0, size);
this.writeFixedBuffer(buf, size);
}
// writeFixedUTF8String(val: string, size: number) {
// const buf = utf8.encode(val.slice(0, size)).slice(0, size);
// this.writeFixedBuffer(buf, size);
// }
}
|
af3ddea76227d3f0e34748747aadc6c0a15953a7
|
TypeScript
|
Nekor4/type-engine
|
/src/engine/core/engine.ts
| 2.859375
| 3
|
import { GameObject } from "./game-object";
import { Collision } from "../colliders";
export class Engine {
private _canvas: HTMLCanvasElement;
private inGameObjects: Array<GameObject> = [];
private isPauzed = false;
public static ctx: CanvasRenderingContext2D;
/** Creates new canvas element on constructor
* @param width Width of canvas.
* @param height Height of canvas. */
constructor(width = 1280, height = 720) {
this.createCanvas(width, height);
console.log("Engine created!");
}
private createCanvas(width: number, height: number): void {
this._canvas = document.createElement("canvas");
// document.body.appendChild(this.canvas);
this._canvas.width = 1280;
this._canvas.height = 720;
this._canvas.style.border = "1px solid";
Engine.ctx = <CanvasRenderingContext2D>this._canvas.getContext("2d");
}
/** Adds game object to game objects array. */
public add(gameObject: GameObject): void {
this.inGameObjects.push(gameObject);
}
/** Starts game loop. */
public start(): void {
if (!this.isPauzed) {
console.log("Game starts!");
this.startObjects();
} else {
console.log("Game resumed!");
}
this.isPauzed = false;
this.gameLoop();
}
/** Pauses game loop. */
public pauze(): void {
console.log("Game paused!");
this.isPauzed = true;
}
/** Returns canvas element. */
public get canvas(): HTMLCanvasElement {
return this._canvas;
}
private startObjects(): void {
for (let i = 0; i < this.inGameObjects.length; i++)
if (this.inGameObjects[i])
this.inGameObjects[i].componentsStart();
}
private gameLoop(): void {
if (this.isPauzed) return;
requestAnimationFrame(() => { this.gameLoop() });
Engine.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
Collision.DetectCollistion(this.inGameObjects);
for (let i = 0; i < this.inGameObjects.length; i++) {
if (this.inGameObjects[i])
this.inGameObjects[i].componentsUpdateLoop();
}
}
}
|
926ce51813fb764f418fffd607691b38b2724071
|
TypeScript
|
JeniTurtle/typeorm-graphql
|
/example/lib/singleProgressTask.ts
| 2.53125
| 3
|
import * as path from 'path';
import * as is from 'is-type-of';
import { Application } from 'egg';
import { Container } from 'typedi';
export const startTask = (app: Application) => {
// 加载单进程任务文件夹
const taskDir = path.join(app.config.baseDir, 'app/task');
app.loader.loadToApp(taskDir, 'task');
// @ts-ignore
const tasks = app.task;
Object.getOwnPropertyNames(tasks).map(async key => {
if (is.class(tasks[key])) {
const instance = Container.get<SingleProgressTask>(tasks[key]).init(app);
await instance.run();
}
});
};
export abstract class SingleProgressTask {
public app: Application;
public disable = false;
private redisKey = 'single_progress_task_';
private isInit = false;
init(app: Application) {
this.redisKey += this.constructor.name;
this.app = app;
this.isInit = true;
return this;
}
async run() {
if (this.disable) {
return;
}
if (!this.isInit) {
throw new Error('Task uninitialized!');
}
// 设置redis标记
const ret = await this.app.redis.setnx(this.redisKey, new Date().getTime());
if (ret === 1) {
// 设置10分钟过期时间
await this.app.redis.expire(this.redisKey, 60 * 10);
await this.task(this.app);
}
}
abstract async task(app: Application);
}
|
f81ca0bc0f1d7b2e42df32e9cc347b858af13558
|
TypeScript
|
csstools/postcss-plugins
|
/plugins/postcss-pseudo-class-any-link/src/replace-any-link.ts
| 2.671875
| 3
|
import type { Result, Rule } from 'postcss';
import parser from 'postcss-selector-parser';
const linkAST = parser().astSync(':link').nodes[0];
const visitedAST = parser().astSync(':visited').nodes[0];
const areaHrefAST = parser().astSync('area[href]').nodes[0];
const hrefAST = parser().astSync('[href]').nodes[0];
export function replaceAnyLink(rule: Rule, result: Result, preserve: boolean, areaHrefNeedsFixing: boolean): boolean {
const updatedSelectors = [];
const untouchedSelectors = [];
try {
for (let i = 0; i < rule.selectors.length; i++) {
const selector = rule.selectors[i];
const updated = modifiedSelector(selector, areaHrefNeedsFixing);
if (updated.length) {
updatedSelectors.push(...updated);
} else {
untouchedSelectors.push(selector);
}
}
} catch (err) {
rule.warn(result, `Failed to parse selector : "${rule.selector}" with message: "${err.message}"`);
return false;
}
if (!updatedSelectors.length) {
return false;
}
rule.cloneBefore({
selectors: updatedSelectors,
});
if (untouchedSelectors.length) {
rule.cloneBefore({
selectors: untouchedSelectors,
});
}
if (!preserve) {
rule.remove();
}
return true;
}
function modifiedSelector(selector, areaHrefNeedsFixing) {
const out = [];
// update the selector
parser((selectorsAST) => {
const replacements = [];
selectorsAST.walkPseudos((pseudo) => {
if (pseudo.value.toLowerCase() !== ':any-link' || (pseudo.nodes && pseudo.nodes.length)) {
return;
}
if (!areaHrefNeedsFixing) {
replacements.push([linkAST.clone({}), visitedAST.clone({})]);
return;
}
const tags = getTagElementsNextToPseudo(pseudo);
if (tags.includes('area')) {
replacements.push([linkAST.clone({}), visitedAST.clone({}), hrefAST.clone({})]);
return;
}
if (tags.length) {
replacements.push([linkAST.clone({}), visitedAST.clone({})]);
return;
}
replacements.push([linkAST.clone({}), visitedAST.clone({}), areaHrefAST.clone({})]);
});
if (!replacements.length) {
return;
}
const replacementsCartesianProduct = cartesianProduct(...replacements);
replacementsCartesianProduct.forEach((replacement) => {
const clone = selectorsAST.clone({}) as parser.Selector;
clone.walkPseudos((pseudo) => {
if (pseudo.value.toLowerCase() !== ':any-link' || (pseudo.nodes && pseudo.nodes.length)) {
return;
}
insertNode(pseudo.parent, pseudo, replacement.shift());
pseudo.remove();
});
out.push(clone.toString());
});
}).processSync(selector);
return out;
}
function cartesianProduct(...args: Array<Array<parser.Node>>): Array<Array<parser.Node>> {
const r = [];
const max = args.length - 1;
function helper(arr, i) {
for (let j = 0, l = args[i].length; j < l; j++) {
const a = arr.slice(0);
a.push(args[i][j]);
if (i == max) {
r.push(a);
} else {
helper(a, i + 1);
}
}
}
helper([], 0);
return r;
}
function getTagElementsNextToPseudo(pseudo: parser.Pseudo) {
const tags = [];
let prev = pseudo.prev();
while (prev) {
if (prev.type === 'combinator' || parser.isPseudoElement(prev)) {
break;
}
if (prev.type === 'tag') {
tags.push(prev.value.toLowerCase());
}
prev = prev.prev();
}
let next = pseudo.next();
while (next) {
if (next.type === 'combinator' || parser.isPseudoElement(next)) {
break;
}
if (next.type === 'tag') {
tags.push(next.value.toLowerCase());
}
next = next.next();
}
return tags;
}
// Inserts a node around a given node.
// - in the same compound selector
// - try to keep the result serializable without side effects
function insertNode(container: parser.Container, aroundNode: parser.Node, node: parser.Node) {
let type = node.type;
if (node.type === 'selector' && node.nodes && node.nodes.length) {
type = node.nodes[0].type;
}
let start = -1;
let end = -1;
const index = container.index(aroundNode);
for (let i = index; i >= 0; i--) {
if (container.nodes[i].type === 'combinator' || parser.isPseudoElement(container.nodes[i].type)) {
break;
}
start = i;
}
if (type === 'tag') {
container.insertBefore(container.at(start), node);
return;
}
for (let i = index; i < container.nodes.length; i++) {
if (container.nodes[i].type === 'combinator' || parser.isPseudoElement(container.nodes[i].type)) {
break;
}
end = i;
}
for (let i = start; i <= end; i++) {
if (container.nodes[i].type === type) {
container.insertAfter(container.at(i), node);
return;
}
}
container.insertAfter(container.at(start), node);
return;
}
|
9c0d425075aeb92d46081eef19600403c1f74992
|
TypeScript
|
prajgit/reactjsexp
|
/src/store/customer-reducer.ts
| 2.90625
| 3
|
import { CustomerStoreModel } from './store-models/customer-model';
import { Action } from '../types/common';
const defaultData = {} as CustomerStoreModel;
//action creators name
export const GET_CUSTOMER_INFO = 'customer/GET_CUSTOMER_INFO';
export const CLEAR_CUSTOMER_INFO = 'customer/CLEAR_CUSTOMER_INFO';
export default function customerReducer(state: CustomerStoreModel = defaultData, action: Action) {
switch (action.type) {
case GET_CUSTOMER_INFO:
return { ...state, customerInfo: action.data };
case CLEAR_CUSTOMER_INFO:
return { ...state, customerInfo: null };
default:
return state;
}
}
|
bee6c0242bee730f5d75b4a9df4e72829ff49a08
|
TypeScript
|
ragu-framework/ragu-client-node
|
/src/adapters/axios.ts
| 2.515625
| 3
|
import {RequestAdapter, Request} from "../client";
import {ComponentResponse} from "../ragu-component";
import axios, {AxiosResponse, CancelTokenSource} from 'axios';
class AxiosRequest implements Request {
private readonly response: Promise<AxiosResponse<ComponentResponse>>;
private cancelToken: CancelTokenSource;
constructor(private readonly componentURL: string) {
this.cancelToken = axios.CancelToken.source();
this.response = axios.get(this.componentURL, { cancelToken: this.cancelToken.token });
}
cancel(): void {
this.cancelToken.cancel();
}
async resolve(): Promise<ComponentResponse> {
const response = await this.response;
return response.data;
}
}
export class AxiosRequestAdapter implements RequestAdapter {
request(componentURL: string): any {
return new AxiosRequest(componentURL);
}
}
|
e376e49d02c911543c2c3183b6694f9744ab94c5
|
TypeScript
|
krsakai/docker_pappeteer_sample
|
/functions/src/models/hitter_score.ts
| 2.625
| 3
|
import { JSON, JsonObject, JsonProperty } from "ta-json";
@JsonObject()
export class HitterScore {
/// 年
@JsonProperty('year')
year: string;
/// 打率
@JsonProperty('avg')
avg: string;
/// 試合数
@JsonProperty('games')
games: string;
/// 打数
@JsonProperty('atBat')
atBat: string;
/// 得点
@JsonProperty('score')
score: string;
/// 安打
@JsonProperty('hit')
hit: string;
/// 2塁打
@JsonProperty('twoBaseHit')
twoBaseHit: string;
/// 3塁打
@JsonProperty('threeBaseHit')
threeBaseHit: string;
/// 本塁打
@JsonProperty('homeRuns')
homeRuns: string;
/// 塁打数
@JsonProperty('totalBases')
totalBases: string;
/// 打点
@JsonProperty('runBattedIn')
runBattedIn: string;
/// 三振
@JsonProperty('strikeouts')
strikeouts: string;
/// 四球
@JsonProperty('basesOnBalles')
basesOnBalles: string;
/// 死球
@JsonProperty('hitByPitch')
hitByPitch: string;
/// 犠打
@JsonProperty('dacrificeHit')
dacrificeHit: string;
/// 犠飛
@JsonProperty('sacrificeFly')
sacrificeFly: string;
/// 盗塁
@JsonProperty('stolenBases')
stolenBases: string;
/// 出塁率
@JsonProperty('onbasePercentage')
onbasePercentage: string;
/// 長打率
@JsonProperty('sluggingPercentage')
sluggingPercentage: string;
constructor(list: (string | null)[], year: string) {
const _list: string[] = list.removeNull();
this.year = year;
this.avg = _list[0];
this.games = _list[1];
this.atBat = _list[2];
this.score = _list[3];
this.hit = _list[4];
this.twoBaseHit = _list[5];
this.threeBaseHit = _list[6];
this.homeRuns = _list[7];
this.totalBases = _list[8];
this.runBattedIn = _list[9];
this.strikeouts = _list[10];
this.basesOnBalles = _list[11];
this.hitByPitch = _list[12];
this.dacrificeHit = _list[13];
this.sacrificeFly = _list[14];
this.stolenBases = _list[15];
this.onbasePercentage = _list[16];
this.sluggingPercentage = _list[17];
}
toJson(): Object {
return JSON.parse(JSON.stringify(this))
}
}
|
e83246acd9faba4f244e54b87df210c659fc95f2
|
TypeScript
|
simotae14/DenoExercises
|
/12-query-for-a-permission/app.ts
| 2.765625
| 3
|
const desc = {
name: "read",
path: "../"
} as const;
// query for a permission
console.log(await Deno.permissions.query(desc));
// request permission
const status = await Deno.permissions.request(desc);
// query for a permission
console.log(await Deno.permissions.query(desc));
if (status.state === "granted") {
const results = await Deno.readDir("../");
for await (const result of results) {
console.log(result);
}
} else {
console.log("This program need permissions to read the current directory only.");
}
|
c704db0b6ee20b35fb3275bd71d9809c420ae8cb
|
TypeScript
|
AndelasOne/Open-Web-Chat
|
/server/src/messages.ts
| 2.828125
| 3
|
import { RequestHandler } from "express";
import { MessageSchema, IMessageDocument, IMessage } from "./types";
import { model, Model } from "mongoose";
// Create Message Model for one Room
const messageModel: Model<IMessageDocument> = model(
"message",
MessageSchema,
"messages"
);
// Get messages
const getMessages = async (room_id: number) => {
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1); // get messages from yesterday
yesterday.toDateString();
const messages = await messageModel.find({
room_id: room_id,
created_at: { $gt: yesterday }, //(not older than a day!)
});
return messages;
};
// Delete Messages in Room
const deleteMessagesById = async (room_id: number) => {
const res = await messageModel.deleteMany({
room_id: room_id,
});
return res.deletedCount;
};
const deleteMessagesByName = async (room_name: String) => {
const res = await messageModel.deleteMany({
room_name: room_name,
});
return res.deletedCount;
};
// Insert Message
const insertMessage = async (message: IMessage) => {
await messageModel.create(message);
console.log("Inserted Message by: " + message.username);
};
// Handle Message Get Request
const messagesLoad: RequestHandler = async (req, res) => {
if (!req.query.room_name || !req.query.room_id) {
console.log("No room_name or room_id given!");
res.status(404);
res.send({ error: "No room_name or room_id given!" });
return;
}
const room_name = req.query.room_name as IMessage["room_name"];
const room_id = Number(req.query.room_id);
// Get Messages from specific room
const messages = await getMessages(room_id);
console.log("Fetched Messages from room: " + room_name);
res.status(200);
res.send(messages);
};
export {
messagesLoad,
insertMessage,
deleteMessagesById,
deleteMessagesByName,
getMessages,
};
|
db3ada578d3948b8de3dc7f43cb03fc12e9edb23
|
TypeScript
|
pvSource/soda_shurup
|
/PepsiFactory.ts
| 2.5625
| 3
|
class PepsiFactory implements SodaFactory {
//Override
public createBottle(): Bottle {
return new PepsiBottle();
}
//Override
public createSoda(): Soda {
return new PepsiSoda();
}
//Override
public createLabel(): Label {
return new PepsiLabel();
}
//Override
public createCloser(): Closer {
return new PepsiCloser();
}
}
|
852d0bbef3cef2b515aea6698a706e0b4f9871f4
|
TypeScript
|
NewGyu/SegaPuyoPuyo
|
/test/StageEvent.test.ts
| 2.515625
| 3
|
import { StageEventObserver } from "~/models/StageEvent"
import { sleep } from "./testutil";
import { FallingPuyoPuyo } from "~/models/Puyo";
describe("StageEvent", () => {
const observer = new StageEventObserver();
it("can fire started event", async () => {
//given
const spy = jest.fn();
observer.on("started", () => spy());
//when
observer.emit("started");
await sleep(1);
//then
expect(spy).toBeCalled();
})
it("can fire newpuyo event", async () => {
//given
const spy = jest.fn();
observer.on("new puyo is put", np => spy(np));
//when
const newPuyoPuyo = new FallingPuyoPuyo({ x: 0, y: 0 });
observer.emit("new puyo is put", { newPuyoPuyo });
await sleep(1);
//then
expect(spy).toBeCalledWith({ newPuyoPuyo });
})
})
|
37e5ccc261235bbe357331cf2d1e3fe596b56d10
|
TypeScript
|
appellation/axios-ratelimiter
|
/src/index.ts
| 2.65625
| 3
|
import { AxiosAdapter, AxiosRequestConfig, AxiosResponse } from 'axios';
import Bucket from './Bucket';
export interface Headers {
global: string;
reset: string;
limit: string;
remaining: string;
retry: string;
}
export interface Config {
key: (method: string, url: string) => string;
headers: Headers;
}
export const buckets: Map<string, Bucket> = new Map();
export default (config: Config): AxiosAdapter => {
return (req: AxiosRequestConfig): Promise<AxiosResponse> => {
const route = config.key(req.method || 'get', req.url || '');
let b = buckets.get(route);
if (!b) {
b = new Bucket(config.headers);
buckets.set(route, b);
}
return b.enqueue(req);
}
}
|
f63d9e4333807f621f339dfad10660f0d0396ae5
|
TypeScript
|
skwon-mdsol/jsalgorithms
|
/src/HashTable.ts
| 3.46875
| 3
|
import DoublyLinkedList from './DoublyLinkedList';
interface IHashTable<V> {
table: DoublyLinkedList<DoublyLinkedList<V>>;
modNum: number;
numElements: number;
size(): number;
hash(key: string): number;
}
/*
const hash = hashfunc(key)
const index = hash % length
*/
export default class HashTable<V> implements IHashTable<V> {
table: DoublyLinkedList<DoublyLinkedList<V>>
modNum: number = 2069;
numElements: number;
constructor (size = 16) {
this.table = new DoublyLinkedList<DoublyLinkedList<V>>(null, null);
this.numElements = 0;
for (let i = 0; i < size; i++) {
this.table.append(new DoublyLinkedList<V>(null, null));
}
}
size(): number {
return this.numElements;
}
hash(key: string) {
/*
const hash: number = Array.from(key).reduce(
(hashAccumulator: number, keySymbol: string) => (hashAccumulator + keySymbol.charCodeAt(0)),
0,
);
return hash % this.table.size();
*/
return 0;
}
}
|
f172feb28edcd4a9e6760c1881a1a1df26db59b0
|
TypeScript
|
source-academy/js-slang
|
/src/stdlib/list.prelude.ts
| 3.984375
| 4
|
export const listPrelude = `
// equal computes the structural equality
// over its arguments
function equal(xs, ys) {
return is_pair(xs)
? (is_pair(ys) &&
equal(head(xs), head(ys)) &&
equal(tail(xs), tail(ys)))
: is_null(xs)
? is_null(ys)
: is_number(xs)
? (is_number(ys) && xs === ys)
: is_boolean(xs)
? (is_boolean(ys) && ((xs && ys) || (!xs && !ys)))
: is_string(xs)
? (is_string(ys) && xs === ys)
: is_undefined(xs)
? is_undefined(ys)
: is_function(xs)
// we know now that xs is a function,
// but we use an if check anyway to make use of the type predicate
? (is_function(ys) && xs === ys)
: false;
}
// returns the length of a given argument list
// assumes that the argument is a list
function $length(xs, acc) {
return is_null(xs) ? acc : $length(tail(xs), acc + 1);
}
function length(xs) {
return $length(xs, 0);
}
// map applies first arg f, assumed to be a unary function,
// to the elements of the second argument, assumed to be a list.
// f is applied element-by-element:
// map(f, list(1, 2)) results in list(f(1), f(2))
function $map(f, xs, acc) {
return is_null(xs)
? reverse(acc)
: $map(f, tail(xs), pair(f(head(xs)), acc));
}
function map(f, xs) {
return $map(f, xs, null);
}
// build_list takes a a function fun as first argument,
// and a nonnegative integer n as second argument,
// build_list returns a list of n elements, that results from
// applying fun to the numbers from 0 to n-1.
function $build_list(i, fun, already_built) {
return i < 0 ? already_built : $build_list(i - 1, fun, pair(fun(i), already_built));
}
function build_list(fun, n) {
return $build_list(n - 1, fun, null);
}
// for_each applies first arg fun, assumed to be a unary function,
// to the elements of the second argument, assumed to be a list.
// fun is applied element-by-element:
// for_each(fun, list(1, 2)) results in the calls fun(1) and fun(2).
// for_each returns true.
function for_each(fun, xs) {
if (is_null(xs)) {
return true;
} else {
fun(head(xs));
return for_each(fun, tail(xs));
}
}
// list_to_string returns a string that represents the argument list.
// It applies itself recursively on the elements of the given list.
// When it encounters a non-list, it applies to_string to it.
function $list_to_string(xs, cont) {
return is_null(xs)
? cont("null")
: is_pair(xs)
? $list_to_string(
head(xs),
x => $list_to_string(
tail(xs),
y => cont("[" + x + "," + y + "]")))
: cont(stringify(xs));
}
function list_to_string(xs) {
return $list_to_string(xs, x => x);
}
// reverse reverses the argument, assumed to be a list
function $reverse(original, reversed) {
return is_null(original)
? reversed
: $reverse(tail(original), pair(head(original), reversed));
}
function reverse(xs) {
return $reverse(xs, null);
}
// append first argument, assumed to be a list, to the second argument.
// In the result null at the end of the first argument list
// is replaced by the second argument, regardless what the second
// argument consists of.
function $append(xs, ys, cont) {
return is_null(xs)
? cont(ys)
: $append(tail(xs), ys, zs => cont(pair(head(xs), zs)));
}
function append(xs, ys) {
return $append(xs, ys, xs => xs);
}
// member looks for a given first-argument element in the
// second argument, assumed to be a list. It returns the first
// postfix sublist that starts with the given element. It returns null if the
// element does not occur in the list
function member(v, xs) {
return is_null(xs)
? null
: v === head(xs)
? xs
: member(v, tail(xs));
}
// removes the first occurrence of a given first-argument element
// in second-argument, assmed to be a list. Returns the original
// list if there is no occurrence.
function $remove(v, xs, acc) {
// Ensure that typechecking of append and reverse are done independently
const app = append;
const rev = reverse;
return is_null(xs)
? app(rev(acc), xs)
: v === head(xs)
? app(rev(acc), tail(xs))
: $remove(v, tail(xs), pair(head(xs), acc));
}
function remove(v, xs) {
return $remove(v, xs, null);
}
// Similar to remove, but removes all instances of v
// instead of just the first
function $remove_all(v, xs, acc) {
// Ensure that typechecking of append and reverse are done independently
const app = append;
const rev = reverse;
return is_null(xs)
? app(rev(acc), xs)
: v === head(xs)
? $remove_all(v, tail(xs), acc)
: $remove_all(v, tail(xs), pair(head(xs), acc));
}
function remove_all(v, xs) {
return $remove_all(v, xs, null);
}
// filter returns the sublist of elements of the second argument
// (assumed to be a list), for which the given predicate function
// returns true.
function $filter(pred, xs, acc) {
return is_null(xs)
? reverse(acc)
: pred(head(xs))
? $filter(pred, tail(xs), pair(head(xs), acc))
: $filter(pred, tail(xs), acc);
}
function filter(pred, xs) {
return $filter(pred, xs, null);
}
// enumerates numbers starting from start, assumed to be a number,
// using a step size of 1, until the number exceeds end, assumed
// to be a number
function $enum_list(start, end, acc) {
// Ensure that typechecking of reverse are done independently
const rev = reverse;
return start > end
? rev(acc)
: $enum_list(start + 1, end, pair(start, acc));
}
function enum_list(start, end) {
return $enum_list(start, end, null);
}
// Returns the item in xs (assumed to be a list) at index n,
// assumed to be a nonnegative integer.
// Note: the first item is at position 0
function list_ref(xs, n) {
return n === 0
? head(xs)
: list_ref(tail(xs), n - 1);
}
// accumulate applies an operation op (assumed to be a binary function)
// to elements of sequence (assumed to be a list) in a right-to-left order.
// first apply op to the last element and initial, resulting in r1, then to
// the second-last element and r1, resulting in r2, etc, and finally
// to the first element and r_n-1, where n is the length of the
// list.
// accumulate(op, zero, list(1, 2, 3)) results in
// op(1, op(2, op(3, zero)))
function $accumulate(f, initial, xs, cont) {
return is_null(xs)
? cont(initial)
: $accumulate(f, initial, tail(xs), x => cont(f(head(xs), x)));
}
function accumulate(f, initial, xs) {
return $accumulate(f, initial, xs, x => x);
}
`
|
c3b6ef36f50eadf0e5a291a3fdf63c0fe61b9ed9
|
TypeScript
|
cooperhsiung/vesicle
|
/src/decorator/core.ts
| 2.515625
| 3
|
import 'reflect-metadata';
import { Server, ServerOptions } from '../server';
const ACTIONS = 'ACTIONS';
const ACTION_MAP = 'ACTION_MAP';
const SERVICE_NAME = 'SERVICE_NAME';
export const Service = (args?: any): ClassDecorator => (target: any) => {};
export const Action = (args?: any): MethodDecorator => (
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
const actionMap = Reflect.getMetadata(ACTION_MAP, target) || {};
const actionName = `${target.constructor.name.toLowerCase()}.${propertyKey as string}`;
actionMap[actionName] = descriptor.value;
Reflect.defineMetadata(ACTION_MAP, actionMap, target);
};
export const Module = (services: any[]): ClassDecorator => (target: any) => {
const actions = Reflect.getMetadata(ACTIONS, target) || {};
for (const service of services) {
const amap = Reflect.getMetadata(ACTION_MAP, service.prototype);
Object.assign(actions, amap);
}
Reflect.defineMetadata(ACTIONS, actions, target);
};
export class Factory {
static create(m: any, options?: ServerOptions): Server {
const actions = Reflect.getMetadata(ACTIONS, m);
const server = new Server(options);
Object.keys(actions).forEach(k => {
server.addAction({ name: k, handler: actions[k] });
});
return server;
}
}
|
1d5f2fce6fc4591f7efd72a12c554ffe1a8c13b5
|
TypeScript
|
lotooo/terraforming-mars
|
/src/cards/PowerSupplyConsortium.ts
| 3
| 3
|
import { IProjectCard } from "./IProjectCard";
import { Tags } from "./Tags";
import { CardType } from "./CardType";
import { Player } from "../Player";
import { Game } from "../Game";
import { SelectPlayer } from "../inputs/SelectPlayer";
import { Resources } from '../Resources';
export class PowerSupplyConsortium implements IProjectCard {
public cost: number = 5;
public tags: Array<Tags> = [Tags.ENERGY];
public name: string = "Power Supply Consortium";
public cardType: CardType = CardType.AUTOMATED;
private getPlayersWithEnergyProduction(currentPlayer: Player, game: Game): Array<Player> {
var players = game.getPlayers().filter((p) => p.getProduction(Resources.ENERGY) > 0);
if (players.length > 1) {
players = players.filter((p) => p.id != currentPlayer.id)
}
return players
}
private doPlay(currentPlayer: Player, targetPlayer: Player, game: Game): void {
targetPlayer.setProduction(Resources.ENERGY,-1,game,currentPlayer);
currentPlayer.setProduction(Resources.ENERGY);
}
public canPlay(player: Player, game: Game): boolean {
if (player.getTagCount(Tags.ENERGY) < 2) return false;
if (game.getPlayers().length == 1) return true;
return this.getPlayersWithEnergyProduction(player, game).length > 0;
}
public play(player: Player, game: Game) {
if (game.getPlayers().length == 1) {
player.setProduction(Resources.ENERGY);
return undefined;
}
const players = this.getPlayersWithEnergyProduction(player, game);
if (players.length === 1) {
this.doPlay(player, players[0], game);
return undefined;
}
return new SelectPlayer(
players,
"Select player to decrease energy",
(foundPlayer: Player) => {
if (foundPlayer.getProduction(Resources.ENERGY) < 1) {
throw "Player must have energy production to remove";
}
foundPlayer.setProduction(Resources.ENERGY,-1,game,player);
player.setProduction(Resources.ENERGY);
return undefined;
}
);
}
}
|
4d04cf535fb378ad005cdb3aeb24fc706af2086e
|
TypeScript
|
bryant-pham/DIP-color-processing-fe
|
/src/app/reducers/actions/image.action.ts
| 2.671875
| 3
|
import { Action } from '@ngrx/store';
import { Image } from '../../models/image';
export enum ActionTypes {
SET_IMAGES = '[Image Component] Set Images',
ADD_IMAGE = '[Image Component] Add Image',
SELECT_IMAGE = '[Image Component] Select Image',
}
export interface ActionWithPayload<T> extends Action {
payload: T;
}
export class SetImages implements ActionWithPayload<Image[]> {
public readonly type = ActionTypes.SET_IMAGES;
constructor(public payload: Image[]) {}
}
export class AddImage implements ActionWithPayload<Image> {
public readonly type = ActionTypes.ADD_IMAGE;
constructor(public payload: Image) {}
}
export class SelectImage implements ActionWithPayload<Image> {
public readonly type = ActionTypes.SELECT_IMAGE;
constructor(public payload: Image) {}
}
|
dc80cc3e6e22d70e01fdb25245da55bebefb265e
|
TypeScript
|
EmJee1/Blackjack
|
/src/Player.ts
| 3.125
| 3
|
import Card from './Card'
class Player {
private playerName: string
private cards: Card[] = []
constructor(playerName: string | number) {
this.playerName = playerName.toString()
}
public drawCard(cardDeck: Card[]) {
const randomIndex = Math.floor(Math.random() * cardDeck.length)
this.cards[
this.cards.push(cardDeck.splice(randomIndex, 1)[0]) - 1
].showCard = true
}
}
export default Player
|
c92448f18170b3417a17a433d0d74a2841e5bdca
|
TypeScript
|
abhinav1144/aws_angular_pipeline
|
/dotx-portal-ui/src/app/shared/table/table-filter.pipe.ts
| 2.921875
| 3
|
import { Pipe, PipeTransform, Injectable } from '@angular/core';
import * as moment from 'moment';
import filter from 'lodash/filter';
@Pipe({
name: 'tFilter',
pure: false
})
@Injectable()
export class TableFilterPipe implements PipeTransform {
/**
* @param items object from array
* @param term term's search
* @param dateFormat array of strings which are in date formats
*/
transform(items: any, term: string, dateFormat: any = []): any {
if (!term || !items) {
return items;
}
filter(items, function (item: any): any {
if (dateFormat && dateFormat.length) {
dateFormat.forEach(val => {
item[val] = item[val] ? moment(item[val]).format('MM/DD/YYYY') : item[val];
});
}
});
return TableFilterPipe.filter(items, term);
}
/**
*
* @param items List of items to filter
* @param term a string term to compare with every property of the list
*
*/
static filter(items: Array<{ [key: string]: any }>, term: string): Array<{ [key: string]: any }> {
const toCompare = term.toLowerCase();
// tslint:disable-next-line: no-shadowed-variable
function checkInside(item: any, term: string): boolean {
if (typeof item === 'string' && item.toString().toLowerCase().includes(toCompare)) {
return true;
}
for (const property in item) {
if (item[property] === null || item[property] === undefined) {
continue;
}
if (typeof item[property] === 'object') {
if (checkInside(item[property], term)) {
return true;
}
} else if (item[property].toString().toLowerCase().includes(toCompare)) {
return true;
}
}
return false;
}
return items.filter((item) => {
return checkInside(item, term);
});
}
}
|
d1b0b69f7eb75f1e69b3207fa0edfea137108492
|
TypeScript
|
AlexVestin/wwv
|
/src/app/shared/period.ts
| 3.75
| 4
|
/*
* All dates are considered in the local timezone.
*/
/*
* Possible spans of intervals/periods.
*/
export enum PeriodWidth {
POINT,
HOUR,
DAY,
WEEK,
MONTH,
YEAR,
}
export function periodString(period: PeriodWidth): string {
const periods: Map<PeriodWidth, string> = new Map([
[PeriodWidth.POINT, 'Per punkt'],
[PeriodWidth.HOUR, 'Per timme'],
[PeriodWidth.DAY, 'Per dygn'],
[PeriodWidth.WEEK, 'Per vecka'],
[PeriodWidth.MONTH, 'Per månad'],
[PeriodWidth.YEAR, 'Per år'],
]);
return periods.get(period);
}
/*
* Calculate the start of the period that a date is within.
* example:
* 12:00 on 23 feb 2019, span=month
* returns
* 00:00 on 1 feb 2019
*/
export function startOfPeriod(time: Date, span: PeriodWidth): Date {
const beg: Date = new Date(0);
beg.setHours(0, 0, 0, 0); // adjust for local timezone
switch (span) {
case PeriodWidth.POINT:
beg.setTime(time.getTime());
break;
case PeriodWidth.WEEK:
// set the same day
beg.setFullYear(time.getFullYear(), time.getMonth(), time.getDate());
// set to monday the same week
const msInADay = 1000 * 3600 * 24;
const timeOffset = ((((beg.getDay() - 1) % 7) + 7) % 7) * msInADay;
beg.setTime(beg.getTime() - timeOffset);
break;
case PeriodWidth.HOUR:
beg.setHours(time.getHours());
/* falls through */
case PeriodWidth.DAY:
beg.setDate(time.getDate());
/* falls through */
case PeriodWidth.MONTH:
beg.setMonth(time.getMonth());
/* falls through */
case PeriodWidth.YEAR:
beg.setFullYear(time.getFullYear());
}
return beg;
}
/*
* Determine if two dates are within the same time period.
*/
export function samePeriod(t1: Date, t2: Date,
span: PeriodWidth): boolean {
switch (span) {
case PeriodWidth.POINT:
return t1.getTime() === t2.getTime();
case PeriodWidth.WEEK:
return t1.getWeek() === t2.getWeek() &&
t1.getWeekYear() === t2.getWeekYear();
case PeriodWidth.HOUR:
if (t1.getHours() !== t2.getHours()) {
return false;
}
/* falls through */
case PeriodWidth.DAY:
if (t1.getDate() !== t2.getDate()) {
return false;
}
/* falls through */
case PeriodWidth.MONTH:
if (t1.getMonth() !== t2.getMonth()) {
return false;
}
/* falls through */
case PeriodWidth.YEAR:
if (t1.getFullYear() !== t2.getFullYear()) {
return false;
}
}
return true;
}
|
68861f8a0f315b94b4bf6ff6865a1540524e84e3
|
TypeScript
|
fatenyahyaoui/SpringProject_Frontend
|
/src/app/message/messageservice.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import { Http, Response, Headers, URLSearchParams, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import { Message } from './message';
@Injectable()
export class MessageserviceService {
//URLs for CRUD operations
allMessagesUrl = "http://localhost:8080/all-messages";
messageUrl = "http://localhost:8080/message";
//Create constructor to get Http instance
constructor(private http:Http) { }
//Fetch all messages
getAllMessages(): Observable<Message[]> {
return this.http.get(this.allMessagesUrl)
.map(this.extractData)
.catch(this.handleError);
}
//Create message
createMessage(message: Message):Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.post(this.messageUrl,message, options)
.map(success => success.status)
.catch(this.handleError);
}
//Fetch message by id
getMessageById(messageId: string): Observable<Message> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let cpParams = new URLSearchParams();
cpParams.set('id', messageId);
let options = new RequestOptions({ headers: cpHeaders, params: cpParams });
return this.http.get(this.messageUrl, options)
.map(this.extractData)
.catch(this.handleError);
}
//Delete message
deleteMessageById(messageId: string): Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let cpParams = new URLSearchParams();
cpParams.set('id', messageId);
let options = new RequestOptions({ headers: cpHeaders, params: cpParams });
return this.http.delete(this.messageUrl, options)
.map(success => success.status)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleError (error: Response | any) {
console.error(error);
return Observable.throw(error.status);
}
}
|
789f1d48c7a17db5708737d045875b71819d96e3
|
TypeScript
|
irla/irla.github.io
|
/lib/filter.ts
| 3.125
| 3
|
export const isNotBlank = (filter?: String): boolean => {
return filter !== undefined && filter.trim().length > 0
}
const equivalents: Map<string, Array<string>> = new Map([
["jms", ["rabbitmq", "activemq"]],
["rmq", ["rabbitmq"]],
["amq", ["activemq"]],
["cloud", ["aws", "gcp"]],
["event", ["axon"]],
["sql", ["db2"]],
["jvm", ["java", "groovy", "kotlin"]]
])
const contains = (filter: string, skillName: string): boolean => {
return skillName.toLowerCase().includes(filter.toLowerCase())
}
const containsEquivalent = (filter: string, skillName: string) => {
const options = equivalents.get(filter.toLowerCase())
if (options) {
return options.find((option: string) => contains(option, skillName)) !== undefined
}
return false
}
const javaAndJavaScript = (filter: string, skillName: string): boolean => {
return filter.toLowerCase() === "java" && skillName.toLowerCase() === "javascript"
}
export const filterMatches = (filter: string, skillName: string): boolean => {
return isNotBlank(filter) && !javaAndJavaScript(filter, skillName) && (
contains(filter, skillName) ||
containsEquivalent(filter, skillName)
)
}
|
9560d525283fa78b212f3160ba3798d70f1b5468
|
TypeScript
|
GitVitor/Vue3-mycoincap
|
/src/composables/use-promise.ts
| 2.828125
| 3
|
import { reactive, toRefs } from "vue";
interface State {
loading: boolean;
error: any;
result?: {
data: object;
};
}
export default function usePromise(
fn: (
args?: any
) => Promise<{
data: object;
}>
) {
const state = reactive<State>({
loading: false,
error: null,
result: undefined,
});
const use = async (...args: any) => {
state.error = null;
state.loading = true;
state.result = undefined;
try {
const result = await fn(...args);
state.result = result;
state.loading = false
} catch (error) {
state.error = error;
}
};
return {
...toRefs(state),
use,
};
}
|
2abc2b691c32e8087225ba963093e38beed4cd25
|
TypeScript
|
ederivero/TypeScript-Challenge-Eduardo
|
/2_medium/8_readOnly.ts
| 3.78125
| 4
|
interface Todo {
title: string
description: string
completed: boolean
}
type MyReadonly2<T, K extends keyof T = keyof T >={
readonly [U in K]: T[K]
} &{
[N in Exclude<keyof T,K>]: T[N]
}
const todo: MyReadonly2<Todo, 'title' | 'description'> = {
title: "Hey",
description: "foobar",
completed: false,
}
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK
// ✔
|
dbd416184d2636196f5ef923c30a7ed40db9bf50
|
TypeScript
|
Kobzol/cuda-profile
|
/visualization/src/lib/file-load/file.ts
| 2.625
| 3
|
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import {Metadata} from '../serialization/metadata';
import {readFile} from '../util/fs';
import {createWorkerJob} from '../util/worker';
import {InvalidFileContent, InvalidFileFormat} from './errors';
import {Run} from '../serialization/run';
import {Trace} from '../serialization/trace';
import JsonWorker from '../../worker/json.worker';
import CapnpWorker from '../../worker/capnp.worker';
import ProtobufWorker from '../../worker/protobuf.worker';
export enum FileType
{
Trace = 0,
Metadata = 1,
Run = 2,
Unknown = 3,
Invalid = 4
}
export interface TraceFile
{
name: string;
loading: boolean;
content: Trace | Metadata | Run | null;
type: FileType;
error: number;
}
export interface FileLoadData
{
type: FileType;
content: Trace | Metadata;
}
/**
* Loads file and parses its content as JSON using a web worker.
* @param {File} file
* @param {boolean} decompress
* @returns {Observable<Object>}
*/
function parseFileJson(file: File, decompress: boolean): Observable<Trace | Metadata | Run>
{
return readFile(file, false, decompress)
.flatMap(data => createWorkerJob(new JsonWorker(), data));
}
/**
* Loads file and parses its content as Protobuf using a web worker.
* @param {File} file
* @param {boolean} decompress
* @returns {Observable<Object>}
*/
function parseFileProtobuf(file: File, decompress: boolean): Observable<Trace>
{
return readFile(file, true, decompress)
.flatMap(data => createWorkerJob(new ProtobufWorker(), data));
}
/**
* Loads file and parses its content as Cap'n Proto using a web worker.
* @param {File} file
* @param {boolean} decompress
* @returns {Observable<Object>}
*/
function parseFileCapnp(file: File, decompress: boolean): Observable<Trace>
{
return readFile(file, true, decompress)
.flatMap(data => createWorkerJob(new CapnpWorker(), data));
}
/**
* Loads file as JSON or Cap'n Proto, according to the extension (.json or .capnp).
* @param {File} file
* @returns {Observable<Object>}
*/
function parseFile(file: File): Observable<Trace | Metadata | Run>
{
if (file.name.match(/\.json$/))
{
return parseFileJson(file, file.name.match(/\.gzip\.json$/) !== null);
}
if (file.name.match(/\.protobuf$/))
{
return parseFileProtobuf(file, file.name.match(/\.gzip\.protobuf$/) !== null);
}
else if (file.name.match(/\.capnp$/))
{
return parseFileCapnp(file, file.name.match(/\.gzip\.capnp/) !== null);
}
else return Observable.throw(new InvalidFileFormat());
}
/**
* Checks validity of trace object.
* @param {Object} content
* @returns {Observable<Trace>}
*/
function validateTrace(content: object): boolean
{
return (
content['type'] === 'trace' &&
'kernel' in content &&
'warps' in content
);
}
/**
* Checks validity of metadata object.
* @param {Object} content
* @returns {boolean}
*/
function validateMetadata(content: object): boolean
{
return (
content['type'] === 'metadata' &&
'kernel' in content
);
}
/**
* Checks validity of run object.
* @param {Object} content
* @returns {boolean}
*/
function validateRun(content: object): boolean
{
return (
content['type'] === 'run' &&
'start' in content &&
'end' in content
);
}
/**
* Checks validity of file content depending on its type.
* @param {File} file
* @param {Object} content
* @returns {boolean}
*/
function validateContent(file: File, content: object): boolean
{
const type = getFileType(file);
switch (type)
{
case FileType.Metadata: return validateMetadata(content);
case FileType.Run: return validateRun(content);
case FileType.Trace: return validateTrace(content);
default: return false;
}
}
/**
* Returns file type, depending on file name.
* @param {File} file
* @returns {FileType}
*/
function getFileType(file: File): FileType
{
if (file.name === 'run.json')
{
return FileType.Run;
}
const metadata = file.name.match(/.*\.metadata\..*/);
return metadata !== null ? FileType.Metadata : FileType.Trace;
}
/**
* Loads file, parses it and creates appropriate data structure (trace or metadata).
* @param {File} file
* @returns {Observable<FileLoadData>}
*/
export function parseAndValidateFile(file: File): Observable<FileLoadData>
{
return parseFile(file)
.catch(error => {
if (!(error instanceof InvalidFileFormat))
{
return Observable.throw(new InvalidFileContent());
}
else return Observable.throw(error);
})
.do(content => {
if (!validateContent(file, content))
{
throw new InvalidFileContent();
}
})
.map(content => ({
type: getFileType(file),
content
}));
}
|
548312998527aebb3869bf86cd67afff3000ab7a
|
TypeScript
|
D0vid/music-tendency
|
/src/Models/MessageSenderHelper.ts
| 2.828125
| 3
|
import { TextChannel, DMChannel, MessageEmbed } from "discord.js";
import { Song } from "./Song";
import { stringify } from "querystring";
const fs = require("fs");
export class MessageSenderHelper{
static readonly header : string = fs.readFileSync("././assets/ascii/header.txt", "ascii");
static readonly help : string = fs.readFileSync("././assets/ascii/help.txt", "utf8");
static PrintStop(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription("⏹ Stopped playing.");
channel.send(embed);
}
static PrintNowPlaying(song : Song){
let embed = new MessageEmbed()
.setColor('#6300aa')
.setTitle(song?.title)
.setURL(song.Uri as string)
.setAuthor("▶ Now Playing" , "https://i.imgur.com/l0hxro3.png" , song.Uri as string)
.setThumbnail(song.Thumbnail as string)
.addFields([
{ name: 'Duration', value: song.DurationAsString, inline: true },
{ name: 'Added by', value: `${song.Sender}`, inline: true }
])
.setFooter('Music Tendency', "https://i.imgur.com/l0hxro3.png")
.setTimestamp(new Date());
song.TargetTextChannel.send(embed);
}
static PrintLeave(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription("See you next time.");
channel.send(embed);
}
static async WriteSpotify(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription("Bip boup. Please wait while i'm automagically taking your songs from Spotify. 🧙🏻♂️🌟")
.setImage("https://media0.giphy.com/media/QyWBTLDn9WHt0FXGJS/giphy.gif");
let msg = await channel.send(embed);
return msg;
}
static PrintQueue(queue: Song[], channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setAuthor("Coming up next" , "https://i.imgur.com/l0hxro3.png")
.setFooter('Music Tendency', "https://i.imgur.com/l0hxro3.png")
.setTimestamp(new Date());
let totalSeconds = 0;
let description = "";
for(let i = 0; i<queue.length;i+=1){
let song = queue[i];
if(i<15){
description+= `${i+1}. ${song.Title.substr(0,70)}\n`;
}
totalSeconds += song.Duration;
}
description+= "... and counting 🦀🎶\n";
embed.setDescription(description);
embed.addFields([
{ name: 'Song Count', value: queue.length, inline: true },
{ name: 'Total time', value: this.GetDurationAsString(totalSeconds), inline: true}
]);
//queueOut += "--------------------------\n";
//queueOut += "... and counting 🦀🎶";
// queueOut += `The playlist will last ${this.SecondsToString(totalSeconds)}`;
return channel.send(embed);
}
static WriteClear(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription("🗑️ All clear.");
channel.send(embed);
}
static WriteSkip(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription("⏭ Skip song.");
channel.send(embed);
}
static WriteSongAdded(channel: TextChannel) {
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription(`Stuff added to the queue`);
channel.send(embed);
}
static PrintError(message : String, channel : TextChannel){
let embed = new MessageEmbed()
.setColor('#fc051d')
.setDescription(`${message} ¯\\_(ツ)_/¯`);
channel.send(embed);
}
static PrintHelp(channel: TextChannel | DMChannel){
//channel.send(`\`\`\`${this.header}\`\`\``);
let embed = new MessageEmbed()
.setColor('#6300aa')
.setDescription(`${this.help}`);
channel.send(embed);
}
static GetDurationAsString(durationInSeconds : number){
let date = new Date(0);
let remaningSeconds = durationInSeconds;
date.setHours(remaningSeconds/3600);
remaningSeconds -= date.getHours() * 3600;
date.setMinutes(remaningSeconds/60);
remaningSeconds -= date.getMinutes() * 60;
date.setSeconds(remaningSeconds);
let timeString = date.toISOString().substr(11, 8);
return timeString;
}
}
|
16bcb42e0d2aaf08c94b46a6641282038ce5fe26
|
TypeScript
|
sveltejs/language-tools
|
/packages/language-server/src/plugins/typescript/features/utils.ts
| 2.53125
| 3
|
import ts from 'typescript';
import { Position } from 'vscode-languageserver';
import {
Document,
getLineAtPosition,
getNodeIfIsInComponentStartTag,
isInTag
} from '../../../lib/documents';
import { ComponentInfoProvider, JsOrTsComponentInfoProvider } from '../ComponentInfoProvider';
import { DocumentSnapshot, SvelteDocumentSnapshot } from '../DocumentSnapshot';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { or } from '../../../utils';
import { FileMap } from '../../../lib/documents/fileCollection';
import { LSConfig } from '../../../ls-config';
type NodePredicate = (node: ts.Node) => boolean;
type NodeTypePredicate<T extends ts.Node> = (node: ts.Node) => node is T;
/**
* If the given original position is within a Svelte starting tag,
* return the snapshot of that component.
*/
export function getComponentAtPosition(
lang: ts.LanguageService,
doc: Document,
tsDoc: SvelteDocumentSnapshot,
originalPosition: Position
): ComponentInfoProvider | null {
if (tsDoc.parserError) {
return null;
}
if (
isInTag(originalPosition, doc.scriptInfo) ||
isInTag(originalPosition, doc.moduleScriptInfo)
) {
// Inside script tags -> not a component
return null;
}
const node = getNodeIfIsInComponentStartTag(doc.html, doc.offsetAt(originalPosition));
if (!node) {
return null;
}
const generatedPosition = tsDoc.getGeneratedPosition(doc.positionAt(node.start + 1));
const def = lang.getDefinitionAtPosition(
tsDoc.filePath,
tsDoc.offsetAt(generatedPosition)
)?.[0];
if (!def) {
return null;
}
return JsOrTsComponentInfoProvider.create(lang, def);
}
export function isComponentAtPosition(
doc: Document,
tsDoc: SvelteDocumentSnapshot,
originalPosition: Position
): boolean {
if (tsDoc.parserError) {
return false;
}
if (
isInTag(originalPosition, doc.scriptInfo) ||
isInTag(originalPosition, doc.moduleScriptInfo)
) {
// Inside script tags -> not a component
return false;
}
return !!getNodeIfIsInComponentStartTag(doc.html, doc.offsetAt(originalPosition));
}
export const IGNORE_START_COMMENT = '/*Ωignore_startΩ*/';
export const IGNORE_END_COMMENT = '/*Ωignore_endΩ*/';
/**
* Surrounds given string with a start/end comment which marks it
* to be ignored by tooling.
*/
export function surroundWithIgnoreComments(str: string): string {
return IGNORE_START_COMMENT + str + IGNORE_END_COMMENT;
}
/**
* Checks if this a section that should be completely ignored
* because it's purely generated.
*/
export function isInGeneratedCode(text: string, start: number, end: number = start) {
const lastStart = text.lastIndexOf(IGNORE_START_COMMENT, start);
const lastEnd = text.lastIndexOf(IGNORE_END_COMMENT, start);
const nextEnd = text.indexOf(IGNORE_END_COMMENT, end);
// if lastEnd === nextEnd, this means that the str was found at the index
// up to which is searched for it
return (lastStart > lastEnd || lastEnd === nextEnd) && lastStart < nextEnd;
}
/**
* Checks if this is a text span that is inside svelte2tsx-generated code
* (has no mapping to the original)
*/
export function isTextSpanInGeneratedCode(text: string, span: ts.TextSpan) {
return isInGeneratedCode(text, span.start, span.start + span.length);
}
export function isPartOfImportStatement(text: string, position: Position): boolean {
const line = getLineAtPosition(position, text);
return /\s*from\s+["'][^"']*/.test(line.slice(0, position.character));
}
export function isStoreVariableIn$storeDeclaration(text: string, varStart: number) {
return (
text.lastIndexOf('__sveltets_2_store_get(', varStart) ===
varStart - '__sveltets_2_store_get('.length
);
}
export function get$storeOffsetOf$storeDeclaration(text: string, storePosition: number) {
return text.lastIndexOf(' =', storePosition) - 1;
}
export function is$storeVariableIn$storeDeclaration(text: string, varStart: number) {
return /^\$\w+ = __sveltets_2_store_get/.test(text.substring(varStart));
}
export function getStoreOffsetOf$storeDeclaration(text: string, $storeVarStart: number) {
return text.indexOf(');', $storeVarStart) - 1;
}
export class SnapshotMap {
private map = new FileMap<DocumentSnapshot>();
constructor(private resolver: LSAndTSDocResolver) {}
set(fileName: string, snapshot: DocumentSnapshot) {
this.map.set(fileName, snapshot);
}
get(fileName: string) {
return this.map.get(fileName);
}
async retrieve(fileName: string) {
let snapshot = this.get(fileName);
if (!snapshot) {
const snap = await this.resolver.getSnapshot(fileName);
this.set(fileName, snap);
snapshot = snap;
}
return snapshot;
}
}
export function isAfterSvelte2TsxPropsReturn(text: string, end: number) {
const textBeforeProp = text.substring(0, end);
// This is how svelte2tsx writes out the props
if (textBeforeProp.includes('\nreturn { props: {')) {
return true;
}
}
export function findContainingNode<T extends ts.Node>(
node: ts.Node,
textSpan: ts.TextSpan,
predicate: (node: ts.Node) => node is T
): T | undefined {
const children = node.getChildren();
const end = textSpan.start + textSpan.length;
for (const child of children) {
if (!(child.getStart() <= textSpan.start && child.getEnd() >= end)) {
continue;
}
if (predicate(child)) {
return child;
}
const foundInChildren = findContainingNode(child, textSpan, predicate);
if (foundInChildren) {
return foundInChildren;
}
}
}
export function findClosestContainingNode<T extends ts.Node>(
node: ts.Node,
textSpan: ts.TextSpan,
predicate: (node: ts.Node) => node is T
): T | undefined {
let current = findContainingNode(node, textSpan, predicate);
if (!current) {
return;
}
let closest = current;
while (current) {
const foundInChildren: T | undefined = findContainingNode(current, textSpan, predicate);
closest = current;
current = foundInChildren;
}
return closest;
}
/**
* Finds node exactly matching span {start, length}.
*/
export function findNodeAtSpan<T extends ts.Node>(
node: ts.Node,
span: { start: number; length: number },
predicate?: NodeTypePredicate<T>
): T | void {
const { start, length } = span;
const end = start + length;
for (const child of node.getChildren()) {
const childStart = child.getStart();
if (end <= childStart) {
return;
}
const childEnd = child.getEnd();
if (start >= childEnd) {
continue;
}
if (start === childStart && end === childEnd) {
if (!predicate) {
return child as T;
}
if (predicate(child)) {
return child;
}
}
const foundInChildren = findNodeAtSpan(child, span, predicate);
if (foundInChildren) {
return foundInChildren;
}
}
}
function isSomeAncestor(node: ts.Node, predicate: NodePredicate) {
for (let parent = node.parent; parent; parent = parent.parent) {
if (predicate(parent)) {
return true;
}
}
return false;
}
/**
* Tests a node then its parent and successive ancestors for some respective predicates.
*/
function nodeAndParentsSatisfyRespectivePredicates<T extends ts.Node>(
selfPredicate: NodePredicate | NodeTypePredicate<T>,
...predicates: NodePredicate[]
) {
return (node: ts.Node | undefined | void | null): node is T => {
let next = node;
return [selfPredicate, ...predicates].every((predicate) => {
if (!next) {
return false;
}
const current = next;
next = next.parent;
return predicate(current);
});
};
}
const isRenderFunction = nodeAndParentsSatisfyRespectivePredicates<
ts.FunctionDeclaration & { name: ts.Identifier }
>((node) => ts.isFunctionDeclaration(node) && node?.name?.getText() === 'render', ts.isSourceFile);
const isRenderFunctionBody = nodeAndParentsSatisfyRespectivePredicates(
ts.isBlock,
isRenderFunction
);
export const isReactiveStatement = nodeAndParentsSatisfyRespectivePredicates<ts.LabeledStatement>(
(node) => ts.isLabeledStatement(node) && node.label.getText() === '$',
or(
// function render() {
// $: x2 = __sveltets_2_invalidate(() => x * x)
// }
isRenderFunctionBody,
// function render() {
// ;() => {$: x, update();
// }
nodeAndParentsSatisfyRespectivePredicates(
ts.isBlock,
ts.isArrowFunction,
ts.isExpressionStatement,
isRenderFunctionBody
)
)
);
export function findRenderFunction(sourceFile: ts.SourceFile) {
// only search top level
for (const child of sourceFile.statements) {
if (isRenderFunction(child)) {
return child;
}
}
}
export const isInReactiveStatement = (node: ts.Node) => isSomeAncestor(node, isReactiveStatement);
export function gatherDescendants<T extends ts.Node>(
node: ts.Node,
predicate: NodeTypePredicate<T>,
dest: T[] = []
) {
if (predicate(node)) {
dest.push(node);
} else {
for (const child of node.getChildren()) {
gatherDescendants(child, predicate, dest);
}
}
return dest;
}
export const gatherIdentifiers = (node: ts.Node) => gatherDescendants(node, ts.isIdentifier);
export function isKitTypePath(path?: string): boolean {
return !!path?.includes('.svelte-kit/types');
}
export function getFormatCodeBasis(formatCodeSetting: ts.FormatCodeSettings): FormatCodeBasis {
const { baseIndentSize, indentSize, convertTabsToSpaces } = formatCodeSetting;
const baseIndent = convertTabsToSpaces
? ' '.repeat(baseIndentSize ?? 4)
: baseIndentSize
? '\t'
: '';
const indent = convertTabsToSpaces ? ' '.repeat(indentSize ?? 4) : baseIndentSize ? '\t' : '';
const semi = formatCodeSetting.semicolons === 'remove' ? '' : ';';
const newLine = formatCodeSetting.newLineCharacter ?? ts.sys.newLine;
return {
baseIndent,
indent,
semi,
newLine
};
}
export interface FormatCodeBasis {
baseIndent: string;
indent: string;
semi: string;
newLine: string;
}
/**
* https://github.com/microsoft/TypeScript/blob/00dc0b6674eef3fbb3abb86f9d71705b11134446/src/services/utilities.ts#L2452
*/
export function getQuotePreference(
sourceFile: ts.SourceFile,
preferences: ts.UserPreferences
): '"' | "'" {
const single = "'";
const double = '"';
if (preferences.quotePreference && preferences.quotePreference !== 'auto') {
return preferences.quotePreference === 'single' ? single : double;
}
const firstModuleSpecifier = Array.from(sourceFile.statements).find(
(
statement
): statement is Omit<ts.ImportDeclaration, 'moduleSpecifier'> & {
moduleSpecifier: ts.StringLiteral;
} => ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)
)?.moduleSpecifier;
return firstModuleSpecifier
? sourceFile.getText()[firstModuleSpecifier.pos] === '"'
? double
: single
: double;
}
export function findChildOfKind(node: ts.Node, kind: ts.SyntaxKind): ts.Node | undefined {
for (const child of node.getChildren()) {
if (child.kind === kind) {
return child;
}
const foundInChildren = findChildOfKind(child, kind);
if (foundInChildren) {
return foundInChildren;
}
}
}
export function getNewScriptStartTag(lsConfig: Readonly<LSConfig>) {
const lang = lsConfig.svelte.defaultScriptLanguage;
const scriptLang = lang === 'none' ? '' : ` lang="${lang}"`;
return `<script${scriptLang}>${ts.sys.newLine}`;
}
|
c78ea86217c86eff5735ab419ade385be8e5ddf4
|
TypeScript
|
modo-studio/todogit
|
/desktop/src/renderer/startup/startup.ts
| 2.734375
| 3
|
import StartupOperation from "./startup-operation"
import * as operations from "./operations"
export class Startup {
operations: Array<StartupOperation>
constructor(operations: Array<StartupOperation>) {
this.operations = operations
}
execute(): Promise<Array<void>> {
return Promise.all(
this.operations.map((operation: StartupOperation): Promise<void> => {
return operation.execute()
})
)
}
static todogit(): Startup {
return new Startup([
new operations.StartupLogger(),
new operations.StartupDatabase(),
new operations.StartupRaven()])
}
}
const appStartup = Startup.todogit()
export default appStartup
|
6655bd62431597e42ef9553937bb215ba5575cf2
|
TypeScript
|
fossabot/api-7
|
/src/services/TwitterUsersService.ts
| 2.671875
| 3
|
import IServiceFetcher from '../utils/IServiceFetcher'
import ITwitterUsersService from './ITwitterUsersService'
let accessToken: string = null
export default class TwitterUsersService implements ITwitterUsersService {
public static BASE_URL = 'https://api.twitter.com/1.1/users'
public static TOKEN_URL = 'https://api.twitter.com/oauth2/token'
constructor(
private apiKey: string,
private apiSecret: string,
private fetcher: IServiceFetcher
) {}
public async retrieve(twitterHandles: string[]): Promise<any> {
if (!accessToken) {
const res = JSON.parse(
await this.fetcher.fetch(TwitterUsersService.TOKEN_URL, {
method: 'POST',
headers: {
Authorization: `Basic ${Buffer.from(
`${this.apiKey}:${this.apiSecret}`
).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: 'grant_type=client_credentials',
json: false,
})
)
accessToken = res.access_token
}
return this.fetcher.fetch(
`${
TwitterUsersService.BASE_URL
}/lookup.json?screen_name=${twitterHandles.join(',')}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
)
}
}
|
85a1c8dd179ccd772862f4a0d73e477fcd36f1fd
|
TypeScript
|
trivikr/smithy-typescript
|
/packages/types/src/streaming-payload/streaming-blob-payload-input-types.ts
| 3.34375
| 3
|
import type { Readable } from "stream";
/**
* @public
*
* This union represents a superset of the compatible types you
* can use for streaming payload inputs.
*
* FAQ:
* Why does the type union mix mutually exclusive runtime types, namely
* Node.js and browser types?
*
* There are several reasons:
* 1. For backwards compatibility.
* 2. As a convenient compromise solution so that users in either environment may use the types
* without customization.
* 3. The SDK does not have static type information about the exact implementation
* of the HTTP RequestHandler being used in your client(s) (e.g. fetch, XHR, node:http, or node:http2),
* given that it is chosen at runtime. There are multiple possible request handlers
* in both the Node.js and browser runtime environments.
*
* Rather than restricting the type to a known common format (Uint8Array, for example)
* which doesn't include a universal streaming format in the currently supported Node.js versions,
* the type declaration is widened to multiple possible formats.
* It is up to the user to ultimately select a compatible format with the
* runtime and HTTP handler implementation they are using.
*
* Usage:
* The typical solution we expect users to have is to manually narrow the
* type when needed, picking the appropriate one out of the union according to the
* runtime environment and specific request handler.
* There is also the type utility "NodeJsClient", "BrowserClient" and more
* exported from this package. These can be applied at the client level
* to pre-narrow these streaming payload blobs. For usage see the readme.md
* in the root of the @smithy/types NPM package.
*/
export type StreamingBlobPayloadInputTypes =
| NodeJsRuntimeStreamingBlobPayloadInputTypes
| BrowserRuntimeStreamingBlobPayloadInputTypes;
/**
* @public
*
* Streaming payload input types in the Node.js environment.
* These are derived from the types compatible with the request body used by node:http.
*
* Note: not all types are signable by the standard SignatureV4 signer when
* used as the request body. For example, in Node.js a Readable stream
* is not signable by the default signer.
* They are included in the union because it may be intended in some cases,
* but the expected types are primarily string, Uint8Array, and Buffer.
*
* Additional details may be found in the internal
* function "getPayloadHash" in the SignatureV4 module.
*/
export type NodeJsRuntimeStreamingBlobPayloadInputTypes = string | Uint8Array | Buffer | Readable;
/**
* @public
*
* Streaming payload input types in the browser environment.
* These are derived from the types compatible with fetch's Request.body.
*/
export type BrowserRuntimeStreamingBlobPayloadInputTypes = string | Uint8Array | ReadableStream | Blob;
|
5f830c27ff0504a4c05ad789f385ded22c6ee4a6
|
TypeScript
|
boomfly/number-to-words-ru
|
/src/units/numbers.ts
| 2.609375
| 3
|
import genders from 'src/units/genders';
import {declensions} from 'src/units/declensions';
type DeclensionNumbers = string | {
[key: string]: string,
};
export interface DeclensionNumbersArray {
[key: string]: [
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
DeclensionNumbers,
];
};
interface Numbers {
numbers: DeclensionNumbersArray,
tenToNineteen: DeclensionNumbersArray,
tens: DeclensionNumbersArray,
hundreds: DeclensionNumbersArray,
};
export const minus = 'минус';
// Правила взяты отсюда http://www.fio.ru/pravila/grammatika/sklonenie-imen-chislitelnykh/
export const numbers: Numbers = {
numbers: {
[declensions.NOMINATIVE]: [
'ноль',
{
[genders.MALE]: 'один',
[genders.NEUTER]: 'одно',
[genders.FEMALE]: 'одна',
},
{
[genders.MALE]:'два',
[genders.NEUTER]:'два',
[genders.FEMALE]:'две',
},
'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять',
],
[declensions.GENITIVE]: [
'ноля',
{
[genders.MALE]: 'одного',
[genders.NEUTER]: 'одного',
[genders.FEMALE]: 'одной',
},
'двух', 'трёх', 'четырёх', 'пяти', 'шести', 'семи', 'восьми', 'девяти',
],
[declensions.DATIVE]: [
'нолю',
{
[genders.MALE]: 'одному',
[genders.NEUTER]: 'одному',
[genders.FEMALE]: 'одной',
},
'двум', 'трём', 'четырём', 'пяти', 'шести', 'семи', 'восьми', 'девяти',
],
[declensions.ACCUSATIVE]: [
'ноль',
{
[genders.MALE]: 'один',
[genders.NEUTER]: 'одно',
[genders.FEMALE]: 'одну',
},
{
[genders.MALE]:'два',
[genders.NEUTER]:'два',
[genders.FEMALE]:'две',
},
'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять',
],
[declensions.INSTRUMENTAL]: [
'нолём',
{
[genders.MALE]: 'одним',
[genders.NEUTER]: 'одним',
[genders.FEMALE]: 'одной',
},
'двумя', 'тремя', 'четырьмя', 'пятью', 'шестью', 'семью', 'восемью', 'девятью',
],
[declensions.PREPOSITIONAL]: [
'ноле',
{
[genders.MALE]: 'одном',
[genders.NEUTER]: 'одном',
[genders.FEMALE]: 'одной',
},
'двух', 'трёх', 'четырёх', 'пяти', 'шести', 'семи', 'восьми', 'девяти',
],
},
tenToNineteen: {
[declensions.NOMINATIVE]: ['десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать'],
[declensions.GENITIVE]: ['десяти', 'одиннадцати', 'двенадцати', 'тринадцати', 'четырнадцати', 'пятнадцати', 'шестнадцати', 'семнадцати', 'восемнадцати', 'девятнадцати'],
[declensions.DATIVE]: ['десяти', 'одиннадцати', 'двенадцати', 'тринадцати', 'четырнадцати', 'пятнадцати', 'шестнадцати', 'семнадцати', 'восемнадцати', 'девятнадцати'],
[declensions.ACCUSATIVE]: ['десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать'],
[declensions.INSTRUMENTAL]: ['десятью', 'одиннадцатью', 'двенадцатью', 'тринадцатью', 'четырнадцатью', 'пятнадцатью', 'шестнадцатью', 'семнадцатью', 'восемнадцатью', 'девятнадцатью'],
[declensions.PREPOSITIONAL]: ['десяти', 'одиннадцати', 'двенадцати', 'тринадцати', 'четырнадцати', 'пятнадцати', 'шестнадцати', 'семнадцати', 'восемнадцати', 'девятнадцати'],
},
tens: {
[declensions.NOMINATIVE]: ['', '', 'двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто'],
[declensions.GENITIVE]: ['', '', 'двадцати', 'тридцати', 'сорока', 'пятидесяти', 'шестидесяти', 'семидесяти', 'восьмидесяти', 'девяноста'],
[declensions.DATIVE]: ['', '', 'двадцати', 'тридцати', 'сорока', 'пятидесяти', 'шестидесяти', 'семидесяти', 'восьмидесяти', 'девяноста'],
[declensions.ACCUSATIVE]: ['', '', 'двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто'],
[declensions.INSTRUMENTAL]: ['', '', 'двадцатью', 'тридцатью', 'сорока', 'пятьюдесятью', 'шестьюдесятью', 'семьюдесятью', 'восемьюдесятью', 'девяноста'],
[declensions.PREPOSITIONAL]: ['', '', 'двадцати', 'тридцати', 'сорока', 'пятидесяти', 'шестидесяти', 'семидесяти', 'восьмидесяти', 'девяноста'],
},
hundreds: {
[declensions.NOMINATIVE]: ['', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот'],
[declensions.GENITIVE]: ['', 'ста', 'двухсот', 'трёхсот', 'четырёхсот', 'пятисот', 'шестисот', 'семисот', 'восьмисот', 'девятисот'],
[declensions.DATIVE]: ['', 'ста', 'двумстам', 'трёмстам', 'четырёмстам', 'пятистам', 'шестистам', 'семистам', 'восьмистам', 'девятистам'],
[declensions.ACCUSATIVE]: ['', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот'],
[declensions.INSTRUMENTAL]: ['', 'ста', 'двумястами', 'тремястами', 'четырьмястами', 'пятьюстами', 'шестьюстами', 'семьюстами', 'восемьюстами', 'девятьюстами'],
[declensions.PREPOSITIONAL]: ['', 'ста', 'двухстах', 'трёхстах', 'четырёхстах', 'пятистах', 'шестистах', 'семистах', 'восьмистах', 'девятистах']
},
};
export default numbers;
|
a4ad51635c6dd94fadac808937225da7421bc4c4
|
TypeScript
|
igncp/code-gym
|
/katas/006/ts/index.ts
| 3.640625
| 4
|
const assert = require("assert");
const swapNumsInArray = (arr: number[], idxA: number, idxB: number): void => {
const tmp = arr[idxA];
arr[idxA] = arr[idxB];
arr[idxB] = tmp;
};
/*
https://en.wikipedia.org/wiki/Insertion_sort
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while
*/
const insertSort = (nums: number[]): number[] => {
const result = nums.slice(0);
let i = 1;
while (i < result.length) {
let j = i;
while (j > 0 && result[j - 1] > result[j]) {
swapNumsInArray(result, j, j - 1);
j -= 1;
}
i += 1;
}
return result;
};
const test = () => {
assert.deepEqual(insertSort([0, 1, 2]), [0, 1, 2]);
assert.deepEqual(insertSort([3, 2, 1, 0]), [0, 1, 2, 3]);
assert.deepEqual(insertSort([1, 2, 1, 0]), [0, 1, 1, 2]);
};
const main = () => {
test();
};
main();
|
7da05a1cd4f7901481b781c548f926752611b181
|
TypeScript
|
clayton-jones/sort
|
/src/index.ts
| 2.953125
| 3
|
import { Sorter } from './Sorter';
import { NumbersCollection } from './NumbersCollection';
import { LinkedList } from './LinkedList';
// const numbers = new NumbersCollection([1, 4, -1, -20, 32, 10]);
// const sorter = new Sorter(numbers);
// sorter.sort();
// console.log(numbers.data);
const list = new LinkedList();
list.add(100);
list.add(24);
list.add(-10);
list.add(-3000);
list.add(2);
list.sort();
list.print();
|
ff76d604081783e4c85157ba09ad222323bb9df1
|
TypeScript
|
Victor-Fiamoncini/my_sorts
|
/src/quicksort/index.ts
| 3.34375
| 3
|
import Sort from '@src/Sort'
class QuickSort extends Sort {
sort(array: number[], start = 0, end = array.length): void {
if (start < end) {
const pivot = this.partition(array, start, end)
this.sort(array, start, pivot - 1)
this.sort(array, pivot + 1, end)
}
}
private partition(array: number[], start: number, end: number) {
const pivot = array[end]
let i = start
for (let j = start; j < end - 1; j++) {
if (array[j] <= pivot) {
const tempJ = array[j]
array[j] = array[i]
array[i] = tempJ
i++
}
}
const tempi = array[i]
array[i] = array[end]
array[end] = tempi
return i
}
}
export default QuickSort
|
fa355d4fb759ac37855c757989ddc1d385405fdd
|
TypeScript
|
Gathondu/shopping-cart
|
/server/src/Schema/types/product.ts
| 2.8125
| 3
|
import {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLInt,
} from 'graphql';
import { DateType } from '../scalars';
/** Define the product type object that we will consume in
* graphQl queries and mutations.
*/
// define a product type for typescript
export type product = {
id: number;
name: string;
sku: string;
price: string;
stockLevel: number;
categoryId: number;
expiryDate: Date;
createdAt: Date;
updatedAt: Date;
};
export const ProductType = new GraphQLObjectType({
name: 'Product',
description: 'A product',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
sku: { type: GraphQLString },
price: { type: GraphQLString },
stockLevel: { type: GraphQLInt },
categoryId: { type: GraphQLInt },
expiryDate: { type: DateType },
createdAt: { type: DateType },
updatedAt: { type: DateType },
}),
});
|
488d9e1e3b3e355f11bff2cad97a2c24940bfe3b
|
TypeScript
|
thapakorn604/todoListDemo
|
/src/core/store/Todo/TodoModule.ts
| 2.796875
| 3
|
import { AnyAction, Reducer } from 'redux';
import { IModule } from 'redux-dynamic-modules';
import {
TodoAction,
TodoActionType,
TodoModuleState,
TodoState,
} from './../../types';
export const initialState: TodoState = [
{ key: 0, title: 'Practice piano', isDone: false },
{ key: 1, title: 'Listen to TedTalk', isDone: false },
{ key: 2, title: 'Continue reading Homosepiens', isDone: false },
];
const todoReducer: Reducer<TodoState, TodoAction> = (
state = initialState,
action,
) => {
switch (action.type) {
case TodoActionType.Create:
return [
...state,
{
key: action.payload.key,
title: action.payload.title,
isDone: false,
},
];
case TodoActionType.Update:
return state.map((todo) =>
todo.key === action.payload.key
? { ...todo, isDone: action.payload.isDone }
: todo,
);
case TodoActionType.Delete:
return state.filter((todo) => todo.key !== action.payload.key);
default:
return state;
}
};
const todoModule: IModule<TodoModuleState> = {
id: 'todoModule',
reducerMap: {
todo: todoReducer as Reducer<TodoState, AnyAction>,
},
initialActions: [],
};
export default todoModule;
|
4f72645e5a890eed3f69ff22c733cff50c807d79
|
TypeScript
|
TheRusskiy/url-pagination
|
/src/utils/isPageValid.ts
| 2.640625
| 3
|
export default function isPageValid(
page: number,
perPage: number,
total?: number
) {
if (page < 0) return false;
if (!total) return true;
const maxPage = Math.ceil(total / perPage) - 1; // 0 indexed
return page <= maxPage;
}
|
3a38770b9701b51d21205731f7f7622388774b05
|
TypeScript
|
turizsolt/der-fahrplan
|
/test/Geometry/LineSegmentChain.test.ts
| 2.53125
| 3
|
import chai, { expect } from 'chai';
import chaiAlmost from 'chai-almost';
import { Coordinate } from '../../src/structs/Geometry/Coordinate';
import { Ray } from '../../src/structs/Geometry/Ray';
import { Right } from '../../src/structs/Geometry/Directions';
import { LineSegmentChain } from '../../src/structs/Geometry/LineSegmentChain';
chai.use(chaiAlmost(0.00001));
describe('Line segment chain', () => {
it('to point, first point', () => {
const chain = LineSegmentChain.fromRays([
Ray.from(0, 0, 0, Right),
Ray.from(100, 0, 0, Right),
]);
const point = new Coordinate(0, 0, 0);
const newChain = chain.getChainToPoint(point);
const expectedChain = LineSegmentChain.fromRays([Ray.from(0, 0, 0, Right), Ray.from(0, 0, 0, Right)]);
expect(newChain.persist()).deep.almost(expectedChain.persist());
});
});
|
3065a71d81a920e5248d58a2a86810c4d1b150f3
|
TypeScript
|
acmeframework/af-conditionals
|
/src/lib/conditionals/is-array.ts
| 3.109375
| 3
|
import typeDetect from 'type-detect';
import { assert_conditional, Conditional } from './conditional';
import { isUndefinedOrNull } from './is-undefined-or-null';
export class IsArray extends Conditional {
public test(value: any): boolean {
return !isUndefinedOrNull(value) && typeDetect(value) === 'Array';
}
}
export let isArrayInstance = new IsArray(); // eslint-disable-line prefer-const
export function isArray(value: any): boolean {
return isArrayInstance.test(value);
}
export function assert_isArray(
value: any,
assertMsg = 'is not an array.'
): void {
assert_conditional(value, isArrayInstance, assertMsg);
}
|
72e2b7b739604d5cc149aeee3691a8f29dffb8b1
|
TypeScript
|
Ainias/js-helper
|
/dist/Promises/PromiseWithHandlers.d.ts
| 2.609375
| 3
|
export declare class PromiseWithHandlers<T> extends Promise<T> {
private readonly resolver;
private readonly rejecter;
constructor(executor?: (resolve: (value?: (PromiseLike<T> | T)) => void, reject: (reason?: any) => void) => void);
resolve(value?: (PromiseLike<T> | T)): void;
reject(reason?: any): void;
}
|
23f848456d2265a6659dd6460e5982015ec83773
|
TypeScript
|
JakubSzark/little-man-computer
|
/LMC.ts
| 3.3125
| 3
|
/*
* Little Man Computer Clone
* Made by: Jakub P. Szarkowicz
* [Email]: jakubshark@gmail.com
* [License]: MIT
* [Credit]: Dr. Stuart Madnick
* [Wiki]: https://en.wikipedia.org/wiki/Little_man_computer
*/
/**
* State of the computer
*/
interface State
{
// The main working register
accumulator: number,
// The memory address of the current operation
programCounter: number,
// Determines whether the program is stopped
programHalted: boolean,
// Clock speed of the computer in milliseconds
clockSpeed: number,
// Random Access Memory of the computer
RAM: Array<number>
}
// Function definition for input callback
type InputCallback = () => number;
// Function definition for output callback
type OutputCallback = (n: number) => void;
/**
* Used to map labels to their
* respective memory addresses.
*/
type Label = Record<string, number>;
// Standard OP Codes for LMC
const operationCodes: any =
{
"INP": 901,
"OUT": 902,
"LDA": 500,
"STA": 300,
"ADD": 100,
"SUB": 200,
"BRP": 800,
"BRZ": 700,
"BRA": 600,
"HLT": 0,
"DAT": -1
};
// The State of the Computer
let state: State =
{
accumulator: 0,
programCounter: 0,
programHalted: false,
clockSpeed: 250,
RAM: new Array<number>(100)
}
/**
* Resets the computer to its default state
*/
function reset()
{
state.accumulator = 0;
state.programCounter = 0;
for (let i = 0; i < state.RAM.length; i++)
state.RAM[i] = 0;
state.programHalted = false;
}
/**
* Halts the currently running program
* @param callback Callback when program is halted successfully.
*/
function halt(callback: FunctionStringCallback)
{
if (!state.programHalted)
{
state.programHalted = true;
if (callback != null)
callback("Program Halted");
}
}
/**
* Parses an array of Strings into an array of operation codes
* @param lines Array of strings to parse
* @param callback Callback for parsing errors
* @returns Operation codes
*/
function parse(lines: string[],
callback: FunctionStringCallback): number[]
{
// Function for splitting a line for tokens
function getTokens(line: string): string[] {
return line.trim().split(/[ ,\t]+/);
}
let codes: number[] = [];
let labels: Map<string, number> = new Map();
// Check for labels and convert them
for (let j = 0; j < lines.length; j++)
{
// We extract tokens
const tokens = getTokens(lines[j]);
if (tokens.length < 2) continue;
// Check if line contains a label
if (!(tokens[0] in operationCodes))
labels.set(tokens[0], j);
}
// Parse instructions and store them
for (let i = 0; i < lines.length; i++)
{
// Ignore empty lines
if (isEmptyOrComment(lines[i]))
continue;
let code: number = 0; // Resulting Operation Token
// We extract tokens
const tokens = getTokens(lines[i]);
// Check if no tokens are available
if (tokens.length == 0)
{
callback(`[Line (${i})]: Does not contain any tokens!`);
continue;
}
let codeToken: string;
let argToken: string;
// Depending on if there is a label, get the correct tokens
if (tokens[0] in operationCodes)
{
codeToken = tokens[0];
argToken = tokens[1];
}
else
{
codeToken = tokens[1];
argToken = tokens[2];
}
// Check if codeToken is a valid operation code
if (codeToken in operationCodes) {
code = operationCodes[codeToken];
}
else
{
callback(`[Line (${i})]: Operation code is not valid!`);
continue;
}
// Arguments
if (argToken != undefined)
{
// Check if argToken is a memory address
if (argToken[0] == '$')
{
argToken = argToken.substr(1); // Remove $
let arg = parseInt(argToken);
if (isNaN(arg))
{
callback(`[Line (${i})]: Address argument is NaN!`);
continue;
}
else if (arg < 0 && arg > state.RAM.length - 1)
{
callback(`[Line (${i})]: Address argument is out of range!`);
continue;
}
else { code += arg; }
}
else if (labels.has(argToken)) // Label Parsing
{
// Get memory address from label
let argVal = labels.get(argToken);
if (argVal != undefined) code += argVal;
}
else if (code == -1) // DAT Parsing
{
let arg = parseInt(argToken);
if (isNaN(arg))
{
callback(`[Line (${i})]: Data argument is NaN!`);
continue;
}
else {
code = arg;
}
}
else
{
callback(`[Line (${i})]: Argument token could not be parsed!`);
continue;
}
}
// Push parsed code
codes.push(code);
}
return codes;
}
/**
* Loads a program into RAM
* @param codes Array of operation codes
*/
function load(codes: number[])
{
reset();
for (let i = 0; i < state.RAM.length; i++)
{
if (i < codes.length) state.RAM[i] = codes[i]
else state.RAM[i] = 0
}
}
/**
* Steps through a program. Evaluates operation codes
* sequencially, if a problem occurs, then program will halt
* @param inCallback Callback called when input is requested
* @param outCallback Callback called when output is requested
*/
function step(inCallback: InputCallback,
outCallback: OutputCallback, haltCallback: Function)
{
if (state.programHalted) return;
// Memory address value at program counter
let addressValue = state.RAM[state.programCounter];
// IR[Address]
let instructionArgument = addressValue -
Math.floor(addressValue / 100.0) * 100;
// Operation Code
let operationCode = addressValue < 900 ?
addressValue - instructionArgument : addressValue;
// Execute based on current operation
switch (operationCode)
{
// IOR -> A
// PC + 1 -> PC
case operationCodes.INP:
state.accumulator = inCallback();
state.programCounter++;
break;
// A -> IOR
// PC + 1 -> PC
case operationCodes.OUT:
outCallback(state.accumulator);
state.programCounter++;
break;
// IR[address] -> MAR
// A + MDR -> A
// PC + 1 -> PC
case operationCodes.ADD:
state.accumulator += state.RAM[instructionArgument];
state.programCounter++;
break;
// IR[address] -> MAR
// A - MDR -> A
// PC + 1 -> PC
case operationCodes.SUB:
state.accumulator -= state.RAM[instructionArgument];
state.programCounter++;
break;
// IR[address] -> MAR
// MDR -> A
// PC + 1 -> PC
case operationCodes.LDA:
state.accumulator = state.RAM[instructionArgument];
state.programCounter++;
break;
// IR[address] -> MAR
// A -> MDR
// PC + 1 -> PC
case operationCodes.STA:
state.RAM[instructionArgument] = state.accumulator;
state.programCounter++;
break;
// IR[address] -> PC
case operationCodes.BRA:
state.programCounter = instructionArgument;
break;
// A > 0
// IF TRUE, IR[address] -> PC
// ELSE, PC + 1 -> PC
case operationCodes.BRP:
if (state.accumulator > 0)
state.programCounter = instructionArgument;
else
state.programCounter++;
break;
// A == 0
// IF TRUE, IR[address] -> PC
// ELSE, PC + 1 -> PC
case operationCodes.BRZ:
if (state.accumulator == 0)
state.programCounter = instructionArgument;
else
state.programCounter++;
break;
// HALT PROGRAM
case operationCodes.HLT:
halt(() => {});
haltCallback();
break;
}
}
// ===========================================
// BROWSER CODE
// ===========================================
let cells: HTMLElement[] = [];
let runningHandle = 0;
// Boxes
let inputBox = document.getElementById("inputText");
let outputBox = document.getElementById("outputText");
let consoleBox = document.getElementById("console");
let notepad = document.getElementById('notepad');
// Registers
let accumulator = document.getElementById('accum');
let pc = document.getElementById('counter');
/**
* Log a message to the console box
* @param msg Message to add
*/
const log = (msg: string, err: boolean) =>
{
if (consoleBox != null)
{
consoleBox.style.color = err ? "red" : "white";
consoleBox.innerHTML = msg;
}
}
function setActiveCell(index: number)
{
var mems = document.getElementsByClassName('mem-cell');
var active = document.getElementsByClassName('active-cell');
for (let i = 0; i < active.length; i++)
active[i].classList.remove('active-cell');
mems[index].classList.add('active-cell');
}
function updateRegisters()
{
// Set Program Counter
if (pc != null)
pc.innerHTML = state.programCounter.toString();
// Set Accumulator
if (accumulator != null)
accumulator.innerHTML = state.accumulator.toString();
// Set Cells
for (let i = 0; i < cells.length; i++)
{
cells[i].innerHTML = state.RAM[i].toString();
if (state.RAM[i] == 0) cells[i].innerHTML += "00";
}
// Set the Active Cell
setActiveCell(state.programCounter);
}
function isEmptyOrComment(text: string): boolean {
return /^\s*$/.test(text) || text.includes('#');
}
function resetComputer()
{
reset();
console.clear();
if (inputBox != null) inputBox.innerHTML = "";
if (consoleBox != null) consoleBox.innerHTML = "";
if (outputBox != null) outputBox.innerHTML = "";
setActiveCell(0);
log ("Computer has reset!", false);
}
function stepComputer()
{
step(() =>
{
let input = prompt("Enter an Input");
if (input != null)
{
if (inputBox != null)
inputBox.innerHTML += input.toString() + "\n";
return parseInt(input);
}
return 0;
},
out =>
{
if (outputBox != null)
outputBox.innerHTML += out.toString() + "\n";
},
() => log("Program has Halted!", true));
updateRegisters();
}
function updateLineNumbers()
{
let lines = document.getElementsByClassName('line');
for (let i = 0; i < lines.length; i++)
{
let num = i.toString();
if (i < 10) num = "0" + num;
lines[i].children[0].innerHTML = num;
}
}
function createLine(index: number): HTMLInputElement | null
{
if (notepad != undefined && notepad.children.length > 99)
return null;
const line = document.createElement('div');
const number = document.createElement('span');
const input = document.createElement('input');
line.append(number);
line.append(input);
input.classList.add('line-input');
line.classList.add('line');
notepad?.insertBefore(line, notepad.children[index]);
input.addEventListener('keydown', event =>
{
function focusLine(lineNumber: number)
{
let lastLine = notepad?.children[lineNumber];
if (lastLine != undefined)
(<HTMLInputElement>lastLine.children[1]).focus();
}
var sel = input.selectionStart;
// Support for Tabbing
if (sel != undefined && event.keyCode == 9)
{
let oldSel = sel;
input.value = input.value.substr(0, sel) + "\t" +
input.value.substr(sel);
input.selectionStart = oldSel + 1;
input.selectionEnd = input.selectionStart;
event.preventDefault();
}
let lineNum = parseInt(line.children[0].innerHTML);
// Making new lines
if (event.keyCode == 13)
{
let newLine = createLine(lineNum + 1);
newLine?.focus();
}
// Removing Lines
if (lineNum > 0)
{
if (event.keyCode == 8 && input.value.length == 0)
{
focusLine(lineNum - 1);
notepad?.removeChild(line);
updateLineNumbers();
event.preventDefault();
}
}
// Up Arrow
if (event.keyCode == 38) { focusLine(lineNum - 1); }
// Down Arrow
if (event.keyCode == 40) { focusLine(lineNum + 1); }
// Make comments different color
let isComment = input.value.search('#') != -1;
input.style.color = isComment ? "cyan" : "white";
});
updateLineNumbers();
return input;
}
// EVENTS
window.onload = async () =>
{
// Create memory cells
for (let i = 0; i < 100; i++)
{
const cell = document.createElement('div');
const cellNum = document.createElement('span');
const cellMem = document.createElement('div');
cellNum.innerHTML = i.toString();
cellMem.innerHTML = "000";
cell.append(cellNum);
cell.append(cellMem);
cell.classList.add('mem-cell');
let memory = document.getElementById('memory');
if (memory != null) memory.append(cell);
cells.push(cellMem);
}
// Get lines from storage if page refreshes
for (let i = 0; i < 99; i++)
{
let storedLine = localStorage.getItem(`line${i}`);
if (storedLine != null)
{
let line = createLine(i);
if (line != null) {
(<HTMLInputElement>line).value = storedLine;
}
}
}
localStorage.clear();
if (notepad != undefined && notepad.children.length == 0)
createLine(0);
};
window.addEventListener('unload', () =>
{
let lineElems = <HTMLCollectionOf<HTMLInputElement>>document
.getElementsByClassName('line-input');
for (let i = 0; i < lineElems.length; i++) {
localStorage.setItem(`line${i}`, lineElems[i].value);
}
});
document.getElementById('load')
?.addEventListener('click', () =>
{
resetComputer();
// Get all lines
let lineElems = <HTMLCollectionOf<HTMLInputElement>>document
.getElementsByClassName('line-input');
let lines: string[] = [];
// Remove all empty lines and comments
for (let i = 0; i < lineElems.length; i++)
if (!isEmptyOrComment(lineElems[i].value))
lines.push(lineElems[i].value);
let errorOccured = false;
let program = parse(lines, err =>
{
log(err, true);
errorOccured = true;
});
load(program);
updateRegisters();
if (!errorOccured)
log("Program Loaded Successfully!", false);
});
document.getElementById('run')
?.addEventListener('click', () =>
{
if (state.programHalted) return;
stepComputer();
runningHandle = setInterval(() => stepComputer(),
state.clockSpeed);
log("Program Running...", false);
});
document.getElementById('stop')
?.addEventListener('click', () =>
{
clearInterval(runningHandle);
halt(() => log("Program has Halted!", true));
});
document.getElementById('step')
?.addEventListener('click', () =>
{
if (state.programHalted) return;
stepComputer();
});
document.getElementById('docs')
?.addEventListener('click', () => {
window.open("https://github.com/JakubSzark/jakubs-little-man-computer", "_blank");
});
document.getElementById('clock')
?.addEventListener('change', () =>
{
var clock = <HTMLInputElement>document.getElementById('clock');
state.clockSpeed = clock.valueAsNumber;
});
|
f2a3649ccac2dcea6b4893a0fa26b99cbd6bb1aa
|
TypeScript
|
trxcllnt/IxJS
|
/spec/iterable-operators/isempty-spec.ts
| 2.5625
| 3
|
import * as Ix from '../Ix';
import * as test from 'tape';
const { empty } = Ix.iterable;
const { isEmpty } = Ix.iterable;
test('Iterable#isEmpty empty', t => {
t.true(isEmpty(empty<number>()));
t.end();
});
test('Iterable#isEmpty not-empty', t => {
t.false(isEmpty([1]));
t.end();
});
|
60e7f7ae4ec7773cfc072d4d9b578d3abaf0ac5e
|
TypeScript
|
onaio/reveal-frontend
|
/src/store/ducks/goals.ts
| 2.65625
| 3
|
import { Dictionary } from '@onaio/utils';
import { get, keyBy, values } from 'lodash';
import { AnyAction, Store } from 'redux';
import SeamlessImmutable from 'seamless-immutable';
import { PlanActionCodesType } from '../../components/forms/PlanForm/types';
/** the reducer name */
export const reducerName = 'goals';
/** interface for goal Object */
export interface Goal {
action_code: PlanActionCodesType;
action_description: string;
action_prefix: string;
action_reason: string;
action_title: string;
completed_task_count: number;
goal_comparator: string;
goal_id: string;
goal_unit: string;
goal_value: number;
id: string;
jurisdiction_id: string;
measure: string;
plan_id: string;
task_business_status_map: Dictionary;
task_count: number;
}
// actions
/** GOALS_FETCHED action type */
export const GOALS_FETCHED = 'reveal/reducer/goals/GOALS_FETCHED';
/** SET_CURRENT_GOAL action type */
export const SET_CURRENT_GOAL = 'reveal/reducer/goals/SET_CURRENT_GOAL';
/** REMOVE_GOALS action type */
export const REMOVE_GOALS = 'reveal/reducer/goals/REMOVE_GOALS';
/** interface for authorize action */
export interface FetchGoalsAction extends AnyAction {
goalsById: { [key: string]: Goal };
type: typeof GOALS_FETCHED;
}
/** interface for setting current goal action */
export interface SetCurrentGoalAction extends AnyAction {
currentGoal: string | null;
type: typeof SET_CURRENT_GOAL;
}
/** Interface for remove goals action */
export interface RemoveGoalsAction extends AnyAction {
type: typeof REMOVE_GOALS;
goalsById: {};
}
/** Create type for Goal reducer action */
export type GoalActionTypes =
| FetchGoalsAction
| SetCurrentGoalAction
| RemoveGoalsAction
| AnyAction;
/** interface for Goal state */
interface GoalState {
goalsById: { [key: string]: Goal[] } | {};
currentGoal: string | null;
}
/** immutable Goal state */
export type ImmutableGoalState = GoalState & SeamlessImmutable.ImmutableObject<GoalState>;
/** initial Goal state */
const initialState: ImmutableGoalState = SeamlessImmutable({
currentGoal: null,
goalsById: {},
});
/** the Goal reducer function */
export default function reducer(state = initialState, action: GoalActionTypes): ImmutableGoalState {
switch (action.type) {
case GOALS_FETCHED:
return SeamlessImmutable({
...state,
goalsById: { ...state.goalsById, ...action.goalsById },
});
case SET_CURRENT_GOAL:
return SeamlessImmutable({
...state,
currentGoal: action.currentGoal,
});
case REMOVE_GOALS:
return SeamlessImmutable({
...state,
goalsById: action.goalsById,
});
default:
return state;
}
}
// action creators
/** fetch Goals creator
* @param {Goal[]} goalsList - array of goal objects
* @returns {FetchGoalsAction} FetchGoalsAction
*/
export const fetchGoals = (goalsList: Goal[] = []): FetchGoalsAction => {
return {
goalsById: keyBy(
goalsList.map((item: Goal) => {
if (typeof item.task_business_status_map === 'string') {
item.task_business_status_map = JSON.parse(item.task_business_status_map);
}
return item;
}),
goal => goal.id
),
type: GOALS_FETCHED,
};
};
/** fetch Current Goal
* @param currentGoal - current selected goal type string if none defaults to null
* @returns {SetchCurrentGoalAction} setchCurrentGoalAction
*/
export const setCurrentGoal = (currentGoal: string | null): SetCurrentGoalAction => {
return {
currentGoal,
type: SET_CURRENT_GOAL,
};
};
// Actions
export const removeGoalsAction: RemoveGoalsAction = {
goalsById: {},
type: REMOVE_GOALS,
};
// selectors
/** get goals by id
* @param {Partial<Store>} state - the redux store
*/
export function getGoalsById(state: Partial<Store>): { [key: string]: Goal } {
return (state as any)[reducerName].goalsById;
}
/** get one goal using its id
* @param {Partial<Store>} state - the redux store
* @param {string} id - the goal id
* @returns {Goal|null} a goal or null
*/
export function getGoalById(state: Partial<Store>, id: string): Goal | null {
return get((state as any)[reducerName].goalsById, id) || null;
}
/** get goals by plan id
* @param {Partial<Store>} state - the redux store
* @param {string} planId - the plan id
* @returns {Goal[]} an array of goals
*/
export function getGoalsByPlanId(state: Partial<Store>, planId: string): Goal[] {
return values((state as any)[reducerName].goalsById).filter((e: Goal) => e.plan_id === planId);
}
/** get goals by goal id
* @param {Partial<Store>} state - the redux store
* @param {string} goalId - the goal id
* @returns {Goal[]} an array of goals
*/
export function getGoalsByGoalId(state: Partial<Store>, goalId: string): Goal[] {
return values((state as any)[reducerName].goalsById).filter((e: Goal) => e.goal_id === goalId);
}
/** get goals by jurisdiction id
* @param {Partial<Store>} state - the redux store
* @param {string} jurisdictionId - the jurisdiction id
* @returns {Goal[]} an array of goals
*/
export function getGoalsByJurisdictionId(state: Partial<Store>, jurisdictionId: string): Goal[] {
return values((state as any)[reducerName].goalsById).filter(
(e: Goal) => e.jurisdiction_id === jurisdictionId
);
}
/** get goals by plan id and jurisdiction id
* @param {Partial<Store>} state - the redux store
* @param {string} planId - the plan id
* @param {string} jurisdictionId - the jurisdiction id
* @returns {Goal[]} an array of goals
*/
export function getGoalsByPlanAndJurisdiction(
state: Partial<Store>,
planId: string,
jurisdictionId: string
): Goal[] {
return values((state as any)[reducerName].goalsById).filter(
(e: Goal) => e.plan_id === planId && e.jurisdiction_id === jurisdictionId
);
}
/** get currently selected goal */
export function getCurrentGoal(state: Partial<Store>) {
return (state as any)[reducerName].currentGoal;
}
|
964f3ecb7995e5e3e7b763f8b0e280935df99f06
|
TypeScript
|
kobi2187/TypeScript.NET
|
/dist/amd/System/Collections/Array/Sorting/mergeSort.d.ts
| 2.828125
| 3
|
import { Primitive } from "../../../Primitive";
/**
* Merge sort O(n log (n))
* Warning: Uses recursion.
* @param target
* @returns {number[]}
*/
export declare function mergeSort<T extends Primitive>(target: T[]): T[];
|
8022ac9e7d102742d5b4b5915e95c27907942962
|
TypeScript
|
EdgeApp/edge-react-gui
|
/src/util/tokenIdTools.ts
| 3.078125
| 3
|
import { EdgeTokenId } from '../types/types'
import { CurrencyConfigMap } from './utils'
/**
* Precisely identify the assets named by a currency-code array.
* Accepts plain currency codes, such as "ETH" or "REP",
* but also scoped currency codes like "ETH-REP".
*
* The goal is to delete this once the wallet stops using this legacy format
* internally.
*/
export function upgradeCurrencyCodes(lookup: (currencyCode: string) => EdgeTokenId[], currencyCodes?: string[]): EdgeTokenId[] | undefined {
if (currencyCodes == null || currencyCodes.length === 0) return
const out: EdgeTokenId[] = []
for (const currencyCode of currencyCodes) {
const [parentCode, tokenCode] = currencyCode.split('-')
if (tokenCode == null) {
// It's a plain code, like "REP", so add all matches:
out.push(...lookup(parentCode))
} else {
// It's a scoped code, like "ETH-REP", so filter using the parent:
const parent = lookup(parentCode).find(match => match.tokenId == null)
if (parent == null) continue
out.push(...lookup(tokenCode).filter(match => match.pluginId === parent.pluginId))
}
}
return out
}
/**
* Creates a function that returns all matching tokenId's for a currency code.
*/
export function makeCurrencyCodeTable(currencyConfigMap: CurrencyConfigMap): (currencyCode: string) => EdgeTokenId[] {
const map = new Map<string, EdgeTokenId[]>()
function addMatch(currencyCode: string, location: EdgeTokenId): void {
const key = currencyCode.toLowerCase()
const list = map.get(key)
if (list != null) list.push(location)
else map.set(key, [location])
}
for (const pluginId of Object.keys(currencyConfigMap)) {
const currencyConfig = currencyConfigMap[pluginId]
const { allTokens, currencyInfo } = currencyConfig
addMatch(currencyInfo.currencyCode, { pluginId })
for (const tokenId of Object.keys(allTokens)) {
const token = allTokens[tokenId]
addMatch(token.currencyCode, { pluginId, tokenId })
}
}
return currencyCode => map.get(currencyCode.toLowerCase()) ?? []
}
|
6cdc0dcd2b418faba8380dbbd5c198ca1bed0b54
|
TypeScript
|
johanneslumpe/styled-props
|
/src/utils/overflow/__tests__/overflowY.ts
| 2.90625
| 3
|
import {
Breakpoints,
Theme,
theme,
ThemeWithoutBreakpoints,
themeWithoutBreakpoints,
} from '../../../test-utils/theme';
import { overflowY } from '../overflowY';
describe('overflowY', () => {
it('should return a function', () => {
const result = overflowY();
expect(result).toBeInstanceOf(Function);
});
it('should use `overflowY` as component and css prop', () => {
const result = overflowY()({ style$OverflowY: 'inherit' });
expect(result).toEqual({ overflowY: 'inherit' });
});
it('should allow using a custom value type', () => {
const result = overflowY<'a'>()({ style$OverflowY: 'a' });
expect(result).toEqual({ overflowY: 'a' });
});
it('should use an interface which marks `overflowY` as optional', () => {
const result = overflowY<'a'>()({});
expect(result).toEqual(undefined);
});
it('should allow using a theme', () => {
const result = overflowY<'value', ThemeWithoutBreakpoints>({
themeProp: 'dummy',
})({ style$OverflowY: 'value', theme: themeWithoutBreakpoints });
expect(result).toEqual({
overflowY: themeWithoutBreakpoints.dummy.value,
});
});
it('should allow using breakpoints', () => {
const result = overflowY<
'a' | 'b' | 'c' | 'd',
Theme,
Breakpoints
>()({
style$OverflowY: {
base: 'a',
large: 'b',
medium: 'c',
small: 'd',
},
theme,
});
expect(result).toEqual({
overflowY: 'a',
[theme.breakpoints.large]: {
overflowY: 'b',
},
[theme.breakpoints.medium]: {
overflowY: 'c',
},
[theme.breakpoints.small]: {
overflowY: 'd',
},
});
});
});
|
aefba5c8fe987b69a247435bb729f16581e02595
|
TypeScript
|
digital-asset/daml-js
|
/src/model/Filters.ts
| 2.625
| 3
|
// Copyright (c) 2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
import {InclusiveFilters} from "./InclusiveFilters";
/**
* Example:
*
* ```
* {
* inclusive: {
* templateIds: [
* {
* packageId: 'some-package-id',
* moduleName: 'SomeModule',
* entityName: 'SomeTemplate'
* }
* ]
* }
* }
* ```
*
* To express values in a more concise way, you can have a look at the {@link ValueHelpers}.
*
* @see InclusiveFilters
* @see Identifier
*/
export interface Filters {
/**
* If not set, no filters will be applied.
*/
inclusive?: InclusiveFilters
}
|
45dd75b58aaaa101f9b8f767c2cd376104cba33c
|
TypeScript
|
namek-network/clover-ui
|
/src/utils/balanceUtils.ts
| 2.625
| 3
|
import { BigNumber as BN } from "bignumber.js";
export function trimEnd0(value: string): string {
const n = new BN(value, 10)
if (n.eq(0)) {
return '0'
}
const afterTrim = value.replace(/0+$/,'')
if (afterTrim.endsWith(".")) {
return afterTrim + "0"
}
return afterTrim
}
|
a54fed1a423d6bfe3d4a465f93d1041a393adf26
|
TypeScript
|
nghiattran/transpiler
|
/src/language/pascal/intermediate/typeimpl/TypeKeyImpl.ts
| 2.859375
| 3
|
import {TypeKey} from '../../../../intermediate/TypeKey';
import {BaseObject} from '../../../../util/BaseObject';
export class TypeKeyImpl extends BaseObject implements TypeKey {
private text : string;
// Enumeration
public static ENUMERATION_CONSTANTS : TypeKeyImpl = new TypeKeyImpl('ENUMERATION_CONSTANTS');
// Subrange
public static SUBRANGE_BASE_TYPE : TypeKeyImpl = new TypeKeyImpl('SUBRANGE_BASE_TYPE');
public static SUBRANGE_MIN_VALUE : TypeKeyImpl = new TypeKeyImpl('SUBRANGE_MIN_VALUE');
public static SUBRANGE_MAX_VALUE : TypeKeyImpl = new TypeKeyImpl('SUBRANGE_MAX_VALUE');
// Array
public static ARRAY_INDEX_TYPE : TypeKeyImpl = new TypeKeyImpl('ARRAY_INDEX_TYPE');
public static ARRAY_ELEMENT_TYPE : TypeKeyImpl = new TypeKeyImpl('ARRAY_ELEMENT_TYPE');
public static ARRAY_ELEMENT_COUNT : TypeKeyImpl = new TypeKeyImpl('ARRAY_ELEMENT_COUNT');
// Record
public static RECORD_SYMTAB : TypeKeyImpl = new TypeKeyImpl('RECORD_SYMTAB');
/**
* Constructor.
*/
constructor(text : string) {
super();
text = text || this.toString().toLowerCase();
}
/**
* Getter.
* @return the text of the definition code.
*/
public getText() : string {
return this.text;
}
public toString() : string {
return this.toString().toLowerCase();
}
}
|
090ef424c1e7e1e258c836cc0eede5e63efb91db
|
TypeScript
|
mevlutbucan/react-payapp
|
/src/utils/index.ts
| 3.765625
| 4
|
/**
* @returns Validation result (true|false).
*/
export const checkCardNumber = (cardNetwork: NetworkType, cardNumber: string) => {
if (!cardNetwork) return false;
// if (cardNetwork.algorithm === 'Luhn')
return checkLuhn(cardNumber);
};
interface IAlgorithmicControlFunction {
(cardNumber: string): boolean;
}
/**
* The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This number must pass the following test:
*
* 1. From the rightmost digit (excluding the check digit) and moving left, double the value of every second digit. The check digit is neither doubled nor included in this calculation; the first digit doubled is the digit located immediately left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the result (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same final result can be found by subtracting 9 from that result (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
* 2. Take the sum of all the digits (including the check digit).
* 3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; otherwise it is not valid.
*
* @param cardNumber As a string without spaces.
*/
const checkLuhn: IAlgorithmicControlFunction = function (cardNumber) {
const sum = cardNumber
.slice(0, cardNumber.length - 1)
.split('')
.reduceRight(
// Callback function of reduce
(acc, num, i) => {
let value = parseInt(num, 10);
if ((cardNumber.length - i) % 2 === 0) {
value *= 2;
if (value > 9) {
value -= 9;
}
}
return acc + value;
},
// Initial value of reduce (check digit)
parseInt(cardNumber.slice(-1), 10)
);
return sum % 10 === 0;
};
|
f802ba43fcd036ec55b38f11fad719d986d0c96a
|
TypeScript
|
sakho3600/preuve-covoiturage
|
/api/services/user/tests/AuthRepositoryProvider.spec.ts
| 2.515625
| 3
|
import { describe } from 'mocha';
import { expect } from 'chai';
import { ConfigInterfaceResolver } from '@ilos/common';
import { PostgresConnection } from '@ilos/connection-postgres';
import { CryptoProvider, CryptoProviderInterfaceResolver } from '@pdc/provider-crypto';
import { AuthRepositoryProvider } from '../src/providers/AuthRepositoryProvider';
import { AuthRepositoryProviderInterface } from '../src/interfaces/AuthRepositoryProviderInterface';
import { UserFindInterface } from '../src/shared/user/common/interfaces/UserFindInterface';
class Config extends ConfigInterfaceResolver {
config = {
confirmation: 7 * 86400,
invitation: 7 * 86400,
reset: 1 * 86400,
};
get(k: string, fb: string): string {
const key = k.split('.').pop();
if (key in this.config) {
return this.config[key];
}
return fb;
}
}
describe('Auth pg repository', async () => {
let repository: AuthRepositoryProviderInterface;
let connection;
let id;
const email = 'toto@toto.com';
const getUser = async function(customEmail = email): Promise<UserFindInterface> {
const result = await connection.getClient().query({
text: 'SELECT * from auth.users where email = $1',
values: [customEmail],
});
return result.rows[0];
};
before(async () => {
connection = new PostgresConnection({
connectionString:
'APP_POSTGRES_URL' in process.env
? process.env.APP_POSTGRES_URL
: 'postgresql://postgres:postgres@localhost:5432/pdc-local',
});
await connection.up();
repository = new AuthRepositoryProvider(
connection,
(new CryptoProvider() as unknown) as CryptoProviderInterfaceResolver,
new Config(),
);
const result = await connection.getClient().query({
text: 'INSERT INTO auth.users (email, firstname, lastname, role) values ($1, $2, $3, $4) RETURNING _id',
values: [email, 'toto', 'tata', 'admin'],
});
id = result.rows[0]._id;
});
after(async () => {
if (id) {
await connection.getClient().query({
text: `DELETE FROM ${repository.table} WHERE _id = $1`,
values: [id],
});
}
await connection.down();
});
it('should create token by email', async () => {
await repository.createTokenByEmail(email, 'confirmation');
const user = await getUser();
expect(user.token).to.match(/^\$2a\$10\$/); // bcrypted token
expect(user.status).to.eq('pending');
expect(user.token_expires_at).is.a('date');
});
it('should clear token by email', async () => {
const success = await repository.clearTokenByEmail(email);
const user = await getUser();
expect(success).to.eq(true);
expect(user.token).to.eq(null);
expect(user.token_expires_at).to.eq(null);
expect(user.status).to.eq('pending');
});
it('should challenge token by email', async () => {
const token = await repository.createTokenByEmail(email, 'confirmation');
const success = await repository.challengeTokenByEmail(email, token);
expect(success).to.eq(true);
});
it('should update password by id', async () => {
const password = '12345';
const result = await repository.updatePasswordById(id, password);
expect(result).to.eq(true);
const user = await getUser();
expect(user.password).not.to.eq(null);
});
it('should update password by email', async () => {
const password = '12345';
const result = await repository.updatePasswordByEmail(email, password);
expect(result).to.eq(true);
const user = await getUser();
expect(user.password).not.to.eq(null);
});
it('should challenge password by id', async () => {
const password = '12345';
const result = await repository.updatePasswordById(id, password);
expect(result).to.eq(true);
const success = await repository.challengePasswordById(id, password);
expect(success).to.eq(true);
const failure = await repository.challengePasswordById(id, 'not_the_password');
expect(failure).to.eq(false);
});
it('should challenge password by email', async () => {
const password = '12345';
const result = await repository.updatePasswordById(id, password);
expect(result).to.eq(true);
const success = await repository.challengePasswordByEmail(email, password);
expect(success).to.eq(true);
const failure = await repository.challengePasswordByEmail(email, 'not_the_password');
expect(failure).to.eq(false);
});
it('should update email by id', async () => {
const courriel = `toto-${Math.random() * 1000}@example.com`;
await repository.updateEmailById(id, courriel);
const user = await getUser(courriel);
expect(user.token).to.match(/\$2a\$10/);
expect(user.status).to.eq('pending');
});
});
|
d1f969f402aff1a916be009f430dde6c75178308
|
TypeScript
|
irtyamine/algorithm-training
|
/1254. Number of Closed Islands.ts
| 3.5
| 4
|
// https://leetcode.com/problems/number-of-closed-islands
function closedIsland (grid: number[][]): number {
const ROWS = grid.length
const COLS = grid[0].length
let numberOfClosedIslands = 0
for (let i = 1; i < ROWS - 1; i++) {
for (let j = 0; j < COLS - 1; j++) {
if (grid[i][j] === 0 && dfs(grid, i, j)) {
numberOfClosedIslands++
}
}
}
return numberOfClosedIslands
function dfs (grid: number[][], i: number, j: number): boolean {
// -1 : visited
// 1 : water
// 0 : land
if (grid[i][j] === -1 || grid[i][j] === 1) {
return true
}
if (isOnTheEdge(i, j)) {
return false
}
grid[i][j] = -1
const up = dfs(grid, i - 1, j)
const down = dfs(grid, i + 1, j)
const left = dfs(grid, i, j - 1)
const right = dfs(grid, i, j + 1)
return up && down && left && right
}
function isOnTheEdge (i: number, j: number): boolean {
return i === 0 || j === 0 || i === ROWS - 1 || j === COLS - 1
}
}
|
2453681043c38a4a862f7c11dab3e747a2e4a321
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/clients/node/client-ec2-node/types/_InstanceCreditSpecificationRequest.ts
| 2.828125
| 3
|
/**
* <p>Describes the credit option for CPU usage of a T2 or T3 instance.</p>
*/
export interface _InstanceCreditSpecificationRequest {
/**
* <p>The ID of the instance.</p>
*/
InstanceId?: string;
/**
* <p>The credit option for CPU usage of the instance. Valid values are <code>standard</code> and <code>unlimited</code>.</p>
*/
CpuCredits?: string;
}
export type _UnmarshalledInstanceCreditSpecificationRequest = _InstanceCreditSpecificationRequest;
|
a43f122b2db20ff7c97b22143d113ddb967b3002
|
TypeScript
|
vargroozzz/pok_bot
|
/src/kafka/maintenances.ts
| 2.796875
| 3
|
import {flow, pipe} from "fp-ts/lib/function"
import * as N from "fp-ts/lib/number"
import * as S from "fp-ts/lib/string"
import {contramap, reverse} from "fp-ts/lib/Ord"
import {filter, filterMap, foldMap, map, sortBy} from "fp-ts/lib/Array"
import {Castle, Maintenance, Store} from "./types"
import * as O from "fp-ts/lib/Option"
const getPriceMultiplier = <A extends {ownerCastle: Castle, castleDiscount?: number}>(store: A) =>
store.ownerCastle === "🍆" ?
(store.castleDiscount ? 100 - store.castleDiscount : 100) * (0.01) :
1
// @ts-ignore
const byPrice = pipe(N.Ord, contramap((s: Maintenance) => s.maintenanceCost * getPriceMultiplier(s)))
const byMana = pipe(N.Ord, contramap((s: Maintenance) => s.mana), reverse)
export const sortByPriceByMana = sortBy([byPrice, byMana])
const hasMana = <A extends {mana: number}>(store: A) => store.mana > 0
export const storeToOptionMaintenance: (store: Store) => O.Option<Maintenance> =
({ownerCastle, mana, link, maintenanceCost, castleDiscount = 0}) =>
maintenanceCost === undefined ?
O.none :
O.some({ownerCastle, mana, link, maintenanceCost, castleDiscount})
export const storesToMaintenances = filterMap(storeToOptionMaintenance)
export const maintenancePrinter = (store: Maintenance) =>
`💧${store.mana} 💰${Math.ceil(store.maintenanceCost * getPriceMultiplier(store))} ${store.ownerCastle} /ws_${store.link}
`
export const maintenancesPrinter = foldMap(S.Monoid)(maintenancePrinter)
export const getMaintenances = flow(storesToMaintenances, filter(hasMana), sortByPriceByMana)
export const printMaintenances = flow(getMaintenances, maintenancesPrinter)
|
97bf2cbd7e2dbee595f3c978549d023f4af560e6
|
TypeScript
|
Aventhor/react-base-routing
|
/src/utils/PathsManager.ts
| 3.046875
| 3
|
import { AppRoute } from '../interfaces/AppRoute';
import { LayoutRoute } from '../interfaces/LayoutRoute';
class PathsManager {
public isAppRoute(object: any): object is AppRoute {
return 'path' in object;
}
public isLayoutRoute(object: any): object is LayoutRoute {
return 'layout' in object;
}
public isRoutesArrayEmpty = (
routes: LayoutRoute[] | AppRoute[]
): boolean => {
return routes.length === 0;
};
public getRoutePathsArray = (route: AppRoute): string[] => {
if (!route.path) return [];
if (route.path instanceof Array) {
return route.path.map((p) => p);
} else {
return [route.path];
}
};
public getPathsArray(routes: AppRoute[]): string[] {
return routes.map((route) => this.getRoutePathsArray(route)).flat(1);
}
public getLayoutPaths(routes: LayoutRoute[]): string[] {
return routes
.map((layout) =>
layout.routes
.map((route) => this.getRoutePathsArray(route))
.flat(1)
)
.flat(1);
}
}
export default new PathsManager();
|
cb161bb8f15009e0afc774fbd833d95f962b5042
|
TypeScript
|
ErgoLied/Homework
|
/Homework/js/lesson26_typescript/main2.ts
| 2.640625
| 3
|
import {IPost, IUser} from "./post";
let post1: IPost = {
id: 1,
userId: 10,
body: 'ololo',
title: 'post'
};
//- Створити функцію конструктор для об'єктів User з полями id, name, surname , email, phone etc
let user: IUser = {
id: 10,
name: 'Meh',
username: 'Meh',
email: 'Sincere@april.biz',
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: {
lat: '4524',
lng: '4524'
},
},
company: {
name: 'Paimon.exe',
catchPhrase: 'Ehe te nanda yo',
bs: 'Sergio gold quotes foundations'
}
}
console.log(user);
console.log(post1);
|
2fcd27ff58b46d0a4e9770aadab03c2bdb603759
|
TypeScript
|
basilred/ts-tests
|
/src/modules/namespaces.ts
| 3.265625
| 3
|
namespace Personnel {
export interface IUser {
displayInfo();
}
export class Employee {
constructor(public name: string) {}
}
export function work(emp: Employee): void {
console.log(`${emp.name} is working`);
}
export const defaultUser = { name: 'Kate' };
}
namespace Data {
export namespace Personnel { // вложенное пространство имён
export class Employee {
constructor(public name: string) {}
}
}
export namespace Clients { // вложенное пространство имён
export class VipClient {
constructor(public name: string) {}
}
}
}
import employee = Data.Personnel.Employee;
export default function() {
// Пространства имён
((sectionName: string) => {
console.log(`\n${sectionName}`);
const alice = new Personnel.Employee('Alice');
console.log(Personnel.work(alice));
})('Пространства имён');
((sectionName: string) => {
console.log(`\n${sectionName}`);
const tom = new Data.Personnel.Employee('Tom');
console.log(tom.name);
const sam = new Data.Clients.VipClient('Sam');
console.log(sam.name);
})('Вложенные пространства имён');
((sectionName: string) => {
console.log(`\n${sectionName}`);
const bob = new employee('Bob');
console.log(bob.name);
})('Псевдонимы пространств имён');
};
|
543a24f13a834b2b6180a898eca8112450e4c440
|
TypeScript
|
githop/animate-canvas
|
/src/index.ts
| 2.6875
| 3
|
import {
CANVAS_WIDTH,
CANVAS_HEIGHT,
X_OFFSET,
Y_OFFSET,
SIDE_LENGTH,
Triangle,
Point,
Path,
History,
getPathCords,
deriveInnerTriangle,
drawTriangles,
_drawTriangles,
clearRect,
makePath,
} from './utils';
document.addEventListener('DOMContentLoaded', (event) => {
const cvs = <HTMLCanvasElement>document.getElementById('cvs');
const ctx = <CanvasRenderingContext2D>cvs.getContext('2d');
// renderBtn.addEventListener('click', () => reDraw(ctx));
// const path = makePath(0,0,100,100);
init(cvs, ctx);
});
function init(cvs: HTMLCanvasElement, ctx: CanvasRenderingContext2D) {
cvs.width = CANVAS_WIDTH;
cvs.height = CANVAS_HEIGHT;
const history: History = { triangles: [], paths: [] };
window.requestAnimationFrame((event) => {
start(ctx, SIDE_LENGTH, X_OFFSET, Y_OFFSET, 3, history, 0.2).then((x: any) => {
console.log('all done!');
})
});
}
async function start(ctx: CanvasRenderingContext2D, sideLen: number, xOffset: number, yOffset: number, depth: number, h: History, speed: number) {
if (depth > 0) {
let tri = getPathCords(sideLen, xOffset, yOffset);
let innerTri = deriveInnerTriangle(sideLen, xOffset, yOffset);
//base triangle
await drawTriangles(ctx, tri, h, speed);
//inverted inner triangle
await drawTriangles(ctx, innerTri, h, speed);
//recursively draw the rest of the inner triangles.
await innerRecur(ctx, innerTri, sideLen, depth, h, speed);
ctx.fillStyle = 'white';
ctx.font = '24px monospace';
const text = 'Sierpinski Triangle';
const centerText = ctx.measureText(text);
ctx.fillText(text, innerTri.centoid.x - (centerText.width / 2), innerTri.centoid.y)
}
}
async function innerRecur(ctx: CanvasRenderingContext2D, innerTri: Triangle, sideLen: number, depth: number, h: History, speed: number) {
if (depth > 0) {
let top = innerTri.a;
let bLeft = getPathCords(sideLen / 2, innerTri.c.x - (sideLen / 2), innerTri.c.y).a;
let bRight = innerTri.c;
for (let inner of [top, bLeft, bRight]) {
let iTri = deriveInnerTriangle(sideLen / 2, inner.x, inner.y);
await drawTriangles(ctx, iTri, h, speed);
}
let d = --depth;
await innerRecur(ctx, deriveInnerTriangle(sideLen / 2, innerTri.a.x, innerTri.a.y), sideLen / 2, d, h, speed);
innerRecur(ctx, deriveInnerTriangle(sideLen / 2, bLeft.x, bLeft.y), sideLen / 2, d, h, speed);
await innerRecur(ctx, deriveInnerTriangle(sideLen / 2, innerTri.c.x, innerTri.c.y), sideLen / 2, d, h, speed);
}
}
|
fdf7e4cefdf5299432260705ecc2a64dab188857
|
TypeScript
|
ingscarrero/nodeJS
|
/ts-generator/bin/framework/types/Immutable.d.ts
| 2.890625
| 3
|
export declare abstract class Immutable<T> {
private data;
/**
*
*/
constructor(data?: T);
getState(): Readonly<T>;
protected setProperty(name: keyof T, value: T[keyof T]): this;
protected handleSetProperty(name: keyof T, value: T[keyof T]): void;
}
|
5d0820b70b187e89d8a2d580c2dc2e2ef0df6320
|
TypeScript
|
ZnoGouDj/codewars-challenges
|
/6kyu/6kyu-consecutive-string.ts
| 3.34375
| 3
|
export function longestConsec(strarr: string[], k: number): string {
let longest = '';
if (strarr.length === 0 || k < 1) return '';
for (let i = 0; i <= strarr.length - k; i++) {
let localLongest = strarr.slice(i, i + k).join('');
if (localLongest.length > longest.length) {
longest = localLongest;
}
}
return longest;
}
|
9862924cadb687ad1506dbeeb049e1b75da91bbe
|
TypeScript
|
soon14/test
|
/admin-client/src/store/modules/userManager/onlineUser.ts
| 2.515625
| 3
|
import { CodeMsg } from '../../index'
import { Commit } from 'vuex'
import { getOnlineUser, downloadOnlineUser, kickUser } from '../../../api/admin/userManager/userManager';
export interface OnlineTable {
uid: number,
channel: string,
ip: string,
location:string,
gid: string
}
export interface State {
onlineTable: OnlineTable[],
totalCount:number,
code:number,
msg:string
}
const state: State = {
onlineTable: [{
uid: 0,
channel: "",
ip: "",
location:"",
gid: ""
}],
totalCount:0,
code:0,
msg:"",
}
const mutations = {
SET_ONLINETABLE: (state: State, data: CodeMsg<any>) => {
state.code = data.code;
state.onlineTable = data.msg.data;
state.totalCount = data.msg.totalCount
},
SET_EXPORTONLINETABLE: (state: State, data: CodeMsg<any>) => {
state.code = data.code;
state.onlineTable = data.msg||data.err;
},
SET_CODE: (state: State, data: CodeMsg<any>) => {
state.code = data.code;
state.msg = data.msg;
},
SET_ERROR: (state: State, data: CodeMsg<any>) => {
state.code = data.code;
state.msg = data.err
},
}
// actions
const actions = {
GetOnlineUser(context: { commit: Commit, state: State }, queryItem) { //获取普通用户信息
return new Promise(async (resolve, reject) => {
getOnlineUser(queryItem).then((response: { data }) => {
context.commit('SET_ONLINETABLE', response.data)
resolve(response.data)
}).catch(error => {
context.commit('SET_ERROR', error)
console.error("catch", error)
resolve()
})
});
},
KickUser(context: { commit: Commit, state: State }, queryItem) { //踢玩家
return new Promise(async (resolve, reject) => {
kickUser(queryItem).then((response: { data }) => {
context.commit('SET_CODE', response.data)
resolve(response.data)
}).catch(error => {
console.error("catch", error)
resolve()
})
});
},
DownloadOnlineUser(context: { commit: Commit, state: State }, queryItem) { //获取普通用户信息
return new Promise(async (resolve, reject) => {
downloadOnlineUser(queryItem).then((response: { data }) => {
context.commit('SET_EXPORTONLINETABLE', response.data)
resolve(response.data)
}).catch(error => {
context.commit('SET_ERROR', error)
console.error("catch", error)
resolve()
})
});
},
}
export default {
state,
// getters,
actions,
mutations
}
|
8de63ce2e8283e116bfc449a72e64dd326220e94
|
TypeScript
|
Kraamel/Marc
|
/src/module/auth/dto/auth-credentials.dto.ts
| 3.046875
| 3
|
import { IsString, Matches, MaxLength, MinLength } from 'class-validator';
export class AuthCredentialsDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;
// @IsString()
// @Matches(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
// {message: 'Invalid email address'})
email: string;
@IsString()
@MinLength(4)
@MaxLength(20)
@Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/,
{message: 'Password too weak, contain at least 1 lower case letter, at least 1 upper case letter and at least 1 number or special character.'})
password: string;
}
|
2c2922e3de2e5a3a9c1ec42ae329d51e2365125a
|
TypeScript
|
Alduino/Muzik
|
/apps/desktop/src/lib/ipc/main.ts
| 2.625
| 3
|
import {ipcMain, WebContents} from "electron";
import AbortController from "node-abort-controller";
import listen, {HandleHandler, InvokeHandler, ListenResult} from "./impl";
const ipcObjects = new Map<string, ListenResult>();
const handleAdders = new Set<(res: ListenResult) => void>();
export function registerWC(id: string, wc: WebContents): void {
if (ipcObjects.has(id))
throw new Error(`A target is already registered with ID '${id}'`);
const obj = listen(
() => new AbortController(),
wc.send.bind(wc),
ipcMain.on.bind(ipcMain)
);
// add obj to list of existing
ipcObjects.set(id, obj);
// call any handlers that have already been set
for (const add of handleAdders) {
add(obj);
}
}
export const handle: HandleHandler = (ev, respond) => {
// add handlers to ipc objects that don't exist yet
handleAdders.add(({handle}) => {
handle(ev, respond);
});
// add handlers to existing ipc objects
for (const [, {handle}] of ipcObjects.entries()) {
handle(ev, respond);
}
};
type InvokeHandlerFactory = (id: string) => InvokeHandler;
export const invoke: InvokeHandlerFactory = id => {
if (!ipcObjects.has(id))
throw new Error(`No target found with name '${id}'`);
return ipcObjects.get(id).invoke;
};
|
25cb90d60477988df2114d22d0f5bc83480ed6fa
|
TypeScript
|
newcanopies/ADA
|
/ada-ui/src/app/classes/parameter-declaration.ts
| 2.890625
| 3
|
export class ParameterDeclaration {
name: string;
type: string;
constructor(parameterDeclarationJSON) {
this.name = parameterDeclarationJSON['name'];
this.type = parameterDeclarationJSON['type'];
}
}
|
ca6d751e108781660034c64a546e128e9fe8eb26
|
TypeScript
|
kyonetca/core
|
/src/core/protocol/hydra/messages/interfaces/WritableAdditiveSharingMessageFactoryInterface.ts
| 2.84375
| 3
|
/// <reference path='../../../../../../ts-definitions/node/node.d.ts' />
/**
* Constructs the payload for an ADDITIVE_SHARING message
* For more information on the message format, see {@link core.protocol.hydra.AdditiveSharingMessageInterface}
*
* @interface
* @class core.protocol.hydra.WritableAdditiveSharingMessageFactoryInterface
*/
interface WritableAdditiveSharingMessageFactoryInterface {
/**
* Constructs the payload for an ADDITIVE_SHARING message.
*
* @method core.protocol.hydra.WritableAdditiveSharingMessageFactoryInterface#constructMessage
*
* @param {string} relayToIp The IP of the node to which the payload should be relayed as a CREATE_CELL_ADDITIVE message
* @param {number} relayToPort The port of the node to which the payload should be relayed as a CREATE_CELL_ADDITIVE message
* @param {Buffer} payload The payload of the message.
* @param {number} payloadLength Optional. Number of octets of the payload.
*
* @returns {Buffer} The resulting payload of an ADDITIVE_SHARING message
*/
constructMessage (relayToIp:string, relayToPort:number, payload:Buffer, payloadLength?:number):Buffer;
}
export = WritableAdditiveSharingMessageFactoryInterface;
|
632327031b48d98dd2964e41d45ca9b8344bd9ac
|
TypeScript
|
sortofsleepy/crossfade-test
|
/src/jirachi/math/vec4.ts
| 3.28125
| 3
|
/* Copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
import glMatrix from './common/matrix'
/**
* @class 4 Dimensional Vector
* @name vec4
*/
var vec4:any = {};
/**
* Creates a new, empty vec4
*
* @returns {vec4} a new 4D vector
*/
vec4.create = function() {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = 0;
out[1] = 0;
out[2] = 0;
out[3] = 0;
return out;
};
/**
* Creates a new vec4 initialized with values from an existing vector
*
* @param {vec4} a vector to clone
* @returns {vec4} a new 4D vector
*/
vec4.clone = function(a) {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Creates a new vec4 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} a new 4D vector
*/
vec4.fromValues = function(x, y, z, w) {
var out = new glMatrix.ARRAY_TYPE(4);
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
};
/**
* Copy the values from one vec4 to another
*
* @param {vec4} out the receiving vector
* @param {vec4} a the source vector
* @returns {vec4} out
*/
vec4.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
};
/**
* Set the html of a vec4 to the given values
*
* @param {vec4} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @param {Number} w W component
* @returns {vec4} out
*/
vec4.set = function(out, x, y, z, w) {
out[0] = x;
out[1] = y;
out[2] = z;
out[3] = w;
return out;
};
/**
* Adds two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
out[3] = a[3] + b[3];
return out;
};
/**
* Subtracts vector b from vector a
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
out[3] = a[3] - b[3];
return out;
};
/**
* Alias for {@link vec4.subtract}
* @function
*/
vec4.sub = vec4.subtract;
/**
* Multiplies two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
out[3] = a[3] * b[3];
return out;
};
/**
* Alias for {@link vec4.multiply}
* @function
*/
vec4.mul = vec4.multiply;
/**
* Divides two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
out[3] = a[3] / b[3];
return out;
};
/**
* Alias for {@link vec4.divide}
* @function
*/
vec4.div = vec4.divide;
/**
* Math.ceil the html of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to ceil
* @returns {vec4} out
*/
vec4.ceil = function (out, a) {
out[0] = Math.ceil(a[0]);
out[1] = Math.ceil(a[1]);
out[2] = Math.ceil(a[2]);
out[3] = Math.ceil(a[3]);
return out;
};
/**
* Math.floor the html of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to floor
* @returns {vec4} out
*/
vec4.floor = function (out, a) {
out[0] = Math.floor(a[0]);
out[1] = Math.floor(a[1]);
out[2] = Math.floor(a[2]);
out[3] = Math.floor(a[3]);
return out;
};
/**
* Returns the minimum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.min = function(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
out[3] = Math.min(a[3], b[3]);
return out;
};
/**
* Returns the maximum of two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {vec4} out
*/
vec4.max = function(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
out[3] = Math.max(a[3], b[3]);
return out;
};
/**
* Math.round the html of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to round
* @returns {vec4} out
*/
vec4.round = function (out, a) {
out[0] = Math.round(a[0]);
out[1] = Math.round(a[1]);
out[2] = Math.round(a[2]);
out[3] = Math.round(a[3]);
return out;
};
/**
* Scales a vec4 by a scalar number
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec4} out
*/
vec4.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
out[3] = a[3] * b;
return out;
};
/**
* Adds two vec4's after scaling the second operand by a scalar value
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec4} out
*/
vec4.scaleAndAdd = function(out, a, b, scale) {
out[0] = a[0] + (b[0] * scale);
out[1] = a[1] + (b[1] * scale);
out[2] = a[2] + (b[2] * scale);
out[3] = a[3] + (b[3] * scale);
return out;
};
/**
* Calculates the euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} distance between a and b
*/
vec4.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2],
w = b[3] - a[3];
return Math.sqrt(x*x + y*y + z*z + w*w);
};
/**
* Alias for {@link vec4.distance}
* @function
*/
vec4.dist = vec4.distance;
/**
* Calculates the squared euclidian distance between two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} squared distance between a and b
*/
vec4.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2],
w = b[3] - a[3];
return x*x + y*y + z*z + w*w;
};
/**
* Alias for {@link vec4.squaredDistance}
* @function
*/
vec4.sqrDist = vec4.squaredDistance;
/**
* Calculates the length of a vec4
*
* @param {vec4} a vector to calculate length of
* @returns {Number} length of a
*/
vec4.length = function (a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
return Math.sqrt(x*x + y*y + z*z + w*w);
};
/**
* Alias for {@link vec4.length}
* @function
*/
vec4.len = vec4.length;
/**
* Calculates the squared length of a vec4
*
* @param {vec4} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
vec4.squaredLength = function (a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
return x*x + y*y + z*z + w*w;
};
/**
* Alias for {@link vec4.squaredLength}
* @function
*/
vec4.sqrLen = vec4.squaredLength;
/**
* Negates the html of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to negate
* @returns {vec4} out
*/
vec4.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
out[3] = -a[3];
return out;
};
/**
* Returns the inverse of the html of a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to invert
* @returns {vec4} out
*/
vec4.inverse = function(out, a) {
out[0] = 1.0 / a[0];
out[1] = 1.0 / a[1];
out[2] = 1.0 / a[2];
out[3] = 1.0 / a[3];
return out;
};
/**
* Normalize a vec4
*
* @param {vec4} out the receiving vector
* @param {vec4} a vector to normalize
* @returns {vec4} out
*/
vec4.normalize = function(out, a) {
var x = a[0],
y = a[1],
z = a[2],
w = a[3];
var len = x*x + y*y + z*z + w*w;
if (len > 0) {
len = 1 / Math.sqrt(len);
out[0] = x * len;
out[1] = y * len;
out[2] = z * len;
out[3] = w * len;
}
return out;
};
/**
* Calculates the dot product of two vec4's
*
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @returns {Number} dot product of a and b
*/
vec4.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
};
/**
* Performs a linear interpolation between two vec4's
*
* @param {vec4} out the receiving vector
* @param {vec4} a the first operand
* @param {vec4} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec4} out
*/
vec4.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1],
az = a[2],
aw = a[3];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
out[3] = aw + t * (b[3] - aw);
return out;
};
/**
* Generates a random vector with the given scale
*
* @param {vec4} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec4} out
*/
vec4.random = function (out, scale) {
scale = scale || 1.0;
//TODO: This is a pretty awful way of doing this. Find something better.
out[0] = glMatrix.RANDOM();
out[1] = glMatrix.RANDOM();
out[2] = glMatrix.RANDOM();
out[3] = glMatrix.RANDOM();
vec4.normalize(out, out);
vec4.scale(out, out, scale);
return out;
};
/**
* Transforms the vec4 with a mat4.
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec4} out
*/
vec4.transformMat4 = function(out, a, m) {
var x = a[0], y = a[1], z = a[2], w = a[3];
out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
return out;
};
/**
* Transforms the vec4 with a quat
*
* @param {vec4} out the receiving vector
* @param {vec4} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec4} out
*/
vec4.transformQuat = function(out, a, q) {
var x = a[0], y = a[1], z = a[2],
qx = q[0], qy = q[1], qz = q[2], qw = q[3],
// calculate quat * vec
ix = qw * x + qy * z - qz * y,
iy = qw * y + qz * x - qx * z,
iz = qw * z + qx * y - qy * x,
iw = -qx * x - qy * y - qz * z;
// calculate result * inverse quat
out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
out[3] = a[3];
return out;
};
/**
* Perform some operation over an array of vec4s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
vec4.forEach = (function() {
var vec = vec4.create();
return function(a, stride, offset, count, fn, arg) {
var i, l;
if(!stride) {
stride = 4;
}
if(!offset) {
offset = 0;
}
if(count) {
l = Math.min((count * stride) + offset, a.length);
} else {
l = a.length;
}
for(i = offset; i < l; i += stride) {
vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3];
fn(vec, vec, arg);
a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3];
}
return a;
};
})();
/**
* Returns a string representation of a vector
*
* @param {vec4} a vector to represent as a string
* @returns {String} string representation of the vector
*/
vec4.str = function (a) {
return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')';
};
/**
* Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
*
* @param {vec4} a The first vector.
* @param {vec4} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
vec4.exactEquals = function (a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
};
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec4} a The first vector.
* @param {vec4} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
vec4.equals = function (a, b) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
return (Math.abs(a0 - b0) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
Math.abs(a2 - b2) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&
Math.abs(a3 - b3) <= glMatrix.EPSILON*Math.max(1.0, Math.abs(a3), Math.abs(b3)));
};
export default vec4;
|
0f9a297a9a25eac2418166803808f826001fdbfc
|
TypeScript
|
iannmichels/web-avaliacao
|
/src/assets/util/util.ts
| 2.96875
| 3
|
import { FormControl, ValidatorFn } from '@angular/forms';
export class Util {
public static ADMIN: String = 'admin';
public static GUEST: String = 'comum';
public static isUndefined(obj: any): boolean {
if (obj === undefined || obj === null || obj === '' || obj === 'null') {
return true;
} else {
return false;
}
}
public static isEmail(email: string): boolean {
const regexp = new RegExp('/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/');
return !regexp.test(email);
}
public static alphaNumeric(allowedPhrase: string): ValidatorFn {
return (c: FormControl): { [key: string]: boolean } | null => {
if (c.value) {
allowedPhrase = allowedPhrase ? allowedPhrase : '';
let regEx = new RegExp(/^[a-zA-Z0-9]*$/);
if (!regEx.test(c.value.replace(allowedPhrase.toUpperCase(), '').replace(allowedPhrase.toLowerCase(), ''))) {
return { 'alphanumeric': true };
}
}
return null;
};
};
}
|
cb7f6f8acc9c2aec7913711a55e961b55f8f3e54
|
TypeScript
|
kyk85/ADA_Module3_Week04_Geolocation
|
/src/pages/home/home.ts
| 2.546875
| 3
|
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ActionSheetController } from 'ionic-angular'
import { Geolocation } from '@ionic-native/geolocation';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { SocialSharing } from '@ionic-native/social-sharing';
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from '@ionic-native/native-geocoder';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
private geolocation:Geolocation,
public camera:Camera,
public socialSharing:SocialSharing,
public actionSheetCtrl: ActionSheetController,
public nativeGeocoder: NativeGeocoder ) {
}
location
base64Image
message
address
lat
long
getLocation(){
this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
this.lat=resp.coords.latitude
this.long=resp.coords.longitude
this.location=this.lat + ", " + this.long
this.nativeGeocoder.reverseGeocode(this.lat, this.long)
.then((result: NativeGeocoderReverseResult) => this.address=JSON.stringify(result))
.catch((error: any) => console.log(error));
}).catch((error) => {
console.log('Error getting location', error);
});
}
takePicture(){
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
sharePhoto(){
let actionSheet = this.actionSheetCtrl.create({
title: 'How would you like to share your image?',
buttons: [
{
text: 'Facebook',
//role: 'destructive',
handler: () => {
this.facebookShare();
//console.log('Destructive clicked');
}
},
{
text: 'Instagram',
handler: () => {
this.instaShare();
//console.log('Archive clicked');
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
//console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}
facebookShare(){
this.socialSharing.shareViaFacebook("This is awesome", this.base64Image).then(() => {
// Sharing via email is possible
this.message="Uploaded to Facebook"
}).catch(() => {
// Sharing via email is not possible
});
}
instaShare(){
this.socialSharing.shareViaInstagram("This is awesome", this.base64Image).then(() => {
// Sharing via email is possible
this.message="Uploaded to Instagram"
}).catch(() => {
// Sharing via email is not possible
});
}
}
|
b0051839b7af36f928a3c6e64b0fe6ef4db08443
|
TypeScript
|
sunnysk/ant-design-pro-layout
|
/src/utils/utils.ts
| 2.5625
| 3
|
import { useRef, useEffect } from 'react';
import isEqual from 'lodash.isequal';
import { stringify } from 'use-json-comparison';
import hash from 'hash.js';
import { MenuDataItem } from '../typings';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path: string): boolean => reg.test(path);
const isNode =
typeof process !== 'undefined' &&
process.versions != null &&
process.versions.node != null;
export const isBrowser = () =>
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
!isNode;
export function guid() {
return 'xxxxxxxx'.replace(/[xy]/g, c => {
// eslint-disable-next-line no-bitwise
const r = (Math.random() * 16) | 0;
// eslint-disable-next-line no-bitwise
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
export const getKeyByPath = (item: MenuDataItem) => {
const { path, name } = item;
if (path && path !== '/') {
return path;
}
// 如果有name, 使用name
if (name) {
return name;
}
// 如果还是没有,用对象的hash 生成一个
try {
return hash
.sha256()
.update(stringify(item))
.digest('hex');
} catch (error) {
// dom some thing
}
// 要是还是不行,返回一个随机值
return guid();
};
export const getOpenKeysFromMenuData = (menuData?: MenuDataItem[]) => {
if (!menuData) {
return undefined;
}
return menuData.reduce((pre, item) => {
if (item.key) {
pre.push(item.key);
}
if (item.children) {
const newArray: string[] = pre.concat(
getOpenKeysFromMenuData(item.children) || [],
);
return newArray;
}
return pre;
}, [] as string[]);
};
function deepCompareEquals(a: any, b: any) {
return isEqual(a, b);
}
function useDeepCompareMemoize(value: any) {
const ref = useRef();
// it can be done by using useMemo as well
// but useRef is rather cleaner and easier
if (!deepCompareEquals(value, ref.current)) {
ref.current = value;
}
return ref.current;
}
export function useDeepCompareEffect(
effect: React.EffectCallback,
dependencies?: Object,
) {
useEffect(effect, useDeepCompareMemoize(dependencies));
}
const themeConfig = {
daybreak: 'daybreak',
'#1890ff': 'daybreak',
'#F5222D': 'dust',
'#FA541C': 'volcano',
'#FAAD14': 'sunset',
'#13C2C2': 'cyan',
'#52C41A': 'green',
'#2F54EB': 'geekblue',
'#722ED1': 'purple',
};
export function genThemeToString(val?: string): string {
return val ? themeConfig[val] : undefined;
}
export const usePrevious = <T>(state: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = state;
});
return ref.current;
};
|
d401ff51c2fbc110b535d7ec7bf8a763b36d2a80
|
TypeScript
|
Tsophen/Web-Application
|
/src/fetches/loadEncryptionKey.ts
| 3.03125
| 3
|
/**
* Loads an Encryption Key from the given Storage instance
*
* @returns Encryption Key
*/
const loadEncryptionKey = (storage: Storage): Promise<string> => {
return new Promise((resolve, reject) => {
let encryptionKey = storage.getItem("ek");
if(!encryptionKey || encryptionKey === null)
return reject();
return resolve(encryptionKey);
});
}
export default loadEncryptionKey;
|
3cc95acb452dddd148ed5dd4f01a2b341583a32a
|
TypeScript
|
aws/jsii
|
/packages/jsii-pacmak/test/targets/python/type-name.test.ts
| 2.609375
| 3
|
import {
Assembly,
CollectionKind,
NamedTypeReference,
PrimitiveType,
SchemaVersion,
Type,
TypeKind,
TypeReference,
} from '@jsii/spec';
import {
toTypeName,
NamingContext,
PythonImports,
} from '../../../lib/targets/python/type-name';
const BORING_TYPE = 'BoringClass';
const NESTED_TYPE = 'NestedType';
const SUBMODULE_TYPE = 'SubmoduleType';
const SUBMODULE_NESTED_TYPE = 'SubmoduleNested';
const OTHER_SUBMODULE_TYPE = 'OtherType';
const LOCAL_MODULE = 'local_module_name';
const REMOTE_MODULE = 'remote_module_name';
const assembly: Assembly = {
schema: SchemaVersion.LATEST,
name: '@foo/bar',
version: '1.2.3',
dependencyClosure: {
'@remote/classes': {
submodules: {
'@remote/classes.nested': {
targets: { python: { module: `${REMOTE_MODULE}.submodule` } },
},
},
targets: { python: { module: REMOTE_MODULE } },
},
},
targets: { python: { module: LOCAL_MODULE } },
types: {
[`@foo/bar.${BORING_TYPE}`]: {
fqn: `@foo/bar.${BORING_TYPE}`,
},
[`@foo/bar.${BORING_TYPE}.${NESTED_TYPE}`]: {
fqn: `@foo/bar.${BORING_TYPE}.${NESTED_TYPE}`,
namespace: BORING_TYPE,
},
[`@foo/bar.submodule.${SUBMODULE_TYPE}`]: {
fqn: `@foo/bar.submodule.${SUBMODULE_TYPE}`,
namespace: 'submodule',
},
[`@foo/bar.submodule.${SUBMODULE_TYPE}.${SUBMODULE_NESTED_TYPE}`]: {
fqn: `@foo/bar.submodule.${SUBMODULE_TYPE}.${SUBMODULE_NESTED_TYPE}`,
namespace: `submodule.${SUBMODULE_TYPE}`,
},
[`@foo/bar.other.${OTHER_SUBMODULE_TYPE}`]: {
fqn: `@foo/bar.other.${OTHER_SUBMODULE_TYPE}`,
namespace: 'other',
},
[`@foo/bar.Struct`]: {
datatype: true,
fqn: `@foo/bar.Struct`,
kind: TypeKind.Interface,
},
},
} as any;
describe(toTypeName, () => {
type Example = {
/** The name of the example */
readonly name: string;
/** The TypeReference to pass in to toTypeName */
readonly input: TypeReference | undefined;
/** The expected python name of the type */
readonly pythonType: string;
/** If different from pythonType, the forward declaration to use for the type */
readonly forwardPythonType?: string;
/** The optional version of the type's name (if not provided, typing.Optional[<pythonType>]) */
readonly optionalPythonType?: string;
/** The required imports for this python type (if not provided, none) */
readonly requiredImports?: PythonImports;
/** The submodule from which to generate names (if not provided, the root submodule) */
readonly inSubmodule?: string;
/** The nesting context in which to generate names (if not provided, none) */
readonly inNestingContext?: readonly string[];
/** Additional context keys to register */
readonly context?: Omit<
NamingContext,
| 'assembly'
| 'emittedTypes'
| 'surroundingTypeFqns'
| 'submodule'
| 'typeResolver'
>;
};
const examples: readonly Example[] = [
// ################################## NONE #################################
{
name: 'None',
input: undefined,
pythonType: 'None',
},
// ############################ PRIMITIVE TYPES ############################
{
name: 'Primitive: Boolean',
input: { primitive: PrimitiveType.Boolean },
pythonType: 'builtins.bool',
},
{
name: 'Primitive: Date',
input: { primitive: PrimitiveType.Date },
pythonType: 'datetime.datetime',
},
{
name: 'Primitive: Number',
input: { primitive: PrimitiveType.Number },
pythonType: 'jsii.Number',
},
{
name: 'Primitive: String',
input: { primitive: PrimitiveType.String },
pythonType: 'builtins.str',
},
{
name: 'Primitive: JSON',
input: { primitive: PrimitiveType.Json },
pythonType: 'typing.Mapping[typing.Any, typing.Any]',
},
{
name: 'Primitive: Any',
input: { primitive: PrimitiveType.Any },
pythonType: 'typing.Any',
optionalPythonType: 'typing.Any',
},
// ############################## COLLECTIONS ##############################
{
name: 'Array',
input: {
collection: {
kind: CollectionKind.Array,
elementtype: { primitive: PrimitiveType.String },
},
},
pythonType: 'typing.List[builtins.str]',
},
{
name: 'Map',
input: {
collection: {
kind: CollectionKind.Map,
elementtype: { primitive: PrimitiveType.String },
},
},
pythonType: 'typing.Mapping[builtins.str, builtins.str]',
},
// ############################## TYPE UNIONS ##############################
{
name: 'Union',
input: {
union: {
types: [
{ primitive: PrimitiveType.String },
{ primitive: PrimitiveType.Number },
],
},
},
pythonType: 'typing.Union[builtins.str, jsii.Number]',
},
// ############################### USER TYPES ##############################
{
name: 'User Type (Foreign)',
input: { fqn: '@remote/classes.FancyClass' },
pythonType: `_remote_module_name_fb17b8fa.FancyClass`,
requiredImports: {
[`${REMOTE_MODULE} as _remote_module_name_fb17b8fa`]: new Set(['']),
},
},
{
name: 'User Type (Foreign, Submodule)',
input: { fqn: '@remote/classes.nested.SubmoduledType' },
pythonType: `_remote_module_name_submodule_fb17b8fa.SubmoduledType`,
requiredImports: {
[`${REMOTE_MODULE}.submodule as _remote_module_name_submodule_fb17b8fa`]:
new Set(['']),
},
},
{
name: 'User Type (Local)',
input: { fqn: `${assembly.name}.BoringClass` },
pythonType: 'BoringClass',
forwardPythonType: '"BoringClass"',
},
{
name: 'User Type (Local, Nested)',
input: { fqn: `${assembly.name}.${BORING_TYPE}.${NESTED_TYPE}` },
pythonType: 'BoringClass.NestedType',
forwardPythonType: '"BoringClass.NestedType"',
},
{
name: 'User Type (Local, Submodule)',
input: { fqn: `${assembly.name}.submodule.${SUBMODULE_TYPE}` },
pythonType: `_${SUBMODULE_TYPE}_72dbc9ef`,
requiredImports: {
'.submodule': new Set([
`${SUBMODULE_TYPE} as _${SUBMODULE_TYPE}_72dbc9ef`,
]),
},
},
{
name: 'User Type (Local, Submodule, Nested)',
input: {
fqn: `${assembly.name}.submodule.${SUBMODULE_TYPE}.${SUBMODULE_NESTED_TYPE}`,
},
pythonType: `_${SUBMODULE_TYPE}_72dbc9ef.${SUBMODULE_NESTED_TYPE}`,
requiredImports: {
'.submodule': new Set([
`${SUBMODULE_TYPE} as _${SUBMODULE_TYPE}_72dbc9ef`,
]),
},
},
{
name: 'User Type (Locally Nested)',
input: {
fqn: `${assembly.name}.submodule.${SUBMODULE_TYPE}.${SUBMODULE_NESTED_TYPE}`,
},
// Always a forward reference, since the surrounding type isn't *defined* just yet!
pythonType: `"${SUBMODULE_TYPE}.${SUBMODULE_NESTED_TYPE}"`,
inSubmodule: `${assembly.name}.submodule`,
inNestingContext: [`${assembly.name}.submodule.${SUBMODULE_TYPE}`],
},
{
name: 'User Type (Local, Parent)',
input: { fqn: `${assembly.name}.other.${OTHER_SUBMODULE_TYPE}` },
pythonType: `_${OTHER_SUBMODULE_TYPE}_78b5948e`,
requiredImports: {
'..other': new Set([
`${OTHER_SUBMODULE_TYPE} as _${OTHER_SUBMODULE_TYPE}_78b5948e`,
]),
},
inSubmodule: `${assembly.name}.submodule`,
},
// ############################# SPECIAL CASES##############################
{
name: 'Struct parameter type annotation',
input: { fqn: `${assembly.name}.Struct` },
forwardPythonType: `typing.Union["Struct", typing.Dict[builtins.str, typing.Any]]`,
pythonType: `typing.Union[Struct, typing.Dict[builtins.str, typing.Any]]`,
context: {
typeAnnotation: true,
parameterType: true,
},
},
];
for (const example of examples) {
const context: NamingContext = {
...example.context,
assembly,
emittedTypes: new Set(),
surroundingTypeFqns: example.inNestingContext,
submodule: example.inSubmodule ?? assembly.name,
typeResolver: (fqn) => {
const type = assembly.types?.[fqn];
return type ?? ({ fqn } as any as Type);
},
};
const contextWithEmittedType: NamingContext = {
...context,
emittedTypes: new Set(
[
// Sneak through to get the type's FQN, but be null-safe, etc... then filter.
(example.input as NamedTypeReference | undefined)?.fqn as string,
].filter((v) => !!v),
),
};
describe(example.name, () => {
const typeName = toTypeName(example.input);
test('typeName.pythonType(context)', () => {
expect(typeName.pythonType(context)).toBe(
example.forwardPythonType ?? example.pythonType,
);
expect(typeName.pythonType(contextWithEmittedType)).toBe(
example.pythonType,
);
});
test('typeName.requiredImports(context)', () => {
expect(typeName.requiredImports(context)).toEqual(
example.requiredImports ?? {},
);
});
});
// None + Optional is meaningless!
if (example.input == null) {
continue;
}
describe(`${example.name} + Optional`, () => {
const typeName = toTypeName({ type: example.input!, optional: true });
test('typeName.pythonType(context)', () => {
expect(typeName.pythonType(context)).toBe(
example.optionalPythonType ??
`typing.Optional[${
example.forwardPythonType ?? example.pythonType
}]`,
);
expect(typeName.pythonType(contextWithEmittedType)).toBe(
example.optionalPythonType ??
`typing.Optional[${example.pythonType}]`,
);
});
test('typeName.requiredImports(context)', () => {
expect(typeName.requiredImports(context)).toEqual(
example.requiredImports ?? {},
);
});
});
}
});
|
525a8a573c183a22f8a537ebb7c7d4c3cb01f14e
|
TypeScript
|
pokewalkthrough/pokeapi
|
/src/interfaces/utility/common/version-game-index.ts
| 2.546875
| 3
|
import { INamedAPIResource } from './named-api-resource';
export interface IVersionGameIndex {
/**
* The internal id of an API resource within game data.
*/
game_index: number;
/**
* The version relevent to this game index.
*/
version: INamedAPIResource;
}
|
fec0627e33c3d23611a7d79a7e4ab29eb7e542c8
|
TypeScript
|
software-training-for-students/manual-editor
|
/core/importManualHtml.ts
| 2.546875
| 3
|
import ElementInfo, * as ElementTypes from "core/ElementInfo";
import { ContentState, convertFromHTML, convertToRaw } from "draft-js";
import {decode} from "he";
import {addElements, Document} from "stores/Document";
// These are used for images in the old manual style.
const legacyImagesFolder = "images/";
const legacyKeyboardIconsFolder = "keyboard-icons/";
function extractElements(parentElement: Element): ElementInfo[] {
let encounteredIntro = !(parentElement instanceof HTMLBodyElement);
let items: ElementInfo[] = [];
for (let i = 0; i < parentElement.childNodes.length; ++i) {
let currentElement = parentElement.childNodes.item(i);
if (!encounteredIntro) {
if (currentElement.textContent === "Introduction") {
encounteredIntro = true;
}
continue;
}
if (currentElement.nodeType === Node.ELEMENT_NODE) {
items = items.concat(convertCurrentElement(<Element> currentElement));
}
if (currentElement.nodeType === Node.TEXT_NODE && currentElement.textContent && currentElement.textContent.trim().length) {
let parsedHtml = convertFromHTML(currentElement.textContent);
items.push({
elementState: {
value: convertToRaw(ContentState.createFromBlockArray(parsedHtml.contentBlocks, parsedHtml.entityMap)),
},
elementType: "RichText",
});
}
}
return items;
}
function convertCurrentElement(currentElement: Element): ElementInfo[] {
switch (currentElement.tagName.toLowerCase()) {
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return [
{
elementState: {
level: <ElementTypes.Heading["level"]> parseInt(currentElement.tagName[1], 10),
value: (<HTMLElement> currentElement).innerText,
},
elementType: "Heading",
},
];
case "ul":
return generateMetaItem("UnorderedList", currentElement);
case "li":
{
return extractElements(currentElement).map((element) => {
if (element.elementType === "RichText") {
element = {
elementType : "ListItem",
elementState : element.elementState,
};
}
return element;
});
}
case "ol":
{
let elementType: ElementTypes.MetaElementType = currentElement.classList.contains("instruction-list") ? "InstructionList" : "OrderedList";
return generateMetaItem(elementType, currentElement);
}
case "p":
{
let parsedHtml = convertFromHTML(currentElement.outerHTML);
let content = ContentState.createFromBlockArray(parsedHtml.contentBlocks, parsedHtml.entityMap);
return [
{
elementState: {
value: convertToRaw(content),
},
elementType: "RichText",
},
];
}
case "pre":
return [
generateCodeItem(<HTMLPreElement>currentElement),
];
case "div":
return [
generateDivItem(<HTMLDivElement> currentElement),
];
case "img":
return [
generateImageItem(<HTMLImageElement> currentElement),
];
case "br":
return [];
case "table":
return generateMetaItem("Table", currentElement);
case "tbody":
return extractElements(currentElement);
case "tr":
return generateMetaItem("TableRow", currentElement);
case "th":
return generateMetaItem("TableHeader", currentElement);
case "td":
return generateMetaItem("TableCell", currentElement);
default:
console.warn(`Unsupported Tag ${currentElement.tagName}. Imported into a Raw HTML element.`);
return [
{
elementState: {
value: currentElement.outerHTML,
},
elementType: "RawHtml",
},
];
}
}
function generateMetaItem(elementType: ElementTypes.MetaElementType, currentElement: Element) {
let listElements: ElementInfo[] = [
{
elementType,
metaItemType: "open",
},
{
elementType,
metaItemType: "close",
},
];
Array.prototype.splice.apply(listElements, (<any[]> [1, 0]).concat(extractElements(currentElement)));
return listElements;
}
function generateCodeItem(element: HTMLPreElement): ElementInfo {
let codeLanguage: string = "";
let head = element.ownerDocument.head;
for (let j = 0; j < head.children.length; ++j) {
let headElement = head.children.item(j);
if (headElement.tagName.toLowerCase() === "script") {
let scriptTag = <HTMLScriptElement> headElement;
let found = scriptTag.src.match(/([A-Za-z-]+)-highlight.js/);
if (found) {
codeLanguage = found[1];
break;
}
}
}
return {
elementState: {
language: codeLanguage,
value: decode(element.children[0].innerHTML),
},
elementType: "Code",
};
}
function generateImageItem(element: HTMLDivElement | HTMLImageElement): ElementInfo {
let classList = element.classList;
const border = element.getAttribute("border") !== null || classList.contains("border");
const captionElement = element.querySelector("p");
const caption = captionElement ? captionElement.innerText : "";
let className: string;
for (let i = 0; i < classList.length; ++i) {
if (classList.item(i).includes("image") || classList.item(i) === "sidebar-icon") {
className = classList.item(i);
if (className.includes("sidebyside")) {
let leftSource = importImagePath(element.querySelectorAll("img")[0].getAttribute("src")!);
let rightSource = importImagePath(element.querySelectorAll("img")[1].getAttribute("src")!);
return {
elementState: {
value: {
border,
caption,
leftSource,
rightSource,
className: <ElementTypes.SideBySideImageClassName> className,
},
},
elementType: "SideBySideImage",
};
} else {
let imgElement = element instanceof HTMLImageElement ? element : element.querySelector("img")!;
let source = importImagePath(imgElement.getAttribute("src")!);
return {
elementState: {
value: {
border,
caption,
source,
className: <ElementTypes.SingleImageClassName> className,
},
},
elementType: "SingleImage",
};
}
}
}
throw new Error("Impossible error: Class-list does not contain an image class, but the className attribute does.");
}
function generateDivItem(element: HTMLDivElement): ElementInfo {
const classList = element.classList;
const classes = element.className;
if (classes.includes("image") || classes.includes("sidebar-icon")) {
return generateImageItem(element);
} else if (classList.contains("sidebar-note")) {
return generateSidebarNote(element);
} else if (classList.contains("toolbox")) {
return generateToolbox(element);
} else if (classList.contains("keyboard-shortcut")) {
return createKeyboardShortcut(element);
} else {
console.warn(`Unsupported div classes: ${classes}. Imported into a Raw HTML element`);
return {
elementState: {
value: element.outerHTML,
},
elementType: "RawHtml",
};
}
}
function createKeyboardShortcut(element: HTMLDivElement): ElementInfo {
const titleElement = element.querySelector("h2");
const title = titleElement ? titleElement.innerText : "";
const parsedHtml = convertFromHTML(element.querySelector("p")!.outerHTML);
const content = convertToRaw(ContentState.createFromBlockArray(parsedHtml.contentBlocks, parsedHtml.entityMap));
const labels = element.querySelectorAll("h3");
switch (labels.length) {
case 0:
case 1:
{
let keyImages = element.getElementsByTagName("img");
let keys: string[] = [];
for (let i = 0; i < keyImages.length; ++i) {
let image = keyImages.item(i);
let regexMatch = image.getAttribute("src")!.match(/icon-([a-z0-9]+).svg/i)!;
keys.push(regexMatch[1]);
}
return {
elementState: {
value: {
title,
content,
shortcuts: <ElementTypes.Keys[][]> [keys],
type: keys.length ? "shortcut" : "no-shortcut",
},
},
elementType: "KeyboardShortcut",
};
}
default:
console.warn("Unsupported number of labels. Only importing first 2 shortcuts");
case 2:
let firstLabel = labels.item(0);
let secondLabel = labels.item(1);
let firstKeys: string[] = [];
for (let image = firstLabel.nextElementSibling; image !== secondLabel; image = image!.nextElementSibling) {
let regexMatch = image!.getAttribute("src")!.match(/icon-([a-z0-9]+).svg/i)!;
firstKeys.push(regexMatch[1]);
}
let secondKeys: string[] = [];
for (let image = secondLabel.nextElementSibling; image && image !== labels.item(2); image = image.nextElementSibling) {
let regexMatch = image.getAttribute("src")!.match(/icon-([a-z0-9]+).svg/i)!;
secondKeys.push(regexMatch[1]);
}
return {
elementState: {
value: {
title,
content,
shortcuts: <ElementTypes.Keys[][]> [firstKeys, secondKeys],
type: "multi-shortcut",
},
},
elementType: "KeyboardShortcut",
};
}
}
function generateSidebarNote(element: HTMLDivElement): ElementInfo {
const titleElement = element.querySelector("h2");
const title = titleElement ? titleElement.innerText : "";
const parsedHtml = convertFromHTML(element.querySelector("p") !.outerHTML);
const content = convertToRaw(ContentState.createFromBlockArray(parsedHtml.contentBlocks, parsedHtml.entityMap));
const imageElement = element.querySelector("img");
const imgSource = imageElement ? imageElement.src : "";
return {
elementState: {
value: {
title,
content,
imgSource,
},
},
elementType: "SidebarNote",
};
}
function generateToolbox(element: HTMLDivElement): ElementInfo {
let items = [];
let children = extractToolboxChildren(element);
for (let item of children) {
let image = item.querySelector("img");
let imgSrc = image !== null ? importImagePath(image.getAttribute("src") !) : "";
let content = item.querySelector("p") !;
let name = content.querySelector("b") !.innerText;
content.removeChild(content.querySelector("b") !);
let description = content.innerText;
items.push({
imgSrc,
name,
description,
});
}
return {
elementState: {
value: items,
},
elementType: "Toolbox",
};
}
function extractToolboxChildren(toolbox: HTMLDivElement) {
let children = [];
let currentChild = document.createElement("div");
for (let i = 0; i < toolbox.children.length; i++) {
let element = toolbox.children.item(i);
if (element instanceof HTMLDivElement) {
currentChild = document.createElement("div");
children.push(element);
} else {
currentChild.appendChild(element.cloneNode(true));
if (element instanceof HTMLParagraphElement) {
children.push(currentChild);
currentChild = document.createElement("div");
}
}
}
return children;
}
function importImagePath(imagePath: string) {
if (imagePath.startsWith(legacyImagesFolder)) {
return imagePath.substr(legacyImagesFolder.length).toLowerCase();
}
if (imagePath.startsWith(legacyKeyboardIconsFolder)) {
return imagePath.substr(legacyKeyboardIconsFolder.length).toLowerCase();
}
return imagePath;
}
export default function importManualHtml(html: string): Document {
let parser = new DOMParser();
let oldManual = parser.parseFromString(html, "text/html");
let newManual: Document = {
1: {
editing: false,
itemId: 1,
level: 1,
value: oldManual.querySelector("#coverpage-title h1")!.textContent!,
},
2: {
editing: false,
itemId: 2,
level: 2,
value: oldManual.querySelector("#coverpage-title h2")!.textContent!,
},
3: {
editing: false,
itemId: 3,
level: 1,
value: "Introduction",
},
elementOrdering: [
{itemId: 3, elementType: "Heading"},
],
nextItemId: 4,
};
addElements(newManual, extractElements(oldManual.body), true);
return newManual;
}
|
98e4d41334e4c7597312fe0de867ba2a85900afd
|
TypeScript
|
Dharini9/store-multiple-libraries
|
/src/app/store-ngrx/app.state.ts
| 2.828125
| 3
|
export interface CandidateDetailsState {
candidateID: number;
candidateName: string;
}
export interface ClientDetailsState {
clientID: number;
clientName: string;
}
export const initialcandidateDetailsState: CandidateDetailsState = {
candidateID: 0,
candidateName: ''
};
export const initialClientDetailsState: ClientDetailsState = {
clientID: 0,
clientName: ''
};
export interface AppState {
candidateDetails: CandidateDetailsState;
clientDetails: ClientDetailsState;
}
export const initialAppState: AppState = {
candidateDetails: initialcandidateDetailsState,
clientDetails: initialClientDetailsState
};
export function getInitialAppState() {
return initialAppState;
}
|