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
|
|---|---|---|---|---|---|---|
c8ab83bf72075693c3edf3374fae4f5b0333d5de
|
TypeScript
|
AdrianSalvador21/ionic-tracking-expense
|
/src/app/core/reducers/auth.reducer.ts
| 2.734375
| 3
|
import * as fromAuth from '../actions/auth.actions';
export interface AuthState {
userData: any;
}
const initialStatus: AuthState = {
userData: {}
};
export function userReducer( state = initialStatus, action: fromAuth.actions ): any {
switch ( action.type ) {
case fromAuth.SET_USER:
return {
...state,
userData: {...state.userData, ...action.userData}
};
default:
return state;
}
}
|
2ebfdab56b7ee845e48e135258eed2b22b3f7688
|
TypeScript
|
painterner/react-starter
|
/src/common/helper.ts
| 2.609375
| 3
|
export function delayPromise(data: any, time: number) {
return new Promise(res => {
setTimeout(() => {
res(data)
}, time);
})
}
|
c5b471313adedecc2c8c3086cad473a2bfc00a45
|
TypeScript
|
repetere/promisie
|
/src/index.ts
| 2.90625
| 3
|
import utilities from './utilities';
import { SettleValues } from './utilities/settle';
export interface PromisifyAllOptions {
recursive?: boolean;
readonly?: boolean;
}
export interface ParallelOptions {
recursive?: boolean;
concurrency?: number;
}
export interface RetryOptions {
times?: number;
timeout?: number;
}
export interface PromisifyAllObjectParam {
[key: string]: ((...args: any[]) => void) | any
}
function isNestedPromisifyAllObjectParam(v: any): v is PromisifyAllObjectParam {
return v && typeof v === 'object';
}
export interface PromisifyAllObjectResult {
[key: string]: (<T>(...args: any[]) => Promisie<T>) | any
}
function setHandlers(success: (arg: any) => any, failure: any) {
return {
success,
failure: (typeof failure === 'function') ? failure : undefined
};
};
export default class Promisie<T = any> extends Promise<T> {
[key: string]: Function;
constructor(callback: (
resolve: (value?: T | PromiseLike<T>) => void,
reject: (value?: T | PromiseLike<T>) => void,
) => void) {
super(callback);
}
then<TSuccess = T, TFailure = any>(
onfulfilled?: ((value: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined,
): Promisie<TSuccess> {
return super.then(onfulfilled, onrejected) as Promisie<TSuccess>
}
try<TSuccess = T, TFailure = any>(
onfulfilled?: ((value: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined,
): Promisie<TSuccess> {
const { success, failure } = setHandlers(function (data) {
try {
return (typeof onfulfilled === 'function')
? onfulfilled(data)
: Promisie.reject(new TypeError('ERROR: try expects onSuccess handler to be a function'));
}
catch (e) {
return Promisie.reject(e);
}
}, onrejected);
return this.then(success, failure) as Promisie<TSuccess>;
}
spread<TSuccess = T, TFailure = any>(
onfulfilled?: ((...args: T[]) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined,
): Promisie<TSuccess> {
const { success, failure } = setHandlers(function (data) {
if (typeof data[Symbol.iterator] !== 'function') {
return Promisie.reject(new TypeError('ERROR: spread expects input to be iterable'));
}
if (typeof onfulfilled !== 'function') {
return Promisie.reject(new TypeError('ERROR: spread expects onSuccess handler to be a function'));
}
return onfulfilled(...data);
}, onrejected);
return this.then(success, failure) as Promisie<TSuccess>;
}
map<TSuccess = T, TFailure = any>(
onfulfilled?: ((datas: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined | number,
concurrency?: number,
): Promisie<TSuccess[]> {
if (typeof onrejected === 'number') {
concurrency = onrejected;
onrejected = undefined;
}
const { success, failure } = setHandlers(function (data) {
if (!Array.isArray(data)) {
return Promisie.reject(new TypeError('ERROR: map expects input to be an array'));
}
if (typeof onfulfilled !== 'function') {
return Promisie.reject(new TypeError('ERROR: map expects onSuccess handler to be a function'));
}
return Promisie.map<TSuccess>(data, concurrency, onfulfilled);
}, onrejected);
return this.then(success, failure) as Promisie<TSuccess[]>;
}
each<TSuccess = T, TFailure = any>(
onfulfilled?: ((datas: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined | number,
concurrency?: number,
): Promisie<TSuccess[]> {
if (typeof onrejected === 'number') {
concurrency = onrejected;
onrejected = undefined;
}
const { success, failure } = setHandlers(function (data) {
if (!Array.isArray(data)) {
return Promisie.reject(new TypeError('ERROR: each expects input to be an array'));
}
if (typeof onfulfilled !== 'function') {
return Promisie.reject(new TypeError('ERROR: each expects onSuccess handler to be a function'));
}
return Promisie.each<TSuccess>(data, concurrency, onfulfilled);
}, onrejected);
return this.then(success, failure) as Promisie<TSuccess[]>;
}
settle<TSuccess = T, TFailure = any>(
onfulfilled?: ((datas: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined,
): Promisie<SettleValues<TSuccess>> {
const { success, failure } = setHandlers(function (data) {
if (!Array.isArray(data)) {
return Promisie.reject(new TypeError('ERROR: settle expects input to be an array'));
}
if (typeof onfulfilled !== 'function') {
return Promisie.reject(new TypeError('ERROR: settle expects onSuccess handler to be a function'));
}
const operations = data.map(d => () => onfulfilled(d));
return Promisie.settle<TSuccess>(operations);
}, onrejected);
return this.then(success, failure) as Promisie<SettleValues<TSuccess>>;
}
retry<TSuccess = T, TFailure = any>(
onfulfilled?: ((args: T) => any) | null | undefined,
onrejected?: ((reason: any) => TFailure | PromiseLike<TFailure>) | null | undefined | RetryOptions,
options?: RetryOptions,
): Promisie<TSuccess> {
if (onrejected && typeof onrejected === 'object') {
options = onrejected;
onrejected = undefined;
}
const { success, failure } = setHandlers(function (data) {
if (typeof onfulfilled !== 'function') return Promisie.reject(new TypeError('ERROR: retry expects onSuccess handler to be a function'));
return Promisie.retry<TSuccess>(() => {
return onfulfilled(data);
}, options);
}, onrejected);
return this.then(success, failure) as Promisie<TSuccess>;
}
finally<TSuccess = T>(onfulfilled?: (() => any) | null | undefined): Promisie<TSuccess> {
const _handler = () => (typeof onfulfilled === 'function')
? onfulfilled()
: Promisie.reject(new TypeError('ERROR: finally expects handler to be a function'));
return this.then(_handler, _handler) as Promisie<TSuccess>;
}
static promisify(
fn: (...args: any[]) => void,
_this?: any
): <T = any>(...args: any[]) => Promisie<T> {
const promisified = function<T>(this: any, ...args: any[]): Promisie<T> {
return new Promisie((resolve, reject) => {
args.push(function(err: any, data: any) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
fn.apply(this, args);
});
}
if (_this) {
return promisified.bind(_this);
}
return promisified;
}
static promisifyAll(
mod: PromisifyAllObjectParam,
_this?: any,
options?: PromisifyAllOptions,
): PromisifyAllObjectResult {
const withDefaultOptions = Object.assign({
readonly: true,
recursive: false,
}, options);
let input: PromisifyAllObjectParam = Object.create(mod);
if (!withDefaultOptions.readonly) {
input = Object.assign(input, mod) as PromisifyAllObjectParam;
} else {
input = utilities.safeAssign(mod) as PromisifyAllObjectParam;
}
const promisified: PromisifyAllObjectResult = {};
Object.keys(input).forEach((key: string): void => {
if (typeof input[key] === 'function') {
promisified[`${key}Async`] = (_this)
? this.promisify(input[key], _this)
: this.promisify(input[key]);
} else if (withDefaultOptions.recursive) {
const v = input[key];
if (isNestedPromisifyAllObjectParam(v)) {
promisified[key] = this.promisifyAll(
v,
_this,
withDefaultOptions,
);
}
}
});
return promisified;
}
static series<T = any>(fns: Array<((state: any) => any) | any[]>): Promisie<T> {
return Promisie.iterate<T>(utilities.series(fns), null);
}
static pipe<T = any>(fns: Array<(...args: any[]) => any>): (...args: any[]) => Promisie<T> {
return function(...args: any[]): Promisie<T> {
const operations = Object.assign([], fns) as Array<(...args: any[]) => any>;
const first = operations[0];
operations[0] = function(): any {
return first(...args);
}
return Promisie.series<T>(operations);
}
}
static compose<T = any>(fns: Array<(...args: any[]) => any>): (...args: any[]) => Promisie<T> {
return Promisie.pipe<T>(fns.reverse());
}
static map<T = any>(datas: any[], concurrency: any, fn?: (arg: any) => any): Promisie<Array<T>> {
const method = (typeof concurrency === 'function')
? concurrency
: fn;
if (typeof concurrency !== 'number') {
concurrency = 1;
}
return Promisie.promisify(utilities.map)<Array<T>>(method, datas, concurrency);
}
static each<T = any>(datas: T[], concurrency: any, fn?: (arg: any) => any): Promisie<Array<T>> {
return Promisie
.map<T>(datas, concurrency, fn)
.then(() => datas) as Promisie<Array<T>>;
}
static parallel<T = any>(fns: { [key: string]: any }, args?: any, options: ParallelOptions = {}): Promisie<{ [key: string]: any }> {
const { recursive = false, concurrency } = options;
if (recursive) {
fns = utilities.handleRecursiveParallel<T>(fns);
}
return Promisie.promisify(utilities.parallel)<T>(fns, args, concurrency);
}
static settle<T = any>(fns: any[], concurrency?: number): Promisie<SettleValues> {
return Promisie.promisify(utilities.settle)<SettleValues<T>>(fns, concurrency);
}
static iterate<T = any>(generator: (arg?: any) => Generator, initial: any): Promisie<T> {
const iterator = utilities.iterator(generator(initial));
return Promisie.promisify(iterator)<T>(initial);
}
static doWhilst<T = any>(fn: () => T | Promise<T>, evaluate: (arg: T) => boolean): Promisie<T> {
return Promisie.iterate<T>(utilities.doWhilst<T>(fn, evaluate), null);
}
static sleep(timeout: number): Promisie<void> {
return new Promisie((resolve) => {
setTimeout(() => {
resolve();
}, timeout);
});
}
static retry<T = any>(fn: () => T | Promise<T>, options?: RetryOptions): Promisie<T | void> {
const { times = 3, timeout = 0 } = options || {};
return Promisie.iterate(utilities.retry<T>(fn, { times, timeout }), null)
.then(result => {
const { __isRejected, e, value } = result as { __isRejected?: boolean, e: Error | null, value: T | null };
if (__isRejected) {
return Promisie.reject(e);
}
return Promisie.resolve(value);
});
}
}
|
f9d121d15641cbaf30ff6696d0c1c5a037bfd1bd
|
TypeScript
|
yhagio/ts-js-algo
|
/src/practice9-solution.ts
| 4
| 4
|
// Write a function, makeChange, that returns an integer that represents
// the least number of coins that add up to an amount where
// the amount is always divisible by 5.
// coin values: 5, 10, 25
export function makeChange(coins: number[], input: number): number {
if (input % 5 !== 0) {
throw new Error("Input must be divisible by 5");
}
// DESC order (Big ones first)
coins.sort((a, b) => b - a);
let i = 0;
let total = 0;
while (input > 0) {
if (coins[i] <= input) {
input -= coins[i];
total++;
} else {
i++;
}
}
return total;
}
// input amount: 40 , output # of coins: 3 (25, 10, 5)
// input amount: 35, output # of coins: 2 (25, 10)
|
9ce6fdb92aeae6f977e7ab2c220859c1baebc838
|
TypeScript
|
waynevanson/accounting-ts
|
/dist/domain.d.ts
| 3.265625
| 3
|
import { Newtype } from "newtype-ts";
import { NonZero } from "newtype-ts/lib/NonZero";
/**
* @summary
* A limitless (by javascript's terms) number that should not equal the following:
* - `0`
* - `Infinity`
* - `NaN`
*
* @todo Allow for numbers greater than what javascript's number type can handle.
* @todo decimal should be between 0 and 99
*/
export declare type Number = [NonZero, NonZero];
export declare type Debit = Record<"DR", Number>;
export declare type Credit = Record<"CR", Number>;
export declare type EntryAmount = Debit | Credit;
export declare type CashReceipt = {
Date: Date;
from: string;
amount: Number;
to: string;
description: string;
identifier: string;
};
export declare type SourceDocument = CashReceipt;
/**
* @summary
* An entry into that would be used in a journal, such as the general journal.
*/
export interface Entry {
date: Date;
account: string;
amount: EntryAmount;
}
export declare type DoubleIndexedArray<A> = [A, A, ...A[]];
/**
* @summary
* The data (source of truth) for the transaction, which consists of
* multiple entries.
*
* Always has a minimum of two entries that BALANACE
*
* @todo validate balance effect of transaction
*/
export interface Transaction extends Newtype<{
readonly Transaction: unique symbol;
}, DoubleIndexedArray<Entry>> {
}
export interface JournalEntry {
account: string;
amount: EntryAmount;
}
export interface JournalEntries extends Newtype<{
readonly JournalTransaction: unique symbol;
}, DoubleIndexedArray<JournalEntry>> {
}
export interface JournalTransaction {
date: Date;
description: string;
entries: JournalEntries;
}
export declare type Journal = {
transactions: Array<JournalTransaction>;
};
export interface SingleEntryLedger {
date: Date;
accounts: string;
amount: EntryAmount;
}
export interface DoubleEntryLedger extends Record<"debit" | "credit", {
date: Date;
accounts: string;
amount: Number;
}> {
}
export declare type BalanceSheet = {};
export declare type ProfitAndLossStatement = {};
export declare type TrialBalance = {};
export declare type Reports = BalanceSheet | ProfitAndLossStatement;
export interface ChartOfAccount {
id: number;
}
|
216143ec76aa4f81c66fab4a6b4fa2387ac054bd
|
TypeScript
|
zeropool/StyleGuide
|
/StyleGuide/AtlasClient/Client/Core/DataStudio/src/scripts/application/shared/AuthHelpers.ts
| 2.765625
| 3
|
/// <reference path="../../../references.d.ts" />
module Microsoft.DataStudio.AuthHelpers {
import TypeInfo = Microsoft.DataStudio.Diagnostics.TypeInfo;
export function extractPuid(token: any): string {
var parsedToken = jwt.decode(token);
if (TypeInfo.isDefined(parsedToken.puid)) { // AAD user
if (!TypeInfo.isString(parsedToken.puid)) {
console.warn("Invalid PUID format: puid is present in the idToken, but it doesn't seem to be a string:", parsedToken.puid);
return "";
}
var puid: string = parsedToken.puid;
var puidRegex = /^[0-9A-Z]{16}$/;
if (!puidRegex.test(puid)) {
console.warn("Invalid PUID format: puid as a string is present in the idToken, but it doesn't match our regex/understanding:", puid);
}
return puid;
}
if (TypeInfo.isDefined(parsedToken.altsecid)) { // Live user
if (!TypeInfo.isString(parsedToken.altsecid)) {
console.warn("Invalid PUID format: altsecid is present in the idToken, but it doesn't seem to be a string:", parsedToken.altsecid);
return "";
}
var altsecid: string = parsedToken.altsecid;
var altsecidRegex = /^1:live\.com:[0-9A-Z]{16}$/;
if (!altsecidRegex.test(altsecid)) {
console.warn("Invalid PUID format: altsecid as a string is present in the idToken, but it doesn't match our regex/understanding:", altsecid);
return altsecid; // let's return whatever we got..
}
var fields: string[] = altsecid.split(':');
// For live.com users, the PUID seems to be conventionally represented as puid@Live.com, so let's follow the same thing
return fields[2] + "@Live.com";
}
console.warn("Invalid PUID format: Neither 'puid' nor 'altsecid' seems to be present in the idToken for this user, understand better?:", parsedToken);
return "";
}
}
|
b62b3472ba37eb53bf3b789ad91f61cfa19e5e30
|
TypeScript
|
jcmelchorp/proyecto-calli
|
/projects/calli/src/app/quiz/store/quiz.actions.ts
| 2.609375
| 3
|
import { Action } from '@ngrx/store';
import { Quiz } from '../models/quiz.model';
export enum QuizActionTypes {
QUIZ_QUERY = '[Quiz] Query',
QUIZ_LOADED = '[Quiz] Fetched',
QUIZ_ADDED = '[Quiz] Added',
QUIZ_EDITED = '[Quiz] Edited',
QUIZ_DELETED = '[Quiz] Deleted',
QUIZ_ERROR = '[Quiz] Error',
}
export class QuizQuery implements Action {
readonly type = QuizActionTypes.QUIZ_QUERY;
}
export class QuizLoaded implements Action {
readonly type = QuizActionTypes.QUIZ_LOADED;
constructor(public payload: { quiz: Quiz[] }) { }
}
export class QuizAdded implements Action {
readonly type = QuizActionTypes.QUIZ_ADDED;
constructor(public payload: { quiz: Quiz }) { }
}
export class QuizEdited implements Action {
readonly type = QuizActionTypes.QUIZ_EDITED;
constructor(public payload: { quiz: Quiz }) { }
}
export class QuizDeleted implements Action {
readonly type = QuizActionTypes.QUIZ_DELETED;
constructor(public payload: { quiz: Quiz }) { }
}
export class QuizError implements Action {
readonly type = QuizActionTypes.QUIZ_ERROR;
constructor(public payload: { error: any }) { }
}
export type QuizActions =
| QuizQuery
| QuizLoaded
| QuizAdded
| QuizEdited
| QuizDeleted
| QuizError;
|
5b3028ca586f7d130e29490c6e93cbf55d7ab1ff
|
TypeScript
|
actions-cool/analyze-action
|
/src/index.ts
| 3.0625
| 3
|
const ifCount = (owner: string, countOfficial: boolean) => {
let result = true;
if (!countOfficial) {
if (owner === 'github' || owner === 'actions') {
result = false;
}
}
return result;
};
export type ACTION_TYPE = {
owner: string;
repo: string;
version: string;
};
export type RESULT_TYPE = {
name: string;
actions: ACTION_TYPE[];
};
/**
* @author xrkffgg
* @description Analyze the action.yml requested by axios
*/
const analyzeActionYml = (param: string, countOfficial = true) => {
const params: string[] = param.split(/\r\n|\n/g);
const result: RESULT_TYPE = {
name: '',
actions: [],
};
params.forEach(item => {
if (item && item.startsWith('name:')) {
result.name = item.replace(/'|"|name:/g, '').trim();
}
if (item && item.trim().startsWith('uses:')) {
const line = item.trim().replace(/'|"|uses:/g, '');
const arr = line.split('@');
const actionArr = arr[0].split('/');
const version = arr[1];
if (actionArr.length === 2 && ifCount(actionArr[0].trim(), countOfficial)) {
result.actions.push({
owner: actionArr[0].trim(),
repo: actionArr[1].trim(),
version,
});
}
}
});
return result;
};
export default {
analyzeActionYml,
};
|
6b5c294398307a2c06540a232f4f257f4341b02f
|
TypeScript
|
ai-overflow/ai_backend
|
/frontend/src/store/modules/auth/state.ts
| 2.890625
| 3
|
export interface AuthTokenType {
accessToken: string | null,
tokenExpiration: Date,
tokenType: string | null
}
const defaultAuthToken: AuthTokenType | null = {
accessToken: '',
tokenExpiration: new Date(),
tokenType: ''
};
const authToken: AuthTokenType | null = JSON.parse(localStorage.getItem('authToken') ?? "null");
const currentDate = new Date();
const initialAuthToken = function () {
if (!authToken || !authToken.tokenExpiration) {
return null;
}
authToken.tokenExpiration = new Date(authToken.tokenExpiration);
if (authToken.tokenExpiration < currentDate) {
return null;
}
return authToken;
}();
export default function () {
return {
status: {
authToken: initialAuthToken ? initialAuthToken : defaultAuthToken,
loggedIn: !!initialAuthToken
}
}
}
|
6aa7a81cd76f81a8a21cb0fbe6ef5679ce45b41d
|
TypeScript
|
rogemus/Tetris
|
/src/core/game/Player.ts
| 2.90625
| 3
|
import { Position, RotationDirection } from '../../types';
import { dispatchEvent } from '../../utils';
import { ROWS_REMOVED_EVENT, SCORE_UPDATE_EVENT, SPEED_UPDATE_EVENT } from './events';
import Piece from './Piece';
class Player {
public nextPiece: Piece = new Piece();
public piece: Piece = new Piece();
public pos: Position = { x: 4, y: 0 };
public score = {
pointsMultiplier: 5,
points: 0,
combo: 1
}
public speed = {
speedLevel: 1,
speedMultiplier: 1
}
constructor() {
this.attachEvents();
}
public drop(): void {
this.pos.y++;
}
public move(direction: number): void {
this.pos.x += direction;
}
public reset(): void {
this.pos = { x: 4, y: 0 };
this.piece = this.nextPiece;
this.nextPiece = new Piece();
}
public clear(): void {
this.pos = { x: 4, y: 0 };
this.piece = new Piece();
this.nextPiece = new Piece();
this.score = {
pointsMultiplier: 5,
points: 0,
combo: 1
};
dispatchEvent(SCORE_UPDATE_EVENT, {
score: this.score
});
dispatchEvent(SPEED_UPDATE_EVENT, {
speed: this.speed
});
}
public revertDrop(): void {
this.pos.y--;
}
public rotate(direction: RotationDirection): void {
this.piece.flip(direction);
}
private addScore(points: number): void {
this.score.combo = points;
this.score.points += points * this.score.combo * this.score.pointsMultiplier;
}
private attachEvents(): void {
document.addEventListener(ROWS_REMOVED_EVENT, this.handlePointsChange.bind(this));
}
private handlePointsChange(e: CustomEvent): void {
this.addScore(e.detail.removedCount);
this.speedUp();
dispatchEvent(SCORE_UPDATE_EVENT, {
score: this.score
});
dispatchEvent(SPEED_UPDATE_EVENT, {
speed: this.speed
});
}
private speedUp(): void {
if (
this.speed.speedLevel < 7 && (
this.score.points >= 20 ||
this.score.points >= 100 ||
this.score.points >= 300 ||
this.score.points >= 600 ||
this.score.points >= 900 ||
this.score.points >= 1500
)
) {
this.score.pointsMultiplier += 2;
this.speed.speedLevel += 1;
this.speed.speedMultiplier += 1;
}
}
}
export default Player;
|
66cb9af748272674e79ef0b0dfb60fd274863bc2
|
TypeScript
|
markgoho/ng2-wp-api
|
/examples/Collection using the service.ts
| 2.765625
| 3
|
/*
* In this example, we display a collection of posts, pagination and a button to load the next page.
* we also set the QueryArgs for the request to get embedded posts and filter the results to 6 posts per page
*
* get pagination properties from `wpCollection.service`
*/
import { Component, OnInit } from '@angular/core';
import {WpQueryArgs, WpEndpoint, WpService, CollectionResponse} from 'ng2-wp-api';
@Component({
selector: 'test-collection',
template: `
<div class="test">
<div *ngFor="let post of posts" class="item">
<h3>
{{post.title.rendered}}
</h3>
</div>
</div>
<pre>{{pagination | json}}</pre>
`
})
export class SiderComponent implements OnInit {
endpoint = WpEndpoint.posts;
args;
posts;
pagination;
collection;
constructor(private wpService: WpService) {
}
ngOnInit() {
this.get();
}
get(){
this.args = new WpQueryArgs({
per_page: 4
});
this.collection = this.wpService.collection().posts();
// or this.collection = this.wpService.collection().endpoint(WpHelper.endpoint.posts);
this.collection.get(this.args).subscribe((res: CollectionResponse) => {
if(res.error){
console.log(res.error);
}
else{
this.pagination = res.pagination;
this.posts = res.data;
}
});
}
/** Get next collection combined with current collection */
getMore() {
this.collection.more().subscribe((res: CollectionResponse) => {
this.posts = res.data;
this.pagination = res.pagination;
});
}
/** Get next collection only */
getMore() {
this.collection.next().subscribe((res: CollectionResponse) => {
this.posts = res.data;
this.pagination = res.pagination;
});
}
/** Get prev collection only */
getMore() {
this.collection.prev().subscribe((res: CollectionResponse) => {
this.posts = res.data;
this.pagination = res.pagination;
});
}
}
/* Optional component that uses Post class which wraps the post response making it easy to access.
* NOTE: The embed in QueryArgs must be set to true in order to get Post class to work.
*/
import {WpPost} from 'ng2-wp-api';
@Component({
selector: 'item',
template: `
<div class="post-title"> {{post.title()}} </div>
<div class="post-image">
<img [src]="post.featuredImageUrl('small')"/>
</div>
<div class="post-excerpt" [innerHtml]="post.excerpt()">
`,
})
export class Item {
@Input() data;
post: WpPost;
ngOnInit() {
this.post = new WpPost(this.data);
}
}
|
a7dbaade3037328f5deba30a8467a8946f44dc47
|
TypeScript
|
jakobwesthoff/tosec-tool
|
/src/Library/CrcStream.ts
| 2.8125
| 3
|
import { crc32 } from "crc";
import { Duplex, DuplexOptions } from "stream";
export class CrcStream extends Duplex {
private lastValue: number;
constructor(options?: DuplexOptions) {
super({...options, encoding: "utf8"});
}
// tslint:disable-next-line:function-name
public _write(
chunk: any,
_encoding: string,
callback: (error?: Error | null) => void
): void {
if (this.lastValue !== undefined) {
this.lastValue = crc32(chunk, this.lastValue);
} else {
this.lastValue = crc32(chunk);
}
callback();
}
// tslint:disable-next-line:function-name
public _read(_size: number): void {
if (this.lastValue !== undefined) {
this.push(this.lastValue.toString(16).padStart(8, '0'), 'utf8');
}
else {
this.push(crc32('').toString(16).padStart(8, '0'), 'utf8');
}
}
}
|
5f1d01dc0d6ed430cd58930f6484276b77951c76
|
TypeScript
|
chrisk8er/animation-editor
|
/src/area/util/areaUtils.ts
| 3.015625
| 3
|
import { AREA_PLACEMENT_TRESHOLD } from "~/area/state/areaConstants";
import { AreaReducerState } from "~/area/state/areaReducer";
import { isVecInRect } from "~/util/math";
export const getHoveredAreaId = (
position: Vec2,
areaState: AreaReducerState,
areaToViewport: {
[areaId: string]: Rect;
},
): string | undefined => {
let areaId: string | undefined;
const keys = Object.keys(areaState.areas);
for (let i = 0; i < keys.length; i += 1) {
if (areaState.layout[keys[i]].type !== "area") {
continue;
}
const areaViewport = areaToViewport[keys[i]];
if (isVecInRect(position, areaViewport)) {
areaId = keys[i];
break;
}
}
return areaId;
};
export type PlaceArea = "top" | "left" | "right" | "bottom" | "replace";
export const getAreaToOpenPlacementInViewport = (rect: Rect, position: Vec2): PlaceArea => {
const w = rect.width;
const h = rect.height;
const x = position.x - rect.left;
const y = position.y - rect.top;
let placement: PlaceArea | undefined;
let dist = Infinity;
const treshold = Math.min(w, h) * AREA_PLACEMENT_TRESHOLD;
const tests: Array<{ placement: PlaceArea; dist: number }> = [
{ placement: "left", dist: x },
{ placement: "top", dist: y },
{ placement: "right", dist: w - x },
{ placement: "bottom", dist: h - y },
];
for (const test of tests) {
if (test.dist < treshold && test.dist < dist) {
dist = test.dist;
placement = test.placement;
}
}
if (!placement) {
return "replace";
}
return placement;
};
|
d218107f8b98e98d4c808341ef92ae92bf8c6f3b
|
TypeScript
|
packpacka/vue-dc-app
|
/src/app/store/mutations.ts
| 3.21875
| 3
|
interface IMutationLink<T> {
saveAddress: T;
clearAddress: T;
}
type Mutation = (state: any, payload: any) => void;
interface IMutations extends IMutationLink<Mutation> { }
export const mutations: IMutations = {
saveAddress: (state, address: string) => {
state.selectedAddress = address;
},
clearAddress: (state) => {
state.selectedAddress = undefined;
},
};
interface IMutationKeys extends IMutationLink<string> { }
export const mutationKeys: IMutationKeys = Object.keys(mutations).reduce((res, key) => ({ ...res, [key]: key }), {}) as IMutationKeys;
|
7d85fd58940b6164410160a62c0d7b91cc61f4ea
|
TypeScript
|
up-n-running/Record-Of-Support-Workbook
|
/LSA Workbook/lsa/lsa-utils.ts
| 2.5625
| 3
|
function isAMasterNotAChild( spreadSheet, globalSettingsWorkSheet, alertIfMaster ) {
Logger.log( "isAMasterNotAChild called" )
//get default values for params if any params are missing
spreadSheet = (spreadSheet) ? spreadSheet : SpreadsheetApp.getActiveSpreadsheet();
globalSettingsWorkSheet = (globalSettingsWorkSheet)
? globalSettingsWorkSheet
: spreadSheet.getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
Logger.log( "globalSettingsWorkSheet = " + globalSettingsWorkSheet );
alertIfMaster = ( alertIfMaster ) ? alertIfMaster : false;
var masterFileIdFromSettings = globalSettingsWorkSheet.getRange(
SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_MASTER_FILE_ID,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO
).getValue(); //if this field is blank it's a master
var isMaster = masterFileIdFromSettings == "";
if( isMaster && alertIfMaster ) {
var ui = SpreadsheetApp.getUi();
ui.alert ( "Action not available", "Sorry this action is not available on the Master Workbook", ui.ButtonSet.OK );
}
return ( isMaster );
}
function currentUserIsADev( spreadSheet, globalSettingsWorkSheet ) {
spreadSheet = (spreadSheet) ? spreadSheet : SpreadsheetApp.getActiveSpreadsheet();
globalSettingsWorkSheet = (globalSettingsWorkSheet)
? globalSettingsWorkSheet
: spreadSheet.getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
var devEmailAddressFromSettings = globalSettingsWorkSheet.getRange(
SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_DEVS_EMAIL,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO
).getValue(); //if this field is blank it's a master
//just one of the quirks of google scripts - theres three ways to get the user and they dont all return something!
var userEmail = Session.getActiveUser().getEmail();
userEmail = (userEmail) ? userEmail : Session.getEffectiveUser().getEmail();
userEmail = (userEmail) ? userEmail : Session.getUser().getEmail();
return ( devEmailAddressFromSettings.trim() == userEmail );
}
/**
* [lsa-utils.gs]
* Check to see if a particular action is available on this particular Workbook
* @param spreadsheet {Spreadsheet=} The Spreadsheet Object we are checking
* @param ui {UserInterface=} The UserInterface object we are using to make alerts
* @param settingsSheet {Sheet=} The spreadsheet's global settings sheet
* @param alertIfFail {bool=} Whether to throw an alert if this check fails
* @param allowLSAMode {bool=} Whether to allow this action on Child LSA Workbooks
* @param allowMasterMode {bool=} Whether to allow this action on the Master Workbook
* @param allowMasterMode {bool=} Whether to allow this action on decommissioned child Workbooks
* @return {bool} true iff we are allowed to perform the action on this workbook
*/
function isAuthorised_( spreadsheet, ui, settingsSheet, alertIfFail, allowLSAMode, allowMasterMode, allowDecomissionedMode ) {
//parse params
spreadsheet = ( spreadsheet ) ? spreadsheet : SpreadsheetApp.getActive();
alertIfFail = ( alertIfFail ) ? true : false;
ui = ( ui ) ? ui : ( alertIfFail ? SpreadsheetApp.getUi() : null );
settingsSheet = ( settingsSheet ) ? settingsSheet : spreadsheet.getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
allowLSAMode = ( allowLSAMode ) ? true : false;
allowMasterMode = ( allowMasterMode ) ? true : false;
allowDecomissionedMode = ( allowDecomissionedMode ) ? true : false;
if( !allowLSAMode || ! allowMasterMode ) {
let masterFileIdFromSettings = settingsSheet.getRange(
SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_MASTER_FILE_ID,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO
).getValue(); //if this field is blank it's a master
let isMaster = masterFileIdFromSettings == "";
if( isMaster && !allowMasterMode ) {
if( alertIfFail ) {
ui.alert ( "Action not available", "Sorry this action is not available on the Master Workbook", ui.ButtonSet.OK );
}
return false;
}
if( !isMaster && !allowLSAMode ) {
if( alertIfFail ) {
ui.alert ( "Action not available", "Sorry this action is only available on the Master Workbook", ui.ButtonSet.OK );
}
return false;
}
}
if( !allowDecomissionedMode && !isCorrectInstance( settingsSheet ) ) {
if( alertIfFail ) {
ui.alert ( "Action not available", "Sorry this action is not available on a decomissioned Workbook", ui.ButtonSet.OK );
}
return false;
}
return true;
}
/**
* [lsa-utils.gs]
* Find a particular LSAs folder given the LSAs workbook file object
*
* In google drive a file can have >1 parent folder so if there is more than one it will look for the one:
* - whose parent folder in turn matches the id passed in rootAllLSAsFolderId (if rootAllLSAsFolderId is set)
* - and / or with matching folderName ( if folderName parameter is set )
*
* If there is at least one parent but neither match then it will return the first parent folder found
* If there is no parent then something is very wrong so log this then cleanly return the root folder
*
* @param workBookFile {File} The File object of the LSAs Workbook
* @param folderName {String=} The Directory name of the LSAs Directory
* @param rootAllLSAsFolderId {String=} The Id the LSAs Directory's root folder in turn
* @return {Folder} The found folder based on the best guess algorithm described or the Users Root folder if not found
*/
function getLSAsFolderFromWorkbookFile( workBookFile, folderName, rootAllLSAsFolderId ) {
//parse optional param
folderName = (folderName) ? folderName : null;
rootAllLSAsFolderId = (rootAllLSAsFolderId) ? rootAllLSAsFolderId : null;
Logger.log( "getLSAsFolderFromWorkbookFile called, folderName = '"+folderName+"', rootAllLSAsFolderId = '"+rootAllLSAsFolderId+"'" );
var parents = workBookFile.getParents();
var usersFolder = null, tempFolder = null;
let keepLooking = true;
while ( keepLooking && parents.hasNext() ) {
tempFolder = parents.next();
if( folderName == null && rootAllLSAsFolderId == null ) {
//its a match
Logger.log( "ITS A MATCH - RETURNING FIRST PARENT FOUND AS NO FILTERS USED" );
usersFolder = tempFolder;
keepLooking = false;
}
else if( folderName == null || tempFolder.getName() == folderName ) {
if( rootAllLSAsFolderId == null ) {
//its a match
Logger.log( "ITS A MATCH - NO rootAllLSAsFolderId FILTER APPLIED" );
usersFolder = tempFolder;
keepLooking = false;
}
else {
let parentsParents = tempFolder.getParents();
let parentsParent
while( parentsParents.hasNext() ) {
parentsParent = parentsParents.next();
if( rootAllLSAsFolderId == parentsParent.getId() ) {
//its a match
Logger.log( "ITS A MATCH: rootAllLSAsFolderId MATCHES & folderName == null || tempFolder.getName() == folderName" );
usersFolder = tempFolder;
keepLooking = false;
}
}
}
}
}
return usersFolder;
}
/**
* Check that the LSA Name and the Record Date fields are populated on the Input SHeet
*/
function validateInputSheetFields( inputSheet, ui, settingsSheet ) {
Logger.log( "inputSheet.getRange( SHEETS.INPUT.REFS.LESSON_DATE.ROW_NO, SHEETS.INPUT.REFS.LESSON_DATE.COL_NO ).getValue() = " + inputSheet.getRange( SHEETS.INPUT.REFS.LESSON_DATE.ROW_NO, SHEETS.INPUT.REFS.LESSON_DATE.COL_NO ).getValue() );
let recordDate: Date = inputSheet.getRange( SHEETS.INPUT.REFS.LESSON_DATE.ROW_NO, SHEETS.INPUT.REFS.LESSON_DATE.COL_NO ).getValue();
recordDate = new Date( recordDate );
let today = new Date( new Date().setHours(0,0,0,0) );
let endOfToday = new Date( new Date().setHours(23,59,59,59) );
if( inputSheet.getRange( SHEETS.INPUT.REFS.LESSON_DATE.ROW_NO, SHEETS.INPUT.REFS.LESSON_DATE.COL_NO ).getValue() == "" ) {
ui.alert( "What Date Are These Records For?",
"Please enter the date at the top of the '"+SHEETS.INPUT.NAME+"' Sheet and then try again.",
ui.ButtonSet.OK );
return false;
}
else if( !isValidDate( recordDate ) ) {
ui.alert( "Invalid Record Date",
"The 'Date of Lessons' entered at the top of the '"+SHEETS.INPUT.NAME+"' Sheet is not a valid date.\n\n" +
"The 'New Day Cleanup' button will always enter todays date for you.\n\n" +
"Please enter a valid date manually however in this instance, to avoid losing your RoS data.",
ui.ButtonSet.OK );
return false;
}
else if( recordDate > endOfToday ) {
ui.alert( "Future Record Date",
"The 'Date of Lessons' entered at the top of the '"+SHEETS.INPUT.NAME+"' Sheet is in the future.\n\n" +
"You cannot generate Records of Support for future dates, sorry.",
ui.ButtonSet.OK );
return false;
}
else if( recordDate < today ) {
settingsSheet = ( settingsSheet ) ? settingsSheet : SpreadsheetApp.getActive().getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
let noOfDaysAgoAllowed = settingsSheet.getRange( SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_MAX_PAST_DAYS_ROS,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO ).getValue();
if( today.getTime() - recordDate.getTime() > noOfDaysAgoAllowed*(24*3600*1000) ) {
ui.alert( "Record Date too far in the past",
"The 'Date of Lessons' entered at the top of the '"+SHEETS.INPUT.NAME+"' Sheet is too far in the past.\n\n" +
"You can only generate Records of Support up to "+noOfDaysAgoAllowed+" days in the past, sorry.",
ui.ButtonSet.OK );
return false;
}
}
if( recordDate < today ) {
let confirmResponse = ui.alert( "Generate Historic Records of Support?",
"The 'Date of Lessons' entered at the top of the '"+SHEETS.INPUT.NAME+"' Sheet is in the past.\n\n" +
"Are you sure you want to generate Records of Support for a previous date?",
ui.ButtonSet.YES_NO );
if( confirmResponse != ui.Button.YES ) {
return false;
}
}
if( inputSheet.getRange( SHEETS.INPUT.REFS.LSA_NAME.ROW_NO, SHEETS.INPUT.REFS.LSA_NAME.COL_NO ).getValue() == "" ) {
ui.alert( "What is your name?",
"Please enter your name (LSA Name) at the top of '"+SHEETS.INPUT.NAME+"' Sheet and then try again.",
ui.ButtonSet.OK );
return false;
}
return true;
}
/**
* Returns true if it worked, false if it didn't
*/
function ExportOneRoSRecord( recordNo, ui, learnerNamesToEmail, learnerNamesToSkip ) {
//if last param is missing
ui = (ui) ? ui : SpreadsheetApp.getUi();
//find which column letter we should be accessing
let recordColumnLetter = columnToLetter( recordNo + SHEETS.INPUT.REFS.COL_NO_RECORD_1 - 1 );
let spreadsheet = SpreadsheetApp.getActive();
//get RoS Sheet
let recordSheet = spreadsheet.getSheetByName(recordNo);
uiSensitiveToast( spreadsheet, ui, "Generating Record " + recordNo, "Saving Record " + recordNo );
//if( recordSheet ) {
refreshRoSSheetsLinkToInputSheet_( recordNo, recordSheet, spreadsheet );
if( recordSheet.isSheetHidden() ) {
recordSheet.showSheet();
}
let globalSettingsSheet = spreadsheet.getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
let rootRoSDirectoryId = globalSettingsSheet.getRange(
SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_DIR_ID_ROS,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO
).getValue();
let inputSheet = spreadsheet.getSheetByName( SHEETS.INPUT.NAME);
let recordDate = inputSheet.getRange( SHEETS.INPUT.REFS.REF_DATE ).getValue();
let recordLSAName = inputSheet.getRange( SHEETS.INPUT.REFS.REF_LSA_NAME ).getValue();
let recordStartTime = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_START_TIME ).getValue();
let recordDuration = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_DURATION ).getValue();
let recordLearnerName = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_LEARNER_NAME ).getValue();
let recordLessonName = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_LESSON_NAME ).getValue();
let recordEmailAddress = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_EMAIL_ADDRESS ).getValue();
recordEmailAddress = substututeIfPlaceholderEmailAddress_( recordEmailAddress );
let recordAutoSignComments = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_AUTOSIGN_COMMENTS ).getValue();
let recordLearnerId = inputSheet.getRange( "" + recordColumnLetter + SHEETS.INPUT.REFS.ROW_NO_LEARNER_ID ).getValue();
let learnerObj: any = getChildLearnerObjByLearnerIdFromSameVersionSource_( spreadsheet, null, recordLearnerId, null );
Logger.log("3");
Logger.log( "learnerNamesToSkip.includes( '"+recordLearnerName+"' ) = " + learnerNamesToSkip.includes( recordLearnerName ) );
//only export if not a skipped name
if( learnerNamesToSkip.includes( recordLearnerName ) )
{
learnerObj.SIGN_TYPE = "Skip";
}
Logger.log( "learnerObj.SIGN_TYPE = '" + learnerObj.SIGN_TYPE + "'" );
Logger.log( "learnerObj.SIGNATURE_ID = '" + learnerObj.SIGNATURE_ID + "'" );
//perform a sanity check to make sure the learner data is okay as mey have have to adjust it or skip it
if( learnerObj.SIGN_TYPE == "Stored" && !learnerObj.SIGNATURE_ID ) {
learnerObj.SIGN_TYPE = "PDF";
if( !learnerNamesToEmail.includes( recordLearnerName ) ) {
let selectedBtn = ui.alert( "No Stored Signature for " + recordLearnerName,
recordLearnerName + " is set to " +
"use 'Stored Signature' type Records of Support.\n\n" + "However, they have not yet saved " +
"their signature so we can only send the PDF version instead which is a bit " +
"more complex for them to sign.\n\n" +
"After you have exported your records of support please go to the 'Settings - Learners' sheet and " +
"use the 'Stored Signature' column to generate a reminder email for them to prompt them to save their Signature with us.\n\n" +
"Press 'OK' to send their Records of Support in the PDF format instead (you may have to talk your learner through the signing process).\n" +
"Or press 'Cancel' to skip generating Records of Support for " + recordLearnerName,
ui.ButtonSet.OK_CANCEL );
if( selectedBtn == ui.Button.CANCEL ) {
learnerObj.SIGN_TYPE = "Skip";
learnerNamesToSkip.push( recordLearnerName );
}
}
}
Logger.log("3a");
let rosFile = null;
if( learnerObj.SIGN_TYPE == "Stored" ) {
rosFile = saveRosSpreadsheetToGivenFolder(
spreadsheet,
rootRoSDirectoryId,
learnerObj,
recordLearnerName,
recordStartTime,
recordDuration,
recordLSAName,
recordDate,
recordNo,
( recordAutoSignComments != "" ),
recordSheet,
recordEmailAddress,
ui );
}
else if( learnerObj.SIGN_TYPE == "PDF" ) {
rosFile = savePDFsToGivenFolder(
rootRoSDirectoryId,
learnerObj,
recordLearnerName,
recordStartTime,
recordDuration,
recordLSAName,
recordDate,
recordNo,
( recordAutoSignComments != "" ),
null,
recordSheet.getSheetId(),
ui );
}
Logger.log("4");
if( rosFile ) { //if it succeeded
//give file permission to learner if they dont have it already
let existingEditors = rosFile.getEditors();
existingEditors.push( { getEmail: function() { return "lsa.admin@wlc.ac.uk"; } } ); //TO DO: CHANGE THIS HACK TO GET VALUE FROM GLOBAL SETTINGS
let needToAddEditor = true;
for( var e=0; needToAddEditor && e<existingEditors.length; e++ ) {
needToAddEditor = !( recordEmailAddress == existingEditors[e].getEmail() );
}
if( needToAddEditor ) {
rosFile.addEditor(recordEmailAddress);
}
//save file info in spreadsheet to activate hyperlinks to see file on Input and 'My RoS Files' Sheets
AddFileToWorkbook( spreadsheet, inputSheet, null, recordNo, rosFile, recordLearnerName, recordLearnerId,
recordEmailAddress, recordLessonName, recordDate, recordStartTime, recordDuration, learnerObj.SIGN_TYPE,
recordAutoSignComments );
Logger.log("5a");
return rosFile.getId();
}
Logger.log("5b");
return null; //if it failed
}
function getOrCreateLearnerYearAndMonthSubDir( spreadsheet: GoogleAppsScript.Spreadsheet.Spreadsheet,
recordDate: any, learnerName: string, learnerObj: any, rootRoSDirectoryId: string ) {
//learner folder id should be passed in on learner record but if learner folder id is "" then it's probably a short term learner
//so just use the learner name and create (or get) the directory
//if learnerObj not found (edge case - should never happen) then just use learner name as folder name - just in case
let learnerFolder = null;
let learnerFolderId = ""
let learnerFolderToCreateName = learnerName;
if( learnerObj != null ) {
learnerFolderId = learnerObj.LEARNER_DIR; //still might be empty string
learnerFolderToCreateName = learnerFolderToCreateName + " (" + learnerObj.LEARNER_ID + ")" +
( ( learnerObj.CATEGORY != "Long Term" ) ? " " + learnerObj.CATEGORY : "" );
}
if( learnerFolderId != "" ) {
learnerFolder = DriveApp.getFolderById( learnerFolderId );
}
if( learnerFolder == null ) {
learnerFolder = createOrGetChildFolder( rootRoSDirectoryId, learnerFolderToCreateName, null );
}
//if there was no learner folder stored in the Settings - Learners sheet ( probably because its a short term learner )
//then save the link to it here
if( learnerObj != null && learnerObj.LEARNER_DIR == "" ) {
let learnerSheet = spreadsheet.getSheetByName( SHEETS.SETTINGS_LEARNERS.NAME );
let learnerRowNum = findInColumn( learnerSheet, learnerObj.LEARNER_ID, SHEETS.SETTINGS_LEARNERS.REFS.COL_NO_LEARNER_ID,
SHEETS.SETTINGS_LEARNERS.REFS.ROW_NO_FIRST_LEARNER, SHEETS.SETTINGS_LEARNERS.REFS.ROW_NO_LAST_LEARNER );
if( learnerRowNum > 0 ) {
learnerSheet.getRange( learnerRowNum, SHEETS.SETTINGS_LEARNERS.REFS.COL_NO_LEARNER_DIR ).setValue( learnerFolder.getId() );
learnerObj.LEARNER_DIR = learnerFolder.getId();
}
}
let learnerMonthFolder = createOrGetChildFolder(
learnerFolder.getId(), Utilities.formatDate(new Date( recordDate ), GLOBAL_CONSTANTS.TIMEZONE, "yyyy-MM" ), null
);
return learnerMonthFolder;
}
function generateRosFileName(learnerName: string, lessonTimeObj: any, lsaName: string, isAutoSign: boolean, isPDF: boolean ) {
return learnerName + '_' +
Utilities.formatDate( lessonTimeObj.start, GLOBAL_CONSTANTS.TIMEZONE, "yyyy-MM-dd" ) + '_' +
Utilities.formatDate( lessonTimeObj.start, GLOBAL_CONSTANTS.TIMEZONE, "HH:mm" ) + '-' +
Utilities.formatDate( lessonTimeObj.end, GLOBAL_CONSTANTS.TIMEZONE, "HH:mm" ) + '_' +
lsaName +
( ( isAutoSign ) ? "_AUTO_SIGNED" : "") +
( ( isPDF ) ? ".pdf" : "");
}
/**
* Save brand new file info in spreadsheet to activate hyperlinks to see file on Input and 'My RoS Files' Sheets
* Creates new My RoS Files record if there isn't one already for that fileId (which their should be with an add)
*/
function AddFileToWorkbook( spreadsheet, inputSheet, myFilesSheet, recordNo, pdfFile, learnerName, learnerId, learnerEmail,
lessonName, lessonDate, startTime, duration, signType, autoSignComments ) {
Logger.log( "AddFileToWorkbook called, learnerEmail = "+learnerEmail+", startTime = "+startTime+", autoSignComments = " + autoSignComments );
//parse params
spreadsheet = ( spreadsheet ) ? spreadsheet : SpreadsheetApp.getActive();
inputSheet = ( inputSheet ) ? inputSheet : spreadsheet.getSheetByName( SHEETS.INPUT.NAME );
myFilesSheet = ( myFilesSheet ) ? myFilesSheet : spreadsheet.getSheetByName( SHEETS.MY_FILES.NAME );
//get file info
var fileId = pdfFile.getId();
var fileName = pdfFile.getName();
var fileLastUpdated = pdfFile.getLastUpdated();
//parse lesson times information
let lessonTimeObj = getlessonTimesObjectFromInputSheetValues( lessonDate, startTime, duration );
//Find the file in the My RoS Files Sheet
var fileRowNo = getRowNumOnFilesSheetReadyForInsertOrUpdate( myFilesSheet, fileId, null );
//now make the actual update to the record on the My RoS Files Sheet
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME ).setValue( fileName );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_USERS_FILE_ID).setValue( fileId );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_CREATED_DATE ).setValue( fileLastUpdated );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_UPDATED_DATE ).setValue( fileLastUpdated );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_DELETED_DATE ).setValue( "" );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_LEARNER_NAME ).setValue( learnerName );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_LEARNER_ID ).setValue( learnerId );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_LEARNER_EMAIL).setValue( learnerEmail );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_LESSON_NAME ).setValue( lessonName );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_LESSON_DATE ).setValue( lessonDate );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_START_TIME ).setValue( Utilities.formatDate( lessonTimeObj.start, GLOBAL_CONSTANTS.TIMEZONE, "HH:mm" ) );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_DURATION ).setValue( lessonTimeObj.duration );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_SIGN_TYPE ).setValue( signType );
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_AUTOSIGN_CMTS).setValue( autoSignComments );
//now make the actual update to the record on the Input Files Sheet
var recordColumnNo = recordNo + SHEETS.INPUT.REFS.COL_NO_RECORD_1 - 1;
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_ID , recordColumnNo ).setValue( fileId );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_NAME , recordColumnNo ).setValue( fileName );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_CREATED , recordColumnNo ).setValue( fileLastUpdated );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_UPDATED , recordColumnNo ).setValue( fileLastUpdated );
}
/**
* Update existing file's updated date in spreadsheet to activate hyperlinks to see file on Input and 'My RoS Files' Sheets
* Creates new My RoS Files record if there isn't one already for that fileId (which their should be with an add)
*/
function UpdateFileInfoInWorkbook( spreadsheet, inputSheet, myFilesSheet, recordNo, rosFile, flagAsJustTrashed ) {
//parse params
spreadsheet = ( spreadsheet ) ? spreadsheet : SpreadsheetApp.getActive();
inputSheet = ( inputSheet ) ? inputSheet : spreadsheet.getSheetByName( SHEETS.INPUT.NAME );
myFilesSheet = ( myFilesSheet ) ? myFilesSheet : spreadsheet.getSheetByName( SHEETS.MY_FILES.NAME );
//get file info
var fileId = rosFile.getId();
var fileLastUpdated = rosFile.getLastUpdated();
//Find the file in the My RoS Files Sheet
var fileRowNo = getRowNumOnFilesSheetReadyForInsertOrUpdate( myFilesSheet, fileId, true );
//now make the actual update to the record on the My RoS Files Sheet
//assuming row was found above - it SHOULD ALWAYS be found above but in reality it isnt
//when input data is being imported from a previous version of a workbook after an upgrade
//so handle this elegantly
if( fileRowNo > 0 ) {
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_UPDATED_DATE ).setValue( fileLastUpdated );
if( flagAsJustTrashed ) {
myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_DELETED_DATE ).setValue( new Date() );
}
}
//if we dont pass in a recordNo, then we must find it (if it exists - only todays files will exist)
if( !recordNo || recordNo < 0 ) {
let foundColNo = findInRow( inputSheet, fileId, SHEETS.INPUT.REFS.ROW_NO_FILE_ID,
SHEETS.INPUT.REFS.COL_NO_RECORD_1, SHEETS.INPUT.REFS.COL_NO_RECORD_LAST );
recordNo = ( foundColNo >= 0 ) ? ( foundColNo - SHEETS.INPUT.REFS.COL_NO_RECORD_1 + 1 ) : null;
}
//now make the actual update to the record on the Input Files Sheet
if( recordNo && recordNo >= 0 ) {
let recordColumnNo = recordNo + SHEETS.INPUT.REFS.COL_NO_RECORD_1 - 1;
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_UPDATED , recordColumnNo ).setValue( fileLastUpdated );
if( flagAsJustTrashed ) {
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_ID , recordColumnNo ).setValue( "" );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_NAME , recordColumnNo ).setValue( "" );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_CREATED , recordColumnNo ).setValue( "" );
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_UPDATED , recordColumnNo ).setValue( "" );
}
}
}
function getRowNumOnFilesSheetReadyForInsertOrUpdate( myFilesSheet, fileId, dontAllowCreateNewRow )
{
dontAllowCreateNewRow = ( dontAllowCreateNewRow ) ? true : false;
//Find the file in the My RoS Files Sheet
var fileRowNo = findInColumn( myFilesSheet, fileId, SHEETS.MY_FILES.REFS.COL_NO_USERS_FILE_ID,
SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE, SHEETS.MY_FILES.REFS.ROW_NO_LAST_FILE );
//if file doesnt exist in the list the move all rows down one, losing the last row in the process to make space in the top row
if( fileRowNo < 0 && !dontAllowCreateNewRow ) {
fileRowNo = SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE;
//check if the top row is blank
var preExistingFileName = myFilesSheet.getRange( fileRowNo, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME ).getValue();
if( preExistingFileName != "" ) {
//copy all bar the bottom row down one
myFilesSheet.getRange(
SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME,
SHEETS.MY_FILES.REFS.ROW_NO_LAST_FILE - SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE,
SHEETS.MY_FILES.REFS.COL_NO_AUTOSIGN_CMTS - SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME + 1
).copyTo (
myFilesSheet.getRange( SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE + 1, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME ),
SpreadsheetApp.CopyPasteType.PASTE_VALUES, false
);
//delete top row
myFilesSheet.getRange( SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME,
1, SHEETS.MY_FILES.REFS.COL_NO_AUTOSIGN_CMTS - SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME + 1 )
.clear({contentsOnly: true, skipFilteredRows: false});
}
}
return fileRowNo;
}
/**
* [lsa-utils.gs]
* Loops through each of the 25 records on the Input sheet that have status of Sent to Learner,
* except for those records who'se fileid is in fileIdsToSkip.
* keeps track of which are signed and which are still unsigned in the optional array parms, stillUnsignedFileIds and newlySignedFileIds
* Also updates the spreadsheet to save the file info on both Input and My Files Sheets which in turn refreshes status bar to be up to
* date
* @param spreadsheet {Spreadsheet=} The spreadsheet containing the input sheet
* @param inputSheet {Sheet=} The input sheet to check
* @param ui {UserInterface=} The ui opject if there is one
* @param fileIdsToSkip {String[]=} Array of fileids not to bother checking
* @param onlyTheseLearnerNames {String[]=} Array of Learner Names to filter by. pass null to apply no filter and check all learners
* @return filesCheckedFileIDs {String[]} The File IDs of all the files actually checked
*/
function CheckForSignatures_InputSheet( spreadsheet, inputSheet, ui, fileIdsToSkip, onlyTheseLearnerNames ) {
//parse params
spreadsheet = (spreadsheet) ? spreadsheet : SpreadsheetApp.getActive();
inputSheet = (inputSheet) ? inputSheet : spreadsheet.getSheetByName( SHEETS.INPUT.NAME );
ui = (ui) ? ui : SpreadsheetApp.getUi();
fileIdsToSkip = (fileIdsToSkip) ? fileIdsToSkip : new Array();
//return array
var fileIdsChecked = new Array();
//switch UI to Input Sheet
if( !ui.FAKE_MODE ) { spreadsheet.setActiveSheet(inputSheet, true); }
let noOfRecordsOnInputSheet = SHEETS.INPUT.REFS.COL_NO_RECORD_LAST-SHEETS.INPUT.REFS.COL_NO_RECORD_1 + 1;
for( let recordNo = 1 ; recordNo <=noOfRecordsOnInputSheet ; recordNo++ ) {
let recordColumnNo = recordNo + SHEETS.INPUT.REFS.COL_NO_RECORD_1 - 1;
let fileId = inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_FILE_ID, recordColumnNo ).getValue();
let recordStatus = inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_STATUS_BAR, recordColumnNo ).getValue();
let recordLearnerName = inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_LEARNER_NAME, recordColumnNo ).getValue();
if( fileId!=="" &&
recordStatus != SHEETS.INPUT.STATUSES.SIGNED &&
recordStatus != SHEETS.INPUT.STATUSES.SAVED_EMAILWAIT &&
recordStatus != SHEETS.INPUT.STATUSES.SIGNED_AUTOSIGN &&
!fileIdsToSkip.includes(fileId) &&
( !onlyTheseLearnerNames || onlyTheseLearnerNames.includes( recordLearnerName ) ) ) {
//select the cell so user can follow where we are
if( !ui.FAKE_MODE ) {
inputSheet.setActiveSelection( inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_STATUS_BAR,
recordColumnNo )
);
}
//refresh the updated date on file data on both sheets
UpdateFileInfoInWorkbook( spreadsheet, inputSheet, null, recordNo, DriveApp.getFileById( fileId ), false );
fileIdsChecked.push( fileId );
}
}
return fileIdsChecked;
}
/**
* [lsa-utils.gs]
* Loops through each of the 25 records on the Input sheet that have status of Sent to Learner,
* except for those records who'se fileid is in fileIdsToSkip.
* keeps track of which are signed and which are still unsigned in the optional array parms, stillUnsignedFileIds and newlySignedFileIds
* Also updates the spreadsheet to save the file info on both Input and My Files Sheets which in turn refreshes status bar to be up to
* date
* @param spreadsheet {Spreadsheet=} The spreadsheet containing the My Files sheet
* @param myFilesSheet {Sheet=} The My Files sheet to check
* @param ui {UserInterface=} The ui opject if there is one
* @param fileIdsToSkip {String[]=} Array of fileids not to bother checking
* @param onlyTheseLearnerIds {String[]=} Array of Learner IDs to filter by. pass null to apply no filter and check all learners
* @return filesCheckedFileIDs {String[]} The File IDs of all the files actually checked
*/
function CheckForSignatures_MyFilesSheet( spreadsheet, inputSheet, myFilesSheet, ui, fileIdsToSkip, onlyTheseLearnerIds ) {
//parse params
spreadsheet = (spreadsheet) ? spreadsheet : SpreadsheetApp.getActive();
inputSheet = ( inputSheet ) ? inputSheet : spreadsheet.getSheetByName( SHEETS.INPUT.NAME );
myFilesSheet = (myFilesSheet) ? myFilesSheet : spreadsheet.getSheetByName( SHEETS.MY_FILES.NAME );
ui = (ui) ? ui : SpreadsheetApp.getUi();
fileIdsToSkip = (fileIdsToSkip) ? fileIdsToSkip : new Array();
//return array
var fileIdsChecked = new Array();
//switch UI to My Files Sheet
if( !ui.FAKE_MODE ) { spreadsheet.setActiveSheet(myFilesSheet, true); }
//find the row numbers where the status = unsigned
let unsignedRowNums = findAllInColumn( myFilesSheet,
SHEETS.MY_FILES.STATUSES.UNSIGNED,
SHEETS.MY_FILES.REFS.COL_NO_STATUS_BAR,
SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE,
SHEETS.MY_FILES.REFS.ROW_NO_LAST_FILE );
let rowFileId = null;
let rowLearnerId = null;
for (const rowNum of unsignedRowNums) {
rowFileId = myFilesSheet.getRange( rowNum, SHEETS.MY_FILES.REFS.COL_NO_USERS_FILE_ID ).getValue();
rowLearnerId = myFilesSheet.getRange( rowNum, SHEETS.MY_FILES.REFS.COL_NO_LEARNER_ID ).getValue();
if( !fileIdsToSkip.includes(rowFileId) && ( !onlyTheseLearnerIds || onlyTheseLearnerIds.includes( rowLearnerId ) ) ) {
//select the cell so user can follow where we are
if( !ui.FAKE_MODE ) {
myFilesSheet.setActiveSelection( myFilesSheet.getRange(
rowNum,
SHEETS.MY_FILES.REFS.COL_NO_STATUS_BAR )
);
}
//spreadsheet.toast( "Checking for signatures from "+rowLearnerName+" on row " + rowNum, 'Checking Row ' + rowNum );
//refresh the updated date on file data on both sheets
UpdateFileInfoInWorkbook( spreadsheet, inputSheet, myFilesSheet, null, DriveApp.getFileById( rowFileId ), false );
fileIdsChecked.push( rowFileId );
}
}
return fileIdsChecked;
}
/**
* [lsa-utils.gs]
* Generate PDFs for all 'To Send'/'To Save' Records from the list of record numbers passed in. For all of the Learners that we generate
* Records for, check all of their historic unsigned files to see if they have recently been signed. and then get a list of
* historic still-unsigned files for each learner then use this info to send 1email to each learner
* each email lists the newly generated files and the still-unsigned historic files to prompt them to sign all
* @param recordNumList {Array[Integer]=} Array of record numbers (or null for ALL record numbers)
* @param spreadsheet {Spreadsheet=} The Spreadsheet
* @param inputSheet {Sheet=} The Input Sheet for the Spreadsheet
* @param myFilesSheet {Sheet=} The My Files Sheet for the Spreadsheet
* @param ui {UserInterface=} The ui object to use
*/
function ExportToSendRoSsFromList( recordNumList, spreadsheet: GoogleAppsScript.Spreadsheet.Spreadsheet,
inputSheet, myFilesSheet, ui ) {
//parse params
spreadsheet = ( spreadsheet ) ? spreadsheet : SpreadsheetApp.getActive();
inputSheet = ( inputSheet ) ? inputSheet : spreadsheet.getSheetByName(SHEETS.INPUT.NAME);
myFilesSheet = ( myFilesSheet ) ? myFilesSheet : spreadsheet.getSheetByName(SHEETS.MY_FILES.NAME);
ui = ( ui ) ? ui : SpreadsheetApp.getUi();
if( !isAuthorised_( spreadsheet, ui, null, true, true, true, false ) ) { return false; }
Logger.log( "isAuthorised_" );
if( !recordNumList ) {
//empty array means dont export any, null or undefined means export all of them
recordNumList = new Array();
for( let i = 1; i <= SHEETS.INPUT.REFS.COL_NO_RECORD_LAST - SHEETS.INPUT.REFS.COL_NO_RECORD_1 + 1 ; i++ ) {
recordNumList.push( i );
}
}
Logger.log( "recordNumList = " + recordNumList );
//switch to input sheet so user can see which record is being worked on
if( !ui.FAKE_MODE ){ spreadsheet.setActiveSheet(inputSheet, true); }
Logger.log( "spreadsheet.getActiveSheet().getName() = " + spreadsheet.getActiveSheet().getName() ); //
if( validateInputSheetFields( inputSheet, ui, null ) ) {
// ***** FIRST GENERATE THE RECORDS OF SUPPORT ON THE INPUT SHEET AND KEEP TRACK OF WHCH ONES WE'VE GENRATED *****
//keep track of what happened as we look through each of the Records of Support
let couldntExportErrors = "";
let learnerNamesToEmail: Array<string> = new Array();
let learnerNamesToSkip: Array<string> = new Array();
let learnerIdsToEmail = new Array(); //mirrors the above array
let learnerEmailAddressesUsed = new Array(); //mirrors the above array but gets populated right at the end
let newFileIDsToEmailFlatList = Array(); //1d array [i]
let newFileRecordNosToEmailByFileId = {};
let noOfRecordsGenerated = 0;
let alreadyRefreshedLearnerSheetFromMaster = false;
//loop through each of the records 1 through 25
let recordNo = -1;
let recordStatus = null;
let recordLearnerName = null;
let recordLearnerId = null;
let exportedFileId = null;
for( var i = 0 ; i < recordNumList.length ; i++ ) {
recordNo = recordNumList[i];
//get info about record that we need from Input Sheet
recordStatus = inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_STATUS_BAR,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + recordNo - 1
).getValue();
recordLearnerName = inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_LEARNER_NAME,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + recordNo - 1
).getValue();
recordLearnerId = inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_LEARNER_ID,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + recordNo - 1
).getValue();
//either export it or add a message to the error feedback for the user
if( recordStatus == SHEETS.INPUT.STATUSES.UNSENT || recordStatus == SHEETS.INPUT.STATUSES.UNSENT_AUTOSIGN ) {
//select the cell so user can follow where we are
if( !ui.FAKE_MODE ) {
inputSheet.setActiveSelection( inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_STATUS_BAR,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + recordNo - 1 )
);
}
//if first one, refresh learner data in case sign types have changed or in case sorted signature
//images have just come in
if( !alreadyRefreshedLearnerSheetFromMaster ) {
uiSensitiveToast( spreadsheet, ui,
"Checking for recent Stored Signature updates",
"Refreshng Learners" );
RefreshSettingsLearnerSheetDataFromMasterDatabaseFromChild( spreadsheet, ui, null, false );
alreadyRefreshedLearnerSheetFromMaster = true;
}
//geenrate PDF onto shared drive
exportedFileId = null;
try{
exportedFileId = ExportOneRoSRecord( recordNo, ui, learnerNamesToEmail, learnerNamesToSkip );
}
catch( e ) {
debugCatchError( e );
ui.alert( "Issue exporting Record" + recordNo, "Export failed for record " + recordNo + "\n\nThis is normally a one-off and nothing to worry about." +
"The record will be exported next time you Generate Records of Support.\n\nPress OK to continue.\n\n\n\n" +
"Error Details:\n" + e,
ui.ButtonSet.OK );
}
//if it worked, update the tracking variables.
if( exportedFileId != null ) {
noOfRecordsGenerated++;
//add the learner and the file to to the lists of files by learner
if( recordStatus != SHEETS.INPUT.STATUSES.UNSENT_AUTOSIGN ) {
if( !learnerNamesToEmail.includes( recordLearnerName ) ) {
learnerNamesToEmail.push( recordLearnerName );
learnerIdsToEmail.push( recordLearnerId );
}
newFileIDsToEmailFlatList.push( exportedFileId );
newFileRecordNosToEmailByFileId[ exportedFileId ] = recordNo;
}
}
else
{
couldntExportErrors += " - Record " + recordNo + " - EXPORT " +
( learnerNamesToSkip.includes( recordLearnerName ) ? "SKIPPED\n" : "FAILED - please try again\n" );
}
}
else if( recordStatus == SHEETS.INPUT.STATUSES.SAVED_EMAILWAIT ) {
//this is a previously saved record where the email failed to send so we'll pick this up as if weve just saved it
//adding it to the list of files and learners that we're going to email
//add the learner and the file to to the lists of files by learner
if( !learnerNamesToEmail.includes( recordLearnerName ) ) {
learnerNamesToEmail.push( recordLearnerName );
learnerIdsToEmail.push( recordLearnerId );
}
let tempFileId = inputSheet.getRange(
SHEETS.INPUT.REFS.ROW_NO_FILE_ID,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + recordNo - 1
).getValue();
newFileIDsToEmailFlatList.push( tempFileId );
newFileRecordNosToEmailByFileId[ tempFileId ] = recordNo;
}
else if( recordStatus != SHEETS.INPUT.STATUSES.SIGNED && recordStatus != SHEETS.INPUT.STATUSES.SIGNED_AUTOSIGN &&
recordStatus != SHEETS.INPUT.STATUSES.UNSIGNED && recordStatus != SHEETS.INPUT.STATUSES.BLANK ) {
//if it's none of the usual statuses then it must be an error message
couldntExportErrors += " - Record " + recordNo + " - " + recordStatus + "\n";
}
}
//VARIABLES PASSED ON TO NEXT SECTION
//couldntExportErrors //Logger.log( "couldntExportErrors = " + couldntExportErrors );
//learnerNamesFound //Logger.log( "learnerNamesFound = " + learnerNamesFound );
//newFileIDsFlatList //Logger.log( "newFileIDsFlatList = " + newFileIDsFlatList );
//newFileRecordNosByFileId //Logger.log( "newFileRecordNosByFileId = " + newFileRecordNosByFileId );
if( learnerNamesToEmail && learnerNamesToEmail.length > 0 ) {
// ***** NEXT CHECK FOR SIGNATURES ON INPUT SHEET (SKIP THE JUST GENERATED FILES TO SAVE TIME) *****
uiSensitiveToast( spreadsheet, ui,
"Checking for today's signatures from these learners:\n"+learnerNamesToEmail,
"Checking Today's Signatures" );
let fileIdsCheckedForSignatures = CheckForSignatures_InputSheet( spreadsheet, inputSheet, ui,
newFileIDsToEmailFlatList, learnerNamesToEmail);
//VARIABLES PASSED ON TO NEXT SECTION
//couldntExportErrors //Logger.log( "couldntExportErrors = " + couldntExportErrors );
//learnerNamesFound //Logger.log( "learnerNamesFound = " + learnerNamesFound );
//newFileIDsFlatList //Logger.log( "newFileIDsFlatList = " + newFileIDsFlatList );
//newFileRecordNosByFileId //Logger.log( "newFileRecordNosByFileId = " + newFileRecordNosByFileId );
//fileIdsCheckedForSignatures //Logger.log( "fileIdsCheckedForSignatures = " + fileIdsCheckedForSignatures );
// ***** NEXT CHECK FOR SIGNATURES ON MY FILES SHEET (SKIP THE JUST GENERATED FILES AND JUST CHECKED FILES TO SAVE TIME) *****
uiSensitiveToast( spreadsheet, ui,
"Checking for signatures on old Records from these learners:\n"+learnerNamesToEmail,
"Checking Historic Signatures", 10 );
let fileIdsToExclude = CloneArray_ShallowCopy( newFileIDsToEmailFlatList ).concat( fileIdsCheckedForSignatures );
fileIdsCheckedForSignatures = fileIdsCheckedForSignatures.concat(
CheckForSignatures_MyFilesSheet( spreadsheet, inputSheet, myFilesSheet, ui, fileIdsToExclude, learnerIdsToEmail )
);
//VARIABLES PASSED ON TO NEXT SECTION
//couldntExportErrors
Logger.log( "couldntExportErrors = " + couldntExportErrors );
//learnerNamesToEmail
Logger.log( "learnerNamesToEmail = " + learnerNamesToEmail );
//learnerIdsToEmail
Logger.log( "learnerIdsToEmail = " + learnerIdsToEmail );
//newFileIDsFlatList
Logger.log( "newFileIDsFlatList = " + newFileIDsToEmailFlatList );
//newFileRecordNosByFileId
Logger.log( "newFileRecordNosByFileId = " + newFileRecordNosToEmailByFileId );
//fileIdsCheckedForSignatures
Logger.log( "fileIdsCheckedForSignatures = " + fileIdsCheckedForSignatures );
// ***** NOW QUERY THE MY FILES SHEET STATUS COLUMN TO POPULATE ARRAYS OF ONES ARE STILL UNSIGNED BY LEAERNER ID *****
uiSensitiveToast( spreadsheet, ui, "Collecting data ready for sending emails", "Preparing Emails", 15 );
let newFilesByLearnerId = new Array(); //2d array, [learner name][i]
let oldUnsignedFilesByLearnerId = new Array(); //2d array, [learner name][i]
const dataRowOffset = SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME;
let myFilesRow = null;
let thisStatus = null;
let thisFileId = null;
let thisLearnerId = null;
let thisFileStruct = null;
let mostRecentSignType = null;
var allMyFilesData = myFilesSheet.getRange( SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE, SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME,
SHEETS.MY_FILES.REFS.ROW_NO_LAST_FILE - SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE + 1,
SHEETS.MY_FILES.REFS.COL_NO_SIGN_TYPE - SHEETS.MY_FILES.REFS.COL_NO_FILE_NAME + 1
).getValues();
for ( let rowIndex = 0; rowIndex < allMyFilesData.length; rowIndex++ ) {
myFilesRow = allMyFilesData[rowIndex];
thisFileId = myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_USERS_FILE_ID - dataRowOffset ];
if( newFileIDsToEmailFlatList.includes( thisFileId ) ) {
//WE'VE FOUND A FILE THAT WAS JUST CREATED SO IT GOES IN THE JUST CREATED LIST (WE KNOW ITS UNSIGNED AS ITS JUST CREATED)
//create an object that represents the file
thisFileStruct = {
id : thisFileId,
lessonName : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LESSON_NAME - dataRowOffset ],
lessonTimesObj : getlessonTimesObjectFromMyFilesSheetValues(
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LESSON_DATE - dataRowOffset ],
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_START_TIME - dataRowOffset ],
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_DURATION - dataRowOffset ]
),
signType : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_SIGN_TYPE - dataRowOffset ],
email : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LEARNER_EMAIL - dataRowOffset ],
url : DriveApp.getFileById( thisFileId ).getUrl(),
recordNo : newFileRecordNosToEmailByFileId[ thisFileId ]
};
//add the file object to the 2D list of files by Learner Name
thisLearnerId = myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LEARNER_ID - dataRowOffset ];
if( !newFilesByLearnerId[ ""+thisLearnerId ] ) { newFilesByLearnerId[ ""+thisLearnerId ] = new Array(); }
newFilesByLearnerId[ ""+thisLearnerId ].push( thisFileStruct );
}
else if( fileIdsCheckedForSignatures.includes( thisFileId ) ) {
//WE'VE FOUND A FILE THAT WAS JUST CHECKED FOR UPDATES SO IT GOES IN THE OLD FILES LIST (BUT ONLY IF STILL UNSIGNED)
thisStatus = myFilesSheet.getRange( SHEETS.MY_FILES.REFS.ROW_NO_FIRST_FILE + rowIndex,
SHEETS.MY_FILES.REFS.COL_NO_STATUS_BAR ).getValue();
if( thisStatus == SHEETS.MY_FILES.STATUSES.UNSIGNED ) {
//create an object that represents the file
thisFileStruct = {
id : thisFileId,
lessonName : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LESSON_NAME - dataRowOffset ],
lessonTimesObj : getlessonTimesObjectFromMyFilesSheetValues(
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LESSON_DATE - dataRowOffset ],
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_START_TIME - dataRowOffset ],
myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_DURATION - dataRowOffset ]
),
signType : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_SIGN_TYPE - dataRowOffset ],
email : myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LEARNER_EMAIL - dataRowOffset ],
url : DriveApp.getFileById( thisFileId ).getUrl()
};
//add the file object to the 2D list of files by Learner Name
thisLearnerId = myFilesRow[ SHEETS.MY_FILES.REFS.COL_NO_LEARNER_ID - dataRowOffset ];
if( !oldUnsignedFilesByLearnerId[ ""+thisLearnerId ] ) { oldUnsignedFilesByLearnerId[ ""+thisLearnerId ] = new Array(); }
oldUnsignedFilesByLearnerId[ ""+thisLearnerId ].push( thisFileStruct );
}
}
}
//VARIABLES PASSED ON TO NEXT SECTION
//couldntExportErrors //Logger.log( "couldntExportErrors = " + couldntExportErrors );
//learnerNamesFound //Logger.log( "learnerNamesFound = " + learnerNamesFound );
//newFileIDsFlatList //Logger.log( "newFileIDsFlatList = " + newFileIDsFlatList );
//newFileRecordNosByFileId //Logger.log( "newFileRecordNosByFileId = " + newFileRecordNosByFileId );
//fileIdsCheckedForSignatures //Logger.log( "fileIdsCheckedForSignatures = " + fileIdsCheckedForSignatures );
// ***** NOW SEND EMAILS TO EACH OF THE LEARNERS TOUCHED ABOVE *****
//before we switch back to input sheet load the email blobs into memory as this takes a while and the previous toast is still
//relevant here
EnsureLearnerEmailBlobsLoaded_(); //takes a while to run
SpreadsheetApp.flush(); //takes a while and ensures that the spreadsheet is up to date when the user is staring at input sheet
//Switch back view to the Input Sheet
if( !ui.FAKE_MODE ) { spreadsheet.setActiveSheet( inputSheet, true ); };
uiSensitiveToast( spreadsheet, ui, "Emailing the following Learners:\n" + learnerNamesToEmail, "Emailing Learners" );
//Send Learner Emails
learnerEmailAddressesUsed = new Array();
var emailTemplate = HtmlService.createTemplateFromFile('html/html-email-learner-tosign');
const lSAName = inputSheet.getRange( SHEETS.INPUT.REFS.LSA_NAME.ROW_NO,SHEETS.INPUT.REFS.LSA_NAME.COL_NO ).getValue();
let learnerSheet = spreadsheet.getSheetByName( SHEETS.SETTINGS_LEARNERS.NAME );
let globalSettingsSheet = spreadsheet.getSheetByName( SHEETS.GLOBAL_SETTINGS.NAME );
let learnerWebappDeployId = globalSettingsSheet.getRange (
SHEETS.GLOBAL_SETTINGS.REFS.ROW_NO_WEBAPP_LEARNER_DEPLOYID,
SHEETS.GLOBAL_SETTINGS.REFS.COL_NO
).getValue();
let learnerObj = null;
let thisSendEmailAddress = null;
let foundLearnerName = null; let foundLearnerId = null;
let learnerFriendlyName = null;
for( let li=0; li < learnerNamesToEmail.length; li++ ) {
foundLearnerName = learnerNamesToEmail[ li ];
learnerFriendlyName = foundLearnerName;
foundLearnerId = learnerIdsToEmail[ li ];
//find learner email address from learner Sheet - if it doesnt exist (ie learner record deleted), then revert back
//to the most recent email address from the My Files sheet
learnerObj = getChildLearnerObjByLearnerIdFromSameVersionSource_( spreadsheet, learnerSheet, foundLearnerId, null );
if( learnerObj != null ) {
thisSendEmailAddress = learnerObj.EMAIL_ADDRESS;
learnerFriendlyName = ( learnerObj.NICKNAME ) ? learnerObj.NICKNAME : learnerObj.FORENAME;
}
else {
//no need to check newFilesByLearner as if we've just geenrated a new file for this learner
//then the email address will DEFFO have been found above.
thisSendEmailAddress = oldUnsignedFilesByLearnerId[foundLearnerId][0].email;
}
learnerEmailAddressesUsed.push( thisSendEmailAddress );
//send email
SendLearnerSignEmail( spreadsheet, newFilesByLearnerId[""+foundLearnerId], oldUnsignedFilesByLearnerId[""+foundLearnerId],
thisSendEmailAddress, foundLearnerName, learnerFriendlyName, lSAName, ""+foundLearnerId,
learnerObj.SIGN_TYPE, learnerObj.SIGNATURE_ID, false, learnerWebappDeployId, emailTemplate );
//flag email as sent in the Input Sheet
//FIND ALL newFilesByLearner FILES for this Learner on the Input Sheet and mark them as email sent
let newFilesEmailed = newFilesByLearnerId[""+foundLearnerId];
for( let nfi=0; nfi < newFilesEmailed.length; nfi++ ) {
inputSheet.getRange( SHEETS.INPUT.REFS.ROW_NO_LEARNER_EMAILED,
SHEETS.INPUT.REFS.COL_NO_RECORD_1 + newFilesEmailed[nfi].recordNo - 1 ).setValue( "Yes" );
}
SpreadsheetApp.flush();
}
}
//VARIABLES PASSED ON TO NEXT SECTION
//couldntExportErrors //Logger.log( "couldntExportErrors = " + couldntExportErrors );
//learnerNamesFound //Logger.log( "learnerNamesFound = " + learnerNamesFound );
//learnerEmailAddressesUsed //Logger.log( "learnerEmailAddressesUsed = " + learnerEmailAddressesUsed );
// ***** FEEDBACK ONCE FILES HAVE BEEN SENT *****
//emailed lerners feedback
let learnersEmailedFeedback = ( noOfRecordsGenerated == 0 ) ? "" : "\nThe following learners have been emailed:\n";
for( let i=0; i<learnerNamesToEmail.length ; i++ ) {
learnersEmailedFeedback += " - " + learnerNamesToEmail[i] + " (" +
substututeIfPlaceholderEmailAddress_( learnerEmailAddressesUsed[i] ) + ")\n";
}
//records skipped feedback
let recordErrorsFeedback = ( couldntExportErrors=="" )
? "" : ( "\nThe following Records could not be generated because of missing information:\n" + couldntExportErrors );
//feedback to user
ui.alert(
"Finished Sending Records",
"A total of " + noOfRecordsGenerated + " Record" + ( noOfRecordsGenerated == 1 ? "" : "s" ) + " of Support " +
( noOfRecordsGenerated == 1 ? "was" : "were" ) + " saved on the shared drive.\n" +
learnersEmailedFeedback +
recordErrorsFeedback,
ui.ButtonSet.OK);
}
}
/**
* [lsa-utils.gs]
* sheet-defs.gs contains data about default field values for some of the sheets. Use this function when you want to set the values of
* some of the cells on a sheet to these defult values. The default field defs are split up into seperate sections to allow updating
* around locked cells whilst writing all ranges in one go for efficiency
* This function appends row and height data to each of the sections (each defaultDefList) passed in defaultDefListArray
* It then returns the default data array ready to be saved later using saveDataRangeValues
* @param sheetRefsObject {Object} from the sheet-defs listing which rows are on which row numbers
* @param defaultDefListArray {Object} An Array of Section Field Lists, Each Section Field Lists gets annotated with row and height data
* @return rangesArray {Array} An array of arrays of objects (one per section) holding the default values ready to write to spreadsheet
*/
function getDataArraysFromDefaultsDef( sheetRefsObject, defaultDefListArray ) {
let defaultDefList = null;
let defaultFieldDef = null;
let fieldName = null;;
let fieldDefaultValue = null;
let row = null;
let height = null;
//loop through each def list and then each field in the list creating an array of default values as we go
let rangesArray = new Array();
let rangeFieldsArray = null;
for( let d=0; d < defaultDefListArray.length; d++ ) {
rangeFieldsArray = new Array();
defaultDefList = defaultDefListArray[d];
height = 0;
for( let i=0; i < defaultDefList.length; i++ ) {
defaultFieldDef = defaultDefList[i];
fieldName = defaultFieldDef[0];
fieldDefaultValue = defaultFieldDef[1];
if( i==0 ) {
row = sheetRefsObject[ 'ROW_NO_'+fieldName ];
defaultDefList.ROW = row;
}
if( fieldDefaultValue === null ) { //its a list of checkboxes
height += sheetRefsObject[ 'ROW_NO_'+fieldName.substring(0, fieldName.length-5)+"LAST" ] - row + 1;
for( let j=0; j<height; j++ ) { rangeFieldsArray.push( [ false ] ); }
}
else { //its just a single field
height += 1;
rangeFieldsArray.push( [ fieldDefaultValue ] );
}
}
defaultDefList.HEIGHT = height;
rangesArray.push( rangeFieldsArray )
}
return rangesArray;
}
/**
* [lsa-utils.gs]
* See: getDataArraysFromDefaultsDef documentation for more information
* This function saves the default data array sections back to the sheet at column columnNo using saveDataRangeValues
* @param defaultDefListArray {Object} An Array of Section Field Lists, Each Section Field Lists gets annotated with row and height data
* @param rangesValuesArray {Array<Array<Array<Object>>>} An array of arrays of objects (one per section) holding the default values ready to write
* @param sheet {GoogleAppsScript.Spreadsheet.Sheet} the sheet to write to
* @param columnNo {number} the column number to write to
* @param upUntilThisColumnNo {number=} OPTIONAL If you use this parameter it will update a 2d range of many columns all at once
* @param rowOffset {number} If the form you are saving to is lower (+) or higher (-) than the data definitions, 0 if not.
*/
function saveDataRangeValues( defaultDefListArray,
rangesValuesArray: Array<Array<Array<Object>>>, sheet: GoogleAppsScript.Spreadsheet.Sheet,
columnNo: number, upUntilThisColumnNo: number|null, rowOffset: number ) {
//Parse Params
upUntilThisColumnNo = (upUntilThisColumnNo) ? upUntilThisColumnNo : columnNo;
let defaultDefList = null;
for( let d=0; d < defaultDefListArray.length; d++ ) {
defaultDefList = defaultDefListArray[d];
for( let i=columnNo; i < upUntilThisColumnNo; i++ ) { //duplicate values if >1 column
for( let f=0; f<rangesValuesArray[d].length; f++ ) {
rangesValuesArray[d][f].push( rangesValuesArray[d][f][0] );
}
}
sheet.getRange(
defaultDefList.ROW+rowOffset, columnNo,
defaultDefList.HEIGHT, upUntilThisColumnNo-columnNo + 1
).setValues( rangesValuesArray[d] );
}
}
/**
* [lsa-utils.gs]
* sheet-defs.gs contains data about default field values for some of the sheets. Use this function when you want to copy the values
* for these fields from one sheet to another (or from one column to another)
* The default field defs are split up into seperate sections to allow updating
* around locked cells whilst writing all ranges in one go for efficiency. The calso contain default value definitions
* but these are ignored as we are not using default values we are reading real values
* This function appends row and height data to each of the sections (each defaultDefList) passed in defaultDefListArray
* It then returns the data array array ready to be saved elsewhere later using saveDataRangeValues
* @param sheetRefsObject {Object} from the sheet-defs listing which rows are on which row numbers
* @param sheet {GoogleAppsScript.Spreadsheet.Sheet} The sheet to load the data from
* @param columnNo {number} The number fo the column to load the data from
* @param defaultDefListArray {Array} An Array of Section Field Lists, Each Section Field Lists gets annotated with row and height data
* @param rowOffset {number} If the form you are loading from is lower (+) or higher (-) than the data definitions, 0 if not.
* @return {Array<Array<Array<object>>>} An array of 2D arrays of objects (one per section) holding the default values ready to write to spreadsheet
*/
function loadDataArraysFromSheet( sheetRefsObject: Object, sheet: GoogleAppsScript.Spreadsheet.Sheet,
columnNo: number, defaultDefListArray, rowOffset: number ) {
let thisDefList = null;
let thisFieldDef: Array<string> = null;
let fieldName: string = "";
let fieldDefaultValue: Object|null = null;
let row: number = -1;
let height: number = -1;
//loop through each def list and then each field in the list creating an array of default values as we go
let valueRangesArray: Array<Array<Array<object>>> = new Array();
let sheetRangeArray: Array<GoogleAppsScript.Spreadsheet.Range> = new Array();
let rangeFieldsArray = null;
for( let d=0; d < defaultDefListArray.length; d++ ) {
rangeFieldsArray = new Array();
thisDefList = defaultDefListArray[d];
height = 0;
for( let i=0; i < thisDefList.length; i++ ) {
thisFieldDef = thisDefList[i];
fieldName = thisFieldDef[0];
fieldDefaultValue = thisFieldDef[1];
if( i==0 ) {
row = sheetRefsObject[ 'ROW_NO_'+fieldName ];
thisDefList.ROW = row;
}
if( fieldDefaultValue === null ) { //its a list of checkboxes
height += sheetRefsObject[ 'ROW_NO_'+fieldName.substring(0, fieldName.length-5)+"LAST" ] - row + 1;
}
else { //its just a single field
height += 1;
}
}
thisDefList.HEIGHT = height;
sheetRangeArray.push( sheet.getRange( thisDefList.ROW + rowOffset, columnNo, height, 1 ) );
}
//now read all data in one go
for( let r=0; r<sheetRangeArray.length; r++ ) {
valueRangesArray.push( sheetRangeArray[r].getValues() );
}
return valueRangesArray;
}
interface lessonTimes {
start: Date,
end: Date,
duration: number
};
function getlessonTimesObjectFromInputSheetValues( lessonDate: Date, startTime: string, duration: string ) {
let lessonTimes: lessonTimes = {
start: null ,
end: null,
duration: 0,
}
let dateString = Utilities.formatDate( lessonDate, GLOBAL_CONSTANTS.TIMEZONE, "dd MMMM yyyy" );
//start time
lessonTimes.start = new Date( dateString + " " + startTime.slice(0, -1) + " " + startTime.slice(-1)+"M" );
//duration
let indexOfH = duration.indexOf( "h" );
let indexOfM = duration.indexOf( "m" );
if( indexOfH >= 0) {
lessonTimes.duration += 60 * parseInt( duration.substr( indexOfH-1, 1 ), 10 );
}
if( indexOfM >= 0) {
lessonTimes.duration += parseInt( duration.substr( indexOfM-2, 2 ), 10 );
}
//end time
lessonTimes.end = new Date( lessonTimes.start.getTime() + lessonTimes.duration * 60000 );
return lessonTimes;
}
function getlessonTimesObjectFromMyFilesSheetValues( lessonDate: Date, startTime: Date, duration ) {
let startTimeMillis = lessonDate.getTime() + startTime.getHours() * 1000*60*60 + startTime.getMinutes() * 1000*60 +
startTime.getSeconds() * 1000 + startTime.getMilliseconds();
let endTimeMillis = startTimeMillis + duration * 1000 * 60;
let lessonTimes: lessonTimes = {
start: new Date( startTimeMillis ),
end: new Date( endTimeMillis ),
duration: duration,
};
return lessonTimes;
}
|
ce09c01cc722df90ff6b47fd66e3e9662dc3ec85
|
TypeScript
|
baijiadu/auktionator
|
/client/cordova/app/util/util.ts
| 2.8125
| 3
|
export const Util = {
generateRandomStr(start) {
start = start || 2;
return Math.random().toString(36).substring(start);
},
isIdNumber(idNumber) {
if (!/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(idNumber)) return '่บซไปฝ่ฏๅทๆ ผๅผไธๆญฃ็กฎ';
const idNumberWi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
idNumberY = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];
let idNumberWiSum = 0;
if (idNumber.length != 18) return '่ฏท่พๅ
ฅๆๆ็่บซไปฝ่ฏๅท';
for (var i = 0; i < 17; i++) {
idNumberWiSum += idNumber.substring(i, i + 1) * idNumberWi[i];
}
const idNumberMod = idNumberWiSum % 11, idNumberLast = idNumber.substring(17);
if (idNumberMod == 2) {
if (idNumberLast.toUpperCase() != 'X') return '่ฏท่พๅ
ฅๆๆ็่บซไปฝ่ฏๅท';
} else {
if (idNumberLast != idNumberY[idNumberMod]) return '่ฏท่พๅ
ฅๆๆ็่บซไปฝ่ฏๅท';
}
return 'yes';
}
};
|
cebdc915ffae1d48421a28b2ad954e55d4aa885d
|
TypeScript
|
HanRenHui/react-eleme
|
/src/store/reducer/user.ts
| 2.734375
| 3
|
import { Action } from '../../interface/user'
import { fromJS } from 'immutable'
import * as types from '../action-types'
const defaultState = fromJS({
userinfo: null,
address: []
})
export default function reducer(state=defaultState, action: Action) {
switch(action.type) {
case types.SET_USER_INFO:
return state.set('userinfo', fromJS(action.payload))
case types.LOG_OUT:
return state.set('userinfo', null)
case types.EDIT_NAME:
return state.setIn(['userinfo', 'name'], action.payload)
case types.UPDATE_ADDRESS:
return state.set('address', fromJS(action.payload))
default:
return state
}
}
|
55e8e2c2f3ea2120a245e199303a6f96cb057108
|
TypeScript
|
gary837837/EPGStation
|
/src/server/DBRevisionChecker.ts
| 2.578125
| 3
|
import * as fs from 'fs';
import * as path from 'path';
import Base from './Base';
import DBRevisionInfo from './DBRevisionInfoInterface';
import DBTableBase from './Model/DB/DBTableBase';
import MigrationBase from './Model/DB/MigrationBase';
import factory from './Model/ModelFactory';
/**
* DBRevisionChecker
*/
class DBRevisionChecker extends Base {
private migrations: MigrationBase[] = [];
private infoFilePath: string;
private dbInfo: DBRevisionInfo | null = null;
private currentRevision = 0;
public constructor() {
super();
this.migrations.push(<MigrationBase> factory.get('MigrationV1'));
this.migrations.push(<MigrationBase> factory.get('MigrationV2'));
this.migrations.push(<MigrationBase> factory.get('MigrationV3'));
this.migrations.push(<MigrationBase> factory.get('MigrationV4'));
this.migrations.push(<MigrationBase> factory.get('MigrationV5'));
this.migrations.push(<MigrationBase> factory.get('MigrationV6'));
this.migrations.push(<MigrationBase> factory.get('MigrationV7'));
this.migrations.push(<MigrationBase> factory.get('MigrationV8'));
this.migrations.push(<MigrationBase> factory.get('MigrationV9'));
this.infoFilePath = this.config.getConfig().dbInfoPath || path.join(__dirname, '..', '..', 'data', 'dbinfo.json');
this.readFile();
// set currentRevision
for (const migration of this.migrations) {
if (migration.revision > this.currentRevision) {
this.currentRevision = migration.revision;
}
}
}
/**
* DB version check & upgrade
*/
public async run(): Promise<void> {
// DB ๆ
ๅ ฑใใชใ
if (this.dbInfo === null) {
const servicesDB = <DBTableBase> factory.get('ServicesDB');
const programsDB = <DBTableBase> factory.get('ProgramsDB');
const rulesDB = <DBTableBase> factory.get('RulesDB');
const recordedDB = <DBTableBase> factory.get('RecordedDB');
const encodedDB = <DBTableBase> factory.get('EncodedDB');
const recordedHistoryDB = <DBTableBase> factory.get('RecordedHistoryDB');
// ๅ Table ใๅญๅจใใใ
const tableStatus = {
Services: await servicesDB.exists(),
Programs: await programsDB.exists(),
Rules: await rulesDB.exists(),
Recorded: await recordedDB.exists(),
Encoded: await encodedDB.exists(),
RecordedHistory: await recordedHistoryDB.exists(),
};
if (!tableStatus.Services && !tableStatus.Programs && !tableStatus.Rules && !tableStatus.Recorded && !tableStatus.Encoded && !tableStatus.RecordedHistory) {
// ๆฐ่ฆ
this.dbInfo = { revision: this.currentRevision };
this.writeFile();
this.log.system.info('create dbinfo.json');
return;
} else if (tableStatus.Services && tableStatus.Programs && tableStatus.Rules && tableStatus.Recorded && tableStatus.Encoded && !tableStatus.RecordedHistory) {
// version 0.5.9 ไปฅไธใใใฎใขใใใฐใฌใผใ
this.dbInfo = { revision: 0 };
this.log.system.info('upgrade from less than or equal to version 0.5.9');
} else {
// DB table ใๆฌ ๆใใฆใใ
this.log.system.fatal('DB table is missing.');
process.exit(1);
}
}
if (this.dbInfo === null) { return; }
for (const migration of this.migrations) {
if (migration.revision > this.dbInfo.revision) {
// DB upgrade ๅฆ็
this.log.system.info(`upgrade ${ this.dbInfo.revision } => ${ migration.revision }`);
try {
await migration.upgrade();
} catch (err) {
this.log.system.fatal('upgrade error');
this.log.system.fatal(err);
process.exit(1);
}
this.dbInfo.revision = migration.revision;
this.writeFile();
}
}
}
/**
* get current revision
* @return number
*/
public getCurrentRevision(): number {
return this.currentRevision;
}
/**
* get DBRevisionInfo
* @return DBRevisionInfo
*/
public getDBRevisionInfo(): DBRevisionInfo | null {
return this.dbInfo;
}
/**
* create new File
*/
public createNewFile(): void {
this.dbInfo = { revision: this.currentRevision };
this.writeFile();
}
/**
* DB revision ๆ
ๅ ฑใใใกใคใซใใ่ชญใฟ่พผใ
*/
private readFile(): void {
try {
const info: string | null = fs.readFileSync(this.infoFilePath, 'utf-8');
if (info === null) { throw new Error('db revision file is null'); }
this.dbInfo = JSON.parse(info);
} catch (e) {
if (e.code === 'ENOENT') {
this.log.system.warn('dbinfo.json is not found.');
this.dbInfo = null;
} else {
this.log.system.fatal(e);
this.log.system.fatal('dbinfo.json parse error');
process.exit(1);
}
}
}
/**
* DB revision ๆ
ๅ ฑใใใกใคใซใธๆธใ่พผใ
*/
private writeFile(): void {
if (this.dbInfo === null) {
this.log.system.fatal('dbInfo is null');
process.exit(1);
}
fs.writeFileSync(
this.infoFilePath,
JSON.stringify(this.dbInfo),
{ encoding: 'utf-8' },
);
}
}
export default DBRevisionChecker;
|
86881ae3b6f234d6f97c60e577d4f64f32d7e867
|
TypeScript
|
sYsguard/collie-cli
|
/src/db/meta.ts
| 2.546875
| 3
|
/**
* Contains meta information about the tenants in this directory.
* Can be used to perform some sort of migrations and or control when
* the last collection took place.
*/
export interface Meta {
version: number;
tenantCollection: {
lastCollection: string;
};
iamCollection?: {
lastCollection: string;
};
costCollection?: {
from: string;
to: string;
};
}
|
d53710e9ea1a2e4352b52a5c7d9d84e3b5ec990a
|
TypeScript
|
morgadodesarrollador/aturistico
|
/routes/usuario.ts
| 2.921875
| 3
|
import { Router, Request, Response } from 'express';
import { UsuarioModel } from '../models/usuario.model'
import bcrypt from 'bcrypt';
import Token from "../clases/tokens";
import { MDLcheckToken } from "../middleware/autenticacion";
const userRoutes = Router();
//Login
userRoutes.post('/login', (req: Request, res: Response) => {
//con email/pass, Contiene el objeto del POST
const body = req.body;
//buscamos el objeto, en el Modelo de Usuarios (colecciรณn),
// cuyo email sea igual al que llega por POST
UsuarioModel.findOne({ email: body.email }, (err, userDB) =>{
if (err) throw err; //err en la bd
if (!userDB) { //email no existe
return res.json({
ok: false,
mensaje: 'email/pass no son correctas'
})
}
//el email si existe en la BD, comparamos las contraseรฑas
//la pasada por el post en body.password y this.password en el mรฉtodo
//compararPassword
if (userDB.compararPassword(body.password)) {
//email existe y el password es el mismo.
//creamos el token en base a un payload (campos)
const tokenUser = Token.getJwtToken({
_id : userDB._id,
nombre : userDB.nombre,
email : userDB.email,
avatar : userDB.avatar
});
res.json ({
ok: true,
token : tokenUser
})
}else {
//emil existe y password errรกneo
return res.json({
ok: false,
mensaje: 'pass no son correctas'
})
}
});
});
//crear usuario
userRoutes.post ('/create', (req:Request, res:Response) => {
const user = { //info del objeto user del POST a travรฉs del body parser
nombre : req.body.nombre,
email : req.body.email,
password : bcrypt.hashSync(req.body.password, 10),
avatar : req.body.avatar
};
UsuarioModel.create( user ) //regresa una Promesa
.then (userDB => { //caso de insercciรณn OK, respondemos ...
const tokenUser = Token.getJwtToken({
_id : userDB._id,
nombre : userDB.nombre,
email : userDB.email,
avatar : userDB.avatar
});
res.json({
ok: true,
user: tokenUser
})
}).catch ( err => { //error de la promesa
res.json ({
ok: false,
err
})
})
});
//MDLcheckToken es una F.MDLW que se ejecuta antes que /update
// [ fmdlw1, fmdlw2...]
userRoutes.post ('/update', MDLcheckToken, (req:any, res:Response) => {
//cuando llega aquรญ, el token ha sido verificado y en el viene el id del usuario
//y poder hacer la consulta a mongodb
const user = { //campos a modificar del usuario
nombre: req.body.nombre || req.usuario.nombre,
email: req.body.email || req.usuario.email,
avatar: req.body.avatar || req.usuario.avatar,
};
//req.usuario._id: sale del token correpondiente al usuario q modifica sus datos
//in: _id, user, 'regresar reg actualizado, callback
UsuarioModel.findByIdAndUpdate(req.usuario._id, user, {new: true},
(err, userDB: any) => {
if ( err ) throw err; //error grave de BD
if (!userDB)
res.json({
ok:false,
msg: 'Usuario con ese id no encontrado'
})
//el usuario existe, y hay q actualizar el nuevo token
const tokenUser = Token.getJwtToken({
_id : userDB._id,
nombre : userDB.nombre,
email : userDB.email,
avatar : userDB.avatar
});
res.json({
ok: true,
user: userDB,
token: tokenUser
})
})
});
userRoutes.get ('/prueba', (req:Request, res:Response) => {
res.json({
ok: true,
mensaje: 'Todo funciona ok'
})
});
export default userRoutes;
|
3964d4ce98552e18b7de5dc68f87109279a16929
|
TypeScript
|
choyongjoon/life-in-weeks
|
/src/models/Life.ts
| 3.15625
| 3
|
import { isNil, range } from 'lodash'
import Week from './Week'
import Year from './Year'
export default class Life {
public static maxNumYears = 200
public dob: string
public lifeExpectancy: number
public years: Year[]
constructor(dob: string, lifeExpectancy: number) {
this.dob = dob
this.lifeExpectancy = lifeExpectancy
const lifeStart = new Date(dob)
if (isNaN(lifeStart.getTime())) {
this.years = []
return
}
const numYears = Math.min(lifeExpectancy, Life.maxNumYears)
this.years = range(numYears).map(i => new Year(i, lifeStart))
}
public findWeeks = (event: any) => {
const eventStart = new Date(event.start)
const eventEnd = new Date(event.end)
if (eventStart > eventEnd) return []
const startIndex = this.findIndex(eventStart)
const endIndex = this.findIndex(eventEnd)
if (!startIndex) return []
let weeksInRange: Week[] = []
const endYearIndex = endIndex ? endIndex.yearIndex : this.years.length - 1
for (let i = startIndex.yearIndex; i <= endYearIndex; i++) {
let startWeekIndex = 0
if (i === startIndex.yearIndex) startWeekIndex = startIndex.weekIndex
let endWeekIndex
if (i === endYearIndex && endIndex && !isNil(endIndex.weekIndex)) {
endWeekIndex = endIndex.weekIndex + 1
}
weeksInRange = weeksInRange.concat(
this.years[i].sliceWeeks(startWeekIndex, endWeekIndex)
)
}
return weeksInRange
}
public findIndex = (date: Date) => {
if (!this.years[0]) return null
const lifeStartYear = this.years[0].start.getFullYear()
const dateYear = date.getFullYear()
let yearIndex = dateYear - lifeStartYear
let year = this.years[yearIndex]
if (year && year.start > date) {
yearIndex -= 1
year = this.years[yearIndex]
}
if (!year) return null
const weekIndex = year.findIndex(date)
if (weekIndex === null) return null
return {
yearIndex,
weekIndex
}
}
public applyEvent = (event: any) => {
const weeks = this.findWeeks(event)
weeks.forEach(week => week.applyEvent(event))
}
}
|
838bccdfbb995445bebae41dfb5f97c07f958dbe
|
TypeScript
|
sebastianrachfal/next-article-explorer
|
/src/features/article/calls.ts
| 2.546875
| 3
|
import { ArticleData } from './interfaces';
import { ArticlePageData } from './pageInterfaces';
export const fetchArticleData = async (page: number = 1): Promise<ArticleData[]> => {
try {
let data = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/api/graphql`, {
method: 'POST',
body: ` makeRestCall {
get(path: "/articles?page=${page}") {
jsonBody
}
}`,
}).then((r) => r.json());
return data.makeRestCall.get.jsonBody;
} catch (err) {
throw new Error(err.message);
}
};
export const fetchArticle = async (id: number = 1): Promise<ArticlePageData> => {
try {
let data = await fetch(`${process.env.NEXT_PUBLIC_API_HOST}/api/graphql`, {
method: 'POST',
body: ` publishedArticle(id: ${id}) {
id
title
tags
socialImage
publishedTimestamp
positiveReactionsCount
comments {
nodes {
idCode
bodyHtml
user {
name
profileImage
}
children {
idCode
bodyHtml
user {
name
profileImage
}
children {
idCode
bodyHtml
user {
name
profileImage
}
}
}
}
}
user {
name
profileImage
}
bodyMarkdown
}`,
}).then((r) => r.json());
const article = data.publishedArticle;
article.comments = article.comments.nodes;
return article;
} catch (err) {
throw new Error(err.message);
}
};
|
70a714fb01ab191652beb5325924c887f62ea4a8
|
TypeScript
|
Pwera/Playground
|
/deno/nasa/api.ts
| 2.53125
| 3
|
import { Router } from "./deps.ts";
import * as planets from "./models/planets.ts";
import * as launches from "./models/launches.ts";
const router = new Router();
router.get("/", (ctx) => {
ctx.response.body = "NASA";
});
router.get("/planets", (ctx) => {
const response = planets.getAllPlanets();
ctx.response.body = response;
//log.info(`/planets returned ${response.length} rows`);
});
router.get("/launches", (ctx) => {
const response = launches.getAllLaunches();
ctx.response.body = response;
//log.info(`/launches returned ${response.length} rows`);
});
router.delete("/launches/:id", (ctx) => {
if (ctx.params?.id) {
const result = launches.remove(Number(ctx.params.id));
ctx.response.body = { success: result };
}
});
router.get("/launches/:id", (ctx) => {
if (ctx.params?.id) {
const launchList = launches.get(Number(ctx.params.id));
if (launchList) {
ctx.response.body = launchList;
} else {
ctx.throw(400, "Launch with that ID doesn't exist");
}
}
});
router.post("/launches", async (ctx) => {
const result = await ctx.request.body();
const data = await result.value;
launches.add(data);
ctx.response.body = { success: true };
ctx.response.status = 201;
});
router.get("/error", (ctx) => {
ctx.throw(
501,
"Some server error, this log message is not visible on client side!",
);
});
export default router;
|
b1fbebd2ca6bfb9d4527a9065fe10b7e350f5937
|
TypeScript
|
CheckPointSW/smart-console-extensions
|
/src/uuid.ts
| 2.6875
| 3
|
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
const crypto = require('crypto');
function rng() {
return crypto.randomBytes(16);
}
let byteToHex: any = [];
for (let j = 0; j < 256; ++j) {
byteToHex[j] = (j + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf: any, offset: any = undefined) {
let i = offset || 0;
let bth = byteToHex;
// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
return [
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
'-',
bth[buf[i++]],
bth[buf[i++]],
'-',
bth[buf[i++]],
bth[buf[i++]],
'-',
bth[buf[i++]],
bth[buf[i++]],
'-',
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
bth[buf[i++]],
].join('');
}
export default function uuidv1(options: any, buf: any, offset: any) {
const i = (buf && offset) || 0;
if (typeof options == 'string') {
buf = options === 'binary' ? new Array(16) : null;
options = null;
}
options = options || {};
let rnds: any = options.random || (options.rng || rng)();
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = (rnds[6] & 0x0f) | 0x40;
rnds[8] = (rnds[8] & 0x3f) | 0x80;
// Copy bytes to buffer, if provided
if (buf) {
for (let ii = 0; ii < 16; ++ii) {
buf[i + ii] = rnds[ii];
}
}
return buf || bytesToUuid(rnds);
}
|
7d2f754c95b80cae0f9508d74d7dc67348106d01
|
TypeScript
|
delprofundo/serverless-chassis-typescript
|
/src/sec/permissionsMatrix.ts
| 2.75
| 3
|
/** ******************************************
* AUTH HARNESS PERMISSIONS MATRIX
* simple matrix mapping permissions to functions in
* this service.
* 22 March 2018
* delProfundo (@brunowatt)
* bruno@hypermedia.tech
******************************************* */
import * as logger from "log-winston-aws-level";
import * as R from "ramda";
import { PermissionCheckParameters } from "./sec.types";
const { SERVICE_BASE_PATH } = process.env;
/* const CLIENT_TYPES = {
GATEWAY: "GATEWAY", // a partner service that is directly integrated
CLIENT: "CLIENT", // a user authenticed interface, cognito/s3/react for instance
NODE: "NODE", // an internal component of our system
LEAF: "LEAF", // semi-intelligent data source only (ie: iot device)
ADMIN: "ADMIN",
AUTH_ADMIN: "AUTH_ADMIN",
SYSTEM: "SYSTEM"
}; */
const MEMBER_ROLES = {
MEMBER: "MEMBER",
BRAND_ADMIN: "BRAND_ADMIN",
PLATFORM_ADMIN: "PLATFORM_ADMIN",
SYSTEM: "SYSTEM"
};
export interface ApiPermissionMatrix {
readonly path: string;
readonly resources: ApiResource[];
}
export interface ApiResource {
readonly resource: string;
readonly methods: ResourceMethod[];
}
type Role = string;
export interface ResourceMethod {
readonly method: HttpMethod;
readonly allow: Role[];
readonly deny: Role[];
}
enum HttpMethod {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE"
}
export interface PermissionEffect {
readonly effect: "allow" | "deny";
}
export const PERMISSION_DENY: PermissionEffect = { effect: "deny" };
export const PERMISSION_ALLOW: PermissionEffect = { effect: "allow" };
/**
* This array stores an object for each API path with nested entries allowing simple lookup of permissions
*/
const permMatrix: ApiPermissionMatrix[] = [
{
path: `/${SERVICE_BASE_PATH}`,
resources: [
{
resource: "/",
methods: [
{
method: HttpMethod.GET,
allow: [MEMBER_ROLES.MEMBER, MEMBER_ROLES.SYSTEM, MEMBER_ROLES.PLATFORM_ADMIN],
deny: []
},
{
method: HttpMethod.POST,
allow: [MEMBER_ROLES.MEMBER, MEMBER_ROLES.PLATFORM_ADMIN],
deny: []
}
]
},
{
resource: "/{id}",
methods: [
{
method: HttpMethod.GET,
allow: [MEMBER_ROLES.MEMBER, MEMBER_ROLES.SYSTEM, MEMBER_ROLES.PLATFORM_ADMIN],
deny: []
}
]
},
{
resource: "/{id}/finalize",
methods: [
{
method: HttpMethod.PUT,
allow: [MEMBER_ROLES.MEMBER],
deny: []
}
]
},
{
resource: "/echo",
methods: [
{
method: HttpMethod.POST,
allow: [MEMBER_ROLES.MEMBER],
deny: []
}
]
}
]
}
];
/**
* matrix interface, returns the effect clause of a IAM role
* @param path
* @param resource
* @param method
* @param memberRole
* @param clientType
* @returns {Promise<{effect: string}>}
*/
export default async function validateAccess({
path,
resource,
method,
memberRole,
clientType
}: PermissionCheckParameters): Promise<PermissionEffect> {
// this is to switch between users/clients
let effectiveEntity;
if (memberRole) {
effectiveEntity = memberRole;
} else if (clientType) {
effectiveEntity = clientType;
} else {
logger.info("neither client or user type present, deny access");
return PERMISSION_DENY;
}
return validateMappedResourceMethod(permMatrix, path, resource, method, effectiveEntity);
}
const validateMappedResourceMethod = (
permissionMatrix: ApiPermissionMatrix[],
path: string,
resource: string,
method: string,
integratorRole: string
): PermissionEffect => {
const basePathFilter = R.compose(
R.chain(R.prop<string, ApiResource[]>("resources")),
R.filter(R.propEq("path", path))
);
const resourcePathFilter = R.compose(
R.chain(R.prop<string, ResourceMethod[]>("methods")),
R.filter(R.propEq("resource", resource))
);
const httpMethodFilter = R.filter(R.propEq("method", method));
const resourceAccess: ResourceMethod[] = R.compose(
httpMethodFilter,
resourcePathFilter,
basePathFilter
)(permissionMatrix);
if (R.isEmpty(resourceAccess)) {
return PERMISSION_DENY;
} else {
if (R.contains(integratorRole, resourceAccess[0].deny)) {
return PERMISSION_DENY;
}
return R.contains(integratorRole, resourceAccess[0].allow) ? PERMISSION_ALLOW : PERMISSION_DENY;
}
};
|
e8c62b6d029295cb87823e197ea37c4b98c21355
|
TypeScript
|
cpmech/cloud
|
/az-cognito/src/admin/types.ts
| 2.53125
| 3
|
import AWS from 'aws-sdk';
export type ICognitoUserType = AWS.CognitoIdentityServiceProvider.UserType;
export type IAdminUserResponse = AWS.CognitoIdentityServiceProvider.AdminGetUserResponse;
export interface ICognitoUser extends Omit<ICognitoUserType, 'Attributes'> {
Data: {
[key: string]: string;
};
}
export interface IUserInput {
email: string;
password: string;
groups: string; // comma-separated
}
export const newUserInput = (): IUserInput => ({
email: '',
password: '',
groups: '',
});
|
94ae996c8954fb7ade996b7e9a71fca57f28e993
|
TypeScript
|
dev-warner/dc-visualization-sdk
|
/packages/dc-visualization-core/src/__tests__/deliveryKey.spec.ts
| 2.546875
| 3
|
import { ClientConnection } from 'message-event-channel'
import { DeliveryKey } from '../delivery-key'
describe('DeliveryKey', () => {
describe('get', () => {
it('should call connection with get key and return string', async () => {
const on = jest.fn()
const request = jest.fn(() => 'some-content-key')
const connection = ({
on,
request,
} as never) as ClientConnection
const deliveryKey = new DeliveryKey(connection)
const result = await deliveryKey.get()
expect(connection.request).toBeCalledWith(
'visualisation-sdk:delivery-key:get'
)
expect(result).toEqual('some-content-key')
})
})
describe('changed', () => {
it('should add handlers to call later', () => {
let run: Function = () => {}
const on = jest.fn((key, _run) => {
run = _run
})
const emit = jest.fn()
const connection = ({
on,
emit,
} as never) as ClientConnection
const handler1 = jest.fn()
const handler2 = jest.fn()
const deliveryKey = new DeliveryKey(connection)
const dispose1 = deliveryKey.changed(handler1)
const dispose2 = deliveryKey.changed(handler2)
expect(
deliveryKey.changeHandlerContainer.changeHandlers.get(
'323217f643c3e3f1fe7532e72ac01bb0748c97be'
)?.size
).toEqual(2)
run('some-content-key')
expect(handler1).toBeCalledWith('some-content-key')
expect(handler2).toBeCalledWith('some-content-key')
run('some-content-key')
expect(handler1).toBeCalledWith('some-content-key')
expect(handler2).toBeCalledWith('some-content-key')
expect(connection.emit).not.toBeCalled()
dispose1()
dispose2()
expect(
deliveryKey.changeHandlerContainer.changeHandlers.get(
'323217f643c3e3f1fe7532e72ac01bb0748c97be'
)?.size
).toEqual(0)
})
})
})
|
c78c49ac5f3f8655b466830344bffc253ed0d122
|
TypeScript
|
Turro75/rp2040js
|
/demo/intelhex.ts
| 2.625
| 3
|
/**
* Minimal Intel HEX loader
* Part of AVR8js
*
* Copyright (C) 2019, Uri Shaked
*/
export function loadHex(source: string, target: Uint8Array, baseAddress: number = 0) {
let highAddressBytes = 0;
for (const line of source.split('\n')) {
if (line[0] === ':' && line.substr(7, 2) === '04') {
highAddressBytes = parseInt(line.substr(9, 4), 16);
}
if (line[0] === ':' && line.substr(7, 2) === '00') {
const bytes = parseInt(line.substr(1, 2), 16);
const addr = ((highAddressBytes << 16) | parseInt(line.substr(3, 4), 16)) - baseAddress;
for (let i = 0; i < bytes; i++) {
target[addr + i] = parseInt(line.substr(9 + i * 2, 2), 16);
}
}
}
}
|
97b9c65addbfad9b938c9615d8ca572099c0f6e9
|
TypeScript
|
Swamp-boy/FSD-3-Slider
|
/src/components/ts/MinMaxFields/MinMaxFields.ts
| 2.8125
| 3
|
class MinMaxFields {
public min: number;
public max: number;
public sliderField: HTMLElement;
public minField: HTMLElement;
public minSpan: HTMLElement;
public maxField: HTMLElement;
public maxSpan: HTMLElement;
constructor(sliderField: HTMLElement, min: number, max: number) {
this.sliderField = sliderField;
this.min = min;
this.max = max;
}
public createMinField(): void {
this.minField = document.createElement('div');
this.minField.classList.add('js-slider-min-field');
this.minSpan = document.createElement('span');
this.minSpan.innerHTML = String(this.min);
this.minField.appendChild(this.minSpan);
}
public createMaxField():void {
this.maxField = document.createElement('div');
this.maxField.classList.add('js-slider-max-field');
this.maxSpan = document.createElement('span');
this.maxSpan.innerHTML = String(this.max);
this.maxField.appendChild(this.maxSpan);
}
public setMinField(position: string): void {
if (position === 'horizontal') {
const top = -this.minField.offsetHeight - 5; /* space from field to slider */
this.minField.style.top = String(top) + 'px';
this.minField.style.left = '0px';
} else {
const right = 5; /* space from field to slider */
this.minField.style.right = String(right) + 'px';
this.minField.style.bottom = '9px';
}
}
public setMaxField(position: string): void {
if (position === 'horizontal') {
const top = -this.maxField.offsetHeight - 5;
this.maxField.style.top = String(top) + 'px';
this.maxField.style.right = '0px';
} else {
const right = 5; /* space from field to slider */
this.maxField.style.right = String(right) + 'px';
this.maxField.style.top = '9px';
}
}
public setMaxFieldWidth(): void {
if (this.maxSpan.offsetWidth + 10 > this.maxField.offsetWidth) {
this.maxField.style.width = String(this.maxField.offsetWidth + 10) + 'px';
}
}
public setMinFieldWidth():void {
if (this.minSpan.offsetWidth + 10 > this.minField.offsetWidth) {
this.minField.style.width = String(this.minField.offsetWidth + 10) + 'px';
}
}
public rotate(): void {
this.minField.classList.add('js-slider-min-field_vertical');
this.maxField.classList.add('js-slider-max-field_vertical');
}
}
export default MinMaxFields;
|
13d39be00eb872b53003bad3ba457355571b8978
|
TypeScript
|
syedMohib44/Deception-Aura-Web
|
/api/entity/SuperAdmin.ts
| 2.796875
| 3
|
import { Schema, Document, model } from 'mongoose';
export interface ISuperAdmin extends Document {
_id: any;
email: string;
password: string;
lastLogin?: Date;
refreshToken?: string;
}
const SuperAdminSchema = new Schema({
email: { type: String, required: true, unique: true, trim: true, lowercase: true },
password: { type: String, required: true, minlength: 8, maxlength: 255 },
lastLogin: { type: Date },
refreshToken: { type: String },
}, { timestamps: true });
SuperAdminSchema.virtual('fullName').get(function (this: any) {
return `${this.firstName} ${this.lastName}`;
});
export default model<ISuperAdmin>('SuperAdmin', SuperAdminSchema);
|
1e500bddb991e60fc3bd3e9456f070c482ae7c7a
|
TypeScript
|
angelisco1/curso-sopra-3
|
/angular/proyecto/src/app/cmp-formularios/cmp-formularios.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-cmp-formularios',
templateUrl: './cmp-formularios.component.html',
styleUrls: ['./cmp-formularios.component.css']
})
export class CmpFormulariosComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
// username: this.formBuilder.control('angel', [Validators.required, this.esUnStark]),
username: this.formBuilder.control('angel', [Validators.required, this.esUnStark(['robb', 'arya', 'rickon', 'sansa', 'bran', 'tony'])]),
password: this.formBuilder.control('', [Validators.required, Validators.minLength(5)])
});
}
login() {
console.log(this.form);
}
esUnStark(nombresValidos: Array<string>) {
return (control: FormControl) => {
if (nombresValidos.includes(control.value.toLowerCase())) {
return null;
}
return {
esUnStark: false
}
}
}
// esUnStark(control: FormControl) {
// const nombresValidos = ['robb', 'arya', 'rickon', 'sansa', 'bran', 'tony'];
// if (nombresValidos.includes(control.value.toLowerCase())) {
// return null;
// }
// return {
// esUnStark: false
// }
// }
}
// pristine -> valor inicial
// dirty -> valor modificado
// untouched -> el campo no ha perdido el foco ninguna vez
// touched -> el campo ha perdido el foco una vez
// valid -> el campo es valido
// invalid -> el campo es invalido
|
e18c73835c254356fe88dc58a9a7196823f2965e
|
TypeScript
|
Megaloden106/personal-finance-manager
|
/client/store/models/action.ts
| 2.640625
| 3
|
import { Action } from 'redux';
import { Epic } from 'redux-observable';
import { AxiosPromise, AxiosError } from 'axios';
export interface Metadata {
[propName: string]: any;
}
export interface FluxAction<T> extends Action<string> {
type: string;
payload?: T;
error?: boolean;
meta?: Metadata;
}
export type ServiceCreator = (action: FluxAction<any>) => AxiosPromise;
export type ActionCreator = <T = undefined>(
type: string,
payload?: T,
error?: boolean,
meta?: Metadata,
) => FluxAction<T>;
export type EpicCreator = <T = undefined>(
actionType: string,
service: (action: FluxAction<T>) => AxiosPromise | Promise<AxiosError>,
) => Epic;
|
97b4f8b510e4437eed17c38eb3add390a20f0885
|
TypeScript
|
Kauto/animationvideo
|
/src/Sprites/Text.ts
| 2.796875
| 3
|
import calc from "../func/calc";
import type { OrFunction } from "../helper";
import { Position } from "../Position";
import { AdditionalModifier } from "../Scene";
import { CircleParameterList, SpriteCircleOptions } from "./Circle";
import { ISprite, SpriteBase, SpriteBaseOptionsInternal } from "./Sprite";
export interface SpriteTextOptions extends SpriteCircleOptions {
text?: OrFunction<string|string[]>
font?: OrFunction<undefined|string>
position?: OrFunction<undefined|Position>
borderColor?: OrFunction<undefined|string>
lineWidth?: OrFunction<undefined|number>
}
export interface SpriteTextOptionsInternal extends SpriteBaseOptionsInternal {
x: number
y: number
rotation: number
scaleX: number
scaleY: number
alpha: number
compositeOperation: GlobalCompositeOperation
text: string
font: string
position: Position
borderColor: undefined|string
color: undefined|string
lineWidth: number
}
export default class Text extends SpriteBase<SpriteTextOptions, SpriteTextOptionsInternal> implements ISprite {
constructor(givenParameters:SpriteTextOptions) {
super(givenParameters);
}
_getParameterList() {
return Object.assign({}, this._getBaseParameterList(), CircleParameterList, {
text: (value:SpriteTextOptions['text']) => {
const text = calc(value)
return (Array.isArray(text) ? text.join('') : text) || ''
},
font: '2em monospace',
position: Position.CENTER,
color: undefined,
borderColor: undefined,
lineWidth: 1
})
}
detectDraw(context:CanvasRenderingContext2D, color:string) {
if (this.p.enabled && this.p.isClickable) {
context.save();
context.translate(this.p.x, this.p.y);
context.scale(this.p.scaleX, this.p.scaleY);
context.rotate(this.p.rotation);
if (!this.p.position) {
context.textAlign = 'left';
context.textBaseline = 'top';
}
context.font = this.p.font;
context.fillStyle = color;
context.fillText(this.p.text, 0, 0);
context.restore();
}
}
detect(context:CanvasRenderingContext2D, x:number, y:number):"c" {
return "c"
}
// draw-methode
draw(context:CanvasRenderingContext2D, additionalModifier:AdditionalModifier) {
if (this.p.enabled) {
context.globalCompositeOperation = this.p.compositeOperation;
context.globalAlpha = this.p.alpha * additionalModifier.alpha;
context.save();
if (!this.p.position) {
context.textAlign = 'left';
context.textBaseline = 'top';
}
context.translate(this.p.x, this.p.y);
context.scale(this.p.scaleX, this.p.scaleY);
context.rotate(this.p.rotation);
context.font = this.p.font;
if (this.p.color) {
context.fillStyle = this.p.color;
context.fillText(this.p.text, 0, 0);
}
if (this.p.borderColor) {
context.strokeStyle = this.p.borderColor;
context.lineWidth = this.p.lineWidth;
context.strokeText(this.p.text, 0, 0);
}
context.restore();
}
};
}
|
6c5db6ba732149653ba57ebe1925f368192dd417
|
TypeScript
|
hitmaneac/3fs
|
/src/app/helper.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HelperService {
constructor() {
}
bytesToSize(bytes) {
let sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
let i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${Math.round(bytes / Math.pow(1024, i))}${sizes[i]}`;
}
}
|
c07d209cdaa40cf674f358b228eab73731c2605c
|
TypeScript
|
ryanArora/CalmBot
|
/src/commands/moderation/format.ts
| 2.96875
| 3
|
import { Message, MessageAttachment } from "discord.js";
import Client from "../../structures/Client";
import { ICommand, PermissionsEnum, RunCallback } from "../../structures/Interfaces";
const format = "**Type of Punishment:** PUNISHMENT_TYPE\n**Discord name & #:** DISCORD_NAME\n**Discord ID:** DISCORD_ID\n**Evidence:** REASON";
const genFormat = (punishmentType: string, name: string, id: string, reason: string): string => format.replace("PUNISHMENT_TYPE", punishmentType).replace("DISCORD_NAME", name).replace("DISCORD_ID", id).replace("REASON", reason);
function FormatCommand(): ICommand {
const run: RunCallback = async (client: Client, message: Message, args: string[]) => {
if (args.length < 3) {
message.channel.send(`Invalid arguments!\n${client.prefix}format <punishment type> <user id> <reason> <attach image>`);
return;
}
let image: string | undefined = undefined;
if (message.attachments.size > 0 && attachIsImage(message.attachments.array()[0]!!)) image = message.attachments.array()[0]!!.url;
const userid = args[1];
client.users
.fetch(userid as string)
.then((user) => {
const msg = genFormat(args[0]!!, user.tag, user.id, args.slice(2, args.length).join(" ") as string);
if (image) message.channel.send(msg, { files: [image] });
else message.channel.send(msg);
})
.catch(() => {
const msg = genFormat(args[0] as string, "Invalid user ID", args[1] as string, args.slice(2, args.length).join(" ") as string);
if (image) message.channel.send(msg, { files: [image] });
else message.channel.send(msg);
});
};
return {
run: run,
settings: {
description: "Generate a punishment format",
usage: "format <punishment type> <user id> <reason> [attach image]",
guildOnly: true,
permissions: PermissionsEnum.STAFF,
},
};
}
function attachIsImage(msgAttach: MessageAttachment) {
var url = msgAttach.url;
if (url === undefined) return false;
return url.indexOf("png", url.length - "png".length /*or 3*/) !== -1 || url.indexOf("jpeg", url.length - "jpeg".length /*or 3*/) !== -1 || url.indexOf("jpg", url.length - "jpg".length /*or 3*/) !== -1;
}
export default FormatCommand();
|
cb2bbb18cea1337f57824ec48a2aac88289da1f0
|
TypeScript
|
aeoncleanse/PracticeReact
|
/application/server/src/dataShapes.ts
| 2.65625
| 3
|
// We want our query to return in this shape
export interface Data {
"id": number,
"createdAt": Date,
"updatedAt": Date,
"title": string
}
|
87380d0d7b2361a059b29af12691137513702829
|
TypeScript
|
cjol/fauna-fp
|
/src/curry/replaceStrRegex.ts
| 2.921875
| 3
|
import * as fns from "../fns";
import { Arg, Query } from "../types";
/**
* Replaces a portion of a string with another string.
*/
export function replaceStrRegex(
pattern: Arg<string>,
replacement: Arg<string>
): (haystack: Arg<string>) => Query<string>;
export function replaceStrRegex(
pattern: Arg<string>
): (replacement: Arg<string>) => (haystack: Arg<string>) => Query<string>;
export function replaceStrRegex(pattern: Arg<string>, replacement?: Arg<string>) {
if (replacement === undefined) {
return (replacement: Arg<string>) => replaceStrRegex(pattern, replacement);
}
return (haystack: Arg<string>) => fns.replaceStrRegex(pattern, replacement, haystack);
}
|
bf47ec0788154f98f27469fc27a33a7711c48b2f
|
TypeScript
|
robotty/dank-twitch-irc
|
/lib/message/parser/tag-values.spec.ts
| 2.703125
| 3
|
import { assert } from "chai";
import { assertThrowsChain } from "../../helpers.spec";
import { TwitchBadge } from "../badge";
import { TwitchBadgesList } from "../badges";
import { TwitchEmote } from "../emote";
import { MissingTagError } from "./missing-tag-error";
import { ParseError } from "./parse-error";
import { tagParserFor, TagValueParser } from "./tag-values";
describe("./message/parser/tag-values", function () {
function checkRequire<V, A extends any[]>(
subject: (
tagParser: TagValueParser
) => (key: string, ...converterArgs: A) => V,
...converterArgs: A
): void {
describe("#requireData", function () {
it("should throw MissingTagError on missing key", function () {
assertThrowsChain(
() => subject(tagParserFor({}))("key", ...converterArgs),
MissingTagError,
'Required tag value not present at key "key" (is undefined)'
);
});
it("should throw MissingTagError on null value", function () {
assertThrowsChain(
() => subject(tagParserFor({ key: null }))("key", ...converterArgs),
MissingTagError,
'Required tag value not present at key "key" (is null)'
);
});
});
}
function checkGet<V, A extends any[]>(
subject: (
tagParser: TagValueParser
) => (key: string, ...converterArgs: A) => V | undefined,
...converterArgs: A
): void {
describe("#getData", function () {
it("should return undefined on missing key", function () {
assert.isUndefined(subject(tagParserFor({}))("key", ...converterArgs));
});
it("should return undefined on null value", function () {
assert.isUndefined(
subject(tagParserFor({ key: null }))("key", ...converterArgs)
);
});
});
}
describe("#getString(), #requireString()", function () {
checkGet((p) => p.getString);
checkRequire((p) => p.requireString);
it("should return the value if value exists (also on empty string)", function () {
assert.strictEqual(
tagParserFor({ key: "value" }).getString("key"),
"value"
);
assert.strictEqual(
tagParserFor({ key: "value" }).requireString("key"),
"value"
);
assert.strictEqual(tagParserFor({ key: "" }).getString("key"), "");
assert.strictEqual(tagParserFor({ key: "" }).requireString("key"), "");
});
});
function checkThrowsUnparseableInt<V, A extends any[]>(
subject: (
tagParser: TagValueParser
) => (key: string, ...converterArgs: A) => V | undefined,
...converterArgs: A
): void {
it("should throw ParseError on empty string input", function () {
assertThrowsChain(
() => subject(tagParserFor({ key: "" }))("key", ...converterArgs),
ParseError,
'Failed to parse integer from tag value ""'
);
});
it("should throw ParseError on invalid integer input", function () {
assertThrowsChain(
() => subject(tagParserFor({ key: "abc" }))("key", ...converterArgs),
ParseError,
'Failed to parse integer from tag value "abc"'
);
});
}
describe("#getInt(), #requireInt()", function () {
checkGet((p) => p.getInt);
checkRequire((p) => p.requireInt);
checkThrowsUnparseableInt((p) => p.getInt);
checkThrowsUnparseableInt((p) => p.requireInt);
it("should return a number if value exists and was parseable", function () {
assert.strictEqual(15, tagParserFor({ key: "15" }).getInt("key"));
assert.strictEqual(15, tagParserFor({ key: "15" }).requireInt("key"));
});
});
describe("#getBoolean(), #requireBoolean()", function () {
checkGet((p) => p.getBoolean);
checkRequire((p) => p.requireBoolean);
checkThrowsUnparseableInt((p) => p.getInt);
checkThrowsUnparseableInt((p) => p.requireInt);
it("should return false if the parsed integer is 0", function () {
assert.isFalse(tagParserFor({ key: "0" }).getBoolean("key"));
assert.isFalse(tagParserFor({ key: "0.0" }).getBoolean("key"));
});
it("should return false if the parsed integer is non-0", function () {
assert.isTrue(tagParserFor({ key: "1" }).getBoolean("key"));
assert.isTrue(tagParserFor({ key: "-1" }).getBoolean("key"));
assert.isTrue(tagParserFor({ key: "15" }).getBoolean("key"));
assert.isTrue(tagParserFor({ key: "-15" }).getBoolean("key"));
});
});
describe("#getColor(), #requireColor()", function () {
checkGet((p) => p.getColor);
checkRequire((p) => p.requireColor);
it("should parse #RRGGBB color input correctly", function () {
assert.deepStrictEqual(tagParserFor({ key: "#aabbcc" }).getColor("key"), {
r: 0xaa,
g: 0xbb,
b: 0xcc,
});
assert.deepStrictEqual(tagParserFor({ key: "#AABBCC" }).getColor("key"), {
r: 0xaa,
g: 0xbb,
b: 0xcc,
});
assert.deepStrictEqual(tagParserFor({ key: "#12D3FF" }).getColor("key"), {
r: 0x12,
g: 0xd3,
b: 0xff,
});
});
it("#getColor() should return undefined on empty string input", function () {
assert.isUndefined(tagParserFor({ key: "" }).getColor("key"));
});
it("#requireColor() should throw MissingDataError on empty string input", function () {
assertThrowsChain(
() => tagParserFor({ key: "" }).requireColor("key"),
MissingTagError,
'Required tag value not present at key "key" (is empty string)'
);
});
});
describe("#getTimestamp(), #requireTimestamp()", function () {
checkGet((p) => p.getTimestamp);
checkRequire((p) => p.requireTimestamp);
checkThrowsUnparseableInt((p) => p.getTimestamp);
checkThrowsUnparseableInt((p) => p.requireTimestamp);
it("should interpret given integer values as milliseconds since UTC epoch", function () {
assert.strictEqual(
tagParserFor({ key: "1234567" }).requireTimestamp("key").getTime(),
1234567
);
});
});
describe("#getBadges(), #requireBadges()", function () {
checkGet((p) => p.getBadges);
checkRequire((p) => p.requireBadges);
it("should return an empty list on empty string input", function () {
assert.deepStrictEqual(
tagParserFor({ key: "" }).getBadges("key"),
new TwitchBadgesList()
);
});
it("should return single-element array on single badge", function () {
assert.deepStrictEqual(
tagParserFor({ key: "admin/1" }).getBadges("key"),
new TwitchBadgesList(new TwitchBadge("admin", "1"))
);
});
it("should accept two badges in the tag source", function () {
assert.deepStrictEqual(
tagParserFor({ key: "admin/1,subscriber/32" }).getBadges("key"),
new TwitchBadgesList(
new TwitchBadge("admin", "1"),
new TwitchBadge("subscriber", "32")
)
);
});
it("should accept three badges in the tag source", function () {
assert.deepStrictEqual(
tagParserFor({ key: "admin/1,subscriber/32,bits/1000" }).getBadges(
"key"
),
new TwitchBadgesList(
new TwitchBadge("admin", "1"),
new TwitchBadge("subscriber", "32"),
new TwitchBadge("bits", "1000")
)
);
});
});
describe("#getTagEmotes()", function () {
checkGet((p) => p.getEmotes, "lul");
checkRequire((p) => p.requireEmoteSets, "lul");
it("should return an empty list on empty string input", function () {
const actual = tagParserFor({ key: "" }).getEmotes("key", "test");
assert.deepStrictEqual(actual, []);
});
it("should return single-element array on single emote", function () {
const actual = tagParserFor({ key: "25:4-8" }).getEmotes(
"key",
"asd Kappa def"
);
assert.deepStrictEqual(actual, [new TwitchEmote("25", 4, 9, "Kappa")]);
});
it("should return 2-element array on 2 identical emotes", function () {
const actual = tagParserFor({ key: "25:4-8,14-18" }).getEmotes(
"key",
"asd Kappa def Kappa def"
);
assert.deepStrictEqual(actual, [
new TwitchEmote("25", 4, 9, "Kappa"),
new TwitchEmote("25", 14, 19, "Kappa"),
]);
});
it("should return 2-element array on 2 different emotes", function () {
const actual = tagParserFor({ key: "25:4-8/1902:14-18" }).getEmotes(
"key",
"asd Kappa def Keepo def"
);
assert.deepStrictEqual(actual, [
new TwitchEmote("25", 4, 9, "Kappa"),
new TwitchEmote("1902", 14, 19, "Keepo"),
]);
});
it("should return a correctly sorted 3-element array on interleaved emotes", function () {
const actual = tagParserFor({ key: "25:5-9,27-31/1902:16-20" }).getEmotes(
"key",
"test Kappa test Keepo test Kappa"
);
assert.deepStrictEqual(actual, [
new TwitchEmote("25", 5, 10, "Kappa"),
new TwitchEmote("1902", 16, 21, "Keepo"),
new TwitchEmote("25", 27, 32, "Kappa"),
]);
});
});
describe("#getEmoteSets(), #requireEmoteSets()", function () {
checkGet((p) => p.getEmoteSets);
checkRequire((p) => p.requireEmoteSets);
it("should return an empty list on empty string input", function () {
const actual = tagParserFor({ key: "" }).getEmoteSets("key");
assert.deepStrictEqual(actual, []);
});
it("should parse one emote set correctly", function () {
const actual = tagParserFor({ key: "0" }).getEmoteSets("key");
assert.deepStrictEqual(actual, ["0"]);
});
it("should parse two emote set correctly", function () {
const actual = tagParserFor({ key: "0,3343" }).getEmoteSets("key");
assert.deepStrictEqual(actual, ["0", "3343"]);
});
it("should parse three emote set correctly", function () {
// also tests that function preserves order (no sorting)
const actual = tagParserFor({ key: "0,7897,3343" }).getEmoteSets("key");
assert.deepStrictEqual(actual, ["0", "7897", "3343"]);
});
});
});
|
ea0afcd3ca72f24ee96e573893e957b04e86cb79
|
TypeScript
|
yelhouti/primeng
|
/src/app/showcase/doc/selectbutton/multipledoc.ts
| 2.640625
| 3
|
import { Component, Input } from '@angular/core';
import { Code } from '../../domain/code';
@Component({
selector: 'multiple-doc',
template: ` <section>
<app-docsectiontext [title]="title" [id]="id">
<p>SelectButton allows selecting only one item by default and setting <i>multiple</i> option enables choosing more than one item. In multiple case, model property should be an array.</p>
</app-docsectiontext>
<div class="card flex justify-content-center">
<p-selectButton [options]="paymentOptions" [(ngModel)]="value" [multiple]="true" optionLabel="name" optionValue="value"></p-selectButton>
</div>
<app-code [code]="code" selector="select-button-multiple-demo"></app-code>
</section>`
})
export class MultipleDoc {
@Input() id: string;
@Input() title: string;
paymentOptions: any[] = [
{ name: 'Option 1', value: 1 },
{ name: 'Option 2', value: 2 },
{ name: 'Option 3', value: 3 }
];
value!: number;
code: Code = {
basic: `
<p-selectButton [options]="paymentOptions" [(ngModel)]="value" [multiple]="true" optionLabel="name" optionValue="value"></p-selectButton>`,
html: `
<div class="card flex justify-content-center">
<p-selectButton [options]="paymentOptions" [(ngModel)]="value" [multiple]="true" optionLabel="name" optionValue="value"></p-selectButton>
</div>`,
typescript: `
import { Component } from '@angular/core';
@Component({
selector: 'select-button-multiple-demo',
templateUrl: './select-button-multiple-demo.html'
})
export class SelectButtonMultipleDemo {
value!: number;
paymentOptions: any[] = [
{ name: 'Option 1', value: 1 },
{ name: 'Option 2', value: 2 },
{ name: 'Option 3', value: 3 }
];
}`
};
}
|
cecab3d8e8220b686db41fb428dac7b747e6cc96
|
TypeScript
|
sparkdesignsystem/spark-design-system
|
/angular/projects/spark-angular/src/lib/directives/inputs/sprk-radio-input/sprk-radio-input.directive.ts
| 2.546875
| 3
|
import { Directive, Input, HostBinding, ElementRef } from '@angular/core';
@Directive({
selector: '[sprkRadioInput]',
})
export class SprkRadioInputDirective {
constructor(public ref: ElementRef) {}
/**
* This will be used to determine the variant of
* the radio input.
*/
@Input()
variant: 'huge' | undefined;
/**
* The value supplied will be assigned
* to the `data-id` attribute on the
* element. This is intended to be
* used as a selector for automated
* tools. This value should be unique
* per page.
*/
@Input()
idString: string;
/**
* Assigned to the `data-analytics` attribute
* serving as a unique selector for outside
* libraries to capture data.
*/
@Input()
analyticsString: string;
@HostBinding('class.sprk-b-SelectionInput') selectClass = true;
@HostBinding('class.sprk-b-Radio__input') radioClass = true;
@HostBinding('class.sprk-b-Radio__input--huge')
get variantStr() {
return this.variant === 'huge';
}
@HostBinding('attr.data-id')
get idStr() {
return this.idString;
}
@HostBinding('attr.data-analytics')
get analyticsStr() {
return this.analyticsString;
}
}
|
11ebc6036f29216564b811af69eef27de9123b6d
|
TypeScript
|
IgnatZakalinsky/cards-back-3-0
|
/src/p1-common/c1-errors/errors.ts
| 3.296875
| 3
|
export const toSimpleSafely = (value: any) => {
if (typeof value === 'boolean'
|| typeof value === 'number'
|| typeof value === 'string'
|| typeof value === 'undefined'
|| value === null
) return value
else if (typeof value === 'object') return value.toString()
else return 'some ' + typeof value
}
export const deepCopySafely = (o: any, depth: number) => {
if (depth === 0 || typeof o !== 'object' || o === null) return toSimpleSafely(o)
else {
const newO: any = {}
for (const p of Object.keys(o)) {
newO[p] = deepCopySafely(o[p], depth - 1)
}
return newO
}
}
export const onUncaughtException = (f?: (e?: string) => void) => {
process.on('uncaughtException', (e) => {
const dp = deepCopySafely(e, 3) // !!! error copy in 3 lvl
f && f(JSON.stringify(['uncaughtException', dp])) // log in db
console.log(`!!! Uncaught Exception${f ? ' with log in db' : ''}: `, dp, e)
})
}
export const onUnhandledRejection = (f?: (e?: string) => void) => {
process.on('unhandledRejection', (reason, p) => {
const dp = deepCopySafely(reason, 3)
f && f(JSON.stringify(['unhandledRejection reason', dp])) // log in db
console.log(`!!! Unhandled Rejection${f ? ' with log in db' : ''}: `, dp, reason)
p.then(x => {
const dpx = deepCopySafely(x, 3)
f && f(JSON.stringify(['unhandledRejection !!! then: ', dpx])) // log in db
console.log('!!! then: ', dpx, x)
})
.catch(e => {
const dpe = deepCopySafely(e, 3)
f && f(JSON.stringify(['unhandledRejection !!! catch: ', dpe])) // log in db
console.log('!!! catch: ', dpe, e)
})
})
}
/** ะพัะปะพะฒ ะพัะธะฑะพะบ ััะพะฑ ัะตัะฒะตั ะฝะต ะฟะฐะดะฐะป
*/
export const globalCatch = (fUncaught?: (e?: string) => void, fUnhandled?: (e?: string) => void) => {
onUncaughtException(fUncaught)
onUnhandledRejection(fUnhandled)
}
|
aef629c34c05f6bfd2badd654cafc4f0f263c7b9
|
TypeScript
|
bgauthier555/ux-common-interface
|
/src/ComponentContainer.ts
| 3
| 3
|
/**
* Component container, allows to add multiple child components
*
* @copyright Benoit Gauthier <bgauthier555@gmail.com>
* @author Benoit Gauthier <bgauthier555@gmail.com>
* @licence MIT
*/
import {Component} from "./Component";
abstract class ComponentContainer extends Component {
/**
* Component sub items
*/
public items: any = [];
/**
*
* @param id
*/
constructor(sId: string) {
super(sId);
this.items = [];
}
/**
* Render container components and returns HTML string
*/
public render(map: any = null) : string
{
let sChildItems = '';
for(let x in this.items) {
if (this.items.hasOwnProperty(x)) {
sChildItems = sChildItems + this.items[x].render(map);
}
}
let sHtml = super.render({
child_items : sChildItems
});
return sHtml;
}
/**
* Returns list of comonents
* @returns {Array}
*/
public getItems() : any
{
return this.items;
}
/**
* Adds a child component to this container
* @param item
* @returns {Component}
*/
public addItem(item: Component | ComponentContainer) : Component | ComponentContainer
{
// Set item _oParent to this container item
item._oParent = this;
this.items[this.items.length] = item;
// Remove from main component item list, since this component is a child component
// @ts-ignore
window.UX.Page.removeItem(item.getId());
return item;
}
/**
* Adds Li item to component
* @param id
* @returns {Component}
*/
public addLi(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Li(id));
}
/**
* Adds Ol item to component
* @param id
* @returns {Component}
*/
public addOl(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Ol(id));
}
/**
* Add Ul item to component
* @param id
* @returns {Component}
*/
public addUl(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Ul(id));
}
/**
* Adds div item to component
* @param id
* @returns {Component}
*/
public addDiv(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Div(id));
}
/**
* Adds anchor item to component
* @param id
* @returns {Component}
*/
public addAnchor(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Anchor(id));
}
/**
* Adds alert item to component
* @param id
* @returns {Component}
*/
public addAlert(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Alert(id));
}
/**
* Adds button item to component
* @param id
* @returns {Component}
*/
public addButton(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Button(id));
}
/**
* Adds checkbox item to component
* @param id
* @returns {Component}
*/
public addCheckbox(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Checkbox(id));
}
/**
* Adds heading item to component
* @param id
* @returns {Component}
*/
public addHeading(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Heading(id));
}
/**
* Adds input item to component
* @param id
* @returns {Component}
*/
public addInput(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Input(id));
}
/**
* Adds paragraph item to component
* @param id
* @returns {Component}
*/
public addParagraph(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Paragraph(id));
}
/**
* Adds password item to component
* @param id
* @returns {Component}
*/
public addPassword(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Password(id));
}
/**
* Adds pre item to component
* @param id
* @returns {Component}
*/
public addPre(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Pre(id));
}
/**
* Adds select item to component
* @param id
* @returns {Component}
*/
public addSelect(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Select(id));
}
/**
* Adds textarea item to component
* @param id
* @returns {Component}
*/
public addTextArea(id: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.TextArea(id));
}
/**
* Adds head item to component
* @param id
* @returns {Component}
*/
public addHead(sId: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Head(sId));
}
/**
* Adds title item to component
* @param id
* @returns {Component}
*/
public addTitle(sId: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Title(sId));
}
/**
* Adds body item to component
* @param id
* @returns {Component}
*/
public addBody(sId: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Body(sId));
}
/**
* Adds row item to component
* @param id
* @returns {Component}
*/
public addRow(sId: string = null) : Component
{
// @ts-ignore
return this.addItem(new window.UX.Row(sId));
}
public findItem(sId: string) : Component | null
{
for(let x in this.items) {
if (this.items[x].getId() == sId) {
return this.items[x];
} else {
let item = this.items[x].findItem(sId);
if (item != null) {
return item;
}
}
}
return null;
}
}
export {ComponentContainer};
|
83d561d1d1a517bd99bf230142810bbadc63e95a
|
TypeScript
|
Furmanus/AbyssRL
|
/src/scripts/timeEngine/queueMember.ts
| 2.8125
| 3
|
import { IActor } from '../entity/entity_interfaces';
import { dungeonState } from '../state/application.state';
export interface SerializedQueueMember {
nextActionAt: number;
actorId: string | IActor;
isRepeatable: boolean;
lastSavedActorSpeed: number;
}
export class QueueMember {
public nextActionAt: number;
public isRepeatable: boolean;
private actorId: string;
public get actor(): IActor {
return dungeonState.entityManager.getActorById(this.actorId);
}
public constructor(data: SerializedQueueMember) {
const { nextActionAt, actorId, isRepeatable, lastSavedActorSpeed } = data;
if (typeof actorId === 'string') {
this.actorId = actorId;
} else {
this.actorId = actorId.getId();
}
this.nextActionAt = nextActionAt + 1 / lastSavedActorSpeed;
this.isRepeatable = isRepeatable;
}
public takeAction(): void {
this.actor.act();
if (this.actor) {
this.nextActionAt += 1 / this.actor.getSpeed();
}
}
public getDataToSerialization(): SerializedQueueMember {
return {
nextActionAt: this.nextActionAt,
actorId: this.actorId,
isRepeatable: this.isRepeatable,
lastSavedActorSpeed: this.actor.getSpeed(),
};
}
}
|
35e3293ff13d57c58c178a733482c3ea9e6ec869
|
TypeScript
|
krzosa/Genetic-algorithm
|
/src/utils/random.ts
| 3.265625
| 3
|
export function getRandomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
export function getRandomIndexs(n: number) {
var indexs = []
for(let i = 0; i<n; i++) {
indexs.push(i)
}
let randomIndexs = []
let i = indexs.length
while (i--) {
let j = Math.floor(Math.random() * (i+1));
randomIndexs.push(indexs[j]);
indexs.splice(j,1);
}
return randomIndexs
}
|
9922fc06f4caff5b73eb4da21d23de4c15c1e8bc
|
TypeScript
|
tuxcy17/typescript-dp
|
/src/Observer/Subject.ts
| 2.859375
| 3
|
import * as _ from 'underscore';
import {Observer} from './Observer';
abstract class Subject {
// Fields
private observers: Array<Observer> = [];
public attach(observer: Observer): void {
this.observers.push(observer);
}
public detach(observer: Observer): void {
let index: number;
_.each(this.observers, (o, i) => {
if (o === observer) {
index = i;
}
});
if (index != null) {
this.observers.splice(index, 1);
}
}
public notifyObservers(): Array<any> {
const res = [];
_.each(this.observers, function (o) {
res.push(o.update());
});
return res;
}
}
class ConcreteSubject extends Subject {
private subjectState: string;
public getSubjectState(): string {
return this.subjectState;
}
public setSubjectState(value: string): void {
this.subjectState = value;
}
}
export {ConcreteSubject, Subject};
|
68d135492980cdd6c5e3f96c92f604b914685c0e
|
TypeScript
|
OctopusDeploy/OctoTFS
|
/source/tasks/Utils/taskInput.ts
| 3.046875
| 3
|
import * as tasks from "azure-pipelines-task-lib/task";
export interface TaskWrapper {
getInput(name: string, required?: boolean): string | undefined;
getBoolean(name: string, required?: boolean): boolean | undefined;
setSuccess(message: string, done?: boolean): void;
setFailure(message: string, done?: boolean): void;
setOutputVariable(name: string, value: string): void;
getVariable(name: string): string | undefined;
getOutputVariable(step: string, name: string): string | undefined;
}
export class ConcreteTaskWrapper implements TaskWrapper {
public getInput(name: string, required?: boolean): string | undefined {
return tasks.getInput(name, required);
}
public getBoolean(name: string, required?: boolean): boolean | undefined {
return tasks.getBoolInput(name, required);
}
public setSuccess(message: string, done?: boolean) {
tasks.setResult(tasks.TaskResult.Succeeded, message, done);
}
public setFailure(message: string, done?: boolean) {
tasks.setResult(tasks.TaskResult.Failed, message, done);
}
public setOutputVariable(name: string, value: string) {
tasks.setVariable(name, value, false, true);
}
public getVariable(name: string): string | undefined {
return tasks.getVariable(name);
}
public getOutputVariable(step: string, name: string): string | undefined {
return tasks.getVariable(`${step}.${name}`);
}
}
|
a2ee105eb3ea3dc22f4f31b429e11251e578d9dc
|
TypeScript
|
gfregalado/Typescript-Sandbox
|
/Typescript 3rd Party Libraries & Typescript/src/app.ts
| 2.875
| 3
|
import "reflect-metadata"
import {plainToClass} from "class-transformer"
import { Product } from "./product.model"
const products = [{title:"A Carpet", price: 29.99}, {title:"A Carpet 2", price: 39.99}]
//const p1 = new Product('A book', 12.99)
/* const loadedProducts = products.map(prod => {
return new Product(prod.title, prod.price);
})
*/
const loadedProducts = plainToClass(Product, products)
for (const prod of loadedProducts){
console.log(prod.getInformation())
}
|
87e5010d6ec6f70a54741c3d9fa3fc14b35d3bd9
|
TypeScript
|
nicolas-zanardo/crm_and_stockWine
|
/assets/app/shared/components/navbar/employees/mainNavbar/nav/components/MainTopBar.ts
| 2.8125
| 3
|
import ComponentsMainNavBar from "../ComponentsMainNavBar";
export default class MainTopBar extends ComponentsMainNavBar {
constructor() {
super();
this.onInit();
this.endLoad();
}
/**
* onInit()
* --------
* function that starts when the class is instantiated
* @private
*/
protected onInit(): void {
this.clickNavbarBrand();
this.setDisplayLeftBar();
}
/**
* onload()
* -------
* function that starts when the page is finished loading
* @private
*/
protected endLoad(): void {
window.addEventListener("load", () => {
this.setValueFasMenu();
});
}
/**
* setValueFasMenu()
* -----------------
* Constraint: Onload
* Control the Dynamics SCC fontaswome for the menu navbar
* @private
*/
private setValueFasMenu() {
const navbarBrandFont = this.mainTopBarBrand!
.querySelector(".navbar-brand>svg");
// NavBar Is Open
if (localStorage.getItem("isOpenNavBar") == "open") {
navbarBrandFont!.classList.add("fa-bars");
navbarBrandFont!.classList.replace("fa-bars", "fa-times");
}
// NavBar Is Close
if (localStorage.getItem("isOpenNavBar") == "close") {
navbarBrandFont!.classList.add("fa-times");
navbarBrandFont!.classList.replace("fa-times", "fa-bars");
}
// NavBar Is not initialized
if (localStorage.getItem("isOpenNavBar") == undefined || null) {
navbarBrandFont!.classList.remove("fa-times");
navbarBrandFont!.classList.add("fa-bars");
}
}
/**
* setDisplayLeftBar
* -----------------
* Open and close whit CSS main left nav bar
* @private
*/
private setDisplayLeftBar() {
const navbarBrandSelect_i: HTMLElement | null = this.mainTopBar!
.querySelector(".navbar-brand>i")
// NavBar Is Open
if (localStorage.getItem("isOpenNavBar") == "open") {
this.mainLeftBar!.style.left = "0px";
this.mainLeftUnderBar!.style.left = "-50px";
navbarBrandSelect_i!.classList.add("fa-times");
}
// NavBar Is Close
if (localStorage.getItem("isOpenNavBar") == "close") {
navbarBrandSelect_i!.classList.add("fa-bars");
this.mainLeftBar!.style.left = "-50px";
this.mainLeftUnderBar!.style.left = "-100px";
}
// NavBar Is not initialized
if (localStorage.getItem("isOpenNavBar") == undefined || null) {
navbarBrandSelect_i!.classList.add("fa-bars");
this.mainLeftBar!.style.left = "0px";
this.mainLeftUnderBar!.style.left = "-50px";
}
}
/**
* clickNavbarBrand()
* ------------------
* Open and close the left navBar
* @private
*/
private clickNavbarBrand(): void {
this.mainTopBarBrand!.addEventListener('click', () => {
// Initialisation value CSS with JS
if (this.mainLeftBar!.style.left == "" || this.mainLeftUnderBar!.style.left == "") {
this.mainLeftBar!.style.left = "-50px";
this.mainLeftUnderBar!.style.left = "-100px";
}
// If left navbar is close
if (this.mainLeftBar!.style.left === "-50px" &&
this.mainLeftUnderBar!.style.left === "-100px") {
this.mainLeftBar!.style.left = "0px";
this.mainLeftUnderBar!.style.left = "-50px";
// Set value in local storage for don't change the
// status of navbar
localStorage.setItem("isOpenNavBar", "open");
this.setValueFasMenu();
} else {
this.mainLeftBar!.style.left = "-50px";
this.mainLeftUnderBar!.style.left = "-100px";
// Set value in local storage for don't change the
// status of navbar
localStorage.setItem("isOpenNavBar", "close");
this.setValueFasMenu();
}
})
}
}
|
0e5718177af2e40a3570b772172310fa1666b2a9
|
TypeScript
|
msdiles/scylla
|
/client/src/state/types/app.types.ts
| 2.65625
| 3
|
export const APP_SET_ERROR = "APP_SET_ERROR"
export const APP_REMOVE_ERROR = "APP_REMOVE_ERROR"
export const APP_SET_MESSAGE = "APP_SET_MESSAGE"
export const APP_REMOVE_MESSAGE = "APP_REMOVE_MESSAGE"
export const APP_REDIRECT = "APP_REDIRECT"
//SetError
export interface SetErrorPayload {
error: string
}
interface SetErrorAction {
type: typeof APP_SET_ERROR
payload: SetErrorPayload
}
//RemoveError
export interface RemoveErrorPayload {
error: string
}
interface RemoveErrorAction {
type: typeof APP_REMOVE_ERROR
payload: RemoveErrorPayload
}
//SetMessage
export interface SetMessagePayload {
message: string
}
interface SetMessageAction {
type: typeof APP_SET_MESSAGE
payload: SetMessagePayload
}
//RemoveMessage
export interface RemoveMessagePayload {
error: string
}
interface RemoveMessageAction {
type: typeof APP_REMOVE_MESSAGE
payload: RemoveMessagePayload
}
//Redirect
export interface RedirectPayload {
path: string
}
export interface RedirectAction {
type: typeof APP_REDIRECT
payload: RedirectPayload
}
export type AppActionTypes =
| SetErrorAction
| RemoveErrorAction
| SetMessageAction
| RemoveMessageAction
| RedirectAction
|
cd4b0f7145b105b10fc6e6d707896264a4cbf8b1
|
TypeScript
|
kiurchv/fhir-codegen
|
/src/generated/FhirSampledData.ts
| 2.609375
| 3
|
import * as t from 'io-ts'
import { FhirDecimal } from './FhirDecimal'
import { FhirElement } from './FhirElement'
import { FhirExtension } from './FhirExtension'
import { FhirPositiveInt } from './FhirPositiveInt'
import { FhirQuantity } from './FhirQuantity'
import { FhirString } from './FhirString'
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
export const FhirSampledData: t.Type<FhirSampledData, FhirSampledDataOutput> = t.recursion('FhirSampledData', () =>
t.intersection([
t.type({
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
origin: t.readonly(FhirQuantity),
}),
t.partial({
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_data: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_dimensions: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_factor: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_lowerLimit: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_period: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_upperLimit: t.readonly(FhirElement),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
data: t.readonly(FhirString),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
dimensions: t.readonly(FhirPositiveInt),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
extension: t.readonlyArray(FhirExtension),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
factor: t.readonly(FhirDecimal),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
id: t.readonly(FhirString),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
lowerLimit: t.readonly(FhirDecimal),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
period: t.readonly(FhirDecimal),
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
upperLimit: t.readonly(FhirDecimal),
}),
])
)
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
export interface FhirSampledData {
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_data?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_dimensions?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_factor?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_lowerLimit?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_period?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_upperLimit?: Readonly<t.TypeOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
data?: Readonly<t.TypeOf<typeof FhirString>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
dimensions?: Readonly<t.TypeOf<typeof FhirPositiveInt>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
extension?: ReadonlyArray<t.TypeOf<typeof FhirExtension>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
factor?: Readonly<t.TypeOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
id?: Readonly<t.TypeOf<typeof FhirString>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
lowerLimit?: Readonly<t.TypeOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
origin: Readonly<t.TypeOf<typeof FhirQuantity>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
period?: Readonly<t.TypeOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
upperLimit?: Readonly<t.TypeOf<typeof FhirDecimal>>
}
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
export interface FhirSampledDataOutput {
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_data?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_dimensions?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_factor?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_lowerLimit?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_period?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
_upperLimit?: Readonly<t.OutputOf<typeof FhirElement>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
data?: Readonly<t.OutputOf<typeof FhirString>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
dimensions?: Readonly<t.OutputOf<typeof FhirPositiveInt>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
extension?: ReadonlyArray<t.OutputOf<typeof FhirExtension>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
factor?: Readonly<t.OutputOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
id?: Readonly<t.OutputOf<typeof FhirString>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
lowerLimit?: Readonly<t.OutputOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
origin: Readonly<t.OutputOf<typeof FhirQuantity>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
period?: Readonly<t.OutputOf<typeof FhirDecimal>>
/** A series of measurements taken by a device, with upper and lower limits. There may be more than one dimension in the data. */
upperLimit?: Readonly<t.OutputOf<typeof FhirDecimal>>
}
|
2a82d798d5e4b07883744328e6292cfd97ff058e
|
TypeScript
|
chromium/chromium
|
/ui/file_manager/file_manager/state/ducks/folder_shortcuts_unittest.ts
| 2.515625
| 3
|
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(b/296792757)
import '../store.js';
import {MockFileSystem} from '../../common/js/mock_entry.js';
import {State} from '../../externs/ts/state.js';
import {setUpFileManagerOnWindow, setupStore, waitDeepEquals} from '../for_tests.js';
import {convertEntryToFileData} from '../reducers/all_entries.js';
import {getEmptyState} from '../store.js';
import {addFolderShortcut, refreshFolderShortcut, removeFolderShortcut} from './folder_shortcuts.js';
export function setUp() {
setUpFileManagerOnWindow();
}
/** Generate a fake file system with fake file entries. */
function setupFileSystem(): MockFileSystem {
const fileSystem = new MockFileSystem('fake-fs');
fileSystem.populate([
'/shortcut-1/',
'/shortcut-2/',
'/shortcut-3/',
'/shortcut-4/',
]);
return fileSystem;
}
/** Tests folder shortcuts can be refreshed correctly. */
export async function testRefreshFolderShortcuts(done: () => void) {
const initialState = getEmptyState();
// Add shortcut-1 to the store.
const fileSystem = setupFileSystem();
const shortcutEntry1: DirectoryEntry = fileSystem.entries['/shortcut-1'];
initialState.allEntries[shortcutEntry1.toURL()] =
convertEntryToFileData(shortcutEntry1);
initialState.folderShortcuts.push(shortcutEntry1.toURL());
const store = setupStore(initialState);
// Dispatch a refresh action with shortcut 2 and 3.
const shortcutEntry2: DirectoryEntry = fileSystem.entries['/shortcut-2'];
const shortcutEntry3: DirectoryEntry = fileSystem.entries['/shortcut-3'];
store.dispatch(
refreshFolderShortcut({entries: [shortcutEntry2, shortcutEntry3]}));
// Expect all shortcut entries are in allEntries, and only shortcut 2 and 3
// are in the folderShortcuts.
const want: Partial<State> = {
allEntries: {
[shortcutEntry2.toURL()]: convertEntryToFileData(shortcutEntry2),
[shortcutEntry3.toURL()]: convertEntryToFileData(shortcutEntry3),
},
folderShortcuts: [shortcutEntry2.toURL(), shortcutEntry3.toURL()],
};
await waitDeepEquals(store, want, (state) => ({
allEntries: state.allEntries,
folderShortcuts: state.folderShortcuts,
}));
done();
}
/** Tests folder shortcut can be added correctly. */
export async function testAddFolderShortcut(done: () => void) {
const initialState = getEmptyState();
// Add shortcut-1 and shortcut-3 to the store.
const fileSystem = setupFileSystem();
const shortcutEntry1: DirectoryEntry = fileSystem.entries['/shortcut-1'];
const shortcutEntry3: DirectoryEntry = fileSystem.entries['/shortcut-3'];
initialState.allEntries[shortcutEntry1.toURL()] =
convertEntryToFileData(shortcutEntry1);
initialState.allEntries[shortcutEntry3.toURL()] =
convertEntryToFileData(shortcutEntry3);
initialState.folderShortcuts.push(shortcutEntry1.toURL());
initialState.folderShortcuts.push(shortcutEntry3.toURL());
const store = setupStore(initialState);
// Dispatch an action to add shortcut 4.
const shortcutEntry4: DirectoryEntry = fileSystem.entries['/shortcut-4'];
store.dispatch(addFolderShortcut({entry: shortcutEntry4}));
// Expect the newly added shortcut 4 is in the store.
const want1: Partial<State> = {
allEntries: {
[shortcutEntry1.toURL()]: convertEntryToFileData(shortcutEntry1),
[shortcutEntry3.toURL()]: convertEntryToFileData(shortcutEntry3),
[shortcutEntry4.toURL()]: convertEntryToFileData(shortcutEntry4),
},
folderShortcuts: [
shortcutEntry1.toURL(),
shortcutEntry3.toURL(),
shortcutEntry4.toURL(),
],
};
await waitDeepEquals(store, want1, (state) => ({
allEntries: state.allEntries,
folderShortcuts: state.folderShortcuts,
}));
// Dispatch another action to add already existed shortcut 1.
store.dispatch(addFolderShortcut({entry: shortcutEntry1}));
// Expect no changes in the store.
await waitDeepEquals(store, want1, (state) => ({
allEntries: state.allEntries,
folderShortcuts: state.folderShortcuts,
}));
// Dispatch another action to add shortcut 2 to check sorting.
const shortcutEntry2: DirectoryEntry = fileSystem.entries['/shortcut-2'];
store.dispatch(addFolderShortcut({entry: shortcutEntry2}));
// Expect shortcut 2 will be inserted in the middle.
const want2: Partial<State> = {
allEntries: {
...want1.allEntries,
[shortcutEntry2.toURL()]: convertEntryToFileData(shortcutEntry2),
},
folderShortcuts: [
shortcutEntry1.toURL(),
shortcutEntry2.toURL(),
shortcutEntry3.toURL(),
shortcutEntry4.toURL(),
],
};
await waitDeepEquals(store, want2, (state) => ({
allEntries: state.allEntries,
folderShortcuts: state.folderShortcuts,
}));
done();
}
/** Tests folder shortcut can be removed correctly. */
export async function testRemoveFolderShortcut(done: () => void) {
const initialState = getEmptyState();
// Add shortcut-1 to the store.
const fileSystem = setupFileSystem();
const shortcutEntry1: DirectoryEntry = fileSystem.entries['/shortcut-1'];
initialState.allEntries[shortcutEntry1.toURL()] =
convertEntryToFileData(shortcutEntry1);
initialState.folderShortcuts.push(shortcutEntry1.toURL());
const store = setupStore(initialState);
// Dispatch an action to remove shortcut 1.
store.dispatch(removeFolderShortcut({key: shortcutEntry1.toURL()}));
// Expect shortcut 1 is removed from the store.
await waitDeepEquals(store, [], (state) => state.folderShortcuts);
// Dispatch another action to remove non-existed shortcut 2.
const shortcutEntry2: DirectoryEntry = fileSystem.entries['/shortcut-2'];
store.dispatch(removeFolderShortcut({key: shortcutEntry2.toURL()}));
// Expect no changes in the store.
await waitDeepEquals(store, [], (state) => state.folderShortcuts);
done();
}
|
ba460fe519d9575a1373bd603d9b0d6dc6fbc7dc
|
TypeScript
|
vinodharani/TypeScript-Basics
|
/enum/enum.ts
| 3.578125
| 4
|
enum DaysOfTheWeek {
MON = 1, TUE, WED, THU, FRI, SAT, SUN
}
// when you assign a value to MON, the other days takes a value of 2, 3, 4 etc
// or you can manually assign a value by using the =
let day : DaysOfTheWeek;
day = DaysOfTheWeek.MON;
if (day === DaysOfTheWeek.MON) {
console.log("Got to go to work")
}
|
1918fc276779e104226785abc9d07571d4447b2e
|
TypeScript
|
PierreLeduc/RobotlegsJS
|
/src/robotlegs/bender/framework/impl/getQualifiedClassName.ts
| 3
| 3
|
// ------------------------------------------------------------------------------
// Copyright (c) 2017-present, RobotlegsJS. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
// ------------------------------------------------------------------------------
/*============================================================================*/
/* Public Functions */
/*============================================================================*/
/**
* Returns the fully qualified class name of an object. Support EcmaScript from v3 upto v6.
*
* @param {any} value The object for which a fully qualified class name is desired.
* @return {string} A string containing the fully qualified class name.
*/
export function getQualifiedClassName(value: any): string {
// es pattern
let v3: RegExp = /function\ ([^\(]+)/;
let v6: RegExp = /class\ ([^\ ]+)/;
let classDescriptor: string = value.toString();
let result: RegExpMatchArray = classDescriptor.match(v3) || classDescriptor.match(v6);
return result[1];
}
|
ea43cd302f0f02bfaf9204fcf819570b5638ffbb
|
TypeScript
|
miryambathilde/ListadoEmpleados
|
/src/app/components/empleado-list/empleado-list.component.ts
| 2.671875
| 3
|
import { Component, OnInit } from '@angular/core';
/* modelo de la clase empleado */
import { Empleado } from 'src/app/models/Empleado';
@Component({
selector: 'app-empleado-list',
templateUrl: './empleado-list.component.html',
styleUrls: ['./empleado-list.component.css']
})
export class EmpleadoListComponent implements OnInit {
/* iteramos el array de la variable listEmpleados donde iteramos el modelo de la clase Empleado y el array con las propiedades */
listEmpleados: Empleado [] = [
{numeroEmpleado: 1, nombre: 'Sergio', apellidos: 'Sรกnchez', sexo:'Masculino', salario: 15000, moneda: 'โฌ'},
{numeroEmpleado: 2, nombre: 'Miryam', apellidos: 'Bathilde', sexo:'Femenino', salario: 35000, moneda: 'โฌ'},
{numeroEmpleado: 3, nombre: 'Oliver', apellidos:'Crevillen', sexo:'Masculino', salario: 10000, moneda: 'โฌ'},
{numeroEmpleado: 4, nombre: 'Manuela', apellidos: 'Pรฉrez', sexo:'Femenino', salario: 18000, moneda: 'โฌ'},
{numeroEmpleado: 5, nombre: 'Lola', apellidos: 'Lozano', sexo:'Femenino', salario: 20000, moneda: 'โฌ'},
{numeroEmpleado: 6, nombre: 'Sergio', apellidos: 'De Sousa', sexo:'Masculino', salario: 22000, moneda: 'โฌ'},
{numeroEmpleado: 7, nombre: 'Luca', apellidos: 'De Sousa', sexo:'Masculino', salario: 17000, moneda: 'โฌ'},
]
/* variable de ngmodel que por defecto va a tener todos los sexos */
radioButtonSeleccionado = 'Todos';
constructor() { }
ngOnInit(): void {
}
/* metodo para obtener el total de empleados que nos devuelve un number, y le decimos que devuelva la longitud de numeros del array de listEmpleados */
obtenerTotalEmpleados(): number {
return this.listEmpleados.length;
}
/* metodo para obtener el total de empleados FEMENINOS que nos devuelve un number, y le decimos que devuelva la lista de empleados filtrada por sexo
y pasamos por parametro
el arrow function en donde dentro de list el sexo sea exactamente igual a Femenino + el numero de empleados femeninos */
obtenerTotalFemeninos(): number {
return this.listEmpleados.filter(list => list.sexo === 'Femenino').length;
}
/* metodo para obtener el total de empleados FEMENINPOS que nos devuelve un number, y le decimos que devuelva la lista de empleados filtrada
por sexo y pasamos por parametro
el arrow function en donde dentro de list el sexo sea exactamente igual a Masculino + el numero de empleados femeninos */
obtenerTotalMasculinos(): number {
return this.listEmpleados.filter(list => list.sexo === 'Masculino').length;
}
/* IMPORTAMOS EL METODO empleadoNumeroRadioButtonChange del componente hijo, le pasamos por parametro
radioButtonSelect que es de tipo y string y no devuelve nada */
empleadoNumeroRadioButtonChange(radioButtonSelect: string): void {
/* le pasamos radioButtonSeleccionado que es la variable declarada arriba para todos, y le ponemos como valor
lo que nos llege por el metodo con el parametro radioButtonSelect */
this.radioButtonSeleccionado = radioButtonSelect;
}
}
|
0da0b0e8ff2e4a8faa587799998d96aa0ff8116d
|
TypeScript
|
paullewallencom/angular-978-1-7864-6669-3
|
/_/Section 5/app.component.ts
| 2.578125
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'd3-app',
template: `
<div [style.background]="backgroundColor">
<h2>Hello, world! I'm learning {{course}} and my favorite color is <span [style.color]="favoriteColor">{{favoriteColor}}</span>.</h2>
<label>Enter favorite color: </label><input type="text" [(ngModel)]="favoriteColor">
<button (click)="changeBackgroundColor()">Change background color</button>
</div>
`
})
export class AppComponent {
backgroundColor = 'white';
course = 'Angular 2';
favoriteColor = 'black';
changeBackgroundColor() {
this.backgroundColor = this.backgroundColor === 'white' ? 'grey' : 'white';
}
}
|
cfd48a3907635c23038ccd20b91b18a6862b3df5
|
TypeScript
|
anzen-marco/heroes
|
/src/app/heroes/heroes.component.ts
| 3.5625
| 4
|
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero'; //Se importa la interface creada
import { HEROES } from '../mock-heroes'; //Listado de hรฉroes demos guardados en un array con los que se va a trabajar.
import { HeroService } from '../hero.service';//Se importa el servicio.
import { MessageService } from '../message.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.scss']
})
export class HeroesComponent implements OnInit {
/*
private: indica que la variable solo funciona dentro de la clase.
heroService: es el nombre de la propiedad con la que s ellamarรก ene l cรณdigo. pued ser cualquier nombre.
HerService: el nombre con el que se inyecta, se define en el import.
*/
constructor(private heroService: HeroService, private messageService: MessageService) { }
/*
El tipo se define Hero, la cual perence a la interface Hero importada y que se puede urlizar dentro del cรณdigo
Se deben utilizar todas los tipos marcados en hero.ts, de lo contrario se marcarรก un error.
*/
hero: Hero = { //Se define el tipo hero como base la interfase Hero.
id: 10000, //Dato que e sposible escribir dada la interfase.
name: 'Windstorm',
element: 'Wind' //No se puede agregar una propiedad si no esta definida en la interface.
}
/*
Se define una nueva propiedad para poder mostrar la lista demo de Hรฉroes
heroes: nombre de la propiedad.
HEROES: Array creado en mock-heroes.ts el cual trae la lista de hรฉroes.
*/
//heroes = HEROES;
/*
Se define el tipo selectedHero basado en la interface Hero.
onSelect: es el mรฉtodo que engloba la funcionalidad de seleccionar la propiedad de la interface. El nombre puede ser el que sea..
void: como la funciรณn no regresanada, se utiliza void para delimitarlo.
this: serefiere al alemento individual de la lista. Es como un querySelector de javascript.
selectedHero: hace referencia al tipo SelectedHero declarado arriba,
hero: hace referencia al tipo hero declarado arriba que contiene los datos que se van a mostrar.
*/
selectedHero: Hero;
onSelect(hero: Hero): void {
this.selectedHero = hero;
this.messageService.add('HeroesComponent: Hรฉroe seleccionado id=${hero.id}');
}
heroes: Hero[];
/*
Este mรฉtodo regresa la informaciรณnd e los hรฉroes desde el servicio.
Asigna un array de hรฉroes a la propiedas heroes.
getHeroes(): nombre del mรฉtodo.
this: hace referencia al mismo mรฉtodo
getHeroes(): void {
this.heroes = this.heroService.getHeroes();
}
*/
/*
.subscribe: es un mรฉtodo de RxJS el cual pasa el array a la llamada.
*/
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
ngOnInit(): void {
//console.log(HEROES);
this.getHeroes(); //Se llama el mรฉtodo
//console.log(getHeroes());
}
}
|
dcb6260f0c30b56027045721f8dddacc371fb388
|
TypeScript
|
krivtsov/exercism
|
/typescript/space-age/space-age.ts
| 3.203125
| 3
|
class SpaceAge {
seconds: number;
constructor(age: number) {
this.seconds = age;
}
getAge = (planetYear: number) => +(this.seconds / 60 / 60 / 24 / 365.25 / planetYear).toFixed(2);
onEarth = () => {
const earthYear = 1;
return this.getAge(earthYear);
};
onMercury() {
const mercuryYear = 0.2408467;
return this.getAge(mercuryYear);
}
onVenus = () => {
const venusYear = 0.61519726;
return this.getAge(venusYear);
};
onMars() {
const marsYear = 1.8808158;
return this.getAge(marsYear);
}
onJupiter() {
const jupiterYear = 11.862615;
return this.getAge(jupiterYear);
}
onSaturn() {
const saturnYear = 29.447498;
return this.getAge(saturnYear);
}
onUranus() {
const uranusYear = 84.016846;
return this.getAge(uranusYear);
}
onNeptune() {
const neptuneYear = 164.79132;
return this.getAge(neptuneYear);
}
}
export default SpaceAge;
|
877501a8df73c1acbe803a5e93c8fdd0847205e6
|
TypeScript
|
rpinaa/spa-architecture-angular-domain
|
/src/app/common/pipes/enumeration.pipe.ts
| 2.53125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enumeration'
})
export class EnumerationPipe implements PipeTransform {
transform(value: number, args?: number): string {
return value ? ('0' + value).slice(-args) : value + '';
}
}
|
5a323c57e6c82efd98290fd603fa060f269753e0
|
TypeScript
|
sorsogon/production
|
/src/utils/filters.ts
| 2.6875
| 3
|
import Vue, { PluginObject } from 'vue';
export default new class implements PluginObject<undefined> {
public install(_Vue: typeof Vue) {
/**
*
*/
Vue.filter('formatDateString', (date: Date) => {
const dateString = date.toLocaleDateString();
const time: any[] = [ date.getHours(), date.getMinutes(), date.getSeconds() ];
time.forEach((mem, i) => {
time[i] = mem < 10 ? `0${mem}` : mem == 24 ? '00' : mem;
});
return dateString + ' ' + time.join(':');
});
/**
*
*/
Vue.filter('formatAddress', (address: _object) => {
return `${address.city}, ${address.barangay}`;
});
/**
*
*/
Vue.filter('formatCurrency', (num: string | number) => {
num = num ?? 0;
return 'โฑ ' + num.toLocaleString('us', {minimumFractionDigits: 2, maximumFractionDigits: 2});
});
/**
*
*/
Vue.filter('formatTimeString', (num: number) => {
return Math.round(num/1e3);
});
}
}
|
73a95680d68359d527e856448517b3646fd97b1d
|
TypeScript
|
marinp1/toggl-2-toggl
|
/service/types/dynamo.ts
| 3.078125
| 3
|
export type DynamoSingleValue = string | number | boolean | null;
export type DynamoMapValue<T extends Record<string, any> = {}> = {
readonly [x in keyof T]: T[x] extends object
? DynamoMapValue<T[x]>
: T[x] extends any[]
? DynamoArrayValue<T[x]>
: T[x];
};
export interface DynamoArrayValue<T>
extends Array<DynamoArrayValue<T> | DynamoSingleValue | DynamoMapValue<T>> {}
export type DynamoValueType<T extends object = {}> =
| DynamoSingleValue
| DynamoMapValue<T>
| DynamoArrayValue<T>;
|
53884422b8eb9755d97c94b268aadb6cbd2235e9
|
TypeScript
|
NepipenkoIgor/rxjs200321
|
/0-theory/old/multicasting.ts
| 2.6875
| 3
|
import { BehaviorSubject, ConnectableObservable, interval, ReplaySubject, Subject, Subscription } from "rxjs";
import { multicast, publish, refCount, share } from "rxjs/operators";
const sequence$ = interval(1000)
.pipe(
share()
// publish + refCount = share()
// multicast(subject) = publish
); // as ConnectableObservable<any>
// sequence$.connect();
let sub1: Subscription;
setTimeout(() => {
sub1 = sequence$.subscribe((v) => {
console.log('Sub 1', v)
})
}, 1000)
setTimeout(() => {
sub1.unsubscribe();
}, 3000)
setTimeout(() => {
sequence$.subscribe((v) => {
console.log('Sub 2', v)
})
}, 5000)
|
b93857a8299795fc2e0719122b994f1f6709fd58
|
TypeScript
|
neat-soft/next.js
|
/packages/next/build/compiler.ts
| 2.609375
| 3
|
import webpack from 'webpack'
export type CompilerResult = {
errors: Error[],
warnings: Error[]
}
export function runCompiler (config: webpack.Configuration[]): Promise<CompilerResult> {
return new Promise(async (resolve, reject) => {
const compiler = webpack(config)
compiler.run((err, multiStats: any) => {
if (err) {
return reject(err)
}
const result: CompilerResult = multiStats.stats.reduce((result: CompilerResult, stat: webpack.Stats): CompilerResult => {
if (stat.compilation.errors.length > 0) {
result.errors.push(...stat.compilation.errors)
}
if (stat.compilation.warnings.length > 0) {
result.warnings.push(...stat.compilation.warnings)
}
return result
}, {errors: [], warnings: []})
resolve(result)
})
})
}
|
cf8071e1bba6aa4f3940d1746e617f2ca7ffbf21
|
TypeScript
|
RaduSzasz/TS2JaVerT
|
/src/assertions/CustomPredicate.ts
| 2.859375
| 3
|
import { AssertionKind } from "./Assertion";
import { AssertionObject } from "./AssertionObject";
export class CustomPredicate extends AssertionObject {
private readonly varNames: string[];
constructor(private predicateName: string, ...varNames: string[]) {
super (AssertionKind.Custom);
this.varNames = varNames;
}
public toString() {
return `${this.predicateName}(${this.varNames.join(", ")})`;
}
public getThisAssertion() {
const [first] = this.varNames;
if (first === "this") {
return this;
}
return undefined;
}
}
|
538a06c9e221ad73fde8950e9cfe974bc3d515ff
|
TypeScript
|
forkkit/rippledb
|
/src/tests/sstable.test.ts
| 2.625
| 3
|
import fs from 'fs'
import Slice from '../Slice'
import SSTable from '../SSTable'
import SSTableBuilder from '../SSTableBuilder'
import { getTableFilename } from '../Filename'
import { createDir, cleanup } from '../../fixtures/dbpath'
import { Options } from '../Options'
import { random } from '../../fixtures/random'
import { InternalKey, SequenceNumber, ValueType } from '../Format'
const dbpath = createDir()
afterAll(() => cleanup(dbpath))
cleanup(dbpath)
test('sstable', async () => {
await fs.promises.mkdir(dbpath, { recursive: true })
const fd1 = await fs.promises.open(getTableFilename(dbpath, 1), 'w')
const builder = new SSTableBuilder(new Options(), fd1)
const count = 1000
let i = 0
const list = []
while (i < count) {
list.push(random())
i++
}
i = 0
list.sort((a, b) =>
Buffer.from(a[0]).compare(Buffer.from(b[0])) < 0 ? -1 : 1
)
while (i < count) {
const [key, value] = list[i]
const ikey = new InternalKey(
new Slice(key),
new SequenceNumber(i),
ValueType.kTypeValue
)
await builder.add(ikey, new Slice(value))
i++
}
await builder.finish()
const fd = await fs.promises.open(getTableFilename(dbpath, 1), 'r+')
const table = await SSTable.open(new Options(), fd)
const listKeys = []
const listValues = []
for await (const entry of table.entryIterator()) {
const ikey = InternalKey.from(entry.key)
listKeys.push(ikey.userKey.toString())
listValues.push(entry.value.toString())
}
expect(list.map(pair => pair[0]).join('|')).toEqual(listKeys.join('|'))
expect(list.map(pair => pair[1]).join('|')).toEqual(listValues.join('|'))
})
|
56cf40ccc9fe7b8d277a3e00603823328d805413
|
TypeScript
|
here4you81/n2server
|
/back/src/apple/apple.service.ts
| 2.546875
| 3
|
import { Injectable } from '@nestjs/common';
import { CreateAppleDto } from './dto/create-apple.dto';
import { UpdateAppleDto } from './dto/update-apple.dto';
@Injectable()
export class AppleService {
create(createAppleDto: CreateAppleDto) {
return 'This action adds a new apple';
}
findAll() {
return `This action returns all apple`;
}
findOne(id: number) {
return `This action returns a #${id} apple`;
}
update(id: number, updateAppleDto: UpdateAppleDto) {
return `This action updates a #${id} apple`;
}
remove(id: number) {
return `This action removes a #${id} apple`;
}
}
|
bba7f902fc0798f4a77b62c5874c3c70b7e3afab
|
TypeScript
|
VitaminCtea/ts-canvas
|
/src/scrollBar/map.ts
| 2.921875
| 3
|
export type Info<T = string> = {
offset: T,
scroll: T,
scrollSize: T,
size: T,
axis: T,
client: T,
direction: T,
content: T
}
type Map = {
vertical: Info
horizontal: Info
}
export const map: Map = {
vertical: {
offset: 'offsetHeight',
scroll: 'scrollTop',
scrollSize: 'scrollHeight',
size: 'height',
axis: 'Y',
client: 'clientY',
direction: 'top',
content: 'clientHeight'
},
horizontal: {
offset: 'offsetWidth',
scroll: 'scrollLeft',
scrollSize: 'scrollWidth',
size: 'width',
axis: 'X',
client: 'clientX',
direction: 'left',
content: 'clientWidth'
}
}
|
96408bb6d0270d877bda407c99a5d004cd731c10
|
TypeScript
|
fochlac/mui-feedback-dialog-connected
|
/lib/utils/http.ts
| 2.578125
| 3
|
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
}
export const getRequest = (url:string):Promise<unknown> => {
return fetch(url, { headers }).then((res) => (res.status < 400 ? res.json() : Promise.reject(res.json())))
}
export const postRequest = (url: string, body: Record<string, unknown>): Promise<Record<string, unknown>> => {
return fetch(url, {
headers,
method: 'POST',
body: JSON.stringify(body)
}).then((res) => (res.status < 400 ? res.json() : Promise.reject(res.json())))
}
|
99e76f3ffb2de427a8775af1271e4d85280eaeec
|
TypeScript
|
keff6/100AlgorithmsChallenge
|
/bishopAndPawn/bishopAndPawn.ts
| 3.40625
| 3
|
function bishopAndPawn(bishop: string, pawn: string): boolean {
const letterPosition = {
a: 1, b: 2, c: 3, d: 4,
e: 5, f: 6, g: 7, h: 8,
}
const [bishopX, bishopY] = [letterPosition[bishop[0]], parseInt(bishop[1])];
const [pawnX, pawnY] = [letterPosition[pawn[0]], parseInt(pawn[1])];
return (bishopX + pawnX === bishopY + pawnY) || (bishopX + bishopY === pawnX + pawnY)
}
console.log(bishopAndPawn('a1', 'c3'));
|
e966f1197bd577788285e9b484e03d31964c94ca
|
TypeScript
|
crisantizan/santz-framework-php
|
/public/typescript/src/libs/MethodValidate.ts
| 2.796875
| 3
|
// Clase que debe ser usada por cualquier controlador creado,
// permite llamar un mรฉtodo especรญfico cuando este existe
export class MethodValidate {
public methodExist (method:string) {
let self = 'this.';
method = `${self}${method}`;
return (eval(method));
}
}
|
0869ffe9ccd58adbee845516152fdf2c54a63feb
|
TypeScript
|
NotGamerPro/nodepolus2
|
/lib/packets/packetElements/clientVersion.ts
| 3.15625
| 3
|
export class ClientVersion {
public readonly year: number;
public readonly month: number;
public readonly day: number;
public readonly revision: number;
constructor(year: number, month: number, day: number, revision: number) {
this.year = year;
this.month = month;
this.day = day;
this.revision = revision;
}
static parse(version: number): ClientVersion {
let year = Math.floor(version / 25000);
version %= 25000;
let month = Math.floor(version / 1800);
version %= 1800;
let day = Math.floor(version / 50);
let revision = version % 50;
return new this(year, month, day, revision);
}
serialize(): number {
return (
this.year * 25000 + this.month * 1800 + this.day * 50 + this.revision
);
}
equals(otherVersion: ClientVersion): boolean {
return (
this.year == otherVersion.year &&
this.month == otherVersion.month &&
this.day == otherVersion.day &&
this.revision == otherVersion.revision
);
}
}
|
3dd99da5570828b25f310115bbf84e4fd155780a
|
TypeScript
|
easy261925/ant-design-pro-spring-boot
|
/src/utils/axios.ts
| 2.78125
| 3
|
import axios, { AxiosRequestConfig } from 'axios';
import { notification } from 'antd';
import { PROJECT_NAME } from '@/utils/CONSTANTS'
const PROJECT_TOKEN = `${PROJECT_NAME}_TOKEN`
/**
* ่ทๅ token ๏ผๆฅๅฃ่ฎฟ้ฎๆ้๏ผ
*/
const getToken = () => localStorage.getItem(PROJECT_TOKEN);
/**
* ่ฎพ็ฝฎ token
*/
const setToken = (token: string) => {
localStorage.setItem(PROJECT_TOKEN, token);
};
/**
* ็งป้ค token
*/
const removeToken = () => {
localStorage.removeItem(PROJECT_TOKEN);
};
/**
* ๅธธ่ง HTTP ็ถๆ็ ไธๆ่ฟฐ
*/
const toStatusText = (status: number) => {
const map = {
200: 'ๆๅ - ๆๅกๅจๅทฒๆๅ่ฟๅ่ฏทๆฑ็ๆฐๆฎ',
201: 'ๅทฒๅๅปบๆไฟฎๆน - ๆฐๅปบๆไฟฎๆนๆฐๆฎๆๅ',
202: 'ๅทฒๆฅๅ - ไธไธช่ฏทๆฑๅทฒ็ป่ฟๅ
ฅๅๅฐๆ้๏ผๅผๆญฅไปปๅก๏ผ',
204: 'ๅ ้คๆๅ - ๅ ้คๆฐๆฎๆๅ',
400: '้่ฏฏ่ฏทๆฑ - ๅๅบ็่ฏทๆฑๆ้่ฏฏ๏ผๆๅกๅจๆฒกๆ่ฟ่กๆฐๅปบๆไฟฎๆนๆฐๆฎ็ๆไฝ',
401: 'ๆชๆๆ - ็จๆทๆฒกๆๆ้๏ผไปค็ใ่ดฆๅทใๅฏ็ ้่ฏฏ๏ผ',
403: '็ฆๆญข - ็จๆทๅพๅฐๆๆ๏ผไฝๆฏ่ฎฟ้ฎๆฏ่ขซ็ฆๆญข็',
404: 'ๆชๆพๅฐ - ๅๅบ็่ฏทๆฑ้ๅฏน็ๆฏไธๅญๅจ็่ฎฐๅฝ๏ผๆๅกๅจๆฒกๆ่ฟ่กๆไฝ',
405: 'ๆนๆณ็ฆ็จ - ็ฆ็จ่ฏทๆฑไธญๆๅฎ็ๆนๆณ',
406: 'ไธๆฅๅ - ่ฏทๆฑ็ๆ ผๅผไธๅฏๅพ',
408: '่ฏทๆฑ่ถ
ๆถ - ๆๅกๅจ็ญๅ่ฏทๆฑๆถๅ็่ถ
ๆถ',
410: 'ๅทฒๅ ้ค - ่ฏทๆฑ็่ตๆบ่ขซๆฐธไน
ๅ ้ค๏ผไธไธไผๅๆขๅค',
412: 'ๆชๆปก่ถณๅๆๆกไปถ - ๆๅกๅจๆชๆปก่ถณ่ฏทๆฑ่
ๅจ่ฏทๆฑไธญ่ฎพ็ฝฎ็ๅ
ถไธญไธไธชๅๆๆกไปถ',
413: '่ฏทๆฑๅฎไฝ่ฟๅคง - ๆๅกๅจๆ ๆณๅค็่ฏทๆฑ๏ผๅ ไธบ่ฏทๆฑๅฎไฝ่ฟๅคง๏ผ่ถ
ๅบๆๅกๅจ็ๅค็่ฝๅ',
414: '่ฏทๆฑ็URI่ฟ้ฟ - ่ฏทๆฑ็URI๏ผ้ๅธธไธบ็ฝๅ๏ผ่ฟ้ฟ๏ผๆๅกๅจๆ ๆณๅค็',
415: 'ไธๆฏๆ็ๅชไฝ็ฑปๅ - ่ฏทๆฑ็ๆ ผๅผไธๅ่ฏทๆฑ้กต้ข็ๆฏๆ',
422: '้ช่ฏ้่ฏฏ - ๅฝๅๅปบไธไธชๅฏน่ฑกๆถ๏ผๅ็ไธไธช้ช่ฏ้่ฏฏ',
500: 'ๆๅกๅจๅ
้จ้่ฏฏ - ๆๅกๅจๅ็้่ฏฏ๏ผ่ฏทๆฃๆฅๆๅกๅจ',
502: '็ฝๅ
ณ้่ฏฏ - ้่ฏฏ็็ฝๅ
ณ',
503: 'ๆๅกไธๅฏ็จ - ๆๅกๅจๆๆถ่ฟ่ฝฝๆ็ปดๆค',
504: '็ฝๅ
ณ่ถ
ๆถ - ๆๅกๅจไฝไธบ็ฝๅ
ณๆไปฃ็๏ผไฝๆฏๆฒกๆๅๆถไปไธๆธธๆๅกๅจๆถๅฐ่ฏทๆฑ',
};
return map[status];
};
interface RequestConfig {
method?: string,
responseType?: any,
body?: Object,
headers?: Object,
cache?: boolean,
}
/**
* request ๆนๆณ๏ผaxios ็็ฎๅๅฐ่ฃ
*/
export default function request(url: string, config: AxiosRequestConfig & RequestConfig = {}) {
axios.defaults.headers.common.token = getToken(); // ่ทๅ token
// axios.defaults.headers.common['Accept-Language'] = `${getLocale()};q=0.9`; // ๅฝ้
ๅโAccept-Language:zh-CN,zh;q=0.9โ => zh-CN ๆ en-US
const {
method = 'get',
responseType = 'json',
body = {},
headers = {
'Content-Type': 'application/json'
},
cache = false,
...rest
} = config;
const newBody = /(put|post|patch)/i.test(method) ? { data: body } : { params: body }; // data ๅๆฐ๏ผๅจไปฅไธโ่ฏทๆฑ็ฑปๅโไธญๅฏ็จ๏ผput, post, patch
return axios
.request({
url, // URL ๅฐๅ
method, // ่ฏทๆฑ็ฑปๅ๏ผget, post, put, delete...
responseType, // ๅๅบๆฐๆฎ็ฑปๅ
headers: {
...headers,
...(cache
? { 'Cache-Control': 'public, max-age=86400' }
: { 'Cache-Control': 'no-cache, no-store, must-revalidate', Pragma: 'no-cache' }),
},
...newBody, // ่ฏทๆฑๅๆฐ
...rest, // ๅฉไฝๅๆฐ
})
.then(response => {
if (response.data.code === 200) {
return response.data
} else {
notification.error({
message: response.data.message,
});
return response.data
}
})
.catch(error => {
notification.error({
message: `ๆๅกๅจๅผๅธธ๏ผ่ฏท็จๅ้่ฏ`,
});
return {
success: false,
}
});
}
export { getToken, setToken, removeToken, toStatusText };
|
e291ea87ef18cd62875e7693d50de208884edf7e
|
TypeScript
|
ulrichomega/adventofcode2017
|
/2_2.ts
| 3.140625
| 3
|
import * as fs from "fs";
import * as _ from "lodash";
const fileContents: string = fs.readFileSync("inputs/2_1", {encoding: "utf8"}).trim();
const stringResults: string[][] = _.map(_.split(fileContents, "\n"), (input: string) => {
return _.split(input, "\t");
});
const intResults: number[][] = _.map(stringResults, (input: string[]) => {
return _.map(input, _.parseInt);
});
console.log(_.sum(_.map(intResults, (row: number[]): number => {
let numberToReturn: number = 0;
_.each(row, (value: number, index: number, others: number[]): any => {
// The results of dividing value by all other values in the row
const divisionResults: number[] = _.map(_.without(others, value), _.bind(_.divide, _, value, _));
// If any resulting values are integers, then they are the valid answer for this row
const dividedValue: number = _.find(divisionResults, _.isInteger);
if (dividedValue) {
numberToReturn = dividedValue;
return false; // Stop processing
}
});
console.log(numberToReturn);
return numberToReturn;
})));
|
d8d9f1f19f30816d6bca36705ec5f00f2ebccc14
|
TypeScript
|
AFASResearch/mobile-web-experiments
|
/src/utilities.ts
| 2.65625
| 3
|
import {UserInfo} from './interfaces';
let moment = <any>require('moment');
export let randomId = () => Math.random().toString(36).substr(2);
export let nameOfUser = (user: UserInfo) => {
if (!user) {
return '';
}
return `${user.firstName} ${user.lastName}`;
};
export let getFormattedDate = (date: Date) => {
return moment(date).format('YYYY-MM-DD HH:mm');
};
export let getFormattedDateSmall = (date: Date) => {
// return moment(date).format('HH:mm');
return moment(date).calendar();
};
|
844269646eb5577da0fa2a09318d394a1d3ad549
|
TypeScript
|
JoseRFelix/my-study-planner-api
|
/src/services/user.ts
| 2.515625
| 3
|
import {Service, Inject} from 'typedi'
import {IUser} from '../interfaces/IUser'
import cloudinary from '../loaders/cloudinary'
import IUserConfig from '../interfaces/IUserConfig'
@Service()
export default class UserService {
constructor(
@Inject('userModel') private userModel: Models.UserModel,
@Inject('logger') private logger,
) {}
public async UploadProfileImage(user: IUser, image: string): Promise<string> {
try {
const result: Express.CloudinaryResult = await cloudinary.uploader.upload(
image,
{
width: 200,
height: 200,
crop: 'pad',
},
)
if (!result) throw new Error("Couldn't upload image to Cloudinary")
const userRecord = await this.userModel.findOneAndUpdate(
{_id: user._id},
{
$set: {
picture: result.secure_url,
},
},
{new: true},
)
if (!userRecord) throw new Error("Couldn't add image to user")
return userRecord.picture
} catch (e) {
this.logger.log(e)
throw e
}
}
public async ChangeConfig(
_id: string,
config: IUserConfig,
): Promise<IUserConfig> {
try {
const userRecord: IUser = await this.userModel.findOneAndUpdate(
{_id},
{
$set: {
'configuration.darkMode': config.darkMode,
},
},
{new: true},
)
if (!userRecord) throw new Error("Couldn't update User")
return userRecord.configuration
} catch (e) {
this.logger.log(e)
throw e
}
}
public async ChangeFirstSignin(_id: string): Promise<string> {
try {
const userRecord: IUser = await this.userModel.findOneAndUpdate(
{_id},
{
$set: {
firstSignIn: false,
},
},
{new: true},
)
if (!userRecord) throw new Error("Couldn't update User")
return 'success'
} catch (e) {
this.logger.log(e)
throw e
}
}
}
|
687a226b4e19ad946d6065736d90de660da0cb4b
|
TypeScript
|
evilbinary/typescript-pipeline
|
/src/object.ts
| 2.78125
| 3
|
import { deepGet } from './other';
import { processPipe, pipeApply } from './pipeline';
const regexObject = /{([\w|\.|$|#|\\|:|,]*)}/g;
export class OObject {
public static empty: any = null;
public static Format(
format: string,
args: any,
toObject: boolean = false
): string {
try {
return OObject.format(regexObject, format, args, toObject);
} catch (e) {
console.log(e);
return OObject.empty;
}
}
private static getMatches(string, regex) {
const matches = [];
let match = null;
// tslint:disable-next-line: no-conditional-assignment
while ((match = regex.exec(string))) {
matches.push(match);
}
return matches;
}
private static format(
regex: any,
format: string,
arg: any,
toObject: boolean = false
): any {
// console.log('format', format);
const matches = OObject.getMatches(format, regex);
// console.log('matches=>', matches);
const mret = matches.map(o => {
// console.log('\n$$$$$$$$$$exp==>:', o[1]);
const exp = o[1].split('|');
const retExp = exp.map(obj => {
if (obj === '.') {
return arg;
}
// console.log(' obj=>', obj);
return deepGet(arg, obj, obj);
});
// console.log(' retExp:', retExp);
let result = null;
if (retExp.length !== 1) {
result = retExp.reduce((p, k, index) => {
let pret = null;
// console.log(' p=', p, 'k=', k, 'index=', index);
pret = processPipe(p, k, p);
// console.log(' return=>', pret);
if (p === exp[index - 1]) {
return null;
}
return pret;
});
// console.log('result is ', result);
if (result === null || result === {}) {
return o[0];
}
return result;
} else {
// console.log('o[0]', o[1], ' retExp[0]', retExp[0]);
result = o[1] === retExp[0] ? o[0] : retExp[0];
}
// console.log('result:', result);
return result;
// args.reduce(()=>);
});
try {
matches.forEach((m, i) => {
if (typeof mret[i] === 'string' || typeof mret[i] === 'number') {
format = format.replace(m[0], mret[i]);
} else {
format = format.replace(m[0], JSON.stringify(mret[i]));
}
});
if (toObject) {
return JSON.parse(format);
} else {
return format;
}
} catch (e) {
return format;
}
}
}
|
5cb12c30155589b8df49439911cbbed596a1297f
|
TypeScript
|
kyrsanter/kosunka
|
/src/redux/thunk.ts
| 2.640625
| 3
|
import {GameService} from "../service/game-service";
import {
dropCardActionCreator,
dropCardToColumnActionCreator,
startGameActionCreator, turnOverStackCardActionCreator
} from "./actions/main";
const service = new GameService();
export const initThunk = () => (dispatch: any) => {
const {stack, remainingCards, columns} = service.leftCardsFilter();
dispatch(startGameActionCreator(stack, remainingCards, columns));
};
export const dropCardThunk = (id: number, suite: string) => (dispatch: any) => {
dispatch(dropCardActionCreator(id, suite))
};
export const dropCardToColumnThunk = (col: number, idsArr: Array<string>) => (dispatch: any) => {
dispatch(dropCardToColumnActionCreator(col, idsArr))
};
export const turnOverStackCardThunk = (cardName: string) => (dispatch: any) => {
debugger
dispatch(turnOverStackCardActionCreator(cardName))
}
|
8e662e884656d6982e42b3f229d99ad71504c59e
|
TypeScript
|
Adwisecards/adwise
|
/adwise-backend/src/app/modules/users/useCases/verifications/getVerification/GetVerificationUseCase.ts
| 2.53125
| 3
|
import { Types } from "mongoose";
import { IUseCase } from "../../../../../core/models/interfaces/IUseCase";
import { Result } from "../../../../../core/models/Result";
import { UseCaseError } from "../../../../../core/models/UseCaseError";
import { IVerificationRepo } from "../../../repo/verifications/IVerificationRepo";
import { GetVerificationDTO } from "./GetVerificationDTO";
import { getVerificationErrors } from "./getVerificationErrors";
export class GetVerificationUseCase implements IUseCase<GetVerificationDTO.Request, GetVerificationDTO.Response> {
private verificationRepo: IVerificationRepo;
public errors: UseCaseError[] = [
...getVerificationErrors
];
constructor(verificationRepo: IVerificationRepo) {
this.verificationRepo = verificationRepo;
}
public async execute(req: GetVerificationDTO.Request): Promise<GetVerificationDTO.Response> {
if (!Types.ObjectId.isValid(req.userId)) {
return Result.fail(UseCaseError.create('c', 'userId is not valid'));
}
const verificationFound = await this.verificationRepo.findByUser(req.userId);
if (verificationFound.isFailure) {
return Result.fail(verificationFound.getError()!.code == 500 ? UseCaseError.create('a', 'Error upon finding verification') : UseCaseError.create('a0', 'Verification does not exist'));
}
const verificatiton = verificationFound.getValue()!;
return Result.ok({
verificationId: verificatiton._id
});
}
};
|
8f0b986a2a32063ea70d6915a8f5623a5ccdeca2
|
TypeScript
|
senkuu/atypikhouse-api
|
/src/resolvers/inputs/CriteriaInput.ts
| 2.5625
| 3
|
import { Field, InputType } from "type-graphql";
import { CriteriaTypes } from "../../entities/Criteria";
@InputType()
export class CreateCriteriaInput {
@Field()
name: string;
@Field({ nullable: true })
additional?: string;
@Field()
criteriaType: CriteriaTypes;
@Field()
isGlobal: boolean;
}
@InputType()
export class UpdateCriteriaInput {
@Field({ nullable: true })
name?: string;
@Field({ nullable: true })
additional?: string;
@Field({ nullable: true })
isGlobal?: boolean;
}
|
4750d1f05c4b35fed86b1c7cf6f6b461c43391dd
|
TypeScript
|
Flamestriken911/alchemy-frontend
|
/Backend/Components/Ingredient.ts
| 3.296875
| 3
|
import Effect = require('./Effect');
class Ingredient {
name: string;
id: number;
effects: Effect[];
addedEffects: number; //Number of effect matches added by this ingredient to the current mixture
discoveries: number; //Number of effect discoveries added by this ingredient to the current mixture
constructor(_id: number, _name: string, _effects: Effect[]){
this.id = _id;
this.name = _name;
this.effects = _effects;
this.addedEffects = 0;
this.discoveries = 0;
}
//Helper method that uses checker method to compare effects in an ingredient to effects in a list of effects in the mixture
UpdateIngredientWithMatches = (effectsToLookFor: Effect[], matchCounterFunction) => {
this.effects.forEach((effect) => {
effectsToLookFor.forEach((mixtureEffect) => {
matchCounterFunction(effect, mixtureEffect);
})
})
}
DetermineDiscoveries = (effect1: Effect, effect2: Effect) => {
if(effect1.name === effect2.name){
//If there's a match, update the discovery value of each effect if appropriate
if(!effect1.discovered) {
effect1.willBeDiscovered = true;
effect1.currentDiscoveryValue = (effect2.discovered || effect2.willBeDiscovered) ? 1 : 2;
} else {
effect1.willBeDiscovered = false;
effect1.currentDiscoveryValue = 0;
}
this.discoveries += effect1.currentDiscoveryValue;
}
}
DetermineAddedEffects = (effect1: Effect, effect2: Effect) => {
if(effect1.name === effect2.name){
//If there's a match, increase the effect value if neither ingredient is already adding to the mixture
if(!effect2.willHaveEffect) {
effect1.willHaveEffect = true;
effect1.currentAddedEffectsValue = 1;
} else {
effect1.willHaveEffect = false;
effect1.currentAddedEffectsValue = 0;
}
this.addedEffects += effect1.currentAddedEffectsValue;
}
}
ToStorageString = () => {
var storageString = `${this.id},${this.name}`;
this.effects.forEach((effect) => {
storageString += ',' + effect.ToStorageString();
})
return storageString;
}
}
export = Ingredient;
|
60435607126bdf8809b1cf991777a04c316ac3dd
|
TypeScript
|
haohello/noteui
|
/packages/system/src/enhancers/space.ts
| 2.671875
| 3
|
import { system, get, compose } from './core'
import { Config } from './types'
const defaults = {
space: [0, 4, 8, 16, 32, 64, 128, 256, 512],
}
const isNumber = n => typeof n === 'number' && !isNaN(n)
const getMargin = (n, scale) => {
if (!isNumber(n)) {
return get(scale, n, n)
}
const isNegative = n < 0
const absolute = Math.abs(n)
const value = get(scale, absolute, absolute)
if (!isNumber(value)) {
return isNegative ? '-' + value : value
}
return value * (isNegative ? -1 : 1)
}
const configs: Record<string, Config> = {}
configs.margin = {
margin: {
property: 'margin',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginTop: {
property: 'marginTop',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginRight: {
property: 'marginRight',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginBottom: {
property: 'marginBottom',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginLeft: {
property: 'marginLeft',
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginX: {
properties: ['marginLeft', 'marginRight'],
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
marginY: {
properties: ['marginTop', 'marginBottom'],
scale: 'space',
transform: getMargin,
defaultScale: defaults.space,
},
}
configs.margin.m = configs.margin.margin
configs.margin.mt = configs.margin.marginTop
configs.margin.mr = configs.margin.marginRight
configs.margin.mb = configs.margin.marginBottom
configs.margin.ml = configs.margin.marginLeft
configs.margin.mx = configs.margin.marginX
configs.margin.my = configs.margin.marginY
configs.padding = {
padding: {
property: 'padding',
scale: 'space',
defaultScale: defaults.space,
},
paddingTop: {
property: 'paddingTop',
scale: 'space',
defaultScale: defaults.space,
},
paddingRight: {
property: 'paddingRight',
scale: 'space',
defaultScale: defaults.space,
},
paddingBottom: {
property: 'paddingBottom',
scale: 'space',
defaultScale: defaults.space,
},
paddingLeft: {
property: 'paddingLeft',
scale: 'space',
defaultScale: defaults.space,
},
paddingX: {
properties: ['paddingLeft', 'paddingRight'],
scale: 'space',
defaultScale: defaults.space,
},
paddingY: {
properties: ['paddingTop', 'paddingBottom'],
scale: 'space',
defaultScale: defaults.space,
},
}
configs.padding.p = configs.padding.padding
configs.padding.pt = configs.padding.paddingTop
configs.padding.pr = configs.padding.paddingRight
configs.padding.pb = configs.padding.paddingBottom
configs.padding.pl = configs.padding.paddingLeft
configs.padding.px = configs.padding.paddingX
configs.padding.py = configs.padding.paddingY
export const margin = system(configs.margin)
export const padding = system(configs.padding)
export const space = compose(margin, padding)
export default space
|
d28e3762f56877fc8c3f1e2a33f765334fe07a2c
|
TypeScript
|
sgabhart22/stones-frontend
|
/src/app/shared/board.ts
| 3.375
| 3
|
import { Cell } from './cell';
export class Board<T> {
rows: number;
columns: number;
cells: Cell<T>[][];
state: any;
constructor(r: number, c: number) {
this.rows = r;
this.columns = c;
this.cells = [];
this.state = {};
for(var i: number = 0; i < this.rows; i++) {
this.cells[i] = [];
this.state[i] = [];
for(var j: number = 0; j < this.columns; j++) {
this.cells[i][j] = new Cell();
this.state[i][j] = 'none';
}
}
}
getDimensions(): Object {
return {
'rows': this.rows,
'columns': this.columns
};
}
setAt(x: number, y: number, piece: T) {
if(!this.cells[x][y].getMember()) {
this.cells[x][y].setMember(piece);
this.state[x][y] = piece;
}
}
getAt(x: number, y: number): T {
return this.cells[x][y].getMember();
}
getState(): any {
return this.state;
}
getNeighbors(x: number, y: number): any {
let neighbors = [];
if(x - 1 >= 0) {
neighbors.push({ 'x': x - 1, 'y': y });
}
if(x + 1 < this.rows) {
neighbors.push({ 'x': x + 1, 'y': y });
}
if(y - 1 >= 0) {
neighbors.push({ 'x': x, 'y': y - 1 });
}
if(y + 1 < this.columns) {
neighbors.push({ 'x': x, 'y': y + 1 });
}
return neighbors;
}
hasNoNeighbors(x: any, y: any): boolean {
let isolated = true;
this.getNeighbors(x, y).forEach(neighbor => {
if(this.getAt(neighbor['x'], neighbor['y'])) isolated = false;
});
return isolated;
}
}
|
e4c9c1a2c73fe2e6e48251c748537c7ff25323af
|
TypeScript
|
Bigomby/toshi.js
|
/src/request-signer/index.ts
| 3.03125
| 3
|
import axios, { AxiosRequestConfig } from 'axios';
import { Wallet } from '../wallet';
import { keccak256 } from 'js-sha3';
export type Interceptor = (config: AxiosRequestConfig) => AxiosRequestConfig;
export class RequestSigner {
constructor(private readonly wallet: Wallet) {}
public getInterceptor(): Interceptor {
return (config: AxiosRequestConfig): AxiosRequestConfig => {
const timestamp = this.getUnixTimestamp(Date.now());
if (!config.method || !config.url) {
throw Error('Missing method or URL');
}
const payload = this.buildPayload(
JSON.stringify(config.data),
config.method.toUpperCase(),
config.url,
timestamp,
);
const signature = this.wallet.signPayload(payload);
config.headers['Toshi-ID-Address'] = this.wallet.getAddress();
config.headers['Toshi-Signature'] = signature;
config.headers['Toshi-Timestamp'] = timestamp;
return config;
};
}
private getUnixTimestamp(date: number) {
return Math.floor(date / 1000);
}
/**
* CREATING THE PAYLOAD FOR SIGNING
*
* 1. If your request has no body skip to step 4.
* 2. Take the body of your request and hash it with KECCAK-256.
* 3. Base64 encode the result of Step 2 as a string.
* 4. Get the request verb of the request (e.g. GET, POST, etc) as a string.
* 5. Get the path of the request as a string.
* 6. Get a unix timestamp representing the current time as a string.
* 7. Take the results of steps 3-6 and concatenate them as follows:
*
* {VERB}\n{PATH}\n{TIMESTAMP}\n{HASH}
*/
private buildPayload(
body: string,
method: string,
path: string,
timestamp: number,
): string {
let encodedBody = '';
if (body) {
const hash = keccak256(body);
encodedBody = Buffer.from(hash, 'hex').toString('base64');
}
return `${method}\n${path}\n${timestamp}\n${encodedBody}`;
}
}
|
600b6207e745cb02d001a7e5e0431331a44eff8c
|
TypeScript
|
usc-isi-i2/d-repr
|
/www/app/src/store/types/UIConfiguration.ts
| 2.765625
| 3
|
export default class UIConfiguration {
public displayMax1Resource: boolean;
constructor(displayMax1Resource: boolean) {
this.displayMax1Resource = displayMax1Resource;
}
public setDisplayMax1Resource(displayMax1Resource: boolean) {
const instance = this.shallowClone();
instance.displayMax1Resource = displayMax1Resource;
return instance;
}
private clone() {
return new UIConfiguration(this.displayMax1Resource);
}
private shallowClone() {
return new UIConfiguration(this.displayMax1Resource);
}
}
|
23dd5eb54aafae3383d57097b02d153bfa9b388f
|
TypeScript
|
q3spxx/mt2-back
|
/src/repositories/histories/histories.repository.ts
| 2.59375
| 3
|
export class HistoriesRepository {
private model: IHistoriesModel;
private mapper: IHistoryDataMapper;
constructor(model: IHistoriesModel, mapper: IHistoryDataMapper) {
this.model = model;
this.mapper = mapper;
}
public async getHistories(): Promise<HistoryDTO[]> {
const data = await this.model.getHistories();
return data.map(test => this.mapper.toDalEntity(test));
}
public async createHistory(params: HistoryDTO): Promise<HistoryDTO> {
const data = await this.model.createHistory(this.mapper.toDomain(params));
return this.mapper.toDalEntity(data);
}
}
|
05516637cbb9855efc56108c7875df9ff0eaaef4
|
TypeScript
|
fbuether/WeltraumEindringlinge
|
/src/actors/Squadron.ts
| 2.6875
| 3
|
import * as planck from "planck-js";
import * as EventEmitter from "eventemitter3";
import {Random} from "../engine/Random";
import {Actor} from "../engine/Actor";
import {Sprite} from "../engine/components/Sprite";
import {Engine} from "../engine/Engine";
import {Loader} from "../engine/Loader";
import {Vector} from "../engine/Vector";
import {Enemy, EnemyClass} from "../actors/Enemy";
import {Scene} from "../engine/Scene";
export interface SquadronConfig {
enemyClass: EnemyClass;
count: number; // overall number of enemies
spawnPackSize: [number,number]; // spawn these many at once
spawnPackLimit: number; // maximum present enemies reached by pack spawning.
spawnPackDelay: number; // spawn packs soonest after this many ms.
spawnRandom: [number,number]; // delay after spawn event and actual spawn.
spawnDelay: number; // spawn a single enemy at least every this many ms.
}
type Events = "enemy-destroyed" | "enemy-escaped" | "squad-destroyed";
export class Squadron extends Actor {
public readonly events = new EventEmitter<Events>();
private random: Random;
private readonly config: SquadronConfig;
private count: number;
private current = 0;
private lastSpawn = Number.POSITIVE_INFINITY;
public constructor(engine: Engine, config: SquadronConfig) {
super("squadron", engine);
this.random = this.engine.random.fork();
this.config = config;
this.count = this.config.count;
}
public delete() {
this.events.removeAllListeners();
}
public update(delta: number) {
this.lastSpawn += delta;
let packLimit = this.config.spawnPackLimit - this.current;
// console.log(this.current, packLimit, this.lastSpawn, this.config.spawnPackDelay);
if (this.current < packLimit
&& this.lastSpawn >= this.config.spawnPackDelay) {
let spawnCount = Math.min(
this.random.int(...this.config.spawnPackSize),
this.count);
for (let i = 0; i < spawnCount; i++) {
this.spawnEnemy();
}
this.lastSpawn = 0;
}
if (this.lastSpawn >= this.config.spawnDelay) {
this.spawnEnemy();
this.lastSpawn = 0;
}
}
private spawnEnemy() {
if (this.count <= 0) {
return;
}
this.current += 1;
this.count -= 1;
this.engine.delay(this.random.int(...this.config.spawnRandom), () => {
let screen = this.engine.getScreenBounds();
let hasOverlap = false;
let pos = new Vector(0, 0);
for (let i = 0; i < 10; i++) {
let y = screen.top + 60;
let x = this.random.int(screen.left + 60, screen.right - 60);
pos = new Vector(x, y);
let newEnemyShape = new planck.AABB(
new Vector(-36, -24).add(pos).mul(Engine.PhysicsScale),
new Vector(36, 24).add(pos).mul(Engine.PhysicsScale));
hasOverlap = false;
this.engine.physics.queryAABB(newEnemyShape, () => {
hasOverlap = true;
return false;
});
if (!hasOverlap) {
break;
}
}
if (hasOverlap) {
console.warn("could not place enemy, too much overlap.");
return;
}
let enemy = new Enemy(this.engine, pos, this.config.enemyClass);
enemy.events.on("destroyed", this.onEnemyDestroyed, this);
enemy.events.on("escaped", this.onEnemyEscaped, this);
this.add(enemy);
});
}
private onEnemyDestroyed(enemy: Enemy) {
this.current -= 1;
this.components.delete(enemy);
this.events.emit("enemy-destroyed", this, enemy);
if (this.count <= 0 && this.current <= 0) {
this.events.emit("squad-destroyed", this);
this.kill();
}
}
private onEnemyEscaped(enemy: Enemy) {
this.components.delete(enemy);
enemy.kill();
this.events.emit("enemy-escaped", this, enemy);
}
}
|
3392fbb6520d18aaa98fea67681406c32812d192
|
TypeScript
|
1910javareact/Demos
|
/1Week/garden-book/src/index.ts
| 2.984375
| 3
|
import express from 'express';
import bodyparser from 'body-parser';
import { gardenRouter } from './routers/garden-router';
import { postRouter } from './routers/post-router';
import { loggingMiddleware } from './middleware/logging-middleware';
import { sessionMiddleware } from './middleware/session-middleware';
import { getGardenByUsernameAndPassword } from './services/garden-service';
import { corsFilter } from './middleware/cors-middleware';
const app = express(); //this line builds the application from express
//req is the request object from the client
//res is the response object we send out
// app.use('/', (req, res)=>{ //our first endpoint on uri /
// res.json('Hello Garden')//send as json "Hello Garden"
// })
//this is what we call middleware
//every request will go through this bodyparser
//bodyparser will turn the json string on a req into a js object
//then it will fall through to the next endpoint
app.use(bodyparser.json());
//lets write some middleware for logging
//because if there is one thing programmers love
//its having GBs of info about what people are doing
app.use(loggingMiddleware);
app.use(corsFilter);
//this is going to add to every req object
//an object called session
//we can access using req.session
app.use(sessionMiddleware);
//we are registering the router with a base path of /gardens
app.use('/gardens', gardenRouter);
app.use('/posts', postRouter);
app.post('/login', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
res.status(400).send('please have a username and password field');
} else {
try {
const user = await getGardenByUsernameAndPassword(username, password);
req.session.user = user;
res.json(user); //its standard to send the logged in user info after the log in
} catch (e) {
res.status(e.status).send(e.message);
}
}
});
//now we need to make the server actually run
//this means the server has to be listening for requests
app.listen(2020, () => {
console.log('app has started');
});
|
b92e04bc8c92053ab6a8638d1aa9adc3b4ca603d
|
TypeScript
|
maxscott/loan-assignment
|
/src/loanAssigner.ts
| 3.59375
| 4
|
import { Loan, Facility, Assignment } from './models';
/**
* Assignment works by selecting the first facility which an Assignment is allowed for.
* Facilities are traversed from low to high interest.
* The assignment model is responsible for validating it's own creation.
*/
export class LoanAssigner {
interestRateIndex: Array<Facility>
/**
* Pre-processes the facilities for easier future assignment.
* In this instance, pre-processing includes sorting on low-to-high interest rates.
*
* @param Array<Facility> The facilities the assigner can choose from.
*/
constructor(public facilities: Array<Facility>) {
// Current state: scan by lowest interest rate
this.interestRateIndex = [...facilities].sort((a, b) => {
return a.interestRate < b.interestRate ? -1 : 1
});
}
/**
* Attempt to create assignments, which check for all validation criteria.
*
* @param Loan The loan to assign.
* @returns Assignment The assignment made for this loan.
*/
assign(loan: Loan): Assignment | null {
for (const facility of this.interestRateIndex) {
try {
return new Assignment(loan, facility);
} catch (e) {
console.debug(e.message);
}
}
return null;
}
}
|
ea17dbeaeaa03dd70cfdf91221c39995f39eacc3
|
TypeScript
|
FrankeSa/EA2-Inverted
|
/L10_Inheritance/L10_Corona/HumanCell/Human_Cell.ts
| 2.515625
| 3
|
namespace L10_Corona {
export class HumanCell {
position: Vector;
constructor(_position: Vector) {
if (_position)
this.position = _position;
else
this.position = new Vector(0, 0);
}
draw(): void {
let r1: number = 20;
let r2: number = 80;
let gradient: CanvasGradient = crc2.createRadialGradient(0, 0, r1, 15, 0, r2);
gradient.addColorStop(0, "HSLA(240, 100%, 50%)");
gradient.addColorStop(1, "HSLA(195, 100%, 65%,0)");
crc2.save();
crc2.translate(this.position.x, this.position.y);
crc2.fillStyle = gradient;
crc2.beginPath();
crc2.arc(0, 0, r2, 0, 2 * Math.PI);
crc2.closePath();
crc2.fill();
crc2.restore();
}
}
}
|
552d8e525dd50a93ec08120af6e4b08c012ed3c8
|
TypeScript
|
l3tnun/EPGStation
|
/client/src/model/state/recorded/RecordedState.ts
| 2.578125
| 3
|
import { inject, injectable } from 'inversify';
import * as apid from '../../../../../api';
import IVideoApiModel from '../..//api/video/IVideoApiModel';
import IRecordedApiModel from '../../api/recorded/IRecordedApiModel';
import IRecordedState, { MultipleDeletionOption, SelectedInfo } from './IRecordedState';
import IRecordedUtil, { RecordedDisplayData } from './IRecordedUtil';
@injectable()
export default class RecordedState implements IRecordedState {
private recordedApiModel: IRecordedApiModel;
private recordedUtil: IRecordedUtil;
private videoApiModel: IVideoApiModel;
private recorded: RecordedDisplayData[] | null = null;
private total: number = 0;
constructor(
@inject('IRecordedApiModel') recordedApiModel: IRecordedApiModel,
@inject('IRecordedUtil') recordedUtil: IRecordedUtil,
@inject('IVideoApiModel') videoApiModel: IVideoApiModel,
) {
this.recordedApiModel = recordedApiModel;
this.recordedUtil = recordedUtil;
this.videoApiModel = videoApiModel;
}
/**
* ๅๅพใใ้ฒ็ปๆ
ๅ ฑใใฏใชใข
*/
public clearData(): void {
this.recorded = null;
this.total = 0;
}
/**
* ้ฒ็ปๆ
ๅ ฑใๅๅพ
* @param option: apid.GetRecordedOption
* @return Promise<void>
*/
public async fetchData(option: apid.GetRecordedOption): Promise<void> {
const recrods = await this.recordedApiModel.gets(option);
this.total = recrods.total;
const oldSelectedIndex: { [recordedId: number]: boolean } = {};
if (this.recorded !== null) {
for (const r of this.recorded) {
oldSelectedIndex[r.recordedItem.id] = r.isSelected;
}
}
this.recorded = recrods.records.map(r => {
const result = this.recordedUtil.convertRecordedItemToDisplayData(r, option.isHalfWidth);
if (typeof oldSelectedIndex[result.recordedItem.id] !== 'undefined') {
result.isSelected = oldSelectedIndex[result.recordedItem.id];
}
return result;
});
}
/**
* ๅๅพใใ้ฒ็ปๆ
ๅ ฑใ่ฟใ
* @return RecordedStateData[]
*/
public getRecorded(): RecordedDisplayData[] {
return this.recorded === null ? [] : this.recorded;
}
/**
* ๅๅพใใ้ฒ็ปใฎ็ทไปถๆฐใ่ฟใ
* @return number
*/
public getTotal(): number {
return this.total;
}
/**
* ใจใณใณใผใๅๆญข
* @param recordedId: apid.RecordedId
* @return Promise<void>
*/
public async stopEncode(recordedId: apid.RecordedId): Promise<void> {
await this.recordedApiModel.stopEncode(recordedId);
}
/**
* ้ธๆใใ็ช็ตๆฐใ่ฟใ
* @return SelectedInfo
*/
public getSelectedCnt(): SelectedInfo {
if (this.recorded === null) {
return {
cnt: 0,
size: 0,
};
}
let selectedCnt = 0;
let selectedSize = 0;
for (const r of this.recorded) {
if (r.isSelected === true) {
selectedCnt++;
if (typeof r.recordedItem.videoFiles !== 'undefined') {
for (const v of r.recordedItem.videoFiles) {
selectedSize += v.size;
}
}
}
}
return {
cnt: selectedCnt,
size: selectedSize,
};
}
/**
* ้ธๆ (ๅ้คๆใฎ่คๆฐ้ธๆ)
* @param recordedId: apid.RecordedId
*/
public select(recordedId: apid.RecordedId): void {
if (this.recorded === null) {
return;
}
for (const r of this.recorded) {
if (r.recordedItem.id === recordedId) {
r.isSelected = !r.isSelected;
return;
}
}
}
/**
* ๅ
จใฆ้ธๆ (ๅ้คๆใฎ่คๆฐ้ธๆ)
*/
public selectAll(): void {
if (this.recorded === null) {
return;
}
let isUnselectAll = true;
for (const r of this.recorded) {
if (r.isSelected === false) {
isUnselectAll = false;
}
r.isSelected = true;
}
// ๅ
จใฆ้ธๆๆธใฟใงใใใฐ้ธๆใ่งฃ้คใใ
if (isUnselectAll === true) {
for (const r of this.recorded) {
r.isSelected = false;
}
}
}
/**
* ๅ
จใฆใฎ้ธๆ่งฃ้ค (ๅ้คๆใฎ่คๆฐ้ธๆ)
*/
public clearSelect(): void {
if (this.recorded === null) {
return;
}
for (const r of this.recorded) {
r.isSelected = false;
}
}
/**
* ้ธๆใใ็ช็ตใๅ้คใใ
* @param option: MultipleDeletionOption
*/
public async multiplueDeletion(option: MultipleDeletionOption): Promise<void> {
if (this.recorded === null) {
return;
}
// ๅ้คใใ video file ใๅๆใใ
const videoFileIds: apid.VideoFileId[] = [];
for (const r of this.recorded) {
if (r.isSelected === false || typeof r.recordedItem.videoFiles === 'undefined') {
continue;
}
for (const v of r.recordedItem.videoFiles) {
if (option === 'All' || (option === 'OnlyOriginalFile' && v.type === 'ts') || (option === 'OnlyEncodedFile' && v.type === 'encoded')) {
videoFileIds.push(v.id);
}
}
}
// ้ธๆ็ถๆ
ใๅ
ใซๆปใ
this.clearSelect();
// ๅๆใใใใใชใใกใคใซใๅ้คใใ
let hasError = false;
for (const v of videoFileIds) {
try {
await this.videoApiModel.delete(v);
} catch (err) {
console.error(err);
hasError = true;
}
}
if (hasError === true) {
throw new Error();
}
}
}
|
b66ae6045b267231dec0802b5ec1840319837857
|
TypeScript
|
satyaye/project-reports-action
|
/project-reports-schemes.ts
| 2.703125
| 3
|
import {ProjectIssue} from './project-reports-lib'
export function dataFromCard(card: ProjectIssue, filterBy: string, data: string): any {
const fn = module.exports[`get${filterBy}`]
if (!fn) {
throw new Error(`Invalid filter: ${filterBy}`)
}
return fn(card, data)
}
//
// returns last updated using last comment with a body matching a pattern
//
export function getLastCommentPattern(card: ProjectIssue, pattern: string): any {
if (!card.comments) {
return ''
}
const re = new RegExp(pattern)
const comment = card.comments.filter(comment => comment.body.match(re)).pop()
return comment ? comment['updated_at'] : null
}
// export function diffHours(date1: Date, date2: Date): number {
// return Math.abs(date1.getTime() - date2.getTime()) / (60*60*1000);
// }
|
921d93b46f987ba5361ae8ee082d8db36a9d0db6
|
TypeScript
|
lizzzp1/tslint-microsoft-contrib
|
/test-data/NoReservedKeywords/NoReservedKeywordsTestInput-instanceof.ts
| 3.078125
| 3
|
class SampleInstanceOf3 {
// class variables
private instanceof;
}
// class properties
class SampleInstanceOf4 {
private var;
set instanceof(value) {}
get instanceof() {
return this.var;
}
}
class SampleInstanceOf5 {
instanceof() {} // class methods
}
// interface declarations
interface SampleInstanceOf6 {
instanceof: any;
}
|
9993073172205ff068ca7d0217718565a22730a8
|
TypeScript
|
allanartuso/order-fox-exercise
|
/calculator.spec.ts
| 2.953125
| 3
|
import { calculate, Operation } from "./calculator";
describe("calculator", () => {
it("", () => {
const expected = 2 - 4 / 3 - 5 - 7 + (2 * 20) / 2;
const actual = calculate([
{
operation: Operation.ADDITION,
params: [
2,
[
{
operation: Operation.DIVISION,
params: [-4, 3],
},
{
operation: Operation.SUBTRACTION,
params: [5, 7],
},
{
operation: Operation.MULTIPLICATION,
params: [
2,
[
{
operation: Operation.DIVISION,
params: [20, 2],
},
],
],
},
],
],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = (2 / 4) * 7;
const actual = calculate([
{
operation: Operation.MULTIPLICATION,
params: [
7,
[
{
operation: Operation.DIVISION,
params: [2, 4],
},
],
],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = 5 - 7;
const actual = calculate([
{
operation: Operation.ADDITION,
params: [5],
},
{
operation: Operation.SUBTRACTION,
params: [7],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = -5 - 7;
const actual = calculate([
{
operation: Operation.SUBTRACTION,
params: [5, 7],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = 5 + 7;
const actual = calculate([
{
operation: Operation.ADDITION,
params: [5, 7],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = 5 / 7;
const actual = calculate([
{
operation: Operation.DIVISION,
params: [5, 7],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = 5 * 7;
const actual = calculate([
{
operation: Operation.MULTIPLICATION,
params: [5, 7],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = -5 * 7;
const actual = calculate([
{
operation: Operation.SUBTRACTION,
params: [
[
{
operation: Operation.MULTIPLICATION,
params: [5, 7],
},
],
],
},
]);
expect(actual).toEqual(expected);
});
it("", () => {
const expected = 5 + (2 * 7 + 2) * (10 / 5 - 3) - 2;
const actual = calculate([
{
operation: Operation.ADDITION,
params: [5],
},
{
operation: Operation.MULTIPLICATION,
params: [
[
{
operation: Operation.MULTIPLICATION,
params: [2, 7],
},
{
operation: Operation.ADDITION,
params: [2],
},
],
[
{
operation: Operation.SUBTRACTION,
params: [3],
},
{
operation: Operation.DIVISION,
params: [10, 5],
},
],
],
},
{
operation: Operation.SUBTRACTION,
params: [2],
},
]);
expect(actual).toEqual(expected);
});
});
|
9ffc9c75ece884b373a9f3c04e89b04a5e731b94
|
TypeScript
|
sid-code/roguelike
|
/src/map.ts
| 3.25
| 3
|
/*
* This code describes a single level of the dungeon, or a "map".
*
* The "generate" function generates a rooms-and-corridors map for
*/
import { PSprng as rng } from "./rng";
import { DungeonOptions } from "./game";
import { CoordPair } from "./interfaces";
export enum Direction {
NORTH, EAST, SOUTH, WEST
}
var dirs = [
Direction.NORTH,
Direction.EAST,
Direction.SOUTH,
Direction.WEST
];
interface Delta extends CoordPair {
x: number;
y: number;
}
interface DirMap {
[dir: number]: Delta;
}
var deltas: DirMap = {};
deltas[Direction.NORTH] = {x: 0, y: -1};
deltas[Direction.EAST] = {x: 1, y: 0};
deltas[Direction.SOUTH] = {x: 0, y: 1};
deltas[Direction.WEST] = {x: -1, y: 0};
export enum Tile {
NOTHING=4, FLOOR, WALL, TEMP, TEMP2, DOOR
}
export enum TileStatus {
UNSEEN, SEEN, MAPPED
}
interface CellularAutomataOptions<T> {
width: number; // width of grid
height: number; // height
rule: {
birth: Array<number>; // standard 2d cell automata rules
survive: Array<number>;
}
alive: T; // which value signifies alive?
dead: T; // which value signifies dead?
}
interface Grid<T> {
length: number;
[n: number]: T;
slice: (n: number) => Grid<T>;
}
// Helper functions to treat 1-d array as 2-d
// If x, y is out of bounds, return defaultValue
function get<T>(array: Grid<T>, width: number, height: number,
x: number, y: number, defaultValue: T = null): T {
if (x >= width || x < 0 || y >= height || y < 0) return defaultValue;
return array[width * y + x];
};
function set<T>(array: Grid<T>, width: number, height: number,
x: number, y: number, newValue: T) {
if (x >= width || x < 0 || y >= height || y < 0) return;
array[width * y + x] = newValue;
};
/*
* Class for representing rooms in the dungeon
*/
class Room {
x: number;
y: number;
w: number;
h: number;
constructor(x: number, y: number, w: number, h: number) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
overlap(other: Room): boolean {
if (this.x + this.w <= other.x || other.x + other.w <= this.x) {
return false;
}
if (this.y >= other.y + other.h || other.y >= this.y + this.h) {
return false;
}
return true;
}
// Checks if the room can be drawn on the map. If checkOverlap is true
// (default value if not provided), then it will be checked to see if it
// doesn't overlap other rooms.
checkOnMap(map: DMap, checkOverlap: boolean = true): boolean {
var i;
if (this.x + this.w >= map.width || this.y + this.h >= map.height) {
return false;
}
if (checkOverlap) {
for (i = 0; i < map.rooms.length; i++) {
var other = map.rooms[i];
if (this.overlap(other)) return false;
}
}
return true;
}
// draws a room at its position
drawOn(map: DMap) {
var px = this.x, py = this.y,
w = this.w, h = this.h;
var x, y;
for (x = px; x <= px + w; x++) {
for (y = py; y <= py + h; y++) {
if (x == px || y == py || x == px + w || y == py + h) {
map.set(x, y, Tile.WALL);
} else {
map.set(x, y, Tile.TEMP);
}
}
}
map.rooms.push(this);
};
static genRandomRoom(map: DMap): Room {
var x, y, w, h; // all of these must be odd;
x = map.rng.nextInt(0, (map.width-1) / 2) * 2;
y = map.rng.nextInt(0, (map.height-1) / 2) * 2;
w = map.rng.nextInt((map.minRoomSize-1) / 2, (map.maxRoomSize+1) / 2) * 2;
h = map.rng.nextInt((map.minRoomSize-1) / 2, (map.maxRoomSize+1) / 2) * 2;
return new Room(x, y, w, h);
}
}
interface DMapOptions extends DungeonOptions {
rng: rng;
}
export class DMap {
/*
* Constructor
*/
options: DMapOptions;
rng: rng;
width: number;
height: number;
minRoomSize: number;
maxRoomSize: number;
allowRoomOverlap: boolean;
numRoomAttempts: number;
cavernWidth: number;
cavernHeight: number;
numCaves: number;
caveSetting: Array<number>;
numExtraConnectors: number;
connectorThickness: number;
straightTendency: number;
grid: Uint16Array;
seenGrid: Uint8Array;
rooms: Array<Room>;
constructor(options: DMapOptions) {
this.options = options;
this.rng = options.rng;
this.width = options.width;
this.height = options.height;
if (this.width % 2 === 0) {
throw "map width must be odd";
}
if (this.height % 2 === 0) {
throw "map height must be odd";
}
this.minRoomSize = options.minRoomSize || 5;
this.maxRoomSize = options.maxRoomSize || 11;
this.allowRoomOverlap = options.allowRoomOverlap;
this.numRoomAttempts = options.numRoomAttempts || 100;
this.cavernWidth = options.caveWidth || 24;
this.cavernHeight = options.caveHeight || 10;
this.numCaves = options.numCaves || 20;
this.caveSetting = options.caveSetting || [];
this.numExtraConnectors = options.numExtraConnectors || 10;
this.connectorThickness = options.connectorThickness || 1;
this.straightTendency = options.straightTendency || 0.5;
if (!this.width || this.width < DMap.limits.width.min ||
this.width > DMap.limits.width.max) {
throw "invalid map width, must be within " +
DMap.limits.width.min + ".." + DMap.limits.width.max + ".";
}
if (!this.height || this.height < DMap.limits.height.min ||
this.height > DMap.limits.height.max) {
throw "invalid map width, must be within " +
DMap.limits.height.min + ".." + DMap.limits.height.max + ".";
}
// The actual tiles
this.grid = new Uint16Array(this.width * this.height);
// What the player has seen (1=seen, 0=unseen, maybe more for unseen but
// magically mapped)
this.seenGrid = new Uint8Array(this.width * this.height);
}
static limits = {
width: {min: 15, max: 1999},
height: {min: 15, max: 1999},
};
// Helper function to determine whether a given tile is a floor tile (e.g.
// can be walked on.)
static isFloorTile(tile: Tile): boolean {
return tile == Tile.FLOOR;
};
/*
* Member functions
*/
// get and set for normal grid
get(x: number, y: number): Tile {
return get(this.grid, this.width, this.height, x, y, Tile.NOTHING);
}
set(x: number, y: number, val: Tile) {
set(this.grid, this.width, this.height, x, y, val);
}
// get and set for the seen grid
getSeen(x: number, y: number): TileStatus {
return get(this.seenGrid, this.width, this.height, x, y, TileStatus.UNSEEN);
}
setSeen(x: number, y: number, val: TileStatus) {
set(this.seenGrid, this.width, this.height, x, y, val);
}
fill() {
var x, y;
for (x = 0; x < this.width; x++) {
for (y = 0; y < this.height; y++) {
this.set(x, y, Tile.WALL);
}
}
};
// fills the map with a border of a wall. If fillFloor is true (which is the
// default value), then the floor will be filled too.
fillBorder(fillFloor: boolean = true) {
var x, y;
for (x = 0; x < this.width; x++) {
for (y = 0; y < this.height; y++) {
if (x === 0 || y === 0 || x == this.width - 1 || y == this.height - 1) {
this.set(x, y, Tile.WALL);
} else {
if (fillFloor) {
this.set(x, y, Tile.FLOOR);
}
}
}
}
};
generate() {
this.fill();
this.generateRooms(this.numRoomAttempts);
this.generateCaves(this.numCaves);
this.generateMaze();
this.fixTemporaryWalls();
this.connectComponents();
this.addExtraConnectors();
while (this.killDeadEnds());
this.killIslands(15);
this.fillBorder(false);
};
generateCavern(width: number, height: number): Uint16Array {
var cavern = new Uint16Array(width * height);
var i;
for (i = 0; i < cavern.length; i++) {
cavern[i] = (this.rng.next() < 0.35) ? 0 : 1;
}
var birth = [];
if (this.caveSetting.length > 0) {
for (i = 0; i < this.caveSetting.length; i++) {
var value = this.caveSetting[i];
if (value >= 5 || value <= 8) {
birth.push(value);
}
}
} else {
// Random, each of {6, 7, 8} has a 0.5 chance of being in the setting.
// If it ends up being empty, then it'll just be set to [6, 7, 8]
for (i = 6; i <= 8; i++) {
var value = this.caveSetting[i];
if (this.rng.next() < 0.5) {
birth.push(value);
}
}
if (birth.length === 0) {
birth = [6, 7, 8];
}
}
for (i = 0; i < 5; i++) {
this.runCellularAutomataStep(cavern, {
width: width,
height: height,
alive: 1,
dead: 0,
rule: {
birth: birth,
survive: [4,5,6,7,8]
}
});
}
return cavern;
};
// Function to place rooms in the dungeon. The parameter signifies how many
// attempts should be made.
generateRooms(numTries: number) {
this.rooms = [];
var i, room;
for (i = 0; i < numTries; i++) {
room = Room.genRandomRoom(this);
if (room.checkOnMap(this, this.allowRoomOverlap)) {
room.drawOn(this);
}
}
};
generateCaves(numCaves: number) {
var x, y, i;
for (i = 0; i < numCaves; i++) {
var cavernWidth = this.cavernWidth;
var cavernHeight = this.cavernHeight;
var cavern = this.generateCavern(cavernWidth, cavernHeight);
var offsetX = this.rng.nextInt(1, (this.width - cavernWidth)/2) * 2 + 1;
var offsetY = this.rng.nextInt(1, (this.height - cavernHeight)/2) * 2 + 1;
for (x = offsetX; x < offsetX + cavernWidth; x++) {
for (y = offsetY; y < offsetY + cavernHeight; y++) {
// NOTE: instead of using Tile.WALL, it uses DMap.TEMP2. This is to
// prevent the mazes from being drawn between the little cavey rooms.
// The TEMP2s are converted into WALLs later.
this.set(x, y, (get(cavern, cavernWidth, cavernHeight, x - offsetX, y - offsetY) == 1) ? Tile.TEMP : Tile.TEMP2);
}
}
}
};
// Removes the temporary walls that generateCaves makes
fixTemporaryWalls() {
var x,y;
for (x = 0; x < this.width; x++) {
for (y = 0; y < this.height; y++) {
if (this.get(x, y) == Tile.TEMP2) {
this.set(x, y, Tile.WALL);
}
}
}
}
// Used for maze generation purposes to find out where to start generating the maze.
getFirstBlank(): CoordPair {
var x, y;
for (x = 1; x < this.width - 1; x += 2) {
for (y = 1; y < this.height - 1; y += 2) {
if (this.get(x, y) == Tile.WALL) {
return {x: x, y: y};
}
}
}
return null;
};
// Used whenever we need to place an object on a floor tile.
//
// The parameter "exclude" should be an array of points {x: x, y: y} which
// should NOT be chosen, even if they are floor tiles. If omitted, an empty
// array is used.
getRandomFloorTile(exclude: Array<CoordPair>): CoordPair {
var x, y, count = 0;
do {
x = this.rng.nextInt(1, this.width);
y = this.rng.nextInt(1, this.height);
// Make sure we don't have an infinite loop.
count++;
if (count > 200) {
return {x: -1, y: -1};
}
// Don't use any points in exclude.
if (exclude.find(function(p) { return p.x == x && p.y == y; })) {
continue;
}
} while (!DMap.isFloorTile(this.get(x, y)));
return {x: x, y: y};
};
// Generates a maze around the rooms.
generateMaze() {
while (true) {
var firstBlank = this.getFirstBlank();
if (!firstBlank) return;
var pos = firstBlank;
var stack = [pos];
var visited = [pos];
var lastDir;
var delta;
while (stack.length > 0) {
pos = stack.pop();
visited.push(pos);
this.set(pos.x, pos.y, Tile.TEMP);
// Find out where we can go next.
var nextDirs = [];
var i;
for (i = 0; i < dirs.length; i++) {
var dir = dirs[i];
delta = deltas[dir];
if (this.get(pos.x + 2 * delta.x, pos.y + 2 * delta.y) == Tile.WALL) {
nextDirs.push(dir);
}
}
if (nextDirs.length === 0) {
// Backtrack one square because there were no more options.
visited.pop();
if (visited.length > 0) {
stack.push(visited.pop());
}
} else {
// Choose a random direction from nextDirs and keep going.
// OR, use the last direction to make corridors straighter.
var next;
if (lastDir && nextDirs.indexOf(lastDir) > -1 &&
this.rng.next() < this.straightTendency) {
next = lastDir;
} else {
next = this.rng.sample(nextDirs);
lastDir = next;
}
// Carve out in the direction "next".
delta = deltas[next];
pos = {x: pos.x + delta.x, y: pos.y + delta.y};
this.set(pos.x, pos.y, Tile.TEMP);
pos = {x: pos.x + delta.x, y: pos.y + delta.y};
this.set(pos.x, pos.y, Tile.TEMP);
// Add our new position to the processing stack.
stack.push(pos);
}
}
}
};
// This function replaces some walls with doors (or whatever) to connect
// the mazes to the rooms.
connectComponents() {
var numTemp = 0;
var x, y;
for (x = 1; x < this.width - 1; x++) {
for (y = 1; y < this.height - 1; y++) {
if (this.get(x, y) == Tile.TEMP) {
numTemp++;
}
}
}
x = 0;
y = 0;
while (this.get(x, y) != Tile.TEMP) {
x = this.rng.nextInt(1, this.width);
y = this.rng.nextInt(1, this.height);
}
numTemp -= this.floodFill(x, y, Tile.FLOOR);
var connectors;
while (true) {
connectors = this.getConnectors(Tile.TEMP, Tile.FLOOR);
if (connectors.length == 0) break;
var randomConnector: CoordPair = this.rng.sample(connectors);
var cx = randomConnector.x, cy = randomConnector.y;
if (this.get(cx, cy) == Tile.WALL) {
this.set(cx, cy, Tile.TEMP);
var numFilled = this.floodFill(cx, cy, Tile.FLOOR) - 1;
if (numFilled === 0) {
// Nothing was filled
this.set(cx, cy, Tile.WALL);
} else {
numTemp -= numFilled;
}
}
if (numTemp === 0) {
break;
}
}
// Remove all residual TEMP tiles.
var x, y;
for (x = 0; x < this.width; x++) {
for (y = 0; y < this.height; y++) {
if (this.get(x, y) == Tile.TEMP) { this.set(x, y, Tile.WALL); }
}
}
};
getConnectors(tileFrom: Tile, tileTo: Tile): Array<CoordPair> {
var connectors = [];
var x, y;
for (x = 1; x < this.width - 1; x++) {
for (y = 1; y < this.height - 1; y++) {
if (this.get(x, y) == Tile.WALL && (this.checkIfConnector(x, y, tileFrom, tileTo))) {
connectors.push({x: x, y: y});
}
}
}
return connectors;
};
floodFill(x: number, y: number, newTile: number): number {
return this.genericFloodFill(this.grid, this.width, this.height, x, y, newTile);
}
genericFloodFill<T>(grid: Grid<T>, width: number, height: number, x: number,
y: number, newValue: T): number {
var tilesChanged = 0;
var oldValue = get(grid, width, height, x, y);
var stack = [{x: x, y: y}];
while (stack.length > 0) {
var pos = stack.pop();
if (get(grid, width, height, pos.x, pos.y) == oldValue) {
// This should only change when we *actually* change the color of the
// tile. The way this algorithm works, it might attempt to change some
// tiles twice so we don't want those to be overcounted.
tilesChanged++;
}
set(grid, width, height, pos.x, pos.y, newValue);
var px = pos.x, py = pos.y;
if (get(grid, width, height, px + 1, py) == oldValue) stack.push({x: px + 1, y: py});
if (get(grid, width, height, px - 1, py) == oldValue) stack.push({x: px - 1, y: py});
if (get(grid, width, height, px, py + 1) == oldValue) stack.push({x: px, y: py + 1});
if (get(grid, width, height, px, py - 1) == oldValue) stack.push({x: px, y: py - 1});
}
return tilesChanged;
};
// Checks if the tile at x, y has neighbors of both types tileFrom and tileTo
// The neighbors must also be in opposite directions.
checkIfConnector(x: number, y: number, tileFrom: Tile, tileTo: Tile): boolean {
var north = this.get(x, y + 1), south = this.get(x, y - 1);
if ((north == tileFrom && south == tileTo) ||
(north == tileTo && south == tileFrom)) return true;
var east = this.get(x + 1, y), west = this.get(x - 1, y);
if ((east == tileFrom && west == tileTo) ||
(east == tileTo && west == tileFrom)) return true;
return false;
};
// Removes dead ends in the maze.
killDeadEnds(): boolean {
var result = false;
var x, y;
for (x = 1; x < this.width - 1; x++) {
for (y = 1; y < this.height - 1; y++) {
if (DMap.isFloorTile(this.get(x, y)) && this.countTilesAround(x, y, Tile.WALL) == 3) {
this.set(x, y, Tile.WALL);
result = true;
}
}
}
return result;
};
killIslands(maxSize: number) {
var x, y, islandSize;
for (x = 1; x < this.width - 1; x++) {
for (y = 1; y < this.height - 1; y++) {
if (this.get(x, y) == Tile.WALL) {
islandSize = this.floodFill(x, y, Tile.TEMP);
if (islandSize < maxSize) {
this.floodFill(x, y, Tile.FLOOR);
}
}
}
}
for (x = 1; x < this.width - 1; x++) {
for (y = 1; y < this.height - 1; y++) {
if (this.get(x, y) == Tile.TEMP) {
this.set(x, y, Tile.WALL);
}
}
}
}
countTilesAround(x: number, y: number, tile: Tile) {
var count = 0;
if (this.get(x + 1, y) == tile) count++;
if (this.get(x, y + 1) == tile) count++;
if (this.get(x - 1, y) == tile) count++;
if (this.get(x, y - 1) == tile) count++;
return count;
}
addExtraConnectors() {
var connectors = this.getConnectors(Tile.FLOOR, Tile.FLOOR);
var numExtraConnectors = this.numExtraConnectors;
while (numExtraConnectors > 0) {
if (connectors.length === 0) break;
var connector = this.rng.sampleAndRemove(connectors);
var x, y;
var thickness = this.connectorThickness - 1;
for (x = connector.x - thickness; x <= connector.x + thickness; x++) {
for (y = connector.y - thickness; y <= connector.y + thickness; y++) {
if (x > 0 && x < this.width - 1 && y > 0 && y < this.height - 1) {
this.set(x, y, Tile.FLOOR);
}
}
}
numExtraConnectors--;
}
};
runCellularAutomataStep<T>(grid: Grid<T>, options: CellularAutomataOptions<T>) {
var width = options.width;
var height = options.height;
var rule = options.rule;
var alive = options.alive == null ? Tile.WALL : options.alive;
var dead = options.dead == null ? Tile.FLOOR : options.dead;
var gridCopy = grid.slice(0);
var x, y, x2, y2;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
var aliveNeighborCount = 0;
for (x2 = x - 1; x2 <= x + 1; x2++) {
for (y2 = y - 1; y2 <= y + 1; y2++) if (!(x == x2 && y == y2)) {
if (get(grid, width, height, x2, y2, dead) == alive) {
aliveNeighborCount++;
}
}
}
if (get(grid, width, height, x, y, dead) == dead) {
if (rule.birth.indexOf(aliveNeighborCount) > -1) {
set(gridCopy, width, height, x, y, alive);
}
} else {
if (rule.survive.indexOf(aliveNeighborCount) == -1) {
set(gridCopy, width, height, x, y, dead);
}
}
}
}
// Replace the old grid with the new one.
var i;
for (i = 0; i < grid.length; i++) {
grid[i] = gridCopy[i];
}
};
}
|
7458e07096ee5d139e0ff0b46fcfe61c60b113e2
|
TypeScript
|
mtrybus2208/ng-colour-game
|
/src/app/shared/pipes/mapGameTimeToSec.pipe.ts
| 2.578125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'mapGameTimeToSec'
})
export class MapGameTimeToSecPipe implements PipeTransform {
transform(value: any, revert?: boolean): any {
if (revert === true) {
switch (value) {
case 30: return 'short';
case 60: return 'medium';
case 90: return 'long';
default: return '90s';
}
} else {
switch (value) {
case 'short': return '30s';
case 'medium': return '60s';
case 'long': return '90s';
default: return '90s';
}
}
}
}
|
223c70482b3e81cfbad2b610ce0a61b82f2eec76
|
TypeScript
|
efueger/sonia-discord
|
/src/features/node/functions/is-valid-port.spec.ts
| 2.828125
| 3
|
import { isValidPort } from './is-valid-port';
describe(`isValidPort()`, (): void => {
let port: unknown;
describe(`when the given port is undefined`, (): void => {
beforeEach((): void => {
port = undefined;
});
it(`should return false`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(false);
});
});
describe(`when the given port is null`, (): void => {
beforeEach((): void => {
port = null;
});
it(`should return false`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(false);
});
});
describe(`when the given port is an empty string"`, (): void => {
beforeEach((): void => {
port = ``;
});
it(`should return false`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(false);
});
});
describe(`when the given port is NaN`, (): void => {
beforeEach((): void => {
port = NaN;
});
it(`should return false`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(false);
});
});
describe(`when the given port is "8"`, (): void => {
beforeEach((): void => {
port = `8`;
});
it(`should return true`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(true);
});
});
describe(`when the given port is 8`, (): void => {
beforeEach((): void => {
port = 8;
});
it(`should return true`, (): void => {
expect.assertions(1);
const result = isValidPort(port);
expect(result).toStrictEqual(true);
});
});
});
|
97a590cc5138b1360a7fb3b0c58394a79be319a0
|
TypeScript
|
adonisjs/core
|
/src/AssetsManager/Drivers/Vite.ts
| 2.734375
| 3
|
import { AssetsDriverContract } from '@ioc:Adonis/Core/AssetsManager'
import { join } from 'path'
import { BaseDriver } from './Base'
/**
* Resolves entry points and assets path for Vite. Relies
* on the "manifest.json" and "entrypoints.json" files.
*
**********************************************************************
* The driver assumes following format for the manifest.json file
**********************************************************************
*
* ```json
* {
* "assetName": {
* "file": "path",
* "src": "path"
* },
* ...
* }
* ```
**********************************************************************
* The driver assumes following format for the entrypoints.json file
***********************************************************************
*
* ```json
* {
* "url": "url"
* "entrypoints": {
* "entryPointName": {
* "js": ["url", "url"],
* "css": ["url", "url"],
* }
* }
* }
* ```
*
* Please read the documentation for understanding the format of the files.
*/
export class ViteDriver extends BaseDriver implements AssetsDriverContract {
public name = 'vite'
/**
* Vite driver has support for entrypoints
*/
public hasEntrypoints = true
/**
* Attributes to apply to the script tag. Vite needs to serve
* source over native ESM
*/
public scriptAttributes: Record<string, any> = { type: 'module' }
/**
* If we should use the manifest. We only use the manifest in production.
*/
private shouldUseManifest() {
return this.application.inProduction
}
/**
* Get the assets url from the entrypoints.json file
*/
private getAssetUrl() {
return this.readFileAsJSON(join(this.publicPath, 'entrypoints.json')).url
}
/**
* Returns path to a given asset file
*/
public assetPath(filename: string): string {
if (!this.shouldUseManifest()) {
return `${this.getAssetUrl()}/${filename}`
}
const manifest = this.manifest()
if (!manifest[filename]) {
throw new Error(`Cannot find "${filename}" asset in the manifest file`)
}
return `${this.getAssetUrl()}/${manifest[filename].file}`
}
/**
* Returns the manifest contents as object
*
* Note that the manifest file is only available in production.
* Vite doesn't generate any manifest file in development.
*/
public override manifest() {
if (!this.shouldUseManifest()) {
throw new Error('Cannot use manifest when not in production')
}
return super.manifest()
}
/**
* Returns list for all the javascript files for a given entry point
*/
public entryPointJsFiles(name: string): string[] {
const entrypoints = this.entryPoints()
if (!entrypoints[name]) {
throw new Error(
`Cannot find assets for "${name}" entrypoint. Make sure to define it inside the "entryPoints" vite config`
)
}
return entrypoints[name].js
}
/**
* Returns list for all the css files for a given entry point
*/
public entryPointCssFiles(name: string): string[] {
const entrypoints = this.entryPoints()
if (!entrypoints[name]) {
throw new Error(
`Cannot find assets for "${name}" entrypoint. Make sure to define it inside the "entryPoints" vite config`
)
}
return entrypoints[name].css
}
/**
* Returns the script needed for the HMR working with React
*/
public getReactHmrScript(): string {
if (!this.application.inDev) {
return ''
}
return `
<script type="module">
import RefreshRuntime from '${this.getAssetUrl()}/@react-refresh'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
`
}
/**
* Returns the script needed for the HMR working with Vite
*/
public getViteHmrScript(): string {
if (!this.application.inDev) {
return ''
}
return `<script type="module" src="${this.getAssetUrl()}/@vite/client"></script>`
}
}
|
32116197c3fca66c44d7f397ac1ed8f68df6c263
|
TypeScript
|
Auclown/algo-challenge-ts
|
/053_find-closest-pair/attempt.ts
| 3.6875
| 4
|
const findClosestPair = (a: number[], sum: number): number => {
let result: number = -1;
for (let i = 0; i < a.length; i++) {
for (let j = i + 1; j < a.length - 1; j++) {
let current = Math.abs(i - j);
if (a[i] + a[j] == sum) {
if (result == -1 || current < result) {
result = current;
}
}
}
}
return result;
};
// Test
console.log(findClosestPair([1, 0, 2, 4, 3, 0], 5)); // 2
console.log(findClosestPair([2, 3, 7], 8)); // -1
|
dabcc411eb0e552c4985f06caeedc7f0397c7765
|
TypeScript
|
Pirsanth/photo-share
|
/controllers/commentLikes.ts
| 2.640625
| 3
|
import { Request, Response } from "express";
import * as model from "../model/manageCommentLikes";
async function addLikes(req: Request, res: Response){
try{
const albumName = req.params["albumName"];
const pictureTitle = req.params["pictureTitle"];
const body: {commentId: string } = req.body;
const result = await model.addLikes(albumName, pictureTitle, req.payload.username, body.commentId);
if(result.n){
res.status(204).send();
}
else{
res.status(404).json({error: "The comment to like cannot be found or the given user has already liked the comment"});
}
}
catch(err){
console.log(err);
res.status(500).json({error: "A server error occured while adding the likes to the comment"});
}
}
async function removeLikes(req: Request, res: Response){
try{
const albumName = req.params["albumName"];
const pictureTitle = req.params["pictureTitle"];
const body: { commentId: string } = req.body;
const result = await model.removeLikes(albumName, pictureTitle, req.payload.username, body.commentId);
if(result.n){
res.status(204).send();
}
else{
res.status(404).json({error: "The comment to remove cannot be found or the given user has not already liked the comment"});
}
}
catch(err){
console.log(err);
res.status(500).json({error: "A server error occured while removing the likes on the comment"});
}
}
export default { addLikes, removeLikes }
|
0368073bb1adbb6b820a0877ab05b1336ec9e8c1
|
TypeScript
|
jngk2/e-notes.org
|
/src/client.ts
| 2.59375
| 3
|
import HTML = marked.Tokens.HTML;
const main = () => {
if ((document.readyState === 'interactive' && Boolean(document.body)) || document.readyState === 'complete') {
go();
} else {
document.addEventListener('DOMContentLoaded', go);
}
}
const clipCopy = async (event: MouseEvent) => {
const code = ((event.target as HTMLElement)?.parentNode as HTMLElement)?.nextElementSibling
if (code && code.textContent) {
await navigator.clipboard.writeText(code.textContent)
}
}
const addClipCopy = (node: HTMLElement) => {
const span = document.createElement('span')
span.addEventListener('click', clipCopy)
span.classList.add('copy-to-clip')
if (node && node.parentNode) {
(node.parentNode as HTMLElement).classList.add('code-columns')
node.parentNode.appendChild(span)
}
}
const go = () => {
Array.from(document.querySelectorAll('code')).map(addClipCopy)
}
main()
|
cb5b5f3d988af9cd268268786dd7df847b3af652
|
TypeScript
|
arogozine/LinqToTypeScript
|
/tests/unittests/tests/SumAsync.ts
| 2.5625
| 3
|
import { asAsync, itAsync, itEnumerableAsync, itParallel } from "../TestHelpers"
describe("sumAsync", () => {
itEnumerableAsync<{ a: number }>("sum Selector", async (asEnumerable) => {
const zooms = await asEnumerable([ { a: 1}, { a: 2 }, {a: 3} ])
.sumAsync(async (x) => x.a)
expect(zooms).toBe(6)
})
itAsync("sum Selector", async () => {
const zooms = asAsync([ { a: 1}, { a: 2 }, {a: 3} ])
expect(await zooms.sumAsync(async (x) => x.a)).toBe(6)
})
itParallel<{ a: number }>("sum Selector", async (asParallel) => {
const zooms = asParallel([ { a: 1}, { a: 2 }, {a: 3} ])
expect(await zooms.sumAsync(async (x) => x.a)).toBe(6)
})
})
|