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 |
|---|---|---|---|---|---|---|
58a5e21a07dcb804c8011a91bd20f2f0e85dc8d0 | TypeScript | jobayersarkar/ivr-tester | /packages/ivr-tester/src/call/transcription/PromptTranscriptionBuilder.ts | 2.953125 | 3 | import { TranscriptEvent } from "./plugin/TranscriberPlugin";
export class PromptTranscriptionBuilder {
private static readonly EMPTY_TRANSCRIPTION = "";
private transcriptions: TranscriptEvent[] = [];
public add(event: TranscriptEvent): void {
this.transcriptions.push(event);
}
public clear(): void {
this.transcriptions = [];
}
public merge(): string {
if (this.transcriptions.length === 0) {
return PromptTranscriptionBuilder.EMPTY_TRANSCRIPTION;
}
// If all transcripts partial then return last partial
const areAllPartial = this.transcriptions.every((t) => t.isFinal === false);
if (areAllPartial) {
const lastPartial = this.transcriptions[this.transcriptions.length - 1];
return lastPartial.transcription;
}
// Return finals
const areAllFinals = this.transcriptions.every((t) => t.isFinal);
if (areAllFinals) {
return this.transcriptions.map((t) => t.transcription).join(" ");
}
// Return Merged finals and last partial
const lastTranscription = this.transcriptions[
this.transcriptions.length - 1
];
const mergedFinals = this.transcriptions
.filter((t) => t.isFinal)
.map((t) => t.transcription)
.join(" ");
if (lastTranscription.isFinal) {
return mergedFinals;
} else {
return `${mergedFinals} ${lastTranscription.transcription}`;
}
}
}
|
d74ad17f0ee971ee7800446074694f38c5d9dd2f | TypeScript | mauricio-alves/curso_typescript | /src/005-type-array/005-type-array.ts | 4.1875 | 4 | // Há duas maneiras criar um array:
// Array<T> ou T[]
// forma Array<T> (tipos):
export function multiplicaArgs(...args: Array<number>): number {
return args.reduce((ac, valor) => ac * valor, 1);
}
const result = multiplicaArgs(1, 2, 3);
console.log(result);
// forma T[] (string):
export function concatenaArgs(...args: string[]): string {
return args.reduce((ac, valor) => ac + valor);
}
const concatenacao = concatenaArgs('a', 'b', 'c');
console.log(concatenacao);
// ou também (string):
export function toUpperCase(...args: string[]): string[] {
return args.map((valor) => valor.toUpperCase());
}
const upper = toUpperCase('a', 'b', 'c');
console.log(upper);
|
4eb982688ec7fdce9e80f814e643b41ca03a4185 | TypeScript | nadipalli-swetha/news-application | /newsApplicationF/src/app/services/news.service.ts | 2.75 | 3 | import { Injectable } from '@angular/core';
import { HttpClient,HttpParams, HttpResponse} from "@angular/common/http";
import { News} from "../models/News";
import { NewsFetcher} from "../interfaces/news-fetcher";
import { throwError} from "rxjs";
import {catchError,retry} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class NewsService implements NewsFetcher {
constructor(private httpClient: HttpClient) {}
/*
Retrieves general news.
*/
getGeneralNews(location, pageSize) {
return this.httpClient.get("/guardianNews/news",
{
params: new HttpParams().set("production-office", location).set("page-size", pageSize),
observe: 'response',// to get the full response; not just the body (JSON).
reportProgress: true
})
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleHttpErrors) // then handle the error.
);
}
/*
Retrieves articles about politics.
*/
getPoliticsArticles(location, pageSize) {
return this.httpClient.get("/guardianNews/politics", {
params: new HttpParams().set("production-office", location).set("page-size", pageSize),
observe: 'response',
reportProgress: true
})
.pipe(
retry(3),
catchError(this.handleHttpErrors)
);
}
/*
Retrieves articles about sports.
*/
getSportsArticles(location, pageSize) {
return this.httpClient.get<News[]>("/guardianNews/sports",
{
params: new HttpParams().set("production-office", location).set("page-size",pageSize),
observe: 'response',
reportProgress: true
})
.pipe(
retry(3),
catchError(this.handleHttpErrors)
);
}
/*
Retrieves articles about the environment.
*/
getEnvironmentalArticles(location, pageSize) {
}
/**
* Function to handle HttpResponse errors.
* @param error
*/
private handleHttpErrors(error: HttpResponse<News[]>) {
if (error instanceof ErrorEvent) {
// client side error.
console.error('An error occurred.' + error.error.message);
} else {
// backend side error.
console.error(`Backend returned code ${error.status}, ` + `body was: ${error.body}`);
}
/*
Notice that this handler returns an RxJS ErrorObservable with a user-friendly error message.
Consumers of the service expect service methods to return an Observable of some kind, even a "bad" one.
*/
return throwError('Something went wrong, try again later?');
};
}
|
47e65f194cbaed8ec43a3b22def7b7dbdb36b172 | TypeScript | Quindon/pokeclicker | /src/scripts/dungeons/DungeonBattle.ts | 2.640625 | 3 | class DungeonBattle extends Battle {
/**
* Award the player with money and exp, and throw a Pokéball if applicable
*/
public static defeatPokemon() {
DungeonRunner.fighting(false);
player.gainMoney(this.enemyPokemon().money);
player.gainExp(this.enemyPokemon().exp, this.enemyPokemon().level, false);
player.gainShards(this.enemyPokemon());
player.addRouteKill();
BreedingHelper.progressEggs(Math.floor(Math.sqrt(DungeonRunner.dungeon.itemRoute)));
DungeonRunner.map.currentTile().type(GameConstants.DungeonTile.empty);
DungeonRunner.map.currentTile().calculateCssClass();
let alreadyCaught: boolean = player.alreadyCaughtPokemon(this.enemyPokemon().name);
let pokeBall: GameConstants.Pokeball = player.calculatePokeballToUse(alreadyCaught);
if (pokeBall !== GameConstants.Pokeball.None) {
this.prepareCatch(pokeBall);
setTimeout(
() => {
this.attemptCatch();
if (DungeonRunner.fightingBoss()) {
DungeonRunner.fightingBoss(false);
DungeonRunner.dungeonWon();
}
},
player.calculateCatchTime(pokeBall)
);
} else if (DungeonRunner.fightingBoss()) {
DungeonRunner.fightingBoss(false);
DungeonRunner.dungeonWon();
}
}
public static generateNewEnemy() {
DungeonRunner.fighting(true);
this.catching(false);
this.counter = 0;
this.enemyPokemon(PokemonFactory.generateDungeonPokemon(DungeonRunner.dungeon.pokemonList, DungeonRunner.chestsOpened, DungeonRunner.dungeon.baseHealth, DungeonRunner.dungeon.level));
}
public static generateNewBoss() {
DungeonRunner.fighting(true);
this.catching(false);
this.counter = 0;
this.enemyPokemon(PokemonFactory.generateDungeonBoss(DungeonRunner.dungeon.bossList, DungeonRunner.chestsOpened));
}
} |
069622dc1051de6e4a6bd7e431bf555db522c8a3 | TypeScript | microsoft/accessibility-insights-web | /src/common/stores/client-stores-hub.ts | 2.65625 | 3 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { every, lowerFirst } from 'lodash';
import { BaseStore } from '../base-store';
export class ClientStoresHub<T> {
public stores: BaseStore<any, Promise<void>>[];
constructor(stores: BaseStore<any, Promise<void>>[]) {
this.stores = stores;
}
public addChangedListenerToAllStores(listener: () => Promise<void>): void {
if (!this.stores) {
return;
}
this.stores.forEach(store => {
store.addChangedListener(listener);
});
}
public removeChangedListenerFromAllStores(listener: () => Promise<void>): void {
if (!this.stores) {
return;
}
this.stores.forEach(store => {
store.removeChangedListener(listener);
});
}
public hasStores(): boolean {
if (!this.stores) {
return false;
}
return every(this.stores, store => store != null);
}
public hasStoreData(): boolean {
return this.stores.every(store => {
return store != null && store.getState() != null;
});
}
public getAllStoreData(): Partial<T> | null {
if (!this.hasStores()) {
return null;
}
return this.stores.reduce((builtState: Partial<T>, store) => {
const key = `${lowerFirst(store.getId())}Data`;
builtState[key as keyof T] = store.getState();
return builtState;
}, {} as Partial<T>);
}
}
|
9332640e417312a59f936356e2ba19f9be210481 | TypeScript | moses-aronov/angular2-weather-app | /src/weather-widget/pipe/speed-unit.pipe.ts | 2.890625 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: "speedUnit"
})
export class SpeedUnitPipe implements PipeTransform {
transform(speed: number, unitType: string) {
switch (unitType) {
case 'kph':
return this.formatSpeed(this.convertMPHtoKPH(speed)) + unitType
default:
return this.formatSpeed(speed) + unitType
}
}
convertMPHtoKPH(speed){
return speed*1.60934
}
formatSpeed(speed: number){
return parseInt(String(speed), 10)
}
} |
09227a8ef35226e0ef25981043798a4adfc46f27 | TypeScript | godspeed-you/grafana-checkmk-datasource | /src/RequestSpec.ts | 2.703125 | 3 | export interface NegatableOption {
value?: string;
negated: boolean;
}
export type ObjectType = 'host' | 'site' | 'service';
export interface MetricFindQuery {
filter: Partial<FiltersRequestSpec>;
objectType: ObjectType;
}
export interface RequestSpec {
// TODO: we need to rename graph_type, as the graph_type differentiates between graph and metric.
// TODO: we also need to rename graph, as this could contain a metric name.
// my suggestion: entity_type and entity then it should be clear that they influence each other.
graph_type: GraphType;
aggregation: Aggregation;
site: string | undefined;
host_name: string | undefined;
host_name_regex: NegatableOption | undefined;
host_in_group: NegatableOption | undefined;
host_labels: string[] | undefined;
host_tags: [TagValue, TagValue, TagValue] | undefined;
service: string | undefined;
service_regex: NegatableOption | undefined;
service_in_group: NegatableOption | undefined;
graph: string | undefined;
}
// subset of RequestSpec used with the Filters Component
export type FiltersRequestSpec = Pick<
RequestSpec,
| 'site'
| 'host_name'
| 'host_name_regex'
| 'host_in_group'
| 'host_labels'
| 'host_tags'
| 'service'
| 'service_regex'
| 'service_in_group'
>;
export interface TagValue {
group?: string;
tag?: string;
operator?: 'is' | 'isnot';
}
export type GraphType = 'single_metric' | 'predefined_graph';
export type Aggregation = 'off' | 'sum' | 'average' | 'minimum' | 'maximum';
export type PickByValue<T, V> = Pick<T, { [K in keyof T]: T[K] extends V ? K : never }[keyof T]>;
export type RequestSpecStringKeys = keyof PickByValue<RequestSpec, string | undefined>;
export type RequestSpecNegatableOptionKeys = keyof PickByValue<RequestSpec, NegatableOption | undefined>;
export const defaultRequestSpec: Partial<RequestSpec> = {
aggregation: 'off',
graph_type: 'predefined_graph',
};
export type FilterEditorKeys = Exclude<keyof RequestSpec, 'graph_type' | 'aggregation' | 'graph'>;
|
2d381ab189d35a94a902a21822b541639533333e | TypeScript | Wikiviews/wikiviews-frontend | /src/app/main/articles/shared/filter/article-selection/article-range.ts | 3.421875 | 3 | export class ArticleRange {
private _beginning: string;
private _end: string;
constructor(begining: string, end: string) {
if (begining > end) throw new Error("Beginning of range mustn't be lexically bigger than end of range");
this._beginning = begining;
this._end = end;
}
get beginning(): string {
return this._beginning;
}
get end(): string {
return this._end;
}
}
|
c9fe02f6f79df899da0154bb5c8e0a93aef95bd1 | TypeScript | sanket90/Training | /src/app/app.component.spec.ts | 2.84375 | 3 | import { ListStack, LinkedListStack, ArrayStack } from './data-structure/stack';
import { Postfix } from './example/postfix';
import { Prefix } from './example/prefix';
import { AddMessage, DeleteMessage, Action } from './store/message.action';
import { messageReducer } from './store/message.reducer'
import { Store } from './store/message.store';
import { TestBed, async } from '@angular/core/testing';
describe('AppComponent', () => {
// Data Structure tests
it('should check array stack', async(() => {
let stack = new ArrayStack<string>()
stack.push("abc")
expect(stack.peek()).toBe("abc")
expect(stack.pop()).toBe("abc")
expect(stack.isEmpty()).toBe(true)
}))
it('should check linked list stack', async(() => {
let stack = new LinkedListStack<string>()
stack.push("abc")
expect(stack.peek()).toBe("abc")
expect(stack.pop()).toBe("abc")
expect(stack.isEmpty()).toBe(true)
}))
it('should check list stack', async(() => {
let stack = new ListStack<string>()
stack.push("abc")
expect(stack.peek()).toBe("abc")
expect(stack.pop()).toBe("abc")
expect(stack.isEmpty()).toBe(true)
}))
it('should check infix to postfix', async(() => {
expect((new Postfix()).fromInfix("a+b")).toBe("ab+")
expect((new Postfix()).fromInfix("a+b*c+d")).toBe("abc*+d+")
expect((new Postfix()).fromInfix("(a+b)/(c*d)-(e+f)")).toBe("ab+cd*/ef+-")
expect((new Postfix()).fromInfix("(c+d)-(a*b)/(a+c)")).toBe("cd+ab*ac+/-")
}))
it('should check infix to prefix', async(() => {
expect((new Prefix()).fromInfix("a+b")).toBe("+ab")
expect((new Prefix()).fromInfix("a+b*c+d")).toBe("+a+*bcd")
expect((new Prefix()).fromInfix("(a+b)/(c*d)-(e+f)")).toBe("-/+ab*cd+ef")
expect((new Prefix()).fromInfix("(c+d)-(a*b)/(a+c)")).toBe("-+cd/*ab+ac")
}))
// Reduc pattern tests
it('should check type defination of actions', async(() => {
let addAction = new AddMessage("new message")
expect(addAction.type).toBe("ADD")
expect(addAction.payload).toBe("new message")
let deleteAction = new DeleteMessage(1)
expect(deleteAction.type).toBe("DELETE")
expect(deleteAction.payload).toBe(1)
}))
it('should check reducer with action Add Message', async(() => {
expect(messageReducer([], new AddMessage("New message"))).toEqual(["New message"])
}))
it('should check reducer with action Delete Message', async(() => {
expect(messageReducer(["message 0", "message 1", "message 2", "message 3"], new DeleteMessage(2)))
.toEqual(["message 0", "message 1", "message 3"])
}))
it('should check Store', async(() => {
let store = new Store([], messageReducer)
expect(store.getState()).toEqual([])
store.dispatch(new AddMessage("message 0"))
store.dispatch(new AddMessage("message 1"))
store.dispatch(new AddMessage("message 2"))
store.dispatch(new AddMessage("message 3"))
expect(store.getState()).toEqual(["message 0", "message 1", "message 2", "message 3"])
store.dispatch(new DeleteMessage(2))
expect(store.getState()).toEqual(["message 0", "message 1", "message 3"])
store.dispatch({type:"WRONG TYPE"})
expect(store.getState()).toEqual(["message 0", "message 1", "message 3"])
}))
}); |
f75c83102fbdf577e946253790be9f362a18042f | TypeScript | Yowza-Animation/tba-types | /StoryboardPro/6/index.d.ts | 2.859375 | 3 | /// <reference path="../../shared/qtscript.d.ts" />
/// <reference path="../../shared/tba.d.ts" />
/// <reference path="../../shared/15/index.d.ts" />
/**
* Action interface is used to perform menu or tool bar functions
*/
declare namespace Action {
/**
* using action manager, perform the requested action (slot - menu item, toolbar item,...)
*/
function perform(slot: string): void;
/**
* using action manager, perform the requested action (slot - menu item, toolbar item,...)
*/
function perform(slot: string, responder: string): void;
}
/**
* This interface is used to access caption properties. Note that the text in captions is in html format
*/
declare class CaptionManager extends QObject {
/**
* returns number of panel captions
*/
public numberOfPanelCaptions(): int;
/**
* returns name of the panel caption at index
*/
public nameOfPanelCaption(index: int): string;
/**
* returns text of the panel caption
*/
public textOfPanelCaption(name: string, panelId: string): string;
/**
* adds a panel caption
*/
public addPanelCaption(name: string): boolean;
/**
* adds a panel sketch
*/
public addPanelSketch(name: string, panelId: string): boolean;
/**
* deletes a panel caption
*/
public deletePanelCaption(name: string): boolean;
/**
* deletes a panel sketch
*/
public deletePanelSketch(name: string, panelId: string): boolean;
/**
* renames a panel caption
*/
public renamePanelCaption(name: string, newName: string): boolean;
/**
* renames a panel sketch
*/
public renamePanelSketch(name: string, panelId: string, newName: string): boolean;
/**
* sets text on a panel caption
*/
public setPanelCaptionText(name: string, panelId: string, text: string): boolean;
/**
* returns number of project captions
*/
public numberOfProjectCaptions(): int;
/**
* returns name of the panel caption at index
*/
public nameOfProjectCaption(index: int): string;
/**
* adds a project caption
*/
public addProjectCaption(name: string): boolean;
/**
* returns text of the project caption
*/
public textOfProjectCaption(name: string): string;
/**
* deletes a project caption
*/
public deleteProjectCaption(name: string): boolean;
/**
* renames a project caption
*/
public renameProjectCaption(name: string, newName: string): boolean;
/**
* sets new text in a project caption
*/
public setProjectCaptionText(name: string, text: string): boolean;
}
/**
* Simplified CheckBox widget
*/
declare class CheckBox extends SCRIPT_QSWidget {
/**
* the text shown alongside the checkbox
*/
text: string;
/**
* whether or not the checkbox is checked
*/
checked: boolean;
}
/**
*
*/
declare class ColorRGBA extends QObject {
/**
* Create a new default ColorRGBA (ie. opaque white).
*/
constructor();
/**
* Create a new ColorRGBA.
*/
constructor(r: double, g: double, b: double, a: double);
/**
* red value [ 0, 255 ]
*/
r: int;
/**
* green value [ 0, 255 ]
*/
g: int;
/**
* blue value [ 0, 255 ]
*/
b: int;
/**
* alpha value [ 0, 255 ]
*/
a: int;
}
/**
* Simplified Dialog widget. This class and the associated widget classes are used to build simple dialogs
*/
declare class Dialog extends SCRIPT_QSWidget {
/**
* add a new tab to the dialog
*/
public newTab(label: string): void;
/**
* add a new column to the dialog
*/
public newColumn(): void;
/**
* add spacers to the dialog layout
*/
public addSpace(space: int): void;
/**
* add widgets to the dialog
*/
public add(widget: SCRIPT_QSWidget): void;
/**
* run the dialog in modal mode. Pressing ok accepts the dialog input. Pressing cancel cancels the dialog.
*/
public exec(): boolean;
/**
* it is the title of the dialog
*/
title: string;
/**
* it is the width of the dialog
*/
width: int;
/**
* it is the name of the ok button
*/
okButtonText: string;
/**
* it is the name of the cancel button
*/
cancelButtonText: string;
}
/**
* DrawingTool params class - used as parameters in drawingTools calls
*/
declare class DrawingToolParams extends QObject {
public applyAllDrawings(): boolean;
public setApplyAllDrawings(b: boolean): void;
}
/**
*
*/
declare namespace DrawingTools {
/**
* sets the current art to be one of the following : underlayArt, colourArt, lineArt or overlayArt
*/
function setCurrentArt(int: any): void;
/**
* sets the current drawing to be from column columnName at frame frame
*/
function setCurrentDrawingFromColumnName(columnName: string, frame?: int): boolean;
/**
* sets the current drawing to be from node nodeName at frame frame
*/
function setCurrentDrawingFromNodeName(nodeName: string, frame?: int): boolean;
/**
* converts the selected pencil lines in layer of the current drawing using params
*/
function convertPencilToBrush(art?: int, params?: DrawingToolParams): void;
/**
* extracts the centreline from srcLayer and puts the extracted line in dstLayer using params.
*/
function extractCenterline(srcArt?: int, dstArt?: int, params?: DrawingToolParams): void;
/**
* computes the breaking triangles of the current layer using params.
*/
function computeBreakingTriangles(params?: DrawingToolParams): void;
/**
* readonly property - returns underlayArt mask
*/
var underlayArt: int;
/**
* readonly property - returns colourArt mask
*/
var colourArt: int;
/**
* readonly property - returns lineArt mask
*/
var lineArt: int;
/**
* readonly property - returns overlayArt mask
*/
var overlayArt: int;
/**
* readonly property - returns mask for all 4 art layers
*/
var allArts: int;
}
declare type MovieFormat = "jpg" | "mov" | "tga";
declare type BitmapFormat = "jpg" | "psd" | "tga";
/**
* This interface is used to export the storyboard project
*/
declare class ExportManager extends QObject {
/**
* Export storyboard to bitmap file.
*/
public exportToBitmap(exportDir: string, filePattern: string, bitmapFormat: BitmapFormat, resX: int, resY: int): boolean;
/**
* Export storyboard to movie file.
*/
public exportToMovie(exportDir: string, filePattern: string, movieFormat: MovieFormat, resX: int, resY: int): boolean;
/**
* Export storyboard panels, taking into consideration the scene camera (layout )
*/
public exportLayout(exportDir: string, filePattern: string, movieFormat: MovieFormat, resX: int, resY: int): boolean;
/**
* Export storyboard to pdf file.
*/
public exportToPDF(fileName: string): boolean;
/**
* Export storyboard to Final Cut Pro XML format.
*/
public exportToFCPXML(exportFilePath: string, filePattern: string, movieFormat: MovieFormat): boolean;
/**
* Export storyboard to Avid Media Composer AAF format.
*/
public exportToAAF(exportFilePath: string, filePattern: string, imageFormat: BitmapFormat): boolean;
/**
* Sets a selection of scenes to be exported.
*/
public setSelectedScenes(scenes: StringList): void;
/**
* Sets a selection of panels to be exported.
*/
public setSelectedPanels(panels: StringList): void;
/**
* Export the current scene.
*/
public setUseCurrentScene(flag: boolean): boolean;
/**
* Export the current panel.
*/
public setUseCurrentPanel(flag: boolean): boolean;
/**
* Export the tracked panel(s)
*/
public setUseTrackedPanels(flag: boolean): boolean;
/**
* Export the selected panel(s)
*/
public setUseSelectedPanels(flag: boolean): boolean;
/**
* Allow Camera Scaling.
*/
public setCameraScaling(flag: boolean): void;
/**
* Exports the camera frames black border.
*/
public setShowCamera(flag: boolean): void;
/**
* Prints each camera keyframe on the exported images.
*/
public setShowCameraKeyFrames(flag: boolean): void;
/**
* Sets a transparent background. This is only useful when exporting to photoshop ( psd files ).
*/
public setTransparentBG(flag: boolean): void;
/**
* Set Fit Camera Path.
*/
public setBitmapFitCameraPath(flag: boolean): void;
/**
* Set Rectify Static Camera.
*/
public setBitmapRectifyStatic(flag: boolean): void;
/**
* Sets the magnification of the image. By default there is no magnification.
*/
public setZoomFactor(zoom: double): void;
/**
* Maintain Size Through Scene. This ensures that all images exported are the same size.
*/
public setMaintainSize(flag: boolean): void;
/**
* Show the reference frame.
*/
public setShowReference(flag: boolean): void;
/**
* Export one image for each layer.
*/
public setExportOneImagePerLayer(flag: boolean): void;
/**
* By default, this is false.
*/
public setApplyLayerMotionCamera(flag: boolean): void;
/**
* Display the camera labels.
*/
public setShowCameraLabel(flag: boolean): void;
/**
* Set the pdf profile to be used during the pdf export.
*/
public setPDFProfile(profile: string): boolean;
/**
* Returns the names of known pdf profiles.
*/
public getPDFProfiles(): StringList;
/**
* Specify the granularity of movie clip generation.
*/
public setOneMovieClipPer(perWhat: string): boolean;
/**
* Set the audio/video export settings ( for Quicktime export )
*
* This is provided as a work-around to specify explicit QuickTime settings. The easiest way to access a given QuickTime settings string to to save the given setting in the exportMovie dialog, and consult the EXPORT_DLG_MOVIE_VIDEO_CONFIG preference in your user preferences.
*/
public setMovieConfig(config: string): void;
/**
* Export caption as comments in FCP XML.
*/
public setExportCaptions(flag: boolean): void;
/**
* Export markers at scene beginning.
*/
public setExportMarkers(flag: boolean): void;
/**
* Export scenes reference track.
*/
public setExportScenesReferenceTrack(flag: boolean): void;
/**
* Render scene/panel name overlay.
*/
public setShowScenePanelNamesOverlay(flag: boolean): void;
/**
* Render 4:3 safety overlay.
*/
public setShow43SafetyOverlay(flag: boolean): void;
/**
* Notify flix server when exporting to FCP XML.
*/
public setNotifyFlix(flag: boolean): void;
/**
* Signal emitted if export was successful.
*/
exportReady: QSignal<() => void>;
}
/**
* The FileMapper function, toNativePath( String&) will return the complete path of the passed path resolving shortcuts in windows. Will also convert the path separator to
*/
declare namespace fileMapper {
/**
* returns the complete path of the passed path resolving shortcuts in windows
*/
function toNativePath(path: string): string;
}
/**
* With the Function Manager, you can manipulate the camera functions and the layer functions. Note that for all methods you must give the unique id. For the camera, this is the sceneId. For a layer functions, this is the panelId
*/
declare class FunctionManager extends QObject {
/**
* returns the Start value from the Hold Value Editor dialog box, for Bezier and Velo-based Function Editors.
*/
public holdStartFrame(shotId: string, columnName: string): int;
/**
* returns the Stop value from the Hold Value Editor dialog box, for Bezier, Ease and Velo-based Function Editors
*/
public holdStopFrame(shotId: string, columnName: string): int;
/**
* returns the Step value from the Hold Value Editor dialog box, for Bezier, Ease and Velo-based Function Editors
*/
public holdStep(shotId: string, columnName: string): int;
/**
* sets a value on a column at the given frame
*/
public setEntry(shotId: string, columnName: string, subColumn: int, AtFrame: double, value: string): boolean;
/**
* gets a value from a column at the given frame
*/
public getEntry(shotId: string, columnName: string, subColumn: int, AtFrame: double): string;
/**
* sets a keyframe on a column
*/
public setKeyFrame(shotId: string, columnName: string, AtFrame: double): boolean;
/**
* clears a keyframe on a column
*/
public clearKeyFrame(shotId: string, columnName: string, AtFrame: double): boolean;
/**
* returns the number of keyframes and control points on a curve
*/
public numberOfPoints(shotId: string, columnName: string): int;
/**
* returns the type of the function ( Bezier, Ease, VeloBased or 3dPath )
*/
public functionType(shotId: string, columnName: string): string;
/**
* returns the X value (frame number) of a point on a function curve
*/
public pointX(shotId: string, columnName: string, point: int): double;
/**
* returns the Y value of a point on a function curve
*/
public pointY(shotId: string, columnName: string, point: int): double;
/**
* returns a 1 (one) to indicate that the point is on a ant segment, or a 0 (zero) to indicate that the point is not on a ant segment
*/
public pointConstSeg(shotId: string, columnName: string, point: int): boolean;
/**
* returns the continuity of the curve that follows the point. One of the following values will be returned, in upper-case: SMOOTH, CORNER or STRAIGHT
*/
public pointContinuity(shotId: string, columnName: string, point: int): string;
/**
* returns the X value of the left handle of a point on a curve
*/
public pointHandleLeftX(shotId: string, columnName: string, point: int): double;
/**
* returns the Y value of the left handle of a point on a curve.
*/
public pointHandleLeftY(shotId: string, columnName: string, point: int): double;
/**
* returns the X value of the right handle of a point on a curve.
*/
public pointHandleRightX(shotId: string, columnName: string, point: int): double;
/**
* returns the Y value of the right handle of a point on a curve
*/
public pointHandleRightY(shotId: string, columnName: string, point: int): double;
/**
* returns the number of frames in the ease-in
*/
public pointEaseIn(shotId: string, columnName: string, point: int): double;
/**
* returns the angle of the ease-in handle
*/
public angleEaseIn(shotId: string, columnName: string, point: int): double;
/**
* returns the number of frames in the ease-out
*/
public pointEaseOut(shotId: string, columnName: string, point: int): double;
/**
* returns the angle of the ease-out handle
*/
public angleEaseOut(shotId: string, columnName: string, point: int): double;
/**
* returns the number of keyframes and control points on the 3D Path
*/
public numberOfPointsPath3d(shotId: string, columnName: string): int;
/**
* returns the value of the specified point on the X path
*/
public pointXPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the value of the specified point on the Y path
*/
public pointYPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the value of the specified point on the Z path
*/
public pointZPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the tension value for the specified point on the 3D Path
*/
public pointTensionPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the continuity value (STRAIGHT, SMOOTH or CORNER) for the specified point on the 3D Path.
*/
public pointContinuityPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the bias value for the specified point on the 3D Path
*/
public pointBiasPath3d(shotId: string, columnName: string, point: int): double;
/**
* returns the frame at which it's locked, or returns 0 if the point is not locked.
*/
public pointLockedAtFrame(shotId: string, columnName: string, point: int): double;
/**
* sets the Start value in the Hold Value Editor dialog box, for Bezier, Ease and Velo-based Function Editors
*/
public setHoldStartFrame(shotId: string, columnName: string, start: int): boolean;
/**
* sets the Stop value in the Hold Value Editor dialog box, for Bezier, Ease and Velo-based Function Editors
*/
public setHoldStopFrame(shotId: string, columnName: string, stop: int): boolean;
/**
* sets the Hold value in the Hold Value Editor dialog box, for Bezier, Ease and Velo-based Function Editors.
*/
public setHoldStep(shotId: string, columnName: string, step: int): boolean;
/**
* sets the values of a point on a Bezier function curve
*/
public setBezierPoint(shotId: string, columnName: string, frame: int, y: double, handleLeftX: double, handleLeftY: double, handleRightX: double, handleRightY: double, Seg: boolean, continuity: string): boolean;
/**
* sets the values of a point on an Velobased function curve
*/
public setVeloBasePoint(shotId: string, columnName: string, frame: int, y: double): boolean;
/**
* sets the values of a point on an Ease function curve
*/
public setEasePoint(shotId: string, columnName: string, frame: int, y: double, easeIn: double, angleEaseIn: double, easeOut: double, angleEaseOut: double, Seg: boolean, continuity: string): boolean;
/**
* adds a keyframe to a 3D Path and sets the X, Y and Z value, as well as the tension, continuity and bias.
*/
public addKeyFramePath3d(shotId: string, columnName: string, frame: int, x: double, y: double, z: double, tension: double, continuity: double, bias: double): boolean;
/**
* adds a keyframe after a point on a 3D Path and sets the X, Y and Z values, as well as the tension, continuity and bias
*/
public addCtrlPointAfterPath3d(shotId: string, columnName: string, point: int, x: double, y: double, z: double, tension: double, continuity: double, bias: double): boolean;
/**
* removePointPath3d may be used to remove either a key frame, or a control point
*/
public removePointPath3d(shotId: string, columnName: string, point: int): boolean;
/**
* setPointPath3d may be used to set values in either a key frame, or a control point, but cannot change a key frame into a control point or a control point into a key frame. To change a key frame into a control point or a control point into a key frame, you must remove the point and add a new point.
*/
public setPointPath3d(shotId: string, columnName: string, point: int, x: double, y: double, z: double, tension: double, continuity: double, bias: double): boolean;
/**
* sets the ant segment flag of point i of path p to b.
*/
public setPath3dPointConstantSegment(shotId: string, columnName: string, point: int, ant: boolean): boolean;
/**
* sets the ant segment flag of point found at frame f of path p to b.
*/
public setPath3dPointConstantSegmentForFrame(shotId: string, columnName: string, point: double, ant: boolean): boolean;
}
/**
* This interface is used to access the layers within a given panel
*/
declare class LayerManager extends QObject {
/**
* returns number of layers in a panel
*/
public numberOfLayers(panelId: string): int;
/**
* Adds a vector Layer.
*/
public addVectorLayer(panelId: string, targetLayerIdx: int, before: boolean, suggestedName: string): boolean;
/**
* Adds a bitmap Layer.
*/
public addBitmapLayer(panelId: string, targetLayerIdx: int, before: boolean, suggestedName: string): boolean;
/**
* Returns if layer is Vector.
*/
public isVectorLayer(panelId: string, index: int): boolean;
/**
* Returns if layer is 3D.
*/
public is3DLayer(panelId: string, index: int): boolean;
/**
* Returns if layer is Bitmap.
*/
public isBitmapLayer(panelId: string, index: int): boolean;
/**
* Deletes a given layer.
*/
public deleteLayer(panelId: string, index: int): boolean;
/**
* Renames a given layer.
*/
public renameLayer(panelId: string, index: int, suggestedName: string): boolean;
/**
* Returns name of layer.
*/
public layerName(panelId: string, index: int): string;
/**
* Imports image and creates a new layer at index 0, returns if successful.
*/
public importImageAsLayer(panelId: string, fullPathAndFileName: string): boolean;
/**
* Set layers visiblility flag.
*/
public setLayerVisible(panelId: string, index: int, visible: boolean): boolean;
/**
* Get layers visiblility flag.
*/
public layerVisibility(panelId: string, index: int): boolean;
/**
* Set layers opacity value.
*/
public setLayerOpacity(panelId: string, index: int, opacity: double): boolean;
/**
* Get layers opacity value.
*/
public layerOpacity(panelId: string, index: int): double;
/**
* Set layers alignment value.
*/
public setLayerAlignment(panelId: string, index: int, alignment: string): boolean;
/**
* Get layers Alignment value.
*/
public layerAlignment(panelId: string, index: int): string;
/**
* Get the path to a layer's drawing.
*/
public getLayerDrawingName(panelId: string, index: int, fullPath: boolean): string;
/**
* Return the elementId of the layer. Useful for the element/Drawing interface.
*/
public getLayerElementId(panelId: string, index: int): int;
}
/**
* Simplified MessageBox widget
*/
declare namespace MessageBox {
/**
* information box. One button, OK.
*/
function information(unknown_0: QScriptContext, unknown_1?: QScriptEngine): QScriptValue;
/**
* warning box. Two buttons are Abort and Retry.
*/
function warning(unknown_0: QScriptContext, unknown_1?: QScriptEngine): QScriptValue;
/**
* critical box. One button, Retry.
*/
function critical(unknown_0: QScriptContext, unknown_1?: QScriptEngine): QScriptValue;
}
/**
* Allows the user to print messages to the message log window
*/
declare namespace MessageLog {
/**
* writes the message to the message log
*/
function trace(message: string): void;
/**
* writes the message to the message log if debug mode is on
*/
function debug(messageIfDebug: string): void;
/**
* sets debug mode to on/off
*/
function setDebug(b: boolean): void;
/**
* returns whether debug mode is set
*/
function isDebug(): boolean;
}
/**
* This interface is used to access the shot cameras or the panel layers, and add or remove motion to them
*/
declare class MotionManager extends QObject {
/**
* adds a Keyframe to the camera
*/
public addCameraKeyFrame(shotId: string, offset: int): boolean;
/**
* remove Keyframe from the camera
*/
public removeCameraKeyFrame(shotId: string, offset: int): boolean;
/**
* clears all Motion from the camera
*/
public clearCameraMotion(shotId: string): boolean;
/**
* retrieves a specific function from the camera, which may be manipulated using the FunctionManager attributes for camera pegs are position.attr3dpath, scale.x, scale.y, scale.z, rotation.anglez, skew
*/
public linkedCameraFunction(shotId: string, attrName: string): string;
/**
* adds a Keyframe to the layer
*/
public addLayerKeyFrame(panelId: string, layerIndex: int, offset: int): boolean;
/**
* remove Keyframe from the layer
*/
public removeLayerKeyFrame(panelId: string, layerIndex: int, offset: int): boolean;
/**
* clears all Motion from the layer
*/
public clearLayerMotion(panelId: string, layerIndex: int): boolean;
/**
* retrieves a specific function from the layer, which may be manipulated using the FunctionManager attributes for layers are offset.attr3dpath, scale.x, scale.y, scale.z, rotation.anglez, skew
*/
public linkedLayerFunction(panelId: string, layerIndex: int, attrName: string): string;
/**
* returns the linked function name for the given node and attribute, which may be manipulated using the FunctionManager
*/
public getLinkedFunction(idString: string, nodeName: string, attrName: string): string;
/**
* sets the linked function for the given node and attribute
*/
public setLinkedFunction(idString: string, nodeName: string, attrName: string, functionName: string): boolean;
/**
* creates a new function of the given type within the project or shot or panel
*/
public addFunction(idString: string, name: string, type: string): boolean;
/**
* Changes the attributes of a module.
*/
public setTextAttr(idString: string, nodeName: string, attrName: string, atFrame: double, attrValue: string): boolean;
/**
* Gets the value of a attribute in a module.
*/
public getTextAttr(idString: string, nodeName: string, attrName: string, atFrame: double): string;
/**
* returns the model matrix for the given node.
*/
public getNodeMatrix(idString: string, nodeName: string, atFrame: double): Matrix4x4;
}
/**
* This set of functions is used to query/modify the current penstyle and list of penstyles. The list of penstyles includes the brush, pencil and texture styles
*/
declare namespace PenstyleManager {
/**
* Gets the number of penstyles.
*/
function getNumberOfPenstyles(): int;
/**
* Gets the name of the penstyle.
*/
function getPenstyleName(index: int): string;
/**
* Gets the index of the current penstyle.
*/
function getCurrentPenstyleIndex(): int;
/**
* Gets the name of the current penstyle.
*/
function getCurrentPenstyleName(): string;
/**
* sets the current penstyle
*/
function setCurrentPenstyleByName(name: string): void;
/**
* sets the current penstyle
*/
function setCurrentPenstyleByIndex(index: int): void;
/**
* set the current penstyle minimum size
*/
function changeCurrentPenstyleMinimumSize(minimum: double): void;
/**
* set the current penstyle maximum size
*/
function changeCurrentPenstyleMaximumSize(maximum: double): void;
/**
* set the current penstyle outline smoothness
*/
function changeCurrentPenstyleOutlineSmoothness(smooth: double): void;
/**
* set the current penstyle centreline smoothness
*/
function changeCurrentPenstyleCenterlineSmoothness(smooth: double): void;
/**
* set the current penstyle eraser flag
*/
function getCurrentPenstyleMinimumSize(): double;
/**
* Gets the current penstyle maximum size.
*/
function getCurrentPenstyleMaximumSize(): double;
/**
* Gets the current penstyle outline smoothness.
*/
function getCurrentPenstyleOutlineSmoothness(): double;
/**
* Gets the current penstyle center line smoothness.
*/
function getCurrentPenstyleCenterlineSmoothness(): double;
/**
* Gets the current penstyle eraser flag.
*/
function getCurrentPenstyleEraserFlag(): boolean;
/**
* Create a string representing the penstyle which can be used to store the penstyle and import it later.
*/
function exportPenstyleToString(index: int): string;
/**
* Formats the penstyle list into a string, which can be used to store the penstyle list and import it later.
*/
function exportPenstyleListToString(): string;
/**
* Imports a penstyle list from a previously formatted penstyle string.
*/
function importPenstyleListFromString(str: string): void;
/**
* Saves the penstyles.
*/
function savePenstyles(): void;
}
/**
* Used to represent an actual image file on disk which will not be deleted after script execution. Permanent files can be instantiated in the scripting environment or retrieved in an SM_InputPortWrapper object
*/
declare class PermanentFile extends QObject {
/**
* Remove physical file manually. Cannot remove file if there is an open stream.
*/
public remove(): PermanentFile;
/**
* Create a new SCR_FileWrapper.
*/
constructor();
/**
* Create a new PermanentFile.
*/
constructor(path: string);
}
/**
* With the Preferences functions, you can retrieve information about the whole preference system. The user can set and retrieve the value of any preferences in the software
*/
declare namespace preferences {
/**
* get the color from the given preference name
*/
function getColor(name: string, defaultValue: ColorRGBA): ColorRGBA;
/**
* set the color for the given preference name
*/
function setColor(name: string, color: ColorRGBA): void;
/**
* get the double value from the given preference name
*/
function getDouble(name: string, defaultValue: double): double;
/**
* set the double value for the given preference name
*/
function setDouble(name: string, value: double): void;
/**
* get the integer value from the given preference name
*/
function getInt(name: string, defaultValue: int): double;
/**
* set the integer value for the given preference name
*/
function setInt(name: string, value: int): void;
/**
* get the boolean value from the given preference name
*/
function getBool(name: string, defaultValue: boolean): boolean;
/**
* get the boolean value for the given preference name
*/
function setBool(name: string, value: boolean): void;
/**
* get the string value from the given preference name
*/
function getString(name: string, defaultValue: string): string;
/**
* set the string value for the given preference name
*/
function setString(name: string, value: string): void;
function getEnumValue(name: string, defaultValue: int): double;
function setEnumValue(name: string, value: int): void;
function preferences(parent: QObject, name: char): void;
}
/**
* This interface is used to merge/extract another storyboard into the main storyboard
*/
declare class PrjMgtManager extends QObject {
/**
* Set the flag to merge sound clips from the source project.
*/
public setMergeSoundClips(flag: boolean): void;
/**
* Set the flag to respect locked sound tracks.
*/
public setRespectLockedSoundTracks(flag: boolean): void;
/**
* Set the flag to keep the original scenes ( when overwriting ) and move them to the end of the project.
*/
public setKeepOriginalScenes(flag: boolean): void;
/**
* Loads the specified storyboard project to be used as a source for insertion.
*/
public loadSourceProject(scenePath: string): boolean;
/**
* Returns a list of sceneIds from the loaded storyboard project.
*/
public sourceProjectSceneIds(): StringList;
/**
* Returns a list of panelIds from the specified scene of the loaded storyboard project.
*/
public sourceProjectPanelIds(sceneId: string): StringList;
/**
* Returns a list of captions from the loaded storyboard project.
*/
public sourceProjectCaptionNames(): StringList;
/**
* Map source Captions by caption name, on insert. True by default.
*/
public setCaptionRemapByName(flag: boolean): void;
/**
* Returns the scene Name for a given source project scene Id.
*/
public sourceProjectSceneName(sceneId: string): string;
/**
* Returns the sequence Name for a given source project scene Id.
*/
public sourceProjectSequenceName(sceneId: string): string;
/**
* Inserts the specified source scene Id into the project.
*/
public insertScene(srcSceneId: string, dstSceneId: string, overwrite: boolean, before: boolean): string;
/**
* Inserts the specified source panel Id into the project.
*/
public insertPanel(srcSceneId: string, dstSceneId: string, overwrite: boolean, before: boolean): string;
/**
* Extracts the specified range of scenes, and creates a new project with them.
*/
public extractRange(newProjectPath: string, newProjectName: string, fromShotId: string, toShotId: string, removeScenes: boolean): boolean;
}
/**
* Used to launch an external process. Processes can be instantiated in the scripting environment
*/
declare class Process extends QObject {
/**
* Launch process.
*/
public launch(): int;
/**
* Launch process and detach it from application.
*/
public launchAndDetach(): int;
/**
* Fetch command line to be executed in this process.
*/
public commandLine(): string;
/**
* Fetch error code.
*/
public errorCode(): int;
/**
* Fetch error message.
*/
public errorMessage(): string;
/**
* Terminate process.
*/
public terminate(): void;
/**
* Verify if process is still alive.
*/
public isAlive(): boolean;
/**
* Fetch process PID.
*/
public pid(): int;
/**
* Create a new Process. A process created with a pid cannot be launched as it already should have been. terminate() and isAlive() functions can still be called with such a process.
*/
constructor(pid: int);
/**
* Create a new Process.
*/
constructor(name: string, ...args: any[]);
/**
* Create a new Process.
*/
constructor(name: string, list: StringList);
/**
* Create a new Process.
*/
constructor(commandLine: string);
}
/**
* This interface is used to access the properties of the storyboard project
*/
declare class PropertiesManager extends QObject {
/**
* returns the duration of the project in frames
*/
public getDuration(): int;
/**
* sets the project title
*/
public setTitle(title: string): boolean;
/**
* gets the project title
*/
public getTitle(): string;
/**
* sets the project sub title
*/
public setSubTitle(title: string): boolean;
/**
* gets the project sub title
*/
public getSubTitle(): string;
/**
* sets the edisode title
*/
public setEpisodeTitle(title: string): boolean;
/**
* gets the episode title
*/
public getEpisodeTitle(): string;
/**
* sets the project copyright text
*/
public setCopyright(text: string): boolean;
/**
* gets the copyright string
*/
public getCopyright(): string;
/**
* sets the project start time
*/
public setStartTime(nbFrames: int): boolean;
/**
* returns the project start time
*/
public getStartTime(): int;
/**
* sets the project film width
*/
public setFilmWidth(width: double): boolean;
/**
* returns the project film width
*/
public getFilmWidth(): double;
}
/**
* With the Scene functions, you can retrieve and set global scene attributes, like the aspect ratio of the cells in the scene grid
*/
declare namespace scene {
/**
* returns the ID of the current version.
*/
function currentVersion(): int;
/**
* returns the name or the number of the current scene version.
*/
function currentVersionName(): string;
/**
* returns the name of the current environment.
*/
function currentEnvironment(): string;
/**
* returns the name of the current job.
*/
function currentJob(): string;
/**
* returns the name of the current scene.
*/
function currentScene(): string;
/**
* Return the current project path.
*/
function currentProjectPath(): string;
/**
* For windows, returns the remapped path.
*/
function currentProjectPathRemapped(): string;
/**
* Return the temporary project path.
*/
function tempProjectPath(): string;
/**
* For windows, returns the remapped temporary project path.
*/
function tempProjectPathRemapped(): string;
/**
* This function starts the accumulation of all of the functions between it and the endUndoRedoAccum function as one command that will appear in the undo/redo list. If you do not use this function with endUndoRedoAccum, each function in the script generates a separate undo/redo entry.
*/
function beginUndoRedoAccum(commandName: string): void;
/**
* This function ends the accumulation all of the functions between it and the beginUndoRedoAccum function as one command that will appear in the undo/redo list. If you do not use this function with beginUndoRedoAccum, each function in the script generates a separate undo/redo entry.
*/
function endUndoRedoAccum(): void;
/**
* This function cancels the accumulation of undo/redo commands. No command will be added to the undo/redo list and all commands that have already been executed will be rolled-back (undone).
*/
function cancelUndoRedoAccum(): void;
/**
* undoes the last n operation. If n is not specified, it will be 1
*/
function undo(depth?: int): void;
/**
* redoes the last n operation. If n is not specified, it will be 1
*/
function redo(depth?: int): void;
/**
* Clear command history.
*/
function clearHistory(): void;
/**
* returns the X value of the aspect ratio of the cells in the scene grid.
*/
function unitsAspectRatioX(): double;
/**
* returns the Y value of the aspect ratio of the cells in the scene grid.
*/
function unitsAspectRatioY(): double;
/**
* returns the number of units in the X axis of the scene grid.
*/
function numberOfUnitsX(): int;
/**
* returns the number of units in the Y axis of the scene grid.
*/
function numberOfUnitsY(): int;
/**
* returns the number of units in the Z axis of the scene grid.
*/
function numberOfUnitsZ(): int;
/**
* returns the X value of the centre coordinate of the scene grid.
*/
function coordAtCenterX(): int;
/**
* returns the Y value of the centre coordinate of the scene grid.
*/
function coordAtCenterY(): int;
/**
* returns the current preview resolution. For example, when the current resolution is 720x540 pixels this function will return 720.
*/
function currentResolutionX(): int;
/**
* returns the current preview resolution. For example, when the current resolution is 720x540 pixels this function will return 540.
*/
function currentResolutionY(): int;
/**
* returns the default resolution name. The resolution name is a global parameter saved with the project. It may be empty when the project is used as a custom resolution, which is not one of the pre-defined resolutions.
*/
function defaultResolutionName(): string;
/**
* returns the default resolution. This resolution is a global parameter saved with the project, not the current preview resolution. For example, when the default scene resolution is 720x540 pixels this function will return 720.
*/
function defaultResolutionX(): int;
/**
* returns the default resolution. This resolution is a global parameter saved with the project, not the current preview resolution. For example, when the default scene resolution is 720x540 pixels this function will return 540.
*/
function defaultResolutionY(): int;
/**
* returns the default resolution field of view (FOV). The default FOV is a global scene parameter.
*/
function defaultResolutionFOV(): double;
/**
* returns the list of known resolution
*/
function namedResolutions(): StringList;
/**
* returns the named resolution. For example, when the named resolution is 720x540 pixels this function will return 720.
*/
function namedResolutionX(name: string): int;
/**
* returns the named resolution. For example, when the named resolution is 720x540 pixels this function will return 540.
*/
function namedResolutionY(name: string): int;
/**
* returns the frame rate, as frame per seconds.
*/
function getFrameRate(): int;
/**
* performs the " save all " command. Effectively, this saves the entire project and all modified files.
*/
function saveAll(): boolean;
/**
* saves the project as a new version.
*/
function saveAsNewVersion(name: string, markAsDefault: boolean): boolean;
/**
* sets the aspect ratio of the scene. The scene's final aspect ratio will be: X * numberOfUnitsX()/Y * numberOfUnitsY()
*/
function setUnitsAspectRatio(x: double, y: double): boolean;
/**
* sets the number of X, Y, and Z units in the scene grid.
*/
function setNumberOfUnits(x: int, y: int, z: int): boolean;
/**
* sets the value of the centre (X, Y) coordinates.
*/
function setCoordAtCenter(x: int, y: int): boolean;
/**
* allows the default scene resolution and field of view to be changed.
*/
function setDefaultResolution(x: int, y: int, fov: double): boolean;
/**
* This function allows the default scene resolution name to be changed.
*/
function setDefaultResolutionName(name: string): boolean;
/**
* This function allows the default frame rate of the project to be changed. The frame rate is expressed as frame per second. Typical value is 12, 24 or 30.
*/
function setFrameRate(frameRate: int): boolean;
/**
* returns the model matrix for the default camera.
*/
function getCameraMatrix(frame: int): Matrix4x4;
/**
* converts a field coordinate into an OGL coordinate
*/
function toOGL(pointOrVector: QObject): QObject;
/**
* converts an OGL coordinate into a field coordinate.
*/
function fromOGL(pointOrVector: QObject): QObject;
/**
* retrieves default display set in current scene.
*/
function getDefaultDisplay(): string;
/**
* closes the current scene.
*/
function closeScene(): void;
/**
* closes the current scene and exits.
*/
function closeSceneAndExit(): void;
/**
* closes the current scene and open the scene specified by env, job, scene and version
*/
function closeSceneAndOpen(envName: string, jobName: string, sceneName: string, versionName: string): boolean;
/**
* returns all palettes that were either unrecovered or recovered but not yet saved, depending on the arguments of the function.
*/
function getMissingPalettes(unrecovered: boolean, recoveredNotYetSaved: boolean): StringList;
function getMetadataList(): QScriptValue;
}
/**
*
*/
declare class SCR_FileIOTypeWrapper extends QObject {}
/**
* Base class to TemporaryFile and PermanentFile
*/
declare class SCR_FileWrapper extends QObject {
/**
* Specify absolute path of this image file. Name of file can be changed only if there is an open stream.
*/
public setPath(path: string): SCR_FileWrapper;
/**
* Retrieve file path.
*/
public path(): string;
/**
* Retrieve file extension.
*/
public extension(): string;
/**
* Verify if file exists on disk.
*/
public exists(): boolean;
/**
* Check if file is opened.
*/
public isOpen(): boolean;
/**
* Check if file is closed.
*/
public isClose(): boolean;
/**
* Open file stream for read/write.
*/
public open(m?: int): boolean;
/**
* Close file stream.
*/
public close(): boolean;
/**
* Write string in current stream.
*/
public write(text: string): void;
/**
* Write string line in current stream.
*/
public writeLine(text: string): void;
/**
* Write entire content of parameter file in current stream.
*/
public write(file: SCR_FileWrapper): void;
/**
* Read entire content of stream.
*/
public read(): string;
/**
* Read single line of stream.
*/
public readLine(): string;
public move(dest: SCR_FileWrapper): boolean;
public copy(dest: SCR_FileWrapper): boolean;
}
/**
*
*/
declare namespace SCR_SystemInterfaceImpl {
function println(arg: string): void;
function getenv(str: string): string;
function processOneEvent(): void;
}
/**
* This interface is used to access the GUI storyboard selection. In batch mode, this interface is a no-op
*/
declare class SelectionManager extends QObject {
/**
* returns list of selected sequences
*/
public getSequenceSelection(): StringList;
/**
* returns list of selected scenes
*/
public getSceneSelection(): StringList;
/**
* returns list of selected panels
*/
public getPanelSelection(): StringList;
/**
* Clear selection.
*/
public clearSelection(): boolean;
/**
* Select All.
*/
public selectAll(): boolean;
/**
* set Selected Panels
*/
public setPanelSelection(l: StringList): boolean;
/**
* set Selected Scenes
*/
public setSceneSelection(l: StringList): boolean;
/**
* set Selected Sequences
*/
public setSequenceSelection(l: StringList): boolean;
/**
* sets the current panel and moves the playhead
*/
public setCurrentPanel(panelId: string): boolean;
}
/**
*
*/
declare class soundColumnInterface extends QObject {
public sequences(): QScriptValue;
public column(): string;
}
/**
*
*/
declare class soundSequenceInterface extends QObject {
constructor(startFrame: any, endFrame: any, startTime: float, stopTime: float, name: string, filename: string);
public startFrame(): void;
public stopFrame(): void;
public startTime(): float;
public stopTime(): float;
public name(): string;
public filename(): string;
_startFrame: void;
_stopFrame: void;
_startTime: float;
_stopTime: float;
_name: string;
_filename: string;
}
/**
* This interface is used to access the audio tracks of a storyboard project
*/
declare class SoundTrackManager extends QObject {
/**
* return the number of Audio tracks
*/
public numberOfSoundTracks(): int;
/**
* return the columnName of the audio track at index
*/
public nameOfSoundTrack(index: int): string;
/**
* add a new empty audio track
*/
public addSoundTrack(): string;
/**
* delete audio track
*/
public deleteSoundTrack(columnName: string): boolean;
/**
* import a sound file into a given audio track at the specified frame
*/
public importSoundBuffer(columnName: string, soundFile: string, targetFrame: int): boolean;
/**
* returns a SoundColumnInterface object that contains a reference to that sound column. The SoundColumnInterface object contains a useful interface to introspecting the sound and its sound sequences.
*/
public soundColumn(columnName: string): QObject;
}
/**
* By using the SpecialFolders functions, you can retrieve information about the different folders (directories) used by the application. All of the functions are read-only. They return strings that represent folders in use by the various applications. Depending on the application (e.g. Toon Boom Harmony versus Toon Boom AnimatePro), the same content is stored in a different location
*/
declare namespace specialFolders {
/**
* read-only property for the root installation folder
*/
var root: string;
/**
* read-only property that contains the folder where application configuration files are stored. Normally, this is the /etc folder.
*/
var config: string;
/**
* read-only property that contains where the resources files are stored.
*/
var resource: string;
/**
* read-only property that indicates where the <install>/etc folder is.
*/
var etc: string;
/**
* read-only property that contains the folder where the language files are stored.
*/
var lang: string;
/**
* read-only property that contains the platform specific folder.
*/
var platform: string;
/**
* A read-only property containing the folder where the platforms specific applications are stored. Application and Binary folders are different on OS X, but are identical on all other platforms.
*/
var app: string;
/**
* This is a read-only property that contains the folder where the platforms specific binaries are stored. Application and Binary folders are different on OS X. They are identical on all other platforms.
*/
var bin: string;
/**
* This is a read-only property that contains the folder where the platforms specific 32-bit binaries are stored.
*/
var bin32: string;
/**
* This is a read-only property that contains the folder where the platforms specific libraries are stored.
*/
var library: string;
/**
* Location where the plugins that were designed for the previous SDK are stored. Replaces the plugins property.
*/
var legacyPlugins: string;
/**
* Location where the plugins that comply with the current SDK are stored.
*/
var plugins: string;
/**
* This is a read-only property that contains where the application will create its temporary files.
*/
var temp: string;
/**
* This is a read-only property that contains the folder where the user configuration is stored.
*/
var userConfig: string;
/**
* This is a read-only property that contains the folder where the html help folder is.
*/
var htmlHelp: string;
}
/**
* This interface is used to access the main storyboard project. It can be used to query the sequences, scenes, panels and transitions of the project. As well, it can be used to create, delete or rename project objects
*/
declare class StoryboardManager extends QObject {
/**
* Returns the number of sequences in the project.
*/
public numberOfSequencesInProject(): int;
/**
* Returns the sequenceId of the ith sequence in project.
*/
public sequenceInProject(i: int): string;
/**
* Returns sequenceId of the sequence of the given scene.
*/
public sequenceIdOfScene(sceneId: string): string;
/**
* returns the number of scenes in a sequence
*/
public numberOfScenesInSequence(sequenceId: string): int;
/**
* Returns sceneId of the ith scene in sequence.
*/
public sceneInSequence(sequenceId: string, i: int): string;
/**
* returns the number of scenes in project
*/
public numberOfScenesInProject(): int;
/**
* Returns sceneId of the ith scene in project.
*/
public sceneInProject(i: int): string;
/**
* Returns sceneId of the panel.
*/
public sceneIdOfPanel(panelId: string): string;
/**
* Returns the number of panels in a scene.
*/
public numberOfPanelsInScene(sceneId: string): int;
/**
* Returns the panelId of the ith panel in the scene.
*/
public panelInScene(sceneId: string, index: int): string;
/**
* returns the number of panels in project
*/
public numberOfPanelsInProject(): int;
/**
* Returns panelId of the ith panel in project.
*/
public panelInProject(i: int): string;
/**
* Returns the name of the sequence.
*/
public nameOfSequence(sequenceId: string): string;
/**
* Returns the name of the scene.
*/
public nameOfScene(sceneId: string): string;
/**
* Returns the name of the panel.
*/
public nameOfPanel(panelId: string): string;
/**
* Returns the unique id of the sequence.
*/
public sequenceId(sequenceName: string): string;
/**
* Returns the unique id of the scene.
*/
public sceneId(sequenceName: string, sceneName: string): string;
/**
* Returns the unique id of the panel.
*/
public panelId(sequenceName: string, sceneName: string, panelName: string): string;
/**
* Creates a new sequence.
*/
public createSequence(firstShotId: string, lastShotId: string): string;
/**
* Inserts a new scene.
*/
public insertScene(after: boolean, shotId: string, name: string): string;
/**
* Append a scene at the end of the project.
*/
public appendScene(name: string): string;
/**
* Inserts a new panel.
*/
public insertPanel(after: boolean, panelId: string, name: string): string;
/**
* Append a panel at the end of the project.
*/
public appendPanel(name: string): string;
/**
* Split a panel into 2 panels.
*/
public splitPanel(panelId: string, atFrame: int): boolean;
/**
* Deletes a sequence.
*/
public deleteSequence(seqId: string): boolean;
/**
* Deletes a scene.
*/
public deleteScene(sceneId: string): boolean;
/**
* Deletes a panel.
*/
public deletePanel(panelId: string): boolean;
/**
* Renames a sequence.
*/
public renameSequence(seqId: string, newName: string): boolean;
/**
* Renames a scene.
*/
public renameScene(sceneId: string, newName: string): boolean;
/**
* Renames a panel.
*/
public renamePanel(panelId: string, newName: string): boolean;
/**
* gets the panel Duration
*/
public getPanelDuration(panelId: string): int;
/**
* sets the panel duration
*/
public setPanelDuration(panelId: string, frames: int): boolean;
/**
* returns the start frame of a scene
*/
public sceneStartFrame(shotId: string): int;
/**
* returns the last frame of a scene
*/
public sceneEndFrame(shotId: string): int;
/**
* returns a list of the sceneIds of scenes that have leading transitions
*/
public scenesWithTrx(): StringList;
/**
* returns the sceneId of the shot to the right of the transition
*/
public sceneIdOfTrx(trxId: string): string;
/**
* returns the transition ID of the transition to the left of the shot
*/
public trxIdOfScene(shotId: string): string;
/**
* returns whether a scene has a leading transition
*/
public sceneHasTrx(shotId: string): boolean;
/**
* returns a string identifying the transition type
*/
public trxType(trxId: string): string;
/**
* returns the length of the transition
*/
public trxLength(trxId: string): int;
/**
* Create a transition ( at the beginning of the target shot ), and return the unique ID of the transition.
*/
public createTrx(shotId: string, length: int, stringType: string, angle?: int, reverse?: boolean): string;
/**
* modify the transition
*/
public modifyTrx(trxId: string, stringType: string, angle?: int, revers?: boolean): boolean;
/**
* resize a transition
*/
public resizeTrx(trxId: string, length: int): boolean;
/**
* delete a transition
*/
public deleteTrx(trxId: string): boolean;
}
/**
* Used to represent an actual image file on disk which will be deleted after script execution. Temporary files can be instantiated in the scripting environment or retrieved in an SM_InputPortWrapper object
*/
declare class TemporaryFile extends QObject {
/**
* Change extension from automatically generated file name. Extension won't change if there is an open stream.
*/
public setExtension(ext: string): TemporaryFile;
/**
* Create a new TemporaryFile.
*/
constructor();
/**
* Create a new TemporaryFile.
*/
constructor(extension: string);
}
/**
* The View functions provide information about the contents of selected View windows
*/
declare namespace view {
/**
* returns a unique identifier for the current, active View.
*/
function currentView(): string;
/**
* returns a string that indicates what type of View the currentView is.
*/
function type(viewName: string): string;
/**
* forces a refresh of the drawing and scene planning views.
*/
function refreshViews(): void;
/**
* returns the drawing tool manager.
*/
function currentToolManager(): QObject;
}
|
3d118ec45fa05e24d583c31d28cd6b857e91e6b8 | TypeScript | Happy-Ferret/FromJS | /packages/babel-plugin-data-flow/src/helperFunctions/OperationLog.ts | 3.421875 | 3 | // todo: would be better if the server provided this value
const getOperationIndex = (function() {
var operationIndexBase = Math.round(Math.random() * 1000 * 1000 * 1000);
var operationIndex = 0;
return function getOperationIndex() {
var index = operationIndex;
operationIndex++;
return operationIndexBase + operationIndex;
};
})();
// TODO: don't copy/paste this
function eachArgument(args, arrayArguments, fn) {
Object.keys(args).forEach(key => {
if (arrayArguments.includes(key)) {
args[key].forEach((a, i) => {
fn(a, "element" + i, newValue => (args[key][i] = newValue));
});
} else {
fn(args[key], key, newValue => (args[key] = newValue));
}
});
}
function serializeValue(value): SerializedValue {
// todo: consider accessing properties that are getters could have negative impact...
var knownValue = null;
if (value === String.prototype.slice) {
knownValue = "String.prototype.slice";
}
var length;
// todo: more performant way than doing try catch
try {
length = value.length;
} catch (err) {
length = null;
}
var type = typeof value;
var primitive;
if (["string", "null", "number"].includes(type)) {
primitive = value;
}
let str;
try {
str = (value + "").slice(0, 200);
} catch (err) {
str = "(Error while serializing)";
}
return <SerializedValue>{
length,
type,
str,
primitive,
knownValue
};
}
export interface SerializedValue {
length: any;
type: string;
str: string;
primitive: number | null | string;
knownValue: string | null;
}
export default class OperationLog {
operation: string;
result: SerializedValue;
args: any;
extraArgs: any;
index: number;
astArgs: any;
constructor({ operation, result, args, astArgs, extraArgs }) {
var arrayArguments = [];
if (operation === "arrayExpression") {
arrayArguments = ["elements"];
}
this.operation = operation;
this.result = serializeValue(result);
if (operation === "objectExpression" && args.properties) {
// todo: centralize this logic, shouldn't need to do if, see "arrayexpression" above also"
args.properties = args.properties.map(prop => {
return {
key: prop.key[1],
type: prop.type[1],
value: prop.value[1]
};
});
} else {
// only store argument operation log because ol.result === a[0]
eachArgument(args, arrayArguments, (arg, argName, updateArg) => {
updateArg(arg[1]);
});
}
if (typeof extraArgs === "object") {
eachArgument(extraArgs, arrayArguments, (arg, argName, updateArg) => {
updateArg(arg[1]);
});
}
this.args = args;
this.astArgs = astArgs;
this.extraArgs = extraArgs;
this.index = getOperationIndex();
}
}
|
a170ae18f342c8e68666253d20051ed2b551776f | TypeScript | evanholt1/projbackendtest | /src/utils/schemas/point.schema.ts | 2.65625 | 3 | import { Prop } from '@nestjs/mongoose';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
//@Schema()
export class Point {
@ApiPropertyOptional({ type: String, enum: ['Point'] })
@Prop({ enum: ['Point'], default: 'Point' })
type: string;
@ApiPropertyOptional({
type: [Number],
isArray: true,
minItems: 2,
maxItems: 2,
})
@Prop()
coordinates: number[];
}
|
bca6301cbfa81dfa70249dbb15195d991a274e02 | TypeScript | nroper/foundations | /packages/cognito-auth/src/password/reset-password.test.ts | 2.546875 | 3 | import { resetPassword } from './reset-password'
import { resetPasswordService } from '../services/password/reset-password'
import errorStrings from '../constants/error-strings'
import { ResetPasswordParams } from '../core/types'
jest.mock('../services/password/reset-password')
const mockedPasswordService = resetPasswordService as jest.Mock
describe('resetPassword', () => {
it('should call the success handler correctly on success', async () => {
const params = { userName: 'will@mail.com', cognitoClientId: 'someCognitoClientId' } as ResetPasswordParams
mockedPasswordService.mockImplementation(() => 'SUCCESS')
expect(await resetPassword(params)).toEqual('SUCCESS')
})
it('should call the error handler correctly if params are missing', async () => {
console.error = jest.fn()
const params = { userName: '', cognitoClientId: '' } as ResetPasswordParams
const error = new Error(errorStrings.USERNAME_REQUIRED)
mockedPasswordService.mockImplementation(() => 'SUCCESS')
await resetPassword(params)
expect(console.error).toHaveBeenCalledTimes(1)
expect(console.error).toHaveBeenCalledWith(`${errorStrings.RESET_PASSWORD_FAILED}, ${error}`)
})
it('should call the error handler correctly if service thows an error', async () => {
console.error = jest.fn()
const params = { userName: 'will@mail.com', cognitoClientId: 'someCognitoClientId' } as ResetPasswordParams
const error = new Error('API FAILED')
mockedPasswordService.mockImplementation(() => {
throw error
})
await resetPassword(params)
expect(console.error).toHaveBeenCalledTimes(1)
expect(console.error).toHaveBeenCalledWith(`${errorStrings.RESET_PASSWORD_FAILED}, ${error}`)
})
afterEach(() => {
jest.resetAllMocks()
})
afterAll(() => {
jest.restoreAllMocks()
})
})
|
f731f6aae621834ba203248d6be1e11201272c2b | TypeScript | wellwind/angular-advanced-20190427 | /src/app/posts/post.ts | 2.53125 | 3 | export interface MutipleArticle {
articles: Article[];
}
export interface SingleArticle {
article: Article;
}
export interface Article {
slug: string;
title: string;
description: string;
body: string;
tagList: string[];
createdAt: string;
updatedAt: string;
author: string;
}
export interface ArticleTitleExist {
titleExist: boolean;
}
|
c7c43c4f0d1f81dea46ae47c8eb0fe8f63390227 | TypeScript | lmjieSCU/H5game | /Even_look/src/Effects/GridEffect.ts | 2.90625 | 3 | /**cells配对成功消失特效 */
class GridEffect {
public createAngImgAt(arg1: number, arg2: number): egret.Bitmap {
let angle = new egret.Bitmap;
angle.texture = RES.getRes("angle_png");
angle.anchorOffsetX = angle.width / 2;
angle.anchorOffsetY = angle.height / 2;
GameCtrl.I.setposition(angle, arg1, arg2, false);
return angle;
}
public createLineImgAt(arg1: NPoint, arg2: NPoint): Array<egret.Bitmap> {
let min: number = 0;
let max: number = 0;
let line: egret.Bitmap;
let lines: Array<egret.Bitmap> = new Array<egret.Bitmap>();
if (arg1.x == arg2.x) {
min = Math.min(arg1.y, arg2.y);
max = Math.max(arg1.y, arg2.y);
for (let i = min; i < max; i++) {
line = this.createLineImg(new NPoint(arg1.x, i), new NPoint(arg1.x, i + 1));
lines.push(line);
}
return lines;
}
if (arg1.y == arg2.y) {
min = Math.min(arg1.x, arg2.x);
max = Math.max(arg1.x, arg2.x);
for (let i = min; i < max; i++) {
line = this.createLineImg(new NPoint(i, arg1.y), new NPoint(i + 1, arg1.y));
lines.push(line);
}
return lines;
}
return null;
}
private createLineImg(arg1: NPoint, arg2: NPoint): egret.Bitmap {
let line: egret.Bitmap = new egret.Bitmap;
line.texture = RES.getRes("line_png");
line.anchorOffsetX = line.width / 2;
line.anchorOffsetY = line.height / 2;
line.scaleX = Math.min(UI.WINSIZE_W / 8, UI.WINSIZE_H / 8) / line.width;
let type: string = null;
if (arg1.x == arg2.x && Math.abs(arg1.y - arg2.y) == 1) {
type = "horizon";
GameCtrl.I.setposition(line, arg1.x, (arg1.y + arg2.y) / 2.0, false);
line.rotation = 0;
return line;
}
if (arg1.y == arg2.y && Math.abs(arg1.x - arg2.x) == 1) {
type = "vertical";
GameCtrl.I.setposition(line, (arg1.x + arg2.x) / 2.0, arg2.y, false);
line.rotation = 90;
return line;
}
return null;
}
} |
86c018723a873936996da8ba91cea7c5f6231cf8 | TypeScript | EmmyLua/VSCode-EmmyLua | /src/findJava.ts | 2.640625 | 3 | import * as path from "path";
import * as vscode from "vscode";
import {substituteFolder} from "./substitution";
function validateJava(javaPath: string): boolean {
//TODO check java path
return false;
}
export default function(): string|null {
var executableFile: string = "java";
if(process["platform"] === "win32") {
executableFile += ".exe";
}
var settingsPath = vscode.workspace.getConfiguration("emmylua").get("java.home");
if (settingsPath) {
let fullPath = substituteFolder(<string>settingsPath);
let javaPath = path.join(fullPath, "bin", executableFile);
return javaPath;
}
if("JAVA_HOME" in process.env) {
let javaHome = <string> process.env.JAVA_HOME;
let javaPath = path.join(javaHome, "bin", executableFile);
return javaPath;
}
if("PATH" in process.env) {
let PATH = <string> process.env.PATH;
let paths = PATH.split(path.delimiter);
let pathCount = paths.length;
for(let i = 0; i < pathCount; i++) {
let javaPath = path.join(paths[i], executableFile);
if(validateJava(javaPath)) {
return javaPath;
}
}
}
return null;
} |
a1365ca4beef004d2f53907623f8a02061c00238 | TypeScript | salilgupta2510/React-Native-Learning-Sapient | /exercise-1-typescript-warmup/src/domain/order.ts | 3.109375 | 3 | import { Placement } from './placement';
import { Side } from './types';
export interface OrderStatus {
committed: number;
done: number;
notDone: number;
uncommitted: number;
pctDone: number;
pctNotDone: number;
pctUncommitted: number;
}
/**
* An order to buy or sell a security for a specific fund.
*/
export class Order {
placementMap: Map<string, Placement> = new Map();
constructor(
readonly id: string,
public side: Side,
public symbol: string,
public quantity: number
) { }
place(placement: Placement) {
this.placementMap.set(placement.id, placement);
}
get status(): OrderStatus {
// TODO: Convert placementMap into an array
let placementArr = Array.from(this.placementMap.values());
// Use the array reduce function to compute OrderStatus
return placementArr.reduce((result, currentVal): OrderStatus => {
if (this.id === currentVal.orderId) {
result.committed += currentVal.quantity;
}
result.done = currentVal.done;
result.notDone = result.committed - result.done;
result.uncommitted = this.quantity - result.committed;
result.pctDone = result.done / this.quantity;
result.pctNotDone = result.notDone / this.quantity;
result.pctUncommitted = result.uncommitted / this.quantity;
return result;
}, {
committed: 0,
done: 0,
notDone: 0,
uncommitted: 0,
pctDone: 0,
pctNotDone: 0,
pctUncommitted: 0
}
);
}
}
|
db4d24c56ffc0caaa8441a4764aeb8bc0b9c9b70 | TypeScript | AllNamesRTaken/GoodCore | /src/lib/Cookie.ts | 2.796875 | 3 | import { find } from "./Arr";
import { getDate, assert } from "./Util";
import { transform } from "./Obj";
export function getCookie(key: string) {
let cookie = find(document.cookie.split(";").map((cookie) => cookie.trim()), (cookie) => cookie.indexOf(`${key}=`) === 0);
return cookie ? cookie.trim().split("=")[1] : undefined;
}
export function setCookie(key: string, value: string, expires: Date, path?: string | null, sameSite: "Strict" | "Lax" | "None" = 'Lax', requireSSL: boolean = false) {
document.cookie = `${key}=${value}; expires=${expires.toUTCString()}${(path ? "; path=" + path : "")};SameSite=${(this.CookieSameSite ?? 'Lax')};{${(this.RequireSSL || this.CookieSameSite === 'None' ? 'secure;' : '')}`;
}
export function removeCookie(key: string, path?: string | null, sameSite: "Strict" | "Lax" | "None" = 'Lax', requireSSL: boolean = false) {
document.cookie = `${key}=${"null"}; expires=${(new Date(0)).toUTCString()}${(path ? "; path=" + path : "")};SameSite=${(this.CookieSameSite ?? 'Lax')};{${(this.RequireSSL || this.CookieSameSite === 'None' ? 'secure;' : '')}`;
}
export function parseAllCookies(): Indexable<string> {
return document.cookie.split(";")
.map((cookie) => cookie.trim())
.reduce((p, c, i) => {
let [key, value] = c.split("=");
p[key] = value;
return p;
}, {} as Indexable<string>);
}
export function getMonster<T extends object>(options: Partial<ICookieMonsterOptions<T>>): ICookieMonster<T> {
return new CookieMonster(options);
}
interface ICookieMonsterOptions<T extends Indexable<any>> {
name: string;
defaults: T;
retainTime: string;
path: string;
localStorage: boolean;
session: boolean;
sameSite: "Strict" | "Lax" | "None";
requireSSL: boolean;
}
interface ICookieMonster<T extends Indexable<any>, K extends keyof T = keyof T> {
setCookie<S extends K>(key: S, value: T[S]): void;
getCookie<S extends K>(key: S): T[S];
eatCookie(key: K): void;
removeCookies(): void;
}
type InternalCookie<T> = T & {
};
class CookieMonster<T extends Indexable<any>, K extends keyof T = keyof T> implements ICookieMonster<T, K> {
private _defaultOptions: ICookieMonsterOptions<T> = {
name: "",
defaults: {} as T,
retainTime: "7d",
path: "",
localStorage: false,
session: false,
sameSite: 'Lax',
requireSSL: false
};
private _defaultsKeyIndexes: Indexable<number> = {};
private _options: ICookieMonsterOptions<T> = this._defaultOptions;
private _cookies: Partial<InternalCookie<T>> = {};
constructor(options?: Partial<ICookieMonsterOptions<T>>) {
this._options = {...this._defaultOptions, ... options};
assert(this._options.name !== "", "The Cookie Monster must have a name");
assert(Object.keys(this._options.defaults).length > 0, "Empty defaults object makes no sense");
this._defaultsKeyIndexes = Object.keys(this._options.defaults).reduce((p, c, i) => (p[c] = i, p), {} as Indexable<number>);
this._cookies = {...this._options.defaults };
this.openJar();
}
public setCookie<S extends K>(key: S, value: T[S]): void {
this._cookies[key] = value;
this.saveCookies();
}
public getCookie<S extends K>(key: S): T[S] {
return this._cookies[key]!;
}
public eatCookie(key: K): void {
this._cookies[key] = this._options.defaults[key];
this.saveCookies();
}
public removeCookies() {
if (this._options.localStorage) {
if (this._options.session) {
sessionStorage.removeItem(this._options.name);
} else {
localStorage.removeItem(this._options.name);
}
} else {
removeCookie(this._options.name, this._options.path, this._options.sameSite, this._options.requireSSL);
}
}
private saveCookies() {
if (this._options.localStorage) {
if (this._options.session) {
sessionStorage.setItem(this._options.name, this.makeRecipe(this._cookies));
} else {
localStorage.setItem(this._options.name, this.makeRecipe(this._cookies));
}
} else {
let expires: Date = getDate(this._options.retainTime);
setCookie(this._options.name, this.makeRecipe(this._cookies), expires, this._options.path, this._options.sameSite, this._options.requireSSL);
}
}
private makeRecipe(cookie: Partial<InternalCookie<T>>): string {
let essentials = transform<Partial<T>>(cookie, (acc, value, key) => {
if (value !== this._options.defaults[key]) {
(acc as Indexable<any>)[key] = value;
}
}, {});
let recipe = this.deflateNames(essentials);
return this.escape(JSON.stringify(recipe));
}
private deflateNames(essentials: Partial<T>) {
let recipe = transform<Indexable<any>>(essentials, (acc, value, key) => {
if (key in this._defaultsKeyIndexes) {
acc[this._defaultsKeyIndexes[key].toString()] = value;
}
}, {});
return recipe;
}
private inflateNames(recipe: Indexable<any>) {
let keyLookup = Object.keys(this._options.defaults);
let essentials = transform<Indexable<any>, Partial<InternalCookie<T>>>(recipe, (acc, value, key) => {
let index = parseInt(key as string, 10);
let isIndex = !isNaN(index) && index.toString() === key;
if (isIndex) {
(acc as Indexable<any>)[keyLookup[index]] = value;
}
}, { } as Partial<InternalCookie<T>>);
return essentials;
}
private bakeCookies(recipe: string): Partial<InternalCookie<T>> {
return {...this._options.defaults, ...this.inflateNames(JSON.parse(this.unescape(recipe)) as Indexable<any> )} as T;
}
private escape(str: string): string {
return str.replace(/;/g, "¤s").replace(/=/g, "¤e");
}
private unescape(str: string): string {
return str.replace(/¤s/g, ";").replace(/¤e/g, "=");
}
private openJar() {
let local_recipe = localStorage.getItem(this._options.name);
let session_recipe = sessionStorage.getItem(this._options.name);
let cookie_recipe = getCookie(this._options.name);
let recipe = (
this._options.localStorage ?
this._options.session ?
session_recipe :
local_recipe :
cookie_recipe);
this.vacuum();
if (recipe) {
let cookies = this.bakeCookies(recipe);
this._cookies = {...this._cookies, ...cookies};
this.removeCookies();
this.saveCookies();
}
}
private vacuum() {
localStorage.removeItem(this._options.name);
sessionStorage.removeItem(this._options.name);
removeCookie(this._options.name, this._options.path);
}
}
|
62d0e5489a1382a6377f44084372db35780ebc04 | TypeScript | staherianYMCA/test | /TypeScript/test/HelloWorldInTypeScript/HelloWorldInTypeScript/Scripts/ArrayVariables.ts | 4.25 | 4 | let arrayOfStrings = ["str1", "str2", "str3"];
// myStr="str1"
let myStr = arrayOfStrings[0];
// compiler error
// cannot assign an array of numbers
// to an array of string.
//arrayOfStrings = [1, 2, 3];
// can contain any types like List<object> in C#
let arrayOfAny: any[] = [1, "str2", false];
// for any[] reassigning to an array
// containing different types works fine
arrayOfAny = [true, 2, "str3"];
// another way to define array of strings
// by using Array<string>
let arrayOfStrings2: Array<string>;
// now arrayOfStrings2 contains ["str1", "str2", "str3", "str4"]
arrayOfStrings2 = [...arrayOfStrings, "str4"];
let i = 5; |
00ed0dc364a80bfbcdaa89dc0a5d8f555cee5e69 | TypeScript | si-saude/saude-app | /src/app/controller/gerencia/gerencia.filter.ts | 2.578125 | 3 | import { GenericFilter } from './../../generics/generic.filter';
import { EmpregadoFilter } from './../empregado/empregado.filter';
import { BooleanFilter } from './../../generics/boolean.filter';
export class GerenciaFilter extends GenericFilter {
private codigo: string;
private codigoCompleto: string;
private descricao: string;
private gerente: EmpregadoFilter;
private secretario1: EmpregadoFilter;
private secretario2: EmpregadoFilter;
private ausentePeriodico: BooleanFilter = new BooleanFilter();
public getCodigo() {
return this.codigo;
}
public setCodigo(c: string) {
this.codigo = c;
}
public getCodigoCompleto() {
return this.codigoCompleto;
}
public setCodigoCompleto(cc: string) {
this.codigoCompleto = cc;
}
public getDescricao() {
return this.descricao;
}
public setDescricao(d: string) {
this.descricao = d;
}
public getGerente():EmpregadoFilter{
return this.gerente;
}
public setGerente(g:EmpregadoFilter){
this.gerente = g;
}
public getSecretario1():EmpregadoFilter{
return this.secretario1;
}
public setSecretario1(s:EmpregadoFilter){
this.secretario1 = s;
}
public getSecretario2():EmpregadoFilter{
return this.secretario2;
}
public setSecretario2(s:EmpregadoFilter){
this.secretario2 = s;
}
public getAusentePeriodico():BooleanFilter{
return this.ausentePeriodico;
}
public setAusentePeriodico(ausentePeriodico:BooleanFilter){
this.ausentePeriodico = ausentePeriodico;
}
} |
67f7ab6ea6103cff0721c25b1dad24258db652a9 | TypeScript | samanthabroking/cadmus_web | /libs/parts/philology/philology-ui/src/lib/differ-result-to-msp-adapter.ts | 2.578125 | 3 | // library: https://www.npmjs.com/package/diff-match-patch
// types: https://www.npmjs.com/package/@types/diff-match-patch
import { MspOperation, MspOperator } from './msp-operation';
import { Diff, DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL } from 'diff-match-patch';
import { TextRange } from '@cadmus/core';
class DiffAndMsp {
diff: Diff;
msp: MspOperation;
}
const DIFF_OP = 0;
const DIFF_TXT = 1;
/**
* Misspelling adapter for Google diff-match-patch library.
*/
export class DifferResultToMspAdapter {
public isMovDisabled: boolean;
private mapDiffsWithReplacements(diffs: Diff[], output: DiffAndMsp[]) {
let start = 1;
for (let i = 0; i < diffs.length; i++) {
if (
diffs[i][DIFF_OP] === DIFF_DELETE &&
i + 1 < diffs.length &&
diffs[i + 1][DIFF_OP] === DIFF_INSERT
) {
const msp = new MspOperation();
msp.operator = MspOperator.replace;
msp.rangeA = new TextRange(start, diffs[i][DIFF_TXT].length);
msp.valueA = diffs[i][DIFF_TXT];
msp.valueB = diffs[i + 1][DIFF_TXT];
output.push({
diff: diffs[i],
msp: msp
});
start += diffs[i][DIFF_TXT].length;
i++;
} else {
output.push({
diff: diffs[i],
msp: null
});
if (
diffs[i][DIFF_OP] === DIFF_DELETE ||
diffs[i][DIFF_OP] === DIFF_EQUAL
) {
start += diffs[i][DIFF_TXT].length;
}
}
}
}
private detectMoves(mspDiffs: DiffAndMsp[]) {
// first look for INS..DEL
for (let i = 0; i < mspDiffs.length; i++) {
// for each INS:
if (mspDiffs[i].msp && mspDiffs[i].msp.operator === MspOperator.insert) {
const ins = mspDiffs[i].msp;
// find a DEL with the same value
let nextDel: DiffAndMsp = null;
for (let j = i + 1; j < mspDiffs.length; j++) {
if (
mspDiffs[j].msp &&
mspDiffs[j].msp.operator === MspOperator.delete &&
mspDiffs[j].msp.valueA === ins.valueB
) {
nextDel = mspDiffs[j];
break;
}
}
// if found, assume a MOV from DEL to INS
if (nextDel) {
const nextDelIndex = mspDiffs.indexOf(nextDel);
const del = mspDiffs[nextDelIndex].msp;
const mov = new MspOperation();
mov.operator = MspOperator.move;
mov.rangeA = del.rangeA;
mov.rangeB = ins.rangeA;
mov.valueA = del.valueA;
mspDiffs[nextDelIndex] = {
diff: mspDiffs[nextDelIndex].diff,
msp: mov
};
mspDiffs.splice(i, 1);
i--;
}
}
}
// then look for DEL..INS
for (let i = 0; i < mspDiffs.length; i++) {
// for each DEL:
if (mspDiffs[i].msp && mspDiffs[i].msp.operator === MspOperator.delete) {
// find an INS with the same value
const del = mspDiffs[i].msp;
let nextIns: DiffAndMsp = null;
for (let j = i + 1; j < mspDiffs.length; j++) {
if (
mspDiffs[j].msp &&
mspDiffs[j].msp.operator === MspOperator.insert &&
mspDiffs[j].msp.valueB === del.valueA
) {
nextIns = mspDiffs[j];
break;
}
}
// if found, assume a MOV from DEL to INS
if (nextIns) {
const ins = nextIns.msp;
const nextInsIndex = mspDiffs.indexOf(nextIns);
const mov = new MspOperation();
mov.operator = MspOperator.move;
mov.rangeA = del.rangeA;
mov.rangeB = ins.rangeA;
mov.valueA = del.valueA;
mspDiffs[i] = {
diff: mspDiffs[i].diff,
msp: mov
};
mspDiffs.splice(nextInsIndex, 1);
}
}
}
}
/**
* Adapt the diff-match-patch diffing result to a set of misspelling
* operations.
*
* @param result The diffing result.
* @returns An array of misspelling operations.
*/
public adapt(result: Diff[]): MspOperation[] {
if (!result) {
return [];
}
const mspDiffs: DiffAndMsp[] = [];
this.mapDiffsWithReplacements(result, mspDiffs);
let index = 0;
for (let i = 0; i < mspDiffs.length; i++) {
if (mspDiffs[i].msp) {
index += mspDiffs[i].msp.rangeA.length;
continue;
}
const md = mspDiffs[i];
switch (md.diff[DIFF_OP]) {
case DIFF_EQUAL:
index += md.diff[DIFF_TXT].length;
break;
case DIFF_DELETE:
const del = new MspOperation();
del.operator = MspOperator.delete;
del.rangeA = new TextRange(index + 1, md.diff[DIFF_TXT].length);
del.valueA = md.diff[DIFF_TXT];
mspDiffs[i] = {
diff: md.diff,
msp: del
};
index += md.diff[DIFF_TXT].length;
break;
case DIFF_INSERT:
const ins = new MspOperation();
ins.operator = MspOperator.insert;
ins.rangeA = new TextRange(index + 1, 0);
ins.valueB = md.diff[DIFF_TXT];
mspDiffs[i] = {
diff: md.diff,
msp: ins
};
break;
}
}
if (!this.isMovDisabled) {
this.detectMoves(mspDiffs);
}
return mspDiffs.filter(md => md.msp).map(md => md.msp);
}
}
|
14e9172d56b400b4937c81df450a96424fc41cfc | TypeScript | laden666666/my-doc-jsx | /src/docjsx/core/BasePlugin.ts | 2.953125 | 3 | /**
* 插件库的基础类
*/
export class BasePlugin {
//输出工具
blockNodeMap = {};
//输出工具
inlineNodeMap = {};
format = {}
constructor(){
}
/**
* 向插件库注册块级标签
* @param format 引擎
* @param name 标签名
* @param blockNode 块级标签扩展
*/
registerBlockNode(format, name, blockNode){
if(!this.format[format]){
this.format[format] = {
blockNodeMap : {},
inlineNodeMap : {},
}
}
this.format[format].blockNodeMap[name] = blockNode
}
/**
* 向插件库注册行内标签
* @param format 引擎
* @param name 标签名
* @param inlineNode 行内标签扩展
*/
registerInlineNode(format, name, inlineNode){
if(!this.format[format]){
this.format[format] = {
blockNodeMap : {},
inlineNodeMap : {},
}
}
this.format[format].inlineNodeMap[name] = inlineNode
}
} |
0b9e6dd7e726edaf68c75199f147ad09b0e7092b | TypeScript | wdcvalentin/product-checker | /src/index.ts | 2.75 | 3 | import axios from 'axios';
import cheerio from 'cheerio';
const AxiosInstance = axios.create();
const productIds = [
'PB00385045',
'PB00254175',
// 👇👇 is an error test
// 'PB99993070'
]
const logging = async (url: string, id: string) => {
const { productName, availability, price } = await getData(url, id);
console.log('price', price);
console.log('productName', productName);
console.log('availability : ', availability !== 'Rupture' ? true : false);
console.log('------------------------------------------------------------');
};
const getData = async (url: string, id: string) => {
try {
const response = await AxiosInstance.get(url);
const html = response.data;
const $ = cheerio.load(html);
if (!$('.title > h1').text()) {
return {
productName: null,
availability: null,
price: null,
}
}
const productName = $('.title > h1').text();
const availability = $('.content > div > span').text();
const price = $('.product-info > .wrap-aside > aside > .price >.price').text();
return {
productName,
availability,
price
}
} catch (error) {
productIds.filter(p_id => p_id !== id);
productIds.some(_id => _id === id)
console.log(`${url} is down`);
};
};
productIds.map(id => {
const url: string = `https://www.ldlc.com/fiche/${id}.html`;
getData(url, id);
// logging(url);
setInterval(() => {
logging(url, id);
}, 3000);
})
|
b9066b467f614d787268ffe10244f62f48a26e90 | TypeScript | wmelani/structured-schema-logger | /src/ILogger.ts | 2.53125 | 3 | import { ILoggingEntry } from "./ILoggingEntry";
export interface ILogger {
log(entry: ILoggingEntry): void;
error(entry: ILoggingEntry, error: Error): void;
}
|
2bc7aaec9c2700bc1a09c2b29ccaba4b7be4e15d | TypeScript | EnssureIT/broleto | /src/utils/getValue.ts | 3.34375 | 3 | export const getValueForBankType = (number: string, codeType: string) => {
let value = '0';
if (codeType === 'CODIGO DE BARRAS') {
value = number.substr(9, 10);
}
if (codeType === 'LINHA DIGITAVEL') {
value = number.substr(-8, 8);
}
return Number((parseInt(value, 10) / 100.0).toFixed(2));
};
export const getValueForAgreementType = (number: string, codeType: string) => {
let value = '0';
if (codeType === 'CODIGO DE BARRAS') {
value = number.substr(4, 11);
}
if (codeType === 'LINHA DIGITAVEL') {
value = `${number.substr(0, 11)}${number.substring(12)}`.substr(4, 11);
}
return Number((parseInt(value, 10) / 100.0).toFixed(2));
};
export const getValue = (
number: string,
type: 'BANCO' | 'ARRECADACAO' | string,
codeType: 'LINHA DIGITAVEL' | 'CODIGO DE BARRAS' | 'INVALIDO',
) => {
if (type === 'BANCO') return getValueForBankType(number, codeType);
if (type === 'ARRECADACAO') return getValueForAgreementType(number, codeType);
return 0;
};
|
eca9e890c24af78ca7be3ec2ecdc5df811d0dbf3 | TypeScript | DawidRubch/RockPaperScissorsGame | /rpsFrontEnd/rpsfe/src/core/socketUseCases/changePointsCount.ts | 2.53125 | 3 | import { Socket } from "../SocketClient/socket";
export const changePointsCount: (setPointsCount: any) => void = (
setPointsCount
) => {
let socket = Socket.socket;
if (socket) {
socket.on("pointsCount", (scoreCount: any) => {
setPointsCount(scoreCount);
});
}
};
|
abb943acc03897603e2b3ecb40e22daaf52392b7 | TypeScript | natura-cosmeticos/natds-js | /packages/web/src/Components/Snackbar/Snackbar.props.ts | 2.921875 | 3 | import { SnackbarProps, SnackbarOrigin } from '@material-ui/core/Snackbar'
export type HorizontalAnchorOrigin = SnackbarOrigin['horizontal'];
export type VerticalAnchorOrigin = SnackbarOrigin['vertical'];
export interface ISnackbarProps extends SnackbarProps {
/**
* The action to display.
*
* @optional
* @type node
*/
action?: SnackbarProps['action']
/**
* The anchor of the `Snackbar`.
* Defaults to `{ horizontal: "center", vertical: "bottom" }`
*
* @optional
* @type { horizontal: "left" | "center" | "right", vertical: "top" | "bottom" }
*/
anchorOrigin?: SnackbarProps['anchorOrigin']
/**
* The number of milliseconds to wait before automatically calling the `onClose` function.
*
* `onClose` should then set the state of the `open` prop to hide the `Snackbar`.
* This behavior is disabled by default with the `null` value.
*
* @default null
* @type number
*/
autoHideDuration?: SnackbarProps['autoHideDuration']
/**
* Replace the `SnackbarContent` component.
*
* @optional
* @type element
*/
children?: SnackbarProps['children']
/**
* Override or extend the styles applied to the component.
*
* @todo add link to Material UI CSS API
* @type object
*/
classes?: SnackbarProps['classes']
/**
* Props applied to the `ClickAwayListener` element.
*
* @type object
*/
ClickAwayListenerProps?: SnackbarProps['ClickAwayListenerProps']
/**
* Props applied to the `SnackbarContent` element.
*
* @type object
*/
ContentProps?: SnackbarProps['ContentProps']
/**
* If `true`, the `autoHideDuration` timer will expire even if the window is not focused.
*
* @default false
* @type bool
*/
disableWindowBlurListener?: SnackbarProps['disableWindowBlurListener']
/**
* When displaying multiple consecutive `Snackbar`s from a parent rendering a single `<Snackbar/>`,
*
* Add the `key` prop to ensure independent treatment of each message. e.g. `<Snackbar key={message} />`.
* Otherwise, the message may update-in-place and features such as `autoHideDuration` may be canceled.
*
* @example `<Snackbar key={message} />`
*
* @type any
*/
key?: SnackbarProps['key']
/**
* The message to display.
*
* @type node
*/
message?: SnackbarProps['message']
/**
* Callback fired when the component requests to be closed.
*
* Typically `onClose` is used to set state in the parent component, which is used to control the `Snackbar` `open` prop.
*
* Signature: `function(event: object, reason: string) => void`
*
* @param {object} event The event source of the `callback.reason`. Can be: `"timeout"` (`autoHideDuration` expired) or: `clickaway`.
* @param {string} reason The `reason` parameter can optionally be used to control the response to `onClose`, for example ignoring `clickaway`.
* @return {void}
*
* @optional
* @type func
*/
onClose?: SnackbarProps['onClose']
/**
* Callback fired before the transition is entering.
*
* @optional
* @type func
*/
onEnter?: SnackbarProps['onEnter']
/**
* Callback fired when the transition has entered.
*
* @optional
* @type func
*/
onEntered?: SnackbarProps['onEntered']
/**
* Callback fired when the transition is entering.
*
* @optional
* @type func
*/
onEntering?: SnackbarProps['onEntering']
/**
* Callback fired before the transition is exiting.
*
* @optional
* @type func
*/
onExit?: SnackbarProps['onExit']
/**
* Callback fired when the transition has exited.
*
* @optional
* @type func
*/
onExited?: SnackbarProps['onExited']
/**
* Callback fired when the transition is exiting.
*
* @optional
* @type func
*/
onExiting?: SnackbarProps['onExiting']
/**
* If `true`, `Snackbar` is open.
*
* @optional
* @type bool
*/
open?: SnackbarProps['open']
/**
* The number of milliseconds to wait before dismissing after user interaction.
*
* If `autoHideDuration` prop isn't specified, it does nothing.
* If `autoHideDuration` prop is specified but `resumeHideDuration` isn't, we default to `autoHideDuration` / 2 ms.
*
* @optional
* @type number
*/
resumeHideDuration?: SnackbarProps['resumeHideDuration']
/**
* The component used for the transition. Defaults to `Grow`.
*
* @optional
* @type element
*/
TransitionComponent?: SnackbarProps['TransitionComponent']
/**
* The duration for the transition, in milliseconds.
*
* You may specify a single timeout for all transitions, or individually with an `object`.
* Defaults to `{ enter: duration.enteringScreen, exit: duration.leavingScreen }`
*
* @type number | { enter?: number, exit?: number }
*/
transitionDuration?: SnackbarProps['transitionDuration']
/**
* Props applied to the Transition element.
*
* @type object
*/
TransitionProps?: SnackbarProps['TransitionProps']
}
|
5fea9eef6257dd8dc578465248156a33cdc54606 | TypeScript | mikelbua/AngularIpartek | /src/app/directives/HelloDirective.ts | 2.5625 | 3 | import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[subrayado]'
})
export class HelloDirective {
@Input() subrayado: string;
constructor(private element: ElementRef) {
} //contructor
@HostListener('mouseenter')
public onMouseEnter() {
debugger;
this.element.nativeElement.style.textDecoration = this.subrayado;
this.element.nativeElement.style.color = 'red';
}
@HostListener('mouseleave')
public onMouseLeave() {
this.element.nativeElement.style.backgroundColor = 'green';
this.element.nativeElement.style.textDecoration = 'none';
this.element.nativeElement.style.color = 'black';
}
} //HelloDirective
|
dbcd772831132a52e2416dd628d49f2b9459f50b | TypeScript | remoteambition/courier-react | /packages/react-inbox/src/actions/messages.ts | 2.515625 | 3 | export interface IGetMessagesParams {
after?: string;
isRead?: boolean;
}
export const QUERY_MESSAGES = `
query GetMessages($after: String, $isRead: Boolean){
messages(params: { isRead: $isRead }, after: $after) {
totalCount
pageInfo {
startCursor
hasNextPage
}
nodes {
id
messageId
created
read
content {
title
body
blocks {
... on TextBlock {
type
text
}
... on ActionBlock {
type
text
url
}
}
data
trackingIds {
clickTrackingId
deliverTrackingId
readTrackingId
unreadTrackingId
}
}
}
}
}
`;
export const getMessages = async (client, params?: IGetMessagesParams) => {
const results = await client.query(QUERY_MESSAGES, params);
const messages = results?.data?.messages?.nodes;
const startCursor = results?.data?.messages?.pageInfo?.startCursor;
return {
appendMessages: Boolean(params?.after),
messages,
startCursor,
};
};
|
973b9fcd76d152aeac614b62903b229808fbeba0 | TypeScript | NoManWorkingITPJMnage/sysurs-fe | /src/store/modules/user.ts | 2.53125 | 3 | import { Module } from 'vuex';
import httpClient from '@/utils/httpClient';
export interface UserState {
userProf: UserProfile | null;
isSignedIn: boolean;
}
export const userModule: Module<UserState, any> = {
namespaced: true,
state: () => ({
userProf: null,
isSignedIn: false,
}),
getters: {
isSignedIn(state) {
return state.isSignedIn;
},
},
mutations: {
setProfile(state, payload: UserProfile) {
state.userProf = payload;
state.isSignedIn = !!payload;
},
},
actions: {
async fetchProfile({ commit }) {
const res = await httpClient.get<UserProfile>('/user');
commit('setProfile', res.data);
},
},
};
|
fe59d8f0106de313fbf6e55a232863d067644638 | TypeScript | JamieFristrom/dungeonlife | /gamesrc/src/ReplicatedStorage/TS/CheatUtility.ts | 2.546875 | 3 | import { PlacesManifest } from "./PlacesManifest"
import { Whitelist } from "./Whitelist"
class CheatUtilityClass
{
// use : calling from Lua
PlayerWhitelisted( player: Player )
{
if( Whitelist.whitelist.find( (value)=> value === player.UserId )!==undefined )
return true;
let rank = 0
const [ success, msg ] = pcall( function() { rank = player.GetRankInGroup( PlacesManifest.getCurrentGame().groupId ) } )
if( !success )
warn( msg )
return rank >= 250 || ( player.UserId >= -8 && player.UserId <= -1 ) // 250 is the admin rank on the private group
}
}
const cheatUtilityClass = new CheatUtilityClass()
export = cheatUtilityClass
|
7c741d895563178734586e69fa482cb6d435301f | TypeScript | kjhwert/uber-eats-server | /src/entities/restaurant.entity.ts | 2.59375 | 3 | import { Field, ObjectType } from '@nestjs/graphql';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { IsOptional, IsString, Length } from 'class-validator';
@ObjectType()
@Entity()
export class Restaurant {
@Field(type => Number)
@PrimaryGeneratedColumn()
id: number;
@Field(type => String)
@Column()
@IsString()
@Length(2, 20)
name: string;
@Field(type => String, { nullable: true })
@Column({ nullable: true })
@IsString()
@IsOptional()
address: string;
@Field(type => String)
@Column()
@IsString()
@Length(2, 10)
ownersName: string;
}
|
8eeac9c60dcd5d36a80d71557bbe848a4e168dbd | TypeScript | nick-meier/travetto | /module/cache/src/decorator.ts | 2.5625 | 3 | import { CacheManager, CacheConfig } from './service';
type TypedMethodDecorator<U> = (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => U>) => void;
export function Cacheable<U>(config: Partial<CacheConfig<U>> & { dispose: (k: string, v: U) => any }, keyFn?: (...args: any[]) => string): TypedMethodDecorator<U>;
export function Cacheable(config: string | Partial<CacheConfig<any>>, keyFn?: (...args: any[]) => string): TypedMethodDecorator<any>;
export function Cacheable(config: string | Partial<CacheConfig<any>>, keyFn?: (...args: any[]) => string): TypedMethodDecorator<any> {
return function (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => any>) {
if (typeof config === 'string') {
config = {
namespace: config
};
}
descriptor.value = CacheManager.enableCaching(descriptor.value as Function, {
namespace: target.constructor,
name: propertyKey,
keyFn,
...config,
});
return descriptor;
};
} |
8bea00bfc5e2484b538c29b23a599ae855896ec9 | TypeScript | Flexicon/py-roadmap | /src/app/shared/data/resources.ts | 2.6875 | 3 | import { Topic } from '../models/topic.model';
export const topics: Topic[] = [
{
title: 'Numbers, Strings and Lists',
checklist: [
{ title: 'Removing whitespace from a string' },
{ title: 'Transforming text to uppercase and lowercase' },
{ title: 'Converting strings to integers' },
{ title: 'Replacing a portion of text with different text' },
{ title: 'Getting a portion of a string' },
{ title: 'Splitting a string into an array based on a character' },
{ title: 'Adding items to an array' },
{ title: 'Merging two or more arrays together' },
{ title: 'Filtering and transforming arrays' }
]
},
{
title: 'Variables, naming and Functions',
checklist: [
{ title: 'Variable/Constant naming formats' },
{ title: 'Function declarations' },
{ title: 'Understanding variable scope' },
{ title: 'Setting default values for function arguments' },
{ title: 'Lambdas' }
]
}
];
|
9d8627f0131c17f360760e3c63021f913d166be4 | TypeScript | yosbelms/fun2 | /dev-tools/util.ts | 2.578125 | 3 | export const hashMap: Map<string, string> = new Map()
export const hashMapFileName = 'hashMap.json'
export const mapToJson = (hashMap: Map<string, string>) => {
const obj: { [k: string]: string } = {}
for (let [key, value] of hashMap.entries()) {
obj[key] = value
}
return JSON.stringify(obj, null, 2)
}
|
386993ede07a587a8ed926a378832d35d424bd61 | TypeScript | TallerWebSolutions/dojo-tdd | /typescript/src/roman-numbers/index.ts | 3.796875 | 4 | export enum Numerals {
'I' = 1,
'V' = 5,
'X' = 10,
'L' = 50,
'C' = 100,
'D' = 500,
'M' = 1000
}
export const isAllowed = (numeral: string): boolean => !['IIII', 'XXXX', 'CCCC', 'MMMM'].some(
value => numeral.includes(value)
)
export const valueOf = (arg: string): number => {
if (!isAllowed(arg)) {
throw new Error('Invalid roman numeral')
}
const values: string[] = arg.split('')
const sumResult = values.reduce((carry, value, index) => {
if(Numerals[values[index + 1]] > Numerals[value]) {
return carry - Numerals[value]
}
return carry + Numerals[value]
}, 0)
return sumResult
}
|
cc99f6e9f2a24c6cc847c7aa55820f9aa4a9bdc9 | TypeScript | lilaw/bookshelf | /src/utils/listItems.ts | 3.015625 | 3 | /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { useClient } from "@/utils/client";
import type { item, HttpError } from "@/types";
import { isListItemsData, isItemData } from "@/type-guards";
import { areYouABadBody } from "@/utils/client";
import { queryClient } from "@/utils/QueryClient";
type updateItemPayload = {
id: string;
finishDate?: number | null;
rating?: number;
notes?: string;
};
type createItemPayload = { bookId: string };
type removeItmPayload = { id: string };
export function performListItems(): Promise<item[]> {
const client = useClient();
const listItems = queryClient.fetchQuery<item[], HttpError>(
"list-items",
() =>
client("list-items")
.then(areYouABadBody(isListItemsData))
.then((data) => data.listItems)
);
return listItems;
}
export function performListItem(bookId: string): Promise<item | undefined> {
return performListItems().then(
(listItems) => listItems.find((book) => book.bookId === bookId) ?? undefined
);
}
export function performCreateListItem(bookId: string) {
const client = useClient();
return queryClient.executeMutation<item, HttpError, createItemPayload>({
mutationFn: () => {
return client("list-items", {
data: { bookId },
method: "POST",
})
.then(areYouABadBody(isItemData))
.then((data) => data.listItem);
},
onSettled: () => queryClient.invalidateQueries("list-items"),
});
}
export function performRemoveListItem(listItemId: string) {
const client = useClient();
const remove = () => client(`list-items/${listItemId}`, { method: "DELETE" });
// remove return this type form serve. I don't think I will use it.
// type removeSuccessful = { success: true };
return queryClient.executeMutation<unknown, HttpError, removeItmPayload>({
mutationFn: remove,
onSettled: () => queryClient.invalidateQueries("list-items"),
});
}
export function perfermUdateListItem(payload: updateItemPayload) {
const client = useClient();
function perform(): Promise<item> {
return client(`list-items/${payload.id}`, {
data: payload,
method: "PUT",
})
.then(areYouABadBody(isItemData))
.then((data) => data.listItem);
}
function optimisticUpdate(): unknown {
const oldvalue = queryClient.getQueryData("list-items");
queryClient.setQueryData<item[]>(
"list-items",
function updateCache(listItems: item[] | undefined) {
if (typeof listItems === "undefined") return [];
return listItems.map((item) =>
item.id === payload.id ? { ...item, ...payload } : item
);
}
);
return oldvalue;
}
// just rollback whaterver previous cached value, I don't care what type you are. you are unknow. (this unknow probability is undefined or item. not sure)
return queryClient.executeMutation<
item,
HttpError,
updateItemPayload,
unknown
>({
mutationFn: perform,
onSettled: () => queryClient.invalidateQueries("list-items"),
onMutate: optimisticUpdate,
onError: (err, payload, oldvalue) => {
queryClient.setQueryData("list-items", oldvalue);
},
});
}
|
5c78df93a8e6ed373ae5db7ed3b69678e8324f3d | TypeScript | Starle21/FullStackOpen-exercises-part9-Typescript | /patientor_backend/src/utils.ts | 3.1875 | 3 | import {
NewPatient,
Gender,
EntryType,
NewEntryWithoutId,
Diagnose,
HealthCheckRating,
} from "./types";
const isString = (text: unknown): text is string => {
return typeof text === "string" || text instanceof String;
};
const parseName = (name: unknown): string => {
if (!name || !isString(name)) {
throw new Error("Incorrect or missing name");
}
return name;
};
const isDate = (date: string): boolean => {
return Boolean(Date.parse(date));
};
const parseDateOfBirth = (dateOfBirth: unknown): string => {
if (!dateOfBirth || !isString(dateOfBirth) || !isDate(dateOfBirth)) {
throw new Error("Incorrect or missing date: " + dateOfBirth);
}
return dateOfBirth;
};
const parseSsn = (ssn: unknown): string => {
if (!ssn || !isString(ssn)) {
throw new Error("Incorrect or missing ssn");
}
return ssn;
};
const parseOccupation = (occupation: unknown): string => {
if (!occupation || !isString(occupation)) {
throw new Error("Incorrect or missing occupation");
}
return occupation;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isGender = (param: any): param is Gender => {
return Object.values(Gender).includes(param);
};
const parseGender = (gender: unknown): Gender => {
if (!gender || !isGender(gender)) {
throw new Error("Incorrect or missing gender: " + gender);
}
return gender;
};
type Fields = {
name: unknown;
dateOfBirth: unknown;
ssn: unknown;
gender: unknown;
occupation: unknown;
entries: unknown;
};
export const toNewPatientEntry = ({
name,
dateOfBirth,
ssn,
gender,
occupation,
}: Fields): NewPatient => {
const newPatientEntry: NewPatient = {
name: parseName(name),
dateOfBirth: parseDateOfBirth(dateOfBirth),
ssn: parseSsn(ssn),
gender: parseGender(gender),
occupation: parseOccupation(occupation),
entries: [],
};
return newPatientEntry;
};
// // eslint-disable-next-line @typescript-eslint/no-explicit-any
// const isEntry = (param: any): param is Entry[] => {
// return Object.values(EntryType).includes(param.type);
// };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isType = (param: any): param is EntryType => {
return Object.values(EntryType).includes(param);
};
const parseType = (type: unknown): EntryType => {
if (!type || !isType(type)) {
throw new Error("Incorrect or missing entry type");
}
return type;
};
const parseDescription = (description: unknown): string => {
if (!description || !isString(description)) {
throw new Error("Incorrect or missing entry description");
}
return description;
};
const parseDate = (date: unknown): string => {
if (!date || !isString(date) || !isDate(date)) {
throw new Error("Incorrect or missing date: " + date);
}
console.log(date);
return date;
};
const parseSpecialist = (specialist: unknown): string => {
if (!specialist || !isString(specialist)) {
throw new Error("Incorrect or missing entry specialist");
}
return specialist;
};
const parseDiagnosisCodes = (codes: unknown): Array<Diagnose["code"]> => {
if (!Array.isArray(codes) || !codes.map((code) => isString(code))) {
throw new Error("Incorrect or missing entry of Diagnoses");
}
return codes as Array<Diagnose["code"]>;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isHealthCheck = (param: any): param is HealthCheckRating => {
return Object.values(HealthCheckRating).includes(param);
};
const parseHealthCheck = (rating: unknown): HealthCheckRating => {
if (rating === undefined || !isHealthCheck(rating)) {
throw new Error("Incorrect or missing health check rating: " + rating);
}
return rating;
};
const parseEmployerName = (employerName: unknown): string => {
if (!employerName || !isString(employerName)) {
throw new Error("Incorrect or missing employer's name: " + employerName);
}
return employerName;
};
function parseCriteria(criteria: unknown): string {
if (!criteria || !isString(criteria)) {
throw new Error("Incorrect or missing discharge criteria");
}
return criteria;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const toPatientMedicalRecord = (newEntry: any): NewEntryWithoutId => {
const newEntryParsed = {
type: parseType(newEntry.type),
description: parseDescription(newEntry.description),
date: parseDate(newEntry.date),
specialist: parseSpecialist(newEntry.specialist),
} as NewEntryWithoutId;
if (newEntry.diagnosisCodes) {
newEntryParsed.diagnosisCodes = parseDiagnosisCodes(
newEntry.diagnosisCodes
);
}
switch (newEntryParsed.type) {
case EntryType.HealthCheck:
newEntryParsed.healthCheckRating = parseHealthCheck(
newEntry.healthCheckRating
);
return newEntryParsed;
case EntryType.OccupationalHealthcare:
newEntryParsed.employerName = parseEmployerName(newEntry.employerName);
if (newEntry.sickLeave) {
newEntryParsed.sickLeave = {
startDate: parseDate(newEntry.sickLeave.startDate),
endDate: parseDate(newEntry.sickLeave.endDate),
};
}
return newEntryParsed;
case EntryType.Hospital:
newEntryParsed.discharge = {
date: parseDate(newEntry.discharge.date),
criteria: parseCriteria(newEntry.discharge.criteria),
};
return newEntryParsed;
default:
return assertNever(newEntryParsed);
}
};
const assertNever = (value: never): never => {
throw new Error(
`Unhandled discriminated union member: ${JSON.stringify(value)}`
);
};
|
2aae9590b5fc20d645d158357f121648bd4783b7 | TypeScript | NayeliZurita/image-processing | /src/ImageLocal.ts | 2.734375 | 3 | import { DefaultSettings } from "./DefaultSettings.js";
import { ImageOp } from "./ImageOp.js";
export class ImageLocal implements ImageOp {
//atributos
protected img: HTMLImageElement;
protected screen: CanvasRenderingContext2D;
protected readyToDraw: boolean;
protected isScaled: boolean;
// protected document: HTMLDocument;
public constructor(p: CanvasRenderingContext2D, ready?: boolean){
this.img = new Image();
this.screen = p;
// this.document = d;
this.readyToDraw = ready;
this.isScaled = false;
this.drawSmallImg = this.drawSmallImg.bind(this);
this.handleFileSelect = this.handleFileSelect.bind(this);
this.onload = this.onload.bind(this);
}
public handleFileSelect(evt:any):void {
let files: any;
if(evt.type === "drop") {
evt.stopPropagation();
evt.preventDefault();
files = evt.dataTransfer.files;
}
if(evt.type === "change")
files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
let output:any[] = [];
//console.log(evt)
let f:any = files[0];
output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate.toLocaleDateString(), '</li>');
this.img.src = f.name;
this.readyToDraw = true;
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
this.onload();
}
public drawSmallImg(evt:any):void{
let xPos:number = evt.offsetX-2;
let yPos: number = evt.offsetY - 2;
let pixel:ImageData = this.screen.getImageData(xPos, yPos, 1, 1);
if (this.readyToDraw) {
if (this.isScaled) {
xPos *= (this.img.width/DefaultSettings.SIZE_WIDTH);
yPos *= (this.img.height/DefaultSettings.SIZE_HEIGHT);
}
this.screen.clearRect(0, 0, DefaultSettings.SIZE_WIDTH, DefaultSettings.SIZE_HEIGHT);
this.screen.strokeStyle = "lightgray";
this.screen.imageSmoothingEnabled = false;
this.isScaled ?
this.screen.drawImage(this.img, 0, 0, DefaultSettings.SIZE_WIDTH, DefaultSettings.SIZE_HEIGHT)
: this.screen.drawImage(this.img, 0, 0, this.img.width, this.img.height);
this.screen.strokeRect(evt.offsetX+5, evt.offsetY+5, DefaultSettings.SMALL_W,DefaultSettings.SMALL_H);
this.screen.drawImage(this.img, Math.floor(xPos - 3), Math.floor(yPos - 3), 5, 5, evt.offsetX + 5, evt.offsetY + 5, DefaultSettings.SMALL_W, DefaultSettings.SMALL_H);
let color:HTMLElement = document.getElementById('color');
let data:Uint8ClampedArray = pixel.data;
let rgba = 'rgba(' + data[0] + ', ' + data[1] +
', ' + data[2] + ', ' + (data[3] / 255) + ')';
color.style.background = rgba;
//color.textContent = rgba;
document.getElementById('rgb').innerHTML = '<strong>'+ rgba + '</strong> ';
}
}
public getImage():HTMLImageElement{
return this.img;
}
public getScreen():CanvasRenderingContext2D{
return this.screen;
}
public setScaled(v:boolean):void{
this.isScaled = v;
}
public onload() {
this.getScreen().clearRect(0, 0, DefaultSettings.SIZE_WIDTH, DefaultSettings.SIZE_HEIGHT);
/** SI nuestro canvas es mas pequeño que la imagen se dibuja a su escala normal,
* si es mas grande se dibuja reescalado al ancho de ventana por default */
if (this.getImage().width > DefaultSettings.SIZE_WIDTH
|| this.getImage().height > DefaultSettings.SIZE_HEIGHT) {
this.getScreen().drawImage(this.getImage(), 0, 0, DefaultSettings.SIZE_WIDTH, DefaultSettings.SIZE_HEIGHT);
this.setScaled(true);
}
else {
this.getScreen().drawImage(this.getImage(), 0, 0, this.getImage().width, this.getImage().height);
this.setScaled(false);
}
}
} |
9e81318142b4464ecd35c70e0ce00002a1ba2aa0 | TypeScript | chefomar/no-data | /src/noDataInClassRule.ts | 3.0625 | 3 | import * as Lint from 'tslint';
import * as ts from 'typescript';
import { isClass } from './utils/isClass';
import { isClassProperty } from './utils/isClassProperty';
import { containsWord } from './utils/containsWord';
const ALLOW_CLASS_NAME = 'allow-class-name';
const ALLOW_CLASS_PROPERTIES = 'allow-class-properties';
interface NoDataInClassOptions {
allowClassProperties: boolean;
allowClassName: boolean;
}
export class Rule extends Lint.Rules.AbstractRule {
static readonly FAILURE_STRING = 'The word \"data\" is not allowed';
static readonly DISALLOWED_WORD = 'data';
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction<NoDataInClassOptions>(sourceFile, walk, {
allowClassName: this.ruleArguments.includes(ALLOW_CLASS_NAME),
allowClassProperties: this.ruleArguments.includes(ALLOW_CLASS_PROPERTIES),
});
}
}
function walk(context: Lint.WalkContext<NoDataInClassOptions>) {
ts.forEachChild(context.sourceFile, recur);
function recur(node: ts.Node) {
if (!context.options.allowClassName && isClass(node)) {
validateClassName(node as ts.ClassDeclaration, context);
}
if (!context.options.allowClassProperties && isClassProperty(node)) {
validatePropertyName(node as ts.PropertyDeclaration, context);
}
ts.forEachChild(node, recur);
}
}
function validateClassName(classDeclaration: ts.ClassDeclaration, context: Lint.WalkContext<NoDataInClassOptions>): void {
const classNameNode = classDeclaration.name;
const className = classNameNode.getText();
if (containsWord(className, Rule.DISALLOWED_WORD)) {
context.addFailureAtNode(classNameNode, Rule.FAILURE_STRING);
}
}
function validatePropertyName(propertyDeclaration: ts.PropertyDeclaration, context: Lint.WalkContext<NoDataInClassOptions>): void {
const propertyNameNode = propertyDeclaration.name;
const propertyName = propertyNameNode.getText();
if (containsWord(propertyName, Rule.DISALLOWED_WORD)) {
context.addFailureAtNode(propertyNameNode, Rule.FAILURE_STRING);
}
}
|
26fda236d331d5e95ca466be972eef007f25d9da | TypeScript | anishghosh103/ngrx-social-app | /src/app/store/auth/auth.reducer.ts | 2.765625 | 3 | import * as Auth from './auth.actions';
import { UserModel } from 'src/app/models/user.model';
export interface State {
loggedIn: boolean;
loading: boolean;
userData: UserModel;
}
export const initialState: State = {
loading: false,
loggedIn: false,
userData: null
};
export function AuthReducer(state = initialState, action: Auth.ActionsUnion) {
const { type } = action;
switch (type) {
case Auth.ActionTypes.LOGIN_INIT:
return {
...state,
loading: true
};
case Auth.ActionTypes.LOGIN_SUCCESS:
return {
...state,
loading: false,
loggedIn: true,
userData: action['payload']
}
case Auth.ActionTypes.LOGIN_FAILED:
return {
...state,
loading: false,
loggedIn: false,
userData: null
}
case Auth.ActionTypes.SIGNUP_INIT:
return {
...state,
loading: true
};
case Auth.ActionTypes.SIGNUP_SUCCESS:
return {
...state,
loading: false,
loggedIn: true,
userData: action['payload']
}
case Auth.ActionTypes.SIGNUP_FAILED:
return {
...state,
loading: false,
loggedIn: false,
userData: null
}
case Auth.ActionTypes.LOGOUT:
return initialState;
default:
return state;
}
} |
1967bada8f01ee2b9eb36d6f4fe236e39357d68c | TypeScript | levinean/journey_through_health | /journey-through-health-fend/src/app/types/event.ts | 2.515625 | 3 | import { Image } from './image';
import { Note } from './note';
export enum EVENT_TYPE {
APPOINTMENT = 'appointment',
SURGERY = 'surgery',
EXAM = 'exam',
TEST = 'test',
IMAGING = 'imaging',
}
export enum EVENT_PRIORITY {
HIGH = 'high',
MEDIUM = 'medium',
LOW = 'low',
}
export type Event = {
id: string;
patientId: string;
name: string;
description: string;
hospital: string;
created_at: string;
type: EVENT_TYPE;
priority: EVENT_PRIORITY;
notes: Note[];
images: Image[];
};
export type Filter = {
checked: boolean;
name: string;
searchParam: string;
};
export type SearchFilter = string;
|
18ae9111a603d9b2d3d5a5791a1eac0b04175301 | TypeScript | giladefrati/NearbyAttractions | /services/webapi.ts | 2.75 | 3 | import { Attraction } from "../interfaces"
const googleKey = 'AIzaSyBPWFwHrsgzYw36bl-ecghaFEqNuRuGDUg'
const googleURL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?`
//Create params sending the object to the generator URLSearchParams
export const getAttractions = async (params) => {
//adding key property to the request in order not to expose to users
params['key'] = googleKey
const parsedParams: string = new URLSearchParams(params).toString()
// Call an external API endpoint to get attractions and extract the 'results' section.
const res = await fetch(googleURL + parsedParams)
let data = await res.json()
const attractions: Attraction[] = data['results']
//adding for attraction an new imgURL field
// with his picture reference or 'not found' photo in case there's no one
attractions.forEach((attr) => {
const notFoundPhoto: string = 'https://www.publicdomainpictures.net/pictures/280000/velka/not-found-image-15383864787lu.jpg'
const googlePhotoURL: string =
attr['imgURL'] = !attr.photos || !attr.photos[0] ? notFoundPhoto :
`https://maps.googleapis.com/maps/api/place/photo?maxheight=400&key=${googleKey}&photoreference=${attr.photos[0].photo_reference}`
})
return attractions
}
|
164df1032a62b4d28306a6b767a0a94a3a5f5a6e | TypeScript | gabriel2302/anexos-sec-educacao | /src/modules/institutions/services/UpdateInstitutionService.ts | 2.75 | 3 | import AppError from '@shared/errors/AppError';
import { injectable, inject } from 'tsyringe';
import Institution from '../infra/typeorm/entities/Institution';
import IInstitutionsRepository from '../repositories/IInstitutionsRepository';
type IRequest = {
id: string;
name?: string;
director?: string;
learning_kind?: string;
};
@injectable()
class UpdateInstitutionService {
constructor(
@inject('InstitutionsRepository')
private institutiosRepository: IInstitutionsRepository,
) {}
public async execute({
id,
name,
director,
learning_kind,
}: IRequest): Promise<Institution> {
const institution = await this.institutiosRepository.findById(id);
if (!institution) {
throw new AppError('Institution not found');
}
if (name) {
const checkInstitutionExists =
await this.institutiosRepository.findByName(name);
if (checkInstitutionExists && checkInstitutionExists.id !== id) {
throw new AppError(`Institution name's already in use`);
}
institution.name = name;
}
if (director) {
institution.director = director;
}
if (learning_kind) {
institution.learning_kind = learning_kind;
}
await this.institutiosRepository.save(institution);
return institution;
}
}
export default UpdateInstitutionService;
|
3fc8d09cefc2cf1662fb8a11b64e66904dfc6e2e | TypeScript | chuoique/vlc-remote-control | /src/logger.ts | 2.578125 | 3 | "use strict";
interface Logger {
info: (message: string) => void;
error: (message: string) => void;
}
const logger: Logger = require("eazy-logger").Logger({
prefix: "{blue:[}{magenta:vlc-remote-control}{blue:] }",
useLevelPrefixes: true
});
export function logInfo(message: string): void {
logger.info(message);
}
export function logError(error: Error): void {
logger.error(error.message);
}
|
7643c5e1b6cfaa7e94fe478f23b6868d4ac2f092 | TypeScript | kalambo/rgo | /src/typings.ts | 2.640625 | 3 | export type Obj<T = any> = { [key: string]: T };
export type Falsy = false | null | undefined | void;
export type Scalar = 'boolean' | 'int' | 'float' | 'string' | 'date' | 'json';
export interface ScalarField {
scalar: Scalar;
isList?: true;
meta?: any;
}
export interface RelationField {
type: string;
isList?: true;
meta?: any;
}
export interface ForeignRelationField {
type: string;
foreign: string;
meta?: any;
}
export type Field = ScalarField | RelationField | ForeignRelationField;
export type Schema = Obj<Obj<Field>>;
export const fieldIs = {
scalar: (field: Field): field is ScalarField => {
return !!(field as ScalarField).scalar;
},
relation: (field: Field): field is RelationField => {
return (
!!(field as RelationField).type &&
!(field as ForeignRelationField).foreign
);
},
foreignRelation: (field: Field): field is ForeignRelationField => {
return (
!!(field as RelationField).type &&
!!(field as ForeignRelationField).foreign
);
},
};
export type RecordValue =
| boolean
| number
| string
| Date
| Obj
| boolean[]
| number[]
| string[]
| Date[]
| Obj[];
export type Record = Obj<RecordValue | null>;
export type Data<T = Record | null> = Obj<Obj<T>>;
export type ClientData = Data<
Obj<RecordValue | null | undefined> | null | undefined
>;
export type FilterOp = '=' | '!=' | '<' | '<=' | '>' | '>=' | 'in';
export interface Args<F = undefined, S = undefined> {
filter?: F | any[];
sort?: S | string[];
start?: number;
end?: number;
}
export interface Query extends Args<string | null, string> {
name: string;
alias?: string;
fields: (string | Query)[];
}
export interface ResolveQuery extends Args {
name: string;
alias?: string;
fields: (string | ResolveQuery)[];
extra?: { start: number; end: number };
trace?: { start: number; end?: number };
key?: string;
}
export interface QueryLayer {
root: { type?: string; field: string; alias?: string };
field: ForeignRelationField | RelationField;
args: Args;
fields: string[];
extra?: { start: number; end: number };
trace?: { start: number; end?: number };
path: string[];
key: string;
}
export type GetStart = (
layer: QueryLayer,
rootId: string,
recordIds: (string | null)[],
) => number;
export type DataChanges = Data<Obj<true>>;
export interface State {
server: Data<Record>;
client: Data;
combined: Data<Record>;
diff: Data<1 | -1 | 0>;
}
export interface FetchInfo {
name: string;
field: ForeignRelationField | RelationField;
args: Args;
fields: Obj<number>;
relations: Obj<FetchInfo>;
complete: {
data: {
fields: string[];
slice: { start: number; end?: number };
ids: string[];
};
firstIds: Obj<string | null>;
};
active: Obj<string[]>;
pending?: {
changing: string[];
data: {
fields: string[];
slice: { start: number; end?: number };
ids: string[];
};
};
}
export interface ResolveRequest {
commits?: Data[];
queries?: ResolveQuery[];
context?: Obj;
}
export interface ResolveResponse {
data: Data<Record>;
newIds: Data<string>;
errors: (string | null)[];
firstIds: Data<string | null>;
}
export type Resolver = (() => Promise<Schema>) &
((request: ResolveRequest) => Promise<ResolveResponse>);
export type Enhancer = (resolver: Resolver) => Resolver;
export interface Rgo {
schema: Schema;
flush(): void;
create(type: string): string;
query(): Promise<void>;
query(...queries: Query[]): Promise<Obj>;
query(...queries: (Query | ((data: Obj | null) => void))[]): () => void;
query(query: Query, onLoad: (data: Obj | null) => void): () => void;
query(
query1: Query,
query2: Query,
onLoad: (data: Obj | null) => void,
): () => void;
query(
query1: Query,
query2: Query,
query3: Query,
onLoad: (data: Obj | null) => void,
): () => void;
query(
query1: Query,
query2: Query,
query3: Query,
query4: Query,
onLoad: (data: Obj | null) => void,
): () => void;
query(
query1: Query,
query2: Query,
query3: Query,
query4: Query,
query5: Query,
onLoad: (data: Obj | null) => void,
): () => void;
set(
...values: (
| { key: [string, string, string]; value: RecordValue | null | undefined }
| { key: [string, string]; value: null | undefined })[]
): void;
commit(
...keys: ([string, string] | [string, string, string])[]
): Promise<Data<string>>;
}
|
0a310dbef38115fc7339db5095d079a8a96abe02 | TypeScript | AndrewJBateman/angular-tutorial-assignments | /section26-animations/src/app/app.component.ts | 2.59375 | 3 | import { Component } from '@angular/core';
import { trigger, state, style, transition, animate, keyframes, group } from '@angular/animations';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
animations: [
trigger('divState', [
state('normal', style({
'background-color': 'red',
transform: 'translateX(0)'
})),
state('highlighted', style({
'background-color': 'blue',
transform: 'translateX(100px)'
})),
transition('normal <=> highlighted', animate(300)),
// transition('highlighted => normal', animate(300))
]),
trigger('wildState', [
state('normal', style({
'background-color': 'red',
transform: 'translateX(0) scale(1)'
})),
state('highlighted', style({
'background-color': 'blue',
transform: 'translateX(100px) scale(1)'
})),
state('shrunken', style({
'background-color': 'green',
transform: 'translateX(0) scale(0.5)'
})),
transition('normal => highlighted', animate(300)),
transition('highlighted => normal', animate(800)),
transition('shrunken <=> *', [
style({
'background-color': 'orange'
}),
animate(1000, style({
borderRadius: '50px'
})),
animate(500)
])
]),
trigger('list1', [
state('in', style({
opacity: 1,
transform: 'translateX(0)'
})),
transition('void => *', [
style({
opacity: 0,
transform: 'translateX(-100px)'
}),
animate(300)
]),
transition('* => void', [
animate(300, style({
transform: 'translateX(100px)',
opacity: 0
}))
])
]),
trigger('list2', [
state('in', style({
opacity: 1,
transform: 'translateX(0)'
})),
transition('void => *', [
animate(1000, keyframes([
style({
transform: 'translateX(-100px)',
opacity: 0,
offset: 0
}),
style({
transform: 'translateX(-50px)',
opacity: 0.5,
offset: 0.3
}),
style({
transform: 'translateX(-20px)',
opacity: 1,
offset: 0.8
}),
style({
transform: 'translateX(0)',
opacity: 1,
offset: 1
})
]))
]),
transition('* => void', [
group([
animate(300, style({
color: 'red'
})),
animate(800, style({
transform: 'translateX(100px)',
opacity: 0
}))
])
])
]),
]
})
export class AppComponent {
state = 'normal';
wildState = 'normal';
list = ['Milk', 'Sugar', 'Bread'];
onAnimate() {
this.state == 'normal' ? this.state = 'highlighted' : this.state = 'normal';
this.wildState == 'normal' ? this.wildState = 'highlighted' : this.wildState = 'normal';
}
onShrink() {
this.wildState = 'shrunken';
}
onAdd(item) {
this.list.push(item);
}
onDelete(item) {
this.list.splice(this.list.indexOf(item), 1);
}
animationStarted(event) {
console.log(event);
}
animationEnded(event) {
console.log(event);
}
}
|
dc88d8110072bebf261454cfd4d398c65c6bd552 | TypeScript | G0ldenSp00n/tscoin | /src/commmands/ProveWorkCommand.ts | 2.609375 | 3 | import hash from 'object-hash';
import {Block} from "../entities/Block";
import {performance} from 'perf_hooks';
const DIFFICULTY = 4;
export default class ProveWorkCommand {
constructor() {
}
async prepare(): Promise<void> {
}
static run({
block
}: {
block: Block
}) {
let foundNonce = false;
let nonce = 0;
while(!foundNonce) {
const objHash = hash(block);
const hashCheck = objHash.slice(-DIFFICULTY);
if (hashCheck === new Array(DIFFICULTY + 1).join("0")) {
foundNonce = true;
break;
}
nonce += 1;
block.nonce = ""+nonce;
}
return block;
}
async persist(): Promise<void> {
}
execute(block: Block): Block {
//await this.prepare();
return ProveWorkCommand.run({ block });
//await this.persist();
}
}
|
f1b94174bc28f31658f23e1b454347fa8b7f2bb2 | TypeScript | ExtraHop/controlled-input | /src/interface.ts | 3.5625 | 4 | /**
* Type definition for `ControlledInput#onChange`.
*
* * The first argument must always be a complete new value
* * The second argument must always be the `name` of the field in the
* parent that should be updated.
*/
export type ChangeHandler<T> = (newVal: T, name?: string) => void;
/**
* A change handler for any field of a specific type.
*/
export type FieldChangeHandler<T> = ChangeHandler<T[keyof T]>;
/**
* Props for an externally-controlled user input component.
* The component should accept a value of `T` and then report changes to
* that value via the `onChange` function.
*
* It is **required** that `ControlledInput` components support the disabled state;
* a `ControlledInput` component must be visibly not accepting user input when the
* prop is `true`.
*
* See `practices/inputs.md` in depot-ui for the full guide of how to use
* `ControlledInput`, including an example of composition of controlled inputs.
*/
export interface ControlledInput<T> {
/**
* The name of the controlled component. If specified, this must be passed
* as the second argument to the `onChange` handler.
*/
name?: string;
/**
* Callback invoked when user input may have altered the value of
* the component. For non-primitive types, it is required that the
* instance of `T` be a new object so that deep comparison is not
* needed to trigger component rendering updates.
*
* In some cases, the user may have to take multiple actions for a new
* value to be emitted; for example, filtering in a dropdown may have
* multiple keystrokes before the user selection is changed.
*/
onChange?: ChangeHandler<T>;
/**
* The current value of the controlled component.
*
* In general, this should not be `undefined`; that typically identifies
* uncontrolled components. When an absence of a value is supported by
* the component, `null` is a better signifier as it cannot be mistaken
* for the absence of a key in an object.
*/
value: T;
/**
* When `true`, the component must not emit `onChange` events and must
* present as readonly to the user.
*/
disabled?: boolean;
}
|
3701fca24ea5db4535e2bd630fd29f731f45ab37 | TypeScript | martin-helmich/kube-mail | /src/util.ts | 2.859375 | 3 | import {Readable, Stream} from "stream";
export const readStreamIntoBuffer = (stream: Readable): Promise<Buffer> => {
return new Promise((res, rej) => {
const buffers: Buffer[] = [];
stream.on("data", chunk => {
if (!(chunk instanceof Buffer)) {
chunk = Buffer.from(chunk, "utf-8");
}
buffers.push(chunk);
});
stream.on("end", () => {
res(Buffer.concat(buffers));
});
stream.on("error", rej);
});
};
export declare class TypedStream<T> extends Stream {
on(event: "data", callback: (obj: T) => any): any;
on(event: "end", callback: () => any): any;
on(event: "error", callback: (err: Error) => any): any;
}
|
6007264cf84d1fb22bd76faebb08f1d5eccd07b4 | TypeScript | dgreene1/virtual-alexa | /src/core/SkillRequest.ts | 2.546875 | 3 | import * as uuid from "uuid";
import {AudioPlayerActivity} from "../audioPlayer/AudioPlayer";
import {SlotValue} from "../impl/SlotValue";
import {UserIntent} from "../impl/UserIntent";
import {SkillContext} from "./SkillContext";
export class RequestType {
public static DISPLAY_ELEMENT_SELECTED_REQUEST = "Display.ElementSelected";
public static INTENT_REQUEST = "IntentRequest";
public static LAUNCH_REQUEST = "LaunchRequest";
public static SESSION_ENDED_REQUEST = "SessionEndedRequest";
public static AUDIO_PLAYER_PLAYBACK_FINISHED = "AudioPlayer.PlaybackFinished";
public static AUDIO_PLAYER_PLAYBACK_NEARLY_FINISHED = "AudioPlayer.PlaybackNearlyFinished";
public static AUDIO_PLAYER_PLAYBACK_STARTED = "AudioPlayer.PlaybackStarted";
public static AUDIO_PLAYER_PLAYBACK_STOPPED = "AudioPlayer.PlaybackStopped";
}
export enum SessionEndedReason {
ERROR,
EXCEEDED_MAX_REPROMPTS,
USER_INITIATED,
}
/**
* Creates a the JSON for a Service Request programmatically
*/
export class SkillRequest {
/**
* The timestamp is a normal JS timestamp without the milliseconds
*/
private static timestamp() {
const timestamp = new Date().toISOString();
return timestamp.substring(0, 19) + "Z";
}
private static requestID() {
return "amzn1.echo-external.request." + uuid.v4();
}
private requestJSON: any = null;
private requestType: string;
public constructor(private context: SkillContext) {}
/**
* Generates an intentName request with the specified IntentName
* @param intentName
* @returns {SkillRequest}
*/
public intentRequest(intent: UserIntent): SkillRequest {
const intentName = intent.name;
const isBuiltin = intentName.startsWith("AMAZON");
if (!isBuiltin) {
if (!this.context.interactionModel().hasIntent(intentName)) {
throw new Error("Interaction model has no intentName named: " + intentName);
}
}
this.requestJSON = this.baseRequest(RequestType.INTENT_REQUEST);
this.requestJSON.request.intent = {
name: intentName,
};
const slots = intent.slots();
if (Object.keys(slots).length > 0) {
this.requestJSON.request.intent.slots = slots;
}
// Add in the dialog info
if (this.context.dialogManager().isDialog()) {
this.requestJSON.request.dialogState = this.context.dialogManager().dialogState();
this.requestJSON.request.intent.confirmationStatus = this.context.dialogManager().confirmationStatus();
// Since the dialog manager has an incomplete slot view, we merge it in with the complete list
this.mergeSlots(this.requestJSON.request.intent.slots, this.context.dialogManager().slots());
}
return this;
}
public audioPlayerRequest(requestType: string, token: string, offsetInMilliseconds: number): SkillRequest {
this.requestJSON = this.baseRequest(requestType);
this.requestJSON.request.token = token;
this.requestJSON.request.offsetInMilliseconds = offsetInMilliseconds;
return this;
}
public elementSelectedRequest(token: any): SkillRequest {
this.requestJSON = this.baseRequest(RequestType.DISPLAY_ELEMENT_SELECTED_REQUEST);
this.requestJSON.request.token = token;
return this;
}
public launchRequest(): SkillRequest {
this.requestJSON = this.baseRequest(RequestType.LAUNCH_REQUEST);
return this;
}
public sessionEndedRequest(reason: SessionEndedReason, errorData?: any): SkillRequest {
this.requestJSON = this.baseRequest(RequestType.SESSION_ENDED_REQUEST);
this.requestJSON.request.reason = SessionEndedReason[reason];
if (errorData !== undefined && errorData !== null) {
this.requestJSON.request.error = errorData;
}
return this;
}
public requiresSession(): boolean {
// LaunchRequests and IntentRequests both require a session
// We also force a session on a session ended request, as if someone requests a session end
// we will make one first if there is not. It will then be ended.
return (this.requestType === RequestType.LAUNCH_REQUEST
|| this.requestType === RequestType.DISPLAY_ELEMENT_SELECTED_REQUEST
|| this.requestType === RequestType.INTENT_REQUEST
|| this.requestType === RequestType.SESSION_ENDED_REQUEST);
}
public toJSON() {
const applicationID = this.context.applicationID();
// If we have a session, set the info
if (this.requiresSession() && this.context.activeSession()) {
const session = this.context.session();
const newSession = session.isNew();
const sessionID = session.id();
const attributes = session.attributes();
this.requestJSON.session = {
application: {
applicationId: applicationID,
},
new: newSession,
sessionId: sessionID,
user: this.userObject(this.context),
};
if (this.requestType !== RequestType.LAUNCH_REQUEST) {
this.requestJSON.session.attributes = attributes;
}
if (this.context.accessToken() !== null) {
this.requestJSON.session.user.accessToken = this.context.accessToken();
}
}
// For intent, launch and session ended requests, send the audio player state if there is one
if (this.requiresSession()) {
if (this.context.device().audioPlayerSupported()) {
const activity = AudioPlayerActivity[this.context.audioPlayer().playerActivity()];
this.requestJSON.context.AudioPlayer = {
playerActivity: activity,
};
// Anything other than IDLE, we send token and offset
if (this.context.audioPlayer().playerActivity() !== AudioPlayerActivity.IDLE) {
const playing = this.context.audioPlayer().playing();
this.requestJSON.context.AudioPlayer.token = playing.stream.token;
this.requestJSON.context.AudioPlayer.offsetInMilliseconds = playing.stream.offsetInMilliseconds;
}
}
}
return this.requestJSON;
}
private mergeSlots(slotsTarget: {[id: string]: SlotValue}, slotsSource: {[id: string]: SlotValue}) {
for (const sourceSlot of Object.keys(slotsSource)) {
slotsTarget[sourceSlot] = slotsSource[sourceSlot];
}
}
private baseRequest(requestType: string): any {
this.requestType = requestType;
const applicationID = this.context.applicationID();
const requestID = SkillRequest.requestID();
const timestamp = SkillRequest.timestamp();
// First create the header part of the request
const baseRequest: any = {
context: {
System: {
application: {
applicationId: applicationID,
},
device: {
supportedInterfaces: this.context.device().supportedInterfaces(),
},
user: this.userObject(this.context),
},
},
request: {
locale: this.context.locale(),
requestId: requestID,
timestamp,
type: requestType,
},
version: "1.0",
};
// If the device ID is set, we set the API endpoint and deviceId properties
if (this.context.device().id()) {
baseRequest.context.System.apiAccessToken = this.context.apiAccessToken();
baseRequest.context.System.apiEndpoint = this.context.apiEndpoint();
baseRequest.context.System.device.deviceId = this.context.device().id();
}
if (this.context.accessToken() !== null) {
baseRequest.context.System.user.accessToken = this.context.accessToken();
}
// If display enabled, we add a display object to context
if (this.context.device().displaySupported()) {
baseRequest.context.Display = {};
}
return baseRequest;
}
private userObject(context: SkillContext): any {
const o: any = {
userId: context.user().id(),
};
// If we have a device ID, means we have permissions enabled and a consent token
if (context.device().id()) {
o.permissions = {
consentToken: uuid.v4(),
};
}
return o;
}
}
|
6b8d51371afe32419f977e44d218c707aedc85f8 | TypeScript | rohit-enzigma/Node_Asynchronous | /Model/RetriveUser.ts | 2.703125 | 3 | import * as Promise from 'promise';
let fs = require('fs');
//Retriving data from userDetails file.
export function retrieveUs() {
return new Promise(
function (resolve: any, reject:any) {
let entry = 1;
if(entry == 1) {
console.log('Entered in Retrieve promise block');
let rawdata = fs.readFileSync('./Model/userDetails.json');
let user = JSON.parse(rawdata);
resolve(user);
}
else {
reject("Something Might Gone Wrong");
}
}
);
} |
bfc3f505c3f3c3f1fba7ca6e5067f33559425806 | TypeScript | esthermsama/Curso-Javascript-e-Ionic | /mistabs/src/app/tab2/tab2.page.ts | 2.78125 | 3 | import { Component } from '@angular/core';
import { Imc } from '../imc';
import { TIMC } from '../timc.enum';
@Component({
selector: 'app-tab2',
templateUrl: 'tab2.page.html',
styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
private imc: Imc;
private static readonly FOTO_DELGADO: string = "assets/delgado.jpg";
private static readonly FOTO_DESNUTRIDO: string = "assets/desnutrido.jpg";
private static readonly FOTO_IDEAL: string = "assets/ideal.jpg";
private static readonly FOTO_SOBREPESO: string = "assets/sobrepeso.jpg";
private static readonly FOTO_OBESO: string = "assets/obeso.png";
private arrayImc: Array<Imc>; //declaro el array
constructor() {
this.imc = new Imc();
this.arrayImc = new Array<Imc>(); //creo la lista
}
ngOnInit() {
}
private obtenerImagen(tipoIMC: TIMC): string {
let ruta_foto: string;
switch (tipoIMC) {
case TIMC.DELGADO: ruta_foto = Tab2Page.FOTO_DELGADO; break;
case TIMC.DESNUTRIDO: ruta_foto = Tab2Page.FOTO_DESNUTRIDO; break;
case TIMC.IDEAL: ruta_foto = Tab2Page.FOTO_IDEAL; break;
case TIMC.SOBREPESO: ruta_foto = Tab2Page.FOTO_SOBREPESO; break;
case TIMC.OBESO: ruta_foto = Tab2Page.FOTO_OBESO; break;
}
return ruta_foto;
}
private obtenerIMCNominal(numimc: number): TIMC {
let tipoIMC: TIMC;
if (numimc < 16) {
tipoIMC = TIMC.DESNUTRIDO;
} else if (numimc >= 16 && numimc < 18) {
tipoIMC = TIMC.DELGADO;
} else if (numimc >= 18 && numimc < 25) {
tipoIMC = TIMC.IDEAL;
} else if (numimc >= 25 && numimc < 31) {
tipoIMC = TIMC.SOBREPESO;
} else {
tipoIMC = TIMC.OBESO;
}
return tipoIMC;
}
calcularIMC() {
let valornumimc = this.imc.peso / (this.imc.altura * this.imc.altura);
this.imc.nominal = this.obtenerIMCNominal(valornumimc);
this.imc.foto = this.obtenerImagen(this.imc.nominal);
console.log(this.imc.nominal);
console.log(this.imc.foto);
// Creo el nuevo elemento del array
let imcAux = new Imc();
imcAux.nominal = this.imc.nominal;
imcAux.peso = this.imc.peso;
imcAux.altura = this.imc.altura;
imcAux.foto = this.imc.foto;
// Introducirlo
this.arrayImc.push(imcAux);
console.log(`El array es ${this.arrayImc}`);
}
mostrarArray() {
for (let oimc of this.arrayImc) {
console.log(`altura ${oimc.altura}`);
console.log(`peso ${oimc.peso}`);
console.log(`imc ${oimc.nominal}`);
console.log(`foto ${oimc.foto}`);
console.log("-------------"); //separador
}
}
borrar(){
this.arrayImc.length = 0;
}
ordenarPeso(){
console.log("ordenar por pero ... ");
this.arrayImc.sort((a,b) => (a.peso - b.peso)
);
}
ordenarAltura(){
console.log("ordenar por altura ... ");
this.arrayImc.sort((a,b)=>(a.altura - b.altura)
);
}
}
|
51d76ae4ccb1a11e653e21a970d5c6d8d5508db2 | TypeScript | Findus23/nn_evaluate | /typescript/ui.ts | 2.609375 | 3 | import {calculate_grid} from "./calc";
import {valuesToImage} from "./utils";
import throttle from "lodash/throttle"
export const massExpEl = <HTMLInputElement>document.getElementById("massExp")
export const gammaPercentEl = <HTMLInputElement>document.getElementById("gammaPercent")
export const wtFractionEl = <HTMLInputElement>document.getElementById("wtFraction")
export const wpFractionEl = <HTMLInputElement>document.getElementById("wpFraction")
export const resolutionEl = <HTMLInputElement>document.getElementById("resolution")
export const smoothEl = <HTMLInputElement>document.getElementById("smooth")
export const modeEl = <HTMLSelectElement>document.getElementById("mode")
export const massExpLabel = document.getElementById("massExpLabel")
export const gammaPercentLabel = document.getElementById("gammaPercentLabel")
export const resolutionLabel = document.getElementById("resolutionLabel")
export const wtFractionLabel = document.getElementById("wtFractionLabel")
export const wpFractionLabel = document.getElementById("wpFractionLabel")
export const canvas = <HTMLCanvasElement>document.getElementById("outputCanvas")
function update(): void {
if (smoothEl.checked) {
canvas.classList.remove("crisp")
} else {
canvas.classList.add("crisp")
}
const mass = Math.pow(10, Number(massExpEl.value))
massExpLabel.innerText = mass.toExponential(3) + " kg"
console.log(mass.toFixed(3))
const gamma = Number(gammaPercentEl.value) / 100
gammaPercentLabel.innerText = gamma.toFixed(4)
const wtFraction = Math.pow(10, Number(wtFractionEl.value))
wtFractionLabel.innerText = wtFraction.toExponential(4)
const wpFraction = Math.pow(10, Number(wpFractionEl.value))
wpFractionLabel.innerText = wpFraction.toExponential(4)
const resolution = Number(resolutionEl.value)
resolutionLabel.innerText = resolution.toString() + " px"
const mode = Number(modeEl.value)
const output = calculate_grid(mass, gamma, wpFraction, wtFraction, resolution, mode)
const image = new ImageData(valuesToImage(output), resolution, resolution)
const context = canvas.getContext('2d')
context.canvas.width = resolution;
context.canvas.height = resolution;
context.putImageData(image, 0, 0);
}
export function init(): void {
const start = performance.now()
update()
const end = performance.now()
const testTime = end - start
console.info(`initial run took ${testTime}ms`)
const throttled = throttle(update, testTime)
const type = (testTime > 500) ? "change" : "input"
massExpEl.addEventListener(type, throttled)
gammaPercentEl.addEventListener(type, throttled)
wtFractionEl.addEventListener(type, throttled)
wpFractionEl.addEventListener(type, throttled)
resolutionEl.addEventListener(type, throttled)
smoothEl.addEventListener("change", throttled)
modeEl.addEventListener("change", throttled)
}
|
d8232d099296d4c036edcfd6e2c52a73220984d4 | TypeScript | Fabienraza/Angular_PremierProjetAngular | /src/app/update-hopital/update-hopital.component.ts | 2.515625 | 3 | import { Component, OnInit } from '@angular/core';
import { HopitalService } from '../services/hopital.service';
import { Hopital } from '../models/hopital';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-update-hopital',
templateUrl: './update-hopital.component.html',
styleUrls: ['./update-hopital.component.css']
})
export class UpdateHopitalComponent implements OnInit {
hopital : Hopital = new Hopital();
// Variable permettant de stocker l'id saisi dans la barre d'URL
idHopitalURL : number;
constructor(private hopitalservice : HopitalService , private route : ActivatedRoute) {
// Recuperation de l'iD saisi sur l'URL
this.idHopitalURL = parseInt(this.route.snapshot.paramMap.get('idHop'));
//'id': correspond au paramètre saisi dans la route.
// this.route.snapshot.paramMap.get() : retourne un objet de type String, d'ou la necessite de le convertir en un entier.
}
// Methode pour modifier les donnees de l'hopital
modifHopital(idHopitalURL : number , hopital : Hopital) {
this.hopitalservice.updateHopital(idHopitalURL , hopital).subscribe(
data => {
console.log("Modification reussie");
console.log(data);
}
)
}
ngOnInit(): void {
// Test si recuperation effectué de l'id
console.log(this.idHopitalURL);
//Recupération de l'objet hopital suivant l'id
this.hopitalservice.findHopital(this.idHopitalURL).subscribe(
data => {
this.hopital = data;
}
)
}
}
|
1b5cf10b85667fbc468c23d78b7c1354c22cc064 | TypeScript | jowsy/classical-music-timeline | /src/core/ParameterGroup.ts | 2.71875 | 3 | import { TimeLineBase, TimeLineGeometry } from ".";
export class ParameterGroup<T> {
key:T;
items:TimeLineBase[];
constructor(key:T, items:TimeLineBase[]){
this.key = key;
this.items = items;
}
getXValues() : number[] {
var initial : number[] = [];
this.items.forEach(item => {
if (item instanceof TimeLineGeometry){
initial.push(item.shape.x);
}
});
return initial;
}
} |
c4bf513d7ad6a1ac3b0ee0471799d93f93cc3f5a | TypeScript | D-Brown-Management/Advent-Of-Code-2016 | /Day1JS/app.ts | 3.25 | 3 | import fs = require("fs");
import readline = require('readline');
const inputArray = readInputArray('input.txt');
let currentDirection = 0;
let currentPosition = <Position>{
x: 0,
y: 0
};
let positionArray = [];
positionArray.push({ x: 0, y: 0 });
let firstCrossFound = false;
for (let i = 0; i < inputArray.length; i++) {
const dirChar = inputArray[i].trim().charAt(0);
// set new direction
switch (dirChar) {
case "L":
if (currentDirection > 0) {
currentDirection = (currentDirection - 1) % 4;
}
else {
currentDirection = 3;
}
break;
case "R":
currentDirection = (currentDirection + 1) % 4;
break;
}
const spaces = parseInt(inputArray[i].trim().substring(1));
for (let i = 0; i < spaces; i++) {
// move spaces
switch (currentDirection) {
case 0:
currentPosition.y += 1;
break;
case 1:
currentPosition.x += 1;
break;
case 2:
currentPosition.y -= 1;
break;
case 3:
currentPosition.x -= 1;
break;
}
const posMap = { x: currentPosition.x, y: currentPosition.y };
const pospos = positionArray.find(function (elem) {
return elem.x === posMap.x && elem.y === posMap.y;
});
if (!pospos) {
positionArray.push(posMap);
} else {
if (!firstCrossFound) {
let part2Answer = Math.abs(posMap.x) + Math.abs(posMap.y);
console.log("Part 2 Found:", part2Answer);
firstCrossFound = true;
}
}
}
}
console.log("Part1 Location: ", Math.abs(currentPosition.x) + Math.abs(currentPosition.y));
finishApp();
function readInputArray(filename: string): Array<string> {
var file = fs.readFileSync('input.txt', { encoding: 'utf8' });
var directionArray = file.split(',');
return directionArray;
}
function finishApp(): void {
console.log('Press any key to continue...');
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
}
interface Position {
x: number;
y: number;
}
|
f1a38a2dc70b689c70458e46e710082d98b19b54 | TypeScript | Streeterxs/livrariaDigitalFront | /src/Services/Utils/utils.ts | 2.796875 | 3 | export const enumToObjArrayWithNumbers = (enumToTransform: any, keyName: string, valueKey: string) => {
return Object.keys(enumToTransform)
.filter(key => {
return !!+key || +key === 0
})
.map(key => ({[keyName]: enumToTransform[key], [valueKey]: +key}));
} |
174470ef388bb9ec0d2a18cd2ff2c4bbbcd5e4e6 | TypeScript | raopinwu/LayaAir | /LayaAirTS/LayaAirSample/samples/UI_ColorPicker.ts | 2.578125 | 3 | /// <reference path="../../libs/LayaAir.d.ts" />
module ui {
import ColorPicker = laya.ui.ColorPicker;
import Handler = laya.utils.Handler;
export class ColorPickerSample
{
private skin:string = "res/ui/colorPicker.png";
constructor()
{
Laya.init(550, 400);
Laya.stage.scaleMode = laya.display.Stage.SCALE_SHOWALL;
Laya.loader.load(this.skin, Handler.create(this, this.onColorPickerSkinLoaded));
}
private onColorPickerSkinLoaded():void
{
var colorPicker:ColorPicker = new ColorPicker();
colorPicker.skin = this.skin;
colorPicker.selectedColor = "#ff0033";
colorPicker.pos(100, 100);
colorPicker.changeHandler = new Handler(this, this.onChangeColor, [colorPicker]);
Laya.stage.addChild(colorPicker);
this.onChangeColor(colorPicker);
}
private onChangeColor(colorPicker:ColorPicker): void
{
console.log("你选中的颜色:" + colorPicker.selectedColor);
}
}
}
new ui.ColorPickerSample(); |
c2436592f9158a1047e93f3f9b7f004882dce258 | TypeScript | yellyoshua/kata-idukay-react-native | /hooks/useGame.ts | 3.1875 | 3 | import { PotionProps } from "../types";
export default function useGame() {
const gameResult = (potions: PotionProps[]) => {
const potionsAlias = potions.map(val => val.alias) || [];
const gameStats = createGameStats(potionsAlias, damageRules);
return gameStats;
}
const resetGame = (cb: () => void) => cb();
return {
gameResult,
resetGame
}
}
export const damageRules = (potionsCombinations: number): number => {
switch (potionsCombinations) {
case 1:
return 3;
case 2:
return 5;
case 3:
return 10;
case 4:
return 20;
case 5:
return 25;
default:
return (potionsCombinations - 1) * 5;
}
}
export const createAttacksStats = (potions: string[], lastAttack: number[]): number[] => {
let newPotions = potions;
let currentAtack: string[] = [];
for (let index = 0; index < newPotions.length; index++) {
const currentPotion = newPotions[index];
if (Boolean(!currentAtack.includes(currentPotion))) {
currentAtack.push(currentPotion);
newPotions = newPotions.filter((val, i) => (i !== index));
index = 0;
}
}
const beUnderAtack = Boolean(newPotions.length);
if (beUnderAtack) {
return createAttacksStats(newPotions, [...lastAttack, currentAtack.length])
}
return [...lastAttack, currentAtack.length];
}
export const createGameStats = (potions: string[], cb: (i: number) => number): { potionsDamage: number[]; damageTotal: number; combinations: number[] } => {
let newPotions = potions || [];
const attacksStats = createAttacksStats(newPotions, []);
const potionsDamage = attacksStats.map(cb);
return {
potionsDamage,
damageTotal: potionsDamage.reduce((a, b) => a + b),
combinations: attacksStats
};
} |
ecf5f6e0e038f54c82c40c7ed6bbfa4cc18af8e0 | TypeScript | stephenh/joist.firebase | /test/m2/m2-spec.ts | 2.609375 | 3 |
import { ModelPromise, Store } from '@src/model';
import { Mock } from 'firemock';
import { Child } from './Child';
import { Parent } from './Parent';
describe('m2 One-to-many with one-way child -> parent', () => {
it('should be constructable with a parent instance', async () => {
const db = new Mock().useDeterministicIds();
const store = new Store(db);
// given a new parent
const p: Parent = store.createRecord(Parent, { name: 'p' });
// then we can create a child with it
const c = store.createRecord(Child, { name: 'c', parent: p });
// and both are stored in the db
await store.saveAll();
expect(db.db).toEqual({
parents: { id1: { name: 'p' }},
children: { id2: { name: 'c', parent: 'id1' }}
});
// and we can read back out the parent
expect(c.parent.instance).toEqual(p);
});
it('should be constructable with a parent promise', async () => {
const db = new Mock().useDeterministicIds();
const store = new Store(db);
// given an existing parent
store.createRecord(Parent, { name: 'p' });
// and we hvae a promise for it
const mp: ModelPromise<Parent> = store.findRecord(Parent, 'id1');
// then we can create a child with it
const c = store.createRecord(Child, { name: 'c', parent: mp });
// and both are stored in the db
await store.saveAll();
expect(db.db).toEqual({
parents: { id1: { name: 'p' }},
children: { id2: { name: 'c', parent: 'id1' }}
});
// and we can read back out the parent
expect(c.parent).toEqual(mp);
});
});
|
3da80d9bc3fc43fad2e2fc7b145a0671ab16308a | TypeScript | tnrich/ve-range-utils-ts | /test/isRangeOrPositionWithinRange.test.ts | 2.765625 | 3 | import { isRangeOrPositionWithinRange } from "../src";
import { expect as expect } from "chai";
describe('isRangeOrPositionWithinRange', function () {
it('should correctly determine whether a position is within a range', function () {
expect(isRangeOrPositionWithinRange(1, { start: 1, end: 1 })).to.equal(false)
expect(isRangeOrPositionWithinRange(0, { start: 1, end: 10 })).to.equal(false)
expect(isRangeOrPositionWithinRange(1, { start: 0, end: 10 })).to.equal(true)
expect(isRangeOrPositionWithinRange(11, { start: 1, end: 10 })).to.equal(false)
expect(isRangeOrPositionWithinRange(0, { start: 0, end: 10 })).to.equal(false)
expect(isRangeOrPositionWithinRange(10, { start: 0, end: 10 })).to.equal(true)
expect(isRangeOrPositionWithinRange(10, { start: 10, end: 5 })).to.equal(false)
expect(isRangeOrPositionWithinRange(11, { start: 10, end: 5 })).to.equal(true)
expect(isRangeOrPositionWithinRange(4, { start: 10, end: 5 })).to.equal(true)
expect(isRangeOrPositionWithinRange(5, { start: 10, end: 5 })).to.equal(true)
expect(isRangeOrPositionWithinRange(6, { start: 10, end: 5 })).to.equal(false)
})
it('should correctly determine whether a position is within a range when includeStartEdge/includeEndEdge is set to true', function () {
expect(isRangeOrPositionWithinRange(1, { start: 1, end: 1 }, 11, true, true)).to.equal(true)
expect(isRangeOrPositionWithinRange(0, { start: 0, end: 10 }, 11, true, true)).to.equal(true)
})
it("should correctly determine whether a position is within a range", function () {
expect(isRangeOrPositionWithinRange(null, { start: 1, end: 10 }, 100)).to.equal(
false
);
// expect(isRangeOrPositionWithinRange({}, { start: 1, end: 10 }, 100)).to.equal(false);
expect(isRangeOrPositionWithinRange({ start: 5, end: 10 }, undefined, 100)).to.equal(
false
);
expect(isRangeOrPositionWithinRange(undefined, undefined, 100)).to.equal(false);
expect(
isRangeOrPositionWithinRange({ start: 5, end: 10 }, { start: 1, end: 10 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 5, end: 10 }, { start: -1, end: 10 }, 100)
).to.equal(false);
expect(
isRangeOrPositionWithinRange({ start: 0, end: 10 }, { start: 0, end: 10 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 10, end: 10 }, { start: 1, end: 10 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 11, end: 10 }, { start: 0, end: 10 }, 100)
).to.equal(false);
expect(
isRangeOrPositionWithinRange({ start: 12, end: 16 }, { start: 0, end: 10 }, 100)
).to.equal(false);
expect(
isRangeOrPositionWithinRange({ start: 10, end: 5 }, { start: 10, end: 5 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 10, end: 5 }, { start: 10, end: 5 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 10, end: 5 }, { start: 10, end: 5 }, 100)
).to.equal(true);
expect(
isRangeOrPositionWithinRange({ start: 0, end: 6 }, { start: 10, end: 5 }, 100)
).to.equal(false);
expect(
isRangeOrPositionWithinRange({ start: 10, end: 6 }, { start: 10, end: 5 }, 100)
).to.equal(false);
});
})
|
0ec34b43cd84bc404245715397049d44abac24ed | TypeScript | iamhabee/recipe | /start/routes.ts | 2.6875 | 3 | /*
|--------------------------------------------------------------------------
| Routes
|--------------------------------------------------------------------------
|
| This file is dedicated for defining HTTP routes. A single file is enough
| for majority of projects, however you can define routes in different
| files and just make sure to import them inside this file. For example
|
| Define routes in following two files
| ├── start/routes/cart.ts
| ├── start/routes/customer.ts
|
| and then import them inside `start/routes.ts` as follows
|
| import './routes/cart'
| import './routes/customer'
|
*/
import Route from '@ioc:Adonis/Core/Route'
Route.get('/', async () => {
return { hello: 'world' }
})
Route.group(() => {
const CTR_BASE = "/App/Controllers/Http/";
Route.group(() => {
Route.post('/login', `${CTR_BASE}UsersController.login`)
Route.post('/register', `${CTR_BASE}UsersController.register`)
}).prefix('auth')
Route.get('/profile', `${CTR_BASE}ProfilesController.getCurrentUser`)
Route.get('/event', `${CTR_BASE}EventsController.show`)
Route.get('/event/:id', `${CTR_BASE}EventsController.single`)
Route.get('/eductaion', `${CTR_BASE}EducationsController.show`)
Route.get('/eductaion/:id', `${CTR_BASE}EducationsController.single`)
Route.get('/family', `${CTR_BASE}FamiliesController.show`)
Route.get('/family/:id', `${CTR_BASE}FamiliesController.single`)
Route.get('/hobby', `${CTR_BASE}HobbiesController.show`)
Route.get('/hobby/:id', `${CTR_BASE}HobbiesController.single`)
Route.get('/wishlist', `${CTR_BASE}WishlistsController.show`)
Route.get('/wishlist/:id', `${CTR_BASE}WishlistsController.single`)
Route.get('/work', `${CTR_BASE}WorksController.show`)
Route.get('/work/:id', `${CTR_BASE}WorksController.single`)
Route.group(() => {
// user profile api
Route.put('/profile', `${CTR_BASE}ProfilesController.updateProfile`)
// events and places
Route.put('/event', `${CTR_BASE}EventsController.update`)
Route.post('/event', `${CTR_BASE}EventsController.create`)
Route.delete('/event', `${CTR_BASE}EventsController.delete`)
// Educations
Route.put('/eductaion', `${CTR_BASE}EducationsController.update`)
Route.post('/eductaion', `${CTR_BASE}EducationsController.create`)
Route.delete('/eductaion', `${CTR_BASE}EducationsController.delete`)
// fmilies
Route.put('/family', `${CTR_BASE}FamiliesController.update`)
Route.post('/family', `${CTR_BASE}FamiliesController.create`)
Route.delete('/family', `${CTR_BASE}FamiliesController.delete`)
// hobbies
Route.put('/hobby', `${CTR_BASE}HobbiesController.update`)
Route.post('/hobby', `${CTR_BASE}HobbiesController.create`)
Route.delete('/hobby', `${CTR_BASE}HobbiesController.delete`)
// wishlist
Route.put('/wishlist', `${CTR_BASE}WishlistsController.update`)
Route.post('/wishlist', `${CTR_BASE}WishlistsController.create`)
Route.delete('/wishlist', `${CTR_BASE}WishlistsController.delete`)
// works
Route.put('/work', `${CTR_BASE}WorksController.update`)
Route.post('/work', `${CTR_BASE}WorksController.create`)
Route.delete('/work', `${CTR_BASE}WorksController.delete`)
}).middleware("auth:api");
}).prefix('api/haneefah') |
065b2763490ca24f80af5ae96c592f8b7746cff2 | TypeScript | meirelesgabriel/consulta-medica | /backend/src/routes/consultas.routes.ts | 2.59375 | 3 | import { Router } from 'express';
import { getRepository } from 'typeorm';
import ConsultasController from '../app/controllers/ConsultasController';
import Consultas from '../app/models/Consultas';
const consultasRouter = Router();
consultasRouter.post('/', async (request, response) => {
try {
const { paciente_id, medico_id, data } = request.body;
const consultasController = new ConsultasController();
const consulta = await consultasController.store({
paciente_id,
medico_id,
data,
});
return response.json(consulta);
} catch (erro) {
return response.status(400).json({ error: erro.message });
}
});
// atualizar uma consulta
consultasRouter.post('/update/', async (request, response) => {
try {
const consultasRepositorio = getRepository(Consultas);
const { id, paciente_id, medico_id, data, created_at, updated_at } = request.body;
const consulta = await consultasRepositorio.update(id, {
paciente_id,
medico_id,
data,
created_at,
updated_at,
});
return response.json(consulta);
} catch (erro) {
return response.status(400).json({ error: erro.message });
}
});
// listar todos os consultas
consultasRouter.get('/', async (request, response) => {
const consultasRepositorio = getRepository(Consultas);
const consulta = await consultasRepositorio.find();
// usando a data de criação para ordenar, porque não criei um campo data
//const sortedEventos = evento
// .slice()
// .sort((a, b) => (b.created_at ? -1 : a.created_at ? 1 : 0));
//console.log(sortedEventos);
// console.log(request.user);
return response.json(consulta);
});
// listar uma única consulta
consultasRouter.get('/:id', async (request, response) => {
const consultasRepositorio = getRepository(Consultas);
const { id } = request.params;
const user = await consultasRepositorio.findOne(id);
return response.json(user);
});
// excluir uma consulta
consultasRouter.delete('/:id', async (request, response) => {
const consultasRepositorio = getRepository(Consultas);
const { id } = request.params;
await consultasRepositorio.delete(id);
return response.send();
});
export default consultasRouter;
|
9e450755a5015d9814746f647169a7bf0d40821e | TypeScript | plavcik/cucumber | /gherkin-streams/javascript/src/SourceMessageStream.ts | 2.671875 | 3 | import { makeSourceEnvelope } from '@cucumber/gherkin'
import { Transform, TransformCallback } from 'stream'
/**
* Stream that reads a string and writes a single Source message.
*/
export default class SourceMessageStream extends Transform {
private buffer = Buffer.alloc(0)
constructor(private readonly uri: string) {
super({ readableObjectMode: true, writableObjectMode: false })
}
public _transform(chunk: Buffer, encoding: string, callback: TransformCallback) {
this.buffer = Buffer.concat([this.buffer, chunk])
callback()
}
public _flush(callback: TransformCallback) {
const data = this.buffer.toString('utf8')
const chunk = makeSourceEnvelope(data, this.uri)
this.push(chunk)
callback()
}
}
|
0d3a9268bd0069bd96e08a089478837221122392 | TypeScript | balavignan/Web-ICP-1 | /source code/project/jobseek/src/app/_shared/pipes/stringCleaner.ts | 2.515625 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'removeExtraComma'
})
export class StrinCleaner implements PipeTransform {
transform( value: string ): string {
return value.replace(/(,\s,)|(^,)/, '');
}
}
|
c9b0a0306c834c2769e2a93b7d14249015e1d1cd | TypeScript | imcuttle/rcp | /packages/hoc.uncontrolled/index.ts | 3.046875 | 3 | /**
* @file uncontrolled
* @author Cuttle Cong
* @date 2018/6/16
* @description
*/
import isComponentClass from '@rcp/util.iscompclass'
import displayName from '@rcp/util.displayname'
import createLogger from '@rcp/util.createlogger'
const logger = createLogger('@rcp/hoc.uncontrolled')
function getDefaultName(name: string = '') {
return 'default' + name[0].toUpperCase() + name.slice(1)
}
function normalizePropList(propList: Prop[]): StrictProp[] {
return propList.map(prop => {
if (typeof prop === 'string') {
return {
withDefault: true,
eq: defaultEq,
name: prop
}
}
return {
withDefault: true,
eq: defaultEq,
...prop
}
})
}
/**
* @typedef StrictProp
* @public
* @param name {string}
* @param [withDefault=true] {boolean} - Whether check `default{propKey}` firstly
* @param [eq=(a, b) => a === b] {Function} - Detect new value and old value is equal
*/
export type StrictProp = { name: string; withDefault?: boolean; eq?: (oldValue, newValue) => boolean }
/**
* @typedef Prop {string | StrictProp}
* @public
*/
export type Prop = string | StrictProp
const defaultEq = (a, b) => a === b
/**
*
* @public
* @param propList {Prop[]} eg. `['value']` / `[{ name: 'value', withDefault: false, eq: (a, b) => a === b }]`
* @return {Function} `(Component: React.ComponentClass) => React.ComponentClass`
*/
export default function uncontrolled(propList: Prop[] = []) {
let propArray = normalizePropList(propList)
return function uncontrolled(Component: React.ComponentClass): React.ComponentClass {
logger.invariant(isComponentClass(Component), `\`Component\` should be a react component class`)
if (!propList.length) {
return Component
}
class Uncontrolled extends Component {
static displayName = `Uncontrolled_${displayName(Component)}`
state: any
constructor(props) {
super(props)
this.state = this.state || {}
propArray.forEach(prop => {
const propName = prop.name
if (prop.withDefault) {
const defaultPropName = getDefaultName(propName)
this.state[propName] =
typeof this.props[propName] === 'undefined'
? typeof this.props[defaultPropName] === 'undefined'
? this.state[propName]
: this.props[defaultPropName]
: this.props[propName]
} else {
if (typeof this.props[propName] !== 'undefined') {
this.state[propName] = this.props[propName]
}
}
})
}
componentWillReceiveProps(newProps) {
if (super.componentWillReceiveProps) {
super.componentWillReceiveProps.apply(this, arguments)
}
const newState = {}
let hasNewRecord = false
propArray.forEach(prop => {
const { name: propName, eq = defaultEq } = prop
if (newProps && typeof newProps[propName] !== 'undefined' && !eq(this.state[propName], newProps[propName])) {
newState[propName] = newProps[propName]
hasNewRecord = true
}
})
if (hasNewRecord) {
this.setState(newState)
}
}
}
return Uncontrolled
}
}
|
ce090d66090dc9d9f051251530a63d71d2b96bc7 | TypeScript | scarrasco85/proyecto-experts-angular-imagina2 | /src/app/modules/experts/components/availability-select/availability-select.component.ts | 2.53125 | 3 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
interface Options {
value: string;
viewValue: string;
}
@Component({
selector: 'app-availability-select',
templateUrl: './availability-select.component.html',
styleUrls: ['./availability-select.component.scss']
})
export class AvailabilitySelectComponent implements OnInit {
selectedValue: string = '';
@Output() onSelectedValue: EventEmitter<string> = new EventEmitter();
@Input() texto: string = '';
status: Options[] = [
{value: 'mañanas', viewValue: 'Mañanas'},
{value: 'tardes', viewValue: 'Tardes'},
{value: 'total', viewValue: 'Total'}
];
constructor() {
}
ngOnInit():void{
}
emitSelectedValue(event: any){
this.selectedValue = event.value;
this.onSelectedValue.emit(this.selectedValue);
}
}
function ngOnInit() {
throw new Error('Function not implemented.');
}
|
d32f86fd2484eb0174e12493688ccbc40ea44730 | TypeScript | Primespark24/WRIntake | /imports/api/formConstants.ts | 2.765625 | 3 | // eslint-disable-next-line no-shadow
export enum fieldTypes {
none,
string,
bool,
file,
}
export interface Field {
type: fieldTypes,
name: string,
_id: string,
description?: string,
childFields?: Array<this>,
childFieldsUnique?: boolean, // If there are multiple subfields, if multiple of them can be selected at once
}
const randString = () => Math.random().toString(36).substring(2);
export const namesToBoolFields = (namesArray:Array<string>):Array<Field> => namesArray.map((name):Field => ({ name, type: fieldTypes.bool, _id: randString() }));
// This constant defines the fields that are going to be used in our frontend.
// This should probably be replaced by something more mutable.
export const documentFields: Array<Field> = [
{
type: fieldTypes.file,
name: "File Upload",
_id: randString(),
},
{
type: fieldTypes.none,
name: 'WR/USCIS Payment',
_id: randString(),
description: 'https://www.uscis.gov/feecalculator',
childFields: [
{
name: 'WR ILS Payment',
type: fieldTypes.none,
_id: randString(),
childFields: namesToBoolFields(['DSHS Letter', 'Apple Health', 'Fee Internal Fee Waiver']),
childFieldsUnique: true,
},
{
name: 'USCIS Payment',
type: fieldTypes.none,
_id: randString(),
childFields: namesToBoolFields(['Fee Waiver', 'Reduced $405 (Tax&HH Pay Stubs)', 'Fee $725']),
childFieldsUnique: true,
},
],
},
{
type: fieldTypes.none,
name: 'Language/History & Civics screening',
childFields: namesToBoolFields(['Sufficient', 'Not Sufficient', 'N648 screening needed', 'Age language waiver']),
childFieldsUnique: true,
_id: randString(),
},
{
name: 'Over 18 and NOT a US Citizen',
type: fieldTypes.bool,
_id: randString(),
description: 'Did not derive U.S. Citizenship through USC parents (inc. adoptive) prior to turning 18. ',
},
{
name: 'Selective Service Registration checked/ completed/ '
+ 'or Status Info Letter requested if under age 31 (Male applicants only)',
type: fieldTypes.bool,
_id: randString(),
description: 'https://www.sss.gov/Home/Verification '
+ 'If over 26 and not registered, client needs to request a Status Information Letter through'
+ ' https://www.sss.gov/Home/Men-26-and-OLDER',
},
];
function genBlankForm(form:Array<Field>) {
let thisData = {};
form.forEach((f) => {
const obj = f.childFields ? genBlankForm(f.childFields) : {};
switch (f.type) {
case fieldTypes.bool:
obj[f._id] = false;
break;
case fieldTypes.string:
obj[f._id] = '';
break;
default:
obj[f._id] = undefined;
}
thisData = { ...thisData, ...obj };
});
return thisData;
}
|
9ecfb43981927ccc5896a7660de419dc271e8681 | TypeScript | anyfiddle/anyfiddle-code-server-extension | /src/extension.ts | 2.5625 | 3 | import * as vscode from 'vscode';
type AnyfiddleJSON = {
defaultCommand?: string;
port?: number;
openFiles?: string[];
};
let runCommandStatusBarItem: vscode.StatusBarItem;
let portMappingStatusBarItem: vscode.StatusBarItem;
export async function activate(context: vscode.ExtensionContext) {
if (vscode.workspace.workspaceFolders) {
/**
* Get Anyfiddle JSON
*/
const folder = vscode.workspace.workspaceFolders[0];
const anyfiddleJsonUri = vscode.Uri.joinPath(folder.uri, 'anyfiddle.json');
const anyfiddleJsonDocument = await vscode.workspace.openTextDocument(
anyfiddleJsonUri
);
const anyfiddleJsonText = anyfiddleJsonDocument.getText();
let anyfiddleJson: AnyfiddleJSON = {};
try {
anyfiddleJson = JSON.parse(anyfiddleJsonText);
} catch (e) {}
/**
* Get port mapping and show status bar item
*/
let port = 8080;
if (anyfiddleJson.port) {
port = anyfiddleJson.port;
}
const projectId = process.env.ANYFIDDLE_PROJECT_ID;
if (projectId) {
const previewUrl = `https://${projectId}.anyfiddle.run`;
portMappingStatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
2
);
portMappingStatusBarItem.text = `$(plug) Port ${port} => ${previewUrl}`;
portMappingStatusBarItem.show();
const openPreviewCommandId = 'anyfiddle.openPreview';
vscode.commands.registerCommand(openPreviewCommandId, () => {
vscode.env.openExternal(vscode.Uri.parse(previewUrl));
});
portMappingStatusBarItem.command = openPreviewCommandId;
}
/**
* Get Default command and show status bar item
*/
if (anyfiddleJson.defaultCommand) {
runCommandStatusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
1
);
runCommandStatusBarItem.text = '$(play) Run';
runCommandStatusBarItem.show();
const runCommandId = 'anyfiddle.runCommand';
vscode.commands.registerCommand(runCommandId, () => {
if (anyfiddleJson.defaultCommand) {
vscode.window.terminals[0].sendText(anyfiddleJson.defaultCommand);
vscode.window.terminals[0].show();
}
});
runCommandStatusBarItem.command = runCommandId;
}
/**
* Open files as per anyfiddle json
*/
const rootUri = vscode.workspace.workspaceFolders[0].uri;
if (anyfiddleJson.openFiles) {
anyfiddleJson.openFiles.forEach(async (filename) => {
const document = await vscode.workspace.openTextDocument(
vscode.Uri.joinPath(rootUri, filename)
);
vscode.window.showTextDocument(document);
});
}
}
/**
* Open first terminal
*/
const terminals = vscode.window.terminals;
if (terminals.length === 0) {
const terminal = vscode.window.createTerminal();
terminal.show();
}
}
// this method is called when your extension is deactivated
export function deactivate() {}
|
c1ef5df1311513317431e539742e872ddcda228f | TypeScript | NikoBotDev/Niko-Discord | /src/commands/util/say.ts | 2.546875 | 3 | import { Command } from 'discord-akairo';
import { Message } from 'discord.js';
export default class SayCommand extends Command {
constructor() {
super('say', {
aliases: ['say'],
category: 'util',
description: {
content: 'say something'
},
args: [
{
id: 'text',
match: 'rest'
}
]
});
}
public async exec(msg: Message, { text }: { text: string }) {
msg.channel.send(text);
}
}
|
e1e7f6b8616f0167edf44637ca44fcc36c88ec55 | TypeScript | code3tiger/next-bnb-server | /src/controller/auth/index.ts | 2.578125 | 3 | import { Request, Response } from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../../model/User";
export const postLogin = async (req: Request, res: Response) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).send("이메일 또는 비밀번호가 일치하지 않습니다.");
}
if (!user.password) {
return res.status(400).send("소셜 계정으로 이미 가입된 이메일입니다.");
}
const correctPassword = bcrypt.compareSync(password, user.password);
if (!correctPassword) {
return res.status(404).send("이메일 또는 비밀번호가 일치하지 않습니다.");
}
const token = jwt.sign(user.id, process.env.JWT_SECRET_KEY!);
res.cookie("access_token", token, {
expires: new Date(Date.now() + 60 * 60 * 24 * 1000 * 3),
httpOnly: true,
path: "/",
sameSite: "none",
secure: true,
});
return res.status(200).send({ ...user.toObject(), isLoggedIn: true });
} catch (error) {
return res.status(500).end();
}
};
export const getMe = async (req: Request, res: Response) => {
try {
if (req.cookies) {
const { access_token: token } = req.cookies;
// 첨부된 토큰을 가져와 복호화
if (token) {
const userId = jwt.verify(token, process.env.JWT_SECRET_KEY!);
const user = await User.findById(userId);
if (user) {
return res.status(200).send({ ...user.toObject(), isLoggedIn: true });
} else {
return res.status(404).send("존재하지 않는 사용자입니다.");
}
}
}
} catch (error) {
return res.status(500).end();
}
return res.json({ isLoggedIn: false });
};
export const postSignUp = async (req: Request, res: Response) => {
const { name, email, password, birthday } = req.body;
try {
const user = await User.findOne({ email });
if (user) return res.status(409).send("이미 가입된 이메일입니다.");
const hash = bcrypt.hashSync(password, 10);
const newUser = await User.create({
name,
email,
password: hash,
birthday,
avatarUrl: "/static/image/user/default_user_profile_image.jpg",
});
const token = jwt.sign(newUser.id, process.env.JWT_SECRET_KEY!);
res.cookie("access_token", token, {
expires: new Date(Date.now() + 60 * 60 * 24 * 1000 * 3),
httpOnly: true,
path: "/",
sameSite: "none",
secure: true,
});
return res.status(200).send({ ...newUser.toObject(), isLoggedIn: true });
} catch (error) {
return res.status(500).end();
}
};
export const postLogout = async (req: Request, res: Response) => {
return res
.clearCookie("access_token", {
path: "/",
httpOnly: true,
sameSite: "none",
secure: true,
})
.status(200)
.json({ isLoggedIn: false });
};
|
d3088e7194b5927eae8e510d5bc08a4fbe87d02a | TypeScript | kwhong95/ts_study | /TypeCompatibility/src/3.3.ts | 2.984375 | 3 | export {};
interface Person {
name: string;
age?: number;
}
interface Product {
name: string;
age: number;
}
const obj = {
name: 'mike'
}
const person: Person = obj;
const product: Product = obj; |
abd13eb1019623dadada7f3d168a617fc010ee43 | TypeScript | keyranz1/DonorApp | /src/pipes/gender-decider/gender-decider.ts | 2.671875 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'genderDecider',
})
export class GenderDeciderPipe implements PipeTransform {
transform(gender: any): string {
gender = parseInt(gender);
switch (gender) {
case 0:
return "app-man";
case 1:
return "app-girl";
default:
return "app-unknown";
}
}
}
|
9e3fe8924e4d0d4d7559ab9b08dfdde8b694df4d | TypeScript | James-Yu/LaTeX-Workshop | /src/utils/parser.ts | 2.796875 | 3 | import type * as Ast from '@unified-latex/unified-latex-types'
function macroToStr(macro: Ast.Macro): string {
if (macro.content === 'texorpdfstring') {
return (macro.args?.[1].content[0] as Ast.String | undefined)?.content || ''
}
return `\\${macro.content}` + (macro.args?.map(arg => `${arg.openMark}${argContentToStr(arg.content)}${arg.closeMark}`).join('') ?? '')
}
function envToStr(env: Ast.Environment | Ast.VerbatimEnvironment): string {
return `\\environment{${env.env}}`
}
export function argContentToStr(argContent: Ast.Node[], preserveCurlyBrace: boolean = false): string {
return argContent.map(node => {
// Verb
switch (node.type) {
case 'string':
return node.content
case 'whitespace':
case 'parbreak':
case 'comment':
return ' '
case 'macro':
return macroToStr(node)
case 'environment':
case 'verbatim':
case 'mathenv':
return envToStr(node)
case 'inlinemath':
return `$${argContentToStr(node.content)}$`
case 'displaymath':
return `\\[${argContentToStr(node.content)}\\]`
case 'group':
return preserveCurlyBrace ? `{${argContentToStr(node.content)}}` : argContentToStr(node.content)
case 'verb':
return node.content
default:
return ''
}
}).join('')
}
|
3159b6e8655709d3c500b91621bdd2e43732318a | TypeScript | arogozine/LinqToTypeScript | /src/parallel/_private/count.ts | 3.234375 | 3 | import { IParallelEnumerable, ParallelGeneratorType } from "../../types"
export const count = <TSource>(
source: IParallelEnumerable<TSource>,
predicate?: (x: TSource) => boolean) => {
if (predicate) {
return count2(source, predicate)
} else {
return count1(source)
}
}
const count1 = async <TSource>(source: IParallelEnumerable<TSource>): Promise<number> => {
const dataFunc = source.dataFunc
switch (dataFunc.type) {
case ParallelGeneratorType.PromiseToArray:
case ParallelGeneratorType.PromiseOfPromises:
const arrayData = await source.toArray()
return arrayData.length
case ParallelGeneratorType.ArrayOfPromises:
const promises = dataFunc.generator()
return promises.length
}
}
const count2 = async <TSource>(
source: IParallelEnumerable<TSource>,
predicate: (x: TSource) => boolean): Promise<number> => {
const values = await source.toArray()
let totalCount = 0
for (let i = 0; i < values.length; i++) {
if (predicate(values[i]) === true) {
totalCount ++
}
}
return totalCount
}
|
94ec8e44d62e7fa5576bdc2a6d69c4fabf719bb1 | TypeScript | mandric/ionic-example-app | /src/app/home/home.page.ts | 2.5625 | 3 | import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { UsersService, User, Gender } from '../services/users.service';
interface FilterInput {
label: string,
val: Gender,
isChecked: boolean
}
interface AgeStats {
oldest: number,
youngest: number,
average: number
}
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
users: User[];
stats: AgeStats;
filterForm: FilterInput[] = [];
constructor(private router: Router, private usersService: UsersService) {
for (const g in Gender) {
this.filterForm.push({
label: Gender[g],
isChecked: true,
val: g as Gender
})
}
}
ionViewWillEnter() {
this.init();
}
init() {
this.usersService.getUsers().then(users => {
this.users = this.filteredUsers(users);
this.stats = this.getStats(this.users);
});
}
getStats(users: User[]): AgeStats {
if (!users.length) {
return;
}
let count = 0;
let total = 0;
let oldest = users[0].birthday;
let youngest = users[0].birthday;
for (const u of users) {
count++;
total += new Date(u.birthday).valueOf();
if (u.birthday < oldest) {
oldest = u.birthday;
} else if (u.birthday > youngest) {
youngest = u.birthday;
}
}
return {
oldest: this.getAge(oldest),
youngest: this.getAge(youngest),
average: this.getAge(new Date(Math.round(total/count)))
}
}
getAge(birthday: Date | string): number {
if (typeof birthday === 'string') {
birthday = new Date(birthday);
}
const now = new Date();
const diff = new Date(now.valueOf() - birthday.valueOf());
return Math.abs(diff.getFullYear() - 1970);
}
filteredUsers(users: User[] = []): User[] {
const genders = new Map();
for (const f of this.filterForm) {
if (f.isChecked) {
genders.set(f.val, true);
}
}
const filter = (u: User) => {
return genders.has(u.sex);
};
return users.filter(filter);
}
onUserDelete(id: number) {
this.usersService.deleteUser(id)
.then(() => this.init())
.catch(e => {
alert(e);
console.error(e);
});
}
onFilterChange() {
this.init();
}
loadMockData() {
this.usersService.loadMockData()
.then(() => window.location.reload())
.catch(e => {
alert(e);
console.error(e);
window.location.reload();
})
}
fabAdd(){
this.router.navigate(['/user/new']);
}
}
|
4af1b0eba20b62572a7a1f3bd0649c0dfa68292e | TypeScript | helloworld121/angular-redux-duck | /src/app/model/to-do.model.ts | 2.5625 | 3 | import {IdGenerator} from '../decorator/id-class.decorator';
@IdGenerator()
export default class ToDo {
// title: string;
// completed: boolean;
constructor(public title: string, public completed: boolean) {
console.log(this);
}
}
|
3cde7b85e33ac18e223927103a0f9063fac4efb9 | TypeScript | vietanhtran16/axios-types | /types/axios/index.d.ts | 2.765625 | 3 | type Method = "get" | "delete" | "head" | "options" | "post" | "put" | "patch";
type ResponseType = "arraybuffer" | "document" | "json" | "text" | "stream";
interface Object {
[key: string]: any;
}
interface BaseRequestConfig {
baseURL?: string;
transformRequest?: (data: Object, headers: Object) => Object;
transformResponse?: Array<(data: Object) => Object>;
headers?: Object;
params?: Object;
paramsSerializer?: (params: Object) => string;
data?: Object | string;
timeout?: number;
withCredentials?: boolean;
adapter?: (config: Object) => Promise<Response<any>>;
auth?: {
username: string;
password: string;
};
responseType?: ResponseType;
responseEncoding?: string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
maxBodyLength?: number;
validateStatus?: (status: number) => boolean;
maxRedirects?: number;
socketPath?: string;
httpAgent?: any;
httpsAgent?: any;
proxy?: {
host: string;
port: number;
auth: {
username: string;
password: string;
};
};
cancelToken?: any;
decompress?: boolean;
}
type RequestConfig = BaseRequestConfig & {
url: string;
method?: Method;
};
export interface Response<T> {
data: T;
status: number;
statusText: string;
headers: Object;
config: Object;
request: any;
}
type AliasMethod = <T>(
url: string,
config?: BaseRequestConfig
) => Promise<Response<T>>;
type AliasMethodWithData = <T>(
url: string,
data?: Object | string,
config?: BaseRequestConfig
) => Promise<Response<T>>;
type AxiosInstance = {
<T>(config: RequestConfig): Promise<Response<T>>;
request: <T>(config: RequestConfig) => Promise<Response<T>>;
get: AliasMethod;
delete: AliasMethod;
head: AliasMethod;
options: AliasMethod;
post: AliasMethodWithData;
put: AliasMethodWithData;
patch: AliasMethodWithData;
defaults: Required<RequestConfig>;
interceptors: {
request: {
use: (
interceptor: (config: RequestConfig) => RequestConfig,
errorHandler: (error: any) => Promise<any>
) => void;
};
response: {
use: <T>(
interceptor: (config: Response<T>) => Response<T>,
errorHandler: (error: any) => Promise<any>
) => void;
};
};
};
type Axios = AxiosInstance & {
create: (config: RequestConfig) => AxiosInstance;
all: typeof Promise.all;
spread: (callback: (...args: any[]) => any) => (responses: any[]) => any;
};
declare const axios: Axios;
export default axios;
|
29d6c8761d06d2ff413f35395410912698e36d53 | TypeScript | laotian/codebyai-sdk | /SDKRenderUtils.ts | 2.75 | 3 | import {RenderNode, HtmlViewNode, CODE_TYPE} from './DataDefs';
import path from "path";
function objectIsEqual(nodeA:{[key:string]:string}, nodeB:{[key:string]:string}) {
const nodeAKeys = Object.keys(nodeA).sort();
const nodeBKeys = Object.keys(nodeB).sort();
if(nodeAKeys.length!=nodeBKeys.length){
return false;
}
if(nodeAKeys.length==0 && nodeBKeys.length==0){
return true;
}
return nodeAKeys.every((value, index) => {
return nodeBKeys[index]==value && nodeA[value]==nodeB[value];
});
}
function styleIsEqual(nodeA:RenderNode, nodeB:RenderNode) {
if(!objectIsEqual(nodeA.styles, nodeB.styles)){
return false;
}
if(nodeA.scopeStyles.length!=nodeB.scopeStyles.length){
return false;
}
if(nodeA.scopeStyles.length==0 && nodeB.scopeStyles.length==0){
return true;
}
return nodeA.scopeStyles.forEach((scopeStyle,index)=>{
const thatScopeStyle = nodeB.scopeStyles[index];
return scopeStyle.scope == thatScopeStyle.scope
&& objectIsEqual(scopeStyle.styles,thatScopeStyle.styles);
});
}
function getLines(str:String) {
return str.split("\n").length - 1;
}
function renderSpace(padding:number) {
let value = "";
for(let i=0;i<padding;i++){
value += " ";
}
return value;
}
function computeLine(node: HtmlViewNode, from: number) {
node.codeLine = {
from: node.codeLine.from + from,
end: node.codeLine.end + from,
};
from++; //<View> for one line
for(let i=0; i<node.children.length; i++){
computeLine(node.children[i], from);
from = node.children[i].codeLine.end;
}
}
function formatStyleToCSS(className:string,scope:string, styles:{[key:string]:string|number}, indent:number):string {
let currentStyle = "";
if(!styles || Object.keys(styles).length==0){
return currentStyle;
}
currentStyle += renderSpace(indent) + "." + className + scope + " {\n";
currentStyle += Object.keys(styles).map(key=>{
return `${renderSpace(indent+2)}${key}: ${styles[key]};\n`;
}).join("");
currentStyle += renderSpace(indent) + "}\n";
return currentStyle;
}
function createCSS(renderNodeRoot:RenderNode):Map<string,string> {
//style => className
const styleMap:Map<string,string> = new Map<string, string>();
const styleList:Array<RenderNode> = [];
//repeat styles use the same className
visitViewTree(renderNodeRoot,renderNode=>{
const className = renderNode.name;
const indent = 0;
let cssName = '';
const sameStyleNode = styleList.find(node=>styleIsEqual(node,renderNode));
if(sameStyleNode){
cssName = sameStyleNode.name;
}else{
let styleStr=formatStyleToCSS(className,'',renderNode.styles,indent);
renderNode.scopeStyles.forEach(scopeStyle=>{
styleStr+=formatStyleToCSS(className,scopeStyle.scope,scopeStyle.styles,indent);
});
if(styleStr.length>0){
cssName = className;
styleMap.set(styleStr, cssName);
styleList.push(renderNode);
}
}
if(cssName && !renderNode.className.includes(cssName)){
renderNode.className.push(cssName);
}
return renderNode;
});
return styleMap;
}
/**
* visit the whole viewTree
* @param node viewTree root node
* @param visitor
*/
export function visitViewTree<T extends {children:T[]}>(node: T, visitor: (node: T) => (T | undefined)) {
const resultNode = visitor(node);
if(resultNode){
resultNode.children = resultNode.children.map(child=>visitViewTree(child, visitor)).filter(childNode => childNode);
}
return resultNode;
}
/**
* filter from the viewTree whose root is node
* @param node viewTree root node
* @param satisfy condition, all as default
*/
function filterViewTree<T extends {children:T[]}>(node:T, satisfy:(node:T)=>boolean = ()=>true): T[] {
const nodeList:T[] = [];
visitViewTree(node, target => {
if (satisfy(target)) {
nodeList.push(target);
}
return target;
});
return nodeList;
}
function template(content:string, data:{[key:string]:string}) {
var content = content.replace(new RegExp("\\<\\!\\-\\-\\s([^\\s\\-\\-\\>]+)\\s\\-\\-\\>", "gi"), function($0, $1) {
if ($1 in data) {
return data[$1];
} else {
return $0;
}
});
return content;
}
function renderNode2HtmlViewNode(node:RenderNode, padding:number, codeType:CODE_TYPE): HtmlViewNode{
const componentName = node.viewName;
const space = renderSpace(padding);
let jsx = space;
jsx+=`<${componentName}`;
let propPre = renderSpace(1);
let propJoin = ' ';
let quote = '\'';
if(codeType=='android'){
propPre = renderSpace(padding+2);
propJoin = "\n";
jsx+=propJoin;
quote = '"';
}
const allProps = [].concat(node.props);
if(node.className.length>0) {
const className = node.className.join(" ");
const classNameKey = codeType=="react" ? "className" : "class";
allProps.unshift({
name:classNameKey,
value:className,
})
}
const props = allProps.map(p=>{
let content = `${propPre}${p.name}`;
if(p.expression){
content+=`={${p.value}}`;
}else if(p.value!=undefined){
content += `=${quote}${p.value}${quote}`
}
return content;
}).join(propJoin);
if(props){
jsx+= props;
}
let childContent = "";
let childs = [];
let childNewLine = true;
//文本
if(node.content){
childNewLine = false;
childContent = node.content;
}else{
childs = node.children.map(child=>renderNode2HtmlViewNode(child, padding+2, codeType));
childContent = childs.map(child=>child.codes).join("");
//去掉child.codes
childs.forEach(child=>delete child.codes);
}
if(childContent.length==0){
jsx += " />\n";
}else {
if(childNewLine) {
jsx += `>\n${childContent}${space}</${componentName}>\n`;
}else{
jsx += `>${childContent}</${componentName}>\n`
}
}
let viewNode:HtmlViewNode = {
id: node.id,
name: node.name,
codes: jsx,
rect:{
x: node.layout.left,
y: node.layout.top,
width: node.layout.right - node.layout.left,
height: node.layout.bottom - node.layout.top,
},
children: childs,
codeLine:{
from: 0,
end: getLines(jsx),
},
componentName:node.componentName,
};
if(node.asset && node.asset.length==1 && node.asset[0].path){
const slice = node.asset[0].targetPath;
viewNode.exportable = [{
name: path.basename(slice, ".png"),
format: "png",
path: codeType=="android" ? `./CodeByAI/${codeType}/${slice}` : `./CodeByAI/${codeType}/images/${slice}`,
}];
}
return viewNode;
}
export {
styleIsEqual,
formatStyleToCSS,
createCSS,
computeLine,
getLines,
renderSpace,
filterViewTree,
template,
renderNode2HtmlViewNode,
}
|
bdc1c4faee8d612be235786c638d16b4a8da4535 | TypeScript | tim-vu/vu_gunfight | /webui/src/store/match/reducer.ts | 2.828125 | 3 |
import { MAX_HEALTH } from "common/constants";
import { PlayerInfo, toPlayerInfo } from "models/Player";
import { Team } from "models/Team";
import { Reducer } from "redux";
import { MatchActions, MatchState } from "./types";
const initialState : MatchState = {
team: Team.RU,
teamSize: 2,
map: "Noshar Canals",
spectating: false,
playerInfo: [],
ourHealth: MAX_HEALTH * 2,
theirHealth: MAX_HEALTH * 2
}
const matchReducer : Reducer<MatchState, MatchActions> = (state : MatchState = initialState, action) => {
switch(action.type){
case "DAMAGE_DEALT":
const receiverIsOurTeam = state.playerInfo.some(p => p.team === state.team && p.id === action.receiverId)
return {
...state,
playerInfo: state.playerInfo.map(processDamage(action.giverId, action.receiverId, action.amount, action.lethal)),
ourHealth: receiverIsOurTeam ? state.ourHealth - action.amount : state.ourHealth,
theirHealth: receiverIsOurTeam ? state.theirHealth : state.theirHealth - action.amount
}
case "MATCH_STARTING":
return {
...initialState,
map: action.map,
team: action.team,
teamSize: action.teamSize,
playerInfo: action.players.map(toPlayerInfo),
ourHealth: MAX_HEALTH * action.teamSize,
theirHealth: MAX_HEALTH * action.teamSize
}
case "ROUND_STARTING":
return {
...state,
ourHealth: MAX_HEALTH * state.teamSize,
theirHealth: MAX_HEALTH * state.teamSize
}
case "ROUND_COMPLETED":
return {
...state,
spectating: false
}
default:
return state;
}
}
const processDamage = (giverId : number | null, receiverId : number, amount : number, lethal : boolean) => (player : PlayerInfo) => {
if (player.id === giverId) {
return {
...player,
damageDealt: player.damageDealt + amount,
kills: lethal ? player.kills + 1 : player.kills
}
}
if (player.id === receiverId) {
return {
...player,
deaths: lethal ? player.deaths + 1 : player.deaths
}
}
return player;
}
export default matchReducer; |
d46a011acd5bb8ecb58bec3d4c5b0c17ed48f140 | TypeScript | leekangtaqi/design_pattern_ts | /src/proxy.ts | 3.40625 | 3 | /**
* intention: Provides a proxy for other objects to control access to this object.
*/
interface Subject{
request();
}
class RealSubject implements Subject{
request(){
console.log('real request...');
}
}
class Proxy implements Subject{
realSubject: RealSubject;
constructor(){
this.realSubject = new RealSubject();
}
request(){
console.log('do some else...');
this.realSubject.request();
console.log('do some else...');
}
}
var proxy = new Proxy();
proxy.request(); |
08d274a8a75ced2c8deb00b236950b4c3b63bdf7 | TypeScript | TamasToth92/Student_Form_Sample | /src/app/pipes/age.pipe.spec.ts | 2.578125 | 3 | import { AgePipe } from './age.pipe';
describe('AgePipe', () => {
it('create an instance', () => {
const pipe = new AgePipe();
expect(pipe).toBeTruthy();
});
it ('should mask old female age', () => {
const pipe = new AgePipe();
expect( pipe.transform(45, 'female') ).toBe('40-50');
});
it ('should not mask old male age', () => {
const pipe = new AgePipe();
expect( pipe.transform(45, 'male') ).toBe('45');
});
it ('should not mask young female age', () => {
const pipe = new AgePipe();
expect( pipe.transform(25, 'female') ).toBe('25');
});
it ('should not mask young male age', () => {
const pipe = new AgePipe();
expect( pipe.transform(25, 'male') ).toBe('25');
});
});
|
86427accedb3e772b8ee9aa4283ed3b586a5ad07 | TypeScript | jaehyungz/chipstackoverflow-web | /hooks/useCommentCreation.ts | 2.640625 | 3 | import { useApolloClient } from "@apollo/react-hooks";
import * as React from "react";
import { AnswerId } from "@@/models/Answer";
import { CommentBody } from "@@/models/Comment";
import { PostId } from "@@/models/Post";
import useAuthentication from "@@/hooks/useAuthentication";
import usePost from "@@/hooks/usePost";
import createComment from "@@/repositories/createComment";
export default function useCommentCreation({
postId,
answerId,
}: {
postId: PostId;
answerId: AnswerId;
}) {
const apolloClient = useApolloClient();
const { authenticationToken } = useAuthentication();
const { updateLocally } = usePost({ postId });
const [body, setBody] = React.useState("");
const [
bodyValidationErrorTypes,
setBodyValidationErrorTypes,
] = React.useState<CommentBodyValidationErrorType[]>([
CommentBodyValidationErrorType.tooShort,
]);
const [isSubmitting, setSubmitting] = React.useState(false);
const _setBody = (body: string) => {
const validationErrorTypes = [];
if (body.length < 8) {
validationErrorTypes.push(CommentBodyValidationErrorType.tooShort);
}
if (body.length > 65535) {
validationErrorTypes.push(CommentBodyValidationErrorType.tooLong);
}
setBodyValidationErrorTypes(validationErrorTypes);
setBody(body);
};
const submit = async () => {
if (!authenticationToken) {
throw new Error(
"You called useCommentCreation().submit() with null authentication token. It shouldn't happen here."
);
}
setSubmitting(true);
const comment = await createComment({
postId,
answerId,
body: body as CommentBody,
apolloClient,
authenticationToken,
});
updateLocally((post) => {
if (!post) {
return post;
}
return {
...post,
answers: post.answers.map((answer) => {
if (answer.id === answerId) {
return {
...answer,
comments: [comment, ...answer.comments],
};
}
return answer;
}),
};
});
setSubmitting(false);
};
return {
body,
isValid: bodyValidationErrorTypes.length === 0,
bodyValidationErrorTypes,
isSubmitting,
setBody: _setBody,
submit,
};
}
export enum CommentBodyValidationErrorType {
tooShort,
tooLong,
}
|
72cd1972a2bca0514b37a7817ac972fe0f079132 | TypeScript | LiubomyrPenkov/tscript | /client/calc.spec.ts | 2.640625 | 3 | import {expect} from 'chai';
import {describe, it} from 'mocha';
import mathFuncs from './calc';
let {sum, division, substr, multi} = mathFuncs;
describe('mathFunsc', (): void=>{
it('should return proper sum', (): void=>{
expect(sum(1,3)).to.be.equal(1+3);
});
it('should return proper multi', (): void=>{
expect(multi(2,4)).to.be.equal(2*4);
});
it('should return proper division', (): void=>{
expect(division(4,2)).to.be.equal(4/2);
});
it('should return proper substr', (): void=>{
expect(substr(4,2)).to.be.equal(4-2);
});
});
|
5dc08e6129eee1bfbd7a31dc50cea33284bc8581 | TypeScript | ShieldBattery/ShieldBattery | /app/find-install-path.ts | 2.890625 | 3 | import { HKCU, HKLM, readRegistryValue } from './registry'
// Attempts to find the StarCraft install path from the registry, using a combination of possible
// locations for the information. The possible locations are:
// HKCU\SOFTWARE\Blizzard Entertertainment\Starcraft\InstallPath
// HKLM\SOFTWARE\Blizzard Entertertainment\Starcraft\InstallPath
// HKCU\SOFTWARE\Blizzard Entertertainment\Starcraft\Recent Maps
// HKLM\SOFTWARE\Blizzard Entertertainment\Starcraft\Recent Maps
// (including WOW64 variants for all of the above keys)
export async function findInstallPath() {
const normalRegPath = '\\SOFTWARE\\Blizzard Entertainment\\Starcraft'
const _6432RegPath = '\\SOFTWARE\\WOW6432Node\\Blizzard Entertainment\\Starcraft'
const regValueName = 'InstallPath'
const attempts = [
[HKCU, normalRegPath],
[HKCU, _6432RegPath],
[HKLM, normalRegPath],
[HKLM, _6432RegPath],
]
for (const [hive, path] of attempts) {
try {
const result = await readRegistryValue(hive, path, regValueName)
if (result) {
return result
}
} catch (err) {
// Intentionally empty
}
}
let recentMaps: string | undefined
try {
recentMaps = await readRegistryValue(HKCU, normalRegPath, 'Recent Maps')
} catch (err) {
// Intentionally empty
}
if (!recentMaps) {
try {
recentMaps = await readRegistryValue(HKCU, _6432RegPath, 'Recent Maps')
} catch (err) {
// Intentionally empty
}
}
if (!recentMaps) {
return undefined
}
// Filter out paths from 'Recent Maps' value saved in registry, until we get the one we can be
// reasonably certain is a Starcraft install path. Assumption we make is that Starcraft's install
// path must have the 'maps' folder.
const localAppData = (process.env.LocalAppData || '').toLowerCase()
const paths = recentMaps.split('\\0').filter(p => {
const path = p.toLowerCase()
return (
path.includes('\\maps\\') &&
!/\\shieldbattery(|-dev|-local)\\maps\\/i.test(path) &&
(!localAppData || !path.includes(localAppData))
)
})
if (!paths.length) {
return undefined
}
// We make a reasonable guess that the remaining paths are all inside Starcraft folder. For now
// we're not taking into account multiple different install paths, so just pick the first one.
const path = paths[0]
const mapsIndex = path.toLowerCase().lastIndexOf('\\maps\\')
return path.slice(0, mapsIndex)
}
|
19b372a770eee2c8798f920d2e4e0d3b43da4671 | TypeScript | craftingtheinternet/craftingtheinternet.com | /src/reducers/openGraphImage.ts | 2.765625 | 3 | export type ActionType = {
type: string;
};
export default (state = "ABOUT", action: ActionType) => {
switch (action.type) {
case "ABOUT":
return "about.png";
case "CONTACT":
return "contact.png";
case "RESUME":
return "resume.png";
default:
return state;
}
};
|
34e70d3f7aec9d98644da18d03da7bcd2c7d9161 | TypeScript | Enarchaticy/table-reserve-frontend | /src/app/pages/reservations/date-pipe/date.pipe.ts | 2.921875 | 3 | import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'dateWithDay',
})
export class DatePipe implements PipeTransform {
constructor() {}
transform(value: string): string {
for (let i = -1; i <= 6; i++) {
if (this.areEqualDays(new Date(new Date().setDate(new Date().getDate() + i)), value)) {
if (i === -1) {
return 'tegnap';
} else if (i === 0) {
return 'ma';
} else if (i === 1) {
return 'holnap';
} else {
return new Date(value).toLocaleDateString('hu-HU', { weekday: 'long' });
}
}
}
return value.substr(0, 10);
}
areEqualDays(first: Date, second: string) {
return this.getRealIsoDate(first).substr(0, 10) === second.substr(0, 10);
}
getRealIsoDate(date = new Date()) {
const tzoffset = date.getTimezoneOffset() * 60000;
return new Date(date.getTime() - tzoffset).toISOString().slice(0, -1);
}
}
|
05143b14c2cb073b52a33a293e637455939d73b6 | TypeScript | robence/scotty-client | /src/store/period/reducer.ts | 2.703125 | 3 | import SELECT_PERIOD, { PeriodActionTypes } from './types';
import { State } from '../initialState';
export default function periodReducer(
state: State,
{ type, periodId }: PeriodActionTypes,
): State {
switch (type) {
case SELECT_PERIOD:
return {
...state,
selectedPeriodId: Number(periodId),
};
default:
return state;
}
}
|
e922c85ca85c592fe234a1f8fac4e3d8b017c11e | TypeScript | 923325596/app | /src/services/smapi/transaction.ts | 2.53125 | 3 | export interface ITransaction {
// serielized transaction data - hex - including provided gas and gas price
txData: string;
// signed txData when tx is sigend
signature?: string;
// hex string of user public address
address: string;
}
export enum TransactionStatus {
Pending, // not on mesh yet
OnMesh, // on a mesh layer that might be reversed
Conirmed, // updated the state in an irreverisble layer
}
export class TransactionResult {
public txHash: string;
public result: boolean;
}
|
20d4cbf575b023f02d4629fe38e678c1a5b3fb6a | TypeScript | centreon/centreon | /centreon/www/front_src/src/Authentication/Local/TimeInputs/options.ts | 2.546875 | 3 | import type { SelectEntry } from '@centreon/ui';
import { PartialUnitValueLimit, UnitValueLimit } from '../models';
const commonEntry = {
id: 0,
name: '0'
};
const getTimeInputOptions = ({
max,
min
}: UnitValueLimit): Array<SelectEntry> => [
commonEntry,
...Array(max - min + 1)
.fill(0)
.map((_, index) => ({ id: min + index, name: `${min + index}` }))
];
export const getMonthsOptions = ({
max = 12,
min = 1
}: PartialUnitValueLimit): Array<SelectEntry> =>
getTimeInputOptions({ max, min });
export const getDaysOptions = ({
max = 30,
min = 1
}: PartialUnitValueLimit): Array<SelectEntry> =>
getTimeInputOptions({ max, min });
export const getHoursOptions = ({
max = 23,
min = 1
}: PartialUnitValueLimit): Array<SelectEntry> =>
getTimeInputOptions({ max, min });
export const getMinutesOptions = ({
max = 59,
min = 1
}: PartialUnitValueLimit): Array<SelectEntry> =>
getTimeInputOptions({ max, min });
export const getSecondsOptions = ({
max = 59,
min = 1
}: PartialUnitValueLimit): Array<SelectEntry> =>
getTimeInputOptions({ max, min });
|
0bd30559deda67abbe3df4211d11e22402dcc354 | TypeScript | liaujianjie/firebase-to-supabase-auth-migrator | /typings/firebaserc-object.ts | 2.84375 | 3 | type FirebasercObject = {
projects: {
default: string;
[label: string]: string;
};
};
export function isFirebasercObject(obj: any): obj is FirebasercObject {
if (typeof obj !== "object") {
return false;
}
if (!("default" in obj)) {
return false;
}
for (const projectId in Object.values(obj)) {
if (typeof projectId !== "string") {
return false;
}
}
return true;
}
|
c254792a03e5ba3edeb25d179bf51f0f3e58e42c | TypeScript | disco0/sandbox-vscode | /src/htmlView.ts | 2.609375 | 3 | import * as vscode from "vscode";
import { JSDOM } from "jsdom";
import { getAttributes } from "./getAttributes";
const buildInitScript = (htmlAttributes: {}, styleId: string) => `
const htmlAttrs = ${JSON.stringify(htmlAttributes)};
for (const [attr, value] of Object.entries(htmlAttrs)) {
document.documentElement.setAttribute(attr, value);
}
document.getElementById('_defaultStyles').remove();
setTimeout(() => {
document.documentElement.style = '';
if (htmlAttrs['style']) {
document.documentElement.style = htmlAttrs['style'];
}
}, 0);
const vscode = acquireVsCodeApi();
const style = document.getElementById('${styleId}');
const state = vscode.getState();
if (state && state.css) {
style.textContent = state.css;
}
window.addEventListener('message', event => {
const message = event.data;
if (message.command === 'setCSS') {
const css = message.value;
vscode.setState({ css });
style.textContent = css;
}
});
window.alert = (message) => {
vscode.postMessage({
command: 'alert',
text: message
})
}
`;
export class HTMLView {
webview: vscode.Webview;
_html: string = "";
_css: string = "";
_js: string = "";
_id: string;
constructor(webview: vscode.Webview, context: vscode.ExtensionContext) {
this.webview = webview;
webview.onDidReceiveMessage(
message => {
switch (message.command) {
case "alert":
if (!message.text) {
return;
}
vscode.window.showWarningMessage(message.text);
break;
}
},
undefined,
context.subscriptions
);
this._id = Math.random()
.toString(36)
.substr(2, 9);
this.buildHTML();
}
public set html(html: string) {
this._html = html;
this.buildHTML();
}
public set css(css: string) {
this._css = css;
this.webview.postMessage({ command: "setCSS", value: css });
}
public set js(js: string) {
this._js = js;
this.buildHTML();
}
private buildHTML() {
const dom = new JSDOM(this._html);
const { document } = dom.window;
const styleId = `sandbox-style-${this._id}`;
const init = document.createElement("script");
init.textContent = buildInitScript(
getAttributes(document.documentElement),
styleId
);
document.head.prepend(init);
const style = document.createElement("style");
style.textContent = this._css;
style.id = styleId;
document.head.prepend(style);
const defaultStyle = document.createElement("style");
defaultStyle.textContent = "body{background-color:white;}";
document.head.prepend(defaultStyle);
const script = document.createElement("script");
script.textContent = this._js + "\n//# sourceURL=script.js";
script.id = `sandbox-script-${this._id}`;
document.body.append(script);
this.webview.html = dom.serialize();
}
}
|
db4bf6ffdc597ae476fccea7906c323dacf9471a | TypeScript | restorecommerce/resource-base-interface | /src/core/utils.ts | 3.0625 | 3 | import * as _ from 'lodash';
const marshallObj = (val) => {
try {
return {
type_url: '',
value: Buffer.from(JSON.stringify(val))
};
} catch(error) {
// throw error and it is handled and logged in ServiceBase functions
throw error;
}
};
const updateObject = (obj: any, path: string, value: any, fieldHandlerType: string) => {
try {
if (value && fieldHandlerType === 'encode') {
const marshalled = marshallObj(value);
_.set(obj, path, marshalled);
} else if (value?.value && fieldHandlerType === 'decode') {
let unmarshalled = JSON.parse(value.value.toString());
_.set(obj, path, unmarshalled);
} else if(value && fieldHandlerType == 'convertDateObjToMilisec' && value instanceof Date) {
_.set(obj, path, value.getTime());
} else if(value && fieldHandlerType == 'convertMilisecToDateObj' && typeof(value) == 'number') {
_.set(obj, path, new Date(value));
}
} catch(error) {
// rethrow the error, this is caught and logged in ResourceAPI
throw error;
}
};
const setNestedPath = (object: any, fieldPath: string, fieldHandlerType: string) => {
const prefix = fieldPath?.substring(0, fieldPath.indexOf('.['));
const suffix = fieldPath?.substring(fieldPath.indexOf('].') + 2);
let setRecursive = false;
// recursive check if the sub suffix again contains an array index
if (suffix.indexOf('.[') > 0) {
setRecursive = true;
}
if (prefix && suffix) {
let array = _.get(object, prefix);
array.forEach((obj: any) => {
let fieldExists = _.get(obj, suffix);
if (fieldExists) {
updateObject(obj, suffix, fieldExists, fieldHandlerType);
}
// recursive call
if (fieldExists && setRecursive) {
setNestedPath(obj, suffix, fieldHandlerType);
}
});
}
};
const baseGet = (object: any, path: string[]): any => {
let index = 0;
const length = path.length;
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
};
export const fieldHandler = (obj: any, fieldPath: string, fieldHandlerType: string): any => {
// fieldList contains the split Path to individual fields for fieldPath
// and the baseGet breaks when the first field do not exist
// ex: if fieldPath is `a.[0].b.c` then dotFieldPath is `a.0.b.c`
let dotFieldPath: any = fieldPath.split('.[').join('.');
dotFieldPath = dotFieldPath.split('].').join('.');
dotFieldPath = dotFieldPath.split('.');
const array = fieldPath.includes('[');
let fieldExists = baseGet(obj, dotFieldPath);
// only if the configured field exist check recursively for all entries in object
if (fieldExists && array) {
// use setNestedPath
setNestedPath(obj, fieldPath, fieldHandlerType);
} else if (fieldExists) {
// use normal set and return
updateObject(obj, fieldPath, fieldExists, fieldHandlerType);
}
return obj;
}; |
0bdb43e1ed9d5a762d02865201400fb2b29597bd | TypeScript | magsout/tools | /internal/js-ast-utils/getRequireSource.ts | 2.53125 | 3 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Scope} from "@internal/compiler";
import {AnyNode} from "@internal/ast";
import {doesNodeMatchPattern} from "./doesNodeMatchPattern";
export function getRequireSource(
node: undefined | AnyNode,
scope: Scope,
allowStaticMember: boolean = false,
): undefined | string {
if (node === undefined) {
return undefined;
}
if (
allowStaticMember &&
node.type === "JSMemberExpression" &&
node.property.type === "JSStaticMemberProperty"
) {
node = node.object;
}
if (node.type !== "JSCallExpression") {
return undefined;
}
const {arguments: args, callee} = node;
const [firstArg] = args;
if (args.length !== 1 || firstArg.type !== "JSStringLiteral") {
return undefined;
}
const validRequireCallee =
callee.type === "JSReferenceIdentifier" &&
callee.name === "require" &&
scope.getBinding("require") === undefined;
const validRomeRequireCallee =
(doesNodeMatchPattern(callee, "Rome.requireDefault") ||
doesNodeMatchPattern(callee, "Rome.requireNamespace")) &&
scope.getBinding("Rome") === undefined;
if (validRequireCallee || validRomeRequireCallee) {
return firstArg.value;
}
return undefined;
}
|
dd8bbde11d65a7912350daf4508a2c4f259a748a | TypeScript | hu-tao-supremacy/archive | /src/entities/user.entity.ts | 2.65625 | 3 | import { PrimaryGeneratedColumn, Column, Entity, Index } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ unique: true })
email: string;
@Column({ nullable: true })
nickname?: string;
@Index({ unique: true, where: 'chula_id IS NOT NULL' })
@Column({ nullable: true })
chulaId?: string;
@Column({ nullable: true })
address?: string;
@Column({ nullable: true })
phoneNumber?: string;
@Column({ nullable: true })
district?: string;
@Column({ nullable: true })
province?: string;
@Column({ nullable: true })
zipCode?: string;
@Column({ nullable: true })
profilePictureUrl?: string;
@Column()
isChulaStudent: boolean;
@Column()
didSetup: boolean;
@Column('enum', { enum: ['M', 'F', 'NS'] })
gender: string;
@Column({ nullable: true })
academicYear?: number;
}
|
68c013e6bad3b56dcb7e9a316505aeacd6a57790 | TypeScript | lifesucx/stats | /src/qrcodes/display-dialog.ts | 2.515625 | 3 | import { autoinject } from "aurelia-framework";
import { QrCodeDisplayInput, qrCodeConfigurations } from "./display-input";
import * as qrcode from "qrcode-generator";
import { DialogController, DialogService } from "aurelia-dialog";
import * as lz from "lz-string";
import { FrcStatsContext, makeUserPrefs } from "../persistence";
@autoinject
export class QrCodeDisplayDialog {
qrCodeElement: Element;
modelData: string;
dataArray: string[];
dataData: any[];
i: number = 0;
qrType: TypeNumber = 12;
chunkSize: number = 287;
errorCorrection: ErrorCorrectionLevel = 'M';
qrConfigI = 0;
constructor(public controller: DialogController, private dbContext: FrcStatsContext) {
this.qrConfigI = qrCodeConfigurations.length-1;
this.setQrSize();
}
activate(model: QrCodeDisplayInput) {
this.dataArray = this.makePackets(model.data, this.chunkSize);
this.modelData = model.data;
return this.dbContext.getUserPrefs().then(userState => {
let results = qrCodeConfigurations.findIndex(qrConfig => {
return qrConfig.qrType == userState.qrType;
});
if(results == null || results == -1){
return;
}
else{
this.qrType = userState.qrType;
this.qrConfigI = results;
this.setQrSize();
this.dataArray = this.makePackets(model.data, this.chunkSize);
}
});
}
drawQRCode() {
// I think qrcode-generator is generating Model 2 qr codes? http://www.qrcode.com/en/codes/model12.html
let data = this.dataArray[this.i];
var errorCorrection : ErrorCorrectionLevel = 'M';
var mode: Mode = "Byte";
var cellSize = 4; // default is 2
var margin = 10; // default is cellSize * 4
var x = qrcode(this.qrType, errorCorrection);
x.addData(data, mode);
x.make();
this.qrCodeElement.innerHTML = x.createImgTag(cellSize, margin);
}
encodeInt(i: number){
let toEncode = i.toString(32);
if(i < 32 && toEncode.length != 2){
toEncode = "0" + toEncode;
}
if(toEncode.length != 2){
throw new Error(toEncode + " is NOT two. This is probably a conversion issue.");
}
else{
return toEncode;
}
}
makePackets(data: string, chunkSize: number) {
let packets = [];
let hash = 0;
let compressed = lz.compressToBase64(data);
console.info("raw data length: ", data.length);
console.info("compressed data lemgth: ", compressed.length)
let chunks = this.obtainData(data, chunkSize - 6);
for(var i = 0; i < chunks.length; i++){
let index = this.encodeInt(i);
let max = this.encodeInt(chunks.length);
let hash2 = this.encodeInt(hash);
let packet = index + max + hash2 + chunks[i];
packets.push(packet);
}
if(this.i >= this.dataArray.length - 1){
this.i = this.dataArray.length - 1;
}
return packets;
}
obtainData(data: string, chunkSize: number) {
this.dataArray = [];
// Convert data.
var data2 = data;
for(var i = 0; i < Math.ceil(data2.length / chunkSize); i++){
var printThis = data2.substr(chunkSize * (i), chunkSize);
this.dataArray.push(printThis);
console.info("putting 'printThis' into 'this.dataArray' with length " + printThis.length);
}
return(this.dataArray);
}
increment() {
if(this.i < this.dataArray.length - 1){
this.i = this.i + 1;
}
else if(this.i >= this.dataArray.length - 1){
this.i = this.dataArray.length - 1;
}
this.drawQRCode();
}
decrement() {
if(this.i != 0){
this.i = this.i - 1;
}
this.drawQRCode();
}
setQrSize() {
let config = qrCodeConfigurations[this.qrConfigI];
this.qrType = config.qrType;
this.chunkSize = config.size;
this.errorCorrection = config.errorCorrection;
}
increaseSize(){
if(this.qrConfigI >= qrCodeConfigurations.length-1){
return;
}
this.qrConfigI ++;
this.setQrSize();
this.saveQRcodeSize(this.qrType);
this.drawQRCode();
}
decreaseSize(){
if(this.qrConfigI == 0) {
return;
}
this.qrConfigI --;
this.setQrSize();
this.saveQRcodeSize(this.qrType);
this.drawQRCode();
}
attached() {
this.drawQRCode();
}
saveQRcodeSize(qrType2: TypeNumber){
return this.dbContext.getUserPrefs().then(userState => {
userState.qrType = qrType2;
this.dbContext.userPrefs.put(userState);
});
}
static open(dialogService: DialogService, model: QrCodeDisplayInput) {
return dialogService.open({model: model, viewModel: QrCodeDisplayDialog})
}
}
|
7e4b79ff55edcc65902f6a2d4a98fefe76e75879 | TypeScript | jymfony/jymfony | /src/Component/Console/types/Question/Renderer/AbstractRenderer.d.ts | 2.6875 | 3 | declare namespace Jymfony.Component.Console.Question.Renderer {
import OutputInterface = Jymfony.Component.Console.Output.OutputInterface;
import Question = Jymfony.Component.Console.Question.Question;
import OutputFormatterInterface = Jymfony.Component.Console.Formatter.OutputFormatterInterface;
/**
* Abstract question renderer.
*
* @internal
*/
export abstract class AbstractRenderer extends implementationOf(RendererInterface) {
/**
* The underlying question object.
*/
protected _question: Question;
/**
* Input object.
*/
protected _input: NodeJS.ReadableStream;
/**
* Output object.
*/
protected _output: OutputInterface;
/**
* Output formatter.
*/
protected _outputFormatter: OutputFormatterInterface;
/**
* Constructor.
*/
__construct(question: Question): void;
constructor(question: Question);
}
}
|
1f13fd84bfd3e7045fea4b1d2a9a5eba3bdee086 | TypeScript | Innovalz/InnovalzWebSiteBackEnd | /src/core/typescript/util/transformer.util.ts | 2.75 | 3 | export class TransformerUtil {
static flatFromTree(list: string | any[]) {
let _a, _b;
const map: Record<string, unknown> = {};
const root = [];
for (let i = 0; i < list.length; i += 1) {
map[list[i].id] = i;
list[i].children = [];
}
for (let i = 0; i < list.length; i += 1) {
const node = list[i];
if (node.parent !== null) {
(_b =
(_a = list[map[node.parent] as any]) === null || _a === void 0
? void 0
: _a.children) === null || _b === void 0
? void 0
: _b.push(node);
} else {
root.push(node);
}
}
return root;
}
static stringKeyToRegex(query: { [x: string]: any }) {
const obj: Record<string, unknown> = {};
for (const key in query) {
if (
Object.prototype.hasOwnProperty.call(query, key) &&
typeof query[key] === "string" &&
key != "_id"
) {
obj[key] = new RegExp(query[key], "i");
} else {
obj[key] = query[key];
}
}
return obj;
}
}
|
cfdffdb2a1b9ebeb05d9ad392e8228284842f7ac | TypeScript | bhaktiardyan/TypeScript | /pesawat.ts | 3.046875 | 3 | import { abstractKendaraan } from "./abstractKendaraan";
export class pesawat extends abstractKendaraan {
constructor(pName : string, pKapasitas:number, pJalur:string) {
super(pName, pKapasitas, pJalur);
}
// abstract dari class abstractKendaraan
// methode di class abstractKendaraan ditulis kembali
Maju(): void {
console.log(this._getName()+" bisa maju ")
}
Mundur(): void {
console.log(this._getName()+" bisa mundur ")
}
Terbang(): void {
console.log(this._getName()+" bisa terbang ")
}
// overloading
_setValue(pValue: number): void;
_setValue(pValue: string): void;
_setValue(pValue: any): void {
console.log(typeof pValue)
}
} |