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 |
|---|---|---|---|---|---|---|
1c49861038271d218aef0e9c258c176bf0eabf66 | TypeScript | krt23/calvados | /src/app/core/store/actions/employee.actions.ts | 2.5625 | 3 | import {Action} from '@ngrx/store';
import {Employee} from '../../models/employees.model';
export const GET_EMPLOYEE = '[Employee] Get Employee';
export const GET_EMPLOYEES = '[Employee] Get Employees';
export const ADD_EMPLOYEE = '[Employee] Add Employee';
export const UPDATE_EMPLOYEE = '[Employee] Update Employee';
export const DELETE_EMPLOYEE = '[Employee] Delete Employee';
export const FETCH_EMPLOYEE = '[Employee] Fetch Employee';
export class GetEmployee implements Action {
readonly type = GET_EMPLOYEE;
constructor(public payload: number) {}
}
export class GetEmployees implements Action {
readonly type = GET_EMPLOYEES;
constructor(public payload: Employee[]) {}
}
export class AddEmployee implements Action {
readonly type = ADD_EMPLOYEE;
constructor(public payload: Employee) {}
}
export class UpdateEmployee implements Action {
readonly type = UPDATE_EMPLOYEE;
constructor(public payload: { index: number, employee: Employee }) {}
}
export class DeleteEmployee implements Action {
readonly type = DELETE_EMPLOYEE;
constructor(public payload: number) {}
}
export class FetchEmployee implements Action {
readonly type = FETCH_EMPLOYEE;
}
export type EmployeesActions = GetEmployee | GetEmployees | AddEmployee | UpdateEmployee | DeleteEmployee;
|
8ea1d17df2591fef51a0e279919745b0ac16c58c | TypeScript | seniorteck/Visual-Scripting-React | /src/types/appState.ts | 2.765625 | 3 |
export declare interface AppState {
appState?: "EDITING_VARIABLE" | "EDITING_FUNCTION";
variableState: VariableState;
}
export declare interface VariableState {
id: string | number;
type?: "var" | "let" | "const";
name?: string;
value?: string;
}
//TODO: change name to more meaningful name
export declare interface ActionType {
type: "EDITING_VARIABLE" | "EDITING_FUNCTION" | "DONE"
payload?: AppState;
}
|
7d539a813aa68573e6a8d113774e7da8cb8d25ac | TypeScript | badi3a/discoveryFood | /src/app/shared/food.service.ts | 2.6875 | 3 | import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { Food } from '../model/Food';
import { DatacommunicationService } from './datacommunication.service';
@Injectable({
providedIn: 'root'
})
export class FoodService {
//there is an abstraction beteween the service and the components, where the data are up to date because of Subject.
foodSubject = new Subject<any[]>();
private listFood:Food[];
//DatacommunicationService is the service in which we communicate with the data base
constructor(private dbCom:DatacommunicationService) {
this.loadFoods();
}
//emitFoodSubject when the data are completely loaded by the observer
loadFoods(){
const myObserver = {
next: x => {this.listFood = x;},
error: err => console.error('Observer got an error: ' + err),
complete: () => {
console.log("listFood : ",this.listFood);
this.emitFoodSubject();
},
};
this.dbCom.getAllFoods().subscribe(
myObserver
);
}
emitFoodSubject(){
console.log("listFood emit : ", this.listFood);
this.foodSubject.next(this.listFood.slice());
}
affAllFoods(){
return this.listFood;
}
incrementLike(id:number){
console.log("id : ",id);
var food = this.listFood.find(x=>x.id===id);
food.like++;
console.log
this.dbCom.putFood(food,id.toString()).subscribe(
{
next: x => {},
error: err => console.error('Observer got an error: ' + err),
complete: () => {
console.log("editedFoodLike : ",food);
this.emitFoodSubject();
},
}
);
}
//the field quantity in food is just for the client side of the app and it will never be saved in the database(allways =1)
incrementQuantity(i:number){
this.listFood[i].quantity++;
this.emitFoodSubject();
}
//used when the client click the button remove on the cart page
resetQuantity(id:number){
this.listFood.forEach(food => {
if(food.id == id){food.quantity = 1;}
});
this.emitFoodSubject();
}
deleteFood(i:number){
let food = this.listFood.find(x=>x.id===i);
this.dbCom.deleteFood(food.id.toString()).subscribe(
{
next: x => {this.listFood = this.listFood.filter(emp=>emp.id!=food.id)},
error: err => console.error('Observer got an error: ' + err),
complete: () => {
console.log("listFood : ",this.listFood);
this.emitFoodSubject();
},
}
);
}
addFood(food:Food){
food.like = 0;
this.dbCom.addFood(food).subscribe(
{
next: x => { this.listFood = [food,...this.listFood]},
error: err => console.error('Observer got an error: ' + err),
complete: () => {
console.log("listFood : ",this.listFood);
this.emitFoodSubject();
},
}
);
}
updateFood(editedfood:Food){
this.dbCom.putFood(editedfood,editedfood.id.toString()).subscribe(
{
next: x => {},
error: err => console.error('Observer got an error: ' + err),
complete: () => {
console.log("editedFood : ",editedfood);
this.emitFoodSubject();
},
}
);
}
getFoodById(index:number){
return this.listFood.find(x=>x.id===index);
}
//used in the search work
setFoods(foods:Food[]){
this.listFood = foods;
this.emitFoodSubject();
}
}
|
9ae8d3d5a0bf53f389161d0edcad0579c39941a6 | TypeScript | KiaraGrouwstra/ng2ls | /src/models/models.ts | 2.828125 | 3 | import { Observable } from 'rxjs';
import { Type } from '@angular/core';
export { Type } from '@angular/core';
export { Action } from '@ngrx/store';
import { State } from '../reducers';
import { Reducer } from '../reducers/reducers';
export interface Obj<T> {
[k: string]: T;
}
export type AppState = State;
export type SimpleSelector<T> = (state: T) => any;
export type CombinedSelector = [string[], (...args: any[]) => any];
// const genFn = (hasError, hasFail, hasComplete) => `
// (v: T) => {
// obs: Observable<U>${hasError && ' | Observable<Error>'},
// ${hasComplete && 'complete: V,'}
// ${hasFail && 'fail: W,'}
// }
// `;
export interface NgrxDomain<TState> {
// object of classes for Dependency Injection in effect classes (key -> property name)
di?: Obj<Type<any>>;
// initial state value
init?: TState;
reducers?: Obj<Reducer<any>>;
// selector functions from state$, probably using `obs.select`, `R.map(R.prop(k))` or `combineSelectors`
// selectors combining previous selectors, supplied as tuple of [deps, fn]
// - deps: combined selectors, names matching selectors defined above
// - fn: combining function, array param ordered as above
// simple selectors
selectors?: Obj< CombinedSelector | SimpleSelector<TState> >;
effects?: Obj<{
// Effect<T,U>
// initial payload value
init?: /*T*/any,
// limit effect calling interval (default: 0, unlimited)
debounce?: number,
// whether this is a read operation (ignore all but last)
read?: boolean,
// fallback value to use instead of emitting failure, define either this or `fail`. type matches fn.obs value, along with `ok` reducer param if no `fn.ok`.
fallback?: /*U*/any,
// fn: effect function returning different possible results, param type matching `init` (if specified) and effect action payload.
fn: (pl: /*T*/any) => (Observable</*U*/any|Error> | {
// obs: observable with the result (or error) for the given payload. result will be passed to `ok` reducer unless overridden by `fn.ok`.
obs: Observable</*U*/any|Error>,
// ok: // optional value to pass as a parameter to the `ok` reducer, with matching type. if not specified, the default or value of `fn.obs` (if successful) is passed instead. used to e.g. pass the effect param to the failure error instead of the error (such as the book the user attempted to add/remove, but couldn't).
ok?: (v: /*U*/any) => /*V*/any,
// fail: // optional value to pass as a parameter to the `fail` reducer, with matching type. if not specified, the error is passed instead. used to e.g. pass the effect param to the failure error instead of the error (such as the book the user attempted to add/remove, but couldn't).
fail?: (e: Error) => /*W*/any,
}),
// reducer triggered on effect completion, with param type matching `fn.ok` (if available) or `fallback` + `fn.ok`.
ok?: Reducer</*U|V*/any>,
// reducer triggered on effect failure, define either this or `fallback`. param type matches `fn.fail` if available, otherwise `Error`.
fail?: Reducer</*W*/any|Error>,
}>;
}
// export interface NgrxStruct {
// domains: Obj<
// { // <State>() =>
// state: string, // State
// init: State,
// reducers: Obj<
// [string /*type*/, string /*Reducer<State, T>*/]
// >,
// selectors: Obj<
// string /*<T>(Observable<State>) => T*/, // (using R.map(R.prop) or combineLatest)
// >,
// effects: Obj<
// <T,U,V,W>(
// {
// init?: T,
// debounce?: number,
// read?: boolean,
// } & (
// (
// (
// {
// fallback: U,
// fn: (v: T) => {
// obs: string/*Observable<U>*/,
// complete: string/*V*/,
// },
// } | {
// fn: (v: T) => {
// obs: string/*Observable<U> | Observable<Error>*/,
// complete: string/*V*/,
// fail: string/*W*/,
// },
// fail: string/*Reducer<State, W>*/,
// } | {
// fn: (v: T) => {
// obs: string/*Observable<U> | Observable<Error>*/,
// complete: string/*V*/,
// },
// fail: string/*Reducer<State, Error>*/,
// }
// ) & {
// complete: string/*Reducer<State, V>*/,
// }
// ) | (
// (
// {
// fallback: U,
// fn: (v: T) => {
// obs: string/*Observable<U>*/,
// },
// } | {
// fn: (v: T) => {
// obs: string/*Observable<U> | Observable<Error>*/,
// fail: string/*W*/,
// },
// fail: string/*Reducer<State, W>*/,
// } | {
// fn: (v: T) => {
// obs: string/*Observable<U> | Observable<Error>*/,
// },
// fail: string/*Reducer<State, Error>*/,
// }
// ),
// & {
// complete: string/*Reducer<State, U>*/,
// }
// )
// )
// ),
// >,
// // }
// >
// }
|
15202e80f8c9f879f75e804aa8f622dc64715764 | TypeScript | preconstruct/preconstruct | /packages/cli/src/logger.ts | 3.125 | 3 | import chalk from "chalk";
export function format(
message: string,
messageType: "error" | "success" | "info" | "none",
scope?: string
) {
let prefix = {
error: " " + chalk.red("error"),
success: " " + chalk.green("success"),
info: " " + chalk.cyan("info"),
none: "",
}[messageType];
let fullPrefix = "🎁" + prefix + (scope ? " " + chalk.cyan(scope) : "");
return String(message)
.split("\n")
.map((line) => {
if (!line.trim()) {
return fullPrefix;
}
return `${fullPrefix} ${line}`;
})
.join("\n");
}
export function error(message: string, scope?: string) {
console.error(format(message, "error", scope));
}
export function success(message: string, scope?: string) {
console.log(format(message, "success", scope));
}
export function info(message: string, scope?: string) {
console.log(format(message, "info", scope));
}
export function log(message: string) {
console.log(format(message, "none"));
}
|
8151e1112d9d6c690eb6fdc88124d5b8ffff504b | TypeScript | nathansomething/Smarta | /techvalley/src/app/map/marker.ts | 2.765625 | 3 | export class Marker {
id:Number;
lat:Number;
lng:Number;
constructor(id,lat,lng) {
this.id = id;
this.lat = lat;
this.lng = lng;
}
}
|
80a5fece835296b6c6710493c8cc248c8fb1d891 | TypeScript | TylerGarlick/joiful | /test/unit/decorators/boolean.test.ts | 2.609375 | 3 | import { testConstraint } from '../testUtil';
import { boolean } from '../../../src';
describe('boolean', () => {
testConstraint(
() => {
class MarketingOptIn {
@boolean()
joinMailingList?: boolean;
}
return MarketingOptIn;
},
[{ joinMailingList: true }, { joinMailingList: false }],
[{ joinMailingList: 'yep' as any }],
);
describe('truthy', () => {
testConstraint(
() => {
class MarketingOptIn {
@boolean().truthy('yes').truthy('yeah', 'yeppers')
joinMailingList?: boolean;
}
return MarketingOptIn;
},
[
{ joinMailingList: true },
{ joinMailingList: false },
{ joinMailingList: 'yes' as any },
{ joinMailingList: 'yeah' as any },
{ joinMailingList: 'yeppers' as any },
],
[{ joinMailingList: 'fo shizzle my nizzle' as any }],
);
});
describe('falsy', () => {
testConstraint(
() => {
class MarketingOptIn {
@boolean().falsy('no').falsy('nah', 'nope')
joinMailingList?: boolean;
}
return MarketingOptIn;
},
[
{ joinMailingList: true },
{ joinMailingList: false },
{ joinMailingList: 'no' as any },
{ joinMailingList: 'nah' as any },
{ joinMailingList: 'nope' as any },
],
[{ joinMailingList: 'no way jose' as any }],
);
});
describe('insensitive', () => {
testConstraint(
() => {
class MarketingOptIn {
@boolean().truthy('y').falsy('n').sensitive(false)
joinMailingList?: boolean;
}
return MarketingOptIn;
},
[
{ joinMailingList: true },
{ joinMailingList: false },
{ joinMailingList: 'y' as any },
{ joinMailingList: 'Y' as any },
{ joinMailingList: 'n' as any },
{ joinMailingList: 'N' as any },
],
[{ joinMailingList: 'no' as any }],
);
testConstraint(
() => {
class MarketingOptIn {
@boolean().truthy('y').falsy('n').sensitive()
joinMailingList?: boolean;
}
return MarketingOptIn;
},
[
{ joinMailingList: true },
{ joinMailingList: false },
{ joinMailingList: 'y' as any },
{ joinMailingList: 'n' as any },
],
[
{ joinMailingList: 'Y' as any },
{ joinMailingList: 'N' as any },
],
);
});
});
|
790729b723f83b97ba9e999f63651a1567dd5e7a | TypeScript | nognzlz/ejercicio-angular-6 | /src/app/models/producto.ts | 2.625 | 3 | export class Producto {
public nombre: string;
public detalle: string;
public cantidad: string;
constructor(nombre: string = "", detalle: string = "", cantidad: string = "" ) {
this.nombre = nombre;
this.detalle = detalle;
this.cantidad = cantidad;
}
//constructor(){};
} |
2828a52fb0a1a105553e08cade091e903fb82264 | TypeScript | vakolesnikov/guest_book_frontend | /src/utils/index.ts | 2.8125 | 3 | import moment from 'moment';
import { IPostsFilters } from 'types/index';
export const stringToColor = (str: string) => {
let hash = 0;
let i;
/* eslint-disable no-bitwise */
for (i = 0; i < str.length; i += 1) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (i = 0; i < 3; i += 1) {
const value = (hash >> (i * 8)) & 0xff;
color += `00${value.toString(16)}`.substr(-2);
}
/* eslint-enable no-bitwise */
return color;
};
export const transformFilters = (filters: IPostsFilters) => Object.entries(filters).reduce(
(acc, [key, value]) => {
if (moment.isMoment(value)) {
switch (key) {
case 'startDate': {
return { ...acc, [key]: value.startOf('day').valueOf() };
}
case 'endDate': {
return { ...acc, [key]: value.endOf('day').valueOf() };
}
default: break;
}
}
return value ? { ...acc, [key]: value } : acc;
},
{},
);
|
baf21c40bdf2f45da500b9c39007808a39e3c0c5 | TypeScript | TiPunch69/homebridge-awtrix-plugin | /src/matrix-accessory.ts | 2.703125 | 3 | import {
AccessoryPlugin,
Logging,
HAP,
Service,
}
from 'homebridge';
import axios from 'axios';
/**
* This class represents the services to control the matrix.
*/
export class MatrixAccessory implements AccessoryPlugin {
/**
* the URL path
*/
private readonly url: string;
/**
* the display name (this property must exist)
*/
name: string;
/**
* indicates if the app loop is on hold
*/
private appLoopOnHold = false;
/**
* animation
*/
private animationToggleState = false;
/**
* next app
*/
private nextAppToggleState = false;
/**
* the general log file
*/
private readonly log: Logging;
/**
* the general information service
*/
private readonly informationService: Service;
/**
* the general power switch
*/
private readonly powerSwitchService: Service;
/**
* the service to pause the app loop
*/
private readonly appLoopService: Service;
/**
* the service for matrix animations
*/
private readonly animationService: Service;
/**
* the service to switch to the next app
*/
private readonly nextAppService: Service;
/**
* the constructor from the HAP API
* @param hap the HAP package
* @param log the logging interface
* @param name the display name
* @param url the target URL
* @param informationSerivce the shared information service
*/
constructor(hap: HAP, log: Logging, name: string, url: string, informationService: Service) {
this.url = url;
this.log = log;
this.informationService = informationService;
this.name = name;
this.powerSwitchService = new hap.Service.Switch(this.name, 'On');
this.powerSwitchService.setCharacteristic(hap.Characteristic.Name, 'On/Off');
this.powerSwitchService.getCharacteristic(hap.Characteristic.On)
.onGet(async () => {
return await axios.post(
url,
{ get: 'powerState' },
).then(response => {
const power = response.data.powerState;
if (power !== undefined) {
return power;
} else {
return false;
}
})
.catch(error => {
this.log.error('Error during power state query: ' + error);
return false;
});
})
.onSet(async (value) => {
this.log.debug('Settting power to ' + value);
return await axios.post(
url,
{ power: value },
).then(response => {
if (!response.data.success) {
this.log.error('Error during setting the power state to power state ' + value);
}
})
.catch(error => {
this.log.error('Error during setting the power state to power state ' + value + ':' + error);
});
});
this.appLoopService = new hap.Service.Switch(this.name, 'AppLoop');
this.appLoopService.setCharacteristic(hap.Characteristic.Name, 'AppLoop');
this.appLoopService.getCharacteristic(hap.Characteristic.On)
.onGet(() => {
return this.appLoopOnHold;
})
.onSet(async () => {
this.log.debug('Pausing apploop');
await axios.post(
this.url,
{ app: 'pause' },
).then(response => {
if (response.data === 'App switching paused') {
this.appLoopOnHold = true;
} else {
this.appLoopOnHold = false;
}
})
.catch(error => {
this.log.error('Error during pausing apploop:' + error);
});
});
this.animationService = new hap.Service.Switch(this.name, 'Animation');
this.animationService.setCharacteristic(hap.Characteristic.Name, 'Animation');
this.animationService.getCharacteristic(hap.Characteristic.On)
.onGet(() => {
return this.animationToggleState;
})
.onSet(async (value) => {
this.animationToggleState = value ? true : false;
if (value) {
this.log.debug('Running animation.');
await axios.post(
this.url,
{ showAnimation: 'random' },
).then(response => {
if (!response.data.success) {
this.log.error('Error during animation');
}
})
.catch(error => {
this.log.error('Error during animation:' + error);
});
setTimeout(() => {
this.animationService.setCharacteristic(hap.Characteristic.On, false);
}, 250);
}
});
this.nextAppService = new hap.Service.Switch(this.name, 'Next');
this.nextAppService.setCharacteristic(hap.Characteristic.Name, 'Next');
this.nextAppService.getCharacteristic(hap.Characteristic.On)
.onGet(() => {
return this.nextAppToggleState;
})
.onSet(async (value) => {
this.nextAppToggleState = value ? true : false;
if (value) {
this.log.debug('Moving to next app');
await axios.post(
this.url,
{ app: 'next' },
).then(response => {
if (!response.data.success) {
this.log.error('Error app switching');
}
})
.catch(error => {
this.log.error('Error during app switching:' + error);
});
setTimeout(() => {
this.nextAppService.setCharacteristic(hap.Characteristic.On, false);
}, 250);
}
});
}
/*
* This method is called directly after creation of this instance.
* It should return all services which should be added to the accessory.
*/
getServices(): Service[] {
return [
this.informationService,
this.powerSwitchService,
this.appLoopService,
this.animationService,
this.nextAppService,
];
}
}
|
e069fa3cdb0432e756a261498eb9612c82e253eb | TypeScript | below-1/bram-2014-server | /src/services/foo.ts | 3.078125 | 3 | import { zip, range } from "lodash";
import { readFileSync, writeFileSync } from "fs";
type Row = number[];
type Matrix = Row[];
type ClassificationResult = {
_class: number;
prob: number;
}
type KFoldPart = {
Xs: Matrix;
Ys: Row;
};
export class GaussNB {
d: number = undefined;
n: number = undefined;
means: Map<number, Row> = new Map<number, Row>();
variances: Map<number, Row> = new Map<number, Row>();
classProbs: Map<number, number> = new Map<number, number>();
fit(Xs: Matrix, Ys: Row) {
if (Xs.length == 0) {
throw new Error("Empty matrix");
}
if (Xs.length != Ys.length) {
throw new Error("Input and output not match");
}
this.n = Xs.length;
let colSum: Map<number, Row> = new Map<number, Row>();
let classCount: Map<number, number> = new Map<number, number>();
for (let i = 0; i < this.n; i++) {
let row = Xs[i];
let _class = Ys[i];
// If this is the first pass.
if (i == 0) {
// record the dimension
this.d = row.length;
}
// Initialize current sumation of each attributes
// For current class if it's not exists yet.
if (!colSum.has(_class)) {
colSum.set(_class, Array(this.d).fill(0));
}
// Initialize counter for current class if it's not exists yet.
if (!classCount.has(_class)) {
classCount.set(_class, 0);
}
// Increment counter for current class.
classCount.set(_class, classCount.get(_class) + 1);
// Aggregate sum for each attribute in current class.
let classColSum = colSum.get(_class);
for (let idx_d = 0; idx_d < this.d; idx_d++) {
classColSum[idx_d] += row[idx_d];
}
}
const uniqueClass = Array.from(colSum.keys());
// After we get total sum of each attributes
// Initialize means first.
for (let _class of uniqueClass) {
// Calculate class probaility
this.classProbs.set(_class, classCount.get(_class) * 1.0 / this.n);
let _means = Array(this.d).fill(0);
for (let idx_d = 0; idx_d < this.d; idx_d++) {
_means[idx_d] = colSum.get(_class)[idx_d] * 1.0 / classCount.get(_class);
}
this.means.set(_class, _means);
}
// Initialize the variances.s
let tempSumVariances = new Map<Number, Row>();
for (let i = 0; i < this.n; i++) {
let row = Xs[i];
let _class = Ys[i];
if (!tempSumVariances.has(_class)) {
tempSumVariances.set(_class, Array(this.d).fill(0));
}
for (let idx_d = 0; idx_d < this.d; idx_d++) {
let tmp_mean = this.means.get(_class)[idx_d];
let d_val = row[idx_d];
let tmp_var = (tmp_mean - d_val) ** 2;
tempSumVariances.get(_class)[idx_d] += tmp_var;
}
}
for (let _class of uniqueClass) {
let class_variance = tempSumVariances.get(_class).map((totalVar, idx_d) =>
totalVar / classCount.get(_class)
);
this.variances.set(
_class,
class_variance
);
}
}
predictMatrixProba(Xs: Matrix): Matrix {
let uniqueClass = Array.from(this.classProbs.keys());
uniqueClass = uniqueClass.sort((a, b) => a - b);
uniqueClass = uniqueClass.reverse();
console.log(uniqueClass);
let results: Matrix = [];
for (let xs of Xs) {
if (xs.length != this.d) {
throw new Error(`Dimension of input not equal. Got ${xs.length}`);
}
let classProbs = [];
for (let _class of uniqueClass) {
let class_variances = this.variances.get(_class);
let class_means = this.means.get(_class);
let total_prod = 0;
for(let idx_d = 0; idx_d < this.d; idx_d++) {
let _var = class_variances[idx_d];
let x_d = xs[idx_d];
let mean_d = class_means[idx_d];
let f1 = -1 * Math.log(2 * Math.PI);
let f2 = Math.log(_var);
let f3 = ((x_d - mean_d) ** 2) / _var;
total_prod += 0.5 * (f1 - f2 - f3);
}
// Multiply by class probs.
total_prod += Math.log(this.classProbs.get(_class));
classProbs.push(total_prod);
}
// let result = {
// _class: _maxClass,
// prob: _maxProb
// };
const expsum = classProbs.map(cprob => Math.exp(cprob));
const logsum = expsum.map(exp => Math.exp(exp));
const normProb = classProbs.map((cprob, j) => Math.exp(cprob - logsum[j]));
results.push(normProb);
}
// Normalize log prob
return results;
}
predict_binary(Xs: Matrix): Row {
const probs = this.predictMatrixProba(Xs);
return probs.map(classProbs => {
if (classProbs[0] < classProbs[1]) {
return 0;
}
return 1;
});
}
static normalize(M: Matrix): Matrix {
if (M.length === 0) {
throw new Error(`Matrix is empty`);
}
const n = M.length;
let d = undefined;
let maxes = undefined;
let mins = undefined;
for (let i = 0; i < n; i++) {
let x = M[i];
// On first pass, initialize dimension.
if (i == 0) {
d = x.length;
// Initialize maxes and mins for each dimension.
maxes = Array(d).fill(Number.MIN_VALUE);
mins = Array(d).fill(Number.MAX_VALUE);
}
if (x.length != d) {
throw new Error(`Dimension differ: index=${i}, data=${x}`);
}
for (let idx_d = 0; idx_d < d; idx_d++) {
if (x[idx_d] > maxes[idx_d]) {
maxes[idx_d] = x[idx_d];
}
if (x[idx_d] < mins[idx_d]) {
mins[idx_d] = x[idx_d];
}
}
}
return M.map(row => {
return row.map((x_i, i) => {
return (x_i - mins[i]) * 1.0 / (maxes[i] - mins[i]);
});
});
}
static standardize(M: Matrix, means: Row, variances: Row) {
return M.map((xs, i) => {
return xs.map((x, j) => {
return (x - means[j]) / variances[j];
});
});
}
static means(M: Matrix, d: number): Row {
const colSum = M.reduce(
(_means, xs) =>
zip(_means, xs).map(
([_a, _b]) => _a + _b
),
Array(d).fill(0)
);
return range(0, d).map(j => colSum[j] / M.length);
}
static variances(M: Matrix, means: Row, d: number) : Row {
const diffs = M.map((xs, i) =>
xs.map((x, j) => (x - means[j]) ** 2)
);
// console.log(diffs);
const summed = diffs.reduce(
([ _var, _xs ]) => range(0, d).map(j => _var[j] + _xs[j]),
Array(d).fill(0)
);
return summed.map(s => s / M.length);
}
}
function main() {
console.log(process.cwd());
const filePath = process.cwd() + "/src/services/data_20.json";
const buff = readFileSync(filePath);
let data = JSON.parse(buff.toString());
const keys = ["jk", "BS", "BP", "JB", "JWP"];
let Xs: Matrix = data.map(row => {
return keys.map(k => row[k]);
});
let Ys: Row = data.map(row => {
return row.keterangan;
});
let d = 5;
let Xs_norm = GaussNB.normalize(Xs);
let gauss = new GaussNB();
gauss.fit(Xs_norm, Ys);
// console.log("variances[0]");
// console.log(gauss.variances.get(0));
// console.log();
// console.log("variances[1]");
// console.log(gauss.variances.get(1));
console.log();
console.log(
gauss.predict_binary(Xs_norm.slice(0, 10))
);
}
main(); |
9eec6558a866fb4051b9573ff367b06dc2cbca98 | TypeScript | makito/angular-base | /src/app/common/interfaces/plural-case.interface.ts | 2.9375 | 3 | /**
* интерфейс для описания вариантов произношения
*/
export interface IPluralCase {
/**
* для одного
*/
one: string;
/**
* от двух до четырёх
*/
fromTwoToFour: string;
/**
* от пяти
*/
fromFive: string;
}
|
41aa53a97efc1e000dc7f0c804912869094d2654 | TypeScript | BaconSoap/leaflet-bike-gpx | /src/domTools.ts | 3.0625 | 3 | module util {
/**
* Get an element by its ID
*/
export var getById = function(id) {
return document.getElementById(id);
};
/**
* Add an event listener to an element located by its ID
*/
export var onById = function(id, eventName, cb) {
util.getById(id).addEventListener(eventName, cb);
}
/**
* Change the text of the given element
*/
export var changeTextById = function(id, text) {
util.getById(id).innerText = text;
}
}
|
9a0670268766ea86655be400522e4b7ed741c5e4 | TypeScript | boostcamp-2020/IssueTracker-15 | /web/server/src/entity/issue.entity.ts | 2.625 | 3 | import {
Column,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
} from "typeorm";
import CommentEntity from "./comment.entity";
import MilestoneEntity from "./milestone.entity";
import UserEntity from "./user.entity";
import IssueHasLabelEntity from "./issue-label.entity";
import AssigneesEntity from "./assignees.entity";
@Entity("Issue")
class IssueEntity {
@PrimaryGeneratedColumn()
id!: number;
@Column({ type: "varchar", nullable: false })
title!: string;
@Column({ type: "varchar", nullable: true })
description?: string;
@CreateDateColumn()
createAt!: Date;
@UpdateDateColumn()
updateAt?: Date;
@Column({ type: "boolean", nullable: false, default: true })
isOpened!: boolean;
@Column({ type: "number", nullable: true })
milestoneId?: number;
@Column({ type: "number", nullable: false })
authorId!: number;
@ManyToOne(() => MilestoneEntity, (milestone) => milestone.issues, {
onUpdate: "CASCADE",
})
@JoinColumn({
name: "milestoneId",
referencedColumnName: "id",
})
milestone?: MilestoneEntity;
@ManyToOne(() => UserEntity, (user) => user.issues, {
onUpdate: "CASCADE",
})
@JoinColumn({
name: "authorId",
referencedColumnName: "id",
})
author!: UserEntity;
@OneToMany(() => CommentEntity, (comment) => comment.issue, {
cascade: true,
})
comments?: CommentEntity[];
@OneToMany(
() => IssueHasLabelEntity,
(issueHasLabel) => issueHasLabel.issue,
{ cascade: true }
)
issueHasLabels?: IssueHasLabelEntity[];
@OneToMany(() => AssigneesEntity, (assignees) => assignees.issue, {
cascade: true,
})
assignees?: AssigneesEntity[];
}
export default IssueEntity;
|
191fcae2a1aa75a21ce37d41bed5680b987d114c | TypeScript | erospv/repositorio-curso-Labenu | /semana19/testes-no-backend/tests/UserBusiness/getAllUsers.test.ts | 3.078125 | 3 | import { UserBusiness } from "../../src/business/UserBusiness"
import { User, stringToUserRole, UserRole } from "../../src/model/User"
describe("Testing UserBusiness.getAllUsers", () => {
let userDatabase = {}
let hashGenerator = {}
let tokenGenerator = {}
let idGenerator = {}
it("Should return an array of users with id, name, email and role", async () => {
const getAllUsers = jest.fn(() => [
new User(
"id",
"Eros",
"email@gmail.com",
"senha",
stringToUserRole("NORMAL")
)
])
userDatabase = {getAllUsers}
const userBusiness = new UserBusiness(
userDatabase as any,
idGenerator as any,
hashGenerator as any,
tokenGenerator as any
);
const result = await userBusiness.getAllUsers(UserRole.NORMAL)
expect(userBusiness).toHaveBeenCalledTimes(1);
expect(result).toContainEqual({
id: "id",
name: "Eros",
email: "email@gmail.com",
role: UserRole.NORMAL,
});
})
it("Should return 'You must be an admin to access this endpoint' when user is NORMAL", async () => {
expect.assertions(2);
try {
const userBusiness = new UserBusiness(
userDatabase as any,
idGenerator as any,
hashGenerator as any,
tokenGenerator as any
);
await userBusiness.getAllUsers(UserRole.NORMAL);
} catch (err) {
expect(err.errorCode).toBe(403);
expect(err.message).toBe("You must be an admin to access this endpoint");
}
})
}) |
6ff51dd9f29c7062fe21e515646706d093d17db3 | TypeScript | hoanglt1223/Capstone_Project_BE | /src/projects/dto/update-project.dto.ts | 2.515625 | 3 | import {
IsBoolean,
IsNotEmpty,
IsOptional,
Length,
Validate,
} from 'class-validator'
import { PasswordConfirmValidator } from '@validators/password-confirm.validator'
export class UpdateProjectDto {
@IsOptional()
name: string
@IsOptional()
@IsNotEmpty()
@Length(8, 24)
password: string
@IsOptional()
@IsNotEmpty()
@Validate(PasswordConfirmValidator, ['password'])
password_confirmation: string
@IsOptional()
@IsBoolean()
isInactive: boolean
}
|
f7078c735aec3f2b9f4eb44abf2ceb20346f5fe7 | TypeScript | romulobordezani/formoose | /src/tools/updateFormDataValues/updateFormDataValues.ts | 2.921875 | 3 | import { IFormData, IModel } from "../../interfaces";
/**
* Updates all form data based on an User
* @category Utils
* @alias validate/updateFormDataValues
* @param formData All fields state from component
* @param {IModel} model User Model Abstraction
* @returns {void}
*/
function updateFormDataValues(
formData: IFormData,
model: IModel
) {
const objectAdapter = {};
Object.keys(model).map(key => {
objectAdapter[key] = { value: model[key] };
});
Object.assign(formData, objectAdapter);
}
export default updateFormDataValues;
|
878a361cdc53b3859cadb1b028ff36515f226752 | TypeScript | michaelcheers/SVG.JS | /ShapeCirclerf/app.ts | 2.546875 | 3 | var colorsL = 0;
declare var inner: HTMLInputElement;
declare var outer: HTMLInputElement;
function getColors()
{
var result = [];
for (var n = 0; n < colors.childNodes.length; n++)
{
var item = colors.childNodes.item(n);
result.push((item as HTMLInputElement).value);
}
return result;
}
function submit() { go(inner.valueAsNumber, outer.valueAsNumber);}
function go(innerCircle: number, outerCircle: number) {
canvas.innerHTML = "";
var increment = 0;
var line = new Line({ x: 180, y: 180 });
var lColors = colorsL == 0 ? ["#000000", "#ff0000", "#00ff00", "#0000ff", "#00ffff", "#ff00ff", "#ffff00", "#ffffff"] : getColors();
line.penDown();
var innerAngle = 1 / innerCircle;
var innerStepsN = 360 * innerAngle;
var outerAngle = 1 / outerCircle;
for (var n = 0; n < outerCircle + (outerCircle / innerCircle); n++) {
for (var n2 = 0; n2 < innerCircle; n2++) {
line.changeColor(lColors[increment++ % lColors.length]);
line.move(innerStepsN);
line.turn(innerAngle);
}
line.turn(outerAngle);
}
var path = line.SVGPaths;
path.forEach(function (v) { canvas.appendChild(v) });
}
function addColor()
{
var color = document.createElement('input');
color.id = "color" + colorsL++;
color.type = "color";
color.style.display = 'block';
color.oninput = submit;
colors.appendChild(color);
}
function download()
{
var link = document.createElement('a');
link.href = "data:application/octet-stream," + encodeURIComponent("<svg width=\"500\" height=\"500\" xmlns='http://www.w3.org/2000/svg'>" + canvas.innerHTML + "</svg>");
link.download = 'canvas.svg';
link.click();
}
declare var colors: HTMLSpanElement;
declare var canvas: SVGElement; |
31478cd49c04445f7a67aca5627ba5dd8d13cfc4 | TypeScript | bouquen124/app_convocatoria | /src/app/servicios/boletines.service.ts | 2.5625 | 3 | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
export interface Boletin {
id?: string;
c_profesional_id: string;
titulo: string;
subtitulo: string;
contenido: string;
autor: string
}
@Injectable({
providedIn: 'root'
})
export class BoletinesService {
API = 'http://127.0.0.1:8000/api/c_boletins';
constructor(private http: HttpClient) { }
getBols(){
return this.http.get<any>(this.API);
}
getBol(id:string){
return this.http.get<any>(`${this.API}/${id}`);
}
createBol(
c_profesional_id: string,
titulo: string,
subtitulo: string,
contenido: string,
autor: string)
{
return this.http.post<any>(this.API, {c_profesional_id, titulo, subtitulo, contenido, autor});
}
deleteBol(id:string){
return this.http.delete<any>(`${this.API}/${id}`);
}
updateBol(id:string, tipo : Boletin){
return this.http.put<any>(`${this.API}/${id}`, tipo);
}
}
|
3763a3ace81e0a6f95ab2932c261832c6209c770 | TypeScript | john-piedrahita/plugin-scaffold | /lib/commands/CommandCreateEntity.ts | 2.78125 | 3 | import chalk from 'chalk'
import * as yargs from 'yargs'
import {CommandUtils} from './CommandUtils'
import {banner, errorMessage} from "../utils/helpers";
import {MESSAGES} from "../utils/messages";
import ora from "ora";
import {EMOJIS} from "../utils/emojis";
export class EntityCreateCommand implements yargs.CommandModule {
command = "create:entity";
describe = "Generates a new entity.";
builder(args: yargs.Argv) {
return args
.option("n", {
alias: "name",
describe: "Name of the entity type",
demand: true
})
}
async handler(args: yargs.Arguments) {
let spinner
try {
const fileContent = EntityCreateCommand.getTemplate(args.name as any)
const fileContentRepository = EntityCreateCommand.getTemplateRepository(args.name as any)
const basePath = `${process.cwd()}/src/domain/models/`
const filename = `${args.name}.ts`
const path = basePath + filename
const pathRepository = `${basePath}gateways/${args.name}-repository.ts`
const fileExists = await CommandUtils.fileExists(path)
banner()
setTimeout(() => (spinner = ora('Installing...').start()), 1000)
if (fileExists) throw MESSAGES.FILE_EXISTS(path)
await CommandUtils.createFile(pathRepository, fileContentRepository)
await CommandUtils.createFile(path, fileContent)
setTimeout(() => {
spinner.succeed("Installation completed")
spinner.stopAndPersist({
symbol: EMOJIS.ROCKET,
prefixText: MESSAGES.REPOSITORY_SUCCESS(pathRepository),
text: MESSAGES.FILE_SUCCESS('Entity', path)
});
}, 1000 * 5);
} catch (error) {
setTimeout(() => (spinner.fail("Installation fail"), errorMessage(error, 'entity')), 2000)
}
}
/**
* Gets content of the entity file
*
* @param param
* @returns
*/
protected static getTemplate(param: string): string {
const name = CommandUtils.capitalizeString(param)
return `export type ${name}Model = {
// Attributes
}
export type Add${name}Params = Omit<${name}Model, 'id'>
`
}
/**
* Get content repository file
* @param param
* @protected
*/
protected static getTemplateRepository(param: string) {
const name = CommandUtils.capitalizeString(param)
return `export interface I${name}Repository {
}`;
}
}
|
7194d55da95cf24680660646863c1fca6d15f55c | TypeScript | mdumandag/hazelcast-nodejs-client | /src/config/NearCacheConfig.ts | 2.53125 | 3 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {EvictionPolicy} from './EvictionPolicy';
import {InMemoryFormat} from './InMemoryFormat';
export class NearCacheConfig {
name: string = 'default';
/**
* 'true' to invalidate entries when they are changed in cluster,
* 'false' to invalidate entries only when they are accessed.
*/
invalidateOnChange: boolean = true;
/**
* Max number of seconds that an entry can stay in the cache until it is acceessed
*/
maxIdleSeconds: number = 0;
inMemoryFormat: InMemoryFormat = InMemoryFormat.BINARY;
/**
* Maximum number of seconds that an entry can stay in cache.
*/
timeToLiveSeconds: number = 0;
evictionPolicy: EvictionPolicy = EvictionPolicy.NONE;
evictionMaxSize: number = Number.MAX_SAFE_INTEGER;
evictionSamplingCount: number = 8;
evictionSamplingPoolSize: number = 16;
toString(): string {
return 'NearCacheConfig[' +
'name: ' + this.name + ', ' +
'invalidateOnChange:' + this.invalidateOnChange + ', ' +
'inMemoryFormat: ' + this.inMemoryFormat + ', ' +
'ttl(sec): ' + this.timeToLiveSeconds + ', ' +
'evictionPolicy: ' + this.evictionPolicy + ', ' +
'evictionMaxSize: ' + this.evictionMaxSize + ', ' +
'maxIdleSeconds: ' + this.maxIdleSeconds + ']';
}
clone(): NearCacheConfig {
const other = new NearCacheConfig();
Object.assign(other, this);
return other;
}
}
|
6ab3567f5fb724c799d00c6e588846a6ba2fd551 | TypeScript | relaxvinodh/react-live-ticker | /src/components/reducer/utils.spec.ts | 3.265625 | 3 | import * as R from 'ramda';
import { mapRec, accumalateTotal } from './utils';
export const isLastPositive = R.pipe(
R.last,
R.flip(R.gt)(0),
);
export const filterPositive = R.filter(isLastPositive);
export const filterNegative = R.reject(isLastPositive);
export const mapHead = R.map(R.head);
export const convertToNum = R.map(Number);
describe('test utils', () => {
it('should check if last value is positive in array', () => {
const negativeArr = [1, 3, -2];
expect(isLastPositive(negativeArr)).toBeFalsy();
const positiveArr = [1, 3, 2];
expect(isLastPositive(positiveArr)).toBeTruthy();
});
it('should filter array with positive values', () => {
const data = [[1, 2, 3], [4, 5, -6], [7, 8, -9]];
expect(filterPositive(data)).toEqual([[1, 2, 3]]);
});
it('should filter array with negative values', () => {
const data = [[1, 2, 3], [4, 5, -6], [7, 8, -9]];
expect(filterNegative(data)).toEqual([[4, 5, -6], [7, 8, -9]]);
});
it('should map array numbers to "price", "count", "amount"', () => {
const data = [1, 2, 3];
expect(mapRec(data)).toEqual({ price: 1, count: 2, amount: 3 });
});
it('should accumulate total in the same order of snapshots', () => {
const priceSnap = [3, 2, 1];
const dataPositive = {
3: { price: 3, count: 1, amount: 0.3 },
2: { price: 2, count: 1, amount: 0.2 },
1: { price: 1, count: 1, amount: 0.1 },
};
const totalsPositive = accumalateTotal(priceSnap, dataPositive);
expect(totalsPositive).toEqual({
3: { amount: 0.3, total: 0.3 },
2: { amount: 0.2, total: 0.5 },
1: { amount: 0.1, total: 0.6 },
});
const dataNegative = {
3: { price: 3, count: 1, amount: -0.3 },
2: { price: 2, count: 1, amount: -0.2 },
1: { price: 1, count: 1, amount: -0.1 },
};
const totalsNegative = accumalateTotal(priceSnap, dataNegative);
expect(totalsNegative).toEqual({
3: { amount: -0.3, total: -0.3 },
2: { amount: -0.2, total: -0.5 },
1: { amount: -0.1, total: -0.6 },
});
});
});
|
453b0f6b787ac76ea9d5c0c07823878f34f1106c | TypeScript | vicbitly/dynamic-forms-ts | /src/services/form-service.ts | 2.546875 | 3 | import * as React from 'react';
import { FieldType, DynamicFieldProps } from '../types';
import { ContentHeadlineComponent } from '../components/content-headline';
import { ContentNormalComponent } from '../components/content-normal';
import { TextAreaComponent } from '../components/text-area';
import { TextInputComponent } from '../components/text-input';
import { ButtonListComponent } from '../components/button-list';
import { DropDownComponent } from '../components/drop-down';
export function mapFieldTypeToComponent(fieldType: FieldType):
React.ComponentClass<DynamicFieldProps> | React.SFC<DynamicFieldProps> | null {
switch (fieldType) {
case 'content-headline':
return ContentHeadlineComponent;
case 'content-normal':
return ContentNormalComponent;
case 'pick-one-buttons':
return ButtonListComponent;
case 'pick-one-dropdown':
return DropDownComponent;
case 'text':
return TextInputComponent;
case 'text-area':
return TextAreaComponent;
default:
return null;
}
}
|
5cd1b6a9f7e9dd1f1fe83e08c463fcdd34a59336 | TypeScript | Wattle-bird/cave-dungeon | /src/game/effect.ts | 2.828125 | 3 | export class Effect {
damage = 0;
withDamage(damage: number) {
this.damage = damage;
return this;
}
} |
a692ea4a9c1442f1c7c9abc28a5b3f330f33f001 | TypeScript | fivetran/typescript-closure-tools | /index/closure-library/closure/goog/ui/toolbarselect.d.ts | 2.8125 | 3 | /// <reference path="../../../globals.d.ts" />
/// <reference path="./select.d.ts" />
/// <reference path="./controlcontent.d.ts" />
/// <reference path="./menu.d.ts" />
/// <reference path="./menubuttonrenderer.d.ts" />
/// <reference path="../dom/dom.d.ts" />
declare module goog.ui {
class ToolbarSelect extends ToolbarSelect__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class ToolbarSelect__Class extends goog.ui.Select__Class {
/**
* A select control for a toolbar.
*
* @param {goog.ui.ControlContent} caption Default caption or existing DOM
* structure to display as the button's caption when nothing is selected.
* @param {goog.ui.Menu=} opt_menu Menu containing selection options.
* @param {goog.ui.MenuButtonRenderer=} opt_renderer Renderer used to
* render or decorate the control; defaults to
* {@link goog.ui.ToolbarMenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Select}
*/
constructor(caption: goog.ui.ControlContent, opt_menu?: goog.ui.Menu, opt_renderer?: goog.ui.MenuButtonRenderer, opt_domHelper?: goog.dom.DomHelper);
}
}
|
515acc48fcc2996e974d7c93cd7630290acba1f2 | TypeScript | huangyingqi/huarongdao | /src/huarongdao/myui.ts | 2.609375 | 3 | import * as PIXI from "pixi.js"
export class Button extends PIXI.Sprite{
constructor(texture: PIXI.Texture, title?: string) {
super(texture);
this.interactive = true;
this.buttonMode = true;
this.width = this.width;
this.height = this.height;
if (title) {
let style = new PIXI.TextStyle({
fontFamily: 'Arial',
dropShadow: true,
dropShadowAlpha: 0.7,
dropShadowAngle: 0.1,
dropShadowBlur: 1,
dropShadowColor: "0x111111",
dropShadowDistance: 2,
fill: ['#ffffff'],
stroke: '#664620',
fontSize: 30,
fontWeight: "lighter",
lineJoin: "round",
strokeThickness: 3
});
let text = new PIXI.Text(title, style);
text.x = this.width/4;
text.y = this.height/4;
this.addChild(text);
}
}
} |
e97a52e96ecc30096cc4cd3ace859f692a777e89 | TypeScript | lq1990/myFrontEnd | /TypeScript/设计模式/practices/责任链模式/责任链模式01/client.ts | 2.609375 | 3 | import { ProjectManager } from './ProjectManager';
import { DeptManager } from './DeptManager';
import { GeneralManager } from './GeneralManager';
/**
* 责任链模式:
*
*/
let pm = new ProjectManager();
let dm = new DeptManager();
let gm = new GeneralManager();
pm.setSuccessor(dm);
dm.setSuccessor(gm);
let t1: string = pm.handleRequest("anna",200);
console.log("t1: "+t1);
let t2:string = pm.handleRequest("anna",900);
console.log("t2: "+t2); |
745c7406328222e8178a0a38f4accad64465f591 | TypeScript | taylordeatri/openmrs-esm-user-dashboard-widgets | /src/refapp-grid/formatters.ts | 2.984375 | 3 | import cloneDeep from "lodash.clonedeep";
const formatters = {
convertToTime: (dateTimevalue): string => {
const hour = new Date(dateTimevalue).getHours();
const minutes = new Date(dateTimevalue).getMinutes();
const type = hour >= 12 ? "PM" : "AM";
return `${String(hour % 12).padStart(2, "0")}:${String(minutes).padStart(
2,
"0"
)} ${type}`;
},
suffix: (value, suffix): string => `${value}${suffix}`
};
export const getField = (obj, path: string) => {
if (!path) {
return obj;
}
return path.split(".").reduce((extractedObj, fieldName) => {
return extractedObj[fieldName];
}, obj);
};
const getParentField = (obj, path: string) => {
if (!path) {
return obj;
}
return getField(obj, trimLastPathSection(path));
};
const trimLastPathSection = (path: string): string =>
path
.split(".")
.slice(0, path.split(".").length - 1)
.join(".");
export const formatField = (source, field, formatter) => {
const formaterName =
typeof formatter === "string" ? formatter : formatter.name;
const args = formatter.args ? formatter.args : [];
return formatters[formaterName](getField(source, field), [...args]);
};
export default function format(
source: any,
formatterConfigs: Formatter[]
): any {
const clonnedSource = cloneDeep(source);
formatterConfigs.forEach(config => {
const parent = getParentField(clonnedSource, config.field);
const formattedFieldName = config.formattedField
? config.formattedField
: `${config.field}Formatted`;
parent[formattedFieldName] = formatField(
clonnedSource,
config.field,
config
);
});
return clonnedSource;
}
type Formatter = {
name: string;
field: string;
formattedField?: string;
args?: any[];
};
|
9f6ec73c1f3120d28e6a938a6f50b9a7bc2d8191 | TypeScript | hoffination/TDD-CHESS | /src/logic/Turn.ts | 2.875 | 3 | import { Player } from '../enums/Player'
const Turn = {
options: [Player.WHITE, Player.BLACK],
get(index: number) {
return this.options[index]
},
lookup(name: Player) {
return this.options.indexOf(name)
},
next(index: number) {
return (index + 1) % 2
}
}
export default Turn |
b5b8a748498c5235dfcfb40888b34179f0588976 | TypeScript | LakshanSS/PlaySlotMachine | /public/javascripts/game.ts | 3.484375 | 3 | //Interface ISymbol
interface ISymbol{
setImage:(string)=>void,
setValue:(number)=>void,
getImage:()=>string,
getValue:()=>number
}
//Class Symbol
class Symbol implements ISymbol{
private imgURL:string;
private value:number;
constructor(imgName:string,value:number){
this.imgURL = "/assets/images/"+imgName+".png";
this.value = value;
}
setImage(imgName:string){
this.imgURL = "/assets/images/"+imgName+".png";
}
setValue(value:number){
this.value = value;
}
getImage(){
return this.imgURL;
}
getValue(){
return this.value;
}
//method to compare two Symbols
static compareSymbols(sym1:Symbol,sym2:Symbol){
if(sym1.getImage()==sym2.getImage()){
return true;
}else{
return false;
}
}
}
//Class Reel
class Reel{
private symbolList:Symbol[]=[];
private currentSymbol:Symbol;
private spinning:boolean=false;
constructor(){
this.symbolList.push(new Symbol("cherry",2));
this.symbolList.push(new Symbol("lemon",3));
this.symbolList.push(new Symbol("plum",4));
this.symbolList.push(new Symbol("watermelon",6));
this.symbolList.push(new Symbol("bell",8));
this.symbolList.push(new Symbol("redseven",10));
}
getSymbolList(){
return this.symbolList;
}
setCurrentSymbol(cs:Symbol){
return this.currentSymbol=cs;
}
getCurrentSymbol(){
return this.currentSymbol;
}
setSpinning(b:boolean){
this.spinning = b;
}
isSpinning(){
return this.spinning;
}
}
//Class SlotMachine
class SlotMachine{
public static INITIAL_CREDITS:number=10;
public static MAX_BET:number=3;
credits:number =SlotMachine.INITIAL_CREDITS;
addedCoins:number=0;
betCoins:number=0;
noOfWins:number=0;
noOfLosts:number=0;
areSpinning:boolean=false;
reel1:Reel=new Reel();
reel2:Reel=new Reel();
reel3:Reel=new Reel();
s1Index:number=0;
s2Index:number=2;
s3Index:number=5;
spinS1:number;
spinS2:number;
spinS3:number;///break point
//Method to spin the first reel
spin1(){
document.getElementById("img1").src = (this.reel1.getSymbolList()[this.s1Index].getImage());
this.reel1.setCurrentSymbol(this.reel1.getSymbolList()[this.s1Index]);
this.s1Index++;
if(this.s1Index==6){
this.s1Index=0;
}
}
//Method to spin the second reel
spin2(){
document.getElementById("img2").src = (this.reel2.getSymbolList()[this.s2Index].getImage());
this.reel2.setCurrentSymbol(this.reel2.getSymbolList()[this.s2Index]);
this.s2Index++;
if(this.s2Index==6){
this.s2Index=0;
}
}
//Method to spin the third reel
spin3(){
document.getElementById("img3").src = (this.reel3.getSymbolList()[this.s3Index].getImage());
this.reel3.setCurrentSymbol(this.reel3.getSymbolList()[this.s3Index]);
this.s3Index++;
if(this.s3Index==6){
this.s3Index=0;
}
}
//Method to start spinning the reels
spinReels(){
this.spinS1=setInterval(() =>this.spin1(),100);
this.reel1.setSpinning(true);
this.spinS2=setInterval(() =>this.spin2(),97);
this.reel2.setSpinning(true);
this.spinS3=setInterval(() =>this.spin3(),96);
this.reel3.setSpinning(true);
document.getElementById("msgBox").innerHTML = "Click a reel to stop!";
}
//Method to update the UI after change in the values
updateValues(){
document.getElementById("displayCredit").innerHTML=""+this.credits;
document.getElementById("displayBet").innerHTML=""+this.betCoins;
}
//Method to reset values
resetValues(){
if(this.betCoins!=0){
this.credits+=this.betCoins;
this.betCoins=0;
this.updateValues();
}
}
//Method to compare the symbols and update the result
updateResult(){
if(!this.reel1.isSpinning() && (!this.reel2.isSpinning() && !this.reel1.isSpinning())){
if(Symbol.compareSymbols(this.reel1.getCurrentSymbol(),this.reel2.getCurrentSymbol())||
Symbol.compareSymbols(this.reel1.getCurrentSymbol(),this.reel3.getCurrentSymbol())){
this.credits += this.betCoins*this.reel1.getCurrentSymbol().getValue();
this.noOfWins++;
winSnd.play();
document.getElementById("msgBox").innerHTML = "You won! ("+this.betCoins*this.reel1.getCurrentSymbol().getValue()+
" Coins)";
document.getElementById("msgBox").style.color='#00fa9a';
}else if(Symbol.compareSymbols(this.reel2.getCurrentSymbol(),this.reel3.getCurrentSymbol())){
this.credits += this.betCoins*this.reel2.getCurrentSymbol().getValue();
this.noOfWins++;
winSnd.play();
document.getElementById("msgBox").innerHTML = "You won! ("+this.betCoins*this.reel2.getCurrentSymbol().getValue()+
" Coins)";
document.getElementById("msgBox").style.color='#00fa9a';
}else{
lostSnd.play();
this.noOfLosts++;
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML = "You lost!"
}
this.betCoins=0;
this.areSpinning=false;
this.updateValues();
}
}
newGame(){
newGameSnd.play();
document.getElementById("msgBox").style.color='#00fa9a';
document.getElementById("msgBox").innerHTML = "New Game! Bet and Spin!"
this.noOfWins=0;
this.noOfLosts=0;
this.betCoins=0;
this.addedCoins=0;
this.credits=SlotMachine.INITIAL_CREDITS;
this.updateValues();
}
}
//Load the audio files
var warningSnd = new Audio("/assets/audio/warning.mp3");
var spinSnd = new Audio("/assets/audio/spin.mp3");
var addCoinSnd = new Audio("/assets/audio/addcoin.wav");
var lostSnd = new Audio("/assets/audio/lost.wav");
var winSnd = new Audio("/assets/audio/win.wav");
var newGameSnd = new Audio("/assets/audio/newgame.wav");
var resetSnd = new Audio("/assets/audio/reset.wav");
var betSnd = new Audio("/assets/audio/bet.wav");
//Method to start the game
function startGame(){
//Event Listener for addCredit
document.getElementById("addCredit").addEventListener("click", function(){
if(!sm.areSpinning){
if(sm.credits<1000){
addCoinSnd.play();
sm.addedCoins++;
sm.credits++;
document.getElementById("displayCredit").innerHTML=""+sm.credits;
}else{
document.getElementById("msgBox").style.color='#dc143c';
warningSnd.play();
document.getElementById("msgBox").innerHTML="Can't add more than 1000";
}
}else{
document.getElementById("msgBox").style.color='#dc143c';
warningSnd.play();
document.getElementById("msgBox").innerHTML="Can't add coins while spinning";
}
});
//Event Listener for betOne
document.getElementById("betOne").addEventListener("click", function(){
if(!sm.areSpinning){
if(sm.credits>0){
sm.betCoins++;
sm.credits--;
sm.updateValues();
betSnd.play();
document.getElementById("msgBox").style.color='#00fa9a';
document.getElementById("msgBox").innerHTML="You have bet One!";
}else{
warningSnd.play();
document.getElementById("msgBox").innerHTML="You don't have coins!";
document.getElementById("msgBox").style.color='#dc143c';
}
}else{
warningSnd.play();
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML="Can't bet while spinning";
}
});
//Event Listener for betMax
document.getElementById("betMax").addEventListener("click", function(){
if(!sm.areSpinning){
if(sm.credits+sm.betCoins >= SlotMachine.MAX_BET){
sm.resetValues();
sm.betCoins+=SlotMachine.MAX_BET;
sm.credits-=SlotMachine.MAX_BET;
sm.updateValues();
betSnd.play();
document.getElementById("msgBox").style.color='#00fa9a';
document.getElementById("msgBox").innerHTML="You have bet Max!";
}else{
warningSnd.play();
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML="You don't have coins!";
}
}else{
warningSnd.play();
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML="Can't bet while spinning";
}
});
//Event Listener for reset
document.getElementById("reset").addEventListener("click", function(){
if(!sm.areSpinning){
if(sm.betCoins!=0){
sm.resetValues();
resetSnd.play();
document.getElementById("msgBox").style.color='#00fa9a';
document.getElementById("msgBox").innerHTML="You have reset your bet!";
}
}else{
warningSnd.play();
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML="Can't reset while spinning";
}
});
//Event Listener for spin button
document.getElementById("spinBtn").addEventListener("click", function () {
if (!sm.areSpinning) {
if (sm.betCoins > 0) {
document.getElementById("msgBox").style.color='#00fa9a';
document.getElementById("msgBox").innerHTML = "Click a reel to stop!";
spinSnd.play();
sm.spinReels();
sm.areSpinning=true;
}else{
warningSnd.play();
document.getElementById("msgBox").style.color='#dc143c';
document.getElementById("msgBox").innerHTML = "Please bet before spinning!";
}
}
});
//Event Listener for slot1
document.getElementById("img1").addEventListener("click", function () {
if(sm.areSpinning){
clearInterval(sm.spinS1);
sm.reel1.setSpinning(false);
sm.updateResult();
}
});
//Event Listener for slot2
document.getElementById("img2").addEventListener("click", function () {
if(sm.areSpinning){
clearInterval(sm.spinS2);
sm.reel2.setSpinning(false);
sm.updateResult();
}
});
//Event Listener for slot3
document.getElementById("img3").addEventListener("click", function () {
if(sm.areSpinning){
clearInterval(sm.spinS3);
sm.reel3.setSpinning(false);
sm.updateResult();
}
});
//Event Listener for newGame
document.getElementById("newGame").addEventListener("click",function(){
if(!sm.areSpinning){
sm.newGame();
}
});
//Event Listener for payout
document.getElementById("payout").addEventListener("click",function(){
if(!sm.areSpinning){
alert("(P)of a winning combination = (1/6)*(1/6)= 0.027\n\n"+
"Payout for 2xSeven = 0.027*10$ = 0.270$\n"+
"Payout for 2xBell = 0.027*8$ = 0.216$\n"+
"Payout for 2xWatermelon = 0.027*6$ = 0.162$\n"+
"Payout for 2xPlum = 0.027*4$ = 0.108$\n"+
"Payout for 2xLemon = 0.027*3$ = 0.081$\n"+
"Payout for 2xCherry = 0.027*2$ = 0.054$\n\n"+
"Total Payout for 1$ = 0.891$ (89.1%)");
}
});
//Event Listener for statistics
document.getElementById("statistics").addEventListener("click",function(){
if(!sm.areSpinning){
var totalSpins = sm.noOfWins+sm.noOfLosts;
var noOfWins = sm.noOfWins;
var noOfLosts = sm.noOfLosts;
var gainedCoins = sm.credits-(sm.addedCoins+SlotMachine.INITIAL_CREDITS);
var avgPerSpin = (gainedCoins/totalSpins);
document.getElementById("disSpins").innerHTML="Total Spins: "+totalSpins;
document.getElementById("disWins").innerHTML="No Of Wins: "+noOfWins;
document.getElementById("disLosts").innerHTML="No Of Losts: "+noOfLosts;
document.getElementById("disGain").innerHTML="Gained Coins: "+gainedCoins;
document.getElementById("disAvgPerSpin").innerHTML="Avg per Spin: "+avgPerSpin;
var pieChart = document.getElementById('pieChart');
var color = ['rgb(14,195,141)', 'rgb(206, 5, 11)'];
var data = [{
values: [sm.noOfWins,sm.noOfLosts],
labels: ['NoOfWins','noOfLosts'],
type:'pie',
marker:{
colors:color
},
hoverinfo: 'label+percent'
}];
var layout = {
height:400,
width:400
};
Plotly.newPlot(pieChart, data, layout);
document.getElementById("gameContainer").style.display="none";
document.getElementById("statisticsContainer").style.display="";
}
});
//Event Listener for back
document.getElementById("back").addEventListener("click",function(){
document.getElementById("statisticsContainer").style.display="none";
document.getElementById("gameContainer").style.display="";
});
//Event Listener for save
document.getElementById("saveStatistics").addEventListener("click",function(){
var playerName = document.getElementById("playerName").value;
var playerEmail = document.getElementById("playerEmail").value;
var totalSpins = sm.noOfWins+sm.noOfLosts;
var noOfWins = sm.noOfWins;
var noOfLosts = sm.noOfLosts;
var gainedCoins = sm.credits-(sm.addedCoins+SlotMachine.INITIAL_CREDITS);
var avgPerSpin = (gainedCoins/totalSpins);
var database = firebase.database().ref();
var playerRef = database.push();
playerRef.set({
name: playerName,
email: playerEmail,
totalSpins:totalSpins,
wins: noOfWins,
losts: noOfLosts,
gain: gainedCoins,
avgPerSpin: avgPerSpin
});
sm.newGame();
document.getElementById("playerName").value="";
document.getElementById("playerEmail").value="";
document.getElementById("statisticsContainer").style.display="none";
document.getElementById("gameContainer").style.display="";
});
}
//Creating an instance of a SlotMachine
let sm = new SlotMachine();
//Start the game
startGame();
|
0f17f5b1e564e57cac987777b44fc091c1713cca | TypeScript | xrei/kr | /frontend/src/lib/index.ts | 2.765625 | 3 | export function omit(o: any) {
let clone = {...o}
Object.keys(clone).forEach((key) => clone[key] === undefined && delete clone[key])
return clone
}
export const sleep = (t: number = 1000) => new Promise((resolve) => setTimeout(resolve, t))
|
f27b89d2dad184fbc4e3f57fe6f0740ce0489d22 | TypeScript | borabaloglu/blog-app | /src/modules/posts/dto/posts.lookup.dto.ts | 2.65625 | 3 | import { Transform } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
ArrayUnique,
IsDate,
IsEnum,
IsInt,
IsOptional,
IsString,
Length,
Matches,
Min,
} from 'class-validator';
import lookupHelper from 'src/shared/helpers/lookup.helper';
import { PostType } from '../entities/post.entity';
export class PostsLookupDto {
@IsOptional()
@Transform((value: string) => value.split(',').map(item => +item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsInt({ each: true })
@Min(1, { each: true })
postIds?: number[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => +item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsInt({ each: true })
@Min(1, { each: true })
authorIds?: number[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 100, { each: true })
slugs?: string[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 100, { each: true })
titles?: string[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 240, { each: true })
@Matches(/[^\s]/, { each: true })
subtitles?: string[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 240, { each: true })
@Matches(/[^\s]/, { each: true })
contents?: string[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 5, { each: true })
@Matches(/[^\s]/, { each: true })
languages?: string[];
@IsOptional()
@Transform((value: string) => PostType[value.toUpperCase()])
@IsEnum(PostType)
type?: number;
@IsOptional()
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@IsString({ each: true })
@Length(1, 64, { each: true })
@Matches(/[^\s]/, { each: true })
tags?: string[];
@IsOptional()
@Transform((value: string) => {
const parts = value.split(',').map(date => (date.trim() === '' ? '' : new Date(date)));
return lookupHelper.transformRange(value, parts, new Date(0));
})
@ArrayMinSize(1)
@ArrayMaxSize(2)
@IsDate({ each: true })
createdAtRange?: Date[];
@IsOptional()
@Transform((value: string) => {
const parts = value.split(',').map(date => (date.trim() === '' ? '' : new Date(date)));
return lookupHelper.transformRange(value, parts, new Date(0));
})
@ArrayMinSize(1)
@ArrayMaxSize(2)
@IsDate({ each: true })
updatedAtRange?: Date[];
@IsOptional()
@Transform((value: string) => value.split(',').map(item => item.trim()))
@ArrayUnique()
@ArrayMinSize(1)
@ArrayMaxSize(32)
@Length(1, 240, { each: true })
@Matches(/[^\s]/, { each: true })
search?: string[];
@IsOptional()
@Matches(/^[A-Za-z_]+-?(,[A-Za-z_]+-?)*$/)
order?: string;
@IsOptional()
@Matches(/^[A-Za-z_]+(,[A-Za-z_]+)*$/)
load?: string;
@IsOptional()
@Matches(/^[0-9]+(\.[1-9])?(,[0-9]+(\.[1-9])?)?$/)
page?: string;
}
|
d985fe6be6d8cd93c0704731bdd958dfe2cef5f2 | TypeScript | eyalmendel/logga-ts | /src/config/BaseConfig.ts | 2.796875 | 3 | "use strict";
import { PersistableFactory } from "./../storage/PersistableFactory";
import { FormatterFactory } from "./../formats/FormatterFactory";
import { Levels } from "../levels/Levels";
import Persistable from "../storage/Persistable";
import { Formatter } from "../formats/Formatter";
export class BaseConfig {
private defaultTag!: string;
private defaultLevel!: string;
private defaultFormat: string = "string";
private defaultFormatter!: Formatter;
private defaultStorageMethod: string = "console";
private defaultPersistable!: Persistable;
private tag!: string;
private level!: string;
private storageMethod!: Persistable;
private formatter!: Formatter;
constructor(json?: any) {
this.setDefault();
this.fromJson(json);
}
private setDefault(): void {
this.defaultTag = "no-tag";
this.defaultLevel = Levels.INFO;
this.defaultFormatter = FormatterFactory.create(this.defaultFormat);
this.defaultPersistable = PersistableFactory.create(this.defaultStorageMethod);
}
private fromJson(json: any): void {
const method = json && json.storage ? json.storage.method : null;
const resource = json && json.storage ? json.storage.resource : null;
this.tag = json && json.tag || this.defaultTag;
this.level = json && json.level || this.defaultLevel;
this.storageMethod = PersistableFactory.create(method || this.defaultStorageMethod)
.setResource(resource);
this.formatter = FormatterFactory.create(json && json.format || this.defaultFormat);
}
public getTag(): string {
return this.tag;
}
public getLevel(): string {
return this.level;
}
public getStorageMethod(): Persistable {
return this.storageMethod;
}
public getFormatter(): Formatter {
return this.formatter;
}
public getDefaultStorageMethod(): Persistable {
return this.defaultPersistable;
}
public getDefaultFormatter(): Formatter {
return this.defaultFormatter;
}
public setTag(tag: string): void {
this.tag = tag;
}
public setLevel(level: string): void {
this.level = level;
}
public setStorageMethod(storageMethod: Persistable): void {
this.storageMethod = storageMethod;
}
public setFormatter(formatter: Formatter): void {
this.formatter = formatter;
}
}
|
8af138f1815de67abc2b33cf0f554a2e123c0294 | TypeScript | juriousts/jurious | /packages/templates/src/models/DecoratorTemplate.ts | 2.703125 | 3 | import { ITemplate } from "../interfaces/ITemplate";
export class DecoratorTemplate implements ITemplate {
protected params: object;
constructor(private name: string) {}
private get Params(): string {
return JSON.stringify(this.params, null, "\t").replace('"', "");
}
private get Name(): string {
return this.name;
}
public generate(): string {
return `@${this.Name}(${this.Params})`;
}
}
|
788506429dbc5e5c47d5443226d60d9e04eb0e67 | TypeScript | fanhualei/wukong-antdpro | /doc/test-temp/src/pages/store/storeHelp/list/_mock.ts | 2.515625 | 3 | import { Request, Response } from 'express';
import { parse } from 'url';
import { HelpItem, HelpListParams } from './data.d';
import { getRandomNumber, isInNumberArray } from '../../../../utils/Wk/tools'
let helpListDataSource: HelpItem[] = [];
for (let i = 1; i < 30; i += 1) {
let helpTitle:string = `帮助文章-${i}`;
if (i === 3) {
helpTitle = '修改这个会模拟错误'
}
helpListDataSource.push({
helpId: i,
helpSort: i,
helpTitle,
helpInfo: `这个是正文的内容${i}`,
updateTime: new Date(`2017-07-${Math.floor(i / 2) + 1} 8:10:10`),
// updateTime: new Date(),
pageShow: 1,
typeId: getRandomNumber(1, 15),
});
}
function queryHelpById(req: Request, res: Response) {
const helpId:number = Number(req.query.helpId)
const result:HelpItem = helpListDataSource.filter(item => item.helpId === helpId)[0]
setTimeout(() => res.json(result), 1000);
}
function updateHelp(req: Request, res: Response) {
const newItem:HelpItem = <HelpItem>req.body;
if (!newItem.helpId || newItem.helpId === 0) {
let maxSgId:number = 0;
helpListDataSource.forEach(v => {
if (v.helpId > maxSgId) {
maxSgId = v.helpId;
}
});
newItem.helpId = maxSgId + 1;
helpListDataSource.push(newItem);
} else {
if (newItem.helpId === 3) {
return res.status(500).json({
status: 500,
error: 'Bad Request',
message: '参数无效',
code: 30101,
path: '/result/exception',
exception: 'com.wukong.core.exceptions.BusinessException',
errors: {
name: '长度需要在6和50之间',
email: '不是一个合法的电子邮件地址',
},
timestamp: '2018-05-31T09:41:16.461+0000',
});
}
for (let i:number = 0; i < helpListDataSource.length; i += 1) {
if (helpListDataSource[i].helpId === newItem.helpId) {
helpListDataSource[i] = {
...helpListDataSource[i],
...newItem,
};
break;
}
}
}
return res.json(newItem.helpId);
}
function queryHelp(req: Request, res: Response, u: string) {
let url = u;
if (!url || Object.prototype.toString.call(url) !== '[object String]') {
// eslint-disable-next-line prefer-destructuring
url = req.url;
}
let dataSource = helpListDataSource.concat();
const params = (parse(url, true).query as unknown) as HelpListParams;
if (!params.sorter) {
params.sorter = 'helpSort_aescend'
}
const s = params.sorter.split('_');
dataSource = dataSource.sort((prev, next) => {
if (s[1] === 'descend') {
return next[s[0]] - prev[s[0]];
}
return prev[s[0]] - next[s[0]];
});
if (params.helpTitle) {
dataSource = dataSource.filter(
data => data.helpTitle.indexOf(params.helpTitle) > -1);
}
if (params.typeId) {
dataSource = dataSource.filter(
data => data.typeId === Number(params.typeId));
}
let pageSize = 10;
if (params.pageSize) {
pageSize = parseInt(`${params.pageSize}`, 0);
}
const result = {
list: dataSource,
pagination: {
total: dataSource.length,
pageSize,
current: parseInt(`${params.currentPage}`, 10) || 1,
},
};
return res.json(result);
}
function deleteOneHelp(req: Request, res: Response) {
const { helpId } = req.body;
helpListDataSource = helpListDataSource.filter(item => helpId !== item.helpId);
return res.json(1);
}
function deleteManyHelp(req: Request, res: Response) {
const { helpIds } = req.body;
helpListDataSource = helpListDataSource.filter(item => !isInNumberArray(helpIds, item.helpId));
return res.json(1);
}
export default {
'GET /api/shop/help/queryHelpById': queryHelpById,
'GET /api/shop/help/queryHelp': queryHelp,
'POST /api/shop/help/deleteOneHelp': deleteOneHelp,
'POST /api/shop/help/deleteManyHelp': deleteManyHelp,
'POST /api/shop/help/updateHelp': updateHelp,
};
|
b4d537673c68149c321d09bb7fa748028409d625 | TypeScript | SundareshanB/Acumen | /src/models/uom.model.ts | 2.640625 | 3 | import {Entity, model, property} from '@loopback/repository';
@model()
export class Uom extends Entity {
@property({
type: 'string',
id: true,
generated: true,
})
id?: string;
@property({
type: 'string',
required: true,
unique:true
})
uom: string;
constructor(data?: Partial<Uom>) {
super(data);
}
}
export interface UomRelations {
// describe navigational properties here
}
export type UomWithRelations = Uom & UomRelations;
|
fa96e91685c4bc4b2197378cad2c78ebb2bd359a | TypeScript | celsobonutti/bank | /assets/ts/src/utils/__test__/parseMoney.test.ts | 2.9375 | 3 | import { parseMoney } from '../parseMoney';
describe('parseMoney(money: string)', () => {
test('parses 0 reais correctly', () => {
const money = parseMoney('R$ 0,00');
expect(money).toBe(0);
});
test('parses numbers with thousands', () => {
const money = parseMoney('R$ 1.450,00');
expect(money).toBe(1450);
});
test('parses number with more than one thousand separator', () => {
const money = parseMoney('R$ 1.200.450,25');
expect(money).toBe(1200450.25);
});
});
|
22669fcc95472ac0da6470bf90f37717e94e9806 | TypeScript | scw1021/bacb-angularj | /src/app/_models/registration.ts | 2.78125 | 3 | import { IRegistration } from "../_interfaces/i-registration";
import { IUser } from '../_interfaces/i-user';
import { ListObject } from "./list-object";
import { Phone } from "./phone";
import { User } from "./user";
export class Registration extends User {
public Prefix: ListObject = new ListObject();
public Suffix: ListObject = new ListObject();
public FirstName: string = '';
public MiddleName: string = '';
public LastName: string = '';
public Phone: Phone = new Phone();
public AltPhone: Phone = new Phone();
public MobilePhone: Phone = new Phone();
public constructor(Param1?: IRegistration) {
super(Param1);
if (Param1) {
if (Param1.Prefix) {
this.Prefix = new ListObject(Param1.Prefix);
}
if (Param1.Suffix) {
this.Suffix = new ListObject(Param1.Suffix);
}
this.FirstName = Param1.FirstName;
this.MiddleName = Param1.MiddleName;
this.LastName = Param1.LastName;
this.Phone = new Phone(Param1.Phone);
this.AltPhone = new Phone(Param1.AltPhone);
this.MobilePhone = new Phone(Param1.MobilePhone);
}
}
public get FullName() : string {
let Name = this.MiddleName ? this.FirstName + " " + this.MiddleName + " " + this.LastName : this.FirstName + " " + this.LastName;
if (this.Prefix && this.Prefix.Value !== '') {
Name = this.Prefix.Value + " " + Name;
}
if (this.Suffix && this.Suffix.Value !== '') {
Name += " " + this.Suffix.Value;
}
return Name;
}
public SetMobile(Primary: boolean, Secondary: boolean) {
if (Primary) {
this.MobilePhone = this.Phone;
} else if (Secondary) {
this.MobilePhone = this.AltPhone;
}
}
public Erase() {
super.Erase();
this.Prefix.Erase();
this.Suffix.Erase();
this.FirstName = "";
this.MiddleName = "";
this.LastName = "";
this.Email = "";
this.Phone.Erase();
this.AltPhone.Erase();
this.MobilePhone.Erase();
// this.Username = "";
}
public Export() : IRegistration {
let UserExport: IUser = super.Export();
return Object.assign(UserExport, {
'Prefix' : this.Prefix.Export(),
'Suffix' : this.Suffix.Export(),
'FirstName' : this.FirstName,
'MiddleName' : this.MiddleName,
'LastName' : this.LastName,
'FullName' : this.FullName,
'Email' : this.Email,
'Phone' : this.Phone.Export(),
'AltPhone' : this.AltPhone.Export(),
'MobilePhone' : this.MobilePhone.Export()})
}
}
|
327387be3218234831b0d75d735e4a3c97819801 | TypeScript | moexplore/TypeScript-Dicey-Business | /dice.ts | 3.375 | 3 | let button: HTMLButtonElement = document.getElementById("generatedie") as HTMLButtonElement;
let dieContainer: HTMLDivElement = document.getElementById("dieContainer") as HTMLDivElement;
let rollButton: HTMLButtonElement = document.getElementById("rolldie") as HTMLButtonElement;
let sumButton: HTMLButtonElement = document.getElementById("sumdie") as HTMLButtonElement;
let sumContainer: HTMLDivElement = document.createElement("div") as HTMLDivElement;
sumContainer.classList.add("sumContainer");
document.body.appendChild(sumContainer);
let globalarr: Die[] = [];
class Die {
value: number;
div: HTMLDivElement;
constructor() {
// let value = roll()
this.div = document.createElement("div") as any;
this.value = Math.floor(Math.random() * 6) + 1;
this.div.classList.add("die");
dieContainer.appendChild(this.div);
this.roll();
this.remover()
this.update();
};
roll() {
globalarr.push(this);
this.div.append(this.value.toString());
};
remover() {
this.div.addEventListener('dblclick', () => {
console.log("hey")
globalarr.splice(globalarr.indexOf(this), 1)
this.div.remove()
})
};
update() {
this.div.addEventListener("click", () => {
globalarr.splice(globalarr.indexOf(this), 1)
this.value = Math.floor(Math.random() * 6) + 1;
this.div.innerText = ''
this.div.append(this.value.toString());
globalarr.push(this)
});
};
}
button.addEventListener("click", function () {
new Die();
});
sumButton.addEventListener("click", () => {
sumContainer.innerText = '';
let sumDice = 0;
globalarr.forEach((total) => {
// total = parseInt(this.value);
sumDice += total.value;
});
console.log(sumDice);
sumContainer.append(
`The sum of all the dice heretofore mentioned on this most awesome of a website is ${sumDice}`
);
});
rollButton.addEventListener("click", () => {
globalarr.forEach((num) => {
num.div.innerText = '';
num.value = Math.floor(Math.random() * 6) + 1;
num.div.append(num.value.toString());
});
console.log(globalarr);
});
|
1146781ce6bcddf7e7397775df34240f0d8a8714 | TypeScript | eric-acosta/typescript | /app.ts | 3.03125 | 3 | (()=>{
const sumar = (a:number, b:number):number=> {
return a +b;
}
const nombre= ():string => ' hola eric';
const obtenerSalario = ():Promise<string> => {
return new Promise ((resolve,reject)=>{
resolve('Eric');
});
}
obtenerSalario().then(a => console.log(a.toUpperCase));
})();
|
f2299b7f07f926f0adc15ae507db4d28a5dfc4e9 | TypeScript | skstef/testToDo | /utils/tasks/deleteTask.ts | 2.65625 | 3 | import { IProject } from "../../models/IProject";
export const deleteTask = (
projectId: string,
taskId: string,
parentTaskId?: string
): void => {
const projects: IProject[] = JSON.parse(
(typeof window !== "undefined" &&
window.localStorage.getItem("projects")) ||
"[]"
);
const project = projects.find(({ id }) => id === projectId);
if (project) {
if (parentTaskId) {
const parentTask = project.tasks.find(({ id }) => id === parentTaskId);
if (parentTask) {
parentTask.subTasks = parentTask.subTasks.filter(
({ id }) => id !== taskId
);
}
} else {
project.tasks = project.tasks.filter(({ id }) => id !== taskId);
}
}
localStorage.setItem("projects", JSON.stringify(projects));
};
|
ed46b5f90856873dfbb71a5dc18e9b8bf01053b2 | TypeScript | micahtessler/causal-diagram | /src/app/pattern.service.spec.ts | 2.59375 | 3 |
import { PatternService } from './pattern.service';
import deathFromAbove from './patterns/deathFromAbove.json';
import earlyDouble from './patterns/earlyDouble.json';
import feed from './patterns/feed.json';
import fourCount from './patterns/fourCount.json';
import lateDouble from './patterns/lateDouble.json';
import leftCastle from './patterns/leftCastle.json';
import leftDoubles from './patterns/leftDoubles.json';
import rightCastle from './patterns/rightCastle.json';
import rightTriple from './patterns/rightTriple.json';
import selfTriple from './patterns/selfTriple.json';
import TenClubThreeCountTriangle from './patterns/TenClubThreeCountTriangle.json';
import threeCount from './patterns/threeCount.json';
import threeCountWith441 from './patterns/threeCountWith441.json';
import TriangleThing from './patterns/TriangleThing.json';
import { Pattern } from './model/Pattern';
describe('PatternService', () => {
let service: PatternService;
beforeEach(() => {
service = new PatternService();
}
);
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('clubCount', () => {
it('should calculate the correct number of clubs in 4 count', () => {
const count = service.clubCount(fourCount as Pattern);
expect(count).toEqual(6);
});
it('should calculate the correct number of clubs in 4 count', () => {
const count = service.clubCount(TenClubThreeCountTriangle as Pattern);
expect(count).toEqual(10);
});
it('should calculate the correct number of clubs in 4 count', () => {
const count = service.clubCount(feed as Pattern);
expect(count).toEqual(9);
});
});
describe('addPattern', () => {
beforeEach(() => {
service.patterns = [
fourCount as Pattern
];
});
it('should add a new pattern', () => {
const newPattern = <Pattern>TenClubThreeCountTriangle;
service.addPattern(newPattern);
expect(service.patterns.length).toEqual(2);
expect(service.patterns[1]).toEqual(newPattern);
});
it('should replace an existing pattern', () => {
service.patterns.push(feed as Pattern);
const newPattern = <Pattern>TenClubThreeCountTriangle;
newPattern.name = feed.name;
service.addPattern(newPattern);
expect(service.patterns.length).toEqual(2);
expect(service.patterns[1]).toEqual(newPattern);
});
});
});
|
498bdbc9a3bb987e8833296a7e0f44ea6dfcf74e | TypeScript | KrishnaK-Z/Samosa | /src/app/Services/Authentication/authenticate.service.ts | 2.578125 | 3 | import { Injectable } from '@angular/core';
import { WebRequestService } from 'src/app/Services/WebRequest/web-request.service';
import { HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { shareReplay, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthenticateService {
constructor(
private webRequestService: WebRequestService,
private route: Router
) { }
login(email: string, password: string){
return this.webRequestService.login(email, password).pipe(
shareReplay(),
tap( (response: HttpResponse<any>) =>{
// the auth tokens will be in the header of this response
this.setSession(response.body._id, response.headers.get('x-access-token'), response.headers.get('x-refresh-token'));
console.log("Logged In");
console.log(response);
} )
);
}
signup(email: string, password: string) {
return this.webRequestService.register(email, password).pipe(
shareReplay(),
tap((response: HttpResponse<any>) => {
// the auth tokens will be in the header of this response
this.setSession(response.body._id, response.headers.get('x-access-token'), response.headers.get('x-refresh-token'));
console.log("Successfully signed up and now logged in!");
})
);
}
logout(){
this.removeSession();
this.route.navigate(['/login']);
}
/**
* Stores the userID and tokens
*/
private setSession = (userId: string, accessToken: string, refreshToken: string) => {
localStorage.setItem("userId", userId);
localStorage.setItem("x-access-token", accessToken);
localStorage.setItem("x-refresh-token", refreshToken);
}
private removeSession = () => {
localStorage.removeItem('userId');
localStorage.removeItem('x-access-token');
localStorage.removeItem('x-refresh-token');
}
public getAccessToken () {
return localStorage.getItem('x-access-token') ? localStorage.getItem('x-access-token') : "";
}
public getRefreshToken () {
return localStorage.getItem('x-refresh-token') ? localStorage.getItem('x-refresh-token') : "";
}
public getUserId () {
return localStorage.getItem('userId') ? localStorage.getItem('userId') : "";
}
public setAccessToken (accessToken: string) {
localStorage.setItem('x-access-token', accessToken);
}
public getNewAccessToken () {
return this.webRequestService.getAccessToken(this.getUserId(),
this.getRefreshToken()).pipe(
tap( (response: HttpResponse<any>) => {
this.setAccessToken(response.headers.get('x-access-token'));
} )
);
}
}
|
27fdc454d20f769b71ebeb7e6ffc7c1fab980d15 | TypeScript | andresgutgon/react-playground | /src/hooks/useTodos.test.ts | 2.640625 | 3 | import { renderHook, act } from '@testing-library/react-hooks'
import useTodos from './useTodos'
const locale = 'en'
const initialTodos = [
{ text: 'C Third todo', resolved: false },
{ text: 'A second resolved todo', resolved: true },
{ text: 'A first resolved todo', resolved: true },
{ text: 'B second todo', resolved: false },
{ text: 'C third resolved todo', resolved: true }
]
test('should order todos alphabeticaly and resolved todos last', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
expect(result.current.todos).toEqual([
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should add a todo and sort the result', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.addTodo('A This is first now')
})
expect(result.current.todos).toEqual([
{ text: 'A This is first now', resolved: false },
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should add a todo and sort the result starting with lowercase', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.addTodo('a This is first now')
})
expect(result.current.todos).toEqual([
{ text: 'a This is first now', resolved: false },
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should not add todo with same text', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.addTodo('B second todo')
})
expect(result.current.todos).toEqual([
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should remode the todo by text', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.removeTodo('B second todo')()
})
expect(result.current.todos).toEqual([
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should not remove a non-existing todo', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.removeTodo('Do not exists')()
})
expect(result.current.todos).toEqual([
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should resolve todo', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.resolveTodo('B second todo')
})
expect(result.current.todos).toEqual([
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'B second todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should not resolve a non-existing todo', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.resolveTodo('Do not exists')
})
expect(result.current.todos).toEqual([
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should un-resolve todo', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.unresolveTodo('A first resolved todo')
})
expect(result.current.todos).toEqual([
{ text: 'A first resolved todo', resolved: false },
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('should not un-resolve a non-existing todo', () => {
const { result } = renderHook(() => useTodos({ locale, initialTodos }))
act(() => {
result.current.unresolveTodo('Do not exists')
})
expect(result.current.todos).toEqual([
{ text: 'B second todo', resolved: false },
{ text: 'C Third todo', resolved: false },
{ text: 'A first resolved todo', resolved: true },
{ text: 'A second resolved todo', resolved: true },
{ text: 'C third resolved todo', resolved: true }
])
})
test('reset method', () => {
const { result } = renderHook(() => useTodos({
locale,
initialTodos: [{ text: 'onlyOne', resolved: false }]
}))
act(() => {
result.current.addTodo('A Another todo')
result.current.addTodo('B Another todo')
result.current.addTodo('C Another todo')
})
expect(result.current.todos).toEqual([
{ text: 'A Another todo', resolved: false },
{ text: 'B Another todo', resolved: false },
{ text: 'C Another todo', resolved: false },
{ text: 'onlyOne', resolved: false }
])
act(() => { result.current.reset() })
expect(result.current.todos).toEqual([
{ text: 'onlyOne', resolved: false }
])
})
|
89ced8220a4c3429c138948e8962a66b778e4124 | TypeScript | che-ri/TS-Pratice | /Typescript/src/practice.ts | 4.375 | 4 | //1. 변수에서 타입 정의하기
let count = 0;
count += 1;
// count = "갑자기 분위기 문자열"; //숫자로 선언되었던 count를 문자열로 업데이트하면 에러난다!
const message: string = "hello world"; //문자열
const done: boolean = true; //불리언 값
const numbers: number[] = [1, 2, 3]; //숫자 배열
const messages: string[] = ["hello", "world"]; //문자열 배열
// messages.push(1); //숫자를 넣으려고 하면 안된다!
let mightBeUndefined: string | undefined = undefined; // string 또는 undefined
let nullableNumber: number | null = null; // number 또는 null
let color: "red" | "orange" | "yellow" = "red"; // 'red', 'orange', 'yellow' 중 하나
color = "yellow";
// color = "green"; //에러 발생!
//2. 함수에서 타입 정의하기
function sum(x: number, y: number): number {
//매개변수 x는 number, y는 number 그리고 결과값은 number이라고 명시하였다.
// return null; 을 하면 결과값이 number이 아니니 오류가 난다!
return x + y;
}
sum(1, 2);
function sumArray(number: number[]): number {
return numbers.reduce((acc, cur) => acc + cur, 0); //acc, cur에 커서를 올려보면 타입 유추가 되어 편리하다!
}
const total = sumArray([1, 2, 3, 4, 5]);
function returnNothing(): void {
//아무것도 반환하지 않아야 한다면 void로 명시한다.
console.log("I am just saying hello world");
}
//3. interface 사용하기
//interface는 타입을 정의한 규칙이며, 클래스, 객체를 위한 타입을 지정할 때 사용되는 문법이다.
//3-1 클래스에서 interface사용하기
interface Shape {
getArea(): number; //Shape interface에서 getArea라는 함수가 꼭 있어야 하며 해당 함수의 반환값은 number이다.
}
class Circle implements Shape {
//'implements' 키워드를 사용하여 해당 클래스가 Shape interface의 조건을 충족하겠다는 것을 명시합니다.
constructor(public radius: number) {} //constructor 파라미터에 접근 제한자를 선언하면 암묵적으로 클래스프로퍼티선언이 이루어진다. public은 외부에서 참조가능
//너비를 가져오는 함수를 구현합니다. getArea라는 함수를 만들지 않는다면 오류가 생긴다.
getArea() {
return this.radius * this.radius * Math.PI;
}
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
//constructor 파라미터에 접근 제한자를 선언하면 암묵적으로 클래스프로퍼티선언이 이루어진다. private은 클래스 내부와 상속된 곳에서만 참조가능
getArea() {
return this.width * this.height;
}
}
//아래처럼 타입 지정가능
const circle = new Circle(5);
//함수처럼 구현가능
function getCircleArea(circle: Circle) {
return circle.getArea();
}
//Shape라는 인터페이스배열로 이루어지게 타입 지정가능
const shapes: Shape[] = [new Circle(5), new Rectangle(10, 5)];
shapes.forEach((shape) => console.log(shape.getArea())); //이렇게 내부에 있는 getArea() 사용가능
//3-2 객체에서 interface 사용하기
interface Person {
name: string;
age?: number; //?은 옵셔널체이닝이다. 선택적 설정값이다.
}
// interface Developer {
// name: string;
// age?: number;
// skills: string[];
// }
// 위의 코드에서 Developer 인터페이스는 Person 인터페이스와 구조가 비슷하므로 아래처럼 extend 구문을 활용할 수 있다.
interface Developer extends Person {
skills: string[];
}
const person: Person = {
name: "지영",
age: 28, //옵셔널체이닝이 걸린 프로퍼티를 사용하면 타입값에 undefined도 추가된다. 따라서 age의 타입은 number | undefined 이다.
};
const expert: Developer = {
name: "셰리",
skills: ["javascript", "react"],
};
//4. Type Alias 사용하기
//type은 특정 타입에 별칭을 붙이는 용도로 사용합니다.
type PersonType = {
name: string;
age?: number;
};
//&은 교차타입(intersection Type)으로서 두개 이상의 타입을 합쳐줍니다.
type DeveloperType = PersonType & {
skills: string[];
};
const person2: PersonType = {
name: "지영",
};
const expert2: DeveloperType = {
name: "셰리",
skills: ["javascript", "react"],
};
type PeopleType = PersonType[]; // PersonType[] 를 이제 앞으로 PeopleType 이라는 타입으로 사용 할 수 있습니다.
const people: PeopleType = [person2, expert2]; //콘솔 찍으면 array object로 나온다.
type Color = "red" | "orange" | "yellow";
const redColor: Color = "red";
const colors: Color[] = ["red", "orange"];
//5. Generics 사용하기
//제너릭(Generics)은 타입스크립트에서 함수, 클래스, interface, type alias 를 사용하게 될 때 여러 종류의 타입에 대하여 호환을 맞춰야 하는 상황에서 사용하는 문법입니다.
//https://joshua1988.github.io/ts/guide/generics.html#%EC%A0%9C%EB%84%A4%EB%A6%AD%EC%9D%98-%ED%95%9C-%EC%A4%84-%EC%A0%95%EC%9D%98%EC%99%80-%EC%98%88%EC%8B%9C
//5-1. 함수에서 Generics 사용하기
//아래와 같은 상황에서 Generics를 사용할 수 있습니다
// function merge(a: any, b: any): any {
// return {
// ...a,
// ...b,
// };
// }
// const merged = merge({ foo: 1 }, { bar: 1 });
//위의 코드는 아래처럼 구현할 수 있습니다.
function merge<A, B>(a: A, b: B): A & B {
return { ...a, ...b };
}
const merged = merge({ foo: 1 }, { bar: 1 });
function wrap<T>(param: T) {
return {
param, //return 축약형을 쓰면 타입이 찍히지 않는다.
};
}
const wrapped = wrap(10);
//5-2. interface에서 generics사용하기
interface Items<T> {
list: T[];
}
const items: Items<string> = {
list: ["a", "b", "c"],
};
//5-3. type에서 generics 사용하기
type ItemsType<T> = {
list: T[];
};
const itemsUsingType: ItemsType<string> = {
list: ["a", "b", "c"],
};
//5-4. class에서 generics 사용하기
class Queue<T> {
list: T[] = [];
enqueue(item: T) {
this.list.push(item);
}
dequeue() {
return this.list.shift();
}
}
const queue = new Queue<number>();
queue.enqueue(0);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
console.log(queue.dequeue());
|
c16976f5de6d13161e9480e20bf11f17d58f339c | TypeScript | star47raven/model | /packages/shell/helpers/ThemeHelper.ts | 2.546875 | 3 | import { css, unsafeCSS } from '../../library'
import { DocumentHelper, LocalStorageEntry, Color } from '../../utilities'
import { Background } from '.'
export class ThemeHelper {
static readonly background = new class extends LocalStorageEntry<Background> {
constructor() {
super('MoDeL.Theme.Theme', Background.System)
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => this.value = this.calculatedValue)
}
get calculatedValue() {
return this.value === Background.System
? window.matchMedia('(prefers-color-scheme: dark)').matches
? Background.Dark
: Background.Light
: this.value
}
}
static readonly accent = new class extends LocalStorageEntry<Color> {
private styleElement?: HTMLStyleElement
constructor() {
super(
'MoDeL.Theme.Accent',
new Color('rgb(0, 119, 200)'),
(key: string, value: any) => key.length === 0 ? new Color(...value.colors) : value
)
this.value = this.value
}
override get value() { return super.value }
override set value(value) {
super.value = value
this.styleElement = DocumentHelper.injectCSS(css`
#application {
--mo-accent-base-r:${unsafeCSS(value.baseColor[0])};
--mo-accent-base-g:${unsafeCSS(value.baseColor[1])};
--mo-accent-base-b:${unsafeCSS(value.baseColor[2])};
--mo-accent-gradient-1: ${unsafeCSS(value.colors[0])};
--mo-accent-gradient-2: ${unsafeCSS(value.colors[1] ?? value.colors[0])};
--mo-accent-gradient-3: ${unsafeCSS(value.colors[2] ?? value.colors[1] ?? value.colors[0])};
}
`, this.styleElement)
}
}
} |
4ccfeb9e60a503ac2309a538a885d02a1a6ac1f0 | TypeScript | domenester/nest-initializer | /src/list/list.service.ts | 2.59375 | 3 | import { Injectable } from '@nestjs/common'
import { ListFilter } from '../dtos'
import { ObjectLiteral, Like, Between } from 'typeorm'
export interface BuildListFilter extends ListFilter {
fields: string []
}
@Injectable()
export class ListService {
buildFilter(filter: BuildListFilter): ObjectLiteral {
if (!filter) return {}
const { search, range } = filter
let where = []
if (search) {
filter.fields.forEach( field => where.push({ [field] : Like(`%${filter.search}%`) }))
if (range && range.from && range.to) {
const field = range.field || 'createdAt'
where = where.map( w => ({ ...w, [field]: Between(range.from, range.to)}))
}
return { where }
}
if (range && range.from && range.to) {
const field = range.field || 'createdAt'
where.push({ [field]: Between(range.from, range.to)})
return { where }
}
}
}
|
f8c65cce373783045a77a4dbad47f09b1a45d491 | TypeScript | LesterWeng/tiny-libs | /tiny-html-parser/index.ts | 3.703125 | 4 | enum TokenType {
START_TAG,
END_TAG,
TEXT,
GLOBAL,
}
type Token = {
value: string
type: number
children?: Token[]
}
const HTML_REG = {
startTag: /^<[a-z]+>/,
endTag: /^<\/[a-z]+>/,
}
// tokenizer
const htmlToToken: (html: string) => Token[] = (
html,
) => {
const tokens = []
while (html) {
if (html.startsWith('<')) {
let match = null
let value = ''
if (
(match = html.match(HTML_REG.startTag)) &&
(value = match[0].slice(1, -1))
) {
tokens.push({
value,
type: TokenType.START_TAG,
})
html = html.slice(value.length + 2)
} else if (
(match = html.match(HTML_REG.endTag)) &&
(value = match[0].slice(2, -1))
) {
tokens.push({
value,
type: TokenType.END_TAG,
})
html = html.slice(value.length + 3)
} else {
throw new Error('暂未处理的情况')
}
} else {
const textEndIndex = html.indexOf('<')
if (textEndIndex > 0) {
tokens.push({
value: html.slice(0, textEndIndex),
type: TokenType.TEXT,
})
html = html.slice(textEndIndex)
} else {
tokens.push({
value: html,
type: TokenType.TEXT,
})
html = ''
}
}
}
return tokens
}
const pushChild = (
prevToken: Token,
token: Token,
) => {
if (!prevToken.children) {
prevToken.children = []
}
prevToken.children.push(token)
}
// parser
const tokenToAst: (tokens: Token[]) => any = (
tokens,
) => {
let index = 0
let token = null
const stack = [
{
value: '',
type: TokenType.GLOBAL,
},
]
while ((token = tokens[index])) {
const prevToken = stack[stack.length - 1]
switch (token.type) {
case TokenType.START_TAG:
if (
prevToken &&
[
TokenType.GLOBAL,
TokenType.START_TAG,
].includes(prevToken.type)
) {
pushChild(prevToken, token)
}
stack.push(token)
break
case TokenType.END_TAG:
if (
prevToken &&
[
TokenType.GLOBAL,
TokenType.START_TAG,
].includes(prevToken.type)
) {
stack.pop()
}
break
case TokenType.TEXT:
pushChild(prevToken, token)
break
}
index++
}
return stack[0]
}
const html = `
<html>
<body>
<div>1</div>
<div>2</div>
</body>
</html>
`
const tokens = htmlToToken(html)
const ast = tokenToAst(tokens)
console.log(JSON.stringify(ast))
|
1e2c65b82f0b4cab6caa442b4653f8e4c589951e | TypeScript | jameswilddev/trash-kit | /src/pipeline/stores/key-value-store.ts | 3.1875 | 3 | import StoreBase from './store-base'
export default class KeyValueStore<TValue> extends StoreBase {
private readonly keysAndValues = new Map<string, TValue>()
hasKey (
key: string
): boolean {
return this.keysAndValues.has(key)
}
get (
key: string
): TValue {
if (this.hasKey(key)) {
return this.keysAndValues.get(key) as TValue
} else {
throw new Error(`Unable to get key ${JSON.stringify(key)} which is not currently set in store "${this.name}".`)
}
}
getAll (): ReadonlyMap<string, TValue> {
return new Map(this.keysAndValues)
}
tryGet (
key: string
): null | TValue {
if (this.hasKey(key)) {
return this.keysAndValues.get(key) as TValue
} else {
return null
}
}
set (
key: string,
value: TValue
): void {
if (this.hasKey(key)) {
throw new Error(`Unable to set key ${JSON.stringify(key)} which is already set in store "${this.name}".`)
} else {
this.keysAndValues.set(key, value)
}
}
deleteIfSet (
key: string
): void {
this.keysAndValues.delete(key)
}
}
|
b1b2a79a261888a82f4d4f1f19c9d25a873fc796 | TypeScript | humpback-app/humpback-server | /src/routes/auth.ts | 2.5625 | 3 | import bcrypt from 'bcrypt';
import {usersAccounts} from '../database.js';
import {setUserInfo} from '../common/setUserInfo.js';
import * as Schema from '../schema/index.js';
import type {FastifyInstance} from 'fastify';
/**
* A cryptographic salt is made up of random bits added
* to each password instance before its hashing.
* Salts create unique passwords even in the instance of
* two users choosing the same passwords.
*/
const saltRounds = 10;
/**
* Create user index for faster query performance
* Strength 2 means case insensitive search
*/
const collation = {locale: 'en', strength: 2};
const auth = async (fastify: FastifyInstance) => {
// User login
fastify.post<{Body: Schema.LoginType}>('/login', {schema: {body: Schema.Login}}, async (res, reply) => {
res.body.email = res.body.email.toLowerCase();
const user = await usersAccounts.findOne({email: res.body.email}, {collation});
if (user && bcrypt.compareSync(res.body.password, user.password)) {
const {_id, username, role} = user;
const token = fastify.jwt.sign({_id, username, role});
return {token};
}
reply.code(401).send('Invalid credentials');
});
// User signup
fastify.post<{Body: Schema.SignupType}>('/signup', {schema: {body: Schema.Signup}}, async (res, reply) => {
res.body.email = res.body.email.toLowerCase();
const user = await usersAccounts.findOne(
{$or: [{email: res.body.email}, {username: res.body.username}]},
{collation},
);
if (user || res.body.username.toLowerCase().trim() === 'ghost') {
reply.code(409).send('User already exists with that username or email.');
return;
}
const userCount = await usersAccounts.countDocuments();
if (userCount === 0) {
usersAccounts.createIndex({username: 1, email: 1}, {collation});
res.body.role = 'admin';
} else {
res.body.role = 'subscriber';
}
res.body.password = await bcrypt.hash(res.body.password, saltRounds);
const created = await setUserInfo(res.body);
reply.code(201).send(created);
});
};
export default auth;
|
837d52d54ada39d338a3e1f23f1f50a111a654c7 | TypeScript | JustusPu/bachelor-thesis | /visualization/app/src/app/api/cloud.ts | 2.578125 | 3 | import { Anchor } from "./anchor";
import { functions } from './functions';
import { MessageService } from 'primeng/components/common/messageservice';
export class Cloud {
anchors: Anchor[];
determinedAnchors: Anchor[];
constructor(private messageService: MessageService) {
this.anchors = [];
this.determinedAnchors = [];
}
addNode(name, pos) {
if (this.getNodeByName(name) == null) {
let node = new Anchor(name, pos);
this.anchors.push(node);
return node;
}
return null;
}
removeNode(name) {
let node = this.getNodeByName(name)
if (node != null) {
this.anchors.forEach(function (elem) { elem.deleteNeighbour(this) }, node);
this.anchors = this.anchors.filter(function (elem) { return elem != node });
return true;
}
return false;
}
addDist(nameA, nameB, dist) {
let nodeA = this.getNodeByName(nameA);
let nodeB = this.getNodeByName(nameB);
if (nodeA && nodeB) {
nodeA.addNeighbour(nodeB, dist);
nodeB.addNeighbour(nodeA, dist);
return true;
}
return false;
}
getDist(range, deviation) {
let result = "";
for (let i = 0; i < this.anchors.length; i++) {
result += this.anchors[i].getNeighboursString();
/*for(j=0;j<this.anchors.length;j++){
if(i!=j){
let distance = Math.sqrt(Math.pow(this.anchors[i].pos.x - this.anchors[j].pos.x, 2) + Math.pow(this.anchors[i].pos.y - this.anchors[j].pos.y, 2) + Math.pow(this.anchors[i].pos.z - this.anchors[j].pos.z, 2));
if(distance<range+getRandom(-deviation,deviation)){
result+=this.anchors[i].name+";"+this.anchors[j].name+";"+distance+"\n";
}
}
}*/
}
return result
}
getNodeByName(name) {
return this.anchors.filter(function (element) { return element.name == name; })[0] || null;
}
randomAnchors(count, min, max) {
for (let i = 0; i < count; i++) {
let node = new Anchor(i, { "x": functions.getRandom(min, max), "y": functions.getRandom(min, max), "z": functions.getRandom(min, max) });
this.anchors.push(node);
}
}
calcAllNeighbours(range, deviation) {
for (let i = 0; i < this.anchors.length; i++) {
this.calcNeighbours(this.anchors[i].name, range, deviation)
}
}
calcNeighbours(name, range, deviation) {
let node = this.getNodeByName(name);
if (node != null && node.pos != null) {
node.neighbours = [];
for (let j = 0; j < this.anchors.length; j++) {
if (node.name != this.anchors[j].name && this.anchors[j].pos != null) {
let distance = Math.sqrt(Math.pow(node.pos.x - this.anchors[j].pos.x, 2) + Math.pow(node.pos.y - this.anchors[j].pos.y, 2) + Math.pow(node.pos.z - this.anchors[j].pos.z, 2));
if (distance < range + functions.getRandom(-deviation, deviation)) {
node.addNeighbour(this.anchors[j], distance);
}
}
}
}
}
toString(accuracy) {
//this.anchors.forEach(function(elem){if(elem.pos){pos=roundV(elem.pos,2);console.log(elem.name+":{x:"+pos.x+",y:"+pos.y+",z:"+pos.z+"}")}else{console.log(elem.name+":Position unbestimmt")}});
let result = "";
this.anchors.forEach(elem => {
if (elem.pos) {
let pos = functions.vec2Pos(functions.roundV(functions.pos2Vec(elem.pos), accuracy));
result += elem.name + ":Punkt(" + pos.x + "," + pos.y + "," + pos.z + ")\n";
}
else {
result += (elem.name + ":Position unbestimmt\n")
}
});
return result.slice(0, -1);
}
clearPositions() {
for (let i = 0; i < this.anchors.length; i++) {
this.anchors[i].pos = null;
}
}
async calcPositions() {
console.log("Berechnung gestartet");
let clouds = this.getCompletedClouds();
console.log("Vollständige Ankerwolken bestimmt");
// this.messageService.add({sticky:true,severity:'success', summary: 'Vollständige Ankerwolken bestimmt', detail:'Für mehr Details bitte die Konsole öffnen'});
// console.log(clouds);
for (let i = 0; i < clouds.length; i++) {
if (this.setGroundAnchors(clouds[0])) { break; }
clouds.push(clouds.shift());
}
if (this.determinedAnchors.length > 3) {
for (let i = 0; i < clouds.length; i++) {
//let intersection = clouds[i].filter(function(elem) { return this.indexOf(elem) >-1; },this.determinedAnchors);
let intersection = this.determinedAnchors.filter(function (elem) { return this.indexOf(elem) > -1; }, clouds[i]);
let s = this.getFourIndependentAnchors(intersection, false)
if (s.length > 3) {
let difference = clouds[i].filter(function (elem) { return this.indexOf(elem) < 0; }, this.determinedAnchors);
for (let k = 0; k < difference.length; k++) {
this.setAbsolutePosition(s, difference[k]);
};
clouds.splice(i, 1);
i = -1;
}
}
let undefinedAnchors = this.anchors.filter(function (elem) { return elem.pos == null });
if (undefinedAnchors.length > 0) {
console.log("Es konnten NICHT alle Anker eindeutig bestimmt werden!");
this.messageService.add({ sticky: true, severity: 'info', summary: 'Nicht alle Anker konnten bestimmt werden!', detail: 'Für mehr Details bitte die Konsole öffnen' });
console.log("Gegebenenfalls müssen mehr Anker im Gebäude plaziert werden.");
// console.log("Folgende Anker konnten nicht bestimmt werden:");
// undefinedAnchors.forEach(function(elem){console.log(elem.name)});
}
else {
console.log("Alle Anker konnten bestimmt werden!");
this.messageService.add({ sticky: true, severity: 'success', summary: 'Alle Anker bestimmt', detail: '' });
}
//console.log("Folgende Ankerpositionen konnten bestimmt werden:");
//this.determinedAnchors.forEach(function(elem){console.log(elem.name+":{x:"+elem.pos.x+",y:"+elem.pos.y+",z:"+elem.pos.z+"}")});
//this.determinedAnchors.forEach(function(elem){pos=roundV(elem.pos,2);console.log(elem.name+":"+pos.x+",y:"+pos.y+",z:"+pos.z+"}")});
}
else {
console.log("Keine Ankerkombination steht sozu einander, dass eine eindeutige Positionsbestimmung möglich ist.");
this.messageService.add({ sticky: true, severity: 'error', summary: 'Positionsbestimmung nicht möglich', detail: 'Keine Ankerkombination steht sozu einander, dass eine eindeutige Positionsbestimmung möglich ist.' });
}
for (let i = 0; i < this.determinedAnchors.length; i++) {
for (let j = 0; j < this.determinedAnchors.length; j++) {
if (i != j) {
this.determinedAnchors[i].addNeighbour(this.determinedAnchors[j], Math.sqrt(Math.pow(this.determinedAnchors[i].pos.x - this.determinedAnchors[j].pos.x, 2) + Math.pow(this.determinedAnchors[i].pos.y - this.determinedAnchors[j].pos.y, 2) + Math.pow(this.determinedAnchors[i].pos.z - this.determinedAnchors[j].pos.z, 2)));
}
}
}
}
adjustCOS(fixednodes) {
this.messageService.add({ sticky: true, severity: 'info', summary: 'Ausrichtung des Koordinatensystem gestartet', detail: 'Die bestimmten Anker werden nun anhand von fixen Ankern im Erdkoordinatensystem ausgerichtet' });
fixednodes.forEach(a => {
if (a.pos && a.pos.x && a.pos.y && a.pos.z) {
fixednodes.forEach(b => {
if (b.pos && b.pos.x && b.pos.y && b.pos.z) {
a.addNeighbour(b, Math.sqrt(Math.pow(a.pos.x - b.pos.x, 2) + Math.pow(a.pos.y - b.pos.y, 2) + Math.pow(a.pos.z - b.pos.z, 2)));
}
});
}
});
// console.log(fixednodes);
let adjustAnchor = this.getFourIndependentAnchors(fixednodes, false);
let determinedFixedNodes = [];
adjustAnchor.forEach(elem => {
let pos = this.getAbsolutePosition(elem);
if (pos) {
determinedFixedNodes.push([elem.pos, pos]);
}
});
// console.log(determinedFixedNodes);
if (determinedFixedNodes.length > 3) {
let v = [[determinedFixedNodes[0][0].x - determinedFixedNodes[1][0].x, determinedFixedNodes[0][0].y - determinedFixedNodes[1][0].y, determinedFixedNodes[0][0].z - determinedFixedNodes[1][0].z],
[determinedFixedNodes[0][0].x - determinedFixedNodes[2][0].x, determinedFixedNodes[0][0].y - determinedFixedNodes[2][0].y, determinedFixedNodes[0][0].z - determinedFixedNodes[2][0].z],
[determinedFixedNodes[0][0].x - determinedFixedNodes[3][0].x, determinedFixedNodes[0][0].y - determinedFixedNodes[3][0].y, determinedFixedNodes[0][0].z - determinedFixedNodes[3][0].z]];
let w = [[determinedFixedNodes[0][1].x - determinedFixedNodes[1][1].x, determinedFixedNodes[0][1].y - determinedFixedNodes[1][1].y, determinedFixedNodes[0][1].z - determinedFixedNodes[1][1].z],
[determinedFixedNodes[0][1].x - determinedFixedNodes[2][1].x, determinedFixedNodes[0][1].y - determinedFixedNodes[2][1].y, determinedFixedNodes[0][1].z - determinedFixedNodes[2][1].z],
[determinedFixedNodes[0][1].x - determinedFixedNodes[3][1].x, determinedFixedNodes[0][1].y - determinedFixedNodes[3][1].y, determinedFixedNodes[0][1].z - determinedFixedNodes[3][1].z]];
// console.log(w);
let u = functions.multMatrix(v, functions.invMatrix(w));
let r = functions.vec2Pos(functions.multMatrix(u, functions.pos2Vec(determinedFixedNodes[0][1])));
let x = determinedFixedNodes[0][0].x - r.x;
let y = determinedFixedNodes[0][0].y - r.y;
let z = determinedFixedNodes[0][0].z - r.z;
this.determinedAnchors.forEach(function (elem) {
elem.pos = functions.vec2Pos(functions.addVector([x, y, z], functions.multMatrix(u, functions.pos2Vec(elem.pos))));
});
this.messageService.add({ sticky: true, severity: 'success', summary: 'Ausrichtung des Koordinatensystem erfolgreich', detail: '' });
return true;
}
else {
console.log("Es konnten nicht genug RTK-Anker bestimmt werden!");
this.messageService.add({ sticky: true, severity: 'error', summary: 'Ausrichtung des Koordinatensystem fehlgeschlagen', detail: 'Für mehr Details bitte die Konsole öffnen' });
console.log("Entweder stehen keine vier fixen Anker linear unabhängig zu einander oder die fixen Anker haben keine ausreichende Bestimmung zu den Gebäude-Ankern. Es kann helfen mehr fixe Ankerpunkte einzufügen.")
// console.log("Folgende Anker konnten nicht bestimmt werden:");
// fixednodes.filter(function (elem) { return this.getNodeByName(elem.name) == null; }).forEach(function (elem) { console.log(elem.name) });
}
return false;
}
getTagPosition(node, accuracy?) {
return this.getAbsolutePosition(node);
return functions.vec2Pos(functions.roundV(functions.pos2Vec(this.getAbsolutePosition(node)), accuracy));
}
getAbsolutePosition(node) {
let intersection = node.getNeighbours().filter(function (elem) { return this.indexOf(elem) > -1 }, this.determinedAnchors);
//let intersection = this.determinedAnchors.filter(function(elem){console.log(this.indexOf(elem));return this.indexOf(elem) > -1},node.getNeighbours());
let s = this.getFourIndependentAnchors(intersection, false);
if (s.length > 3) {
return this.calcAbsolutePosition(s, node);
}
return null;
}
setAbsolutePosition(cos, node) {
node.pos = this.calcAbsolutePosition(cos, node);
this.determinedAnchors.push(node);
}
calcAbsolutePosition(cos, node) {
let a = [cos[1].pos.x - cos[0].pos.x,
cos[1].pos.y - cos[0].pos.y,
cos[1].pos.z - cos[0].pos.z];
let b = [cos[2].pos.x - cos[0].pos.x,
cos[2].pos.y - cos[0].pos.y,
cos[2].pos.z - cos[0].pos.z];
let x = functions.unitV(a);
let z = functions.unitV(functions.crossP(a, b));
let mz = [-z[0], -z[1], -z[2]];
let y = functions.unitV(functions.crossP(x, mz));
let x1 = cos[0].getDist(cos[1]);
let x2 = (Math.pow(cos[0].getDist(cos[2]), 2) - Math.pow(cos[1].getDist(cos[2]), 2) + Math.pow(x1, 2)) / (2 * x1);
let y2 = Math.sqrt(Math.pow(cos[0].getDist(cos[2]), 2) - Math.pow(x2, 2));
let d = [node.getDist(cos[0]), node.getDist(cos[1]), node.getDist(cos[2]), node.getDist(cos[3])]
let x3 = (Math.pow(d[0], 2) - Math.pow(d[1], 2) + Math.pow(x1, 2)) / (2 * x1);
let y3 = (Math.pow(d[0], 2) - Math.pow(x3, 2) - Math.pow(d[2], 2) + Math.pow(x2 - x3, 2) + Math.pow(y2, 2)) / (2 * y2);
//let z3=Math.sqrt(Math.pow(d[0],2)-Math.pow(x3,2)-Math.pow(y3,2));
//let z3 = Math.sqrt(Math.round(Math.pow(d[0],2))-Math.round(Math.pow(x3,2)-Math.pow(y3,2)));
let z3 = Math.sqrt(Math.abs(Math.pow(d[0], 2) - Math.pow(x3, 2) - Math.pow(y3, 2)));
let m1 = functions.vec2Pos(functions.addVector(functions.pos2Vec(cos[0].pos), functions.multMatrix([x, y, z], [x3, y3, z3])))
let m2 = functions.vec2Pos(functions.addVector(functions.pos2Vec(cos[0].pos), functions.multMatrix([x, y, mz], [x3, y3, z3])))
let r1 = Math.sqrt(Math.pow(cos[3].pos.x - m1.x, 2) + Math.pow(cos[3].pos.y - m1.y, 2) + Math.pow(cos[3].pos.z - m1.z, 2));
let r2 = Math.sqrt(Math.pow(cos[3].pos.x - m2.x, 2) + Math.pow(cos[3].pos.y - m2.y, 2) + Math.pow(cos[3].pos.z - m2.z, 2));
// console.log(Math.abs(d[3] - r1),Math.abs(d[3] - r2))
if (Math.abs(d[3] - r1) < Math.abs(d[3] - r2)) {
return m1
}
else {
return m2
}
}
getFourIndependentAnchors(cloud, setValues) {
for (let i = 0; i < cloud.length; i++) {
for (let j = i + 1; j < cloud.length; j++) {
if (cloud[i].getDist(cloud[j]) > 0) {
for (let k = 0; k < cloud.length; k++) {
if (k != i && k != j) {
let d = [cloud[i].getDist(cloud[j]), cloud[i].getDist(cloud[k]), cloud[j].getDist(cloud[k])].sort();
if (d[0] + d[1] != d[2]) {
d = [cloud[i].getDist(cloud[j]), cloud[i].getDist(cloud[k]), cloud[j].getDist(cloud[k])];
//d[0]:ab;d[1]:ac;d[2]:bc
let x1 = d[0]; //ab
let x2 = (Math.pow(d[1], 2) - Math.pow(d[2], 2) + Math.pow(d[0], 2)) / (2 * d[0]); //(ac^2-bc^2+ab^2)/(2*ab)
let y2 = Math.sqrt(Math.pow(d[1], 2) - Math.pow(x2, 2)); //√(ac^2-xc^2
for (let m = 0; m < cloud.length; m++) {
if (m != i && m != j && m != k) {
//d2[0]:ad;d2[1]:bd;d2[2]:cd
let d2 = [cloud[i].getDist(cloud[m]), cloud[j].getDist(cloud[m]), cloud[k].getDist(cloud[m])];
let x3 = (Math.pow(d2[0], 2) - Math.pow(d2[1], 2) + Math.pow(d[0], 2)) / (2 * d[0]);
let y3 = (Math.pow(d2[0], 2) - Math.pow(x3, 2) - Math.pow(d2[2], 2) + Math.pow(x2 - x3, 2) + Math.pow(y2, 2)) / (2 * y2)
let z3 = Math.sqrt(Math.round(Math.pow(d2[0], 2)) - Math.round(Math.pow(x3, 2) + Math.pow(y3, 2)));
//let z3=Math.sqrt(Math.pow(d2[0],2)-Math.pow(x3,2)-Math.pow(y3,2));
if (z3 != 0) {
//if(Math.round(Math.pow(d2[0],2))-Math.round(Math.pow(x3,2)+Math.pow(y3,2))!=0){
if (setValues) {
cloud[i].setPosition(0, 0, 0);
cloud[j].setPosition(x1, 0, 0);
cloud[k].setPosition(x2, y2, 0);
cloud[m].setPosition(x3, y3, z3);
this.determinedAnchors.push(cloud[i]);
this.determinedAnchors.push(cloud[j]);
this.determinedAnchors.push(cloud[k]);
this.determinedAnchors.push(cloud[m]);
}
//console.log([cloud[i],cloud[j],cloud[k],cloud[m]])
return [cloud[i], cloud[j], cloud[k], cloud[m]];
}
}
}
}
}
}
}
}
}
return [];
}
setGroundAnchors(cloud) {
return !!this.getFourIndependentAnchors(cloud, true);
}
getCompletedClouds() {
let temp1 = [], temp2 = [];
for (let i = 0; i < this.anchors.length; i++) {
for (let j = 0; j < this.anchors[i].neighbours.length; j++) {
if (this.anchors[i].name < this.anchors[i].neighbours[j].node.name) {
temp1.push([this.anchors[i], this.anchors[i].neighbours[j].node]);
}
}
}
while (1) {
for (let i = 0; i < temp1.length; i++) {
for (let j = 0; j < this.anchors.length; j++) {
if (temp1[i].slice(-1)[0].name < this.anchors[j].name && this.anchors[j].haveAllNeighbours(temp1[i])) {
temp2.push(temp1[i].concat(this.anchors[j]));
}
}
}
if (temp2.length == 0) {
return temp1.reverse();
}
temp1 = temp1.filter(function (shotelem) {
return temp2.filter(function (longelem) {
return shotelem.filter(function (node) {
return longelem.indexOf(node) > -1
}).length == shotelem.length
}).length == 0
}).concat(temp2);
temp2 = [];
}
}
}
|
0e9bc1e6c6cb07936bf4aee138a6270de60786b3 | TypeScript | tictools/javascript-design-patterns | /src/behavioral_patterns/Observer/WeatherData/index.ts | 3.109375 | 3 | export default class WeatherData {
private temperature: number[];
private humidity: number[];
constructor() {
this.temperature = [];
this.humidity = [];
}
public getTemperatureHistory() {
return this.temperature;
}
public getHumidityHistory() {
return this.humidity;
}
public updateTemperature(temperature: number) {
this.temperature.push(temperature);
}
public updateHumidity(humidity: number) {
this.humidity.push(humidity);
}
}
|
bc1c46cdae3ec0415b906be5b4ed156dfdbd06da | TypeScript | dungvo0111/library-backend | /test/services/user.test.ts | 2.71875 | 3 | import jwt from 'jsonwebtoken'
import User from '../../src/models/User'
import UserService from '../../src/services/user'
import * as dbHelper from '../db-helper'
const unregisteredEmail = "unregistered@gmail.com"
const unmatchedPassword = "password123"
async function signUp() {
const user = new User({
email: 'test@gmail.com',
firstName: 'Dung',
lastName: 'Vo',
password: 'abcd1234',
})
return await UserService.signUp(user)
}
describe('user service', () => {
beforeEach(async () => {
await dbHelper.connect()
})
afterEach(async (done) => {
await dbHelper.clearDatabase()
done()
})
afterAll(async (done) => {
await dbHelper.closeDatabase()
done()
})
it('should sign up new user', async () => {
const user = await signUp()
expect(user).toHaveProperty('_id')
expect(user).toHaveProperty('firstName', 'Dung')
expect(user).toHaveProperty('email', 'test@gmail.com')
})
it('should not sign up new user with an already registered email', async () => {
expect.assertions(1)
const user1 = await signUp()
return await UserService.signUp(new User({
//email belong to user1
email: 'test@gmail.com',
firstName: 'John',
lastName: 'Doe',
password: 'abcd1234',
})).catch(e => {
expect(e.message).toEqual('Email has already registered')
})
})
it('should not sign up new user with an invalid email', async () => {
function invalidEmail() {
UserService.signUp(new User({
email: 'test@',
firstName: 'John',
lastName: 'Doe',
password: 'abcd1234',
}))
}
expect(invalidEmail).toThrowError('Must be a valid email address')
})
it('should not sign up new user with an invalid password', async () => {
function invalidPassword() {
UserService.signUp(new User({
email: 'test@email.com',
firstName: 'John',
lastName: 'Doe',
password: 'abcd',
}))
}
expect(invalidPassword).toThrowError('Password must be from eight characters, at least one letter and one number')
})
it('should sign in a registered user', async () => {
const user = await signUp()
const token = await UserService.signIn({
email: user.email,
password: 'abcd1234'
})
const decode = jwt.decode(token)
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
expect(decode).toHaveProperty('email', user.email)
})
it('should not sign in with unregistered email', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.signIn({
email: unregisteredEmail,
password: 'abcd1234'
}).catch(e => {
expect(e.message).toEqual('Email has not been registered')
})
})
it('should not sign in with unmatched password', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.signIn({
email: user.email,
password: unmatchedPassword
}).catch(e => {
expect(e.message).toEqual('Password does not match')
})
})
it('should not sign in with invalid email syntax', async () => {
function badRequest() {
UserService.signIn({
email: 'email@',
password: 'abcd1234'
})
}
expect(badRequest).toThrowError('Must be a valid email address')
})
it('should not sign in with invalid email syntax', async () => {
function badRequest() {
UserService.signIn({
email: 'email@email.com',
password: 'abcd'
})
}
expect(badRequest).toThrowError('Password must be from eight characters, at least one letter and one number')
})
it('should sign in a user with Google account', async () => {
const token = await UserService.googleSignIn({
email: 'dungvo0111@gmail.com',
firstName: 'Dung',
lastName: 'Vo'
})
const decode = jwt.decode(token)
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
expect(decode).toHaveProperty('email', 'dungvo0111@gmail.com')
})
it('should update profile of a registered user', async () => {
const user = await signUp()
const token = await UserService.updateProfile({
firstName: "Dung",
lastName: "Vo",
authData: {
email: user.email,
userId: user._id.toString()
}
})
const decode = jwt.decode(token)
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
expect(decode).toHaveProperty('firstName', 'Dung')
expect(decode).toHaveProperty('lastName', 'Vo')
})
it('should not update profile with invalid email', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.updateProfile({
email: 'email@',
authData: {
email: user.email,
userId: user._id.toString()
}
}).catch(e => {
expect(e.message).toEqual('Must be a valid email address')
})
})
it('should not update profile with taken email', async () => {
expect.assertions(1)
const user1 = await signUp()
const user2 = await UserService.signUp(new User({
email: 'user2@email.com',
firstName: 'John',
lastName: 'Doe',
password: 'abcd1234',
}))
return await UserService.updateProfile({
//user2 accidentally change his email to user1's email
email: user1.email,
authData: {
email: user2.email,
userId: user2._id.toString()
}
}).catch(e => {
expect(e.message).toEqual('This email is already taken')
})
})
it('should change password of a registered user', async () => {
const user = await signUp()
const token = await UserService.changePassword({
oldPassword: "abcd1234",
newPassword: "abcd12345",
authData: {
email: user.email,
userId: user._id.toString()
}
})
const decode = jwt.decode(token)
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
expect(decode).toHaveProperty('email', user.email)
})
it('should not change to an invalid password', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.changePassword({
oldPassword: "abcd1234",
newPassword: "abcd",
authData: {
email: user.email,
userId: user._id.toString()
}
}).catch(e => {
expect(e.message).toEqual('Password must be from eight characters, at least one letter and one number')
})
})
it('should not update to a new password with a given unmatched old password', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.changePassword({
oldPassword: unmatchedPassword,
newPassword: "abcd1234",
authData: {
email: user.email,
userId: user._id.toString()
}
}).catch(e => {
expect(e.message).toEqual('Old password does not match')
})
})
it('should request password retrieval email', async () => {
const user = await signUp()
const token = await UserService.resetPasswordRequest({
email: user.email,
url: 'frontendURL'
})
const decode = jwt.decode(token)
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
expect(decode).toHaveProperty('email', user.email)
expect(decode).toHaveProperty('userId', user._id.toString())
})
it('should not request password retrieval email to an invalid email', async () => {
function badRequest() {
UserService.resetPasswordRequest({
email: "invalidEmail@",
url: 'frontendURL'
})
}
expect(badRequest).toThrowError('Must be a valid email address')
})
it('should not request password retrieval email to an unregistered email', async () => {
expect.assertions(1)
const user = await signUp()
return await UserService.resetPasswordRequest({
email: unregisteredEmail,
url: 'frontendURL'
}).catch(e => {
expect(e.message).toEqual('Email has not been registered')
})
})
it('should reset password', async () => {
const user = await signUp()
const token = await UserService.resetPasswordRequest({
email: user.email,
url: 'frontendURL'
})
const decode = jwt.decode(token)
const reset = await UserService.resetPassword({
newPassword: 'newpassword123',
resetToken: {
email: user.email,
userId: user._id.toString()
}
})
expect(token).toMatch(/^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/)
//check if the decoded info inside token matches the reset user
expect(decode).toHaveProperty('email', reset.email)
expect(decode).toHaveProperty('userId', reset._id.toString())
expect(reset).toHaveProperty('email', user.email)
})
it('should not reset password to an invalid-formatted password', async () => {
const user = await signUp()
function badRequest() {
UserService.resetPassword({
newPassword: 'invalidpassword',
resetToken: {
email: user.email,
userId: user._id.toString()
}
})
}
expect(badRequest).toThrowError('Password must be from eight characters, at least one letter and one number')
})
})
|
fe8e9846b402529b6835667c4ab62407df09bfa7 | TypeScript | efraim-andrade/semana_omnistack_10 | /backend/src/websocket.ts | 2.78125 | 3 | import socketio from 'socket.io'
import { Application } from 'express'
import { parseStringAsArray, getDistanceFromLatLonInKm } from './functions'
type CoordinatesTypes = {
latitude: number,
longitude: number
}
interface ConnectionsType {
id: string;
coordinates: CoordinatesTypes;
techs: string[]
}
const connections: ConnectionsType[] = []
let io
const setupWebsocket = (server: Application): void => {
io = socketio(server)
io.on('connection', socket => {
const { latitude, longitude, techs } = socket.handshake.query
connections.push({
id: socket.id,
coordinates: {
latitude: Number(latitude),
longitude: Number(longitude)
},
techs: parseStringAsArray(techs)
})
})
}
const findConnections = (coordinates: CoordinatesTypes, techs: string[]): ConnectionsType[] => {
return connections.filter(connection => getDistanceFromLatLonInKm(coordinates, connection.coordinates) < 10 && connection.techs.some((item: string) => techs.includes(item)))
}
const sendMessage = (to, message, data) => {
to.forEach(connection => {
io.to(connection.id).emmit(message, data)
})
}
export { setupWebsocket, findConnections, sendMessage }
|
edc38cc2137abe4fc3a458a66b81218c3c6f5d65 | TypeScript | ottomated/DefinitelyTyped | /types/tizen-common-web/filesystem.d.ts | 3.1875 | 3 | declare module 'filesystem' {
import { ErrorCallback, SuccessCallback } from 'tizen';
/**
* String, which points to file or directory.
* In methods available since Tizen 5.0, checking or accessing files or directories may be granted only through a valid path.
* Paths may contain one of the supported virtual roots. The valid path pattern is explained on the top of the page.
* @since 5.0
*/
type Path = string;
/**
* The dictionary that defines attributes to filter the items returned by the `listDirectory()` method (or deprecated `listFiles()`).
* When this dictionary is passed to a method, the result-set of the method will only contain file item entries that match
* the attribute values of the filter.
* A file item only matches the `FileFilter` object if all of the defined filter's attribute values match all of the file item's attributes
* (only matching values other than ***undefined*** or ***null***). This is similar to a SQL's "AND" operation.
* An attribute of the file entry matches the `FileFilter` attribute value in accordance with the
* following rules:
*
* - For `FileFilter` attributes of type DOMString, an entry matches this value only if its corresponding attribute is an exact match. If the filter contains U+0025 "PERCENT SIGN" it is interpreted as a wildcard character and "%" matches any string of any length, including no length. If wildcards are used, the behavior is similar to the LIKE condition in SQL. To specify that a "PERCENT SIGN" character is to be considered literally instead of interpreting it as a wildcard, developers can escape it with the backslash character (\\). Please, remember that the backslash character has to be escaped itself, to not to be removed from the string - proper escaping of the "PERCENT SIGN" in JavaScript string requires preceding it with double backslash ("\\\\%").
* The matching is not case sensitive, such as "FOO" matches a "foo" or an "f%" filter.
* - For File entry attributes of type Date, attributes start and end are included to allow filtering of File entries between two supplied dates. If either or both of these attributes are specified, the following rules apply:
* A) If both start and end dates are specified (that is, other than ***null***), a File entry matches the filter if its corresponding attribute is the same as either start or end or between the two supplied dates (that is, after start and before end).
* B) If only the start attribute contains a value (other than ***null***), a File entry matches the filter if its corresponding attribute is later than or equal to the start one.
* C) If only the end date contains a value (other than ***null***), a file matches the filter if its corresponding attribute is earlier than or equal to the end date.
*
*/
type FileFilter = {
/**
* The File name attribute filter.
* Files that have a name that corresponds with this attribute (either exactly or with the specified wildcards) match this filtering criteria.
*/
name: string;
/**
* If true match only files. If false do not match files.
* May be undefined.
* @since 5.0
*/
isFile: boolean;
/**
* If true match only directories, If false do not match directories.
* May be undefined.
* @since 5.0
*/
isDirectory: boolean;
/**
* The File modified attribute filter.
* Files with modified date later than this attribute or equal to it match the filtering criteria.
*/
startModified: Date;
/**
* The File modified attribute filter.
* Files with modified date earlier than this attribute or equal to it match the filtering criteria.
*/
endModified: Date;
/**
* The File created attribute filter.
* Files with created date later than this attribute or equal to it match the filtering criteria.
*/
startCreated: Date;
/**
* The File created attribute filter.
* Files with created date earlier than this attribute or equal to it match the filtering criteria.
*/
endCreated: Date;
};
/**
* Specifies the file mode when it is opened.
* - `a` append access.
* - `r` read-only access.
* - `rw` read and write access.
* - `rwo` read and write access. Original file content are deleted.
* - `w` write access.
* @remark rwo mode is supported since Tizen 5.0. It will not be recognized by deprecated functions.
*/
enum FileMode {
a = 'a',
r = 'r',
rw = 'rw',
rwo = 'rwo',
w = 'w',
}
type FileModeUnion = FileMode | 'a' | 'r' | 'rw' | 'rwo' | 'w';
/**
* Specifies the type of storage.
* - `INTERNAL` Internal storage is a storage that cannot be removed, such as a flash memory.
* - `EXTERNAL` External storage is removable storage, such as a USB drive or a memory card.
*/
enum FileSystemStorageType {
INTERNAL = 'INTERNAL',
EXTERNAL = 'EXTERNAL',
}
type FileSystemStorageTypeUnion = FileSystemStorageType | 'INTERNAL' | 'EXTERNAL';
/**
* Specifies the state of the storage.
* - `MOUNTED` - The device is mounted and can be browsed.
* - `REMOVED` - The device has been removed. This states applies only to external drives.
* - `UNMOUNTABLE` - The device cannot be mounted due to an error.
*/
enum FileSystemStorageState {
MOUNTED = 'MOUNTED',
REMOVED = 'REMOVED',
UNMOUNTABLE = 'UNMOUNTABLE',
}
type FileSystemStorageStateUnion = FileSystemStorageState | 'MOUNTED' | 'REMOVED' | 'UNMOUNTABLE';
/**
* Specifies starting point for seek operation.
* - `BEGIN` - Beginning of the file.1
* - `CURRENT` - Current position of file indicator.
* - `END` - End of the file.
*/
enum BaseSeekPosition {
BEGIN = 'BEGIN',
CURRENT = 'CURRENT',
END = 'END',
}
type BaseSeekPositionUnion = BaseSeekPosition | 'BEGIN' | 'CURRENT' | 'END';
/**
* The FileSystemManagerObject interface defines what is instantiated by the Tizen object.
* There is a `tizen.filesystem` object that allows accessing the functionality of the Filesystem API.
*/
interface FilesystemManager {
/**
* The maximum file or directory name length for the current platform.
* @returns The maximum name length is 255
*/
readonly maxNameLength: number;
/**
* The maximum path length limit for the current platform.
* @returns The maximum path length is 4096
*/
readonly maxPathLength: number;
/**
* Opens a file or creates a file pointed by `path`.
* If the operation succeeds, a file handle to the newly created or opened file is returned, otherwise an exception is thrown.
* Following file open modes are supported:
*
* - `a` - append mode. File position indicator is always set to the first position after the last character of the file and cannot be modified with seek operations. Write operations always append content to the end of the file. Original file content are not modified. Read operations cannot be performed. If the file does not exist, it is created.
* - `r` - read mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Write operations cannot be performed. Original file content may be read in this mode. If the file does not exist, NotFoundError is thrown.
* - `rw` - read and write mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Original file content may be read or modified in this mode. If the file does not exist, NotFoundError will be thrown.
* - `rwo` - read and write mode, overwriting existing file content. File position indicator is initially set to the beginning of the file. Read and write operations may be performed. Original file content are deleted before opening the file. If the file does not exist, it is created.
* - `w` - write mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Read operations cannot be performed. Original file content are deleted before opening the file. If the file does not exist, it is created.
*
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @privilegeName http://tizen.org/privilege/filesystem.write
* @remark Write permission is needed, when file is opened in modes: ***a***, ***rw***, ***rwo*** and ***w***. Read permission is needed, when file is opened in modes: ***r***, ***rw*** and ***rwo***.
* @param path Path to the file.
* @param openMode Mode in which the file is to be opened.
* @param makeParents Flag indicating whether lacking directories should be created.
* For instance, if method is invoked with parameter `path` equal to ***documents/path/to/dir/file.ext*** and
* there is no directory "path" in "documents" virtual root, directories "path", "to" and "dir" will be created, as well as the new file "file.ext".
* By default, `makeParents` is equal to ***true***. Its value is ignored, when `openMode` is ***r*** or ***rw***.
* @returns Object representing open file.
* @throw WebAPIException IOError, NotFoundError, SecurityError, TypeMismatchError
*/
openFile: (path: Path, openMode: FileModeUnion, makeParents?: boolean) => FileHandle;
/**
* Creates directory pointed by `path`.
* Successful directory creation invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if any of the input/output error occurs.
* - NotFoundError, if directory given in `path` does not exist and `makeParents` is set to false.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param path Path to directory to create.
* @param makeParents Flag indicating whether lacking directories should be created.
* For instance, if method is invoked with parameter `path` equal to ***documents/path/to/dir*** and
* there is no directory "path" in "documents" virtual root, directories "path", "to" and "dir" will be created.
* By default, `makeParents` is equal to ***true***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError,SecurityError, TypeMismatchError
*
*/
createDirectory: (
path: Path,
makeParents?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Deletes file pointed by `path`.
* Successful file deletion invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if any of the input/output error occurs.
* - NotFoundError, if the `path` does not point to an existing file.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param path Path to file.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException with error type InvalidValuesError, SecurityError, TypeMismatchError
*/
deleteFile: (path: Path, successCallback?: PathSuccessCallback, errorCallback?: ErrorCallback) => void;
/**
* Deletes directory or directory tree under the current directory pointed by `path`.
* Successful directory deletion invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if a directory is not empty and `recursive` is equal to ***false***.
* - NotFoundError, if the `path` does not point to an existing directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param path A path to directory.
* @param recursive Flag indicating whether the deletion is recursive or not. If `recursive` is set to ***true*** the method will delete content of a given directory recursively.
* Otherwise, the method succeeds only if the directory is empty, on other cases `errorCallback` is called.
* By default, `recursive` is equal to ***true***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
deleteDirectory: (
path: Path,
recursive?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Copies file from location pointed by `sourcePath` to `destinationPath`.
* Successful file copying invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if any of the input/output error occurs.
* - NotFoundError, if the `sourcePath` does not point to an existing file.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param sourcePath Path to file.
* @param destinationPath Path for copied file. The path must consist of path to an existing directory concatenated with '/' and the name of new file.
* @param overwrite Flag indicating whether to overwrite an existing file. If `overwrite` is set to ***true*** and file pointed by `destinationPath` already exists, the method will overwrite the file.
* Otherwise, if a file with conflicting name already exists `errorCallback` is called.
* By default, `overwrite` is equal to ***false***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
copyFile: (
sourcePath: Path,
destinationPath: Path,
overwrite?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Recursively copies directory pointed by `sourcePath` to `destinationPath`.
* The method merges content of the directory pointed by `sourcePath` with content of the directory pointed by `destinationPath`, if exists.
* If the directory pointed by `destinationPath` does not exist, it is created.
* Successful directory copying invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if a directory with conflicting name already exists and `overwrite` is equal to ***false*** or any of the input/output error occurs.
* - NotFoundError, if the `sourcePath` does not point to an existing directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param sourcePath Path to directory.
* @param destinationPath Path for copied directory. The path must consist of path to an existing directory concatenated with '/' and the name of destination directory.
* @param overwrite Flag indicating whether to overwrite existing content. If `overwrite` is equal to ***true***, the file or directory with conflicting name will be overwritten.
* Otherwise, `errorCallback` will be called with `IOError`.
* By default, `overwrite` is equal to ***false***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
copyDirectory: (
sourcePath: Path,
destinationPath: Path,
overwrite?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Moves file pointed by `sourcePath` to `destinationPath`.
* Successful file moving invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if a file with conflicting name already exists and `overwrite` is equal to ***false*** or any of the input/output error occurs.
* - NotFoundError, if the `sourcePath` or `destinationPath` does not point to an existing file or directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param sourcePath Path to file.
* @param destinationPath A destination directory path to move the file to.
* @param overwrite Flag indicating whether to overwrite an existing file. If `overwrite` is set to ***true*** and file with the same name in `destinationPath` already exists, the method will overwrite the file.
* Otherwise, if a file with conflicting name already exists `errorCallback` is called.
* By default, `overwrite` is equal to ***false***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
moveFile: (
sourcePath: Path,
destinationPath: Path,
overwrite?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Recursively moves directory pointed by `sourcePath` to `destinationPath`.
* The method merges content of the directory pointed by `sourcePath` with content of the directory with the same name in `destinationPath`, if exists.
* Successful directory moving invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if a directory with conflicting name already exists and `overwrite` is equal to ***false*** or any of the input/output error occurs.
* - NotFoundError, if the `sourcePath` or `destinationPath` does not point to an existing directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param sourcePath A path to directory.
* @param destinationPath A destination directory path to move the directory to.
* @param overwrite Flag indicating whether to overwrite existing content. If `overwrite` is equal to ***true***, the file or directory with conflicting name will be overwritten.
* Otherwise, `errorCallback` will be called with `IOError`.
* By default, `overwrite` is equal to ***false***.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
moveDirectory: (
sourcePath: Path,
destinationPath: Path,
overwrite?: boolean,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Renames file or directory located in `path` to name `newName`.
* Successful renaming invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if a file or a directory with conflicting name already exists or any of the input/output error occurs.
* - NotFoundError, if the `path` does not point to an existing file or directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param path A path to directory or file.
* @param newName A new name of directory or file.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
rename: (
path: Path,
newName: string,
successCallback?: PathSuccessCallback,
errorCallback?: ErrorCallback,
) => void;
/**
* Lists directory content located in `path`.
* Successful listing of directory content invokes `successCallback` function, if specified. In case of failure `errorCallback` function is invoked, if specified.
* If the filter is passed and contains valid values, only those directories or files in the directory that match the filter criteria specified in the `FileFilter` interface are returned in successCallback method.
* If the filter is ***null*** or ***undefined*** the implementation must return the full list of files in the directory.
* If the directory does not contain any files or directories, or the filter criteria do not match with any files or directories, the `successCallback` is invoked with an empty array.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if any of the input/output error occurs.
* - NotFoundError, if the `path` does not point to an existing directory.
*
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param path A path to directory.
* @param successCallback Callback function to be invoked on success.
* @param errorCallback Callback function to be invoked when an error occurs.
* @param filter Filter to restrict the listed files.
* @throw WebAPIException InvalidValuesError, SecurityError, TypeMismatchError
*/
listDirectory: (
path: Path,
successCallback: ListDirectorySuccessCallback,
errorCallback?: ErrorCallback,
filter?: FileFilter,
) => void;
/**
* Converts `path` to file URI.
* @since 5.0
* @remark The function does not check if `path` exists in filesystem.
* @param path A path to a file or a directory.
* @returns [File URI](https://tools.ietf.org/html/rfc8089) for given path.
* @throw WebAPIException InvalidValuesError
*/
toURI: (path: Path) => string;
/**
* Checks if given `path` points to a file.
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param path A path to be tested.
* @returns ***true*** if `path` points to a file, ***false*** otherwise.
* @throw WebAPIException InvalidValuesError, IOError, NotFoundError, SecurityError
*/
isFile: (path: Path) => boolean;
/**
* Checks if given `path` points to a directory.
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param path A path to be tested.
* @returns ***true*** if `path` points to a directory, ***false*** otherwise.
* @throw WebAPIException InvalidValuesError, IOError, NotFoundError, SecurityError
*/
isDirectory: (path: Path) => boolean;
/**
* Checks if given `path` exists.
* @since 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param path A path to be tested.
* @returns ***true*** if `path` points to a existing element, ***false*** otherwise.
* @throw WebAPIException InvalidValuesError, IOError, SecurityError
*/
pathExists: (path: Path) => boolean;
/**
* Returns path to directory for given `path`.
* Strips trailing '/', then breaks `path` into two components by last `path` separator, returns first component.
* @since 5.0
* @remark This function does not check if `path` is valid or exists in filesystem.
* @param path Path to file or directory.
* @returns Path to directory for given path.
*/
getDirName: (path: Path) => string;
/**
* Resolves a location to a file handle after validating it.
*
* A `location` can contain a virtual path like "***documents/some_file.txt***"
* or a file URI like "***file:///my_strange_path/some_file.png***".
* A `location` is not allowed to contain the "." or ".." directory entries inside its value.
*
* The list of root locations that must be supported by a compliant implementation are:
*
* - `documents` - The default folder in which text documents (such as pdf, doc...) are stored by default in a device. For example, in some platforms it corresponds to the "My Documents" folder.
* - `images` - The default folder in which still images, like pictures (in formats including jpg, gif, png, etc.), are stored in the device by default. For example, in some platforms it corresponds to the "My Images" folder.
* - `music` - The default folder in which sound clips (in formats including mp3, aac, etc.) are stored in the device by default. For example, in some platforms it corresponds to the "My Music" folder.
* - `videos` - The default folder in which video clips (in formats including avi, mp4, etc.) are stored in the device by default. For example, in some platforms it corresponds to the "My Videos" folder.
* - `downloads` - The default folder in which downloaded files (from sources including browser, e-mail client, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "Downloads" folder.
* - `ringtones` - The default folder in which ringtones (such as mp3, etc.) are stored in the device.
* - `camera` - The default folder in which pictures and videos taken by a device are stored.
* - `wgt`-package - The read-only folder to which the content of a widget file is extracted.
* - `wgt`-private - The private folder in which a widget stores its information. This folder must be accessible only to the same widget and other widgets or applications must not be able to access the stored information.
* - `wgt`-private-tmp - Temporary, the private folder in which a widget can store data that is available during a widget execution cycle. Content of this folder can be removed from this directory when the widget is closed or the Web Runtime is restarted. This folder must be accessible only to the same widget and other widgets or applications must not be able to access it.
*
*
* The `mode` parameter specifies whether the resulting `File` object has read-only access (***r*** access), read and write access (***rw*** access), append access (***a*** access), or write access (***w*** access) to the root location containing directory tree.
* Permission for the requested access is obtained from the security framework. Once the resulting `File` object has access, access is inherited by any other `File` objects that are derived from this instance without any further reference to the security framework, as noted in descriptions of certain methods of `File`.
*
* The ErrorCallback is launched with these error types:
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* For example, the mode is ***w*** for the read-only virtual roots (wgt-package and ringtones).
* - `NotFoundError` - If the location input argument does not correspond to a valid location.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @remark ***camera*** location is supported since Tizen 2.3. If a device does not support camera, NotSupportedError will be thrown.
* @param location Location to resolve that can be a virtual path or file URI.
* @param onsuccess Callback method to be invoked when the location has been successfully resolved, passing the newly created `File` object.
* @param onerror Callback method to be invoked when an error has occurred.
* @param mode Optional value to indicate the file access mode on all files and directories that can be reached from the `File` object passed to onsuccess.
* Default value of this parameter is ***rw*** if absent or ***null***.
* @throw WebAPIException NotSupportedError, SecurityError, TypeMismatchError
*/
resolve: (
location: string,
onsuccess: FileSuccessCallback,
onerror?: ErrorCallback,
mode?: FileModeUnion,
) => void;
/**
* Gets information about a storage based on its label.
* For example: "MyThumbDrive", "InternalFlash".
* The `onsuccess` method receives the data structure as an input argument containing additional information about the drive.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `NotFoundError` - If no drive was found with the given label.
* - `UnknownError` - If any other error occurs.
*
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param label Storage label.
* @param onsuccess Callback method to be invoked when the list of storages is available, passing the storage list to the callback.
* @param onerror Callback method to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
getStorage: (label: string, onsuccess: FileSystemStorageSuccessCallback, onerror?: ErrorCallback) => void;
/**
* Lists the available storages (both internal and external) on a device.
* The onsuccess method receives a list of the data structures as input argument containing additional information about each drive found.
* It can get storages that would have a label named as "internal0", virtual roots (images, documents, ...), "removable1", "removable2".
* "removable1" label is used to resolve sdcard and "removable2" label is used to resolve USB host, if supported.
* The vfat filesystem used to sdcard filesystem widely is not case-sensitive.
* If you want to handle the file on sdcard, you need to consider case-sensitive filenames are regarded as same name.
*
* Labels can differ depending on platform implementation.
*
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `UnknownError` - If any other error occurs.
*
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param onsuccess Callback method to be invoked when a list of storage is available and passing the storage list to the callback.
* @param onerror Callback method to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
listStorages: (onsuccess: FileSystemStorageArraySuccessCallback, onerror?: ErrorCallback) => void;
/**
* Adds a listener to subscribe to notifications when a change in storage state occurs.
* The most common usage for this method is to watch for any additions and removals of external storages.
* When executed, it returns a subscription identifier that identifies the watch operation. After returning the identifier, the watch operation is started asynchronously. The onsuccess method will be invoked every time a storage state changes. If the attempt fails, the onerror if present will be invoked with the relevant error type.
* The watch operation must continue until the removeStorageStateChangeListener() method is called with the corresponding subscription identifier.
*
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param onsuccess Callback method to be invoked when any change is made to storage state.
* @param onerror Callback method to be invoked when an error occurs during the watch process.
* @returns Subscription identifier.
* @throw WebAPIException SecurityError, TypeMismatchError, UnknownError
*/
addStorageStateChangeListener: (onsuccess: FileSystemStorageSuccessCallback, onerror?: ErrorCallback) => number;
/**
* Removes a listener to unsubscribe from a storage watch operation.
* If the `watchId` argument is valid and corresponds to a subscription already in place, the watch process will be stopped and no further callbacks will be invoked.
* Otherwise, the method call has no effect.
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param watchId Subscription identifier.
* @throw WebAPIException SecurityError, UnknownError
*/
removeStorageStateChangeListener: (watchId: number) => void;
}
/**
* The FileSystemStorage interface gives additional information about a storage, such as if the device is mounted, if it is a removable drive or not, or the device's name.
* To retrieve the mount point, the resolve() method should be used using the label as argument.
*/
interface FileSystemStorage {
/**
* The storage name.
* This attribute is used as an input for methods such as getStorage() and also used as `location` parameter for File.resolve() and FileSystemManager.resolve().
*/
readonly label: string;
/**
* The storage type as internal or external.
*/
readonly type: FileSystemStorageTypeUnion;
/**
* The storage state as mounted or not.
*/
readonly state: FileSystemStorageStateUnion;
}
/**
* Object representing file, used for read/write operations.
* Each read or write operation moves position in file forwards to the end of read/written data (there is an underlying file position's indicator).
* @since 5.0
* @remark Due to multibyte UTF-8 encoding, if current file's pointer does not point to beginning of multibyte sequence (see: UTF-16, emoji), using `seek()` combined with UTF-8
* `readString()` will result in string starting from valid character. Incomplete byte sequence at the beginning may be omitted.
* Be aware about using seek and write methods together. It can result in writing in the middle of multibyte sequence, which can lead to file with corrupted content.
*/
interface FileHandle {
/**
* Path, as passed to `openFile`.
*/
readonly path: Path;
/**
* Sets position indicator in file stream to ***offset***.
* Note, that current position indicator value, can be obtained by calling ***seek(0, "CURRENT")***.
* @param offset Number of bytes to shift the position relative to ***whence***.
* @param whence Determines position in file stream to which ***offset*** is added. Default value: "BEGIN".
* @returns File position indicator.
* @throw WebAPIException IOError, TypeMismatchError
*/
seek: (offset: number, whence?: BaseSeekPositionUnion) => number;
/**
* Sets position indicator in file stream to ***offset***.
* Successful seek operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if any error related to file handle occurs.
*
* Note, that current position indicator value, can be obtained in SeekSuccessCallback by calling ***seekNonBlocking(0, "CURRENT")***.
* seekNonBlocking is executed in background and does not block further instructions.
* @param offset Number of bytes to shift the position relative to ***whence***.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @param whence Determines position in file stream to which ***offset*** is added. Default value: "BEGIN".
* @throw WebAPIException TypeMismatchError
*/
seekNonBlocking: (
offset: number,
onsuccess?: SeekSuccessCallback,
onerror?: ErrorCallback,
whence?: BaseSeekPositionUnion,
) => void;
/**
* Reads file content as string.
* Sets file handle position indicator at the end of read data.
* Reads given number of characters.
* @param count Number of characters to read from file. If none is given, method attempts to read whole file.
* @param inputEncoding Default value: ***"UTF-8"***. Encoding to use for read operation on the file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" Latin-1 encoding
* @returns String with data read from file.
* @throw WebAPIException InvalidValuesError IOError, NotSupportedError, TypeMismatchError
* @remark Resulting string can have `length` larger than `count`, due to possible UTF-16 surrogate pairs in it. String length in JavaScript is counted in UTF-16 encoding, so for example string containing one emoji (surrogate of two UTF-16) character will have `length` of two.
*/
readString: (count?: number, inputEncoding?: string) => string;
/**
* Reads file content as string.
* Reads given number of characters.
* Sets file handle position indicator at the end of read data.
* readStringNonBlocking is executed in background and does not block further instructions.
* Successful read operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if read fails or any error related to file handle occurs.
*
* @param onsuccess Callback function with read data from file to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @param count Number of characters to read from file. If none is given, method attempts to read whole file.
* @param inputEncoding Default value: ***"UTF-8"***. Encoding to use for read operation on the file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" Latin-1 encoding
* @throw WebAPIException InvalidValuesError, NotSupportedError, TypeMismatchError
*/
readStringNonBlocking: (
onsuccess?: ReadStringSuccessCallback,
onerror?: ErrorCallback,
count?: number,
inputEncoding?: string,
) => void;
/**
* Writes ***inputString*** content to a file.
* Sets file handle position indicator at the end of written data.
* @param inputString String value to be written to a file.
* @param outputEncoding Default value: UTF-8. Encoding to use for write operation on the file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" Latin-1 encoding
* @returns Number of bytes written (can be more than `inputString` length for multibyte encodings and will never be less)
* @throw WebAPIException IOError, NotSupportedError
*/
writeString: (inputString: string, outputEncoding?: string) => number;
/**
* Writes ***inputString*** content to a file.
* Sets file handle position indicator at the end of written data.
* writeStringNonBlocking is executed in background and does not block further instructions.
* Successful write operation invokes `successCallback` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if write fails or any error related to file handle occurs.
*
* @param inputString String value to be written to a file.
* @param onsuccess Callback function with a number of bytes written as parameter to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @param outputEncoding Default value: ***"UTF-8"***. Encoding to use for write operation on the file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" Latin-1 encoding
* @throw WebAPIException NotSupportedError, TypeMismatchError
*/
writeStringNonBlocking: (
inputString: string,
onsuccess?: WriteStringSuccessCallback,
onerror?: ErrorCallback,
outputEncoding?: string,
) => void;
/**
* Reads file content as `Blob`.
* Sets file handle position indicator at the end of read data.
* @param size Size in bytes of data to read from file. If none is given, method attempts to read whole file.
* @returns Blob object with file content.
* @throw WebAPIException InvalidValuesError IOError
*/
readBlob: (size: number) => Blob;
/**
* Reads file content as `Blob`.
* Sets file handle position indicator at the end of read data.
* readBlobNonBlocking is executed in background and does not block further instructions.
* Successful read operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
*
* The `ErrorCallback` is launched with these error types:
* - IOError, if read fails or any error related to file handle occurs.
*
* @param onsuccess Callback function with `Blob` object to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @param size Size in bytes of data to read from file. If none is given, method attempts to read whole file.
* @throw WebAPIException InvalidValuesError, TypeMismatchError
*/
readBlobNonBlocking: (onsuccess?: ReadBlobSuccessCallback, onerror?: ErrorCallback, size?: number) => void;
/**
* Writes `Blob` to file.
* Sets file handle position indicator at the end of written data.
* @param blob Object of type Blob, which content will be written to a file.
* @throw WebAPIException IOError, TypeMismatchError
*/
writeBlob: (blob: Blob) => void;
/**
* Writes `Blob` to file.
* Sets file handle position indicator at the end of written data.
* writeBlobNonBlocking is executed in background and does not block further instructions.
* Successful write operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if write fails or any error related to file handle occurs.
*
* @param blob Object of type Blob, which content will be written to a file.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError
*/
writeBlobNonBlocking: (blob: Blob, onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
/**
* Reads file content as binary data.
* Can be used in combination with [atob() or btoa()](https://dev.w3.org/html5/spec-LC/webappapis.html#atob) functions.
* Sets file handle position indicator at the end of read data.
* @param size Size in bytes of data to read from file. If none is given, method attempts to read whole file.
* @returns Read data as Uint8Array.
* @throw WebAPIException InvalidValuesError, IOError
*/
readData: (size: number) => Uint8Array;
/**
* Reads file content as binary data.
* Can be used in combination with [atob() or btoa()](https://dev.w3.org/html5/spec-LC/webappapis.html#atob) functions.
* Sets file handle position indicator at the end of read data.
* readDataNonBlocking is executed in background and does not block further instructions.
* Successful read operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if read fails or any error related to file handle occurs.
*
* @param onsuccess Callback function with read data from file to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @param size Size in bytes of data to read from file. If none is given, method attempts to read whole file.
* @throw WebAPIException InvalidValuesError, TypeMismatchError
*/
readDataNonBlocking: (onsuccess?: ReadDataSuccessCallback, onerror?: ErrorCallback, size?: number) => void;
/**
* Writes binary data to file.
* Can be used in combination with [atob() or btoa()](https://dev.w3.org/html5/spec-LC/webappapis.html#atob) functions.
* Sets file handle position indicator at the end of written data.
* @param data An array of type Uint8Array, which content will be written to file as binary data.
* @throw WebAPIException with error type IOError, TypeMismatchError
*/
writeData: (data: Uint8Array) => void;
/**
* Writes binary data to file.
* Can be used in combination with [atob() or btoa()](https://dev.w3.org/html5/spec-LC/webappapis.html#atob) functions.
* Sets file handle position indicator at the end of written data.
* writeDataNonBlocking is executed in background and does not block further instructions.
* Successful write operation invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if write fails or any error related to file handle occurs.
*
* @param data An array of type Uint8Array, which content will be written to file as binary data.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError
*/
writeDataNonBlocking: (data: Uint8Array, onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
/**
* Flushes data.
* For file handles with permission to write, flush writes any changes made to file content to underlying buffer.
* Flush does not ensure that data is written on storage device, it only synchronizes RAM with file descriptor.
* To ensure storage synchronization use `sync`, `close` or their asynchronous equivalent methods, which guarantee such synchronization.
* @throw WebAPIException IOError
*/
flush: () => void;
/**
* Flushes data.
* For file handles with permission to write, flush writes any changes made to file content to underlying buffer.
* Flush does not ensure that data is written on storage device, it only synchronizes RAM with file descriptor.
* To ensure storage synchronization use `sync`, `close` or their asynchronous equivalent methods, which guarantee such synchronization.
* Successful flushing invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if flush fails or any error related to file handle occurs.
*
* This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError
*/
flushNonBlocking: (onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
/**
* Synchronizes data to storage device.
* The sync function is intended to force a physical write of data from the buffer cache and to assure that after a system crash or other failure that all data up to the time of the sync() call is recorded on the disk.
* @throw WebAPIException IOError
*/
sync: () => void;
/**
* Synchronizes data to storage device.
* The syncNonBlocking function is intended to force a physical write of data from the buffer cache and to assure that after a system crash or other failure that all data up to the time of the syncNonBlocking() execution is recorded on the disk.
* Successful syncing invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if sync fails or any error related to file handle occurs.
*
* This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError
*/
syncNonBlocking: (onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
/**
* Closes file handle.
* Closes the given file stream. Closing file guarantees writing changes made to `FileHandle` to the storage device. Further operations on this file handle are not allowed.
* @remark This method is synchronous. If any asynchronous method was called before close, close will block further instructions until all background jobs finish execution.
* Note, that if file handle functions are put into any callbacks and this callback was not yet called, synchronous close will wait only for already ordered background jobs to finish, preventing successful execution of any further operations on closed file handle.
* @throw WebAPIException IOError
*/
close: () => void;
/**
* Closes file handle.
* Closes the given file stream. Closing file guarantees writing changes made to `FileHandle` to the storage device. Further operations on this file handle are not allowed.
* Successful closing invokes `onsuccess` function, if specified. In case of failure `onerror` function is invoked, if specified.
* The `ErrorCallback` is launched with these error types:
*
* - IOError, if close fails or any error related to file handle occurs.
*
* This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
* @param onsuccess Callback function to be invoked on success.
* @param onerror Callback function to be invoked when an error occurs.
* @throw WebAPIException TypeMismatchError
*/
closeNonBlocking: (onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
}
/**
* The File interface represents the file abstraction in use.
* The file object permissions for the file object location and tree rooted
* at that location depend upon the mode defined in the resolve method.
* When a File object creates a child File object,
* the new File object inherits its access rights from
* the parent object without any reference to the security framework, as
* noted in certain methods of File.
* A file handle represents either a file or a directory:
*
* - For a file, the `isFile` attribute is set to ***true***.
* - For a directory, the `isDirectory` attribute is set to ***true***.
*
* A file can be opened for both read and write operations, using a
* FileStream handle. A list of files and sub-directories can be obtained from a
* directory and a resolve method exists to resolve files or sub-directories
* more conveniently than processing directory listings.
*
* A file handle representing a file can be opened for I/O operations,
* such as reading and writing.
*
* A file handle representing a directory can be used for listing all
* files and directories rooted as the file handle location.
*
* @note `deprecated` 5.0
*/
interface File {
/**
* The parent directory handle.
* This attribute is set to ***null*** if there is no parent directory. This also implies that this directory represents a root location.
* @note `deprecated` 5.0
*/
readonly parent?: File;
/**
* The file/directory access state in the filesystem.
* This attribute is set to:
*
* - ***true*** - if object has read-only access at its location.
* - ***false*** - if object has write access at its location.
*
* This attribute represents the actual state of a file or directory in the filesystem. Its value is not affected by the mode used in FileSystemManager.resolve() that was used to create the `File` object from which this `File` object was obtained.
* @note `deprecated` 5.0
*/
readonly readOnly: boolean;
/**
* The flag indicating whether it is a file.
* This attribute can have the following values:
*
* - ***true*** if this handle is a file
* - ***false*** if this handle is a directory
*
* @note `deprecated` 5.0
*/
readonly isFile: boolean;
/**
* The flag indicating whether it is a directory.
* This attribute can have the following values:
*
* - ***true*** if this handle is a directory
* - ***false*** if this handle is a file
*
* @note `deprecated` 5.0
*/
readonly isDirectory: boolean;
/**
* The timestamp when a file is first created in the filesystem.
* This timestamp is equivalent to the timestamp when a call to createFile() succeeds.
* If the platform does not support this attribute, it will
* be ***null***.
* It is unspecified and platform-dependent if the creation
* timestamp changes when a file is moved.
* @note `deprecated` 5.0
*/
readonly created?: Date;
/**
* The timestamp when the most recent modification is made to a file, usually when the last write operation succeeds.
* Opening a file for reading does not change the modification timestamp.
* If the platform does not support this attribute, it will be ***null***.
* It is unspecified and platform-dependent if the modified
* timestamp changes when a file is moved.
* @note `deprecated` 5.0
*/
readonly modified?: Date;
/**
* The path of a file after excluding its file name.
* It begins with the name of the root containing the file, followed by the path, including the directory containing the file, but excluding the file name.
* Except in some special cases of the File representing the root itself, the last
* character is always "/".
* For example, if a file is located at music/ramones/volume1/RockawayBeach.mp3,
* the path is music/ramones/volume1/.
* For example, if a directory is located at music/ramones/volume1, the path is
* music/ramones/.
* For the virtual roots, the path is same as the name of the virtual root.
* For example, if the root is music, then the path is music. If the root is documents, then the path is documents.
* @note `deprecated` 5.0
*/
readonly path: string;
/**
* The file name after excluding the root name and any path components.
* This is the name of this file, excluding the root name and any other path components.
* For example, if a file is located at
* music/ramones/volume1/RockawayBeach.mp3, the `name` is "RockawayBeach.mp3".
* For example, if a directory is located at music/ramones/volume1, the
* `name` is be "volume1".
* For the special case of the root itself, the `name` is an empty string.
* @note `deprecated` 5.0
*/
readonly name: string;
/**
* The full path of a file.
* It begins with the name of the root containing the file,
* and including the name of the file or directory itself.
* For instance, if the RockawayBeach.mp3 file is located at music/ramones/volume1/, then the `fullPath` is music/ramones/volume1/RockawayBeach.mp3.
* For a directory, if the volume1 directory is located at music/ramones/, then the `fullPath` is music/ramones/volume1.
* For the special case of the root itself, if the root is music, then the `fullPath` is music.
* The `fullPath` is always equal to path + name.
* @note `deprecated` 5.0
*/
readonly fullPath: string;
/**
* The size of this file, in bytes.
* If an attempt to read this attribute for a directory is made, ***undefined*** is returned. To retrieve the number of files and directories contained in the directory, use the `length` attribute.
* @note `deprecated` 5.0
*/
readonly fileSize: number;
/**
* The number of files and directories contained in a file handle.
* If an attempt to read this attribute for a file is made, ***undefined*** is returned. To retrieve the size of a file, use the `fileSize` attribute.
* @note `deprecated` 5.0
*/
readonly length: number;
/**
* Returns a URI for a file to identify an entry (such as using it as the src attribute on an HTML img element).
* The URI has no specific expiration, it should be valid at least as long as the file exists.
* If that URI corresponds to any of the public virtual roots (that is
* images, videos, music, documents and downloads) the URI
* must be globally unique and could be used by any widget.
* If that URI corresponds to a file located in any a widget's private areas (such as wgt-package, wgt-private, wgt-private-tmp),
* the generated URI must be unique for that file and for the widget making the request (such as including some derived from the widget ID in the URI).
* These URIs must not be accessible to other widgets, apart from the one invoking this method.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @returns URI that identifies the file or ***null*** if an error occurs.
* @throw WebAPIException with error type SecurityError, if the application does not have the privilege to call this method. For more information, see `Storage privileges`.
* @throw WebAPIException with error type UnknownError, if any other error occurred.
*/
toURI: () => string;
/**
* Lists all files in a directory.
* The list of files is passed as a File[] in onsuccess() and contains directories and files. However, the directories "." and ".." must not be returned. Each `File` object that is part of the array must inherit all the access rights (that is, one of the values in FileMode) from the `File` object in which this method is invoked.
* If the filter is passed and contains valid values, only those directories and files in the directory that match the filter criteria specified in the `FileFilter` interface must be returned in the onsuccess() method. If no filter is passed, the filter is ***null ***or ***undefined***, or the filter contains invalid values, the implementation must return the full list of files in the directory.
* If the directory does not contain any files or directories, or the filter criteria do not match any files or directories, the onsuccess() is invoked with an empty array.
* The ErrorCallback is launched with these error types:
*
* - `IOError` - If the operation is launched on a file (not a directory).
* - `InvalidValuesError` - If any of the input parameters contain an invalid value.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param onsuccess Callback method to be invoked when the list operation has been successfully completed.
* @param onerror Callback method to be invoked when an error has occurred.
* @param filter Criteria to restrict the listed files.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
listFiles: (onsuccess: FileArraySuccessCallback, onerror?: ErrorCallback, filter?: FileFilter) => void;
/**
* Opens the file in the given mode supporting a specified encoding.
* This operation is performed asynchronously. If the file is opened successfully, the onsuccess() method is invoked with a `FileStream` that can be used for reading and writing the file, depending on the mode. The returned `FileStream` instance includes a file pointer, which represents the current position in the file. The file pointer, by default, is at the start of the file, except in the case of opening a file in append ("a") mode, in which case the file pointer points to the end of the file.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `IOError` - The operation is launched on a directory (not a file), the file is not valid or it does not exist.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param mode Mode in which the file is opened
* **"r"** for reading
* **"a"** for appending
* **"w"** for [over]writing
* **"rw"** for reading and writing
* @param onsuccess Callback method to be invoked when a file has been opened.
* @param onerror Callback method to be invoked when an error has occurred.
* @param encoding Encoding to use for read/write operations on the file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" latin1 encoding
* If no encoding is passed by the developer, then the default platform encoding must be used.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
openStream: (
mode: FileModeUnion,
onsuccess: FileStreamSuccessCallback,
onerror?: ErrorCallback,
encoding?: string,
) => void;
/**
* Reads the content of a file as a DOMString.
* If the operation is successfully executed, the onsuccess() method is invoked and a DOMString is passed as input parameter that represents the file content in the format determined by the `encoding` parameter.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `IOError` - If the operation is launched on a directory (not a file), the file is not valid, or the file does not exist.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param onsuccess Callback method to be invoked when a file has been successfully read.
* @param onerror Callback method to be invoked when an error occurs while reading a file.
* @param encoding Encoding for read/write operations on a file, at least the following encodings must be supported:
* "[UTF-8](http://www.ietf.org/rfc/rfc2279.txt)" default encoding
* "[ISO-8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)" latin1 encoding
* If no encoding is passed by the developer, then the default platform encoding must be used.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
readAsText: (onsuccess: FileStringSuccessCallback, onerror?: ErrorCallback, encoding?: string) => void;
/**
* Copies (and overwrites if possible and specified) a file or a
* directory from a specified location to another specified location.
* The copy of the file or directory identified by the `originFilePath` parameter must be created in the path passed in the `destinationFilePath` parameter.
* The file or directory to copy must be under the Directory from which the method is invoked, otherwise the operation must not be performed.
* If the copy is performed successfully, the onsuccess() method is invoked.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `NotFoundError` - If the `originFilePath` does not correspond to a valid file or `destinationPath` is not a valid path.
* - `IOError` - If the file in which the copyTo() method is invoked is a file (and not a directory), `originFilePath` corresponds to a file or directory in use by another process, `overwrite` parameter is ***false*** and `destinationFilePath` corresponds to an existing file or directory.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param originFilePath Origin full virtual file or directory path and it must be under the current directory.
* @param destinationFilePath New full virtual file path or directory path.
* @param overwrite Attribute to determine whether overwriting is allowed or not
* If set to ***true***, it enforces overwriting an existing file.
* @param onsuccess Callback method to be invoked when the file has been copied.
* @param onerror Callback method to be invoked when an error has occurred.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
copyTo: (
originFilePath: string,
destinationFilePath: string,
overwrite: boolean,
onsuccess?: SuccessCallback,
onerror?: ErrorCallback,
) => void;
/**
* Moves (and overwrites if possible and specified) a file or a directory from a specified location to another.
* This operation is different from instantiating copyTo() and then deleting the original file, as on certain platforms, this operation does not require extra disk space.
* The file or directory identified by the `originFilePath` parameter is moved to the path passed in the `destinationFilePath` parameter.
* The file to move must be under the directory from which the method is invoked, else the operation can not be performed.
* If the file or directory is moved successfully, the onsuccess() method is invoked.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `NotFoundError` - If `originFilePath` does not correspond to a valid file or `destinationPath` is not a valid path.
* - `IOError` - If the `File` in which the moveTo() method is invoked is a file (not a directory), `originFilePath` corresponds to a file or directory in use by another process, overwrite parameter is ***false*** and `destinationFilePath` corresponds to an existing file or directory.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param originFilePath Origin full virtual file or directory path and it must be under the current directory.
* @param destinationFilePath New full virtual file path or directory path.
* @param overwrite Flag indicating whether to overwrite an existing file.
* When set to ***true***, the files can be overwritten.
* @param onsuccess Callback method to be invoked when the file has been moved.
* @param onerror Callback method to be invoked when an error has occurred.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
moveTo: (
originFilePath: string,
destinationFilePath: string,
overwrite: boolean,
onsuccess?: SuccessCallback,
onerror?: ErrorCallback,
) => void;
/**
* Creates a new directory.
* A new directory will be created relative to the current
* directory that this operation is performed on. The implementation will attempt to
* create all necessary sub-directories specified in the dirPath, as well. The use of "."
* or ".." in path components is not supported.
* This operation can only be performed on file handles that represent directories (that is, `isDirectory` == ***true***).
* If the directory is successfully created, it will be returned.
* In case the directory cannot be created, an error must be thrown with the appropriate error type.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param dirPath Relative directory path and it only contains characters supported by the underlying filesystem.
* @returns File handle of the new directory.
* The new `File` object has "rw" access rights, as it inherits this from the `File` object on which the createDirectory() method is called.
* @throw WebAPIException with error type IOError, InvalidValuesError, TypeMismatchError, SecurityError, UnknownError
*/
createDirectory: (dirPath: string) => File;
/**
* Creates a empty new file in a specified location that is relative to the directory indicated by current `File` object's `path` attribute.
* The use of "." or ".." in path components is not supported. This operation can only be performed on file handlers that represent a directory (that is, `isDirectory` == ***true***).
* If the file is successfully created, a file handle must be returned by this method.
* In case the file cannot be created, an error must be thrown with the appropriate error type.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param relativeFilePath New file path and it should only contain characters supported by the underlying filesystem.
* @returns File handle for the new empty file.
* The new `File` object has "rw" access rights, as it inherits this from the `File` object on which the createFile() method is
* called.
* @throw WebAPIException with error type IOError, InvalidValuesError, TypeMismatchError, SecurityError, UnknownError
*/
createFile: (relativeFilePath: string) => File;
/**
* Resolves an existing file or directory relative to the current directory this operation is performed on and returns a file handle for it.
* The `filePath` is not allowed to contain the "." or ".." directory entries inside its value.
* The encoding of file paths is [UTF-8](http://www.ietf.org/rfc/rfc2279.txt).
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param filePath Relative file path or file URI to resolve.
* @returns File handle of the file.
* The new `File` object inherits its access rights from the `File` object on which this resolve() method is called.
* @throw WebAPIException with error type TypeMismatchError, InvalidValuesError, IOError, NotFoundError, SecurityError, UnknownError
*/
resolve: (filePath: string) => File;
/**
* Deletes a specified directory and directory tree if specified.
* This method attempts to asynchronously delete a directory or directory tree under the current directory.
* If the `recursive` parameter is set to ***true***, all the directories and files under the specified directory must be deleted. If the `recursive` parameter is set to ***false***, the directory is only deleted if it is empty, otherwise an IOError error type will be passed in onerror().
* If the deletion is performed successfully, the onsuccess() is invoked.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `NotFoundError` -If the passed directory does not correspond to a valid directory.
* - `IOError` - If the `File` in which the delete method is invoked is a file (and not a directory), the directory is in use by another process or the directory is not empty and `recursive` argument is ***false***.
* This code is also used if a recursive deletion partially fails and any data deleted so far cannot be recovered. This may occur due to the lack of filesystem permissions or if any directories or files are already opened by other processes.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param directoryPath Full virtual path to the directory to delete (must be under the current one).
* @param recursive Flag indicating whether the deletion is recursive or not
* When set to ***true*** recursive deletion is allowed. Also, this function deletes
* all data in all subdirectories and so needs to be used with caution.
* @param onsuccess Callback method to be invoked when a directory is successfully deleted.
* @param onerror Callback method to be invoked when an error has occurred.
*
* @throw WebAPIException TypeMismatchError, SecurityError
*/
deleteDirectory: (
directoryPath: string,
recursive: boolean,
onsuccess?: SuccessCallback,
onerror?: ErrorCallback,
) => void;
/**
* Deletes a specified file.
* This function attempts to asynchronously delete a file under the current directory.
* If the deletion is performed successfully, the onsuccess() is invoked.
* The ErrorCallback is launched with these error types:
*
* - `InvalidValuesError` - If any of the input parameters contains an invalid value.
* - `NotFoundError` - If the file does not correspond to a valid file.
* - `IOError` - If the file in which the delete() method is invoked is a file (not a directory), the file is in use by another process, or there is no permission in the file system.
* - `UnknownError` - If any other error occurs.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param filePath Full virtual path to the file to delete (must be under the current directory).
* @param onsuccess Callback method to be invoked when the file is successfully deleted.
* @param onerror Callback method to be invoked when an error has occurred.
* @throw WebAPIException TypeMismatchError, SecurityError
*/
deleteFile: (filePath: string, onsuccess?: SuccessCallback, onerror?: ErrorCallback) => void;
}
/**
* The FileStream interface represents a handle to a File opened for read and/or write operations.
* Read and write operations are performed relative to a position attribute, which is a pointer that represents the current position in the file.
* A series of read/write methods are available that permit both binary and text to be processed.
* Once a file stream is closed, any operation attempt made on this stream results in a standard JavaScript error.
* The read/write operations in this interface do not throw any security exceptions as the access rights are expected to be granted through the initial resolve() method or through the openStream() method of the `File` interface. Therefore, all actions performed on a successfully resolved File and FileStream are expected to succeed. This avoids successive asynchronous calls and may potentially increase application for a user.
* @note `deprecated` 5.0
*/
interface FileStream {
/**
* The flag indicating whether the current file pointer is at the end of the file.
* If set to ***true***, this attribute indicates that the file pointer is at the end of the file.
* If set to ***false***, this attribute indicates that the file pointer is not at the end of the file and so it is anywhere within the file.
* @note `deprecated` 5.0
*/
readonly eof: boolean;
/**
* The flag indicating the stream position for reads/writes.
* The stream position is an offset of bytes from the start of the file stream. When invoking an operation that reads or writes from the stream, the operation will take place from the byte defined by this `position` attribute. If the read or write operation is successful, the position of the stream is advanced by the number of bytes read or written. If the read/write operation is not successful, the position of the stream is unchanged.
* @note `deprecated` 5.0
*/
position: number;
/**
* The number of bytes that are available for reading from the stream.
* The number of bytes available for reading is the maximum amount of bytes that can be read in the next read operation.
* It corresponds to the number of bytes available after the file pointer denoted by the `position` attribute.
* ***-1 ***if EOF is ***true***.
* @note `deprecated` 5.0
*/
readonly bytesAvailable: number;
/**
* Closes this FileStream.
* Flushes any pending buffered writes and closes the File. Always succeeds.
* Note that pending writes might not succeed.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
*/
close: () => void;
/**
* Reads the specified number of characters from the position of the file pointer in a FileStream and returns the characters as a string.
* The resulting string length might be shorter than `charCount` if EOF is ***true***.
*
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param charCount Number of characters being read.
* @returns Array of read characters as a string.
* @throw WebAPIException with error type IOError, TypeMismatchError, InvalidValuesError, SecurityError
*/
read: (charCount: number) => string;
/**
* Reads the specified number of bytes from a FileStream.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param byteCount Number of bytes to read.
* @returns Result of read bytes as a byte (or number) array.
* @throw WebAPIException IOError, TypeMismatchError, InvalidValuesError, SecurityError
*/
readBytes: (byteCount: number) => Uint8Array;
/**
* Reads the specified number of bytes from this FileStream, encoding the result in base64.
* @note `deprecated` 5.0
*
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.read
* @param byteCount Number of bytes to read.
* @returns Array of read characters as base64 encoding string.
* @throw WebAPIException with error type IOError, TypeMismatchError, InvalidValuesError, SecurityError
*/
readBase64: (byteCount: number) => string;
/**
* Writes the specified DOMString to a FileStream.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param stringData Actual string to write.
* @throw WebAPIException IOError, TypeMismatchError, SecurityError
*/
write: (stringData: string) => void;
/**
* Writes the specified bytes to this FileStream.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param byteData Byte data array being written.
* @throw WebAPIException IOError, TypeMismatchError, SecurityError
*/
writeBytes: (byteData: Uint8Array) => void;
/**
* Writes the result to this FileStream after converting the specified base64 DOMString to bytes.
* @note `deprecated` 5.0
* @privilegeLevel public
* @privilegeName http://tizen.org/privilege/filesystem.write
* @param base64Data The base64 data to written.
* @throw WebAPIException with error type IOError, InvalidValuesError, SecurityError
*/
writeBase64: (base64Data: string) => void;
}
/**
* The FileSuccessCallback interface defines file system success callback with a `File` object as input argument.
* It is used in asynchronous operations, such as FileSystemManager.resolve(), copying, moving and deleting files.
* @note `deprecated` 5.0
*/
interface FileSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @note `deprecated` 5.0
* @param file File resulting from the asynchronous call.
*/
(file: File): void;
}
/**
* The FileSystemStorageArraySuccessCallback callback interface specifies a success callback with an array of FileSystemStorage objects as input argument.
* It is used in asynchronous operations, such as FileSystemManager.listStorages().
*/
interface FileSystemStorageArraySuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param storages List of available storage devices.
*/
(storages: FileSystemStorage[]): void;
}
/**
* The FileSystemStorageSuccessCallback callback interface specifies a success callback with a `FileSystemStorage` object as input argument.
* It is used in asynchronous operations, such as FileSystemManager.getStorage() and FileSystemManager.addStorageStateChangeListener().
*/
interface FileSystemStorageSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param storage Storage device structure.
*/
(storage: FileSystemStorage): void;
}
/**
* The PathSuccessCallback callback interface specifies a success callback with a `Path` value as input argument.
* It is used in asynchronous operations of the `FileSystemManager` interface.
* @since 5.0
*/
interface PathSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param path Path to created or changed resource on the filesystem. In case of deletion, path to parent of the deleted resource is given.
*/
(path: Path): void;
}
/**
* The SeekSuccessCallback callback interface specifies a success callback with a `long long` value as input argument.
* It is used in asynchronous operation FileHandle.seekNonBlocking().
* @since 5.0
*/
interface SeekSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param position File position indicator.
*/
(position: number): void;
}
/**
* he ReadStringSuccessCallback callback interface specifies a success callback with a `DOMString` value as input argument.
* It is used in asynchronous operation FileHandle.readStringNonBlocking().
* @since 5.0
*/
interface ReadStringSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param string String with data read from file.
*/
(string: string): void;
}
/**
* The WriteStringSuccessCallback callback interface specifies a success callback with a `long long` value as input argument.
* It is used in asynchronous operation FileHandle.writeStringNonBlocking().
* @since 5.0
*/
interface WriteStringSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param bytesCount Number of bytes written (can be more than inputString length for multibyte encodings and will never be less).
*/
(bytesCount: number): void;
}
/**
* The ReadBlobSuccessCallback callback interface specifies a success callback with a `Blob` object as input argument.
* It is used in asynchronous operation FileHandle.readBlobNonBlocking().
* @since 5.0
*/
interface ReadBlobSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param blob Blob object with file content.
*/
(blob: Blob): void;
}
/**
* The ReadDataSuccessCallback callback interface specifies a success callback with a `Uint8Array` value as input argument.
* It is used in asynchronous operation FileHandle.readDataNonBlocking().
* @since 5.0
*/
interface ReadDataSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param data A TypedArray with file content.
*/
(data: Uint8Array): void;
}
/**
* The FileStringSuccessCallback callback interface specifies a success callback with a DOMString object as input argument.
* It is used in asynchronous operation File.readAsText().
* @note `deprecated` 5.0
*/
interface FileStringSuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @note `deprecated` 5.0
* @param fileStr File represented as a DOMString resulting from the asynchronous call.
*/
(fileStr: string): void;
}
/**
* The FileStreamSuccessCallback interface specifies a success callback with a `FileStream` object as input argument.
* It is used in asynchronous operation File.openStream().
* @note `deprecated` 5.0 Since 5.0
*/
interface FileStreamSuccessCallback {
/**
* Called when the File.openStream asynchronous call completes successfully.
* @note `deprecated` 5.0 Since 5.0
* @param filestream Filestream to access file content.
*/
(filestream: FileStream): void;
}
/**
* The ListDirectorySuccessCallback interface defines success callback for listing methods.
* This callback interface specifies a success callback with a function taking an array of strings as input argument. It is used in asynchronous operation FileSystemManager.listDirectory().
* @since 5.0
*/
interface ListDirectorySuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @param names File or directory names resulting from the asynchronous call.
* @param path Path to listed directory.
*/
(names: string[], path: Path): void;
}
/**
* The FileArraySuccessCallback interface defines file system specific success callback for listing methods.
* This callback interface specifies a success callback with a function taking an array of `File` objects as input argument. It is used in asynchronous methods, such as File.listFiles().
* @note `deprecated` 5.0
*/
interface FileArraySuccessCallback {
/**
* Called when the asynchronous call completes successfully.
* @note `deprecated` 5.0
* @param files Files resulting from the asynchronous call.
*/
(files: File[]): void;
}
}
|
a90035860290e26e1697ace5793becb7ee15b14b | TypeScript | TatsuyaYamamoto/school-idol-game-project | /packages/oimo-no-mikiri/src/js/texture/containers/GameResultPaper/TopTime.ts | 2.71875 | 3 | import { Container } from "pixi.js";
import { t } from "@sokontokoro/mikan";
import Text from "../../internal/Text";
import { Ids as StringIds } from "../../../resources/string";
/**
* Container that has top time' label and value text.
* It's set right end as a container's anchor.
* Then, you should consider it in implementing that {@link StraightWins#position}.
*
* @class
*/
export class TopTime extends Container {
readonly _label: Text;
readonly _value: Text;
constructor(topTime: number) {
super();
this._label = new Text(t(StringIds[StringIds.LABEL_TOP_TIME]), {
fontFamily: "g_brushtappitsu_freeH",
fontSize: 20,
// textBaseline: 'middle',
padding: 5, // prevent to cut off words.
});
this._value = new Text(`${topTime}`, {
fontFamily: "g_brushtappitsu_freeH",
fontSize: 30,
padding: 5, // prevent to cut off words.
});
// Set position to be set right end as anchor.
const totalWidth = this._label.width + this._value.width;
this._label.position.x = -1 * totalWidth + this._label.width * 0.5;
this._value.position.x = -1 * this._value.width * 0.5;
this.addChild(this._label, this._value);
}
}
export default TopTime;
|
3d86d222d39b643f8281ff8d1174e39262eb046c | TypeScript | rajmohan6268/nodejs-db-orm-world | /with Knex/nestjs-knex-postgres/src/app/module/dto/user.dto.ts | 2.5625 | 3 | import { PartialType } from "@nestjs/swagger";
import { IsEmail, IsNotEmpty, IsString } from "class-validator";
export class CreateUserDto {
@IsString()
firstName!: string;
@IsString()
lastName!: string;
@IsString()
@IsEmail()
email!: string;
}
export class UpdateUserDto extends PartialType(CreateUserDto) { }
|
0b952f92cf69bdb36c9ba0e40b8b5b78a0e38811 | TypeScript | gagiD/chartjs-plugin-centerlabel | /src/plugin.ts | 2.796875 | 3 | import { Plugin, ChartType, DoughnutController } from 'chart.js'
import CenterLabelOptions from './CenterLabelOptions'
declare type CenterPlugin<TType extends ChartType = ChartType> = Plugin<
TType,
CenterLabelOptions
>
export default {
id: 'centerlabel',
afterDraw: function (chart, _, options) {
if (options) {
const ctx = chart.ctx
let innerRadius = (chart.chartArea.top - chart.chartArea.bottom) / 2
if (chart.config.type == 'doughnut') {
const meta = chart.getDatasetMeta(0)
const controller = meta.controller as DoughnutController
if (controller) innerRadius = controller.innerRadius
}
const fontStyle = options.fontFamily || 'Arial'
const txt = options.text
const color = options.color || '#000'
const maxFontSize = options.maxFontSize || 75
const sidePadding = options.sidePadding || 20
const sidePaddingCalculated =
(sidePadding / 100) * (innerRadius * 2)
// Start with a base font of 30px
ctx.font = '30px ' + fontStyle
// Get the width of the string and also the width of the element minus 10 to give it 5px side padding
const stringWidth = ctx.measureText(txt).width
const elementWidth = innerRadius * 2 - sidePaddingCalculated
// Find out how much the font can grow in width.
const widthRatio = elementWidth / stringWidth
const newFontSize = Math.floor(30 * widthRatio)
const elementHeight = innerRadius * 2
// Pick a new font size so it will not be larger than the height of label.
let fontSizeToUse = Math.min(
newFontSize,
elementHeight,
maxFontSize
)
let minFontSize = options.minFontSize
const lineHeight = options.lineHeight || 25
let wrapText = false
if (minFontSize === undefined) {
minFontSize = 20
}
if (minFontSize && fontSizeToUse < minFontSize) {
fontSizeToUse = minFontSize
wrapText = true
}
// Set font settings to draw it correctly.
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
const centerX = (chart.chartArea.left + chart.chartArea.right) / 2
let centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2
ctx.font = fontSizeToUse + 'px ' + fontStyle
ctx.fillStyle = color
if (!wrapText) {
ctx.fillText(txt, centerX, centerY)
return
}
const words = txt.split(' ')
let line = ''
const lines = []
// Break words up into multiple lines if necessary
for (let n = 0; n < words.length; n++) {
const testLine = line + words[n] + ' '
const metrics = ctx.measureText(testLine)
const testWidth = metrics.width
if (testWidth > elementWidth && n > 0) {
lines.push(line)
line = words[n] + ' '
} else {
line = testLine
}
}
// Move the center up depending on line height and number of lines
centerY -= (lines.length / 2) * lineHeight
for (let n = 0; n < lines.length; n++) {
ctx.fillText(lines[n], centerX, centerY)
centerY += lineHeight
}
//Draw text in center
ctx.fillText(line, centerX, centerY)
}
},
} as CenterPlugin
|
daa5aba1dbdc0b7dcfc9e0f943dc446de4ff1462 | TypeScript | vicodersvn/nestjs-casbin | /src/components/auth/entities/password-reset.entity.ts | 2.609375 | 3 | import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity({ name: 'password_resets' })
export class PasswordReset {
@PrimaryGeneratedColumn()
id: number;
@Column({
type: 'varchar',
})
email: string;
@Column({
type: 'varchar',
})
token: string;
@Column({ type: 'timestamp' })
expire: Date;
@CreateDateColumn({
type: 'timestamp',
precision: null,
default: () => 'NOW()',
})
public created_at: Date;
@UpdateDateColumn({
type: 'timestamp',
precision: null,
default: () => 'NOW()',
})
public updated_at: Date;
generatePasswordResetLink(base_url: string): string {
const path = `auth/reset?token=${this.token}`;
const url = new URL(path, base_url);
return url.href;
}
generateExpirePasswordResetLink(base_url: string): string {
const path = `auth/expire?token=${this.token}`;
const url = new URL(path, base_url);
return url.href;
}
}
|
3c6674ac0ff3f9250895a2ab5495fc727502ff21 | TypeScript | antunesbe/taskboard_desafio | /src/app/shared/task.model.ts | 2.65625 | 3 | export class Task {
_id: string;
title: string;
description: string;
attachments: any[];
status: string = 'todo';
developed_by: string;
priority: Number;
owner: string;
created_at: Date = new Date();
updated_at: Date = new Date();
constructor(data?: Task){
if(data){
this._id = data._id;
this.title = data.title;
this.description = data.description;
this.attachments = data.attachments;
this.priority = data.priority;
this.developed_by = data.developed_by;
this.owner = data.owner;
this.status = (data.status)?data.status:'todo';
this.created_at = (data.created_at)?data.created_at:new Date();
this.updated_at = new Date();
}
}
} |
943b95ddaa124533268272b4f659c467e79125d7 | TypeScript | thanhtung030400/ThanhtungA1020I1 | /Module_5/bai_6/register_and_login/src/app/register-form/register-form.component.ts | 2.6875 | 3 | import { Component, OnInit } from '@angular/core';
import {AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators} from '@angular/forms';
function comparePassword(c: AbstractControl) {
const v = c.value;
return (v.password === v.confirmPassword) ? null : {
passwordnotmatch: true
};
}
@Component({
selector: 'app-register-form',
templateUrl: './register-form.component.html',
styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {
registerForm: FormGroup;
// comparePassword: ValidatorFn = (passwordGroup: AbstractControl): ValidationErrors|null =>{
// let password = passwordGroup.get('password').value;
// let confirmPassword = passwordGroup.get('confirmPassword').value;
// return password === confirmPassword ? null : {notSame: true}
// };
constructor() {
}
ngOnInit(): void {
this.registerForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.pattern('^[a-z][a-z0-9_\\.]{1,32}@[a-z0-9]{2,}(\\.[a-z0-9]{2,4}){1,2}$')]),
passwordGroup: new FormGroup({
password: new FormControl('', [Validators.required, Validators.minLength(6)]),
confirmPassword: new FormControl('', [Validators.required, Validators.minLength(6)])
}, {validators: comparePassword}),
country: new FormControl('', [Validators.required]),
age: new FormControl('', [Validators.required, Validators.min(18)]),
gender: new FormControl('', [Validators.required]),
phone: new FormControl('', [Validators.required, Validators.pattern('^\\+84\\d{9,10}$')])
});
}
onSubmit() {
console.log(this.registerForm.value);
}
}
|
d5012b197f1aa6efc8c82265e3112985decfa1d4 | TypeScript | fuunnx/portals-poc | /src/lang/stringify/index.test.ts | 2.640625 | 3 | import { parse } from '../parse'
import { stringify } from './index'
import { comment, portalStart, portalEnd, warp } from '../helpers'
test('empty text', () => {
const source = ''
expect(stringify(parse(source))).toEqual(source)
})
test('simple text', () => {
const source = `1
2
3`
expect(stringify(parse(source))).toEqual(source)
})
test('less simple text', () => {
const source = `${comment(portalStart(1))}
1
${comment(portalEnd(1))}
2
${comment(warp(1))}
3`
expect(stringify(parse(source))).toEqual(source)
})
test('multiple per line', () => {
const source = ` ${comment(portalStart(1), portalEnd(1), warp(1))}`
expect(stringify(parse(source))).toEqual(source)
})
test('multiple destinations per line', () => {
const source = `
${comment(portalStart(1), portalEnd(1))}
${comment(portalStart(2), portalEnd(2))}
${comment(warp(1), warp(2))}`
expect(stringify(parse(source))).toEqual(source)
})
test('partial content', () => {
const source = `
${comment(portalStart(2), portalEnd(2))}
${comment(warp(''))}`
expect(stringify(parse(source))).toEqual(source)
})
|
c93fa6fd6455f93830aa286babb92c012be3c5e6 | TypeScript | Ana-MM/Practica-Typescript | /persona.ts | 2.59375 | 3 | import { Direccion } from "./direccion";
import { Mail } from './mail';
import { Telefono } from './telefono';
export class Persona {
private _nombre: string;
private _apellidos: string;
private _edad: number;
private _dni: string;
private _cumpleaños: Date;
private _color: string;
private _sexo: string;
private _direcciones: Direccion[];
private _mails: Mail[];
private _telefonos: Telefono[];
private _notas: string;
constructor(nombre: string, apellidos: string, edad: number, dni: string, cumpleaños: Date, color: string, sexo: string, direcciones: Direccion[], mails: Mail[], telefonos: Telefono[], notas: string) {
this._nombre = nombre;
this._apellidos = apellidos;
this._edad = edad;
this._dni = dni;
this._cumpleaños = cumpleaños;
this._color = color;
this._sexo = sexo;
this._direcciones = direcciones;
this._mails = mails;
this._telefonos = telefonos;
this._notas = notas;
}
public get nombre(): string {
return this._nombre;
}
public set nombre(value: string) {
this._nombre = value;
}
public get apellidos(): string {
return this._apellidos;
}
public set apellidos(value: string) {
this._apellidos = value;
}
public get edad(): number {
return this._edad;
}
public set edad(value: number) {
this._edad = value;
}
public get dni(): string {
return this._dni;
}
public set dni(value: string) {
this._dni = value;
}
public get cumpleaños(): Date {
return this._cumpleaños;
}
public set cumpleaños(value: Date) {
this._cumpleaños = value;
}
public get color(): string {
return this._color;
}
public set color(value: string) {
this._color = value;
}
public get sexo() {
return this._sexo;
}
public set sexo(value) {
this._sexo = value;
}
public get direcciones() {
return this._direcciones;
}
public set direcciones(value) {
this._direcciones = value;
}
public agregarDireccion(value: Direccion) {
this._direcciones.push(value);
}
public get mail() {
return this._mails;
}
public set mail(value) {
this._mails = value;
}
public agregarMail(value: Mail) {
this._mails.push(value);
}
public get telefono() {
return this._telefonos;
}
public set telefono(value) {
this._telefonos = value;
}
public agregarTelefono(value: Telefono) {
this._telefonos.push(value);
}
public get notas() {
return this._notas;
}
public set notas(value) {
this._notas = value;
}
imprimirPersona(): void {
console.log(this._nombre, this._apellidos, this._edad, this._dni, this._cumpleaños, this._color, this._sexo, this._mails, this._telefonos, this._notas);
console.log("-----Direcciones-----")
for (let i = 0; i < this._direcciones.length; i++) {
console.log(this._direcciones[i])
}
console.log("-----Mails-----")
for (let i = 0; i < this._mails.length; i++) {
console.log(this._mails[i])
}
console.log("-----Telefonos-----")
for (let i = 0; i < this._telefonos.length; i++) {
console.log(this._telefonos[i])
}
}
} |
ff0f07ffda8acd5bb4d09e76ec8036e987ec61ad | TypeScript | Sebasmn/angular007 | /src/app/agregar/agregar.component.ts | 2.84375 | 3 | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
interface Usuario{
nombre: string;
apellido: string;
edad: number;
correo: string;
clave: string;
}
@Component({
selector: 'app-agregar',
templateUrl: './agregar.component.html',
styleUrls: ['./agregar.component.css']
})
export class AgregarComponent implements OnInit {
//contiene la referencia al objeto con el formulario reactivo
formularioCreado!: FormGroup;
//la lista de usuarios registrados
listaUsuarios:Array<Usuario> = new Array<Usuario>();
//determina si se desea realizar "Agregar" o "Editar"
esNuevo:boolean = true;
posicionEdicion:number = -1;
btnEliminar:boolean = false;
//inyeccion de dependencias
constructor(private formBuilder:FormBuilder) { }
ngOnInit(): void {
//llamar el metodo para crear el formulario
this.crearFormulario();
}
// metodo para crear el formulario reactivo
crearFormulario(){
// usar formBuilder para crear el formulario
this.formularioCreado = this.formBuilder.group({
nombre: ['', Validators.required],
apellido: ['', Validators.required],
edad: ['', Validators.compose([Validators.required, Validators.min(1)])],
correo: ['', Validators.compose([Validators.required, Validators.email])],
clave: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
});
}
agregar(){
//obtener los valores ingresados en los inputs
//console.log(this.formularioCreado.value);
//agregar al array el registro ingresado en el formulario
this.listaUsuarios.push(this.formularioCreado.value as Usuario);
//limpiar o resetear los controles del formulario
this.formularioCreado.reset();
}
//editar el registro indicado
editar(){
//asignar los datos ingresados en los controles al Array<Usuario>
this.listaUsuarios[this.posicionEdicion].nombre = this.formularioCreado.value.nombre;
this.listaUsuarios[this.posicionEdicion].apellido = this.formularioCreado.value.apellido;
this.listaUsuarios[this.posicionEdicion].edad = this.formularioCreado.value.edad;
this.listaUsuarios[this.posicionEdicion].correo = this.formularioCreado.value.correo;
this.listaUsuarios[this.posicionEdicion].clave = this.formularioCreado.value.clave;
//resetear el formulario
this.formularioCreado.reset();
//mostrar el boton de agregar
this.esNuevo = true;
// cambiar la posicion del registro actual a editar
this.posicionEdicion = -1;
this.btnEliminar = false;
}
editarUsuarioActual(posicion:number){
//editar el usuario en la posicion indicada
// this.listaUsuarios[posicion].nombre = 'Editar';
// this.listaUsuarios[posicion].correo = 'correo@gmail.com';
// this.listaUsuarios[posicion].clave = '123456';
//console.log(this.listaUsuarios[posicion].nombre,this.listaUsuarios[posicion].correo,this.listaUsuarios[posicion].clave);
//utilizar el objeto "formularioCreado", que tiene la referencia al formulario reactivo
//y con el metodo (setValue) asignar un nuevo registro
this.formularioCreado.setValue({
nombre: this.listaUsuarios[posicion].nombre,
apellido: this.listaUsuarios[posicion].apellido,
edad: this.listaUsuarios[posicion].edad,
correo: this.listaUsuarios[posicion].correo,
clave: this.listaUsuarios[posicion].clave
});
//asignar la posicion para editar
this.posicionEdicion = posicion;
//ocultar el boton agregar y mostrar el boton de editar
this.esNuevo = false;
this.btnEliminar = true;
}
//eliminar el registro actual
eliminarUsuarioActual(posicion:number){
//eliminar el registro del Array
this.listaUsuarios.splice(posicion, 1);
}
}
|
b1686d348f0f96db4eebc493b3e49a16609ef5ce | TypeScript | superclassiceth/airgap-vault | /src/app/pipes/amount-converter/amount-converter.pipe.spec.ts | 2.6875 | 3 | import { BigNumber } from 'bignumber.js'
import { AmountConverterPipe } from './amount-converter.pipe'
import { MainProtocolSymbols } from 'airgap-coin-lib/dist/utils/ProtocolSymbols'
const BN: typeof BigNumber = BigNumber.clone({
FORMAT: {
decimalSeparator: `.`,
groupSeparator: `'`,
groupSize: 3
}
})
describe('AmountConverter Pipe', () => {
let amountConverterPipe: AmountConverterPipe
beforeEach(() => {
amountConverterPipe = new AmountConverterPipe()
})
describe('format number with commas', () => {
it('should format short number', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1`))).toEqual(`1`)
})
it('should add highcommas', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1234567891`))).toEqual(`1'234'567'891`)
})
it('should should add highcommas only to first part of number', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`12345.67891`))).toEqual(`12'345.67891`)
})
it('should format long numbers', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1234567891.1234567891`))).toEqual(`1'234'567'891.1234567891`)
})
it('should format short number if smaller than maxDigits', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1`), 8)).toEqual(`1`)
})
it('should add "K" if number is too long', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1234567891`), 8)).toEqual(`1'234'567K`)
})
it('should add "K" if number is too long and omit floating point', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1234567891.1234567891`), 8)).toEqual(`1'234'567K`)
})
it('should format floating point part correctly', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`12345.67891`), 8)).toEqual(`12'345.679`)
})
it('should add "M" if number is too long', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`12345678912345`), 8)).toEqual(`12'345'678M`)
})
it('should add "M" if number is too long and omit floating point', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`12345678912345.000000000001`), 8)).toEqual(`12'345'678M`)
})
it('should limit long floating point', () => {
expect(amountConverterPipe.formatBigNumber(new BN(`1.000000000001`), 8)).toEqual(`1`)
})
})
describe('makeFullNumberSmaller', () => {
it('should not make small number smaller', () => {
expect(amountConverterPipe.makeFullNumberSmaller(new BN('1'), 3)).toEqual('1')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('12'), 3)).toEqual('12')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('123'), 3)).toEqual('123')
})
it('should make large number smaller', () => {
expect(amountConverterPipe.makeFullNumberSmaller(new BN('1234'), 3)).toEqual('1K')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('12345'), 3)).toEqual('12K')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('123456'), 3)).toEqual('123K')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('1234567'), 3)).toEqual('1M')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('12345678'), 3)).toEqual('12M')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('123456789'), 3)).toEqual('123M')
expect(amountConverterPipe.makeFullNumberSmaller(new BN('123456789123456789'), 3)).toEqual(`123'456'789'123M`)
})
})
it('should display very small ETH number to a non-scientific string representation', () => {
expect(amountConverterPipe.transform('1', { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual(
'0.000000000000000001 ETH'
)
})
it('should display a normal ETH number to a non-scientific string representation', () => {
expect(
amountConverterPipe.transform('1000000000000000000', {
protocolIdentifier: MainProtocolSymbols.ETH,
maxDigits: 0
})
).toEqual('1 ETH')
})
it('should display a big ETH number to a non-scientific string representation', () => {
expect(
amountConverterPipe.transform('10000000000000000000000000000000000', {
protocolIdentifier: MainProtocolSymbols.ETH,
maxDigits: 0
})
).toEqual(`10'000'000'000'000'000 ETH`)
})
it('should return a valid amount if value is 0', () => {
expect(amountConverterPipe.transform('0', { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual('0 ETH')
})
it('should return an empty string when protocolIdentifier is not set', () => {
expect(amountConverterPipe.transform('1', { protocolIdentifier: undefined, maxDigits: 0 })).toEqual('')
})
it('should handle values that are not a number', () => {
expect(amountConverterPipe.transform('test', { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual('')
})
it('should handle values that are undefined', () => {
expect(amountConverterPipe.transform(undefined, { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual('')
})
it('should handle values that are null', () => {
expect(amountConverterPipe.transform(null, { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual('')
})
it('should handle values that are empty object', () => {
const value: any = {}
expect(amountConverterPipe.transform(value, { protocolIdentifier: MainProtocolSymbols.ETH, maxDigits: 0 })).toEqual('')
})
function getTest(args) {
it('Test with: ' + JSON.stringify(args), () => {
expect(amountConverterPipe.transform(args.value, { protocolIdentifier: args.protocolIdentifier, maxDigits: 0 })).toEqual(
args.expected
)
})
}
function makeTests(argsArray) {
argsArray.forEach((v) => {
getTest(v)
})
}
const truthyProtocolIdentifiers = [
{ value: '1', protocolIdentifier: MainProtocolSymbols.BTC, expected: '0.00000001 BTC' },
{ value: '1', protocolIdentifier: MainProtocolSymbols.ETH, expected: '0.000000000000000001 ETH' }
]
makeTests(truthyProtocolIdentifiers)
const falsyValues = [
{ value: false, protocolIdentifier: MainProtocolSymbols.ETH, expected: '' },
{ value: 0, protocolIdentifier: MainProtocolSymbols.ETH, expected: '0 ETH' },
{ value: '', protocolIdentifier: MainProtocolSymbols.ETH, expected: '' },
{ value: null, protocolIdentifier: MainProtocolSymbols.ETH, expected: '' },
{ value: undefined, protocolIdentifier: MainProtocolSymbols.ETH, expected: '' },
{ value: NaN, protocolIdentifier: MainProtocolSymbols.ETH, expected: '' }
]
makeTests(falsyValues)
const falsyProtocolIdentifiers = [
{ value: '1', protocolIdentifier: false, expected: '' },
{ value: '1', protocolIdentifier: 0, expected: '' },
{ value: '1', protocolIdentifier: '', expected: '' },
{ value: '1', protocolIdentifier: null, expected: '' },
{ value: '1', protocolIdentifier: undefined, expected: '' },
{ value: '1', protocolIdentifier: NaN, expected: '' },
{ value: '1', protocolIdentifier: 'test', expected: '' },
{ value: '1', protocolIdentifier: 'asdf', expected: '' }
]
makeTests(falsyProtocolIdentifiers)
})
|
65619b1b56295181568b1a65baf6bd184b34e558 | TypeScript | GEBittencourt/sdk-jsddd | /src/lib/query/type/get-all-response.ts | 2.84375 | 3 | /**
* Definition of get all response
*/
export type GetAllResponse<DTO> = {
/**
* List of DTO (Data transfer object)
*/
items: DTO[];
/**
* Show if next page exists
*/
hasNext: boolean;
/**
* Number of page returned
*/
page: number;
/**
* Quantity of page records requested
*/
pageSize: number;
/**
* Total existing data
*/
length?: number;
};
|
92e57fe2859f0e5679482e510135f8ac21b8e637 | TypeScript | react-widget/tree-basic | /src/Node.ts | 2.90625 | 3 | let idx = 1;
interface NodeOptions {
rootId?: null | string | number;
idField?: string;
pidField?: string;
leafField?: string;
}
interface NodeState {
expandedMap?: Record<string, boolean>;
}
export default class Node<T = Record<string, any>> {
id: string | number;
pid: string | number;
leaf: boolean;
data: T;
loading: boolean;
root: boolean;
expanded: boolean;
depth: number;
constructor(
data: T,
parentNode: Node | null,
options: NodeOptions = {},
state: NodeState = {}
) {
const { rootId = null, idField = "id", pidField = "pid", leafField = "leaf" } = options;
const { expandedMap = {} } = state;
this.id = data[idField];
this.pid = data[pidField];
this.leaf = data[leafField];
this.data = data;
if (this.id == null && this.id !== rootId) {
this.id = `node_${idx++}`;
}
this.loading = false;
this.root = !parentNode;
this.expanded = this.root ? true : !!expandedMap[this.id];
this.depth = parentNode ? parentNode.depth + 1 : 0;
}
getId() {
return this.id;
}
getDepth() {
return this.depth;
}
setDepth(depth: number) {
this.depth = depth;
}
getData() {
return this.data;
}
isRoot() {
return this.root;
}
isLeaf() {
return this.leaf;
}
setExpanded(expanded: boolean) {
this.expanded = expanded;
}
isExpanded() {
return this.expanded;
}
setLoading(loading: boolean) {
this.loading = loading;
}
isLoading() {
return this.loading;
}
}
|
6a855bfc92c91fb8a0c306432338975641ca3470 | TypeScript | tajpouria/GOF-design-pattenrs | /SOLID_Principles/single_responsibility_principle/Jounral.ts | 3.484375 | 3 | // bad way
class BadJournal {
public entries: string[] = [];
public saveJournal: Record<string, string> = {};
constructor(public title: string) {}
public addEntry(entry: string) {
this.entries.push(entry);
}
public save() {
this.entries.map((entry, index) => {
this.saveJournal[index] = entry;
});
}
}
// right way
class RightJournal {
public entries: string[] = [];
public saveJournal: Record<string, string> = {};
constructor(public title: string) {}
public addEntry(entry: string) {
this.entries.push(entry);
}
public save() {
Persister.save(this.saveJournal, this.entries);
}
}
class Persister {
static save(placeToSave: Record<string, string>, entriesToSave: string[]) {
return entriesToSave.map((entry, index) => {
placeToSave[index] = entry;
});
}
}
|
b13fef830162ad08a68d9442977ff1442fa83f32 | TypeScript | greghart/climbing-app | /src/typescript/redux/store/thunkBundler.ts | 2.90625 | 3 |
function isPromise(val) {
return val && typeof val.then === 'function';
}
/**
* A replacement for redux-thunk that will intercept and callback promises
*/
function thunkBundler(onPromise?: (promise: Promise<unknown>) => unknown) {
return (ref: any) => {
return (next) => {
return (action) => {
if (typeof action === 'function') {
const ret = action(ref.dispatch, ref.getState);
if (isPromise(ret) && onPromise) {
onPromise(ret);
}
return ret;
}
return next(action);
};
};
};
}
export default thunkBundler;
|
730757d3c3940b2fa115e832b88b2e47e448ca31 | TypeScript | snhardin/you-owe-me-money | /api/src/util/authentication.ts | 2.59375 | 3 | /**
* Name of the cookie to store the JWT in
*/
export const JWT_COOKIE_NAME = 'youOwe-token';
/**
* Information encrypted and stored in the JWT
*/
export interface JwtInfo {
/**
* The email of the user
*/
email: string;
}
|
15857a9555475d3c5e677d6755101a98d8cf7f2a | TypeScript | visgl/deck.gl | /modules/geo-layers/src/wms-layer/utils.ts | 2.671875 | 3 | import {lngLatToWorld} from '@math.gl/web-mercator';
// https://epsg.io/3857
// +proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs
const HALF_EARTH_CIRCUMFERENCE = 6378137 * Math.PI;
/** Projects EPSG:4326 to EPSG:3857
* This is a lightweight replacement of proj4. Use tests to ensure conformance.
*/
export function WGS84ToPseudoMercator(coord: [number, number]): [number, number] {
const mercator = lngLatToWorld(coord);
mercator[0] = (mercator[0] / 256 - 1) * HALF_EARTH_CIRCUMFERENCE;
mercator[1] = (mercator[1] / 256 - 1) * HALF_EARTH_CIRCUMFERENCE;
return mercator;
}
|
ded58b51d022c6742b6e0cc5e67cc765013815a4 | TypeScript | xesxfs/mjgo | /recsmj2/csmj/src/gdmj/view/game/ui/SelectActUI.ts | 2.53125 | 3 | /**
* 操作面板,吃碰杠胡
* @author chenkai
* @date 2016/7/11
*
* @author huanglong
* @data 2017/04/12 chongxie
*/
class SelectActUI extends eui.Component{
private eatBtn:SelectActBtn;
private pengBtn:SelectActBtn;
private gangBtn:SelectActBtn;
private huBtn:SelectActBtn;
private passBtn:SelectActBtn;
private yaoBtn:SelectActBtn;
private qishouBtn:SelectActBtn;
private buBtn:SelectActBtn;
private zhongtuBtn:SelectActBtn;
private btnList = {};
public panelWidth = 600; //面板宽度
private itemWidth = 150; //按钮宽度
public bAnGang:boolean = false; //用于记录暗杠,因为暗杠按钮没有
private bInitRes:boolean = false;
private showBtnList: Array<any>;
public constructor() {
super();
this.skinName = "SelectActUISkin";
}
public childrenCreated(){
this.btnList[ACT_state.Act_Pass] = this.passBtn;
this.btnList[ACT_state.Act_Peng] = this.pengBtn;
this.btnList[ACT_state.Act_Chi] = this.eatBtn;
this.btnList[ACT_state.Act_Gang] = this.gangBtn;
this.btnList[ACT_state.Act_AnGang] = this.gangBtn;
this.btnList[ACT_state.Act_Hu] = this.huBtn;
this.btnList[ACT_state.Act_Bu] = this.buBtn;
this.btnList[ACT_state.Act_Yao] = this.yaoBtn;
this.btnList[ACT_state.Act_Qishou] = this.qishouBtn;
this.btnList[ACT_state.Act_Zhongtu] = this.zhongtuBtn;
this.touchEnabled = false;
this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch ,this);
}
private initRes(){
if(this.bInitRes == false){
this.bInitRes = true;
this.passBtn.setNewActSkin(ACT_act.Act_Pass);
this.eatBtn.setNewActSkin(ACT_act.Act_Chi);
this.pengBtn.setNewActSkin(ACT_act.Act_Peng);
this.gangBtn.setNewActSkin(ACT_act.Act_Gang);
this.huBtn.setNewActSkin(ACT_act.Act_Hu);
this.yaoBtn.setNewActSkin(ACT_act.Act_Yao);
this.buBtn.setNewActSkin(ACT_act.Act_Bu);
this.qishouBtn.setNewActSkin(ACT_act.Act_Qishou);
this.zhongtuBtn.setNewActSkin(ACT_act.Act_Zhongtu);
}
}
//点击按钮,传递相应动作
private onTouch(e:egret.TouchEvent){
if(e.target instanceof SelectActBtn){
for(var key in this.btnList){
if(this.btnList[key] == e.target){
this.dispatchEventWith("sendActEvent", false, parseInt(key));
break;
}
}
}
}
/**
* 根据可行操作,显示操作面板
* @param actList 动作列表Act_state (碰、杠、胡等)
*/
public updateInfo(actList){
this.initRes();
var len = actList.length;
this.bAnGang = false;
this.showBtnList = [];
for(var i=len-1;i>=0;i--){
var act = actList[i];
var btn = this.btnList[act];
if(btn == null){
console.error("缺少动作操作按钮:",act);
continue;
}
if(act ==ACT_state.Act_AnGang){ //因为没有暗杠的img,所以用杠的按钮,这里用bAngGang标志位表示明暗杠
this.bAnGang = true;
}
this.showBtnList.push(btn);
}
for(var key in this.btnList) {
this.btnList[key].visible = false;
}
for(var i = 0;i < this.showBtnList.length;i ++) {
this.showBtnList[i].visible = true;
this.showBtnList[i].playAnim();
}
//按钮居中显示
len = this.showBtnList.length;
var startX: number = this.panelWidth/2 - len*this.itemWidth/2;
var offsetX = 0;
for(var i=0;i<len;i++){
var child = this.showBtnList[i];
if (this.showBtnList[i-1] && this.showBtnList[i-1] == this.zhongtuBtn ) {
offsetX += 80;
}
child.x = startX + this.itemWidth*i + offsetX;
}
}
public show() {
this.visible = true;
}
public hide(){
for(var key in this.btnList){
this.btnList[key].stopAnim();
}
this.visible = false;
}
}
|
62b2a31d3e7cb68b9bb7fcdbb1a741527471dac1 | TypeScript | HenrikThoroe/swc-common-client | /performance_tests/src/base64.ts | 3.328125 | 3 | const base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("")
function encodeBase64(x: number): string {
let result = ""
const blockLength = 6
const bitsToShift = 32 - blockLength
while (x > 0) {
const y = x << bitsToShift >>> bitsToShift // Read block
x = x >>> blockLength // Remove block from number
result = base64Alphabet[y] + result // look up the associated character for block
}
return result
}
export default function testBase64() {
const output: string[] = []
for (let i = 0; i < 1000000; ++i) {
const encoded = encodeBase64(i)
for (const o of output) {
if (o === encoded) {
console.warn("collision")
break
}
}
output.push(encoded)
}
} |
78f5bfc73d991a95dc28cfffca76b675a5dca5a8 | TypeScript | bsdelf/barebone-js | /src/migrations/templates/model.ts | 2.53125 | 3 | import { Sequelize, Table, Index, Column, Model, DataType } from 'sequelize-typescript';
@Table({
freezeTableName: true,
underscored: false,
timestamps: false,
tableName: 'template_model',
})
export class TemplateModel extends Model<TemplateModel> {
@Column({
type: DataType.BIGINT,
autoIncrement: true,
primaryKey: true,
})
id!: number;
@Index
@Column({
type: DataType.STRING(32),
allowNull: false,
defaultValue: '',
unique: false,
})
name!: string;
@Column({
type: DataType.BIGINT,
allowNull: false,
defaultValue: 0,
})
createdAt!: number;
@Column({
type: DataType.BIGINT,
allowNull: true,
})
deletedAt!: number;
}
const models = [TemplateModel];
const up = async (sequelize: Sequelize) => {
sequelize.addModels(models);
for (const model of models) {
await model.sync();
}
};
const down = async (sequelize: Sequelize) => {
sequelize.addModels(models);
for (const model of models) {
await model.drop();
}
};
export { up, down };
|
fb3fd0f3c5cfebe5e41a17a9236b9a9a8eab3c95 | TypeScript | davehenton/beefindr | /src/app/common/models/beekeeper.model.ts | 2.953125 | 3 | import {LocationBasedModel, SerializedLocationBaseModel} from './location-based.model';
export interface SerializedBeeKeeper extends SerializedLocationBaseModel {
email?: string;
messagingID?: string;
firstname?: string;
}
export class BeeKeeper extends LocationBasedModel {
private messagingID = '';
public email = '';
public firstname = '';
public surname = '';
public streetname = '';
public streetnr = '';
public postcode = '';
public place = '';
public country = '';
public userUid = '';
/**
* Constructor. Due to the order in which super/subclasses are initialized
* we have to call ``inflate`` explicitly for this subclass in order
* to have all fields of the subclass properly initialized.
* (see http://joelleach.net/2016/11/18/setting-subclass-properties-in-typescript/ for further details)
*
* @param data Serialized data to be used for instance inflation
*/
public constructor(data: SerializedBeeKeeper ) {
super(data);
this.inflate(data);
}
public getEmail(): string {
return this.email;
}
public getMessagingID(): string {
return this.messagingID;
}
public setMessagingID(id: string) {
this.messagingID = id || this.messagingID;
}
}
|
0a749fdceb88e4333fffaa07858eaac1c5f25106 | TypeScript | peterm94/lagom | /src/Common/Camera.ts | 3.171875 | 3 | import * as PIXI from "pixi.js";
import {Scene} from "../ECS/Scene";
import {MathUtil} from "./Util";
/**
* Camera class for interacting with the viewport.
*/
export class Camera
{
angle = 0;
readonly scene: Scene;
readonly width: number;
readonly height: number;
readonly halfWidth: number;
readonly halfHeight: number;
/**
* Parent scene for this camera.
* @param scene The scene to register for this camera.
*/
constructor(scene: Scene)
{
this.scene = scene;
this.width = scene.game.renderer.screen.width;
this.height = scene.game.renderer.screen.height;
this.halfHeight = this.height / 2;
this.halfWidth = this.width / 2;
}
/**
* Translate a view position to a world position.
* @param x The x position on the view.
* @param y The y position on the view.
*/
viewToWorld(x: number, y: number): PIXI.Point
{
const point = new PIXI.Point();
this.scene.getGame().manager.mapPositionToPoint(point, x, y);
point.x -= this.scene.sceneNode.position.x;
point.y -= this.scene.sceneNode.position.y;
return point;
}
/**
* Position of the camera in the world.
* @returns A Point for the position of the camera.
*/
position(): PIXI.Point
{
return new PIXI.Point(-this.scene.sceneNode.position.x, -this.scene.sceneNode.position.y);
}
/**
* Move the camera to a specific location.
* @param x X point to move to.
* @param y Y point to move to.
* @param offsetX Offset X amount.
* @param offsetY Offset Y amount.
*/
move(x: number, y: number, offsetX = 0, offsetY = 0): void
{
// Move the scene the change amount
this.scene.sceneNode.position.x = -x + offsetX;
this.scene.sceneNode.position.y = -y + offsetY;
}
/**
* Move the camera towards a specific location.
* @param x X point to move to.
* @param y Y point to move to.
* @param lerpAmt The liner interpolation percentage to move.
*/
moveTowards(x: number, y: number, lerpAmt = 0.5): void
{
const xdist = x + this.scene.sceneNode.position.x;
const ydist = y + this.scene.sceneNode.position.y;
this.translate(MathUtil.lerp(0, xdist, lerpAmt),
MathUtil.lerp(0, ydist, lerpAmt));
}
/**
* Translate the camera position.
* @param x X amount to move the camera.
* @param y Y amount to move the camera.
*/
translate(x: number, y: number): void
{
// Move the scene the change amount
this.scene.sceneNode.position.x -= x;
this.scene.sceneNode.position.y -= y;
}
/**
* Rotate the viewport. The rotation will be applied from the top left corner.
* @param angle Angle in degrees to set the rotation to.
*/
rotate(angle: number): void
{
this.scene.sceneNode.angle = angle;
this.angle = angle;
}
rotate2(angle: number): void
{
const rads = MathUtil.degToRad(angle);
// Translate to top left corner (origin)
const transX = -this.halfWidth;
const transY = -this.halfWidth;
// Rotate
this.scene.sceneNode.angle += angle;
this.scene.sceneNode.position.x += transX * Math.cos(rads) - transY * Math.sin(rads) + this.halfWidth;
this.scene.sceneNode.position.y += transX * Math.sin(rads) + transY * Math.cos(rads) + this.halfHeight;
// Move it back.
// this.scene.sceneNode.position.x += this.halfWidth;
// this.scene.sceneNode.position.y += this.halfHeight;
}
/**
* Rotate the viewport around a specific point.
* @param angle The angle in degrees to set the rotation to.
* @param offsetX The X offset from the top left corner.
* @param offsetY The Y offset from the top left corner.
*/
rotateAround(angle: number, offsetX = 0, offsetY = 0): void
{
// TODO this does not work if the camera moves at all.
this.scene.sceneNode.pivot.set(offsetX, offsetY);
this.scene.sceneNode.angle = angle;
this.angle = this.scene.sceneNode.angle;
this.scene.sceneNode.position.x = offsetX;
this.scene.sceneNode.position.y = offsetY;
}
} |
aad0e7b3dbb06457e94512cbec480ce92a53b49d | TypeScript | k3ntako/split-it | /test/tables/UserTable.spec.ts | 2.671875 | 3 | import { expect } from 'chai';
import { userTable } from '../../src/tables';
import PG_Interface from '../../src/PG_Interface';
describe('UserTable model', () => {
const pgInterface = new PG_Interface();
before(async () => {
await pgInterface.query('DELETE FROM transaction_users;');
await pgInterface.query('DELETE FROM transactions;');
await pgInterface.query('DELETE FROM users;');
});
after(async () => {
await pgInterface.query('DELETE FROM transaction_users;');
await pgInterface.query('DELETE FROM transactions;');
await pgInterface.query('DELETE FROM users;');
await pgInterface.end();
});
describe('create', () => {
it('should create a user and save name as Title Case', async () => {
await userTable.create('User table model 1');
const user = await userTable.findByName('User Table Model 1');
if (user) {
expect(user.first_name).to.equal('User Table Model 1');
} else {
expect.fail('Expected user to exist');
}
});
it('should throw error given a blank name', async () => {
try {
await userTable.create('');
expect.fail('Expected UserTable.create to throw error');
} catch (error) {
expect(error.message).to.equal('Name cannot be blank');
}
});
it('should throw error given a name already exists in db', async () => {
await userTable.create('UserModelCreate2');
try {
await userTable.create('Usermodelcreate2');
expect.fail('Expected UserTable.create to throw error');
} catch (error) {
expect(error.message).to.equal('The name, Usermodelcreate2, is already taken.');
}
});
});
describe('findByName', () => {
it('should find user by name', async () => {
const user = await userTable.findByName('Usermodelcreate2');
expect(user).to.have.all.keys(['id', 'first_name']);
if (user) {
expect(user.id).to.be.a('number');
expect(user.first_name).to.equal('Usermodelcreate2');
} else {
expect.fail('Expected user to exist');
}
});
});
describe('getAll', () => {
it('should find all users', async () => {
const users = await userTable.getAll();
expect(users).to.have.lengthOf(2);
expect(users[0]).to.have.all.keys(['id', 'first_name']);
});
});
});
|
72803741bd39cbe337bf1f6c17a05480bd472010 | TypeScript | ypanshin/financial-independence | /assets/components/investment-guide/dist/types/components/calculators/investment-guide/mortgage-form/model/mortgage-form-value.d.ts | 2.546875 | 3 | import { IMortgageValue } from "../../model/mortgage-value";
export interface IMortgageFormValue extends IMortgageValue {
/**
* The mortgage rate.
*/
mortgageRate?: number;
/**
* The mortgage rate.
*/
mortgageBalance?: number;
/**
* The mortgage amortization in years.
*/
mortgageAmortization?: number;
/**
* The flag enables mortgage account.
*/
mortgage?: boolean;
}
export declare enum MortgageFormValueKey {
mortgageRate = "mortgageRate",
mortgageBalance = "mortgageBalance",
mortgageAmortization = "mortgageAmortization",
mortgage = "mortgage"
}
|
14eaaea2677360c4419a55259ee5a49b837e63a9 | TypeScript | tomvin/blade | /src/app/modules/core/services/menu-item/menu-item.model.ts | 2.65625 | 3 | export interface MenuItemCategoryVM {
id: number;
categoryLabel: string; // The category of the menu items inside this menu
fontAwesomeIconName: string; // The font awesome icon name to use for the menu item
menuItems: MenuItemVM[]; // Child menu items (if there are any)
defaultMenuItemIdToNavigateTo: number; // When the category is clicked, will navigate to the specified child id's route on click
}
export interface MenuItemVM {
id: number;
label: string; // Menu text the user can see
route: string; // The route to navigate to
fontAwesomeIconName: string; // The font awesome icon name to use for the menu item
} |
3b4020544ccd8370304431e77bfbf6b2a606db73 | TypeScript | barthap/TheDiary | /Frontend/client/src/actions/photo.actions.ts | 2.734375 | 3 | import {ActionCreator, Action} from "redux";
import {IPhoto} from "../helpers/types";
import {
ADD_PHOTO,
ADD_PHOTO_STATUS, DELETE_PHOTO, DELETE_PHOTO_STATUS,
FETCH_PHOTOS,
FETCH_PHOTOS_STATUS,
photoConstants, UPDATE_PHOTO, UPDATE_PHOTO_STATUS
} from "../consts/photo.constants";
import {IPageConfig} from "../helpers/pagination";
export interface FetchPhotosAction extends Action {
type: FETCH_PHOTOS;
payload?: IPageConfig;
}
export interface FetchPhotosStatus extends Action {
type: FETCH_PHOTOS_STATUS;
payload?: IPhoto[];
}
export interface AddPhotoAction extends Action {
type: ADD_PHOTO;
payload: {
file: File,
title: string
};
}
export interface AddPhotoStatus extends Action {
type: ADD_PHOTO_STATUS;
}
export interface UpdatePhotoAction extends Action {
type: UPDATE_PHOTO;
payload: IPhoto;
}
export interface UpdatePhotoStatus extends Action {
type: UPDATE_PHOTO_STATUS,
payload?: IPhoto;
}
type Id = number;
export interface DeletePhotoAction extends Action {
type:DELETE_PHOTO,
payload: Id;
}
export interface DeletePhotoStatus extends Action {
type: DELETE_PHOTO_STATUS,
payload?: Id;
}
const fetchPhotos: ActionCreator<FetchPhotosAction> = (pageable: IPageConfig = null) => ({
type: photoConstants.FETCH_PHOTOS,
payload: pageable
});
const fetchSuccess: ActionCreator<FetchPhotosStatus> = (items: IPhoto[]) => ({
type: photoConstants.FETCH_PHOTOS_SUCCESS,
payload: items
});
const fetchFailure: ActionCreator<FetchPhotosStatus> = () => ({type: photoConstants.FETCH_PHOTOS_FAILURE});
const fetchPending: ActionCreator<FetchPhotosStatus> = () => ({ type: photoConstants.FETCH_PHOTOS_PENDING });
const addPhoto: ActionCreator<AddPhotoAction> = (file: File, title: string) => ({
type: photoConstants.ADD_PHOTO,
payload: { file, title }
});
const addPhotoSuccess: ActionCreator<AddPhotoStatus> = () => ({type: photoConstants.ADD_PHOTO_SUCCESS});
const addPhotoFailure: ActionCreator<AddPhotoStatus> = () => ({type: photoConstants.ADD_PHOTO_FAILURE});
const addPhotoPending: ActionCreator<AddPhotoStatus> = () => ({type: photoConstants.ADD_PHOTO_PENDING});
const updatePhoto: ActionCreator<UpdatePhotoAction> = (photo: IPhoto) => ({
type: photoConstants.UPDATE_PHOTO,
payload: photo
});
const updatePhotoSuccess: ActionCreator<UpdatePhotoStatus> = (photo: IPhoto) => ({
type: photoConstants.UPDATE_PHOTO_SUCCESS,
payload: photo
});
const updatePhotoFailure: ActionCreator<UpdatePhotoStatus> = () => ({type: photoConstants.UPDATE_PHOTO_FAILURE});
const updatePhotoPending: ActionCreator<UpdatePhotoStatus> = () => ({type: photoConstants.UPDATE_PHOTO_PENDING});
const deletePhoto: ActionCreator<DeletePhotoAction> = (payload: Id) => ({
type: photoConstants.DELETE_PHOTO,
payload
});
const deletePhotoSuccess: ActionCreator<DeletePhotoStatus> = (payload: Id) => ({
type: photoConstants.DELETE_PHOTO_SUCCESS,
payload
});
const deletePhotoFailure: ActionCreator<DeletePhotoStatus> = () => ({type: photoConstants.DELETE_PHOTO_FAILURE});
const deletePhotoPending: ActionCreator<DeletePhotoStatus> = () => ({type: photoConstants.DELETE_PHOTO_PENDING});
export const photoActions = {
fetchPhotos, //fetch page of people from server
fetchPending,
fetchSuccess,
fetchFailure,
addPhoto, //adds photo and saves on server
addPhotoSuccess,
addPhotoFailure,
addPhotoPending,
updatePhoto,
updatePhotoSuccess,
updatePhotoFailure,
updatePhotoPending,
deletePhoto,
deletePhotoSuccess,
deletePhotoFailure,
deletePhotoPending
}; |
6550c41ef89dddee30897d3e75ad4008a621dea4 | TypeScript | nicholasking900816/javascript-ast-walk | /src/lib/javascript-ast-parser/statements/ClassDeclarationStatement.ts | 2.59375 | 3 | import { FunDeclarationStatement } from "./FunDeclarationStatement";
import { IdentifierLiteratureStatement } from "./IdentifierLiteratureStatement";
import { Statement } from "./Statement"
export class ClassDeclarationStatement extends Statement {
type = 'ClassDeclarationStatement';
extend: IdentifierLiteratureStatement;
className: IdentifierLiteratureStatement;
methods: FunDeclarationStatement[] = [];
constructor(currentToken: any) {
super();
this.loc.start = currentToken.loc.start;
}
} |
6128f9dd4082693c10523ce053219899250fae2e | TypeScript | NateRobinson/AndroidUI4Web | /src/androidui/image/NetImage.ts | 2.765625 | 3 | /**
* Created by linfaxin on 15/12/11.
*/
module androidui.image{
export class NetImage {
private platformImage;
private mSrc:string;
private mImageWidth=0;
private mImageHeight=0;
private mOnLoads = new Set<()=>void>();
private mOnErrors = new Set<()=>void>();
private mOverrideImageRatio:number;
constructor(src:string, overrideImageRatio?:number) {
this.init(src);
this.mOverrideImageRatio = overrideImageRatio;
}
protected init(src:string){
this.createImage();
this.src = src;
}
protected createImage(){
this.platformImage = new Image();
}
protected loadImage(){
this.platformImage.src = this.mSrc;
this.platformImage.onload = ()=>{
this.mImageWidth = this.platformImage.width;
this.mImageHeight = this.platformImage.height;
this.fireOnLoad();
};
this.platformImage.onerror = ()=>{
this.mImageWidth = this.mImageHeight = 0;
this.fireOnError();
};
}
public get src():string {
return this.mSrc;
}
public set src(value:string) {
value = convertToAbsUrl(value);
if(value!==this.mSrc){
this.mSrc = value;
this.loadImage();
}
}
public get width():number {
return this.mImageWidth;
}
public get height():number {
return this.mImageHeight;
}
getImageRatio(){
if(this.mOverrideImageRatio!=null) return this.mOverrideImageRatio;
let url = this.src;
if(!url) return 1;
if(url.startsWith('data:')) return 1;//may base64 encode
let idx = url.lastIndexOf('.'); // xxx@3x.png
if(idx>0){
url = url.substring(0, idx);
}
if(url.endsWith('@2x')) return 2;
if(url.endsWith('@3x')) return 3;
if(url.endsWith('@4x')) return 4;
if(url.endsWith('@5x')) return 5;
return 1;
}
private fireOnLoad(){
for(let load of this.mOnLoads){
load();
}
}
private fireOnError(){
for(let error of this.mOnErrors){
error();
}
}
addLoadListener(onload:()=>void, onerror?:()=>void){
if(onload){
this.mOnLoads.add(onload);
}
if(onerror){
this.mOnErrors.add(onerror);
}
}
removeLoadListener(onload?:()=>void, onerror?:()=>void){
if(onload){
this.mOnLoads.delete(onload);
}
if(onerror){
this.mOnErrors.delete(onerror);
}
}
recycle():void {
//no impl for web
}
}
let convertA = document.createElement('a');
function convertToAbsUrl(url:string){
convertA.href = url;
return convertA.href;
}
} |
b93c78f053915ce8ca829e5522d277494982e57c | TypeScript | corets/schema | /src/assertions/mixed.ts | 3.03125 | 3 | import includes from "lodash/includes"
import { LazyValue, ValidationFunctionResult } from "../types"
import { lazyValue } from "../lazyValue"
export const isDefined = (value: any) => value !== null && value !== undefined
export const mixedRequired = (
value: any,
required?: LazyValue<boolean>
): ValidationFunctionResult => {
if (lazyValue(required) === false) return
return isDefined(value)
}
export const mixedEquals = (
value: any,
equal: LazyValue<any>
): ValidationFunctionResult => {
if (!isDefined(value)) return
return value === lazyValue(equal)
}
export const mixedOneOf = (
value: any,
whitelist: LazyValue<(string | number | boolean)[]>
): ValidationFunctionResult => {
if (!isDefined(value)) return
return includes(lazyValue(whitelist), value)
}
export const mixedNoneOf = (
value: any,
blacklist: LazyValue<(string | number | boolean)[]>
): ValidationFunctionResult => {
if (!isDefined(value)) return
return !includes(lazyValue(blacklist), value)
}
////////////////////////////////////////////////////////////////////////////////
export const mixedToDefault = (
value: any,
defaultValue: LazyValue<any>
): number => {
return value === null || value === undefined ? lazyValue(defaultValue) : value
}
|
9a009a370ecf6b291d737c7f68967b941daa1313 | TypeScript | paleite/serverless-next.js | /packages/libs/core/src/route/locale.ts | 2.734375 | 3 | import { Manifest, RoutesManifest } from "../types";
export function addDefaultLocaleToPath(
path: string,
routesManifest: RoutesManifest
): string {
if (routesManifest.i18n) {
const defaultLocale = routesManifest.i18n.defaultLocale;
const locales = routesManifest.i18n.locales;
const basePath = path.startsWith(routesManifest.basePath)
? routesManifest.basePath
: "";
// If prefixed with a locale, return that path
for (const locale of locales) {
if (
path === `${basePath}/${locale}` ||
path.startsWith(`${basePath}/${locale}/`)
) {
return path;
}
}
// Otherwise, prefix with default locale
if (path === "/" || path === `${basePath}`) {
return `${basePath}/${defaultLocale}`;
} else {
return path.replace(`${basePath}/`, `${basePath}/${defaultLocale}/`);
}
}
return path;
}
export function dropLocaleFromPath(
path: string,
routesManifest: RoutesManifest
): string {
if (routesManifest.i18n) {
const locales = routesManifest.i18n.locales;
// If prefixed with a locale, return path without
for (const locale of locales) {
const prefix = `/${locale}`;
if (path === prefix) {
return "/";
}
if (path.startsWith(`${prefix}/`)) {
return `${path.slice(prefix.length)}`;
}
}
}
return path;
}
export const getAcceptLanguageLocale = async (
acceptLanguage: string,
manifest: Manifest,
routesManifest: RoutesManifest
) => {
if (routesManifest.i18n) {
const defaultLocale = routesManifest.i18n.defaultLocale;
const locales = new Set(
routesManifest.i18n.locales.map((locale) => locale.toLowerCase())
);
// Accept.language(header, locales) prefers the locales order,
// so we ask for all to find the order preferred by user.
const Accept = await import("@hapi/accept");
for (const language of Accept.languages(acceptLanguage)) {
const locale = language.toLowerCase();
if (locale === defaultLocale) {
break;
}
if (locales.has(locale)) {
return `${routesManifest.basePath}/${locale}${
manifest.trailingSlash ? "/" : ""
}`;
}
}
}
};
export function getLocalePrefixFromUri(
uri: string,
routesManifest: RoutesManifest
) {
if (routesManifest.basePath && uri.startsWith(routesManifest.basePath)) {
uri = uri.slice(routesManifest.basePath.length);
}
if (routesManifest.i18n) {
for (const locale of routesManifest.i18n.locales) {
if (uri === `/${locale}` || uri.startsWith(`/${locale}/`)) {
return `/${locale}`;
}
}
return `/${routesManifest.i18n.defaultLocale}`;
}
return "";
}
|
b1ee15f86bbb5fc8e38085015b3d54d86f7c4b4e | TypeScript | matthew-dean/less.js | /packages/core/src/functions/list.ts | 2.796875 | 3 | import {
Comment,
Dimension,
Declaration,
Expression,
Rules,
Node,
Num,
Selector,
// Element,
// Mixin,
Quoted,
WS
} from '../tree/nodes'
import { define } from './helpers'
export const _SELF = define(function (n: Node) {
return n
}, [Node])
export const extract = define(function (value: Node, index: Num) {
// (1-based index)
let i = index.value - 1
return value.toArray()[i]
}, [Node], [Num])
export const length = define(function (value: Node) {
return new Num(value.toArray().length)
}, [Node])
/**
* Creates a Less list of incremental values.
* Modeled after Lodash's range function, also exists natively in PHP
*
* @param start
* @param end - e.g. 10 or 10px - unit is added to output
* @param step
*/
export const range = define(function (start: Num | Dimension, end: Num | Dimension, step: Num) {
let from: number
let to: Node
let stepValue = 1
const list = []
if (end) {
to = end
from = start.value
if (step) {
stepValue = step.value
}
} else {
from = 1
to = start
}
let unit: string
if (to instanceof Dimension) {
unit = to.nodes[1].value
}
const listValue = unit
? (val: number) => new Dimension([val, unit])
: (val: number) => new Num(val)
for (let i = from; i <= to.value; i += stepValue) {
list.push(listValue(i))
list.push(new WS())
}
if (list.length > 1) {
list.pop()
}
return new Expression(list)
}, [Num, Dimension], [Num, Dimension], [Num])
export const each = define(function (list: Node, mixin: MixinDefinition) {
const iterator = list.toArray()
let rs: Rules
let newRules: Rules
const returnRules: Rules[] = []
let valueName = '@value'
let keyName = '@key'
let indexName = '@index'
if (mixin.params) {
valueName = mixin.params[0] && mixin.params[0].name.value
keyName = mixin.params[1] && mixin.params[1].name.value
indexName = mixin.params[2] && mixin.params[2].name.value
rs = mixin.rules
}
for (let i = 0; i < iterator.length; i++) {
let key: Node
let value: Node
const item = iterator[i]
if (item instanceof Declaration) {
key = item.name.clone()
value = item.nodes[0]
} else {
key = new Num(i + 1)
value = item
}
if (item instanceof Comment) {
continue
}
newRules = rs.clone()
if (valueName) {
newRules.appendRule(new Declaration({ name: valueName, nodes: [value] }))
}
if (indexName) {
newRules.appendRule(new Declaration({ name: indexName, nodes: [new Num(i + 1)] }))
}
if (keyName) {
newRules.appendRule(new Declaration({ name: keyName, nodes: [key] }))
}
returnRules.push(newRules)
}
return new Rules(newRules).eval(this)
}, [Node], [MixinDefinition])
|
aafcfdbfdf227f7e4c74adbd5ed1ea641482e819 | TypeScript | HediAbed/codecharta | /visualization/app/codeCharta/state/store/dynamicSettings/searchedNodePaths/searchedNodePaths.reducer.spec.ts | 2.59375 | 3 | import { searchedNodePaths } from "./searchedNodePaths.reducer"
import { SearchedNodePathsAction, setSearchedNodePaths } from "./searchedNodePaths.actions"
describe("searchedNodePaths", () => {
describe("Default State", () => {
it("should initialize the default state", () => {
const result = searchedNodePaths(undefined, {} as SearchedNodePathsAction)
expect([...result]).toEqual([])
})
})
describe("Action: SET_SEARCHED_NODE_PATHS", () => {
it("should set new searchedNodePaths", () => {
const result = searchedNodePaths(new Set(), setSearchedNodePaths(new Set(["myPath", "anotherPath"])))
expect([...result]).toEqual(["myPath", "anotherPath"])
})
it("should set new searchedNodePaths", () => {
const result = searchedNodePaths(new Set(["myPath", "anotherPath"]), setSearchedNodePaths())
expect([...result]).toEqual([])
})
})
})
|
f62221921f04b8ebe35c4147a68c0c7d84fa6b68 | TypeScript | cpannwitz/chout-web | /src/services/localStorage.service.ts | 2.53125 | 3 | import { ImmortalStorage, LocalStorageStore, IndexedDbStore } from 'immortal-db'
const stores = [IndexedDbStore, LocalStorageStore]
const db = new ImmortalStorage(stores)
export const localStorageService = {
// single ops
set: (key: string, value: string) => db.set(key, value),
get: (key: string, fallback: string = '') => db.get(key, fallback),
remove: (key: string) => db.remove(key),
// multi ops
setMany: (keyValues: { key: string; value: string }[]) =>
Promise.all(keyValues.map(item => db.set(item.key, item.value))),
getMany: (keys: string[]) => Promise.all(keys.map(item => db.get(item))),
removeMany: (keys: string[]) => Promise.all(keys.map(item => db.remove(item)))
}
|
2d30b419b15de4e03e68b7ccc9b9097fbe86f213 | TypeScript | semakov-andrey/sa-time-tracker | /src/utils/di.ts | 2.671875 | 3 | import { PureComponent } from 'react';
import { isset } from './guards';
class IoCContainer {
private instances: Map<symbol, unknown> = new Map();
public get = <T>(token: symbol): T => {
const constructor = this.instances.get(token);
if (!isset(constructor)) throw new Error('di failed');
return constructor as T;
};
public set = <T>(token: symbol, constructor: () => T): void => {
this.instances.set(token, constructor());
};
};
export const iocContainer = new IoCContainer();
export function inject(token: symbol) {
return function (target: PureComponent, propertyName: string): void {
Object.defineProperty(target, propertyName, {
configurable: true,
enumerable: true,
writable: false,
value: iocContainer.get<unknown>(token)
});
};
};
|
bf75ea7b7280f432faf81364ff22244a236ba41e | TypeScript | redplane/v-personal-cv | /src/models/user-description.ts | 2.734375 | 3 | export class UserDescription {
//#region Properties
/*
* Id of description.
* */
public id: number = 0;
/*
* User id that description belongs to.
* */
public userId: number = 0;
/*
* User description.
* */
public description: string = '';
//#endregion
} |
7a91561a010041d8048ed8305231aa395c3e6f96 | TypeScript | jberglinds/spotify-tunein-backend | /src/socket-app.ts | 2.6875 | 3 | import http from 'http'
import socketIO from 'socket.io'
import {
default as RadioController,
PlayerState,
APIRadioStation
} from './controllers/radio-controller'
enum IncomingEvent {
startBroadcast = 'start-broadcast',
endBroadcast = 'end-broadcast',
updatePlayerState = 'update-player-state',
joinBroadcast = 'join-broadcast',
leaveBroadcast = 'leave-broadcast'
}
export const configure = (server: http.Server) => {
const controller = RadioController.shared()
const radio = socketIO(server).of('/radio')
radio.on('connection', (socket) => {
console.log(`Client connected: ${socket.id}`)
const subscription = controller.addClient(socket.id)
.subscribe(event => {
socket.emit(event.type, event.payload)
})
socket.on('disconnect', (reason) => {
console.log(`Client disconnected: ${socket.id}`)
controller.removeClient(socket.id)
subscription.unsubscribe()
})
socket.on(IncomingEvent.startBroadcast, (station: APIRadioStation, ack: AckCallback) => {
const error = controller.startBroadcasting(socket.id, station)
ack(error && error.message)
})
socket.on(IncomingEvent.endBroadcast, (ack: AckCallback) => {
controller.stopBroadcasting(socket.id)
ack()
})
socket.on(IncomingEvent.joinBroadcast, (stationName: string, ack: (retval: string | PlayerState) => void) => {
const retval = controller.joinBroadcast(socket.id, stationName)
if (retval instanceof Error) {
ack(retval.message)
} else {
ack(retval)
}
})
socket.on(IncomingEvent.leaveBroadcast, (ack: AckCallback) => {
controller.leaveBroadcast(socket.id)
ack()
})
socket.on(IncomingEvent.updatePlayerState, (newState: PlayerState, ack: AckCallback) => {
const error = controller.updatePlayerState(socket.id, newState)
ack(error && error.message)
})
})
}
type AckCallback = (error?: string) => void
|
09e4e33ab815128b0d247ab5053fdcdca8435d2d | TypeScript | TeemuHe/myproject | /src/app/classes/feedback-item.ts | 2.65625 | 3 | export class FeedbackItem {
question: string;
answer: string;
answerList: string[];
constructor(question: string) {
this.question = question;
this.answer = '';
this.answerList = ['Ei arvosteltu', 'Huono', 'Kohtalainen', 'Hyvä', 'Täydellinen'];
}
}
|
3d94a06ddf9a7eb3654913449f453db94a2ab8d3 | TypeScript | zbream/project-euler-node | /src/052/index.ts | 3.546875 | 4 | export function main052() {
return findSmallestPermutedMultiple();
}
function findSmallestPermutedMultiple(): number {
for (let i = 1;; i++) {
if (isPermutedMultiple(i)) {
return i;
}
}
}
function isPermutedMultiple(num: number): boolean {
const digits = getDigits(num);
for (let multiplier = 2; multiplier <= 6; multiplier++) {
const multiplierDigits = getDigits(num * multiplier);
if (!isEqual(digits, multiplierDigits)) {
return false;
}
}
return true;
}
function getDigits(num: number): number[] {
const digits = new Array<number>(10).fill(0);
while (num > 0) {
digits[num % 10]++;
num = Math.floor(num / 10);
}
return digits;
}
function isEqual(digits1: number[], digits2: number[]): boolean {
for (let i = 0; i < 10; i++) {
if (digits1[i] !== digits2[i]) {
return false;
}
}
return true;
}
|
221815c3f7160a684c94b8baf3bec53a387ca0aa | TypeScript | vino337/Angular-MyApp | /src/app/services/customer.service.ts | 2.59375 | 3 | import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CustomerService {
private customersUrl = 'api/customers';
private contactsUrl = 'api/contacts';
private httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(
private httpClient: HttpClient
) { }
getCustomers(): Observable<Object[]> {
return this.httpClient.get<Object[]>(this.customersUrl, this.httpOptions);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`error : ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
`Backend returned code ${error.status}, ` +
`error : ${error.error}`);
}
/*
handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
*/
getCustomer(_customerNo): Observable<any> {
const reqUrl = `${this.customersUrl}/?customerNo=${_customerNo}`;
return this.httpClient.get<any>(reqUrl, this.httpOptions).pipe(
catchError(this.handleError)
);
}
updateCustomer(customer): Observable<any> {
const reqUrl = `${this.customersUrl}/?customerNo=${customer.customerNo}`;
return this.httpClient.put(reqUrl, customer, this.httpOptions).pipe(
catchError(this.handleError)
);
}
addCustomer(customer): Observable<any> {
const reqUrl = `${this.customersUrl}`;
return this.httpClient.post(reqUrl, customer, this.httpOptions).pipe(
catchError(this.handleError)
);
}
getContacts(customerNo): Observable<any> {
const reqUrl = `api/contacts/?customerNo=${customerNo}`;
return this.httpClient.get(reqUrl, this.httpOptions).pipe(
catchError(this.handleError)
);
}
updateContact(contact): Observable<any> {
const reqUrl = `${this.contactsUrl}/?id=${contact.id}`;
return this.httpClient.put(reqUrl, contact, this.httpOptions).pipe(
catchError(this.handleError)
);
}
}
|
14d8041a9b079a5f3fb12ef1a26009b2bca1a6b9 | TypeScript | terra10/codefest_serverless-awslambda | /Lab003/reference/postBeerAdvanced.ts | 2.703125 | 3 | import { APIGatewayProxyEvent, Callback, Context } from 'aws-lambda';
import * as AWS from 'aws-sdk';
import * as https from 'https';
const documentClient = new AWS.DynamoDB.DocumentClient({
httpOptions: {
agent: new https.Agent({
keepAlive: true
})
}
});
// Handler for AWS Lambda
export async function handler(event: APIGatewayProxyEvent, _context: Context, callback: Callback) {
try {
callback(undefined, await postBeerAdvanced(event));
} catch (err) {
callback(err);
}
}
// Main function logic used by handler, test and local development
export async function postBeerAdvanced(event: APIGatewayProxyEvent) {
// Let's build the headers for the response API call
const headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate'
};
try {
// Let's log whats in the API Gateway Event:
console.debug(`postBeer | event: ${JSON.stringify(event)}`);
// Get the information from the event we need like the request body and the unique request id
const eventBody = JSON.parse(event.body);
const uniqueId: string = event.requestContext.requestId;
// We are going to initiate the updateParams object here
// which we strong type to AWS.DynamoDB.DocumentClient.UpdateItemInput to get some TypeScript magic
// we define the DynamoDB Tablename + the unique key and it's new value
// the ExpressionAttributeValues is empty for know since we don't know how many elements the POST will contain
const expressionAttributeValues = {};
const updateParams: AWS.DynamoDB.DocumentClient.UpdateItemInput = {
TableName: 't10a-serverless',
Key: {
identification: uniqueId
},
ExpressionAttributeValues: expressionAttributeValues
};
// Here is the magic where we loop over all the elements in the POST message eventBody
// This key (each element) will be used to build up the expressionAttributeValues
// And will end up something like { item1: value1, item2: value2}
Object.keys(eventBody).forEach(key => expressionAttributeValues[`:${key}`] = eventBody[key]);
// Next we will loop again, yes this can be more efficiently done, to build the UpdateExpression
// This will end up something like: "set item1 = :value1,item2 = :value2"
const array = Object.keys(eventBody).map(key => {
return (`${key} = :${key}`);
});
updateParams.UpdateExpression = `set ${array.join(',')}`;
// Let's take a look at both dynamic objects which are required for the AWS.DynamoDB.DocumentClient.UpdateItemInput
console.debug('expressionAttributeValues: ' + JSON.stringify(expressionAttributeValues));
console.debug('updateParams.UpdateExpression: ' + updateParams.UpdateExpression);
// Execute the update with the documentClient using await for async (wait for response before continue)
await documentClient.update(updateParams).promise();
// All goes well so reply with a 201 http code, the headers and a response msg
return {
statusCode: 201,
headers, // we don't need to type out "headers: headers", javascript understands it's the same
body: JSON.stringify({id: uniqueId})
};
} catch (err) {
console.error(`Unexpected 500 | ${err.message}`);
return {
statusCode: 500,
headers,
body: JSON.stringify({message: err.message})
};
}
}
|
008d54abbeb0592019c395f0d1d0ed7594016dcf | TypeScript | wbalaniucCentennialCollege/COMP397_Mario | /Scripts/Core/game.ts | 2.625 | 3 | /// <reference path = "_reference.ts" />
// Global Variables
var assets: createjs.LoadQueue;
var canvas: HTMLElement;
var stage: createjs.Stage;
var spriteSheetLoader : createjs.SpriteSheetLoader;
var atlas : createjs.SpriteSheet;
var currentScene : objects.Scene;
var scene: number;
// Preload Assets required
var assetData:objects.Asset[] = [
{id: "bg", src: "../../Assets/images/allScene.png"},
{id: "floor", src: "../../Assets/images/floor.png"},
{id: "atlas", src: "../../Assets/images/Test.png"},
{id: "theme", src: "../../Assets/audio/main_theme.mp3"}
];
function preload() {
// Create a queue for assets being loaded
assets = new createjs.LoadQueue(false);
assets.installPlugin(createjs.Sound);
// Register callback function to be run when assets complete loading.
assets.on("complete", init, this);
assets.loadManifest(assetData);
}
function init() {
// Reference to canvas element
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
stage.enableMouseOver(20);
createjs.Ticker.setFPS(config.Game.FPS);
createjs.Ticker.on("tick", this.gameLoop, this);
let atlasData = {
"images": [
/*
assets.getResult("player"),
assets.getResult("block"),
assets.getResult("pipe1.png"),
assets.getResult("pipe2.png"),
assets.getResult("pipe3.png"),
assets.getResult("qBlock")
*/
assets.getResult("atlas")
],
"frames":[
[40,0,45,45,0,0,0],
[43,45,46,86,0,0,0],
[43.131,39,86,0,0,0],
[0,131,43,86,0,0,0],
[0,217,87,87,0,0,0],
[0,304,87,130,0,0,0],
[0,434,93,175,0,0,0],
[0,45,43,86,0,0,0],
[0,0,40,45,0,0,0]
],
"animations":{
"run" : { "frames" : [1, 3] , speed : 0.5},
"player" : { "frames" : [7] },
"block" : { "frames" : [0] },
"qBlock" : { "frames" : [8]},
"pipe1" : { "frames" : [4] },
"pipe2" : { "frames" : [5] },
"pipe3" : { "frames" : [6] }
},
}
atlas = new createjs.SpriteSheet(atlasData);
scene = config.Scene.GAME;
changeScene();
}
function gameLoop(event: createjs.Event): void {
// Update whatever scene is currently active.
currentScene.update();
stage.update();
}
function changeScene() : void {
// Simple state machine pattern to define scene swapping.
switch(scene)
{
case config.Scene.MENU :
stage.removeAllChildren();
currentScene = new scenes.Menu();;
console.log("Starting MENU scene");
break;
case config.Scene.GAME :
stage.removeAllChildren();
currentScene = new scenes.Play();
console.log("Starting PLAY scene");
break;
}
} |
c2e89b6b82b239e06c28bde68f31a33be00e369b | TypeScript | bostalowski/poc-game | /src/controller.ts | 3.09375 | 3 | const ButtonInput = function () {
let isButtonInputActive = false
let isButtonInputDown = false
return {
setInput: (isDown: boolean) => {
if (isButtonInputDown !== isDown) {
isButtonInputActive = isDown
}
isButtonInputDown = isDown
},
isActive: () => isButtonInputActive
}
}
const Controller = function () {
const downButton = ButtonInput()
const leftButton = ButtonInput()
const rightButton = ButtonInput()
const upButton = ButtonInput()
const spaceButton = ButtonInput()
const keyDownUp = (type: string, code: string) => {
const isDown = type === 'keydown'
switch (code) {
case 'ArrowLeft':
leftButton.setInput(isDown)
break
case 'ArrowUp':
upButton.setInput(isDown)
break
case 'ArrowRight':
rightButton.setInput(isDown)
break
case 'ArrowDown':
downButton.setInput(isDown)
break
case 'Space':
spaceButton.setInput(isDown)
break
}
}
return {
keyDownUp,
getLeftButton: () => ({ isActive: leftButton.isActive }),
getRightButton: () => ({ isActive: rightButton.isActive }),
getUpButton: () => ({ isActive: upButton.isActive }),
getDownButton: () => ({ isActive: downButton.isActive }),
getSpaceButton: () => ({ isActive: spaceButton.isActive })
}
}
export default Controller
|
e6d6c3b121f8bdc13f9e33b5b84ad8759fa1c9d3 | TypeScript | milton-reyes/dwelling-kitchen-Inventory | /src/model/FoodStorage.ts | 2.8125 | 3 | export class FoodStorage {
storagesId: number;
upcFood: string;
quantity: number;
datePurchased: Date;
shelfLife: string;
constructor(
storagesId: number,
upcFood: string,
quantity: number,
datePurchased: Date,
shelfLife: string) {
this.storagesId = storagesId;
this.upcFood = upcFood;
this.quantity = quantity;
this.datePurchased = datePurchased;
this.shelfLife = shelfLife;
}
static from(obj:FoodStorageRow): FoodStorage {
const foodStorage = new FoodStorage(
obj.storagesId,
obj.upcFood,
obj.quantity,
obj.datePurchased,
obj.shelfLife
);
return foodStorage;
}
}
export interface FoodStorageRow {
storagesId: number;
upcFood: string;
quantity: number;
datePurchased: Date;
shelfLife: string;
} |
68bd9d1f917014c914052ce05ffcbbf265b5480a | TypeScript | multitoken/calculator | /src/manager/analytics/AnalyticsManagerImpl.ts | 2.625 | 3 | import * as Sentry from '@sentry/browser';
import { AnalyticsManager } from './AnalyticsManager';
import { BasicAnalytics } from './BasicAnalytics';
export class AnalyticsManagerImpl implements AnalyticsManager {
private analytics: BasicAnalytics[] = [];
constructor(analytics: BasicAnalytics[]) {
this.analytics = analytics;
}
public trackPage(pageName: string): void {
this.callMethod('trackPage', pageName);
}
public trackEvent(category: string, action: string, label: string): void {
this.callMethod('trackEvent', category, action, label);
}
public trackException(error: Error): void {
Sentry.captureException(error);
}
private callMethod(method: string, ...args: any[]): void {
this.analytics.forEach(item => {
if (typeof item[method] === 'function') {
item[method].apply(item, args);
}
});
}
}
|
71c499db232abf44da451268eff697737249d1a1 | TypeScript | jvanmelckebeke/pacman-electron | /scripts/tools.ts | 3.46875 | 3 | export class XY {
constructor(x: number, y: number) {
this._x = x;
this._y = y;
}
private _x: number;
get x(): number {
return this._x;
}
set x(value: number) {
this._x = value;
}
private _y: number;
get y(): number {
return this._y;
}
set y(value: number) {
this._y = value;
}
is(o: XY) {
return (this.x == o.x && this.y == o.y);
}
toString() {
return `XY(${this.x}, ${this.y})`;
}
add(dxdy: XY) {
this.x += dxdy.x;
this.y += dxdy.y;
return this;
}
addNumbers(x, y) {
return this.add(new XY(x, y));
}
multiply(m1: number, m2?: number) {
this.x *= m1;
this.y *= m2 | m1;
return this;
}
tAdd(dirPred: XY) {
return new XY(dirPred.x + this.x, dirPred.y + this.y);
}
isXY(t: XYT) {
return (this.x === t.x && this.y === t.y)
}
}
export class XYT extends XY {
constructor(x: number, y: number, t: number) {
super(x, y);
this.value = t;
}
private _value: number;
get value(): number {
return this._value;
}
set value(value: number) {
this._value = value;
}
add(dxdy: XYT) {
this.x += dxdy.x;
this.y += dxdy.y;
return this;
}
addNumbers(x, y) {
return this.add(new XYT(x, y, 0));
}
is(o: XYT): boolean {
return (o.y === this.y && o.x === this.x && o.value === this.value);
}
toString(): string {
return `XYT(${this.x}, ${this.y}, ${this.value})`;
}
}
export function getDirectionArray() {
return [new XY(0, -1), new XY(0, 1), new XY(-1, 0), new XY(1, 0)];
} |
b4e16c6fb9ba4e6df57c870a4c6e19dfcd83f205 | TypeScript | makoscafee/map-api | /src/lib/layers/thematic.ts | 2.546875 | 3 | import { LayerOptions } from '../models/layer-options.model';
import { getLabelsLayer, getLablesSource } from '../utils/labels.util';
import Layer from './index';
const borderColor = '#333';
const borderWeight = 1;
const hoverBorderWeight = 3;
class Thematic extends Layer {
constructor(options: LayerOptions) {
super(options);
const { data } = options;
this.setFeatures(data);
this.createSource();
this.createLayers();
}
public createSource(): void {
const id = this.getId();
const features = this.getFeatures();
const { label } = this.options;
this.setSource(id, { type: 'geojson', data: features });
if (label) {
this.setSource(`${id}-labels`, getLablesSource(features));
}
}
public createLayers(): void {
const id = this.getId();
const { label, labelStyle } = this.options;
// Polygon layer
this.addLayer(
{
filter: ['==', '$type', 'Polygon'],
id: `${id}`,
paint: {
'fill-color': ['get', 'color'],
'fill-outline-color': borderColor
},
source: id,
type: 'fill'
},
true
);
// Point layer
this.addLayer(
{
filter: ['==', '$type', 'Point'],
id: `${id}-point`,
paint: {
'circle-color': ['get', 'color'],
'circle-radius': ['get', 'radius'],
'circle-stroke-color': borderColor,
'circle-stroke-width': borderWeight
},
source: id,
type: 'circle'
},
true
);
// Polygon hover state
this.addLayer(
{
filter: ['==', '$type', 'Polygon'],
id: `${id}-hover`,
paint: {
'line-color': borderColor,
'line-width': [
'case',
['boolean', ['feature-state', 'hover'], false],
hoverBorderWeight,
borderWeight
]
},
source: id,
type: 'line'
},
false
);
// Point hover state
this.addLayer(
{
filter: ['==', '$type', 'Point'],
id: `${id}-point-hover`,
paint: {
'circle-opacity': 0,
'circle-radius': ['get', 'radius'],
'circle-stroke-color': borderColor,
'circle-stroke-width': [
'case',
['boolean', ['feature-state', 'hover'], false],
hoverBorderWeight,
borderWeight
]
},
source: id,
type: 'circle'
},
false
);
if (label) {
this.addLayer(getLabelsLayer(id, label, labelStyle), false);
}
}
public setOpacity(opacity: number): void {
if (this.isOnMap()) {
const mapgl = this.getMapGl();
const id = this.getId();
const { label } = this.options;
mapgl.setPaintProperty(id, 'fill-opacity', opacity);
if (label) {
mapgl.setPaintProperty(`${id}-labels`, 'text-opacity', opacity);
}
}
}
}
export default Thematic;
|