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
|
|---|---|---|---|---|---|---|
c31a58b03dd40432b8492f7c4d1ad538f40a8f6b
|
TypeScript
|
Vivify-Ideas/cypress-testrail-reporter
|
/src/lib/testrail.validation.ts
| 2.90625
| 3
|
import { TestRailOptions } from "./testrail.interface";
const glob = require('glob');
const TestRailLogger = require('./testrail.logger');
export class TestRailValidation {
constructor(private options: TestRailOptions) {
}
public validateReporterOptions (reporterOptions) {
if (!reporterOptions) {
throw new Error('Missing reporterOptions in cypress.json');
}
this.validate(reporterOptions, 'host');
this.validate(reporterOptions, 'username');
this.validate(reporterOptions, 'password');
this.validate(reporterOptions, 'projectId');
if (this.options.suiteId) {
this.validate(reporterOptions, 'suiteId');
}
return reporterOptions;
}
private validate (options, name) {
if (options[name] == null) {
throw new Error(`Missing ${name} value. Please update options in cypress.json`);
}
}
/**
* This function will validate do we pass suiteId as a CLI agrument as a part of command line execution
* Example:
* CYPRESS_ENV="testRailSuiteId=1"
* npx cypress run --env="${CYPRESS_ENV}"
*/
public validateCLIArguments () {
// Read and store cli arguments into array
const cliArgs = process.argv.slice(2);
// Search array for a specific string and store into variable
var index, value, result;
for (index = 0; index < cliArgs.length; ++index) {
value = cliArgs[index];
if (value.includes('testRailSuiteId') === true) {
result = value;
break;
}
}
if (result != undefined) {
/**
* Search for specific variable in case that previous command contains multiple results
* Split variables
*/
const resultArrayArgs = result.split(/,/);
for (index = 0; index < resultArrayArgs.length; ++index) {
value = resultArrayArgs[index];
if (value.includes('testRailSuiteId') === true) {
result = value;
break;
}
}
// Split variable and value
const resultArray = result.split(/=/);
// Find value of suiteId and store it in envVariable
const suiteId = resultArray.find(el => el.length < 15)
if (suiteId.length != 0) {
TestRailLogger.log(`Following suiteId has been set in runtime environment variables: ${suiteId}`);
}
return suiteId;
}
}
/**
* This function will count how many test spec files do we have during execution
* and based on that we will wait until last one is executed to close active test run in TestRail
*/
public countTestSpecFiles () {
// Read and store cli arguments into array
var cliArgs = process.argv.slice(2);
/**
* Count how many test files will be included in the run
* to be able to close test run after last one
*/
var index, value, result, directory;
var workingDirectory = [];
var specFiles = [];
var specFilesArray = [];
for (index = 0; index < cliArgs.length; ++index) {
value = cliArgs[index];
if (
value.includes("cypress/integration") === true ||
value.includes("cypress/e2e") === true ||
value.includes("cypress/tests") === true
) {
result = value;
break;
}
}
const specArg = result.split(/,/);
for (index = 0; index < specArg.length; ++index) {
value = specArg[index];
result = value.replace(/(?:\.(?![^.]+$)|[^\w])+/g, "/");
directory = result.replace(/\b(js|ts|feature)\b/, '');
workingDirectory.push(directory);
}
for (index = 0; index < workingDirectory.length; ++index) {
value = workingDirectory[index];
const options = {
cwd: value,
nodir: true
}
result = glob.sync("*", options);
specFiles.push(result);
}
/**
* Since in previous steps we create 2D array,
* we need to covert it to 1D in order to get desired length
*/
for (index = 0; index < specFiles.length; ++index) {
specFilesArray = specFilesArray.concat(specFiles[index]);
}
return specFilesArray;
}
}
|
f2dfd9aa68ed548bf44ba60a9c59a87c055a3c1e
|
TypeScript
|
isabella232/azure-maps-spider-clusters
|
/src/extensions/EventManager.ts
| 2.578125
| 3
|
import { SpiderClusterManager } from '../SpiderClusterManager';
import { SpiderClusterEventArg } from '../SpiderClusterEventArg';
/**
* This module partially defines the map control.
* This definition only includes the features added by using the drawing tools.
* For the base definition see:
* https://docs.microsoft.com/javascript/api/azure-maps-control/?view=azure-maps-typescript-latest
*/
declare module "azure-maps-control" {
/**
* This interface partially defines the map control's `EventManager`.
* This definition only includes the method added by using the drawing tools.
* For the base definition see:
* https://docs.microsoft.com/javascript/api/azure-maps-control/atlas.eventmanager?view=azure-maps-typescript-latest
*/
export interface EventManager {
/**
* Adds an event to the `SpiderClusterManager`.
* @param eventType The event name.
* @param target The `SpiderClusterManager` to add the event for.
* @param callback The event handler callback.
*/
add(eventType: "featureSelected", target: SpiderClusterManager, callback: (e: SpiderClusterEventArg) => void): void;
/**
* Adds an event to the `SpiderClusterManager`.
* @param eventType The event name.
* @param target The `SpiderClusterManager` to add the event for.
* @param callback The event handler callback.
*/
add(eventType: "featureUnselected", target: SpiderClusterManager, callback: () => void): void;
/**
* Adds an event to the `SpiderClusterManager` once.
* @param eventType The event name.
* @param target The `SpiderClusterManager` to add the event for.
* @param callback The event handler callback.
*/
addOnce(eventType: "featureSelected", target: SpiderClusterManager, callback: (e: SpiderClusterEventArg) => void): void;
/**
* Adds an event to the `SpiderClusterManager` once.
* @param eventType The event name.
* @param target The `SpiderClusterManager` to add the event for.
* @param callback The event handler callback.
*/
addOnce(eventType: "featureUnselected", target: SpiderClusterManager, callback: () => void): void;
/**
* Removes an event listener from the `SpiderClusterManager`.
* @param eventType The event name.
* @param target The `SpiderClusterManager` to remove the event for.
* @param callback The event handler callback.
*/
remove(eventType: string, target: SpiderClusterManager, callback: (e?: any) => void): void;
}
}
|
5c8b77fc00ddf35b23aa5046668ce4417a45316a
|
TypeScript
|
GamesProSeif/jr-gopnik
|
/src/commands/mod/ban.ts
| 2.6875
| 3
|
import { Argument, Command } from 'discord-akairo';
import { GuildMember, Message, MessageEmbed } from 'discord.js';
import { COLORS, MESSAGES } from '../../util/constants';
export default class BanCommand extends Command {
constructor() {
super('ban', {
aliases: ['ban'],
description: {
content: MESSAGES.COMMANDS.MOD.BAN.DESCRIPTION.CONTENT,
usage: MESSAGES.COMMANDS.MOD.BAN.DESCRIPTION.USAGE
},
category: 'mod',
channel: 'guild',
clientPermissions: ['BAN_MEMBERS'],
userPermissions: ['BAN_MEMBERS'],
args: [
{
id: 'member',
type: 'member',
prompt: {
start: MESSAGES.COMMANDS.MOD.BAN.ARGS.MEMBER.PROMPT.START,
retry: MESSAGES.COMMANDS.MOD.BAN.ARGS.MEMBER.PROMPT.RETRY
}
},
{
id: 'reason',
type: 'string',
match: 'rest',
prompt: {
start: MESSAGES.COMMANDS.MOD.BAN.ARGS.REASON.PROMPT.START
}
}
]
});
}
public async exec(
message: Message,
{ member, reason }: { member: GuildMember; reason?: string }
) {
if (
member.roles.highest.position >=
message.member!.roles.highest.position
) {
return this.client.commandHandler.emit(
'missingPermissions',
message,
this.client.commandHandler.modules.get('ban'),
'user',
['Member same or higher in role hierarchy']
);
}
if (
member.roles.highest.position >=
message.guild!.me!.roles.highest.position
) {
return this.client.commandHandler.emit(
'missingPermissions',
message,
this.client.commandHandler.modules.get('ban'),
'client',
['Member same or higher in role hierarchy']
);
}
reason = reason === 'none' ? undefined : reason;
const embed = new MessageEmbed()
.setColor(COLORS.WARNING)
.setAuthor(member.user.tag, member.user.displayAvatarURL())
.setDescription(MESSAGES.COMMANDS.MOD.BAN.RESPONSE.CONFIRM.DESCRIPTION)
.addField(
'❯ Member',
MESSAGES.COMMANDS.MOD.BAN.RESPONSE.CONFIRM.FIELD(member)
)
.addField(`❯ Reason`, reason ? reason : 'Not supplied');
await message.channel.send(embed);
const confirmArg = new Argument(this, {
'id': 'confirm',
'type': [['yes', 'yup', 'y'], ['no', 'nope', 'n']],
'default': 'no'
});
const confirm = await confirmArg.collect(message);
if (confirm.match(/y(es|up)?/)) {
await member.ban({ days: 1, reason });
return message.channel.send(MESSAGES.COMMANDS.MOD.BAN.RESPONSE.DONE(member));
}
return message.channel.send(MESSAGES.CLIENT.COMMAND_HANDLER.PROMPT_CANCEL);
}
}
|
c201dec7053f83a365b6f001798bb17bd2c14b02
|
TypeScript
|
SpocWeb/davinci-newton
|
/src/lib/math/Spacetime1.ts
| 2.765625
| 3
|
import { readOnly } from "../i18n/readOnly";
import { AbstractMeasure } from "./AbstractMeasure";
import { gauss } from "./gauss";
import { GeometricNumber } from "./GeometricNumber";
import { GeometricOperators } from "./GeometricOperators";
import { GradeMasked } from "./GradeMasked";
import { QQ } from "./QQ";
import { stringFromCoordinates } from "./stringFromCoordinates";
import { Unit } from "./Unit";
/**
* @hidden
*/
const COORD_0_A = 0;
/**
* @hidden
*/
const COORD_1_T = 1;
/**
* @hidden
*/
const COORD_2_X = 2;
/**
* @hidden
*/
const COORD_3_TX = 3;
/**
* Coordinates corresponding to basis labels.
* @hidden
*/
const coordinates = function (m: GeometricM11): [a: number, t: number, x: number, tx: number] {
const coords: [number, number, number, number] = [0, 0, 0, 0];
coords[COORD_0_A] = m.a;
coords[COORD_1_T] = m.t;
coords[COORD_2_X] = m.x;
coords[COORD_3_TX] = m.b;
return coords;
};
interface Vector {
t: number;
x: number;
uom?: Unit;
}
interface Spinor {
a: number;
b: number;
uom?: Unit;
}
interface GeometricM11 extends Vector, Spinor {
uom?: Unit;
}
/**
* @hidden
*/
const BASIS_LABELS: ['1', 'e0', 'e1', 'I'] = ["1", "e0", "e1", "I"];
/**
* @hidden
*/
const BASIS_LABELS_LaTeX: ['1', 'e_{0}', 'e_{1}', 'I'] = ["1", "e_{0}", "e_{1}", "I"];
/**
*
*/
export class Spacetime1 extends AbstractMeasure implements GradeMasked, GeometricM11, GeometricNumber<Spacetime1, Spacetime1, Spinor, Vector, number>, GeometricOperators<Spacetime1> {
/**
* The scalar value 0.
*
* This scalar is permanently locked (immutable).
*/
static readonly zero = Spacetime1.scalar(0).permlock();
/**
* The scalar value 1.
*
* This scalar is permanently locked (immutable).
*/
static readonly one = Spacetime1.scalar(1).permlock();
/**
* The vector in the Time direction.
*
* e0 * e0 = 1
*
* This vector is permanently locked (immutable).
*/
static readonly e0 = Spacetime1.vector(1, 0).permlock();
/**
* The vector in the Space direction.
*
* e1 * e1 = -1
*
* This vector is permanently locked (immutable).
*/
static readonly e1 = Spacetime1.vector(0, 1).permlock();
static readonly I = new Spacetime1(0, 0, 0, 1).permlock();
static readonly kilogram = Spacetime1.scalar(1, Unit.KILOGRAM).permlock();
static readonly meter = Spacetime1.scalar(1, Unit.METER).permlock();
static readonly second = Spacetime1.scalar(1, Unit.SECOND).permlock();
static readonly ampere = Spacetime1.scalar(1, Unit.AMPERE).permlock();
static readonly kelvin = Spacetime1.scalar(1, Unit.KELVIN).permlock();
static readonly mole = Spacetime1.scalar(1, Unit.MOLE).permlock();
static readonly candela = Spacetime1.scalar(1, Unit.CANDELA).permlock();
static readonly coulomb = Spacetime1.scalar(1, Unit.COULOMB).permlock();
static readonly newton = Spacetime1.scalar(1, Unit.NEWTON).permlock();
static readonly joule = Spacetime1.scalar(1, Unit.JOULE).permlock();
/**
* Creates a grade 0 (scalar) multivector with value `a * uom`.
* The scalar returned is in the unlocked (mutable) state.
* @param a The scaling factor for the unit of measure.
* @param uom The optional unit of measure. Equivalent to 1 if omitted.
*/
static scalar(a: number, uom?: Unit): Spacetime1 {
return new Spacetime1(a, 0, 0, 0, uom);
}
/**
* Creates a grade 1 (vector) multivector with a value (t * e0 + x * e1) * uom.
* The value returned is in the unlocked (mutable) state.
* @param t the coordinate corresponding to the e0 basis vector.
* @param x the coordinate corresponding to the e1 basis vector.
* @param uom the optional unit of measure. Equivalent to 1 if omitted.
*/
static vector(t: number, x: number, uom?: Unit): Spacetime1 {
return new Spacetime1(0, t, x, 0, uom);
}
/**
* a
*/
private $M00: number;
/**
* t
*/
private $M01: number;
/**
* x
*/
private $M10: number;
/**
* tx
*/
private $M11: number;
/**
*
* @param a the coordinate of this multivector corresponding to the one scalar. Default is zero.
* @param t the coordinate of this multivector corresponding to the e0 basis vector. Default is zero..
* @param x the coordinate of this multivector corresponding to the e1 basis vector. Default is zero.
* @param b the coordinate of this multivector corresponding to the I pseudoscalar. Default is zero.
* @param uom the optional unit of measure for this multivector.
*/
constructor(a = 0, t = 0, x = 0, b = 0, uom?: Unit) {
super(uom);
this.$M00 = a;
this.$M01 = t;
this.$M10 = x;
this.$M11 = b;
}
get a(): number {
return this.$M00;
}
set a(a: number) {
if (this.isMutable()) {
this.$M00 = a;
} else {
throw new Error(readOnly('a').message);
}
}
get t(): number {
return this.$M01;
}
set t(t: number) {
if (this.isMutable()) {
this.$M01 = t;
} else {
throw new Error(readOnly('t').message);
}
}
get x(): number {
return this.$M10;
}
set x(x: number) {
if (this.isMutable()) {
this.$M10 = x;
} else {
throw new Error(readOnly('x').message);
}
}
get b(): number {
return this.$M11;
}
set b(b: number) {
if (this.isMutable()) {
this.$M11 = b;
} else {
throw new Error(readOnly('b').message);
}
}
get grades(): number {
let mask = 0x0;
if (this.$M00 !== 0) {
mask += 0x1;
}
if (this.t !== 0 || this.x !== 0) {
mask += 0x2;
}
if (this.b !== 0) {
mask += 0x4;
}
return mask;
}
add(rhs: Spacetime1, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().add(rhs, α).permlock();
} else {
if (this.isZero()) {
this.a = rhs.a * α;
this.t = rhs.t * α;
this.x = rhs.x * α;
this.b = rhs.b * α;
this.uom = rhs.uom;
return this;
}
else if (rhs.isZero() || α === 0) {
return this;
}
else {
this.a += rhs.a * α;
this.t += rhs.t * α;
this.x += rhs.x * α;
this.b += rhs.b * α;
this.uom = Unit.compatible(this.uom, rhs.uom);
return this;
}
}
}
/**
* @hidden
*/
addScalar(a: number, uom?: Unit, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().addScalar(a, uom, α).permlock();
}
else {
if (this.isZero()) {
this.a = a * α;
this.uom = uom;
return this;
}
else if (a === 0 || α === 0) {
return this;
}
else {
this.a += a * α;
this.uom = Unit.compatible(this.uom, uom);
return this;
}
}
}
/**
* @hidden
* @param v
* @param α
* @returns
*/
addVector(v: Vector, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().addVector(v, α).permlock();
}
else {
if (this.isZero()) {
this.uom = v.uom;
}
else if (v.t === 0 && v.x === 0) {
return this;
}
else {
this.uom = Unit.compatible(this.uom, v.uom);
}
this.t += v.t * α;
this.x += v.x * α;
return this;
}
}
clone(): Spacetime1 {
return new Spacetime1(this.a, this.t, this.x, this.b, this.uom);
}
conj(): Spacetime1 {
if (this.isLocked()) {
return this.clone().conj().permlock();
}
else {
this.$M00 = this.$M00;
this.$M01 = -this.$M01;
this.$M10 = -this.$M10;
this.$M11 = -this.$M11;
return this;
}
}
div(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().div(rhs).permlock();
} else {
return this.mul(rhs.clone().inv().permlock());
}
}
/**
* @hidden
*/
divByNumber(a: number): Spacetime1 {
if (this.isLocked()) {
return this.clone().divByNumber(a).permlock();
}
else {
this.$M00 /= a;
this.$M01 /= a;
this.$M10 /= a;
this.$M11 /= a;
return this;
}
}
divByScalar(a: number, uom?: Unit): Spacetime1 {
if (this.isLocked()) {
return this.clone().divByScalar(a, uom).permlock();
}
else {
this.$M00 /= a;
this.$M01 /= a;
this.$M10 /= a;
this.$M11 /= a;
this.uom = Unit.div(this.uom, uom);
return this;
}
}
divByVector(v: Vector): Spacetime1 {
if (this.isLocked()) {
return this.clone().divByVector(v).permlock();
}
else {
const t = v.t;
const x = v.x;
return this.mulByVector(v).divByScalar(t * t - x * x, Unit.pow(v.uom, QQ.valueOf(2, 1)));
}
}
dual(): Spacetime1 {
if (this.isLocked()) {
return this.clone().dual().permlock();
}
else {
const M000 = this.$M00;
const M001 = this.$M01;
const M010 = this.$M10;
const M011 = this.$M11;
this.$M00 = M011;
this.$M01 = M010;
this.$M10 = M001;
this.$M11 = M000;
return this;
}
}
equals(other: unknown): boolean {
if (other === this) {
return true;
}
else if (other instanceof Spacetime1) {
return Unit.isCompatible(this.uom, other.uom) &&
this.a === other.a &&
this.t === other.t &&
this.x === other.x &&
this.b === other.b;
}
else {
return false;
}
}
ext(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().ext(rhs).permlock();
} else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R000 = rhs.$M00;
const R001 = rhs.$M01;
const R010 = rhs.$M10;
const R011 = rhs.$M11;
this.$M00 = L000 * R000;
this.$M01 = L000 * R001 + L001 * R000;
this.$M10 = L000 * R010 + L010 * R000;
this.$M11 = L000 * R011 + L001 * R010 - L010 * R001 + L011 * R000;
this.uom = Unit.mul(this.uom, rhs.uom);
return this;
}
}
grade(n: number): Spacetime1 {
if (this.isLocked()) {
return this.clone().grade(n).permlock();
}
else {
// There is no change to the unit of measure.
switch (n) {
case 0: {
this.t = 0;
this.x = 0;
this.b = 0;
break;
}
case 1: {
this.a = 0;
this.b = 0;
break;
}
case 2: {
this.a = 0;
this.t = 0;
this.x = 0;
break;
}
default: {
this.a = 0;
this.t = 0;
this.x = 0;
this.b = 0;
}
}
return this;
}
}
inv(): Spacetime1 {
if (this.isLocked()) {
return this.clone().inv().permlock();
}
else {
const x0 = this.$M00;
const x1 = this.$M01;
const x2 = this.$M10;
const x3 = this.$M11;
const A = [
[+x0, +x1, -x2, +x3],
[+x1, +x0, +x3, -x2],
[+x2, +x3, +x0, -x1],
[+x3, +x2, -x1, +x0],
];
const b = [1, 0, 0, 0];
const X = gauss(A, b);
this.a = X[0];
this.t = X[1];
this.x = X[2];
this.b = X[3];
this.uom = Unit.inv(this.uom);
return this;
}
}
isBivector(): boolean {
return this.a === 0 && this.t === 0 && this.x === 0;
}
isOne(): boolean {
return this.a === 1 && this.t === 0 && this.x === 0 && this.b === 0 && Unit.isOne(this.uom);
}
isScalar(): boolean {
return this.t === 0 && this.x === 0 && this.b === 0;
}
isSpinor(): boolean {
return this.t === 0 && this.x === 0;
}
isVector(): boolean {
return this.a === 0 && this.b === 0;
}
isZero(): boolean {
return this.a === 0 && this.t === 0 && this.x === 0 && this.b === 0;
}
lco(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().lco(rhs).permlock();
} else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R000 = rhs.$M00;
const R001 = rhs.$M01;
const R010 = rhs.$M10;
const R011 = rhs.$M11;
this.$M00 = L000 * R000 + L001 * R001 - L010 * R010 + L011 * R011;
this.$M01 = L000 * R001 + L010 * R011;
this.$M10 = L000 * R010 + L001 * R011;
this.$M11 = L000 * R011;
this.uom = Unit.mul(this.uom, rhs.uom);
return this;
}
}
mul(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().mul(rhs).permlock();
} else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R000 = rhs.$M00;
const R001 = rhs.$M01;
const R010 = rhs.$M10;
const R011 = rhs.$M11;
this.$M00 = L000 * R000 + L001 * R001 - L010 * R010 + L011 * R011;
this.$M01 = L000 * R001 + L001 * R000 + L010 * R011 - L011 * R010;
this.$M10 = L000 * R010 + L010 * R000 + L001 * R011 - L011 * R001;
this.$M11 = L000 * R011 + L001 * R010 - L010 * R001 + L011 * R000;
this.uom = Unit.mul(this.uom, rhs.uom);
return this;
}
}
/**
* @hidden
*/
mulByNumber(a: number): Spacetime1 {
if (this.isLocked()) {
return this.clone().mulByNumber(a).permlock();
}
else {
this.$M00 *= a;
this.$M01 *= a;
this.$M10 *= a;
this.$M11 *= a;
return this;
}
}
mulByScalar(a: number, uom: Unit): Spacetime1 {
if (this.isLocked()) {
return this.clone().mulByScalar(a, uom).permlock();
}
else {
this.$M00 *= a;
this.$M01 *= a;
this.$M10 *= a;
this.$M11 *= a;
this.uom = Unit.mul(this.uom, uom);
return this;
}
}
mulByVector(v: Vector): Spacetime1 {
if (this.isLocked()) {
return this.clone().mulByVector(v).permlock();
}
else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R001 = v.t;
const R010 = v.x;
this.$M00 = L001 * R001 - L010 * R010;
this.$M01 = L000 * R001 - L011 * R010;
this.$M10 = L000 * R010 - L011 * R001;
this.$M11 = L001 * R010 - L010 * R001;
this.uom = Unit.mul(this.uom, v.uom);
return this;
}
}
neg(): Spacetime1 {
if (this.isLocked()) {
return this.clone().neg().permlock();
} else {
this.a = -this.a;
this.t = -this.t;
this.x = -this.x;
this.b = -this.b;
return this;
}
}
/**
* @hidden
*/
quaditude(): Spacetime1 {
return this.squaredNorm();
}
/**
* @hidden
*/
quaditudeNoUnits(): number {
const a = this.$M00;
const t = this.$M01;
const x = this.$M10;
const tx = this.$M11;
return a * a + t * t - x * x - tx * tx;
}
rco(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().rco(rhs).permlock();
} else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R000 = rhs.$M00;
const R001 = rhs.$M01;
const R010 = rhs.$M10;
const R011 = rhs.$M11;
this.$M00 = L000 * R000 + L001 * R001 - L010 * R010 + L011 * R011;
this.$M01 = L001 * R000 - L011 * R010;
this.$M10 = L010 * R000 - L011 * R001;
this.$M11 = L011 * R000;
this.uom = Unit.mul(this.uom, rhs.uom);
return this;
}
}
reflect(n: Vector): Spacetime1 {
if (this.isLocked()) {
return this.clone().reflect(n).permlock();
} else {
const t = n.t;
const t2 = t * t;
const x = n.x;
const x2 = x * x;
this.$M00 = this.$M00 * (x2 - t2);
this.$M01 = -this.$M01 * (t2 + x2);
this.$M10 = this.$M10 * (t2 + x2);
this.$M11 = -this.$M11 * (t2 + x2);
return this;
}
}
rev(): Spacetime1 {
if (this.isLocked()) {
return this.clone().rev().permlock();
}
else {
this.$M00 = this.$M00;
this.$M01 = this.$M01;
this.$M10 = this.$M10;
this.$M11 = -this.$M11;
return this;
}
}
rotate(spinor: Spinor): Spacetime1 {
if (this.isLocked()) {
return this.clone().rotate(spinor).permlock();
}
else {
// const Sa = spinor.a;
// const Sb = spinor.b;
throw new Error("Method not implemented.");
}
}
/**
* @hidden
*/
scale(α: number): Spacetime1 {
if (this.isLocked()) {
return this.clone().scale(α).permlock();
} else {
this.$M00 = this.$M00 * α;
this.$M01 = this.$M01 * α;
this.$M10 = this.$M10 * α;
this.$M11 = this.$M11 * α;
return this;
}
}
scp(rhs: Spacetime1): Spacetime1 {
if (this.isLocked()) {
return this.clone().scp(rhs).permlock();
} else {
const L000 = this.$M00;
const L001 = this.$M01;
const L010 = this.$M10;
const L011 = this.$M11;
const R000 = rhs.$M00;
const R001 = rhs.$M01;
const R010 = rhs.$M10;
const R011 = rhs.$M11;
this.$M00 = L000 * R000 + L001 * R001 - L010 * R010 + L011 * R011;
this.$M01 = 0;
this.$M10 = 0;
this.$M11 = 0;
this.uom = Unit.mul(this.uom, rhs.uom);
return this;
}
}
sqrt(): Spacetime1 {
if (this.isLocked()) {
return this.clone().sqrt().permlock();
}
else {
if (this.isScalar()) {
this.$M00 = Math.sqrt(this.$M00);
this.$M01 = 0;
this.$M10 = 0;
this.$M11 = 0;
this.uom = Unit.sqrt(this.uom);
return this;
}
else {
throw new Error(`Target of sqrt() method must be a scalar, but was ${this}`);
}
}
}
squaredNorm(): Spacetime1 {
if (this.isLocked()) {
return this.clone().squaredNorm().permlock();
} else {
const a = this.$M00;
const t = this.$M01;
const x = this.$M10;
const tx = this.$M11;
this.$M00 = a * a + t * t - x * x - tx * tx;
this.$M01 = 0;
this.$M10 = 0;
this.$M11 = 0;
this.uom = Unit.mul(this.uom, this.uom);
return this;
}
}
sub(rhs: Spacetime1, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().sub(rhs, α).permlock();
} else {
if (this.isZero()) {
this.a = -rhs.a * α;
this.t = -rhs.t * α;
this.x = -rhs.x * α;
this.b = -rhs.b * α;
this.uom = rhs.uom;
return this;
}
else if (rhs.isZero() || α === 0) {
return this;
}
else {
this.a -= rhs.a * α;
this.t -= rhs.t * α;
this.x -= rhs.x * α;
this.b -= rhs.b * α;
this.uom = Unit.compatible(this.uom, rhs.uom);
return this;
}
}
}
/**
* @hidden
*/
subScalar(a: number, uom?: Unit, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().subScalar(a, uom, α).permlock();
}
else {
if (this.isZero()) {
this.a = - a * α;
this.uom = uom;
return this;
} else if (a === 0 || α === 0) {
return this;
}
else {
this.a -= a * α;
this.uom = Unit.compatible(this.uom, uom);
return this;
}
}
}
/**
* @hidden
* @param v
* @param α
* @returns
*/
subVector(v: Vector, α = 1): Spacetime1 {
if (this.isLocked()) {
return this.clone().subVector(v, α).permlock();
}
else {
if (this.isZero()) {
this.uom = v.uom;
}
else if (v.t === 0 && v.x === 0) {
return this;
}
else {
this.uom = Unit.compatible(this.uom, v.uom);
}
this.t -= v.t * α;
this.x -= v.x * α;
return this;
}
}
toExponential(fractionDigits?: number): string {
const coordToString = function (coord: number): string { return coord.toExponential(fractionDigits); };
return stringFromCoordinates(coordinates(this), coordToString, BASIS_LABELS, this.uom);
}
toFixed(fractionDigits?: number): string {
const coordToString = function (coord: number): string { return coord.toFixed(fractionDigits); };
return stringFromCoordinates(coordinates(this), coordToString, BASIS_LABELS, this.uom);
}
toLaTeX(radix?: number): string {
const coordToString = function (coord: number): string { return coord.toString(radix); };
return stringFromCoordinates(coordinates(this), coordToString, BASIS_LABELS_LaTeX, this.uom);
}
toPrecision(precision?: number): string {
const coordToString = function (coord: number): string { return coord.toPrecision(precision); };
return stringFromCoordinates(coordinates(this), coordToString, BASIS_LABELS, this.uom);
}
toString(radix?: number): string {
const coordToString = function (coord: number): string { return coord.toString(radix); };
return stringFromCoordinates(coordinates(this), coordToString, BASIS_LABELS, this.uom);
}
/**
* @hidden
*/
__div__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().div(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().divByNumber(rhs).permlock();
}
else if (rhs instanceof Unit) {
return this.clone().divByScalar(1, rhs).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rdiv__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().div(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).div(this).permlock();
}
else if (lhs instanceof Unit) {
return Spacetime1.scalar(1, lhs).div(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__vbar__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().scp(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().scp(Spacetime1.scalar(rhs)).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rvbar__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().scp(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).scp(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__wedge__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().ext(rhs).permlock();
}
else if (typeof rhs === 'number') {
// The outer product with a scalar is scalar multiplication.
return this.clone().mulByNumber(rhs).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rwedge__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().ext(this).permlock();
}
else if (typeof lhs === 'number') {
// The outer product with a scalar is scalar multiplication, and commutes.
return this.clone().mulByNumber(lhs).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__lshift__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().lco(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().lco(Spacetime1.scalar(rhs)).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rlshift__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().lco(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).lco(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rshift__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().rco(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().rco(Spacetime1.scalar(rhs)).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rrshift__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().rco(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).rco(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__bang__(): Spacetime1 {
return this.clone().inv().permlock();
}
/**
* @hidden
*/
__eq__(rhs: number | Spacetime1 | Unit): boolean {
if (rhs instanceof Spacetime1) {
return this.equals(rhs);
}
else if (typeof rhs === 'number') {
return this.equals(Spacetime1.scalar(rhs));
}
else if (rhs instanceof Unit) {
return this.equals(Spacetime1.scalar(1, rhs));
}
else {
return false;
}
}
/**
* @hidden
*/
__ne__(rhs: number | Spacetime1 | Unit): boolean {
if (rhs instanceof Spacetime1) {
return !this.equals(rhs);
}
else if (typeof rhs === 'number') {
return !this.equals(Spacetime1.scalar(rhs));
}
else if (rhs instanceof Unit) {
return !this.equals(Spacetime1.scalar(1, rhs));
}
else {
return true;
}
}
/**
* @hidden
*/
__tilde__(): Spacetime1 {
return this.clone().rev().permlock();
}
/**
* @hidden
*/
__add__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().add(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().addScalar(rhs).permlock();
}
else if (rhs instanceof Unit) {
return this.clone().addScalar(1, rhs, 1).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__radd__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().add(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).add(this).permlock();
}
else if (lhs instanceof Unit) {
return Spacetime1.scalar(1, lhs).add(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__sub__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().sub(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().subScalar(rhs).permlock();
}
else if (rhs instanceof Unit) {
return this.clone().subScalar(1, rhs).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rsub__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().sub(this).permlock();
}
else if (typeof lhs === 'number') {
return Spacetime1.scalar(lhs).sub(this).permlock();
}
else if (lhs instanceof Unit) {
return Spacetime1.scalar(1, lhs).sub(this).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__pos__(): Spacetime1 {
return this.clone().permlock();
}
/**
* @hidden
*/
__neg__(): Spacetime1 {
return this.clone().neg().permlock();
}
/**
* @hidden
*/
__mul__(rhs: number | Spacetime1 | Unit): Spacetime1 {
if (rhs instanceof Spacetime1) {
return this.clone().mul(rhs).permlock();
}
else if (typeof rhs === 'number') {
return this.clone().mulByNumber(rhs).permlock();
}
else if (rhs instanceof Unit) {
return this.clone().mulByScalar(1, rhs).permlock();
}
else {
return void 0;
}
}
/**
* @hidden
*/
__rmul__(lhs: number | Spacetime1 | Unit): Spacetime1 {
if (lhs instanceof Spacetime1) {
return lhs.clone().mul(this).permlock();
}
else if (typeof lhs === 'number') {
return this.clone().mulByNumber(lhs).permlock();
}
else if (lhs instanceof Unit) {
return this.clone().mulByScalar(1, lhs).permlock();
}
else {
return void 0;
}
}
}
|
7d9b317a0808426399a13a87f0cf9b1acf4eb870
|
TypeScript
|
sen-yang/rschedule
|
/packages/core/src/generators/calendar-test-setup.ts
| 2.609375
| 3
|
import { context, dateAdapterFn, TIMEZONES, toISOStrings } from '../../../../tests/utilities';
import { DateAdapter, DateAdapterBase } from '@rschedule/core';
import {
Calendar,
CollectionsGranularity,
Dates,
ICollectionsArgs,
Rule,
Schedule,
} from '@rschedule/core/generators';
export default function calendarTests() {
function toISOStringsCol(calendar: Calendar | DateAdapter[][], args: ICollectionsArgs = {}) {
if (Array.isArray(calendar)) {
return calendar.map(dates => dates.map(date => date.toISOString()));
}
return calendar
.collections({ skipEmptyPeriods: true, granularity: 'millisecond', ...args })
.toArray()
.map(({ dates }) => dates.map(date => date.toISOString()));
}
function testOccurrences(
name: string,
calendar: Calendar,
expectation: DateAdapter[],
collections: {
millisecondly: DateAdapter[][];
yearly: DateAdapter[][];
monthly: { no: DateAdapter[][]; week: DateAdapter[][] };
},
) {
describe(name, () => {
describe('occurrences', () => {
const index = expectation.length < 4 ? 1 : Math.ceil(expectation.length / 2);
it('no args', () => {
expect(toISOStrings(calendar)).toEqual(toISOStrings(expectation));
});
if (expectation.length > 1) {
it('start', () => {
expect(toISOStrings(calendar, { start: expectation[index] })).toEqual(
toISOStrings(expectation.slice(index)),
);
});
it('end', () => {
expect(toISOStrings(calendar, { end: expectation[index] })).toEqual(
toISOStrings(expectation.slice(0, index + 1)),
);
});
}
it('reverse', () => {
expect(toISOStrings(calendar, { reverse: true })).toEqual(
toISOStrings(expectation.reverse()),
);
});
describe('occursOn', () => {
it('date', () => {
for (const date of expectation) {
expect(calendar.occursOn({ date })).toBeTruthy();
}
});
it('weekday', () => {
let weekdays: DateAdapter.Weekday[] = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
for (const date of expectation) {
const weekday = date.toDateTime().get('weekday');
expect(calendar.occursOn({ weekday })).toBeTruthy();
weekdays = weekdays.filter(day => day !== weekday);
}
for (const weekday of weekdays) {
expect(calendar.occursOn({ weekday })).toBeFalsy();
}
});
});
});
describe('collections', () => {
[
['millisecond', collections.millisecondly],
['year', collections.yearly],
['month', collections.monthly.no],
].forEach(pair => {
context(pair[0] as CollectionsGranularity, granularity => {
const expectations = pair[1] as DateAdapter[][];
const collectionIndex =
expectations.length < 4 ? 1 : Math.ceil(expectations.length / 2);
it('no args', () => {
expect(toISOStringsCol(calendar, { granularity })).toEqual(
toISOStringsCol(expectations),
);
});
if (expectations.length > 1) {
it('start', () => {
expect(
toISOStringsCol(calendar, {
granularity,
start: expectations[collectionIndex][0],
}),
).toEqual(toISOStringsCol(expectations.slice(collectionIndex)));
});
it('end', () => {
expect(
toISOStringsCol(calendar, {
granularity,
end: expectations[collectionIndex][0],
}),
).toEqual(toISOStringsCol(expectations.slice(0, collectionIndex + 1)));
});
}
});
});
describe('month', () => {
describe('w/ weekStart', () => {
const expectations = collections.monthly.week;
if (expectations.length === 0) return;
const index = expectations.length < 4 ? 1 : Math.ceil(expectations.length / 2);
it('basic args', () => {
expect(
toISOStringsCol(calendar, {
granularity: 'month',
weekStart: 'MO',
start: expectations[0][0],
end:
expectations[expectations.length - 1][
expectations[expectations.length - 1].length - 1
],
}),
).toEqual(toISOStringsCol(expectations));
});
if (expectations.length > 1) {
it('start', () => {
expect(
toISOStringsCol(calendar, {
granularity: 'month',
weekStart: 'MO',
start: expectations[index][0],
end:
expectations[expectations.length - 1][
expectations[expectations.length - 1].length - 1
],
}),
).toEqual(toISOStringsCol(expectations.slice(index)));
});
}
});
});
});
});
}
describe('Calendar', () => {
context(DateAdapterBase.adapter.name, () => {
// const timezones = !DateAdapterBase.adapter.hasTimezoneSupport ? ['UTC'] : ['UTC'];
const timezones = !DateAdapterBase.adapter.hasTimezoneSupport ? [null, 'UTC'] : TIMEZONES;
timezones.forEach(zone => {
context(zone, timezone => {
const dateAdapter = dateAdapterFn(timezone);
describe('CalendarClass', () => {
it('is instantiable', () =>
expect(new Calendar({ timezone })).toBeInstanceOf(Calendar));
});
it('skipEmptyPeriods: false', () => {
const calendar = new Calendar({
schedules: new Schedule({
rrules: [
// YearlyByMonthAndMonthDay
{
frequency: 'YEARLY',
count: 3,
byMonthOfYear: [1, 3],
byDayOfMonth: [5, 7],
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
timezone,
});
let result = calendar
.collections({ granularity: 'year', start: dateAdapter(1997, 9, 2, 9) })
.toArray()
.map(({ dates }) => dates.map(date => date.toISOString()));
expect(result).toEqual([
[],
[
dateAdapter(1998, 1, 5, 9, 0).toISOString(),
dateAdapter(1998, 1, 7, 9, 0).toISOString(),
dateAdapter(1998, 3, 5, 9, 0).toISOString(),
],
]);
result = calendar
.collections({ granularity: 'month', start: dateAdapter(1997, 9, 2, 9) })
.toArray()
.map(({ dates }) => dates.map(date => date.toISOString()));
expect(result).toEqual([
[],
[],
[],
[],
[
dateAdapter(1998, 1, 5, 9, 0).toISOString(),
dateAdapter(1998, 1, 7, 9, 0).toISOString(),
],
[],
[dateAdapter(1998, 3, 5, 9, 0).toISOString()],
]);
});
testOccurrences(
'1 schedule & 1 rule',
new Calendar({
schedules: new Schedule({
rrules: [
// YearlyByMonthAndMonthDay
{
frequency: 'YEARLY',
count: 3,
byMonthOfYear: [1, 3],
byDayOfMonth: [5, 7],
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
timezone,
}),
[
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
],
{
millisecondly: [
[dateAdapter(1998, 1, 5, 9, 0)],
[dateAdapter(1998, 1, 7, 9, 0)],
[dateAdapter(1998, 3, 5, 9, 0)],
],
yearly: [
[
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
],
],
monthly: {
no: [
[dateAdapter(1998, 1, 5, 9, 0), dateAdapter(1998, 1, 7, 9, 0)],
[dateAdapter(1998, 3, 5, 9, 0)],
],
week: [[dateAdapter(1998, 1, 5, 9, 0), dateAdapter(1998, 1, 7, 9, 0)]],
},
},
);
testOccurrences(
'2 schedules w/ rrules',
new Calendar({
schedules: [
new Schedule({
rrules: [
// YearlyByMonthAndMonthDay
{
frequency: 'YEARLY',
count: 3,
byMonthOfYear: [1, 3],
byDayOfMonth: [5, 7],
start: dateAdapter(1997, 9, 2, 9),
},
// WeeklyIntervalLarge
{
frequency: 'WEEKLY',
count: 2,
interval: 20,
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
new Schedule({
rrules: [
// DailyByMonthDayAndWeekDay
{
frequency: 'DAILY',
count: 3,
byDayOfMonth: [1, 3],
byDayOfWeek: ['TU', 'TH'],
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
],
timezone,
}),
[
dateAdapter(1997, 9, 2, 9, 0),
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
dateAdapter(1998, 2, 3, 9, 0),
dateAdapter(1998, 3, 3, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
],
{
millisecondly: [
[dateAdapter(1997, 9, 2, 9, 0)],
[dateAdapter(1998, 1, 1, 9, 0)],
[dateAdapter(1998, 1, 5, 9, 0)],
[dateAdapter(1998, 1, 7, 9, 0)],
[dateAdapter(1998, 1, 20, 9, 0)],
[dateAdapter(1998, 2, 3, 9, 0)],
[dateAdapter(1998, 3, 3, 9, 0)],
[dateAdapter(1998, 3, 5, 9, 0)],
],
yearly: [
[dateAdapter(1997, 9, 2, 9, 0)],
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
dateAdapter(1998, 2, 3, 9, 0),
dateAdapter(1998, 3, 3, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
],
],
monthly: {
no: [
[dateAdapter(1997, 9, 2, 9, 0)],
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
],
[dateAdapter(1998, 2, 3, 9, 0)],
[dateAdapter(1998, 3, 3, 9, 0), dateAdapter(1998, 3, 5, 9, 0)],
],
week: [
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
],
],
},
},
);
testOccurrences(
'1 schedule & 1 dates',
new Calendar({
schedules: [
new Schedule({
rdates: [dateAdapter(1998, 1, 1, 9, 0)],
}),
new Dates({
dates: [
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(2000, 1, 1, 9, 0),
dateAdapter(2017, 1, 1, 9, 0),
],
}),
],
timezone,
}),
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(2000, 1, 1, 9, 0),
dateAdapter(2017, 1, 1, 9, 0),
],
{
millisecondly: [
[dateAdapter(1998, 1, 1, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
[dateAdapter(2000, 1, 1, 9, 0)],
[dateAdapter(2017, 1, 1, 9, 0)],
],
yearly: [
[dateAdapter(1998, 1, 1, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
[dateAdapter(2000, 1, 1, 9, 0)],
[dateAdapter(2017, 1, 1, 9, 0)],
],
monthly: {
no: [
[dateAdapter(1998, 1, 1, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
[dateAdapter(2000, 1, 1, 9, 0)],
[dateAdapter(2017, 1, 1, 9, 0)],
],
week: [[dateAdapter(1998, 1, 1, 9, 0), dateAdapter(1998, 1, 1, 9, 0)]],
},
},
);
testOccurrences(
'2 schedules w/ rdates & exdates',
new Calendar({
schedules: [
new Schedule({
rdates: [dateAdapter(1998, 1, 1, 9, 0), dateAdapter(2000, 1, 1, 9, 0)],
exdates: [dateAdapter(1998, 1, 20, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
}),
new Schedule({
rdates: [dateAdapter(1998, 1, 1, 9, 0), dateAdapter(2017, 1, 1, 9, 0)],
exdates: [dateAdapter(2000, 1, 1, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
}),
],
timezone,
}),
[dateAdapter(2000, 1, 1, 9, 0), dateAdapter(2017, 1, 1, 9, 0)],
{
millisecondly: [[dateAdapter(2000, 1, 1, 9, 0)], [dateAdapter(2017, 1, 1, 9, 0)]],
yearly: [[dateAdapter(2000, 1, 1, 9, 0)], [dateAdapter(2017, 1, 1, 9, 0)]],
monthly: {
no: [[dateAdapter(2000, 1, 1, 9, 0)], [dateAdapter(2017, 1, 1, 9, 0)]],
week: [],
},
},
);
testOccurrences(
'3 schedules',
new Calendar({
schedules: [
new Schedule({
rrules: [
// YearlyByMonthAndMonthDay
{
frequency: 'YEARLY',
count: 3,
byMonthOfYear: [1, 3],
byDayOfMonth: [5, 7],
start: dateAdapter(1997, 9, 2, 9),
},
// WeeklyIntervalLarge
{
frequency: 'WEEKLY',
count: 2,
interval: 20,
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
new Schedule({
rrules: [
// DailyByMonthDayAndWeekDay
{
frequency: 'DAILY',
count: 3,
byDayOfMonth: [1, 3],
byDayOfWeek: ['TU', 'TH'],
start: dateAdapter(1997, 9, 2, 9),
},
],
}),
new Schedule({
rdates: [dateAdapter(1998, 1, 1, 9, 0), dateAdapter(2000, 1, 1, 9, 0)],
exdates: [dateAdapter(1998, 1, 20, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
}),
],
timezone,
}),
[
dateAdapter(1997, 9, 2, 9, 0),
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
dateAdapter(1998, 2, 3, 9, 0),
dateAdapter(1998, 3, 3, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
dateAdapter(2000, 1, 1, 9, 0),
],
{
millisecondly: [
[dateAdapter(1997, 9, 2, 9, 0)],
[dateAdapter(1998, 1, 1, 9, 0)],
[dateAdapter(1998, 1, 5, 9, 0)],
[dateAdapter(1998, 1, 7, 9, 0)],
[dateAdapter(1998, 1, 20, 9, 0)],
[dateAdapter(1998, 2, 3, 9, 0)],
[dateAdapter(1998, 3, 3, 9, 0)],
[dateAdapter(1998, 3, 5, 9, 0)],
[dateAdapter(2000, 1, 1, 9, 0)],
],
yearly: [
[dateAdapter(1997, 9, 2, 9, 0)],
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
dateAdapter(1998, 2, 3, 9, 0),
dateAdapter(1998, 3, 3, 9, 0),
dateAdapter(1998, 3, 5, 9, 0),
],
[dateAdapter(2000, 1, 1, 9, 0)],
],
monthly: {
no: [
[dateAdapter(1997, 9, 2, 9, 0)],
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
],
[dateAdapter(1998, 2, 3, 9, 0)],
[dateAdapter(1998, 3, 3, 9, 0), dateAdapter(1998, 3, 5, 9, 0)],
[dateAdapter(2000, 1, 1, 9, 0)],
],
week: [
[
dateAdapter(1998, 1, 1, 9, 0),
dateAdapter(1998, 1, 5, 9, 0),
dateAdapter(1998, 1, 7, 9, 0),
dateAdapter(1998, 1, 20, 9, 0),
],
[dateAdapter(1998, 2, 3, 9, 0)],
],
},
},
);
it('retains generators', () => {
// YearlyByMonthAndMonthDay
const rule1 = new Rule(
{
frequency: 'YEARLY',
count: 3,
byMonthOfYear: [1, 3],
byDayOfMonth: [5, 7],
start: dateAdapter(1997, 9, 2, 9),
},
{ data: 'rule 1' },
);
const schedule1 = new Schedule({
rrules: [rule1],
data: 'schedule 1',
timezone,
});
const dates1 = new Dates({
dates: [dateAdapter(1998, 1, 1, 9, 0), dateAdapter(2000, 1, 1, 9, 0)],
data: 'dates 1',
timezone,
});
const schedule2 = new Schedule({
rdates: dates1,
exdates: [dateAdapter(1998, 1, 20, 9, 0), dateAdapter(1998, 1, 1, 9, 0)],
data: 'schedule 2',
timezone,
});
const calendar = new Calendar({
schedules: [schedule1, schedule2],
timezone,
data: 'calendar 1',
});
let adapter = calendar.occurrences({ start: dateAdapter(), take: 1 }).toArray()[0];
// expect(adapter.generators).toEqual([
// calendar,
// schedule1,
// rule1,
// ])
adapter = calendar
.occurrences({ start: dateAdapter(2000, 1, 1, 9, 0), take: 1 })
.toArray()[0];
expect(adapter.generators).toEqual([calendar, schedule2, dates1]);
});
});
});
});
});
}
|
ec8a7592acc030a419e9c4a76aeffd5d5de49bef
|
TypeScript
|
pandapirate/mean-template
|
/server/routes/transaction.ts
| 2.5625
| 3
|
import * as express from 'express';
import { Request, Response } from 'express';
import { Transaction } from '../models/transaction';
const router = express.Router();
router.get('/api/todo/:name', (req: Request, res: Response) => {
const name = req.params.name;
const greeting = { greeting: `Hello, ${ name }` };
return res.send(greeting);
});
router.get('/api/transactions', async (req: Request, res: Response) => {
const trans = await Transaction.find({});
console.log(trans);
return res.status(200).send(trans);
});
router.post('/api/transaction', async (req: Request, res: Response) => {
const trans = Transaction.build({
type: "Income",
description: "Tempus",
amount: 3200,
eventDate: new Date("2021-07-31")
});
await trans.save();
return res.status(201).send(trans);
});
export {router as transactionRouter};
|
97a39071d7f350fd0d876f215786223852a1220f
|
TypeScript
|
adobe/griffon-toolkit
|
/packages/core/src/filterKit.ts
| 2.671875
| 3
|
/*
Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import {
tryCatch, pipe, match as rMatch, nth, curry
} from 'ramda';
import { match, combineAll } from './kit';
/**
* Contains utility functions for dealing with Griffon filters.
*
* @namespace filters
*/
const HASH_REGEX = /.*#filters=(.*)/;
/**
* Extracts the filters from the provided url. Returns a filter object.
*
* @function
* @param {string} url Url to decode filters from
* @returns {object} Filter object
*/
const filterFromHash = tryCatch(
pipe(
rMatch(HASH_REGEX),
nth(1),
(a) => atob(a),
JSON.parse
),
() => {
// console.log("Error", e)
}
);
/**
* Takes a filter object and prepares it for a url hash. It gets converted to JSON and base64 encoded.
*
* @function
* @param {object} filters Filter object
* @returns {string}
*/
const filterToHash = (filters) => `filters=${btoa(JSON.stringify(filters))}`;
/**
* Takes a filter object and returns the JMESPath query of the results.
*
* @function
* @param {object} filters Filter object
* @returns {string}
*/
const filterToPath = (filters) => (Object.values(filters).length ? combineAll(Object.values(filters)) : '*');
/**
* A filter object is an object where all the values are valid JMESPath matchers.
* This will take all these values and `&&` them together, so that each must pass for an
* event to be valid.
*/
const filterData = curry(
(filters, data) => (Object.values(filters).length
? match(filterToPath(filters), data)
: data)
);
export {
filterData,
filterFromHash,
filterToHash,
filterToPath
};
|
1b7c2a63f1589ca2a7e23a0a66a131ad53ecdf69
|
TypeScript
|
xlfsummer/mp-painter
|
/src/lib/painter-fill-stroke/linear-gradient.ts
| 2.765625
| 3
|
import { ColorStop } from "../value";
import { PainterGradientPatternOption, PainterGradientPatternStyle } from "./base";
import { PainterElement } from "../painter-element/base";
export interface PainterLinearGradientOption extends PainterGradientPatternOption{
type: "linear-gradient"
colorStops: ColorStop[],
x1: number
y1: number
x2: number
y2: number
}
export class PainterLinearGradientStyle extends PainterGradientPatternStyle {
option: PainterLinearGradientOption
constructor(element: PainterElement, option: PainterLinearGradientOption){
super(element);
this.option = option
}
get style(){
const { ctx, upx2px } = this.painter;
const { x1, x2, y1, y2 } = this.option;
const gradient = ctx.createLinearGradient(
upx2px(this.element.elementX + x1),
upx2px(this.element.elementY + y1),
upx2px(this.element.elementX + x2),
upx2px(this.element.elementY + y2)
);
this.option.colorStops.forEach(stop => {
gradient.addColorStop(stop.offset, stop.color);
});
return gradient;
}
}
|
44587e55cb77d67a094d1bbc4552b704f3e80cfb
|
TypeScript
|
folkies/tunepal-ng
|
/src/app/transcription/Transcriber.worker.ts
| 2.6875
| 3
|
import { expose } from 'comlink';
import Transcriber, { TranscriptionResult } from './transcriber';
import { ITranscriber, PushResult, TranscriptionInitParams } from './transcription';
export class TranscriberImpl implements ITranscriber {
private transcriber: Transcriber;
private signal: Float32Array[];
private currNumSamples: number;
initialize(initParams: TranscriptionInitParams): void {
this.transcriber = new Transcriber(initParams);
this.resetSignal();
}
private resetSignal() {
this.signal = [];
this.currNumSamples = 0;
}
private mergeSignal() {
let length = this.transcriber.numInputSamples;
let signal = new Float32Array(length);
let currNumSamples = 0;
for (let buffer of this.signal) {
let newNumSamples = currNumSamples + buffer.length;
if (newNumSamples <= length) {
signal.set(buffer, currNumSamples);
}
else {
signal.set(buffer.subarray(0, length - currNumSamples), currNumSamples);
}
currNumSamples = newNumSamples;
}
return signal;
}
transcribe(signal?: Float32Array, midi: boolean = false): TranscriptionResult {
let theSignal = signal ? signal : this.mergeSignal();
let transcription = this.transcriber.transcribe(theSignal, midi);
console.log(`Worker: transcription: ${transcription}`);
const resultMsg = {
transcription: transcription,
sampleRate: this.transcriber.outputSampleRate,
numSamples: this.transcriber.numOutputSamples,
};
return resultMsg;
}
pushSignal(signal: Float32Array): PushResult {
this.signal.push(signal);
this.currNumSamples += signal.length;
let largest = Number.MIN_VALUE;
for (let sample of signal) {
if (sample > largest) largest = sample;
}
return {
amplitude: largest,
timeRecorded: this.currNumSamples / this.transcriber.inputSampleRate,
isBufferFull: this.currNumSamples >= this.transcriber.numInputSamples,
};
}
}
const transcriber = new TranscriberImpl();
expose(transcriber);
|
ac8629fb97727209a69155ca84c21832118b2d68
|
TypeScript
|
stutrek/eagle-oss
|
/data/labelPieces.ts
| 3
| 3
|
import { Glass, Piece } from './types';
export function labelPieces(inputPieces: Piece[], glasses: Glass[]) {
const piecesByGlass: Record<string, Piece[]> = {};
const piecesById: Record<string, Piece> = {};
for (const piece of inputPieces) {
piecesById[piece.id] = piece;
if (piece.glass === undefined) {
continue;
}
if (piecesByGlass[piece.glass] === undefined) {
piecesByGlass[piece.glass] = [];
}
piecesByGlass[piece.glass].push(piece);
}
let count = 0;
for (const glass of glasses) {
if (!piecesByGlass[glass.id]) {
continue;
}
piecesByGlass[glass.id] = piecesByGlass[glass.id].map((piece) => {
const newlabel = `${++count}`;
if (piece.label === newlabel) {
return piece;
}
return (piecesById[piece.id] = {
...piece,
label: newlabel,
});
});
}
const pieces = inputPieces.map((piece) => piecesById[piece.id]);
return pieces;
}
|
76869f5a2d6ad1623e783f2e70a89923cbd4c5b9
|
TypeScript
|
sy1117/bookstagram
|
/server/src/users/entities/user.entity.ts
| 2.578125
| 3
|
import { ObjectType, Field } from '@nestjs/graphql';
import {
Entity,
Column,
BeforeInsert,
BeforeUpdate,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import { IsString } from 'class-validator';
import * as bcrypt from 'bcrypt';
import { InternalServerErrorException } from '@nestjs/common';
import { Post } from 'src/post/entities/post.entity';
import { Comment } from 'src/post/entities/comment.entity';
import { Like } from 'src/post/entities/like.entity';
@ObjectType()
@Entity()
export class User {
@PrimaryGeneratedColumn()
@Field(() => Number)
id: number;
@Column({ unique: true })
@Field(() => String)
@IsString()
userId: string;
@Column({ nullable: true })
@Field(() => String)
@IsString()
profileImageURL: string;
@Column({ select: false })
@Field(() => String)
@IsString()
password: string;
@OneToMany((type) => Post, (post: Post) => post.user)
@Field(() => [Post])
posts: Post[];
@OneToMany((type) => Comment, (comment: Comment) => comment.user)
@Field(() => [Comment])
comments: Comment[];
@OneToMany((type) => Like, (like) => like.userId)
@Field(() => [Like])
likes: Like[];
@BeforeInsert()
@BeforeUpdate()
async hashPassword(): Promise<void> {
if (this.password) {
try {
this.password = await bcrypt.hash(this.password, 10);
} catch (error) {
throw new InternalServerErrorException(error);
}
}
}
async checkPassword(password: string): Promise<boolean> {
try {
const ok = await bcrypt.compare(password, this.password);
return ok;
} catch (error) {
throw new InternalServerErrorException(error);
}
}
}
|
af572c9a061ae3b1029dbe9711e83dec968f1eb0
|
TypeScript
|
roziscoding/vscode-reveal
|
/test/browserHelper.jest.ts
| 2.59375
| 3
|
import * as fs from 'fs'
import * as open from 'open'
import * as os from 'os'
import { DEFAULT_CHROME_PATH, getChromePath, openInBrowser } from '../src/BrowserHelper'
import { mocked } from 'ts-jest/utils'
test('TODO again ...', () => {
expect(true).toBe(true)
})
// jest.mock('os');
// jest.mock('fs');
// jest.mock('open')
// const mockedOpen = mocked(open, true)
// test('Should use windows path on windows', () => {
// (fs.statSync as any).mockImplementation((_) => true);
// (os.platform as any).mockImplementation(() => 'win32');
// const path = getChromePath()
// expect(path).toBe(DEFAULT_CHROME_PATH.WINx86)
// })
// test('Should use linux path on linux', () => {
// (fs.statSync as any).mockImplementation((_) => true);
// (os.platform as any).mockImplementation(() => 'linux');
// const path = getChromePath()
// expect(path).toBe(DEFAULT_CHROME_PATH.LINUX)
// })
// test('Should use osx path on darwin', () => {
// (fs.statSync as any).mockImplementation((_) => true);
// (os.platform as any).mockImplementation(() => 'darwin');
// const path = getChromePath()
// expect(path).toBe(DEFAULT_CHROME_PATH.OSX)
// })
// test('Should use headless chrome only when needed', async () => {
// (fs.statSync as any).mockImplementation((_) => true);
// (os.platform as any).mockImplementation(() => 'win32');
// (open as any).mockImplementation(async (url, opts) => { })
// await openInBrowser(DEFAULT_CHROME_PATH.WINx86, "http://theurl")
// expect(mockedOpen.mock.calls.length).toBe(1);
// expect(mockedOpen.mock.calls[0][0]).toBe("http://theurl")
// // TODO : expect(mockedOpen.mock.calls[0][1]).toStrictEqual({ app: DEFAULT_CHROME_PATH.WINx86 })
// await openInBrowser(DEFAULT_CHROME_PATH.WINx86, "http://theurl", true)
// expect(mockedOpen.mock.calls.length).toBe(2);
// expect(mockedOpen.mock.calls[1][0]).toBe("http://theurl")
// // TODO : expect(mockedOpen.mock.calls[1][1]).toStrictEqual({ app: [DEFAULT_CHROME_PATH.WINx86, "--headless"] })
// })
|
ef194a67aaa757e506dcdade5975224ca87fff48
|
TypeScript
|
Sinclair81/Homebridge-Tasmota-TS
|
/src/util/accessories/SwitchAccessory.ts
| 2.65625
| 3
|
import { wait } from "../wait";
let Characteristic: any;
export class SwitchAccessory {
static switchType: string = "switch";
static infoModel: string = "Switch";
public switchService: any;
log: Function;
request: any;
ip: string;
relais: number;
user: string;
password: string;
updateInterval: number;
debugMsgLog: number;
updateTimer: any;
constructor(log: Function,
request: any,
ip: string,
relais: number,
user: string,
password: string,
updateInterval: number,
debugMsgLog: number,
characteristic: any
) {
this.log = log;
this.request = request;
this.ip = ip;
this.relais = relais;
this.user = user;
this.password = password;
this.updateInterval = updateInterval;
this.debugMsgLog = debugMsgLog;
Characteristic = characteristic;
if (this.updateInterval > 0) {
this.switchAutoUpdate();
}
}
//
// Tasmota Switch Service
//
// async getSwitchOn(): Promise<boolean> {
getSwitchOn = async () => {
// Cancel timer if the call came from the Home-App and not from the update interval.
// To avoid duplicate queries at the same time.
if (this.updateInterval > 0) {
clearTimeout(this.updateTimer);
this.updateTimer = 0;
}
let userPasswordString = ((this.user != "none") && (this.password != "none")) ? "user=" + this.user + "&password=" + this.password + "&" : "";
let requestString = "http://" + this.ip + "/cm?" + userPasswordString + "cmnd=Power" + String(this.relais) + " Status";
this.request(requestString, async (error: any, res: { statusCode: number; }, body: string) => {
if (error) {
let errorString = error.toString();
let hosteUnreach = errorString.includes("EHOSTUNREACH");
if (!hosteUnreach) {
this.log(`error: : ${error}`);
}
} else {
if (res.statusCode == 200) {
let obj = JSON.parse(body.toLowerCase());
const on = this.checkReturnJSON(obj);
this.debugLogBool("Switch ?", on);
await wait(1);
this.switchService.updateCharacteristic(
Characteristic.On,
on as boolean
);
if (obj.warning) {
this.log("Warning: " + obj.warning);
}
}
if (this.updateInterval > 0) {
this.switchAutoUpdate();
}
}
}
);
return false;
};
setSwitchOn = async (on: boolean) => {
this.debugLogBool("Set switch to", on);
let onString = on == true ? "On" : "Off";
let userPasswordString = ((this.user != "none") && (this.password != "none")) ? "user=" + this.user + "&password=" + this.password + "&" : "";
let requestString = "http://" + this.ip + "/cm?" + userPasswordString + "cmnd=Power" + String(this.relais) + " " + onString;
this.request(requestString, async (error: any, res: { statusCode: number; }, body: string) => {
if (error) {
this.log(`error: : ${error}`);
} else {
if (res.statusCode == 200) {
let obj = JSON.parse(body.toLowerCase());
const on = this.checkReturnJSON(obj);
this.debugLogBool("Switch ?", on);
await wait(1);
this.switchService.updateCharacteristic(
Characteristic.On,
on as boolean
);
if (obj.warning) {
this.log("Warning: " + obj.warning);
}
}
if (this.updateInterval > 0) {
this.switchAutoUpdate();
}
}
}
);
};
//
// Helper Functions
//
checkReturnJSON(obj: any): boolean {
let on = false;
if (obj.hasOwnProperty('power')){
on = obj.power == "on" ? true : false;
}
if (obj.hasOwnProperty('power1')){
on = obj.power1 == "on" ? true : false;
}
if (obj.hasOwnProperty('power2')){
on = obj.power2 == "on" ? true : false;
}
if (obj.hasOwnProperty('power3')){
on = obj.power3 == "on" ? true : false;
}
if (obj.hasOwnProperty('power4')){
on = obj.power4 == "on" ? true : false;
}
if (obj.hasOwnProperty('power5')){
on = obj.power5 == "on" ? true : false;
}
if (obj.hasOwnProperty('power6')){
on = obj.power6 == "on" ? true : false;
}
if (obj.hasOwnProperty('power7')){
on = obj.power7 == "on" ? true : false;
}
if (obj.hasOwnProperty('power8')){
on = obj.power8 == "on" ? true : false;
}
if (obj.hasOwnProperty('power9')){
on = obj.power9 == "on" ? true : false;
}
return on;
}
debugLogNum(msg: string, num: number) {
if (this.debugMsgLog == 1) {
this.log(msg, num);
}
}
debugLogBool(msg: string, bool: boolean) {
if (this.debugMsgLog == 1) {
this.log(msg, bool);
}
}
switchAutoUpdate() {
this.updateTimer = setTimeout(() => {
this.getSwitchOn();
}, this.updateInterval + Math.floor(Math.random() * 10000));
}
}
|
0e171ec07dc5c556cd71da86a29ab610bea40f74
|
TypeScript
|
ryu1kn/vscode-edit-with-shell
|
/src/test/lib/command-reader.test.ts
| 2.546875
| 3
|
import * as assert from 'assert';
import {any, mockMethods, mockType, verify, when} from '../helper';
import {CommandReader} from '../../lib/command-reader';
import * as vscode from 'vscode';
import {HistoryStore} from '../../lib/history-store';
describe('CommandReader', () => {
it('allows user to pick and modify a past command. Commands shown last one first', async () => {
const historyStore = mockType<HistoryStore>({getAll: () => ['COMMAND_1', 'COMMAND_2']});
const vscodeWindow = mockMethods<typeof vscode.window>(['showInputBox', 'showQuickPick']);
when(vscodeWindow.showQuickPick(
['COMMAND_2', 'COMMAND_1'],
{placeHolder: 'Select a command to reuse or Cancel (Esc) to write a new command'}
)).thenResolve('COMMAND_1');
when(vscodeWindow.showInputBox({
placeHolder: 'Enter a command',
prompt: 'Edit the command if necessary',
value: 'COMMAND_1'
})).thenResolve('COMMAND_FINAL');
const reader = new CommandReader(historyStore, vscodeWindow);
const command = await reader.read();
assert.deepStrictEqual(command, 'COMMAND_FINAL');
});
it('shows inputBox right away if there is no commands recorded in the history', async () => {
const vscodeWindow = mockMethods<typeof vscode.window>(['showInputBox', 'showQuickPick']);
when(vscodeWindow.showInputBox({
placeHolder: 'Enter a command',
prompt: 'No history available yet'
})).thenResolve('COMMAND');
const historyStore = mockType<HistoryStore>({getAll: () => []});
const reader = new CommandReader(historyStore, vscodeWindow);
const command = await reader.read();
assert.deepStrictEqual(command, 'COMMAND');
verify(vscodeWindow.showQuickPick(any()), {times: 0, ignoreExtraArgs: true});
});
it('shows inputBox if history command picker is dismissed', async () => {
const vscodeWindow = mockMethods<typeof vscode.window>(['showInputBox'], {
showQuickPick: () => Promise.resolve()
});
when(vscodeWindow.showInputBox({placeHolder: 'Enter a command'})).thenResolve('COMMAND');
const historyStore = mockType<HistoryStore>({getAll: () => ['COMMAND_1', 'COMMAND_2']});
const reader = new CommandReader(historyStore, vscodeWindow);
const command = await reader.read();
assert.deepStrictEqual(command, 'COMMAND');
});
});
|
538b9abcadbde8975b499b86e3116dd79d975c0c
|
TypeScript
|
einfachiota/explorer
|
/api/src/models/clients/hornet/IGetTrytesRequest.ts
| 2.609375
| 3
|
export interface IGetTrytesRequest {
/**
* The list of hashes to get.
*/
hashes: string[];
}
|
1f0ace5454d848d5e5d2dc4108eb6e97e5d81d24
|
TypeScript
|
jinlii/form-example
|
/src/app/app.component.ts
| 2.703125
| 3
|
import { Component } from '@angular/core';
import { QuestionService } from './question.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [QuestionService]
})
export class AppComponent {
title = 'form-example';
questions: any[];
constructor(service: QuestionService) {
this.questions = service.getQuestions();
}
printLoop() {
for (let i = 0; i < 10 ; i++) {
setTimeout(function() { console.log(i); }, 100 * i);
}
}
theCityThatAlwaysSleeps() {
let getCity;
if (true) {
let city = "Seattle";
getCity = function() {
return city;
}
}
return getCity(); // returns null though in console
}
}
|
7fede3efd6879fea30faaf3718a337ef98727128
|
TypeScript
|
marius15ru/HEF
|
/HEF-API/ClientApp/src/app/shared/enums.ts
| 2.546875
| 3
|
export enum DataOperation {
Undefined = 0,
Insert = 1,
Read = 2,
Update = 3,
Delete = 4,
List = 5,
ListByPlant = 6,
ListByUser = 7,
ListByJob = 8,
}
export enum Role {
'Óskilgreint' = 0,
'Verkaðili' = 1,
'Stjórnandi' = 2,
}
export enum UserStatus {
'Óskilgreint' = 0,
'Tiltæk/ur' = 1,
'Ótiltæk/ur' = 2,
}
export enum JobStatus {
'Óskilgreint' = 0,
'Óúthlutað' = 1,
'Úthlutað' = 2,
'Í vinnslu' = 3,
'Í bið' = 4,
'Lokið' = 5,
}
export enum MeasurementType {
'Óskilgreint' = 0,
'Celsíus' = 1,
'Lítrar' = 2,
'Þrýstingur(bar)' = 3,
'Metrar' = 4,
'Lítrar á sekúndu' = 5,
'%' = 6,
'ph-gildi' = 7
}
export enum PlantType {
Undefined = 0,
Water = 1,
Data = 2,
Heat = 3,
Drainage = 4
}
export enum Recurring {
'Óskilgreint' = 0,
'Vikulega' = 1,
'Tveggja vikna fresti' = 2,
'Mánaðarlega' = 3,
'Tveggja mánaða fresti' = 4,
'Þriggja mánaða fresti' = 5,
'Hálfs árs fresti' = 6,
'Árlega' = 7,
'Tveggja ára fresti' = 8,
'Þriggja ára fresti' = 9,
'Fimm ára fresti' = 10,
'Tíu ára fresti' = 11
}
export namespace Recurring {
export function values() {
return Object.keys(Recurring).filter(
(type) => isNaN(<any>type) && type !== 'values'
);
}
}
export enum SubJobTask {
'Óskilgreint' = 0,
'Þrífa' = 1,
'Ryksuga' = 2,
'Niðurdráttur' = 3,
'Mæla olíu' = 4,
'Mæla hitastig' = 5,
'Mæla hæð' = 6,
'Skúra' = 7,
'Athuga mótor' = 8,
'Ath Seirumagn' = 9,
'Ath virkni síu' = 10,
'Mæla sýrustig' = 11,
'Fjarlægja steina' = 12,
'Mæla rakastig' = 13
}
|
5356ea80bcab6b5559389f09c059d49f476a6107
|
TypeScript
|
subgan82/calcite-app-components
|
/src/components/utils/dom.ts
| 2.921875
| 3
|
export function getElementDir(el: HTMLElement) {
return getElementProp(el, "dir", "ltr");
}
export function getElementProp(el: HTMLElement, prop, value) {
const closestWithProp = el.closest(`[${prop}]`);
return closestWithProp ? closestWithProp.getAttribute(prop) : value;
}
export interface CalciteFocusableElement extends HTMLElement {
setFocus?: () => void;
}
export function focusElement(el: CalciteFocusableElement): void {
if (!el) {
return;
}
"setFocus" in el && typeof el.setFocus === "function" ? el.setFocus() : el.focus();
}
|
975db265d6ec847f4a3ad71733ee278290911f61
|
TypeScript
|
searchfe/ts2php
|
/src/features/json.ts
| 2.671875
| 3
|
/**
* @file json
* @author cxtom(cxtom2008@gmail.com)
*/
import {
EmitHint,
CallExpression,
createLiteral,
createNodeArray,
ListFormat,
isPropertyAccessExpression,
isIdentifier,
isCallExpression
} from 'byots';
import {
createDiagnostic
} from '../utilities/error';
const methods = {
stringify(node: CallExpression, {emitExpressionList, writePunctuation}) {
writePunctuation('json_encode');
const args = createNodeArray([
node.arguments[0],
// JSON_UNESCAPED_UNICODE
createLiteral(256)
]);
emitExpressionList(node, args, ListFormat.CallExpressionArguments);
},
parse(node: CallExpression, {emitExpressionList, writePunctuation}) {
writePunctuation('json_decode');
const args = createNodeArray([
node.arguments[0],
createLiteral(true)
]);
emitExpressionList(node, args, ListFormat.CallExpressionArguments);
}
};
export default {
emit(hint, node, state) {
const expNode = node.expression;
let func;
const {helpers} = state
if (
hint === EmitHint.Expression
&& isCallExpression(node)
&& isPropertyAccessExpression(expNode)
&& isIdentifier(expNode.expression)
&& expNode.expression.escapedText === 'JSON'
&& (func = methods[helpers.getTextOfNode(expNode.name)])
) {
if (node.arguments.length <= 1) {
return func(node, helpers);
}
state.errors.push(createDiagnostic(
node, state.sourceFile,
`JSON.${helpers.getTextOfNode(expNode.name)} only support 1 argument.`
));
}
return false;
}
};
|
87a95328d0c44619df034e72832aea6ddd6d277b
|
TypeScript
|
Viktor286/code-samples
|
/src/Engineering/Arrays/1502-can-make-arithmetic-progression-from-sequence.ts
| 3.8125
| 4
|
// https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
// A sequence of numbers is called an arithmetic progression
// if the difference between any two consecutive elements is the same.
// Given an array of numbers arr, return true if the array can be
// rearranged to form an arithmetic progression. Otherwise, return false.
function canMakeArithmeticProgression(arr: number[]) {
if (arr.length <= 2) {
return true;
}
let max = -Infinity;
let min = Infinity;
const seen = new Map();
for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) max = arr[i];
if (min > arr[i]) min = arr[i];
seen.set(arr[i], true);
}
const step = (max - min) / (arr.length - 1);
let n = min;
for (let i = 0; i < arr.length - 1; i++) {
if (!seen.has(n + step)) {
return false;
}
n += step;
}
return true;
}
function canMakeArithmeticProgressionTwo(arr: number[]) {
const sorted = arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length - 2; i++) {
if (arr[i + 1] - arr[i] != arr[i + 2] - arr[i + 1]) {
return false;
}
}
return true;
}
|
375135ecfc76cc34ea3a7adcacabd7947b718aaa
|
TypeScript
|
miguelyoobic95/ngIfModalBug
|
/design-system/stencil/src/utils/pipes/base.ts
| 2.6875
| 3
|
export class Pipe<A, C> {
transform(value: A, options: any = {}): C {
return null;
}
}
|
c831b557aa30447d6ee39250089170241e485e82
|
TypeScript
|
shawnrpnus/iSkill
|
/frontend/src/actions/roleAction.ts
| 2.609375
| 3
|
import axios from "axios";
import { GET_ALL_ROLES } from "./types";
export const getAllRoles = () => {
return (dispatch: any) => {
axios.get("/api/role/all").then(response => {
dispatch(getAllRolesSuccess(response.data))
console.log(response.data);
}).catch(err => {
console.log(err);
alert("Error fetching all roles");
console.log(err.response);
})
}
}
const getAllRolesSuccess = (roles: any) => ({
type: GET_ALL_ROLES,
roles: roles
})
|
1b36f0f80e2abd3d90f7c62921a686534944fc45
|
TypeScript
|
RubenDeFreyne/Kolveniershof-web
|
/src/app/models/workdayTemplate.model.ts
| 2.578125
| 3
|
import {User} from './user.model';
import {BusUnit} from './busUnit.model';
import {ActivityUnit} from './activityUnit.model';
import {LunchUnit} from './lunchUnit.model';
export class WorkdayTemplate {
id: string;
templateName: string;
weekNumber: number;
dayNumber: number;
dayActivities: ActivityUnit[];
daycareMentors: User[];
morningBusses: BusUnit[];
amActivities: ActivityUnit[];
lunch: LunchUnit;
pmActivities: ActivityUnit[];
eveningBusses: BusUnit[];
holiday: boolean;
constructor(
templateName: string,
weekNumber: number,
dayNumber: number,
dayActivities: ActivityUnit[],
daycareMentors: User[],
morningBusses: BusUnit[],
amActivities: ActivityUnit[],
lunch: LunchUnit,
pmActivities: ActivityUnit[],
eveningBusses: BusUnit[],
holiday: boolean
) {
this.templateName = templateName;
this.weekNumber = weekNumber;
this.dayNumber = dayNumber;
this.dayActivities = dayActivities;
this.daycareMentors = daycareMentors;
this.morningBusses = morningBusses;
this.amActivities = amActivities;
this.lunch = lunch;
this.pmActivities = pmActivities;
this.eveningBusses = eveningBusses;
this.holiday = holiday;
}
static fromJSON(json: any): WorkdayTemplate {
if ((json === undefined) || (json === null)) {
return null;
}
const workdayTemplate = new WorkdayTemplate(
json.templateName,
json.weekNumber,
json.dayNumber,
json.dayActivities.map(ActivityUnit.fromJSON),
json.daycareMentors.map(User.fromJSON),
json.morningBusses.map(BusUnit.fromJSON),
json.amActivities.map(ActivityUnit.fromJSON),
LunchUnit.fromJSON(json.lunch),
json.pmActivities.map(ActivityUnit.fromJSON),
json.eveningBusses.map(BusUnit.fromJSON),
json.holiday
);
workdayTemplate.id = json._id;
return workdayTemplate;
}
toJSON() {
return {
_id: this.id,
templateName: this.templateName,
weekNumber: this.weekNumber,
dayNumber: this.dayNumber,
dayActivities: this.dayActivities.map(activityUnit => activityUnit.toJSON()),
morningBusses: this.morningBusses.map(busUnit => busUnit.toJSON()),
amActivities: this.amActivities.map(activityUnit => activityUnit.toJSON()),
lunch: this.lunch.toJSON(),
pmActivities: this.pmActivities.map(activityUnit => activityUnit.toJSON()),
eveningBusses: this.eveningBusses.map(busUnit => busUnit.toJSON()),
holiday: this.holiday
};
}
}
|
8b1ca883a0c18dc56b19e22da616d4a02c8babf6
|
TypeScript
|
RichardGreen-IS2/signoz
|
/frontend/src/lib/logs/fieldSearch.ts
| 2.515625
| 3
|
export const fieldSearchFilter = (
searchSpace = '',
currentValue = '',
): boolean => {
if (!currentValue || !searchSpace) {
return true;
}
return searchSpace.toLowerCase().indexOf(currentValue.toLowerCase()) !== -1;
};
|
09f2fe612d82dfe72dbbd3d476399a2448fcaf61
|
TypeScript
|
ZacharyKamerling/rts_client
|
/rts_client/js/app/interaction/build_order.ts
| 2.546875
| 3
|
module Interaction.BuildOrder {
export class BeingIssued implements Interaction.Core.Control {
width: number;
height: number;
type: number;
imgs: string[];
constructor(width: number, height: number, type: number, imgs: string[]) {
this.width = width;
this.height = height;
this.type = type;
this.imgs = imgs;
}
}
export function issue(game: Game, build_type: number) {
let selected = Interaction.SelectingUnits.selectedUnitIDs(game);
let input = game.inputState;
let width = game.unitDrawer.width();
let height = game.unitDrawer.height();
game.chef.put8(Interaction.Core.ServerMessage.Build);
game.chef.putU32(game.orderID++);
game.chef.putU16(build_type);
let xy = game.gameXY();
game.chef.putF64(xy.x);
game.chef.putF64(xy.y);
if (input.shiftDown()) {
game.chef.put8(Interaction.Core.QueueOrder.Append);
}
else {
game.chef.put8(Interaction.Core.QueueOrder.Replace);
}
for (let i = 0; i < selected.length; i++) {
game.chef.putU16(selected[i]);
}
game.connection.send(game.chef.done());
}
}
|
ab49a4f185cf908ea260231beea15152e6e139ef
|
TypeScript
|
maroon775/node-nest-learn
|
/parrot-wings/src/transactions/entities/transactions.entity.ts
| 2.515625
| 3
|
import {
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { UsersEntity } from '../../users/entities/users.entity';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
@Entity('transactions')
export class TransactionsEntity {
@ApiProperty()
@PrimaryGeneratedColumn()
id: number;
@ApiProperty()
@CreateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
})
created_at: Date;
@ApiProperty()
@UpdateDateColumn({
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updated_at: Date;
@ApiProperty()
@Column({ type: 'decimal', precision: 22, scale: 2, default: 0.0 })
amount: number;
@ApiProperty()
@Column({ type: 'decimal', precision: 22, scale: 2, default: 0.0 })
balance: number;
@ApiPropertyOptional()
@Column({ nullable: true })
description?: string;
@ApiProperty()
@Column()
userId: number;
@ManyToOne(() => UsersEntity, (userEntity) => userEntity.transactions)
user: UsersEntity;
@OneToOne(() => TransactionsEntity)
@JoinColumn()
parentTransaction: TransactionsEntity;
}
|
2d1fb8cec0b92682005a1c7f6f9bd69ac2367bc3
|
TypeScript
|
bradenhs/fnx
|
/src/api/oneOf.ts
| 3.046875
| 3
|
// tslint:disable
import { OneOfDescriptor, descriptionTypes } from '../core'
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B>(a: A, b: B): A | B
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B, C>(a: A, b: B, c: C): A | B | C
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B, C, D>(a: A, b: B, c: C, d: D): A | B | C | D
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B, C, D, E>(a: A, b: B, c: C, d: D, e: E): A | B | C | D | E
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B, C, D, E, F>(a: A, b: B, c: C, d: D, e: E, f: F): A | B | C | D | E | F
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf<A, B, C, D, E, F, G>(a: A, b: B, c: C, d: D, e: E, f: F, g: G): A | B | C | D | E | F | G
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf(...kinds: any[]): any
/**
* Describes an item in the state tree that can be one of multiple types.
* https://fnx.js.org/docs/api/oneOf.html
*/
export function oneOf(...kinds: any[]) {
if (kinds.length < 2) {
throw new Error()
}
kinds.forEach(kind => {
if (typeof kind !== 'object') {
throw new Error()
}
switch ((kind as any).type) {
case descriptionTypes.arrayOf:
case descriptionTypes.boolean:
case descriptionTypes.complex:
case descriptionTypes.mapOf:
case descriptionTypes.number:
case descriptionTypes.object:
case descriptionTypes.oneOf:
case descriptionTypes.string:
break
default:
throw new Error()
}
})
const descriptor: OneOfDescriptor = {
type: descriptionTypes.oneOf, kinds,
readonly: false, optional: false,
}
return descriptor
}
|
7c642bb2d5e42313670667a4bb5858c4c395ebd7
|
TypeScript
|
WaldiirNeto/-project_base
|
/src/controllers/user/user.service.ts
| 2.625
| 3
|
import { MessageEnum } from 'enums/message.enum';
import { Injectable, InternalServerErrorException, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from 'repository/user.repository';
import { FindUsersQueryDto, UpdateUserDto, UserDto } from '@dto';
import { UserEntity } from '@entity';
import { UserRole } from '@enums';
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository) { }
public users: UserDto[] = [];
async createAdminUser(userDto: UserDto): Promise<UserEntity> {
if (userDto.password != userDto.passwordConfirmation) {
throw new UnprocessableEntityException(MessageEnum.PASSWORD_MATCH);
} else {
return this.userRepository.createUser(userDto, UserRole.ADMIN);
}
}
async findUserById(userId: string): Promise<UserEntity> {
const user = await this.userRepository.findOne(userId, {
select: ['name', 'role', 'id'],
});
if (!user) throw new NotFoundException(MessageEnum.USER_NOT_FOUND);
return user;
}
async updateUser(updateUserDto: UpdateUserDto, id: string): Promise<UserEntity> {
const user = await this.findUserById(id);
const { name, email, role, status } = updateUserDto;
user.name = name ? name : user.name;
user.email = email ? email : user.email;
user.role = role ? role : user.role;
user.status = status === undefined ? user.status : status;
try {
await user.save();
return user;
} catch (error) {
throw new InternalServerErrorException(
MessageEnum.EXCEPTION_DATABASE,
);
}
}
async findUsers(
queryDto: FindUsersQueryDto,
): Promise<{ users: UserEntity[]; total: number }> {
const users = await this.userRepository.findUsers(queryDto);
return users;
}
async deleteUser(userId: string) {
const result = await this.userRepository.delete({ id: userId });
if (result.affected === 0) {
throw new NotFoundException(
'Não foi encontrado um usuário com o ID informado',
);
}
}
}
|
38eaf97a33f695fce9437d927c9005b99f052a26
|
TypeScript
|
scoopapa/DH
|
/data/mods/spookyhalloweenfuntimes/items.ts
| 2.546875
| 3
|
export const Items: {[itemid: string]: ModdedItemData} = {
cursedportrait: {
name: "Cursed Portrait",
spritenum: 385,
fling: {
basePower: 70,
},
onDamagingHitOrder: 1,
onDamagingHit(damage, target, source, move) {
if (!target.hp) {
if (target.hasType('Ghost')) source.addVolatile('curse');
// if (target.species.baseSpecies === 'Gardevoir') target.formeChange('Possessevoir', this.effect, true);
// this will look like Primal Reversion so I would need to change it
}
},
num: -1,
gen: 8,
desc: "A Ghost-type holder curses the attacker when it faints.",
},
drampaniteaged: {
name: "Drampanite-Aged",
spritenum: 586,
megaStone: "Drampa-Mega-Aged",
megaEvolves: "Drampa",
itemUser: ["Drampa"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -2,
gen: 8,
desc: "If held by a Drampa, this item allows it to Mega Evolve in battle.",
},
drampaniteuntimely: {
name: "Drampanite-Untimely",
spritenum: 586,
megaStone: "Drampa-Mega-Untimely",
megaEvolves: "Drampa",
itemUser: ["Drampa"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -3,
gen: 8,
desc: "If held by a Drampa, this item allows it to Mega Evolve in battle.",
},
hatofdisguise: {
name: "Hat of Disguise",
spritenum: 385,
fling: {
basePower: 70,
},
onBeforeSwitchIn(pokemon) {
if (pokemon.ability === 'illusion') return;
pokemon.illusion = null;
let i;
for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) {
if (!pokemon.side.pokemon[i]) continue;
if (!pokemon.side.pokemon[i].fainted) break;
}
if (!pokemon.side.pokemon[i]) return;
if (pokemon === pokemon.side.pokemon[i]) return;
pokemon.illusion = pokemon.side.pokemon[i];
pokemon.setAbility('illusion');
},
// some of effect hard-coded into Illusion
num: -4,
gen: 8,
desc: "The holder's Ability is Illusion. Consumed when the Illusion is broken.",
},
bloonketcostume: {
name: "Bloonket Costume",
spritenum: 385,
fling: {
basePower: 10,
},
/*
onStart(pokemon) {
if (!pokemon.illusion) {
const details = pokemon.species.name + (pokemon.level === 100 ? '' : ', L' + pokemon.level) +
(pokemon.gender === '' ? '' : ', ' + pokemon.gender) + (pokemon.set.shiny ? ', shiny' : '');
this.add('replace', pokemon, details);
}
},
*/
// some of effect hard-coded into Illusion and some into Team Preview rule
desc: "At team preview, the holder is disguised as Bloonket!",
num: -5,
gen: 8,
},
ghostsheet: {
name: "Ghost Sheet",
spritenum: 385,
fling: {
basePower: 10,
},
onStart(pokemon) {
if (pokemon.getTypes().join() !== 'Ghost' && pokemon.setType('Ghost')) {
this.add('-start', pokemon, 'typechange', 'Ghost');
}
},
onEnd(pokemon) {
if (pokemon.getTypes().join() !== pokemon.baseSpecies.types.join() && pokemon.setType(pokemon.baseSpecies.types)) {
//this.add('-end', pokemon, 'typechange', '[silent]');
this.add('-start', pokemon, 'typechange', pokemon.getTypes(true).join('/'), '[silent]');
}
},
onTakeItem(item, pokemon, source) {
if (pokemon.getTypes().join() !== pokemon.baseSpecies.types.join() && pokemon.setType(pokemon.baseSpecies.types)) {
//this.add('-end', pokemon, 'typechange', '[silent]');
this.add('-start', pokemon, 'typechange', pokemon.getTypes(true).join('/'), '[silent]');
}
return true;
},
desc: "The holder's type is pure Ghost.",
num: -6,
gen: 8,
},
trickortreatbag: {
name: "Trick-or-Treat Bag",
spritenum: 385,
fling: {
basePower: 10,
},
onStart(pokemon) {
if (pokemon.hp === pokemon.maxhp) return;
let activated = 0;
this.add('-message', `${pokemon.illusion ? pokemon.illusion.name : pokemon.name}: Boo!`);
for (const target of pokemon.side.foe.active) {
if (!target || target.fainted) continue;
let scaredThisGuy = false;
for (const moveSlot of ((pokemon.illusion && pokemon.illusion.moveSlots) ? pokemon.illusion.moveSlots : pokemon.moveSlots)) {
if (scaredThisGuy === true) continue;
const move = this.dex.getMove(moveSlot.move);
if (move.category === 'Status') continue;
const moveType = move.id === 'hiddenpower' ? target.hpType : move.type;
if (
this.dex.getImmunity(moveType, target) && this.dex.getEffectiveness(moveType, target) > 0
) {
scaredThisGuy = true;
continue;
}
}
if (scaredThisGuy === true) {
this.add('-message', `${target.illusion ? target.illusion.name : target.name}: Eeeek!`);
activated++;
}
}
this.add('-message', `...`);
if (activated) {
this.add('-message', `${pokemon.illusion ? pokemon.illusion.name : pokemon.name} got some candy!`);
this.heal(pokemon.baseMaxhp * 0.25 * activated);
} else {
this.add('-message', `It wasn't that scary, so nothing happened.`);
}
},
desc: "On entry, the holder scares the target to restore HP.",
num: -7,
gen: 8,
},
nightgoggles: {
name: "Night Goggles",
spritenum: 604,
fling: {
basePower: 80,
},
onStart(pokemon) {
if (pokemon.volatiles['choicelock']) {
this.debug('removing choicelock: ' + pokemon.volatiles['choicelock']);
}
pokemon.removeVolatile('choicelock');
},
onModifyMove(move, pokemon) {
pokemon.addVolatile('choicelock');
},
onTryHit(target, source, move) {
if (target !== source && move.type === 'Ghost' && move.category !== 'Status') {
this.add('-immune', target, '[from] item: Night Goggles');
return null;
}
},
isChoice: true,
desc: "The holder is immune to Ghost but can only use the first move it selects.",
num: -8,
gen: 8,
},
eucalyptuspatch: {
name: "Eucalyptus Patch",
spritenum: 292,
fling: {
basePower: 10,
},
onModifyMove(move) {
if (!move || !move.flags['contact'] || move.target === 'self' || move.type !== 'Grass') return;
if (!move.secondaries) {
move.secondaries = [];
}
move.secondaries.push({
chance: 100,
volatileStatus: 'yawn',
});
},
onAnyHit(target, source, move) {
if (source && source !== target && source === this.effectData.target && move && move.flags['contact'] && move.type === 'Grass' && source.useItem()) {
target.addVolatile('yawn');
}
},
desc: "Inflicts drowsiness when using a Grass-type contact move (consumed).",
num: -9,
gen: 8,
},
crocs: {
name: "Crocs",
spritenum: 715,
fling: {
basePower: 10,
},
desc: "Makes the holder twice as vulnerable to hazards.",
num: -10,
gen: 8,
// implemented in moves.ts
},
swapcauldron: {
name: "Swap Cauldron",
spritenum: 715,
fling: {
basePower: 80,
},
onSwitchIn(pokemon) {
if (!this.field.addPseudoWeather('swapcauldron')) return; // awkwardly limiting to one activation per turn (sorry)
this.useMove('trick', pokemon);
},
condition: {
duration: 1,
},
desc: "Swaps with the target's item on entry!",
num: -11,
gen: 8,
},
thickclub: {
name: "Thick Club",
spritenum: 491,
fling: {
basePower: 90,
},
onModifyAtkPriority: 1,
onModifyAtk(atk, pokemon) {
if (pokemon.baseSpecies.baseSpecies === 'Cubone' || pokemon.baseSpecies.baseSpecies === 'Marowak' || pokemon.baseSpecies.baseSpecies === 'Resurrectric') {
return this.chainModify(2);
}
},
desc: "If held by Cubone, Marowak or Resurrectric, its Attack is doubled.",
itemUser: ["Resurrectric", "Marowak", "Cubone"],
num: 258,
gen: 2,
},
chandelite: {
name: "Chandelite",
spritenum: 578,
megaStone: "Chandelure-Mega",
megaEvolves: "Chandelure",
itemUser: ["Chandelure"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -12,
gen: 8,
desc: "If held by a Chandelure, this item allows it to Mega Evolve in battle.",
},
mismaginite: {
name: "Mismaginite",
spritenum: 578,
megaStone: "Mismagius-Mega",
megaEvolves: "Mismagius",
itemUser: ["Mismagius"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -13,
gen: 8,
desc: "If held by a Mismagius, this item allows it to Mega Evolve in battle.",
},
noivernite: {
name: "Noivernite",
spritenum: 578,
megaStone: "Noivern-Mega",
megaEvolves: "Noivern",
itemUser: ["Noivern"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -14,
gen: 8,
desc: "If held by a Noivern, this item allows it to Mega Evolve in battle.",
},
mightyenite: {
name: "Mightyenite",
spritenum: 578,
megaStone: "Mightyena-Mega",
megaEvolves: "Mightyena",
itemUser: ["Mightyena"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -15,
gen: 8,
desc: "If held by a Mightyena, this item allows it to Mega Evolve in battle.",
},
delphite: {
name: "Delphite",
spritenum: 578,
megaStone: "Delphox-Mega",
megaEvolves: "Delphox",
itemUser: ["Delphox"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -16,
gen: 8,
desc: "If held by a Delphox, this item allows it to Mega Evolve in battle.",
},
obstagoonite: {
name: "Obstagoonite",
spritenum: 578,
megaStone: "Obstagoon-Mega",
megaEvolves: "Obstagoon",
itemUser: ["Obstagoon"],
onTakeItem(item, source) {
if (item.megaEvolves === source.baseSpecies.baseSpecies) return false;
return true;
},
num: -17,
gen: 8,
desc: "If held by an Obstagoon, this item allows it to Mega Evolve in battle.",
},
};
|
708f395c5f4d3d2b8de048072f18f588811291ba
|
TypeScript
|
manuelnaranjo/aws-sdk-typescript
|
/output/typings/aws-polly.d.ts
| 2.515625
| 3
|
// Type definitions for aws-sdk - Amazon Polly
// Project: https://github.com/aws/aws-sdk-js
// Definitions by: https://github.com/ingenieux/aws-sdk-typescript
// GENERATED CODE - DO NOT EDIT
// COMMENTED <reference path="./aws-sdk.d.ts" />
declare module "aws-sdk" {
/**
* apiVersion: 2016-06-10
* endpointPrefix: polly
* serviceAbbreviation:
* signatureVersion: v4
* protocol: rest-json
*
* Amazon Polly is a web service that makes it easy to synthesize speech from text.
The Amazon Polly service provides API operations for synthesizing high-quality
speech from plain text and Speech Synthesis Markup Language (SSML), along with
managing pronunciations lexicons that enable you to get the best results for
your application domain.
*
*/
export class Polly extends Service {
constructor(options?: any);
endpoint: Endpoint;
/**
* Deletes the specified pronunciation lexicon stored in an AWS Region. A lexicon
which has been deleted is not available for speech synthesis, nor is it possible
to retrieve it using either the GetLexicon or ListLexicon APIs.
For more information, see Managing Lexicons
[http://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html].
*
* @error LexiconNotFoundException
* @error ServiceFailureException
*/
deleteLexicon(params: Polly.DeleteLexiconInput, callback?: (err: Polly.LexiconNotFoundException|Polly.ServiceFailureException|any, data: Polly.DeleteLexiconOutput|any) => void): Request<Polly.DeleteLexiconOutput|any,Polly.LexiconNotFoundException|Polly.ServiceFailureException|any>;
/**
* Returns the list of voices that are available for use when requesting speech
synthesis. Each voice speaks a specified language, is either male or female, and
is identified by an ID, which is the ASCII version of the voice name.
When synthesizing speech ( SynthesizeSpeech ), you provide the voice ID for the
voice you want from the list of voices returned by DescribeVoices.
For example, you want your news reader application to read news in a specific
language, but giving a user the option to choose the voice. Using the
DescribeVoices operation you can provide the user with a list of available
voices to select from.
You can optionally specify a language code to filter the available voices. For
example, if you specify en-US, the operation returns a list of all available US
English voices.
This operation requires permissions to perform the polly:DescribeVoices action.
*
* @error InvalidNextTokenException
* @error ServiceFailureException
*/
describeVoices(params: Polly.DescribeVoicesInput, callback?: (err: Polly.InvalidNextTokenException|Polly.ServiceFailureException|any, data: Polly.DescribeVoicesOutput|any) => void): Request<Polly.DescribeVoicesOutput|any,Polly.InvalidNextTokenException|Polly.ServiceFailureException|any>;
/**
* Returns the content of the specified pronunciation lexicon stored in an AWS
Region. For more information, see Managing Lexicons
[http://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html].
*
* @error LexiconNotFoundException
* @error ServiceFailureException
*/
getLexicon(params: Polly.GetLexiconInput, callback?: (err: Polly.LexiconNotFoundException|Polly.ServiceFailureException|any, data: Polly.GetLexiconOutput|any) => void): Request<Polly.GetLexiconOutput|any,Polly.LexiconNotFoundException|Polly.ServiceFailureException|any>;
/**
* Returns a list of pronunciation lexicons stored in an AWS Region. For more
information, see Managing Lexicons
[http://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html].
*
* @error InvalidNextTokenException
* @error ServiceFailureException
*/
listLexicons(params: Polly.ListLexiconsInput, callback?: (err: Polly.InvalidNextTokenException|Polly.ServiceFailureException|any, data: Polly.ListLexiconsOutput|any) => void): Request<Polly.ListLexiconsOutput|any,Polly.InvalidNextTokenException|Polly.ServiceFailureException|any>;
/**
* Stores a pronunciation lexicon in an AWS Region. If a lexicon with the same name
already exists in the region, it is overwritten by the new lexicon. Lexicon
operations have eventual consistency, therefore, it might take some time before
the lexicon is available to the SynthesizeSpeech operation.
For more information, see Managing Lexicons
[http://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html].
*
* @error InvalidLexiconException
* @error UnsupportedPlsAlphabetException
* @error UnsupportedPlsLanguageException
* @error LexiconSizeExceededException
* @error MaxLexemeLengthExceededException
* @error MaxLexiconsNumberExceededException
* @error ServiceFailureException
*/
putLexicon(params: Polly.PutLexiconInput, callback?: (err: Polly.InvalidLexiconException|Polly.UnsupportedPlsAlphabetException|Polly.UnsupportedPlsLanguageException|Polly.LexiconSizeExceededException|Polly.MaxLexemeLengthExceededException|Polly.MaxLexiconsNumberExceededException|Polly.ServiceFailureException|any, data: Polly.PutLexiconOutput|any) => void): Request<Polly.PutLexiconOutput|any,Polly.InvalidLexiconException|Polly.UnsupportedPlsAlphabetException|Polly.UnsupportedPlsLanguageException|Polly.LexiconSizeExceededException|Polly.MaxLexemeLengthExceededException|Polly.MaxLexiconsNumberExceededException|Polly.ServiceFailureException|any>;
/**
* Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input
must be valid, well-formed SSML. Some alphabets might not be available with all
the voices (for example, Cyrillic might not be read at all by English voices)
unless phoneme mapping is used. For more information, see How it Works
[http://docs.aws.amazon.com/polly/latest/dg/how-text-to-speech-works.html].
*
* @error TextLengthExceededException
* @error InvalidSampleRateException
* @error InvalidSsmlException
* @error LexiconNotFoundException
* @error ServiceFailureException
*/
synthesizeSpeech(params: Polly.SynthesizeSpeechInput, callback?: (err: Polly.TextLengthExceededException|Polly.InvalidSampleRateException|Polly.InvalidSsmlException|Polly.LexiconNotFoundException|Polly.ServiceFailureException|any, data: Polly.SynthesizeSpeechOutput|any) => void): Request<Polly.SynthesizeSpeechOutput|any,Polly.TextLengthExceededException|Polly.InvalidSampleRateException|Polly.InvalidSsmlException|Polly.LexiconNotFoundException|Polly.ServiceFailureException|any>;
}
export module Polly {
export type Alphabet = string;
export type AudioStream = any;
export type ContentType = string;
export type ErrorMessage = string;
export type Gender = string;
export type LanguageCode = string;
export type LanguageName = string;
export type LastModified = number;
export type LexemesCount = number;
export type LexiconArn = string;
export type LexiconContent = string;
export type LexiconDescriptionList = LexiconDescription[];
export type LexiconName = string;
export type LexiconNameList = LexiconName[];
export type NextToken = string;
export type OutputFormat = string;
export type RequestCharacters = number;
export type SampleRate = string;
export type Size = number;
export type Text = string;
export type TextType = string;
export type VoiceId = string;
export type VoiceList = Voice[];
export type VoiceName = string;
export interface DeleteLexiconInput {
/** The name of the lexicon to delete. Must be an existing lexicon in the region. **/
Name: LexiconName;
}
export interface DeleteLexiconOutput {
}
export interface DescribeVoicesInput {
/** The language identification tag (ISO 639 code for the language name-ISO 3166
country code) for filtering the list of voices returned. If you don't specify
this optional parameter, all available voices are returned. **/
LanguageCode?: LanguageCode;
/** An opaque pagination token returned from the previous DescribeVoices operation.
If present, this indicates where to continue the listing. **/
NextToken?: NextToken;
}
export interface DescribeVoicesOutput {
/** A list of voices with their properties. **/
Voices?: VoiceList;
/** The pagination token to use in the next request to continue the listing of
voices. NextToken is returned only if the response is truncated. **/
NextToken?: NextToken;
}
export interface GetLexiconInput {
/** Name of the lexicon. **/
Name: LexiconName;
}
export interface GetLexiconOutput {
/** Lexicon object that provides name and the string content of the lexicon. **/
Lexicon?: Lexicon;
/** Metadata of the lexicon, including phonetic alphabetic used, language code,
lexicon ARN, number of lexemes defined in the lexicon, and size of lexicon in
bytes. **/
LexiconAttributes?: LexiconAttributes;
}
export interface InvalidLexiconException {
message?: ErrorMessage;
}
export interface InvalidNextTokenException {
message?: ErrorMessage;
}
export interface InvalidSampleRateException {
message?: ErrorMessage;
}
export interface InvalidSsmlException {
message?: ErrorMessage;
}
export interface Lexicon {
/** Lexicon content in string format. The content of a lexicon must be in PLS
format. **/
Content?: LexiconContent;
/** Name of the lexicon. **/
Name?: LexiconName;
}
export interface LexiconAttributes {
/** Phonetic alphabet used in the lexicon. Valid values are ipa and x-sampa. **/
Alphabet?: Alphabet;
/** Language code that the lexicon applies to. A lexicon with a language code such
as "en" would be applied to all English languages (en-GB, en-US, en-AUS, en-WLS,
and so on. **/
LanguageCode?: LanguageCode;
/** Date lexicon was last modified (a timestamp value). **/
LastModified?: LastModified;
/** Amazon Resource Name (ARN) of the lexicon. **/
LexiconArn?: LexiconArn;
/** Number of lexemes in the lexicon. **/
LexemesCount?: LexemesCount;
/** Total size of the lexicon, in characters. **/
Size?: Size;
}
export interface LexiconDescription {
/** Name of the lexicon. **/
Name?: LexiconName;
/** Provides lexicon metadata. **/
Attributes?: LexiconAttributes;
}
export interface LexiconNotFoundException {
message?: ErrorMessage;
}
export interface LexiconSizeExceededException {
message?: ErrorMessage;
}
export interface ListLexiconsInput {
/** An opaque pagination token returned from previous ListLexicons operation. If
present, indicates where to continue the list of lexicons. **/
NextToken?: NextToken;
}
export interface ListLexiconsOutput {
/** A list of lexicon names and attributes. **/
Lexicons?: LexiconDescriptionList;
/** The pagination token to use in the next request to continue the listing of
lexicons. NextToken is returned only if the response is truncated. **/
NextToken?: NextToken;
}
export interface MaxLexemeLengthExceededException {
message?: ErrorMessage;
}
export interface MaxLexiconsNumberExceededException {
message?: ErrorMessage;
}
export interface PutLexiconInput {
/** Name of the lexicon. The name must follow the regular express format
[0-9A-Za-z]{1,20}. That is, the name is a case-sensitive alphanumeric string up
to 20 characters long. **/
Name: LexiconName;
/** Content of the PLS lexicon as string data. **/
Content: LexiconContent;
}
export interface PutLexiconOutput {
}
export interface ServiceFailureException {
message?: ErrorMessage;
}
export interface SynthesizeSpeechInput {
/** List of one or more pronunciation lexicon names you want the service to apply
during synthesis. Lexicons are applied only if the language of the lexicon is
the same as the language of the voice. For information about storing lexicons,
see PutLexicon [http://docs.aws.amazon.com/polly/latest/dg/API_PutLexicon.html]. **/
LexiconNames?: LexiconNameList;
/** The audio format in which the resulting stream will be encoded. **/
OutputFormat: OutputFormat;
/** The audio frequency specified in Hz.
The valid values for mp3 and ogg_vorbis are "8000", "16000", and "22050". The
default value is "22050".
Valid values for pcm are "8000" and "16000" The default value is "16000". **/
SampleRate?: SampleRate;
/** Input text to synthesize. If you specify ssml as the TextType, follow the SSML
format for the input text. **/
Text: Text;
/** Specifies whether the input text is plain text or SSML. The default value is
plain text. For more information, see Using SSML
[http://docs.aws.amazon.com/polly/latest/dg/ssml.html]. **/
TextType?: TextType;
/** Voice ID to use for the synthesis. You can get a list of available voice IDs by
calling the DescribeVoices
[http://docs.aws.amazon.com/polly/latest/dg/API_DescribeVoices.html] operation. **/
VoiceId: VoiceId;
}
export interface SynthesizeSpeechOutput {
/** Stream containing the synthesized speech. **/
AudioStream?: AudioStream;
/** Specifies the type audio stream. This should reflect the OutputFormat parameter
in your request.
&#42; If you request mp3 as the OutputFormat, the ContentType returned is
audio/mpeg.
* If you request ogg_vorbis as the OutputFormat, the ContentType returned is
audio/ogg.
* If you request pcm as the OutputFormat, the ContentType returned is
audio/pcm in a signed 16-bit, 1 channel (mono), little-endian format. **/
ContentType?: ContentType;
/** Number of characters synthesized. **/
RequestCharacters?: RequestCharacters;
}
export interface TextLengthExceededException {
message?: ErrorMessage;
}
export interface UnsupportedPlsAlphabetException {
message?: ErrorMessage;
}
export interface UnsupportedPlsLanguageException {
message?: ErrorMessage;
}
export interface Voice {
/** Gender of the voice. **/
Gender?: Gender;
/** Amazon Polly assigned voice ID. This is the ID that you specify when calling the
SynthesizeSpeech operation. **/
Id?: VoiceId;
/** Language code of the voice. **/
LanguageCode?: LanguageCode;
/** Human readable name of the language in English. **/
LanguageName?: LanguageName;
/** Name of the voice (for example, Salli, Kendra, etc.). This provides a human
readable voice name that you might display in your application. **/
Name?: VoiceName;
}
}
}
|
366675b7e09d5b589fd2d8998e7a7a871dbb4172
|
TypeScript
|
landzcape/landzcape
|
/explorer/webapp/src/app/domain/layout/elastic-insert/container.ts
| 3.28125
| 3
|
import {Node} from './node';
export class Container {
private _parent?: Container;
constructor(
public readonly value: any,
public readonly children: Container[]) {
}
propagateParent() {
this.children.forEach(child => {
child.parent = this;
child.propagateParent();
});
}
set parent(value: Container) {
this._parent = value;
}
moveRight() {
const index = this.getIndex();
const targetIndex = this.getIndex(1);
this.swapPositions(index, targetIndex);
}
moveLeft() {
const index = this.getIndex();
const targetIndex = this.getIndex(-1);
this.swapPositions(index, targetIndex);
}
private swapPositions(index, targetIndex) {
const parent = this.parent;
const target = parent.children[targetIndex];
parent.children[targetIndex] = parent.children[index];
parent.children[index] = target;
}
private getIndex(offset: number = 0) {
const parent = this.parent;
const index = parent.children.indexOf(this);
if (index < 0 || index > parent.children.length - 1) {
throw new Error(`Invalid parent/child setup: ${index}`);
}
const targetIndex = (parent.children.length + index + offset) % parent.children.length;
return targetIndex;
}
getChildren(depth: number): Container[] {
if (depth <= 0) {
return this.children;
}
return this.children
.map(child => child.getChildren(depth - 1))
.reduce((a, b) => a.concat(b), []);
}
get parent(): Container {
return this._parent;
}
get nodes(): Node[] {
return this.children
.map(child => child.nodes)
.reduce((a, b) => a.concat(b), []);
}
}
|
953bf436f4fd9e51883108362c3e250d514ac4ea
|
TypeScript
|
uidu-org/guidu
|
/packages/data/dashlets/src/utils/index.ts
| 2.5625
| 3
|
import { group, max, mean, sum } from 'd3-array';
import numeral from 'numeral';
// http://tristen.ca/hcl-picker/#/hlc/14/0.53/433339/E8D489
export const colors = [
'#E8D489',
'#CCCB84',
'#B2C182',
'#9BB682',
'#87AA81',
'#769D81',
'#6A907F',
'#62827A',
'#5C7474',
'#555960',
'#58666B',
'#504B54',
'#4B3F46',
'#433339',
];
export function resolve(path: string, obj = {}) {
return path
.split('.')
.reduce((prev, curr) => (prev ? prev[curr] : null), obj);
}
export function manipulator<T>(record: T[], [operation, key]: string[]) {
switch (operation) {
case 'sum':
return sum(record, (c) => resolve(key, c));
case 'count':
return group(
record.filter((l) => !l.fake),
(c) => resolve(key, c),
).size;
case 'max':
return max(record, (c) => resolve(key, c));
case 'mean':
return mean(record, (c) => resolve(key, c) || 0);
default:
return record.length;
}
}
export function format(value: number, formatter: string) {
switch (formatter) {
case 'currency':
return numeral(value).format('$ 0,0.00');
case 'integer':
return numeral(value).format();
case 'percent':
return numeral(value).format('0.0%');
case 'bytes':
return numeral(value).format('0.00b');
default:
return value;
}
}
|
ac5ef762c0099fc90b87c96c5629fd0ac561ed8c
|
TypeScript
|
FrederikBolding/unlock
|
/unlock-app/src/services/graphService.ts
| 2.5625
| 3
|
import ApolloClient from 'apollo-boost'
import { utils } from 'ethers'
import locksByManager from '../queries/locksByManager'
import keyHoldersByLocks from '../queries/keyholdersByLock'
export class GraphService {
public client: any
connect(uri: string) {
this.client = new ApolloClient({
uri,
})
}
locksByManager = async (owner: string) => {
const query = locksByManager()
try {
const result = await this.client.query({
query,
variables: {
owner,
},
})
// TODO: map fields so that we get the same output values than unlock-js (keyPrice should use decimals... etc)
// the Graph returns lower cased addresses.
// To make sure we stay consistent with the rest of the app
// We use checksumed addresses.
return result.data.lockManagers.map((manager: any) => {
return {
...manager.lock,
address: utils.getAddress(manager.lock.address),
}
})
} catch (error) {
console.error(error)
alert(
'We could not load your locks. Please retry and let us know if that keeps failing'
)
return []
}
}
keysByLocks = async (
locks: string[],
expiresAfter: number,
first: number,
skip: number
) => {
const query = keyHoldersByLocks()
const result = await this.client.query({
query,
variables: {
addresses: locks,
expiresAfter,
first,
skip,
},
})
return result
}
}
export default GraphService
|
4401462ed9317432ecfd734871dee73436efebca
|
TypeScript
|
aws-amplify/amplify-ui
|
/packages/ui/src/theme/tokens/fonts.ts
| 2.84375
| 3
|
import {
DesignTokenValues,
FontValue,
OutputVariantKey,
} from './types/designToken';
type FontVariant = 'variable' | 'static';
type BaseFonts<
Output extends OutputVariantKey = unknown,
Platform = unknown
> = {
default?: DesignTokenValues<FontVariant, FontValue, Output, Platform>;
};
// `Fonts` tokens requires special handling for `required` output due to nested tokens
export type Fonts<
Output extends OutputVariantKey = unknown,
Platform = unknown
> = Output extends 'required' | 'default'
? Required<BaseFonts<Output, Platform>>
: BaseFonts<Output, Platform>;
// TODO: update the design tokens to use an array
// export interface FontDesignToken {
// value: Array<string>
// }
export const fonts: Fonts<'default'> = {
default: {
variable: {
value: `'InterVariable', 'Inter var', 'Inter', -apple-system, BlinkMacSystemFont,
'Helvetica Neue', 'Segoe UI', Oxygen, Ubuntu, Cantarell, 'Open Sans',
sans-serif`,
},
static: {
value: `'Inter', -apple-system, BlinkMacSystemFont, 'Helvetica Neue',
'Segoe UI', Oxygen, Ubuntu, Cantarell, 'Open Sans', sans-serif`,
},
},
};
|
f27b65cdadc7e0d2852be773977084bd9ec9d208
|
TypeScript
|
cov-clear/backend
|
/src/presentation/transformers/SharingCodeTransformer.ts
| 2.515625
| 3
|
import { SharingCode } from '../../domain/model/sharingCode/SharingCode';
import { SharingCodeDTO } from '../dtos/access-sharing/SharingCodeDTO';
export class SharingCodeTransformer {
public toSharingCodeDTO(sharingCode: SharingCode): SharingCodeDTO {
return {
code: sharingCode.code,
accessDuration: sharingCode.accessDuration,
expiryTime: sharingCode.expirationTime(),
};
}
}
|
0357f7e416b18f25a57f3d30f0bf2c17c1863a96
|
TypeScript
|
Lonmee/OPlayer
|
/ts/mod/Mgr/AudioMgr.ts
| 2.703125
| 3
|
import {Cmd} from "../../data/sotry/Story";
import {IMgr} from "./Mgr";
import SoundManager = laya.media.SoundManager;
import SoundChannel = laya.media.SoundChannel;
/**
* Created by ShanFeng on 5/8/2017.
*/
enum ChannelEnum {bg, fx, vo, bfx}
export default class AudioMgr implements IMgr {
private channels: SoundChannel[] = [];
exe(cmd: Cmd) {
switch (cmd.code) {
case 501://"播放背景音乐"
this.play(ChannelEnum.bg, cmd.para[0], parseInt(cmd.para[1]));
break;
case 502://"播放音效"
this.play(ChannelEnum.fx, cmd.para[0], parseInt(cmd.para[1]));
break;
case 503://"播放语音"
this.play(ChannelEnum.vo, cmd.para[0], parseInt(cmd.para[1]));
break;
case 504://"播放背景音效"
this.play(ChannelEnum.bfx, cmd.para[0], parseInt(cmd.para[1]));
break;
case 505://"淡出背景音乐"
this.fadeOut(ChannelEnum.bg, parseInt(cmd.para[0]));
break;
case 508://"淡出音效"
this.fadeOut(ChannelEnum.fx, parseInt(cmd.para[0]));
break;
case 506://"停止音效"
this.stop(ChannelEnum.fx);
break
case 507://"停止语音"
this.stop(ChannelEnum.vo);
}
}
update(speed: number) {
}
fadeOut(c: ChannelEnum, t: number) {
}
play(c: ChannelEnum, url: string, v: number) {
switch (c) {
case ChannelEnum.bg:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.fx:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.vo:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.bfx:
// this.channels[c] = SoundManager.playSound(url);
}
}
stop(c: ChannelEnum) {
// this.channels[c].stop();
}
pause() {
}
resume() {
}
};
/*
501 播放背景音乐 0:背景音乐的相对路径 1:音量 2:显示信息 3 网盘还是本地
502 播放音效 0:音效的相对路径 1:音量 2:显示信息 3 网盘还是本地
503 播放语音 0:语音的相对路径 1:音量 2:显示信息 3 网盘还是本地
504 播放背景音效 0:背景音效的相对路径 1:音量 2:显示信息 3 网盘还是本地
505 淡出背景音乐 0:时间
506 停止音效 0:空
507 停止语音 0:空
508 淡出音效 0:时间*/
|
45a2ab0fccc7c89fabfbc9583ec6803c8dc588fe
|
TypeScript
|
jedster1111/YourTune
|
/frontend/src/actions/channelsActions.ts
| 2.96875
| 3
|
import { Action } from "redux";
import { ChannelData } from "../types";
export type ChannelsActions =
| GetChannelsLoadingAction
| GetChannelsSuccessAction
| GetChannelsErrorAction;
export enum ChannelsActionsTypes {
getChannelsLoading = "GET_CHANNELS_LOADING",
getChannelsSuccess = "GET_CHANNELS_SUCCESS",
getChannelsError = "GET_CHANNELS_ERROR"
}
export interface GetChannelsLoadingAction
extends Action<ChannelsActionsTypes.getChannelsLoading> {}
interface GetChannelsSuccessAction
extends Action<ChannelsActionsTypes.getChannelsSuccess> {
payload: { channels: ChannelData[] };
}
interface GetChannelsErrorAction
extends Action<ChannelsActionsTypes.getChannelsError> {
payload: { errorMessage: string };
}
export function createGetChannelsLoadingAction(): GetChannelsLoadingAction {
return {
type: ChannelsActionsTypes.getChannelsLoading
};
}
export function createGetChannelsSuccessAction(
channels: ChannelData[]
): GetChannelsSuccessAction {
return {
type: ChannelsActionsTypes.getChannelsSuccess,
payload: { channels }
};
}
export function createGetChannelsErrorAction(
errorMessage: string
): GetChannelsErrorAction {
return {
type: ChannelsActionsTypes.getChannelsError,
payload: { errorMessage }
};
}
|
ac0084131231a6fe432a423640ed2e93b089e4de
|
TypeScript
|
loquemedalagana/webpack-toy-project
|
/src/components/Card/CardList.ts
| 2.515625
| 3
|
import {
ClosableComponent,
ClosableHeaderComponentConstructor,
CloseableComponentConstructor,
Component,
Composable,
Core,
} from '../Core';
import { Image } from '../Image';
import { Video } from '../Video';
import { Post } from '../Post';
import { PostItem } from '../../types/post';
import { CARDWRAPPER_INNERHTML } from '../../constants/innerHTML';
import { CardDescription } from './CardDescription';
export class CardList extends Core<HTMLElement> implements Composable {
private postComponentList: Array<ClosableComponent>; // Card component로 통합?
constructor(
private cardConstructor: CloseableComponentConstructor,
private cardHeaderConstructor: ClosableHeaderComponentConstructor,
) {
super(CARDWRAPPER_INNERHTML);
this.postComponentList = this.getLocalStorageData();
this.addChildren(this.postComponentList);
}
private static getMediaComponent(postData: Partial<PostItem>): Image | Video | Post {
switch (postData.type) {
case 'video':
return new Video(postData);
case 'post':
return new Post(postData);
case 'image':
return new Image(postData);
}
}
private getLocalStorageData() {
const POST_LIST_LENGTH = localStorage.length;
const extractedPostList: Array<ClosableComponent> = [];
for (let i = 0; i < POST_LIST_LENGTH; i++) {
const key = localStorage.key(i);
const value = JSON.parse(localStorage.getItem(key))! as PostItem;
const cardComponent = this.makeCardComponent(value);
if (extractedPostList.includes(cardComponent)) continue;
extractedPostList.push(cardComponent);
}
return extractedPostList;
}
private static saveInLocalStorage(newElementId: string, postData: Partial<PostItem>) {
const foundValue = localStorage.getItem(newElementId);
if (foundValue === null) {
localStorage.setItem(newElementId, JSON.stringify(postData));
}
}
makeCardComponent(postData: Partial<PostItem>) {
const onCloseListener = () => cardComponent.removeFrom(this.$element);
const cardHeaderComponent = new this.cardHeaderConstructor(postData, onCloseListener);
const mediaComponent = CardList.getMediaComponent(postData);
const cardDescriptionComponent = new CardDescription(postData.description);
const newElementId = postData.id ? postData.id : mediaComponent.getId(postData.url);
const cardComponent = new this.cardConstructor(newElementId);
cardComponent.addChildren([cardHeaderComponent, mediaComponent, cardDescriptionComponent]);
cardComponent.setOnCloseListener(onCloseListener);
CardList.saveInLocalStorage(newElementId, postData);
return cardComponent;
}
addChildren(children: Component[]) {
children.forEach((child) => {
child.attachTo(this.$element, 'afterbegin');
});
}
}
|
84a8f71989ae04d1b5cd11642126bd8872e4b4d8
|
TypeScript
|
shready/bridge-hand
|
/src/modules/Card/__tests__/CardSet.spec.ts
| 3.453125
| 3
|
import { ScorerInterface } from '@/lib/ScorerInterface';
import { Card } from '../Card';
import { CardSet } from '../CardSet';
import { Face } from '../Face';
import { Suit } from '../Suit';
describe('CardSet class', () => {
let cards: Card[] = [];
let scorer: ScorerInterface;
beforeEach(() => {
cards = [
new Card(Face.ace, Suit.spade),
new Card(Face.eight, Suit.heart),
new Card(Face.queen, Suit.club),
];
const scoreMap = {
[Suit.club]: 1,
[Suit.diamond]: 2,
[Suit.heart]: 3,
[Suit.spade]: 4,
};
scorer = {
score(cards: Card[]): number {
return cards.reduce(
(sum: number, card: Card): number => sum + scoreMap[card.getSuit()],
0,
);
}
}
});
it('can be instantiated with array of cards', () => {
const set = new CardSet(cards);
expect(set.getCards()).toStrictEqual(cards);
});
it('can have new cards added', () => {
const set = new CardSet();
const card = new Card(Face.jack, Suit.diamond);
set.addCard(card);
expect(set.getCards()).toStrictEqual([card]);
set.addCards(cards);
expect(set.getCards()).toStrictEqual([card, ...cards]);
});
it('allows cards to be replaced entirely', () => {
const set = new CardSet(cards);
const newCards = [new Card(Face.eight, Suit.heart), new Card(Face.two, Suit.club)];
set.setCards(newCards);
expect(set.getCards()).toStrictEqual(newCards);
});
it('retrieves the number of cards in the set', () => {
const set = new CardSet(cards);
expect(set.getSize()).toBe(3);
set.addCard(new Card(Face.jack, Suit.diamond));
expect(set.getSize()).toBe(4);
});
it('retreives the point value of the cards', () => {
const set = new CardSet([
new Card(Face.ace, Suit.spade),
new Card(Face.eight, Suit.heart),
new Card(Face.queen, Suit.club),
new Card(Face.eight, Suit.heart),
new Card(Face.two, Suit.club),
], scorer);
expect(set.getPointValue()).toBe(12);
});
it('retreives the point value of the cards by suit', () => {
const set = new CardSet([
new Card(Face.ace, Suit.spade),
new Card(Face.eight, Suit.heart),
new Card(Face.queen, Suit.club),
new Card(Face.nine, Suit.heart),
new Card(Face.two, Suit.club),
], scorer);
expect(set.getPointValueForSuit(Suit.club)).toBe(2);
expect(set.getPointValueForSuit(Suit.heart)).toBe(6);
expect(set.getPointValueForSuit(Suit.spade)).toBe(4);
expect(set.getPointValueForSuit(Suit.diamond)).toBe(0);
});
it('retrieves a sorted set of cards', () => {
const cards = [
new Card(Face.ace, Suit.spade),
new Card(Face.eight, Suit.heart),
new Card(Face.queen, Suit.club),
new Card(Face.nine, Suit.heart),
new Card(Face.two, Suit.club),
new Card(Face.seven, Suit.diamond),
new Card(Face.king, Suit.spade),
];
const set = new CardSet(cards);
expect(set.getSortedCards()).toStrictEqual([
cards[0],
cards[6],
cards[3],
cards[1],
cards[5],
cards[2],
cards[4],
]);
});
});
|
8a4929f2149c51fd6c03f3cd95dea4daccb5d194
|
TypeScript
|
interledgerjs/rafiki
|
/packages/rafiki-core/src/services/accounts/in-memory.ts
| 2.734375
| 3
|
import { AccountInfo } from '../../types'
import { Observable, Subject } from 'rxjs'
import { AccountNotFoundError } from '../../errors'
import { Errors } from 'ilp-packet'
import { AccountsService, AccountSnapshot, Transaction } from '.'
import debug from 'debug'
import { map } from 'rxjs/operators'
const { InsufficientLiquidityError } = Errors
// Implementations SHOULD use a better logger than debug for production services
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const log = debug('rafiki:in-memory-accounts-service')
/**
* An in-memory account service for development and testing purposes.
*/
interface InMemoryAccount extends AccountSnapshot {
balancePayableInflight: bigint;
balancePayable: bigint;
balanceReceivable: bigint;
balanceReceivableInflight: bigint;
}
export class InMemoryAccountsService implements AccountsService {
private _updatedAccounts: Subject<AccountSnapshot>
private _accounts: Map<string, InMemoryAccount>
constructor () {
this._accounts = new Map<string, InMemoryAccount>()
this._updatedAccounts = new Subject<AccountSnapshot>()
}
get updated (): Observable<AccountSnapshot> {
return this._updatedAccounts
.asObservable()
.pipe(map(value => Object.assign({}, value)))
}
async get (id: string): Promise<InMemoryAccount> {
const account = this._accounts.get(id)
if (!account) {
throw new AccountNotFoundError(id)
}
return account
}
add (accountInfo: AccountInfo): void {
const account: InMemoryAccount = {
...accountInfo,
balancePayableInflight: BigInt(0),
balancePayable: BigInt(0),
balanceReceivable: BigInt(0),
balanceReceivableInflight: BigInt(0)
}
this._accounts.set(account.id, account)
}
update (accountInfo: AccountInfo): void {
const account = this.get(accountInfo.id)
Object.assign(account, accountInfo)
}
remove (id: string): void {
this._accounts.delete(id)
}
// Adjust amount the we owe
// As this is called after we have got the fulfillment. It doesn't actually make much sense
public async adjustBalancePayable (
amount: bigint,
accountId: string,
callback: (trx: Transaction) => Promise<any>
): Promise<AccountSnapshot> {
const account = await this.get(accountId)
if (amount > BigInt(0)) {
// Need to ensure these are actually called
const transaction: Transaction = {
commit: async () => {
account.balancePayableInflight -= amount
account.balancePayable += amount
},
rollback: async () => {
account.balancePayableInflight -= amount
}
}
try {
// Maybe doing the adjustment must occur before the liquidity check + how to handle atomicity
account.balancePayableInflight += amount
if (
account.balancePayableInflight + account.balancePayable >
account.maximumPayable
) {
throw new InsufficientLiquidityError(
`Max payable exceeded: expected: ${(
account.balancePayableInflight + account.balancePayable
).toString()} maximum: ${account.maximumPayable.toString()}`
)
}
await callback(transaction)
// TODO look at netting
this._updatedAccounts.next(account)
return {
balanceReceivable: account.balanceReceivable,
balancePayable: account.balancePayable
} as AccountSnapshot
} catch (error) {
// Should this rethrow the the error?
account.balancePayableInflight -= amount
throw error(error)
}
} else {
const transaction: Transaction = {
commit: async () => {
account.balancePayable += amount
},
rollback: async () => {}
}
await callback(transaction)
return {
balanceReceivable: account.balanceReceivable,
balancePayable: account.balancePayable
} as AccountSnapshot
}
}
public async adjustBalanceReceivable (
amount: bigint,
accountId: string,
callback: (trx: Transaction) => Promise<any>
): Promise<AccountSnapshot> {
const account = await this.get(accountId)
const transaction: Transaction = {
commit: async () => {
account.balanceReceivableInflight -= amount
account.balanceReceivable += amount
},
rollback: async () => {
account.balanceReceivableInflight -= amount
}
}
// Try commit or catch and rollback
try {
// Maybe doing the adjustment must occur before the liquidity check + how to handle atomicity
account.balanceReceivableInflight += amount
if (
account.balanceReceivableInflight + account.balanceReceivable >
account.maximumReceivable
) {
throw new InsufficientLiquidityError('')
}
await callback(transaction)
// TODO Need to check if commit/rollback was called else throw
return {
balanceReceivable: account.balanceReceivable,
balancePayable: account.balancePayable
} as AccountSnapshot
} catch (error) {
// Should this rethrow the the error?
account.balanceReceivableInflight -= amount
throw error(error)
}
}
// Can take money from payable and transfer to receivables
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async maybeSettle (account: InMemoryAccount): Promise<void> {
// // First potentially net.
// // if payable_balance > 0 && receivable_balance > 0 {
// // let amount_to_net = min(payable_balance, receivable_balance);
// // payable_balance = payable_balance - amount_to_net;
// // receivable_balance = receivable_balance - amount_to_net;
// // }
//
// // Then try settle
// // if (!settlement || !settlementEngine) {
// // logger.debug('Not deciding whether to settle for accountId=' + peer.id + '. No settlement engine configured.')
// // return
// // }
//
}
}
|
38dd5cbc42fcbe7676e5e18fdd1fc288af2e102d
|
TypeScript
|
filipkrw/dodge-game
|
/src/observables/userInterface.ts
| 2.5625
| 3
|
import { BehaviorSubject, EMPTY, fromEvent, of } from 'rxjs'
import { switchMap, mergeWith, withLatestFrom, tap } from 'rxjs/operators'
import { Score } from '../entities/Score'
import { GameState, gameState$ } from './gameState'
import { Title } from '../entities/Title'
export const Interface = (score: Score, title: Title, subtitle: Title) => {
const interface$ = of(score).pipe(
withLatestFrom(of(title), of(subtitle)),
tap(([score, title, subtitle]) => {
score.update()
title.center()
subtitle.center()
})
)
return {
onStart$: interface$.pipe(
tap(([score, title, subtitle]) => {
score.score = 0
score.scoreText.visible = false
score.update()
title.text.visible = true
title.text.value = 'Click anywhere to start'
subtitle.text.visible = true
subtitle.text.value = 'Avoid azure balls'
})
),
onPlay$: interface$.pipe(
tap(([score, title, subtitle]) => {
score.scoreText.visible = true
title.text.visible = false
subtitle.text.visible = false
})
),
onEnd$: interface$.pipe(
tap(([score, title, subtitle]) => {
score.scoreText.visible = false
title.text.visible = true
title.text.value = `You manged to outlive ${score.score} menacing azure balls`
subtitle.text.visible = true
subtitle.text.value = 'Press space to play again'
})
),
}
}
|
62ad9e481cf2260d51258c5e1835659900334f06
|
TypeScript
|
aneeshthunga/CalorieTracker
|
/src/reducers/calorieReducer.ts
| 3.203125
| 3
|
import { IAlterCalorieAction } from '../actions/Actions';
import { IAppState } from '../state/AppContext';
/**
* A reducer witch handles the dispatched {@link IAlterCalorieAction}s and mutates the current {@link IAppState}
* @param state - the current {@link IAppState}
* @param action - the dispatched {@link IAlterCalorieAction}
* @return - the mutated {@link IAppState}
*/
export default function calorieReducer(state: IAppState, action: IAlterCalorieAction): IAppState {
switch (action.type) {
// adds the calories to the total calories
case 'add-calorie':
return {
...state,
totalCalories: state.totalCalories ? state.totalCalories + action.payload : action.payload,
};
// subtracts the calories from the total calories
case 'subtract-calorie':
return {
...state,
totalCalories: state.totalCalories ? state.totalCalories - action.payload : 0,
};
// unreachable code
default:
const _unreachable: never = action.type;
return _unreachable;
}
}
|
2b7fe42e48bcc264f7eeca950f4aefb8044fe723
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/yuka/src/steering/behaviors/InterposeBehavior.d.ts
| 3.34375
| 3
|
import { MovingEntity } from "../../core/MovingEntity";
import { Vector3 } from "../../math/Vector3";
import { SteeringBehavior } from "../SteeringBehavior";
import { Vehicle } from "../Vehicle";
/**
* This steering behavior produces a force that moves a vehicle to the midpoint
* of the imaginary line connecting two other agents.
*/
export class InterposeBehavior extends SteeringBehavior {
/**
* The first agent.
* @default null
*/
entity1: MovingEntity;
/**
* The second agent.
* @default null
*/
entity2: MovingEntity;
/**
* The amount of deceleration.
* @default 3
*/
deceleration: number;
/**
* Constructs a new interpose behavior.
*
* @param [entity1] - The first agent.
* @param [entity2] - The second agent.
* @param [deceleration] - The amount of deceleration.
*/
constructor(entity1?: MovingEntity, entity2?: MovingEntity, deceleration?: number);
/**
* Calculates the steering force for a single simulation step.
*
* @param vehicle - The game entity the force is produced for.
* @param force - The force/result vector.
* @return The force/result vector.
*/
calculate(vehicle: Vehicle, force: Vector3): Vector3;
}
|
878e7d1255fcbe2f0e8fb5131c09bddfc199350c
|
TypeScript
|
nrfm/umbrella
|
/packages/color/src/oklab/oklab-rgb.ts
| 2.578125
| 3
|
import type { ColorOp } from "../api.js";
import { __mulV33 } from "../internal/matrix-ops.js";
const LMS_CONE = [
4.0767245293, -1.2681437731, -0.0041119885, -3.3072168827, 2.6093323231,
-0.7034763098, 0.2307590544, -0.341134429, 1.7068625689,
];
/**
* @remarks
* Reference: https://bottosson.github.io/posts/oklab/
*
* @param out
* @param src
*/
export const oklabRgb: ColorOp = (out, { 0: l, 1: a, 2: b, 3: alpha }) =>
__mulV33(out, LMS_CONE, [
(l + 0.3963377774 * a + 0.2158037573 * b) ** 3,
(l - 0.1055613458 * a - 0.0638541728 * b) ** 3,
(l - 0.0894841775 * a - 1.291485548 * b) ** 3,
alpha,
]);
|
158bda6fef8a67b579d944180f847f66ed2e7b0a
|
TypeScript
|
sintti/full_stack_2020_osa9
|
/patientor_backend/src/services/patientService.ts
| 2.78125
| 3
|
import patientData from '../../data/patients';
import { NonSensitivePatientEntry, Patient, NewPatient } from '../types';
const getAll = (): Array<Patient> => {
return patientData;
};
const getPatient = (id: string): Patient | undefined => {
const patient: Patient | undefined = patientData.find(p => p.id === id)
return patient;
}
const getNonSensitivePatientEntries = (): NonSensitivePatientEntry[] => {
return patientData.map(({ id, name, dateOfBirth, gender, occupation, entries }) => ({
id,
name,
dateOfBirth,
gender,
occupation,
entries
}))
}
const addPatient = ( patient: NewPatient ): Patient => {
const newPatientEntry = {
id: String(Math.random() * 1000),
...patient
};
patientData.push(newPatientEntry);
return newPatientEntry;
};
const addPatientEntries = ( idToModify: string, entry: any ): any => {
console.log({idToModify})
console.log({entry})
const newEntries = {
id: String(Math.random() * 1000),
date: new Date(),
...entry
}
console.log({ newEntries })
let patientToModify: any = patientData.find(p => p.id === idToModify);
patientToModify.entries.push(newEntries);
patientData.push(patientToModify);
return patientToModify;
}
export default {
getAll,
getPatient,
getNonSensitivePatientEntries,
addPatient,
addPatientEntries
}
|
795c25e795ecff9e814dadda135b3f10499a49c6
|
TypeScript
|
shawnrice/teikn
|
/src/Color/Color.ts
| 3.21875
| 3
|
import { HSLToRGB } from './HSLToRGB';
import { namedColorsByValue, NamedColorValue } from './namedColors';
import { RGBToHex } from './RGBToHex';
import { RGBToHSL } from './RGBToHSL';
import { stringToRGBA } from './stringToRGBA';
const clamp = (min: number, max: number, n: number) => Math.min(Math.max(n, min), max);
const hexRange = (num: number) => clamp(0, 255, num);
const percentRange = (num: number) => clamp(0, 1, num);
const degreeRange = (num: number) => clamp(0, 360, num);
const checkNumberInRange = (bounds: { lower: number; upper: number }, n: number) => {
const { lower, upper } = bounds;
if (typeof n !== 'number') {
throw new TypeError(`Must be a number`);
}
if (n < lower || upper < n) {
throw new TypeError(`Must be between ${lower} and ${upper}`);
}
};
const ensurePercentage = (p: number): number => {
checkNumberInRange({ lower: 0, upper: 1 }, p);
return p;
};
const ensureHex = (c: number): number => {
checkNumberInRange({ lower: 0, upper: 255 }, c);
return c;
};
export const round = (digits: number, n: number): number =>
Math.round(n * 10 ** digits) / 10 ** digits;
export const roundArray = (nums: number[]) => (arr: number[]): number[] =>
arr.map((v, i) => round(nums[i], v));
export const roundHSL = roundArray([0, 2, 2]);
const toPercentage = (n: number, precision = 0): number =>
Math.round(n * 10 ** (2 + precision)) / 10 ** precision;
export class Color {
red: number;
blue: number;
green: number;
alpha: number;
constructor(color: string | Color);
constructor(r: number, g: number, b: number, a?: number);
constructor(r: string | Color | number, g?: number, b?: number, a?: number) {
if (r instanceof Color) {
this.red = r.red;
this.green = r.green;
this.blue = r.blue;
this.alpha = r.alpha;
return this;
}
if (typeof r === 'string') {
const [red, green, blue, alpha] = stringToRGBA(r);
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
return this;
}
if (typeof r === 'number' && typeof g === 'number' && typeof b === 'number') {
this.red = r;
this.green = g;
this.blue = b;
this.alpha = typeof a === 'number' ? percentRange(a) : 1;
return this;
}
throw new Error('Bad constructor');
}
static from(color: Color): Color {
return new Color(color);
}
setRed(red: number): Color {
const color = Color.from(this);
color.red = ensureHex(red);
return color;
}
setGreen(green: number): Color {
const color = Color.from(this);
color.green = ensureHex(green);
return color;
}
setBlue(blue: number): Color {
const color = Color.from(this);
color.blue = ensureHex(blue);
return color;
}
setAlpha(alpha: number): Color {
const color = Color.from(this);
color.alpha = ensurePercentage(alpha);
return color;
}
private setRGBA(r?: number, g?: number, b?: number, a?: number): Color {
const color = Color.from(this);
color.red = r ?? this.red;
color.green = g ?? this.green;
color.blue = b ?? this.blue;
color.alpha = a ?? this.alpha;
return color;
}
invert(): Color {
const [r, g, b] = this.asRGB();
return this.setRGBA(0xff ^ r, 0xff ^ g, 0xff ^ b);
}
get hue(): number {
const [hue] = this.asHSL();
return hue;
}
set hue(val: number) {
const [, s, l] = this.asHSL();
const hue = clamp(0, 360, val);
const [r, g, b] = HSLToRGB(hue, s, l);
this.setRGBA(r, g, b);
}
setHue(hue: number): Color {
const [, s, l] = this.asHSL();
return this.setRGBA(...HSLToRGB(degreeRange(hue), s, l));
}
rotateHue(degrees: number): Color {
return this.setHue((this.hue + degrees) % 360);
}
complement(): Color {
return this.rotateHue(180);
}
get saturation(): number {
const [, saturation] = this.asHSL();
return saturation;
}
set saturation(val: number) {
const [h, , l] = this.asHSL();
this.setRGBA(...HSLToRGB(h, percentRange(val), l));
}
setSaturation(saturation: number): Color {
const [h, , l] = this.asHSL();
return this.setRGBA(...HSLToRGB(h, percentRange(saturation), l));
}
get lightness(): number {
const [, , lightness] = this.asHSL();
return lightness;
}
set lightness(lightness: number) {
const [h, s] = this.asHSL();
const [red, green, blue] = HSLToRGB(h, s, percentRange(lightness));
this.setRGBA(red, green, blue);
}
/**
* Sets the lightness of the color (as in HSL), lightness: `∈[0, 1]`
*/
setLightness(lightness: number): Color {
const [h, s] = this.asHSL();
return this.setRGBA(...HSLToRGB(h, s, percentRange(lightness)));
}
/**
* Lightens a color by a percetage, amount: `∈[0, 1]`
*
* Works like scaling a color's lightness in SCSS
*/
lighten(amount: number): Color {
const lightness = this.lightness;
return this.setLightness(lightness + amount * lightness);
}
/**
* Darkens a color by a percentage, amount: `∈[0, 1]`
*/
darken(amount: number): Color {
return this.lighten(amount * -1);
}
/**
* Mixes a color with `amount% white`
*/
tint(amount: number): Color {
return this.mix(new Color(255, 255, 255), amount);
}
/**
* Mixes a color with `amount% black`
*/
shade(amount: number): Color {
return this.mix(new Color(0, 0, 0), amount);
}
/**
* Adds one color to another by averaging their [`r`, `g`, `b`, `a`] components
*/
mix(color: Color | string, amount = 0.5): Color {
const c = color instanceof Color ? color : new Color(color);
const amt = percentRange(amount);
const otherRGBA = c.asRGBA();
const [r, g, b, a] = this.asRGBA().reduce(
(acc, val, index) => {
// Was hitting some floating point rounding errors in the tests, so we're employing
// a different rounding strategy
const computed = Math.round(round(2, otherRGBA[index] * amt + val * (1 - amt)));
return acc.concat(hexRange(computed));
},
[] as number[],
);
return this.setRGBA(r, g, b, a);
}
/**
* Gets the perceptual luminance of a color
*
* Note: `Color.luminance()` does not take into account alpha
*
* @see https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-testsq
*/
luminance(): number {
const [red, green, blue] = this.asRGB().map(x => x / 255);
const val = (x: number) => (x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);
return 0.2126 * val(red) + 0.7152 * val(green) + 0.0722 * val(blue);
}
/**
*
* @see https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio
*/
contrastRatio(color: Color): number {
const colors = [this.luminance(), color.luminance()].map(x => x + 0.05);
return Math.max(...colors) / Math.min(...colors);
}
/**
* Checks if a text contrast is sufficient for WCAG2
*
* (Large text means `14pt + bold` or `18pt regular`)
*
* @see https://www.w3.org/TR/WCAG21/#contrast-minimum
*/
isTextWCAG2CompliantWith(color: Color, largeText = false): boolean {
return this.contrastRatio(color) >= (largeText ? 3 : 4.5);
}
/**
* Checks if a text contrast is sufficient for WCAG3
*
* (Large text means `14pt + bold` or `18pt regular`)
*
* @see https://www.w3.org/TR/WCAG21/#contrast-enhanced
*/
isTextWCAG3CompliantWith(color: Color, largeText = false): boolean {
return this.contrastRatio(color) >= (largeText ? 4.5 : 7);
}
/**
* Checks if a non-text UI color contrast is sufficient
*
* @see https://www.w3.org/TR/WCAG21/#non-text-contrast
*/
isUIWCAGCompliantWith(color: Color): boolean {
return this.contrastRatio(color) >= 3;
}
/**
* Returns the color as `[hue ∈[0, 360], saturation ∈[0, 1], lightness ∈[0, 1]]`
*/
asHSL(): readonly [number, number, number] {
const { red, green, blue } = this;
return RGBToHSL(red, green, blue);
}
/**
* Returns the color as `[red ∈[0, 255], green ∈[0, 255], blue ∈[0, 255]]`
*/
asRGB(): readonly [number, number, number] {
const { red, green, blue } = this;
return [red, green, blue] as const;
}
/**
* Returns the color as `[red ∈[0, 255], green ∈[0, 255], blue ∈[0, 255], alpha ∈[0, 1]]`
*/
asRGBA(): readonly [number, number, number, number] {
const { red, green, blue, alpha } = this;
return [red, green, blue, alpha] as const;
}
toJSON() {
return this.toString();
}
/**
* Outputs the color as a string
*
* - If request is `named`, then it will attempt a named color, but fallback to `rgb`
* - For `hex3`, it will return an abbreviated hex if possible but fallback to a full hex
* - Default: `rgba` if the alpha is not `1`, but `rgb` if the alpha is `1`
*/
toString(type?: 'rgb' | 'rgba' | 'hex' | 'hex3' | 'hsl' | 'hsla' | 'named'): string {
const [red, green, blue, alpha] = this.asRGBA();
const [hue, saturation, lightness] = roundHSL(Array.from(this.asHSL()));
const when = (condition: boolean) => (a: string, b: string) => (condition ? a : b);
const isOpaque = alpha === 1;
const whenOpaque = when(isOpaque);
const rgb = `rgb(${red}, ${green}, ${blue})`;
const rgba = `rgba(${red}, ${green}, ${blue}, ${alpha})`;
const hsl = `hsl(${hue}, ${toPercentage(saturation)}%, ${toPercentage(lightness)}%)`;
// prettier-ignore
const hsla = `hsla(${hue}, ${toPercentage(saturation)}%, ${toPercentage(lightness)}%, ${alpha})`;
switch (type) {
case 'named':
if (this.toString('rgba') === 'rgba(0, 0, 0, 0)') {
return 'transparent';
}
return namedColorsByValue[this.toString('hex') as NamedColorValue] ?? this.toString('rgb');
case 'rgb':
return whenOpaque(rgb, rgba);
case 'rgba':
return rgba;
case 'hex':
return `#${RGBToHex(red, green, blue, false)}`;
case 'hex3':
return `#${RGBToHex(red, green, blue, true)}`;
case 'hsl':
return whenOpaque(hsl, hsla);
case 'hsla':
return hsla;
default:
return whenOpaque(rgb, rgba);
}
}
}
|
a44a3b3b82e6a752d97efaf40fc269dfd66abb66
|
TypeScript
|
gabrielecanepa/exercism
|
/typescript/simple-cipher/simple-cipher.ts
| 3.359375
| 3
|
export class SimpleCipher {
private KEY_LENGTH = 100
private CHARACTERS = String.fromCharCode(...Array(123).keys()).slice(97)
key: string
shift: number
constructor(key?: string, shift?: number) {
this.key = key ?? this.generateKey()
this.shift = shift ?? this.getRandomShift()
}
encode(text: string): string {
return text.replace(/[a-z]/g, char => this.CHARACTERS[this.CHARACTERS.indexOf(char) + this.shift])
}
decode(encodedText: string): string {
return encodedText.replace(/[a-z]/g, char => this.CHARACTERS[this.CHARACTERS.indexOf(char) - this.shift])
}
private generateKey = (key = ''): string => {
for (let i = 0; i < this.KEY_LENGTH; i++) {
key += this.CHARACTERS[this.getRandomShift()]
}
return key
}
private getRandomShift = (): number => {
return Math.floor(Math.random() * (this.CHARACTERS.length + 1))
}
}
|
c320db854c70441456dcca732719d7b67fb39f45
|
TypeScript
|
janakijanu/Training13
|
/uniondemo.ts
| 2.53125
| 3
|
let x:string|number;
x=10;
console.log(x);
x="welcome";
console.log(x);
x="HCL"
console.log(x);
|
84100061aa835f3e0933b916073fa10d89006613
|
TypeScript
|
nex2null/IdleBattle
|
/src/Game/BattleSystem/BattleEffects/LastStandEffect.ts
| 3.21875
| 3
|
import BaseEffect from './BaseEffect';
import BattleCharacter from '../BattleCharacter';
import BattleEffectEnum from '../Enums/BattleEffectEnum';
class LastStandEffect extends BaseEffect {
// Properties
turnsLeft: number;
addedHp: number;
minimumHpPercent: number | null;
// Constructor
constructor(character: BattleCharacter, addedHp: number, turns: number, minimumHpPercent: number | null) {
super(character, BattleEffectEnum.LastStand, '{white-bg}{green-fg}LST{/}', false);
this.turnsLeft = turns;
this.addedHp = Math.round(addedHp);
this.minimumHpPercent = minimumHpPercent;
}
// Get the message to display when a character is inflicted with this effect
getInflictedMessage(characterName: string): string {
return `${characterName} makes their last stand`;
}
// Whether the effect can be applied
canApply() {
return this.character.getEffect(this.type) == null;
}
// Handle when the effect is applied
onApply() {
// Add maximum / current hp to the character
this.character.currentStats.hp += this.addedHp;
this.character.currentStats.maxHp += this.addedHp;
// Process base apply
super.onApply();
}
// Handle when the effect is removed
onRemove() {
// Remove the current / maximum hp that was added to the character
this.character.currentStats.hp -= this.addedHp;
this.character.currentStats.maxHp -= this.addedHp;
// If there is a minimum hp percent then ensure we do not
// reduce the characters hp below it
if (this.minimumHpPercent != null) {
var minimumHp = Math.round(this.character.currentStats.maxHp * this.minimumHpPercent);
if (this.character.currentStats.hp < minimumHp) {
this.character.currentStats.hp = minimumHp;
}
}
}
// Handle before an action is performed
beforeActionPerformed() {
this.turnsLeft--;
if (this.turnsLeft <= 0)
this.character.removeEffect(this);
}
}
export default LastStandEffect;
|
9c6ade0eb66fc63c3006e24247d47deda95bbf12
|
TypeScript
|
aadebdeb/three-raymarch
|
/src/ObjectSpaceRaymarchStandardMaterial.ts
| 2.6875
| 3
|
import { Color, CubeTexture, UniformsUtils, UniformsLib, MultiplyOperation } from 'three';
import { ObjectSpaceRaymarchMaterial, ObjectSpaceRaymarchMaterialParameters } from './ObjectSpaceRaymarchMaterial';
import { RaymarchShaderChunk } from './shaders/RaymarchShaderChunk';
/**
* Parameters of {@link ObjectSpaceRaymarchStandardMaterial}.
*/
export interface ObjectSpaceRaymarchStandardMaterialParameters extends ObjectSpaceRaymarchMaterialParameters {
/**
* Shader chunk which defines `float getDistance(vec3 p)` function.
* This function is used to estimate distance.
*
* e.g.
* ```glsl
* float getDistance(vec3 p) {
* p = mod(p, 0.5) - 0.25;
* return length(p) - 0.1;
* }
* ```
*/
getDistanceChunk?: string,
getMaterialChunk?: string,
/**
* Color of the material, by default set to white (0xffffff).
* Equivalent to [MeshStandardMaterial.color](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.color).
*/
color?: Color,
/**
* Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.
* Equivalent to [MeshStandardMaterial.emissive](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.emissive).
*/
emissive?: Color,
/**
* How much the material is like a metal.
* Non-metallic materials such as wood or stone use 0.0, metallic use 1.0, with nothing (usually) in between.
* Default is 0.5. A value between 0.0 and 1.0 could be used for a rusty metal look.
* Equivalent to [MeshStandardMaterial.metalness](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.metalness).
*/
metalness?: number,
/**
* How rough the material appears.
* 0.0 means a smooth mirror reflection, 1.0 means fully diffuse.
* Default is 0.5.
* Equivalent to [MeshStandardMaterial.roughness](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.roughness).
*/
roughness?: number,
envMap?: CubeTexture | null,
reflectivity?: number,
refractionRatio?: number,
combine?: number,
}
/**
* A material for object space raymarching equivalent to [MeshStandardMaterial](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial).
*
* **Usage:**
*
* ```typescript
* import { Scene, Vector3, Color } from 'three';
* import { ObjectSpaceRaymarch, ObjectSpaceRaymarchStandardMaterial } from 'three-raymarch';
* const material = new ObjectSpaceRaymarchStandardMaterial({
* getDistanceChunk: `
* float getDistance(vec3 p) {
* p = mod(p, 0.5) - 0.25;
* return length(p) - 0.1;
* }`,
* size: new Vector3(5, 5, 5),
* metalness: 0.5,
* roughness: 0.5,
* });
* const raymarch = new ObjectSpaceRaymarch(material);
* const scene = new Scene();
* scene.add(raymarch);
* ```
*/
export class ObjectSpaceRaymarchStandardMaterial extends ObjectSpaceRaymarchMaterial {
constructor(parameters: ObjectSpaceRaymarchStandardMaterialParameters = {}) {
const overrideChunks: {[key: string]: string} = {};
if (parameters.getDistanceChunk) {
overrideChunks['distance_pars_fragment'] = parameters.getDistanceChunk;
}
if (parameters.getMaterialChunk) {
overrideChunks['physical_get_material_pars_fragment'] = parameters.getMaterialChunk;
}
super(
RaymarchShaderChunk['raymarch_physical_frag'],
overrideChunks,
Object.assign({}, parameters, {
uniforms: UniformsUtils.merge([
parameters.uniforms ? parameters.uniforms : {},
UniformsLib.lights,
UniformsLib.fog,
UniformsLib.envmap,
{
'diffuse': { value: parameters.color ? parameters.color : new Color(0xffffff) },
'emissive': { value: parameters.emissive ? parameters.emissive : new Color(0x000000) },
'metalness': { value: parameters.metalness !== undefined ? parameters.metalness : 0.5 },
'roughness': { value: parameters.roughness !== undefined ? parameters.roughness : 0.5 },
// override UniformsLib.envmap
'envMap': { value: parameters.envMap ? parameters.envMap : null },
'reflectivity': { value: parameters.reflectivity !== undefined ? parameters.reflectivity : 1.0 },
'refractionRatio': { value: parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98 },
}
]),
}),
);
this.envMap = parameters.envMap ? parameters.envMap : null;
this.combine = parameters.combine ? parameters.combine : MultiplyOperation;
this.lights = true;
this.fog = true;
}
/**
* Color of the material, by default set to white (0xffffff).
* Equivalent to [MeshStandardMaterial.color](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.color).
*/
get color(): Color {
return this.uniforms['diffuse'].value;
}
set color(color: Color) {
this.uniforms['diffuse'].value = color.clone();
}
/**
* Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.
* Equivalent to [MeshStandardMaterial.emissive](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.emissive).
*/
get emissive(): Color {
return this.uniforms['emissive'].value;
}
set emissive(emissive) {
this.uniforms['emissive'].value = emissive.clone();
}
/**
* How much the material is like a metal.
* Non-metallic materials such as wood or stone use 0.0, metallic use 1.0, with nothing (usually) in between.
* Default is 0.5. A value between 0.0 and 1.0 could be used for a rusty metal look.
* Equivalent to [MeshStandardMaterial.metalness](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.metalness).
*/
get metalness(): number {
return this.uniforms['metalness'].value;
}
set metalness(metalness: number) {
this.uniforms['metalness'].value = metalness;
}
/**
* How rough the material appears.
* 0.0 means a smooth mirror reflection, 1.0 means fully diffuse.
* Default is 0.5.
* Equivalent to [MeshStandardMaterial.roughness](https://threejs.org/docs/index.html#api/en/materials/MeshStandardMaterial.roughness).
*/
get roughness(): number {
return this.uniforms['roughness'].value;
}
set roughness(roughness: number) {
this.uniforms['roughness'].value = roughness;
}
get envMap(): CubeTexture | null {
return this.uniforms['envMap'].value;
}
set envMap(envMap: CubeTexture | null) {
this.uniforms['envMap'].value = envMap;
this.needsUpdate = true;
}
combine: number;
get reflectivity(): number {
return this.uniforms['reflectivity'].value;
}
set reflectivity(reflectivity: number) {
this.uniforms['reflectivity'].value = reflectivity;
}
get refractionRatio(): number {
return this.uniforms['refractionRatio'].value;
}
set refractionRatio(refractionRatio: number) {
this.uniforms['refractionRatio'].value = refractionRatio;
}
}
|
76ba38d7b4667f0e5da3d3956a1cdfc8f41f01a9
|
TypeScript
|
fang-wenlee/typescript
|
/class/objectType.ts
| 3.15625
| 3
|
function user( employee:{first:string; last:string; age:number}): string{
return `Hello ${employee.first} ${employee.last}`;
}
console.log(user({first: "Fang-Wen", last: "Lee", age: 30}))
|
38de35e93d9f4d356b23f17ccf3e1f69d9ed873a
|
TypeScript
|
zaknafain/kings-duty
|
/src/app/events/time-event.ts
| 3.234375
| 3
|
import {
TimeEventAction,
GainPeopleAction,
MovePeopleAction,
LoosePeopleAction
} from './time-event-action';
export interface TimeEvent {
title: string;
description: string;
day: number;
eventActions: TimeEventAction[];
}
export class NewcommerArrivingEvent implements TimeEvent {
title = 'Newcommers are arriving';
description = '';
day = 0;
eventActions = [];
constructor() {
const people = (Math.random() * 90) + 10;
this.day = Math.floor(Math.random() * 100);
this.eventActions.push(new GainPeopleAction({ people, x: 0, y: 0 }));
this.description = `There are some newcommers arriving at your village.
They have survived the wilderness for so long and swear to you if let them in.
There are ${Math.floor(people)} people waiting for you to let them in.`;
}
}
export class PeopleFeelCrowdedEvent implements TimeEvent {
title = 'The people feel crowded';
description = '';
day = 0;
eventActions = [];
constructor(dayNow: number, x: number, y: number) {
const people = (Math.random() * 50) + 20;
this.day = dayNow;
this.eventActions.push(new MovePeopleAction({ people, x, y }));
this.eventActions.push(new LoosePeopleAction({ people: people / 5, x, y }));
this.description = `Some of your people don't feel comfortable anymore.
They wish to leave their homes and found a new one nearby.
If you allow them to leave the will found a new settlement for your realm.
Should you force them to stay, some of them will possibly leave your realm forever.`;
}
}
export class PeopleMovedEvent implements TimeEvent {
title = 'People moved to a different location';
description = '';
day = 0;
eventActions = [];
constructor(dayNow: number, people: number) {
this.day = dayNow;
this.description = `${Math.floor(people)} people left their homes and moved to a different location.`;
}
}
export class PeopleGoneEvent implements TimeEvent {
title = 'People left your realm';
description = '';
day = 0;
eventActions = [];
constructor(dayNow: number, people: number) {
this.day = dayNow;
this.description = `${Math.floor(people)} people were unhappy with your rule and left your society.`;
}
}
|
208fdff77c48dc9d10ceda384aeec80502522c58
|
TypeScript
|
rzmay/rmps
|
/packages/module/src/types/dynamicValue.ts
| 2.65625
| 3
|
export type dynamicValue<T> =
T
| ((t: number) => dynamicValue<T>)
| [dynamicValue<T>, dynamicValue<T>];
|
4a0225095818f503cf7a7b7ad06fbbc33086b9e3
|
TypeScript
|
IronOnet/codebases
|
/codebases/coursera.org/static/bundles/naptimejs/resources/promotionDetails.v1.ts
| 2.609375
| 3
|
import NaptimeResource from './NaptimeResource';
export type DiscountAmount = { [currencyCode: string]: number };
class PromotionDetails extends NaptimeResource {
static RESOURCE_NAME = 'promotionDetails.v1';
// These properties are always included.
id!: string;
// These properties must be requested.
promotionName?: string;
promotionDescription?: string;
discountPercent?: number;
discountAmount?: DiscountAmount;
startsAt?: number;
endsAt?: number;
promotionId?: number;
static byPromoCodeId(id: string, opts: { [key: string]: string | number | boolean | Array<string> }) {
return this.finder('byPromoCodeId', Object.assign({ params: { id } }, opts), (promoDetails) => promoDetails?.[0]);
}
}
export default PromotionDetails;
|
89a1c2908a8ea6a3075c27bfb38d7454edb45d6b
|
TypeScript
|
HanqingZ/Angular_Study
|
/video-courses/src/app/tools/pipes/duration.pipe.ts
| 2.84375
| 3
|
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: 'sortByDuration'
})
export class DurationPipe implements PipeTransform {
transform(length: number): string {
if (length >= 0 && length / 60 > 1) {
return `${Math.floor(length / 60)}h ${length % 60}min`;
} else if (length < 0) {
return "0 min";
}
return `${length} min`;
}
}
|
a38be0d75e2b95992c3bcc9dd22265e58c5af8ee
|
TypeScript
|
pulumi/pulumi-awsx
|
/awsx-classic/codebuild/metrics.ts
| 2.515625
| 3
|
// Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
import * as cloudwatch from "../cloudwatch";
export namespace metrics {
type CodebuildMetricName =
"BuildDuration" | "Builds" | "DownloadSourceDuration" | "Duration" |
"FailedBuilds" | "FinalizingDuration" | "InstallDuration" |
"PostBuildDuration" | "PreBuildDuration" | "ProvisioningDuration" |
"QueuedDuration" | "SubmittedDuration" | "SucceededBuilds" | "UploadArtifactsDuration";
export interface CodebuildMetricChange extends cloudwatch.MetricChange {
/**
* Optional Project this metric should be filtered down to.
*/
project?: aws.codebuild.Project;
}
/**
* Creates an AWS/CodeBuild metric with the requested [metricName]. See
* https://docs.aws.amazon.com/codebuild/latest/userguide/monitoring-builds.html for list of all
* metric-names.
*
* Note, individual metrics can easily be obtained without supplying the name using the other
* [metricXXX] functions.
*
* You can use Amazon CloudWatch to watch your builds, report when something is wrong, and take
* automatic actions when appropriate. You can monitor your builds at two levels:
*
* * At the project level: These metrics are for all builds in the specified project only. To see
* metrics for a project, specify the ProjectName for the dimension in CloudWatch.
*
* * At the AWS account level: These metrics are for all builds in one account. To see metrics at
* the AWS account level, do not enter a dimension in CloudWatch.
*
* CloudWatch metrics show the behavior of your builds over time. For example, you can monitor:
*
* * How many builds were attempted in a build project or an AWS account over time.
* * How many builds were successful in a build project or an AWS account over time.
* * How many builds failed in a build project or an AWS account over time.
* * How much time CodeBuild spent executing builds in a build project or an AWS account over time.
*
* Metrics displayed in the CodeBuild console are always from the past three days. You can use the
* CloudWatch console to view CodeBuild metrics over different durations.
*
* "ProjectName" is the only AWS CodeBuild metrics dimension. If it is specified, then the metrics
* are for that project. If it is not specified, then the metrics are for the current AWS account.
*/
function metric(metricName: CodebuildMetricName, change: CodebuildMetricChange = {}) {
const dimensions: Record<string, pulumi.Input<string>> = {};
if (change.project !== undefined) {
dimensions.ProjectName = change.project.name;
}
return new cloudwatch.Metric({
namespace: "AWS/CodeBuild",
name: metricName,
...change,
}).withDimensions(dimensions);
}
/**
* Measures the duration of the build's BUILD phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function buildDuration(change?: CodebuildMetricChange) {
return metric("BuildDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the number of builds triggered.
*
* Units: Count
* Valid CloudWatch statistics: Sum
*/
export function builds(change?: CodebuildMetricChange) {
return metric("Builds", { statistic: "Sum", unit: "Count", ...change });
}
/**
* Measures the duration of the build's DOWNLOAD_SOURCE phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function downloadSourceDuration(change?: CodebuildMetricChange) {
return metric("DownloadSourceDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of all builds over time.
*
* Units: Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function duration(change?: CodebuildMetricChange) {
return metric("Duration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the number of builds that failed because of client error or because of a timeout.
*
* Units: Count
* Valid CloudWatch statistics: Sum
*/
export function failedBuilds(change?: CodebuildMetricChange) {
return metric("FailedBuilds", { statistic: "Sum", unit: "Count", ...change });
}
/**
* Measures the duration of the build's FINALIZING phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function finalizingDuration(change?: CodebuildMetricChange) {
return metric("FinalizingDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's INSTALL phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function installDuration(change?: CodebuildMetricChange) {
return metric("InstallDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's POST_BUILD phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function postBuildDuration(change?: CodebuildMetricChange) {
return metric("PostBuildDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's PRE_BUILD phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function preBuildDuration(change?: CodebuildMetricChange) {
return metric("PreBuildDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's PROVISIONING phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function provisioningDuration(change?: CodebuildMetricChange) {
return metric("ProvisioningDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's QUEUED phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function queuedDuration(change?: CodebuildMetricChange) {
return metric("QueuedDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the duration of the build's SUBMITTED phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function submittedDuration(change?: CodebuildMetricChange) {
return metric("SubmittedDuration", { statistic: "Average", unit: "Seconds", ...change });
}
/**
* Measures the number of successful builds.
*
* Units: Count
* Valid CloudWatch statistics: Sum
*/
export function succeededBuilds(change?: CodebuildMetricChange) {
return metric("SucceededBuilds", { statistic: "Sum", unit: "Count", ...change });
}
/**
* Measures the duration of the build's UPLOAD_ARTIFACTS phase.
*
* Units:Seconds
* Valid CloudWatch statistics: Average (recommended), Maximum, Minimum
*/
export function uploadArtifactsDuration(change?: CodebuildMetricChange) {
return metric("UploadArtifactsDuration", { statistic: "Average", unit: "Seconds", ...change });
}
}
|
9a5e799afcfb037306ccd08a3f7948e93da90eb1
|
TypeScript
|
MarcosSpessatto/Rocket.Chat
|
/apps/meteor/ee/app/license/server/getTagColor.ts
| 2.5625
| 3
|
export function getTagColor(tag: string): string {
switch (tag) {
case 'bronze':
return '#BD5A0B';
case 'silver':
return '#9EA2A8';
case 'gold':
return '#F3BE08';
default:
return '#4411DD';
}
}
|
044f510b4f914420353e071e281f94bbbeb4f9ef
|
TypeScript
|
TsapovMaksim/codmark-tz
|
/src/redux/ducks/images/types.ts
| 2.78125
| 3
|
import { Action } from 'redux';
export enum ImagesActionsType {
SET_IMAGES = 'images/SET_IMAGES',
SET_LOADING_STATE = 'images/SET_LOADING_STATE',
FETCH_IMAGES = 'images/FETCH_IMAGES',
CLEAR_IMAGES = 'images/CLEAR_IMAGES',
SET_GROUP_IMAGES = 'images/SET_GROUP_IMAGES',
}
export interface ImageInterface {
imageUrl: string;
tag: string;
id: string;
}
export type LoadingStateType =
| 'never'
| 'loading'
| 'loaded'
| 'error'
| 'not found';
export interface FetchImagesActionInterface extends Action<ImagesActionsType> {
type: ImagesActionsType.FETCH_IMAGES;
payload: string[];
}
export interface SetImagesActionInterface extends Action<ImagesActionsType> {
type: ImagesActionsType.SET_IMAGES;
payload: ImageInterface[];
}
export interface SetLoadingStateActionInterface
extends Action<ImagesActionsType> {
type: ImagesActionsType.SET_LOADING_STATE;
payload: LoadingStateType;
}
export interface ClearImagesActionInterface extends Action<ImagesActionsType> {
type: ImagesActionsType.CLEAR_IMAGES;
}
export interface SetGroupImagesActionInterface
extends Action<ImagesActionsType> {
type: ImagesActionsType.SET_GROUP_IMAGES;
payload: boolean;
}
export type ImagesActions =
| SetImagesActionInterface
| SetLoadingStateActionInterface
| ClearImagesActionInterface
| SetGroupImagesActionInterface
| FetchImagesActionInterface;
|
f9c48656925b9fcb0910ea0fb7d0963bef660477
|
TypeScript
|
SunshineH2/pont
|
/packages/pont-engine/src/compatible/clean.ts
| 2.734375
| 3
|
import * as fs from 'fs';
import * as path from 'path';
import type { Manager } from './Manager';
import { main } from './scan';
import { Interface } from './standard';
/** 入口方法 */
export async function clean(manager: Manager) {
const unusedJsonPath = `./${manager.unusedJsonFileName}`;
const suffix = manager.currConfig.templatePath === 'javaScript' ? 'js' : 'ts';
const isExists = fs.existsSync(unusedJsonPath);
if (isExists) {
// 先读取到文件内容
const unusedJsonData = JSON.parse(fs.readFileSync(unusedJsonPath, 'utf8')) as Interface[];
unusedJsonData.forEach((ele) => {
// 文件路径
const paths = [manager.currConfig.outDir, ele.originName, 'mods', ele.modName, `${ele.name}.${suffix}`];
// 最后一级是ts文件
const currentFilePath = path.join(...paths);
const existResult = fs.existsSync(currentFilePath);
if (existResult) {
fs.unlinkSync(currentFilePath);
// 判断文件夹目录下是否只有一个index.ts文件
const currentDirPath = path.join(...paths.slice(0, paths.length - 1));
const dirData = fs.readdirSync(currentDirPath);
// 说明只有一个index.ts文件了直接删除文件夹,否则重写index.ts
if (dirData.length === 1) {
fs.unlinkSync(path.join(...paths.slice(0, paths.length - 1), `index.${suffix}`));
fs.rmdirSync(currentDirPath);
// 此处还需要判断一下mods下的index.ts文件
const currentModDirPath = path.join(...paths.slice(0, paths.length - 2));
const modDirData = fs.readdirSync(currentModDirPath);
const modDir = modDirData.filter((i) => i !== `index.${suffix}`);
const modDirStr = modDir.map((i) => `import * as ${i} from './${i}';`).join('\n');
const str = `${modDirStr}
export const ${ele.originName} = {
${modDir.join(', \n')}
}
`;
fs.writeFileSync(path.join(...paths.slice(0, paths.length - 2), `index.${suffix}`), str);
} else {
// 剔除掉index.ts文件
const dirFiles = dirData.filter((i) => i !== `index.${suffix}`);
const fileStr = dirFiles
.map((item) => `import * as ${item.split('.')?.[0]} from './${item.split('.')?.[0]}';`)
.join('\n');
const totalStr = `${fileStr}
export {
${dirFiles.map((i) => i.split('.')?.[0]).join(', \n')}
}
`;
fs.writeFileSync(path.join(...paths.slice(0, paths.length - 1), `index.${suffix}`), totalStr);
}
}
});
fs.unlinkSync(unusedJsonPath);
} else {
main(manager);
clean(manager);
}
}
|
46c508b888b0e22fa90e154bcac0934854274f17
|
TypeScript
|
arthur-iasbeck/book-store-app
|
/src/users/users.service.ts
| 2.78125
| 3
|
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { BookEntity } from 'src/db/book.entity'
import { UserEntity } from 'src/db/user.entity'
import { Repository } from 'typeorm'
import { GetAndReturnBooksDto } from './dto/get-return-books.dto'
@Injectable()
export class UsersService {
constructor(
@InjectRepository(UserEntity)
private usersRepository: Repository<UserEntity>,
@InjectRepository(BookEntity)
private bookRepository: Repository<BookEntity>,
) {}
async findAll(): Promise<UserEntity[]> {
// Busca pelos usuários do banco (sem as listas de livros a eles associadas)
let users = await this.usersRepository.find()
// Busca pelos livros associados a cada um dos usuários
let usersWithBooks: UserEntity[] = []
for (let user of users) {
let books = await this.bookRepository.find({
where: {
user: user,
},
})
user.books = books
usersWithBooks.push(user)
}
return usersWithBooks
}
async findUserById(id: number): Promise<UserEntity> {
// Busca pelos usuários de id correspondente
let user = await this.usersRepository.findOne(id)
// Busca pelos livros associados ao usuário encontrado
let books = await this.bookRepository.find({
where: {
user: user,
},
})
user.books = books
return user
}
async createUser(userToCreate: UserEntity): Promise<UserEntity> {
console.log('Entrando no createUser()...')
console.log('userToCreate')
console.log(userToCreate)
const user: UserEntity = UserEntity.create()
let book: BookEntity
let books: BookEntity[] = []
for (let bookId of userToCreate.books) {
book = await this.bookRepository.findOne(bookId)
console.log('book = ')
console.log(book)
books.push(book)
}
console.log('books')
console.log(books)
user.name = userToCreate.name
user.books = books
console.log('user = ')
console.log(user)
this.usersRepository.save(user)
return user
}
async returnBooks(userIdAndBooksToReturn: GetAndReturnBooksDto) {
let book: BookEntity
// Determinação do usuáio que está devolvendo os livros
let user = await this.findUserById(userIdAndBooksToReturn.userId)
// Determinação dos livros que o usuário pegou emprestado
let borrowedBooks = await this.bookRepository.find({
where: {
user: user,
},
})
let borrowBooksIds = borrowedBooks.map(borrowedBook => borrowedBook.id)
let booksToReturnIds = userIdAndBooksToReturn.booksIds
console.log('user.books = ')
console.log(user.books)
console.log(`borrowBooksIds = ${borrowBooksIds}`)
console.log(`booksToReturnIds = ${booksToReturnIds}`)
for (let i in borrowBooksIds) {
if (booksToReturnIds.includes(borrowBooksIds[i])) {
user.books.splice(parseInt(i), 1)
}
}
console.log('user = ')
console.log(user)
this.usersRepository.save(user)
return user
}
async borrowBooks(userIdAndBooksToBorrow: GetAndReturnBooksDto) {
let book: BookEntity
// Determinação do usuário que está pegando os livros emprestado
let user = await this.findUserById(userIdAndBooksToBorrow.userId)
// Determinação dos livros que o usuário já pegou emprestado
let borrowedBooks = await this.bookRepository.find({
where: {
user: user,
},
})
let borrowBooksIds = borrowedBooks.map(borrowedBook => borrowedBook.id)
// Combinação entre os livros já pegos e aqueles a serem pegos
let booksToBorrowIds = userIdAndBooksToBorrow.booksIds
let bookToBorrow: BookEntity
for (let bookToBorrowId of booksToBorrowIds) {
if (!borrowBooksIds.includes(bookToBorrowId)){
bookToBorrow = await this.bookRepository.findOne(bookToBorrowId)
borrowedBooks.push(bookToBorrow)
}
}
user.books = borrowedBooks
// Armazenamento do novo usuário, contendo os livros locados
this.usersRepository.save(user)
return user
}
async deleteUser(id: number) {
this.usersRepository.delete(id)
}
}
|
15db6f9b022306b0e1566b23df7b225f23b722d7
|
TypeScript
|
ngnhuuthai/nodesrv
|
/src/check/builder/checkComponent.ts
| 3.078125
| 3
|
import { CheckType } from "../enum/checkType"
export default class CheckComponent<T> {
public readonly isRequired: boolean
constructor(
public readonly checkType: CheckType,
public readonly confirm: boolean,
private readonly thing: T,
public readonly failMessage?: string) {
this.isRequired = this.failMessage !== undefined
}
public getThing(captured?: any, lastThing?: any): any {
if (this.confirm) {
return this.calculateThing(captured, lastThing)
}
return !this.calculateThing(captured, lastThing)
}
private calculateThing(captured?: any, lastThing?: any) {
if (typeof this.thing === "function") {
return this.thing(captured ? captured : lastThing, lastThing)
}
return this.thing
}
}
|
bd2a7749ad12eb238e3b4b5a913e04e3b3bd3fb4
|
TypeScript
|
villehietanen/test
|
/src/models/flight.ts
| 2.75
| 3
|
import * as mongoose from 'mongoose';
export interface IFlight extends mongoose.Document {
departure: string,
arrival: string,
departureDate: Date,
arrivalDate: Date
}
export const FlightSchema = new mongoose.Schema({
departure: {type: String, required: true, minlength: 3, maxlength: 3},
arrival: {type: String, required: true, minlength: 3, maxlength: 3},
departureDate: {type: Date, required: true},
arrivalDate: {type: Date, required: true},
});
const Flight = mongoose.model<IFlight>('Flight', FlightSchema);
export default Flight;
|
9f97ab0bd39a93a700f4bd5b257621df43e969a4
|
TypeScript
|
EduardoAraD/Backend-mars-photos
|
/src/utils/timeAtualization.ts
| 2.6875
| 3
|
import ApiController from '../controllers/ApiController'
const main = async () => {
const data = new Date()
data.setHours(data.getHours() - 3)
console.log(`Atualizando: ${data.getHours()}:${data.getMinutes()}`)
await ApiController.getApi()
}
// milissegundos(1000) - segundos(60) - minutos(60) - horas(24)
export default setInterval(main, 1000 * 60 * 60 * 24) // 24 horas
|
ffb2d1f1ac54d35fe418831473eca928ecc29893
|
TypeScript
|
sebamomann/anmeldesystem-backend
|
/src/modules/enrollment/enrollmentPermission.checker.ts
| 2.71875
| 3
|
import {JWT_User} from '../user/user.model';
import {Enrollment} from './enrollment.entity';
export class EnrollmentPermissionChecker {
private enrollment;
constructor(enrollment: Enrollment) {
this.enrollment = enrollment;
}
/**
* Check if {@link JWT_User} is the creator of of the {@link Enrollment}
*
* @param user {@link JWT_User} to check ownership for
*/
public userIsCreator(user: JWT_User) {
if (!user) {
return false;
}
return this.enrollment.creatorId === user.sub;
}
}
|
32b47ea00ba591ef50d83a83c8353661653e29f1
|
TypeScript
|
triviality-js/triviality
|
/packages/core/src/Context/ConstructContext.ts
| 3.15625
| 3
|
import { ServiceFactory, ServiceTag, SF } from '../ServiceFactory';
import { ServiceFunctionReferenceContainerInterface } from '../Container/ServiceFunctionReferenceContainerInterface';
/**
* Context for constructing new services.
*/
export interface ConstructContext<T> {
/**
* @typeGenerator({
* empty: true,
* templates: [
* " construct<{{T% extends keyof T}}, F extends new ({{d%: T[T%]}}) => S, S>(F: F, {{t%: T%}}): SF<S>;\n"
* ],
* })
*/
construct<F extends new () => S, S>(F: F): SF<S>;
construct<T1 extends keyof T, F extends new (d1: T[T1]) => S, S>(F: F, t1: T1): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, F extends new (d1: T[T1], d2: T[T2]) => S, S>(F: F, t1: T1, t2: T2): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3]) => S, S>(F: F, t1: T1, t2: T2, t3: T3): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, T6 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5], d6: T[T6]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, T6 extends keyof T, T7 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5], d6: T[T6], d7: T[T7]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, T6 extends keyof T, T7 extends keyof T, T8 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5], d6: T[T6], d7: T[T7], d8: T[T8]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, T6 extends keyof T, T7 extends keyof T, T8 extends keyof T, T9 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5], d6: T[T6], d7: T[T7], d8: T[T8], d9: T[T9]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9): SF<S>;
construct<T1 extends keyof T, T2 extends keyof T, T3 extends keyof T, T4 extends keyof T, T5 extends keyof T, T6 extends keyof T, T7 extends keyof T, T8 extends keyof T, T9 extends keyof T, T10 extends keyof T, F extends new (d1: T[T1], d2: T[T2], d3: T[T3], d4: T[T4], d5: T[T5], d6: T[T6], d7: T[T7], d8: T[T8], d9: T[T9], d10: T[T10]) => S, S>(F: F, t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7, t8: T8, t9: T9, t10: T10): SF<S>;
}
export const createFeatureFactoryConstructContext = ({ getService }: ServiceFunctionReferenceContainerInterface) => ({
construct: constructServiceByTags(getService),
});
export const constructServiceByTags = (getServiceFactory: (tag: ServiceTag) => ServiceFactory) => <Service>(
serviceFactory: new(...a: any) => Service,
...tags: string[]): SF<Service> =>
() => new serviceFactory(...tags.map(getServiceFactory).map((sf) => sf()));
|
30a187ad777eac968fd062889f52e820c46927fd
|
TypeScript
|
Sora2455/JavaScript-Experiments
|
/src/modules/ClientClipboard.ts
| 2.875
| 3
|
/**Copy text into the user's cliplboard
* @param text The text to copy into the user's clipboard
* @link Solution taken from https://stackoverflow.com/a/30810322/7077589
*/
export function copyTextToClipboard(text: string): void {
if (window.isSecureContext && navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text);
} else {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand("copy");
} finally {
document.body.removeChild(textArea);
}
}
}
|
19459b80a82d6f917dbaf467fed99068b6c27044
|
TypeScript
|
lucas-eugenio/GrabMdApp
|
/utils/useStorage.ts
| 2.546875
| 3
|
import AsyncStorage from '@react-native-async-storage/async-storage';
const useStorage = () => {
const save = (value: string, key: string): Promise<void> => {
return AsyncStorage.setItem(key, value);
};
const load = (key: string): Promise<string | null> => {
return AsyncStorage.getItem(key);
};
const erase = (key: string): Promise<void> => {
return AsyncStorage.removeItem(key);
};
return { save, load, erase };
};
export default useStorage;
|
00d30adef8e4ed69352075f04c9f0d3ce847fcd5
|
TypeScript
|
Jacks128/tytusx
|
/20211SVAC/G35/codigof/src/ejecucion/expresiones/arreglo.ts
| 2.78125
| 3
|
import { Entorno } from "../entorno";
import { Instruccion } from "../instruccion";
import { Arreglo as InstanciaArreglo } from '../arreglo';
export class Arreglo extends Instruccion {
lista_expresiones: Array<Instruccion>;
constructor(linea : string, lista_expresiones: Array<Instruccion> = null){
super(linea);
this.lista_expresiones = lista_expresiones;
}
ejecutar(e: Entorno) {
const arreglo = [];
this.lista_expresiones?.forEach((item : Object) => {
if(item instanceof Instruccion){
const valor = item.ejecutar(e);
arreglo.push(valor);
}
});
return new InstanciaArreglo(arreglo);
}
}
|
216a08d77300e57973a4ec7ede53f2a4136dc028
|
TypeScript
|
ViniciusFernando13/startaideia-react-forms
|
/src/rules/isLength.ts
| 3.34375
| 3
|
import isLength from "validator/lib/isLength"
import trim from "validator/lib/trim"
import { Rule } from "rules"
export default function ({ value, params }: Rule): String | null {
const str = trim(String(value))
const { exact } = params
if (str.length === 0) return null
if (exact && str.length === exact) {
return null
} else if (exact && str.length !== exact) {
return `O campo precisa ter ${exact} caracteres`
}
if (!isLength(str, params as any)) {
const { min, max }: any = params
if (min && max) {
return `O campo precisa ter entre ${min} e ${max} caracteres`
} else if (min) {
return `O campo precisa ter no mínimo ${min} caracteres`
} else {
return `O campo precisa ter no máximo ${max} caracteres`
}
}
return null
}
|
72a61141a52cea5366a3428c7283868d3ab7d721
|
TypeScript
|
ruanvalente/nestjs-playground
|
/src/user/services/user.service.ts
| 2.515625
| 3
|
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entity/user.entity';
import { UserDTO } from './../dto/user';
import { UserRepository } from '../repository/user.repository';
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
) {}
async store(userDTO: UserDTO): Promise<User> {
if (!userDTO) {
throw new HttpException(
'This field cannot be blank',
HttpStatus.BAD_REQUEST,
);
} else {
return await this.userRepository.store(userDTO);
}
}
async index(): Promise<User[]> {
return await this.userRepository.index();
}
async show(id: string): Promise<User> {
return await this.userRepository.show(id);
}
async updated(id: string, userRequest: UserDTO): Promise<User> {
return await this.userRepository.updated(id, userRequest);
}
async destroy(id: string): Promise<void> {
await this.userRepository.destroy(id);
}
}
|
bdf1c6e26be085128780398fba7373ef0e7ecd89
|
TypeScript
|
rohith231/backendM
|
/user/user.service.ts
| 2.609375
| 3
|
import { Injectable, Inject } from "@nestjs/common";
import { User } from "./user.entity";
import { AuthService } from "../auth/auth.service";
import * as _ from "lodash";
import { Repository } from "typeorm";
@Injectable()
export class UserService {
constructor(
@Inject("USER_REPOSITORY")
private userRepository: Repository<User>,
private authService: AuthService
) {}
async findOne(req: any): Promise<User> {
return await this.userRepository.findOne(req);
}
async findById(id: string) {
return await this.userRepository.findOne(id);
}
async createUser(user): Promise<User> {
// const hashedPassword = await this.authService.hashPassword(user.password);
// const updatatedUser = { password: hashedPassword };
// user = _.extend(user, updatatedUser);
user.attempts = 0;
return this.userRepository.save(user);
}
async updateOne(where: any, update: any) {
return await this.userRepository.update(where, update)
}
isUser(obj: any): obj is User {
return "primaryMobileNo" in obj;
}
isProfileComplete(user: User) {
const { address1, zip, securityAnswer1, securityAnswer2, securityAnswer3 } =
user;
return (
address1 != null &&
zip != 0 &&
securityAnswer1 != null &&
securityAnswer2 != null &&
securityAnswer3 != null
);
}
async deleteUser(id):Promise<any>{
return await this.userRepository.delete(id);
}
}
|
f23f5e73a95ccdef4b014eb3a78d1d821e1bc2f4
|
TypeScript
|
Jacob273/JG.TechLearning.Angular.AuctionApp
|
/typescript-starter/src/B-typescript/as-module/Car.ts
| 3.078125
| 3
|
export class Car {
private name: string;
constructor() {
this.name = 'My superCar'
}
changeCarName(name: string) {
this.name = name;
}
shoutMyName() {
console.log(this.name)
}
}
|
9b509510d6a708ea1578074e670edf15ffc2f60c
|
TypeScript
|
cethack/FOO
|
/src/core/components/cetselect/selectItem.service.ts
| 3.03125
| 3
|
export class SelectItem {
_id: string;
_text: string;
_displayText: string;
static idPropertyName: string = 'id';
static textPropertyName: string = 'text';
constructor(source: any) {
if (typeof source === 'string') {
this.id = this.text = this.displayText = source;
}
if (typeof source === 'object') {
this.id = source[SelectItem.idPropertyName] || source[SelectItem.textPropertyName];
this.text = source[SelectItem.textPropertyName];
// TODO make an input for display text format
this.displayText = source[SelectItem.idPropertyName] + ' ' + source[SelectItem.textPropertyName];
this.displayText = this.displayText.trim();
}
}
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value;
}
get text(): string {
return this._text;
}
set text(value: string) {
this._text = value;
}
get displayText(): string {
return this._displayText;
}
set displayText(text: string) {
this._displayText = text;
}
}
|
abbf58c5236eb33156f4e30ee3dd40c5582d7ee9
|
TypeScript
|
codeartisticninja/1gam17_april
|
/src/script/_classes/lib/WebStory/Teller.ts
| 2.78125
| 3
|
"use strict";
import WebStory = require("./WebStory");
/**
* Teller class
*
* @date 21-mar-2017
*/
var tellers:Teller[] = [];
class Teller {
public interval:number;
constructor(public story:WebStory, public element:HTMLElement) {
this.hurry = this.hurry.bind(this);
this.interval = this.story.impatience ? 128 : (this.story.get("_interval") || Math.max(element.textContent.length*80, 1024));
}
init() {
this.appendElement();
this.wait();
}
wait(interval=this.interval) {
this.interval=interval;
if (this.interval > -1) {
this._hurryTO = setTimeout(this.hurry, this.interval);
}
}
pause() {
clearTimeout(this._hurryTO);
}
goOn() {
if (this.interval === -1) {
this.hurry();
}
}
hurry() {
this.story.continue(this);
}
appendElement() {
return this.story.appendElement(this.element);
}
removeElement() {
if (this.element.dataset["_teller"]) {
tellers[parseInt(this.element.dataset["_teller"])] = null;
this.element.dataset["_teller"] = undefined;
}
this.element.parentElement.removeChild(this.element);
}
registerToElement() {
if (!this.element.dataset["_teller"]) {
var i = tellers.indexOf(null);
if (i !== -1) {
this.element.dataset["_teller"] = "" + i;
tellers[i] = this;
} else {
this.element.dataset["_teller"] = "" + tellers.length;
tellers.push(this);
}
}
}
getTellerFromElement(element:HTMLElement) {
return tellers[parseInt(element.dataset["_teller"])];
}
reevaluate() {
this.element.innerHTML = this.story.currentElement.innerHTML;
this.story.evaluate(this.element);
}
/*
_privates
*/
private _hurryTO:any;
}
export = Teller;
|
e69ef561fc5eb72150a5613141fbe5deb1e20b06
|
TypeScript
|
stevejay/because-npm-api
|
/src/node-service/mapper.test.ts
| 2.90625
| 3
|
import * as mapper from "./mapper";
const INDEXED_REACT_NODE = {
id: "react",
link: "//react",
score: 0,
isNew: false
};
const UNINDEXED_REACT_NODE = {
id: "react",
link: "//react",
score: 0,
isNew: true
};
const INDEXED_REDUX_NODE = {
id: "redux",
link: "//redux",
score: 1,
isNew: false
};
const UNINDEXED_REDUX_NODE = {
id: "redux",
link: "//redux",
score: 1,
isNew: true
};
describe("mapGetNodesResultToNodes", () => {
it("should map", () => {
const getNodesResult = {
nodes: [
{
id: "react",
description: "some description",
link: "//react",
score: 0.5
}
]
};
const actual = mapper.mapGetNodesResultToNodes(getNodesResult);
expect(actual).toEqual([
{
id: "react",
description: "some description",
link: "//react",
score: 0.5,
isNew: false
}
]);
});
});
describe("mapNodeInfoToFindReferencedNodesResult", () => {
test.each([
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[],
[],
null
],
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[],
[UNINDEXED_REDUX_NODE],
null
],
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[INDEXED_REACT_NODE],
[],
null
],
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[INDEXED_REACT_NODE],
[UNINDEXED_REDUX_NODE],
{ tailNode: INDEXED_REACT_NODE, headNode: UNINDEXED_REDUX_NODE }
],
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[INDEXED_REDUX_NODE, INDEXED_REACT_NODE],
[],
{ tailNode: INDEXED_REACT_NODE, headNode: INDEXED_REDUX_NODE }
],
[
{
comment: "some text",
tailNodeId: "react",
headNodeId: "redux"
},
[],
[UNINDEXED_REDUX_NODE, UNINDEXED_REACT_NODE],
{ tailNode: UNINDEXED_REACT_NODE, headNode: UNINDEXED_REDUX_NODE }
]
])(
"should map tweet %o with indexed nodes %o and unindexed nodes %o to %o",
(parsedTweetResult, indexedNodes, unindexedNodes, expected) => {
const actual = mapper.mapNodeInfoToFindReferencedNodesResult(
parsedTweetResult,
indexedNodes,
unindexedNodes
);
expect(actual).toEqual(expected);
}
);
});
|
054a83ae1b7e97bc92b1a02e2bc1575157ef71c1
|
TypeScript
|
ejrbuss/dnd-initiative-tracker
|
/src/Actor.ts
| 2.84375
| 3
|
import { Util } from './util';
import { Template } from './Template';
import { Lang } from './Lang';
let uidCounter = 0;
export interface Actor {
template: Template;
uid: number;
name: string;
initiative: number;
description: string;
note: string;
npc: {
autokill: boolean;
hitPoints: number;
} | null;
}
const init = (template: Template): Actor => {
const actor: Actor = {
template,
uid: uidCounter++,
name: template.name,
initiative: parseFloat(Lang.evaluate(template.initiative.toString())),
description: template.description,
note: '',
npc: template.npc ? {
autokill: template.npc.autokill,
hitPoints: parseFloat(Lang.evaluate(template.npc.hitPoints.toString())),
} : null,
};
if (Number.isNaN(actor.initiative)) {
throw 'Invalid initiative value!';
}
if (actor.npc && Number.isNaN(actor.npc.hitPoints)) {
throw 'Invalid hit points value!';
}
return actor;
};
const epsilon = 0.001;
const after = (a: Actor, b: Actor): Actor =>
Util.merge(a, { initiative: b.initiative - epsilon });
const before = (a: Actor, b: Actor): Actor =>
Util.merge(a, { initiative: b.initiative + epsilon });
export const Actor = { uidCounter, init, after, before };
|
9e1c9365f5220f4fb54caa23d9819453767d8439
|
TypeScript
|
sepp2k/IffyPiffy
|
/runtime/runtime.ts
| 3.203125
| 3
|
interface IffyPiffyObject {
$init(): this;
$needsInit: boolean;
$objectName: string;
$onInherit?(child: IffyPiffyObject): void;
}
interface IffyPiffyVerb extends IffyPiffyObject {
syntax: (string|IffyPiffyThing)[];
defaultAction(): void;
}
interface IffyPiffyThing extends IffyPiffyObject {
name: string;
description: string;
}
interface IffyPiffyRoom extends IffyPiffyThing {
description: string;
items: IffyPiffyItem[];
}
interface IffyPiffyItem extends IffyPiffyThing {
}
let verbs: IffyPiffyVerb[] = [];
let things: IffyPiffyThing[] = [];
export namespace globals {
export let startingRoom: IffyPiffyRoom;
export function say(...strs: string[]) {
latestMessage += str(...strs) + "\n";
}
export function str(...strs: string[]) {
return strs.join("");
}
export function playSound(soundFile: string) {
if (typeof Audio !== "undefined") {
new Audio(resourceDir + "/" + soundFile).play();
}
}
export let Object = {
$init() {
this.$needsInit = false;
},
$objectName: "Object"
} as IffyPiffyObject;
export let Thing = inherit(Object, "Thing", function () {
onHandlers.push([examine, this, function() {
say(init(this).description);
}]);
});
Thing.$onInherit = function (child: IffyPiffyThing) {
things.push(child);
};
export let Item = inherit(Thing, "Item", function () {});
export let Room = inherit(Thing, "Room", function () {
this.items = [];
});
export let Verb = inherit(Object, "Verb", function () {});
Verb.$onInherit = function (child: IffyPiffyVerb) {
verbs.push(child);
};
export let examine = inherit(Verb, "examine", function () {
this.syntax = ["examine", Item];
this.defaultAction = function () {
say("You don't see that anywhere.");
};
});
export let quit = inherit(Verb, "quit", function () {
this.syntax = ["quit"];
this.defaultAction = function () {
say("Goodbye!");
isFinished = true;
};
});
}
function enterRoom(room: IffyPiffyRoom) {
latestMessage += init(room).description;
if (room.items && room.items.length > 0) {
latestMessage += "\n\nYou see here:\n";
for (let i = 0; i < room.items.length - 1; i++) {
latestMessage += init(room.items[i]).name + ", ";
}
latestMessage += "and " + init(room.items[room.items.length - 1]).name + ".";
}
}
let latestMessage: string = "";
let isFinished = false;
let resourceDir = ".";
export let onHandlers: [IffyPiffyVerb, IffyPiffyThing, () => void][] = [];
export function init<T extends IffyPiffyObject>(obj: T): T {
if (typeof obj === "object" && obj.$needsInit) {
obj.$init();
for (let member in obj) {
// I can't be arsed to make the types work here
init(obj[member] as any);
}
}
return obj;
}
export function inherit(parent: IffyPiffyObject, objectName: string, initializer: () => void) {
let child = Object.create(parent);
child.$parent = parent;
child.$needsInit = true;
child.$objectName = objectName;
child.$init = function () {
parent.$init.call(this);
initializer.call(this);
return this;
};
// Only built-in objects have a custom $onInherit handler, so any other object simply
// inherits the one from its parent.
child.$onInherit = parent.$onInherit;
if(parent.$onInherit) parent.$onInherit(child);
return child;
}
function simplifyObject(obj: string) {
return obj.replace(/\s*\b(the|a|an)\b\s*/, "").toLowerCase();
}
export class Story {
title: string;
description: string;
room: IffyPiffyRoom;
isFinished: boolean;
latestMessage: string;
initializer: () => void;
constructor(title: string, description: string, initializer: () => void) {
this.title = title;
this.description = description;
this.initializer = initializer;
}
start(_resourceDir = ".") {
isFinished = false;
this.initializer();
this.room = init(globals.startingRoom);
latestMessage = "";
resourceDir = _resourceDir;
enterRoom(this.room);
this.latestMessage = latestMessage;
this.isFinished = isFinished;
}
private handleInput(command: string) {
latestMessage = "";
let tokens = command.split(/\s+/);
if (tokens.length >= 2) {
let [verb, ...objectParts] = tokens;
let objectName = simplifyObject(objectParts.join(" "));
for (let [handlerVerb, handlerObject, handler] of onHandlers) {
if(handlerObject.name === undefined) continue;
let handlerObjectName = simplifyObject(handlerObject.name);
if (init(handlerVerb).syntax[0] === verb && handlerObjectName === objectName) {
handler.call(handlerObject);
return;
}
}
}
for (let verb of verbs) {
if (init(verb).syntax[0] === tokens[0]) {
verb.defaultAction();
return;
}
}
globals.say("I'm sorry, but I could not understand you.");
}
input(command: string) {
latestMessage = "";
this.handleInput(command);
this.latestMessage = latestMessage;
this.isFinished = isFinished;
}
}
|
ab32e070eb9e7233ee93537ada1234f90cc9e384
|
TypeScript
|
Weakky/woopwoop
|
/plugin/types.ts
| 2.53125
| 3
|
import { ArgDefinition } from 'gqliteral/dist/types'
interface GenTypesShape {
fields: Record<string, any>
aliases: Record<string, any>
objects: Record<string, any>
}
export interface ObjectField {
name: string
args?: string[] | false
alias?: string
}
export type AnonymousField = string | ObjectField
export interface AnonymousAliasField {
name: string
alias: string
}
export interface AnonymousPickOmitField {
pick?: AnonymousField[]
omit?: AnonymousField[]
}
export interface AnonymousAliases {
aliases: AnonymousAliasField[]
}
export type AnonymousInputFields =
| AnonymousField[]
| AnonymousAliases
| AnonymousPickOmitField
export interface AnonymousFieldDetails {
[key: string]: {
args: Record<string, ArgDefinition>
description?: string
list: boolean
resolve: (root: any, args: any, ctx: any, info?: any) => any
}
}
export type InputField<
GenTypes = GraphQLiteralGen,
TypeName extends string = any
> = GenTypes extends GenTypesShape
? TypeName extends keyof GenTypes['fields']
? GenTypes['fields'][TypeName]
: AnonymousField
: AnonymousField
export type AliasField<
GenTypes = GraphQLiteralGen,
TypeName extends string = any
> = GenTypes extends GenTypesShape
? TypeName extends keyof GenTypes['aliases']
? GenTypes['aliases'][TypeName]
: AnonymousAliasField
: AnonymousAliasField
export type PrismaTypeNames<
GenTypes = GraphQLiteralGen
> = GenTypes extends GenTypesShape
? Extract<keyof GenTypes['fields'], string>
: string
export interface AliasesField<GenTypes, TypeName extends string> {
aliases: AliasField<GenTypes, TypeName>[]
}
export interface PickOmitField<GenTypes, TypeName extends string> {
omit?: InputField<GenTypes, TypeName>[]
pick?: InputField<GenTypes, TypeName>[]
}
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR<T, U> = (T | U) extends object
? (Without<T, U> & U) | (Without<U, T> & T)
: T | U
export type AddFieldInput<GenTypes, TypeName extends string> =
| InputField<GenTypes, TypeName>[]
| XOR<PickOmitField<GenTypes, TypeName>, AliasesField<GenTypes, TypeName>>
export type PrismaObject<
GenTypes,
TypeName extends string
> = GenTypes extends GenTypesShape
? TypeName extends keyof GenTypes['objects']
? GenTypes['objects'][TypeName]
: any
: any
|
3e2eac357ef9e965911479ca996a98dc314b0381
|
TypeScript
|
acamposdev/crm-alpha-front
|
/src/app/services/cases.service.ts
| 2.515625
| 3
|
import { throwError as observableThrowError, Observable , Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { END_POINT } from '../config/config';
import { Case } from '../models/case';
import { PopupMessageService } from '../components/popup-message/popup-message.service';
@Injectable()
export class CasesService {
private $cases: Subject<Case[]> = new Subject<Case[]>();
constructor(
private http: HttpClient,
private popupMessage: PopupMessageService
) {
console.log('CasesService - constructor');
}
loadCases(customerId: string) {
return this.http.get(END_POINT + 'api/v1/cases?customerId=' + customerId);
}
loadCase(caseId: any) {
return this.http.get(END_POINT + 'api/v1/cases/' + caseId);
}
save(caseToSave: Case) {
return this.http.post(END_POINT + 'api/v1/cases', caseToSave).pipe(
map((result) => {
this.loadCases(caseToSave.customerId).subscribe((cases: Case[]) => {
this.setCases(cases);
this.popupMessage.popup('success', 'Caso guardado corectamente!');
});
}),
catchError(err => {
this.popupMessage.popup('danger', err.message);
return observableThrowError(err);
})
);
}
setCases(cases: Case[]) {
this.$cases.next(cases);
}
getCasesObservable(): Observable<Case[]> {
return this.$cases.asObservable();
}
}
|
55fbc3532ae06679be71884b31f4a9f66a50fba0
|
TypeScript
|
AndyLnd/jumpnjuice
|
/src/utils/objects.ts
| 3.109375
| 3
|
import { pipe } from './common'
// tslint:disable:no-object-mutation no-any readonly-array no-unbound-method prefer-for-of no-let typedef
export interface PlainObject {
readonly [prop: string]: any
}
export type Diff<
T extends string | number | symbol,
U extends string | number | symbol
> = ({ [P in T]: P } & { [P in U]: never } & { readonly [x: string]: never })[T]
export type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>
export const pluck = <T extends PlainObject, K extends keyof T>(keys: K[]) => (
arr: ReadonlyArray<T>,
): ReadonlyArray<Pick<T, K>> => {
const result: Array<Pick<T, K>> = []
for (const e of arr) {
result.push(
pipe(
e,
pick(...keys),
),
)
}
return result
}
// tslint:disable-next-line:typedef
export const pick = <T extends PlainObject, K extends keyof T>(
...keys: K[]
) => (obj: T): Pick<T, K> => {
const result: any = {}
for (const k of keys) {
result[k] = obj[k]
}
return result
}
export const merge = <T1 extends PlainObject, T2 extends PlainObject>(
obj1: T1,
) => (obj2: T2): T1 & T2 => {
const result: any = {}
Object.assign(result, obj1)
Object.assign(result, obj2)
return result
}
// export const mergeDefaults = <T extends PlainObject>(obj: T) => (
// defaults: Partial<T>,
// ): T => pipe(defaults, merge(obj))
export const update = <T extends PlainObject, K extends keyof T, T2>(
k: K,
f: (x: T[K]) => T2,
) => (obj: T): T2 => {
const result: any = {}
Object.assign(result, obj)
result[k] = f(obj[k])
return result
}
export const omit = <T extends PlainObject, K extends keyof T>(
...keys: K[]
) => (obj: T): Omit<T, K> => {
const result: any = {}
for (const k in obj) {
if (obj.hasOwnProperty(k) && keys.indexOf(k as any) === -1) {
result[k] = obj[k]
}
}
return result
}
export const keys = <T extends PlainObject>(obj: T): ReadonlyArray<string> =>
Object.keys(obj)
// copied from fbjs
const hasOwnProperty = Object.prototype.hasOwnProperty
export const shallowEqual = <T extends PlainObject>(obj1: T) => (
obj2: T,
): boolean => {
if (obj1 === obj2) {
return true
}
// not needed in typescript
if (
typeof obj1 !== 'object' ||
obj1 === null ||
typeof obj2 !== 'object' ||
obj2 === null
) {
return false
}
const keysA = Object.keys(obj1)
const keysB = Object.keys(obj2)
if (keysA.length !== keysB.length) {
return false
}
for (let i = 0; i < keysA.length; i += 1) {
if (
!hasOwnProperty.call(obj2, keysA[i]) ||
obj1[keysA[i]] !== obj2[keysA[i]]
) {
return false
}
}
return true
}
|
3a3e46046f80052cf23d638147126a04ba375d10
|
TypeScript
|
apurvaraman/AssemblyScript
|
/dist/assemblyscript-loader.d.ts
| 2.8125
| 3
|
// Generated by dts-bundle v0.7.3
// Dependencies for this module:
// ../../long
declare module 'assemblyscript-loader' {
import * as Long from "long";
/** Options to set up the environment created by {@link load}. */
export interface ILoadOptions {
/** Memory instance to import, if applicable. */
memory?: WebAssembly.Memory;
/** Imported elements. Usually functions. */
imports?: { [key: string]: any }
}
/** Number memory accessor. */
export interface INumberMemoryAccessor {
/** Gets a value of the underlying type from memory at the specified pointer. */
get(ptr: number): number;
/** Sets a value of the underlying type in memory at the specified pointer. */
set(ptr: number, value: number): void;
}
/** Long memory accessor. */
export interface ILongMemoryAccessor {
/** Gets a Long from memory at the specified pointer. */
get(ptr: number): Long;
/** Sets a Long in memory at the specified pointer. */
set(ptr: number, value: Long): void;
}
/** Array memory accessor. */
export interface IArrayMemoryAccessor {
/** Gets an array from memory at the specified pointer and returns its length and element base pointer. */
get(ptr: number): { length: number, base: number };
/** Creates an array in memory and returns its pointer and element base pointer. */
create(length: number, elementByteSize: number): { ptr: number, base: number };
}
/** String memory accessor. */
export interface IStringMemoryAccessor {
/** Gets a string from memory at the specified pointer. */
get(ptr: number): string;
/** Creates a string in memory and returns its pointer. */
create(value: string): number;
}
/** Common module interface as returned by {@link load}. */
export interface IModule {
/** A reference to the underlying memory instance. */
memory: WebAssembly.Memory;
/** An unsigned byte view on the underlying memory. Note that this view is updated when memory grows, hence make sure to always access it on the module instance directly. */
buffer: Uint8Array;
/** Imported elements. Usually functions. */
imports: { [key: string]: any };
/** Exported elements. Usually functions. */
exports: { [key: string]: any };
/** Gets the current size of the memory in 64kb pages. */
currentMemory(): number;
/** Grows the memory by the specified number of 64kb pages. */
growMemory(numPages: number): number;
/** Signed 8-bit integer accessors. */
sbyte: INumberMemoryAccessor;
/** Signed 8-bit integer accessors. Alias of `sbyte`. */
s8: INumberMemoryAccessor;
/** Unsigned 8-bit integer accessors. */
byte: INumberMemoryAccessor;
/** Unsigned 8-bit integer accessors. Alias of `byte`. */
u8: INumberMemoryAccessor;
/** Signed 16-bit integer accessors. */
short: INumberMemoryAccessor;
/** Signed 16-bit integer value accessors. Alias of `short`. */
s16: INumberMemoryAccessor;
/** Unsigned 16-bit integer accessors. */
ushort: INumberMemoryAccessor;
/** Unsigned 16-bit integer accessors. Alias of `ushort`. */
u16: INumberMemoryAccessor;
/** Signed 32-bit integer accessors. */
int: INumberMemoryAccessor;
/** Signed 32-bit integer accessors. Alias of `int`. */
s32: INumberMemoryAccessor;
/** Unsigned 32-bit integer accessors. */
uint: INumberMemoryAccessor;
/** Unsigned 32-bit integer accessors. Alias of `uint`. */
u32: INumberMemoryAccessor;
/** Signed 64-bit integer accessors. */
long: ILongMemoryAccessor;
/** Signed 64-bit integer accessors. Alias of `long`. */
s64: ILongMemoryAccessor;
/** Unsigned 64-bit integer accessors. */
ulong: ILongMemoryAccessor;
/** Unsigned 64-bit integer accessors. Alias of `ulong`. */
u64: ILongMemoryAccessor;
/** 32-bit float accessors. */
float: INumberMemoryAccessor;
/** 32-bit float accessors. Alias of `float`. */
f32: INumberMemoryAccessor;
/** 64-bit float accessors. */
double: INumberMemoryAccessor;
/** 64-bit float accessors. Alias of `double`. */
f64: INumberMemoryAccessor;
/** Array accessors. */
array: IArrayMemoryAccessor;
/** String accessors. */
string: IStringMemoryAccessor;
}
/** Loads a WebAssembly module either from a buffer or from a file and returns a promise for an {@link IModule}. */
export function load(file: ArrayBuffer | Uint8Array | string, options?: ILoadOptions): Promise<IModule>;
export { load as default };
}
|
46c084e53442d3af20d59462db8807187b4a4bdb
|
TypeScript
|
anetegithub/geranium
|
/storage/interfaces/IStorage.ts
| 2.578125
| 3
|
import { InterfaceUsingException } from "../../exceptions/coherence/InterfaceUsingException";
import { Constructor } from "../../structures/Constructor";
import { IInjected } from "../../coherence/interfaces/IInjected";
import { ICoherenceContainer } from "../../coherence/interfaces/ICoherenceContainer";
import { IEntity } from "./IEntity";
export class IStorage implements IInjected {
["`container"]: ICoherenceContainer;
add<T extends IEntity>(model: T): boolean { throw new InterfaceUsingException("IStorage.add"); }
remove<T extends IEntity>(id: number): boolean { throw new InterfaceUsingException("IStorage.remove"); }
get<T extends IEntity>(id: number): T { throw new InterfaceUsingException("IStorage.get"); }
all<TT extends IEntity>(): IEntity[] { throw new InterfaceUsingException("IStorage.all"); }
}
|
a747c55a594673e9be380e1a212dd200a4ac1049
|
TypeScript
|
socramjunio2/http-aws-api-node
|
/http-aws-api-node/src/http/json/serializers/impl/date-serializer.ts
| 3.1875
| 3
|
import * as moment from "moment-timezone";
const TZ = "America/Sao_Paulo";
const TZ_UTC = process.env.TZ || "America/Sao_Paulo";
export class DateSerializer {
/**
* converte um Date para uma string
* @param source Date a ser convertida
* @param pattern mascara a ser utilizada, default: "YYYY-MM-DDTHH:mm:ss"
* @param timezone caso se deseje utilizar timezone na serializacao. Default: false
*/
public serialize(source: Date, timezone?: boolean, pattern?: string): string {
if (source) {
pattern = pattern ? pattern : "YYYY-MM-DDTHH:mm:ss";
if (timezone) {
return moment(source).tz(TZ).format(pattern);
}
return moment(source).tz(TZ_UTC).format(pattern);
}
}
}
|
eef043fe86bb75ecd60a138bd545461125f72861
|
TypeScript
|
javascript-ninja-123/event-bus-example
|
/ticket/src/nats-wrapper.ts
| 2.671875
| 3
|
import nats, {Stan} from "node-nats-streaming"
export class NatsWrapper {
private static instance: NatsWrapper
private static _client?: Stan
private constructor(){}
public connect(clusterId: string, clientId: string, url: string): Promise<void>{
NatsWrapper._client = nats.connect(clusterId,clientId, {url})
if(!NatsWrapper._client){
throw new Error("failed to connect")
}
return new Promise((resolve,reject) => {
NatsWrapper._client!.on("connect", () => {
console.log("connected to NATS")
resolve()
})
NatsWrapper._client!.on("error", (err) => {
console.log("NATS error occured")
reject(err)
})
})
}
public static getInstance(): NatsWrapper {
if(!NatsWrapper.instance){
NatsWrapper.instance = new NatsWrapper()
}
return NatsWrapper.instance
}
public get client(): Stan{
if(!NatsWrapper._client) throw new Error("not nats")
return NatsWrapper._client
}
}
export const natsWrapper = NatsWrapper.getInstance()
|
386a5134469c78afbbf3b5c9f4df05cbc2fe6832
|
TypeScript
|
jamesblunt1973/davajoo-dashboard-web
|
/src/app/shared/components/counter/counter.component.ts
| 2.515625
| 3
|
import { Component, OnChanges, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.scss']
})
export class CounterComponent implements OnInit, OnChanges {
@Input() number = 0;
digits: Array<string> = [];
constructor() { }
ngOnInit() {
}
ngOnChanges() {
var numStr = this.number.toString();
while (numStr.length < 3) numStr = "0" + numStr;
this.digits = numStr.split('').reverse();
}
}
|
dbfac5f21fc5a825f12788ee55140b0bf2fd056d
|
TypeScript
|
DuffyWang926/sharingHomes
|
/src/features/header/reducer.ts
| 2.75
| 3
|
import { combineReducers } from 'redux';
import { ActionType } from 'typesafe-actions';
import * as header from './actions';
import { CHANGETAB, LOGIN_SUCCESS } from './constants';
export type HeaderAction = ActionType<typeof header>;
export interface user {
name:string
}
export type HeaderState = {
readonly tabKey: number;
readonly user: user;
};
export default combineReducers<HeaderState, HeaderAction>({
tabKey: (state = 0, action) => {
switch (action.type) {
case CHANGETAB:
return action.payload;
default:
return state;
}
},
user: (state = {name:''}, action) => {
switch (action.type) {
case LOGIN_SUCCESS:
const {name} = action.payload
return {name};
default:
return state;
}
},
});
|
4b9ffdc9b09598288d2ac8932247d38856cf5706
|
TypeScript
|
lifeart/els-addon-typed-templates
|
/app/components/component.ts
| 2.75
| 3
|
import Component from '@glimmer/component';
type Args = {
userId: string,
userEmail: string
}
export default class MyComponent extends Component {
args!: Args;
name = 1;
noob = 2;
items = [1, 2, 3];
userName
= 3;
names() {
}
item = {
name: 'boo',
user: {
pets: 12
},
age: 42
}
}
|
de7dda82266576e25a73235ecf614ad026fe5333
|
TypeScript
|
tkpea/PhotoFilterTest
|
/src/library/imageFilter/offsetFilters.ts
| 2.75
| 3
|
const extremeOffsetBlue = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 35
imgData.data[i + 2] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const extraOffsetBlue = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 15
imgData.data[i + 2] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const extremeOffsetGreen = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 35
imgData.data[i + 1] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const extraOffsetGreen = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 15
imgData.data[i + 1] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const extremeOffsetRed = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 35
imgData.data[i] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const extraOffsetRed = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 15
imgData.data[i] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const offset = (imgData: ImageData) => {
console.log('offset called')
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 5
imgData.data[i] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const offsetGreenImgData = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 5
imgData.data[i + 1] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
const offsetBlueImgData = (imgData: ImageData) => {
for (let i = 0; i < imgData.data.length; i += 4) {
const offset = 5
imgData.data[i + 2] =
imgData.data[i + 4 * offset * offset] === undefined
? 0
: imgData.data[i + 4 * offset]
}
return imgData
}
export {
offset,
extraOffsetBlue,
extraOffsetGreen,
extraOffsetRed,
extremeOffsetBlue,
extremeOffsetGreen,
extremeOffsetRed,
offsetGreenImgData,
offsetBlueImgData
}
|
89f682dad03d5b0a1da84b4e3c7491635615bce2
|
TypeScript
|
xiadom/rabb
|
/src/gl-utils/MiscUtils.ts
| 2.90625
| 3
|
type MiscIndexObject = {
indices: number[];
position: number[];
texcoord: number[]
}
export function mapIndices2d(object: MiscIndexObject, prop: string) {
return Array.prototype.reduce.call(object.indices, (acc, id) =>
acc.concat([
object[prop][3 * id],
object[prop][3 * id + 1],
])
, [])
}
export function mapIndices3d(object: MiscIndexObject, prop: string) {
return Array.prototype.reduce.call(object.indices, (acc, id) =>
acc.concat([
object[prop][3 * id],
object[prop][3 * id + 1],
object[prop][3 * id + 2],
])
, [])
}
|
726d70dff27cdcc1c498978b874ae0b97e5a09d6
|
TypeScript
|
clizreynolds/ionic-todo
|
/src/pages/step-counter/step-counter.ts
| 2.8125
| 3
|
import { Component, ChangeDetectorRef } from '@angular/core';
import { Pedometer } from '@ionic-native/pedometer';
import { Platform } from 'ionic-angular';
/**
* Page to display the step counter data and sprite
*
* @export
* @class StepCounterPage
*/
@Component({
selector: 'step-counter',
templateUrl: 'step-counter.html'
})
export class StepCounterPage {
/**
* Intial step count is 0
*
* @memberof StepCounterPage
*/
steps = 0;
/**
* Inital step goal
*
* @type {number}
* @memberof StepCounterPage
*/
goal: number = 10000;
/**
* Percentage of the goal that has been met
*
* @type {number}
* @memberof StepCounterPage
*/
percentage: number;
/**
* Static sprite image source
*
* @memberof StepCounterPage
*/
staticSprite = 'assets/imgs/static-cat-right.gif';
/**
* Running sprite image source
*
* @memberof StepCounterPage
*/
runningSprite = 'assets/imgs/running-cat-right.gif';
/**
* The sprite source that is currently being displayed, initialised as static
*
* @memberof StepCounterPage
*/
spriteSource = this.staticSprite;
/**
* The data object received from the pedometer
*
* @type {*}
* @memberof StepCounterPage
*/
data: any;
/**
* Creates an instance of StepCounterPage. Starts listening for pedometer updates
* @param {ChangeDetectorRef} ref
* @param {Platform} platform
* @param {Pedometer} pedometer
* @memberof StepCounterPage
*/
constructor(private ref: ChangeDetectorRef,
public platform: Platform,
public pedometer: Pedometer) {
this.pedometer.startPedometerUpdates()
.subscribe((data) => {
this.data = data;
this.steps = data.numberOfSteps;
this.setPercentage();
this.ref.detectChanges();
// on walk - trigger sprite walk
this.triggerWalk();
});
this.goal = 10000;
this.setPercentage();
}
/**
* When walking is detected, trigger sprite change
*
* @memberof StepCounterPage
*/
triggerWalk() {
this.spriteSource = this.runningSprite;
setTimeout(() => {
this.spriteSource = this.staticSprite;
}, 3000);
}
/**
* The current percentage of steps the user has taken to reach their goal
*
* @memberof StepCounterPage
*/
setPercentage() {
this.percentage = (this.steps / this.goal) * 100;
}
}
|
68d3140fc1db4411ba35db55cdc7fb2b007ea062
|
TypeScript
|
Deltanic/mathrix
|
/src/convert.ts
| 2.734375
| 3
|
import { AxisOrder } from './enums';
import Vector3 from './primitives/Vector3';
import Quaternion from './primitives/Quaternion';
import Matrix4 from './primitives/Matrix4';
// -----------------------------------------------------------------------------
export function convertVector3ToQuaternion(vec3: Vector3, axisOrder: AxisOrder) {
return new Quaternion(1, 2, 3, 4);
}
export function convertVector3ToMatrix4(vec3: Vector3, axisOrder: AxisOrder) {
return new Matrix4([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]);
}
// -----------------------------------------------------------------------------
export function convertQuaternionToVector3(quat: Quaternion) {
return new Vector3(1, 2, 3);
}
export function convertQuaternionToMatrix4(quat: Quaternion) {
return new Matrix4([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]);
}
// -----------------------------------------------------------------------------
export function convertMatrix4ToVector3(mat4: Matrix4) {
return new Vector3(1, 2, 3);
}
export function convertMatrix4ToQuaternion(mat4: Matrix4) {
return new Quaternion(1, 2, 3, 4);
}
|
dd387838943d77f6bcbd339bb573e91d84a1139e
|
TypeScript
|
screendriver/verify-github-webhook-secret
|
/test/integration/verify.test.ts
| 2.53125
| 3
|
import test from "ava";
import http from "node:http";
import micro from "micro";
import listen from "test-listen";
import got from "got";
import type { Headers } from "got";
import { verifySecret } from "../../src/index.js";
interface TestVerifySecretOptions {
readonly secret: string;
readonly requestBodyJson: unknown;
readonly xHubSignatureHeader?: string;
}
const testVerifySecretMacro = test.macro(async (t, options: TestVerifySecretOptions, isValid: boolean) => {
const { secret, requestBodyJson, xHubSignatureHeader } = options;
const server = new http.Server(
micro.serve(async (request) => {
const valid = await verifySecret(request, secret);
t.is(valid, isValid);
return "";
}),
);
try {
const url = await listen(server);
let headers: Headers | undefined;
if (xHubSignatureHeader !== undefined) {
headers = { "X-Hub-Signature": xHubSignatureHeader };
}
await got.post(url, {
headers,
json: requestBodyJson,
});
} finally {
server.close();
}
});
test(
'returns "false" when "x-hub-signature" header is missing',
testVerifySecretMacro,
{ secret: "my-secret", requestBodyJson: {} },
false,
);
test(
'returns "false" when secret is wrong',
testVerifySecretMacro,
{
secret: "wrong-secret",
requestBodyJson: { foo: "bar" },
xHubSignatureHeader: "sha1=30a233839fe2ddd9233c49fd593e8f1aec68f553",
},
false,
);
test(
'returns "true" when secret is correct',
testVerifySecretMacro,
{
secret: "my-secret",
requestBodyJson: { foo: "bar" },
xHubSignatureHeader: "sha1=30a233839fe2ddd9233c49fd593e8f1aec68f553",
},
true,
);
test("should not hang when verify is called more than once", async (t) => {
const server = new http.Server(
micro.serve(async (request) => {
const valid = await verifySecret(request, "my-secret");
await verifySecret(request, "my-secret");
t.true(valid);
return "";
}),
);
try {
const url = await listen(server);
await got.post(url, {
headers: { "X-Hub-Signature": "sha1=30a233839fe2ddd9233c49fd593e8f1aec68f553" },
json: { foo: "bar" },
});
} finally {
server.close();
}
});
|
5ff407354c20717874d0356430401b43686f75d7
|
TypeScript
|
luna8418/d-emails
|
/src/routes/email.ts
| 2.59375
| 3
|
import { Request, Response } from 'express'
import { Email, EmailItem } from '../types'
import { logger } from '../shared'
import * as emailService from '../services/emailService'
export const sendEmail = async (req: Request, res: Response) => {
const email: Email = req.body
logger.info(`Email received -> ${JSON.stringify(email)}`)
const emailItem: EmailItem = await emailService.handleEmail(email)
logger.info(`Email handled -> ${JSON.stringify(emailItem)}`)
const { id, status } = emailItem
res.status(200).json({ id, status })
}
export const getEmail = async (req: Request, res: Response) => {
const { id } = req.params
logger.debug(`getEmail -> ${id}`)
const email: EmailItem = await emailService.getEmail(id)
if (!email) {
res.status(404).end()
return
}
res.status(200).json({ id, status: email.status })
}
export const deleteEmail = async (req: Request, res: Response) => {
const { id } = req.params
logger.debug(`deleteEmail -> ${id}`)
const email: EmailItem = await emailService.deleteEmail(id)
if (!email) {
res.status(404).end()
return
}
res.status(200).json({ id, deleted: true })
}
|
3ed02cb6fc472bc7437128bcbfea32bfc2bc71e4
|
TypeScript
|
rolznz/infinitris2
|
/core/src/player/NetworkPlayer.ts
| 2.671875
| 3
|
import { PlayerStatus } from '@models/IPlayer';
import ISimulation from '@models/ISimulation';
import Player from './Player';
export default class NetworkPlayer extends Player {
private _socketId: number;
private _isBot: boolean;
constructor(
socketId: number,
simulation: ISimulation,
playerId: number,
status: PlayerStatus,
isBot: boolean,
nickname: string | undefined,
color: number | undefined,
patternFilename?: string,
characterId?: string,
isPremium?: boolean,
isNicknameVerified?: boolean
) {
super(
simulation,
playerId,
status,
nickname,
color,
patternFilename,
characterId,
isPremium,
isNicknameVerified
);
this._socketId = socketId;
this._isBot = isBot;
}
get isNetworked() {
return true;
}
get isBot(): boolean {
return this._isBot;
}
get socketId(): number {
return this._socketId;
}
}
|
3a22bff01fde04bb2da739fc810c7845203dcb4d
|
TypeScript
|
4andrewtanakashi/projetoPraticoModelagem
|
/src/domain/services/search-city.service.ts
| 2.90625
| 3
|
import { City } from '../entities/city';
import { CityNotFoundError } from '../errors/city-not-found.error';
import { CityRepository } from './protocols/city-repository';
export class SearchCityService {
constructor(private readonly cityRepo: CityRepository) {}
async search(query: string): Promise<City[]> {
if (!query || query.trim().length < 3) {
return [];
}
const cities = await this.cityRepo.getAll();
const filteredCities = cities.filter(
(item) => item.name.toLowerCase().indexOf(query.toLowerCase()) > -1
);
if (filteredCities.length == 0) {
throw new CityNotFoundError();
}
return filteredCities;
}
}
|
a2c8cf02d5d519a602f17e95c17fdb9c1feebd6a
|
TypeScript
|
Schr3da/ws-multiplayer-demo
|
/client/src/shared/utils/NetworkUtils.ts
| 2.78125
| 3
|
export interface IRestData<T> {
status: number;
data: T;
}
declare const __FIXED_PORT_9000__;
export const post = <T, K>(url: string, data: T): Promise<K | null> => {
const config: any = {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
return fetch(url, config)
.then(response => response.json())
.then(data => {
if (data.status < 200 || data.status >= 300) {
return null;
}
return data;
});
};
export const getHost = (): string => {
if (__FIXED_PORT_9000__) {
return window.location.hostname + ":9000";
}
return window.location.host;
};
export const getOrigin = (): string => {
if (__FIXED_PORT_9000__) {
return "http://" + window.location.hostname + ":9000";
}
return window.location.origin
};
export const isJson = (data: string): boolean => {
try {
JSON.parse(data);
return true;
} catch {
return false;
}
};
|
b93db09020aa5ecd96674b0c3a3561b08f16dc30
|
TypeScript
|
siminot/log2990-06
|
/client/src/app/carApp/peripheriques/UtilisateurPeripherique.spec.ts
| 2.625
| 3
|
import { UtilisateurPeripherique } from "./UtilisateurPeripherique";
import { GestionnaireClavier } from "../clavier/gestionnaireClavier";
import { EvenementClavier, TypeEvenementClavier, FonctionTouche } from "../clavier/evenementClavier";
describe("UtilisateurPeripherique", () => {
let utilisateur: UtilisateurPeripherique;
it("Constructeur", () => {
utilisateur = new UtilisateurPeripherique(new GestionnaireClavier());
expect(utilisateur).toBeDefined();
});
const FONCTION: Function = UtilisateurPeripherique.prototype.ajouter;
const EVENEMENT_CLAVIER: EvenementClavier = new EvenementClavier("c", TypeEvenementClavier.TOUCHE_APPUYEE);
const FONCTION_TOUCHE: FonctionTouche = new FonctionTouche(FONCTION, EVENEMENT_CLAVIER);
it("Devrait ajouter les evenements", () => {
const TAILLE_AVANT: number = utilisateur["fonctionsEnregistrees"].length;
utilisateur.ajouter(FONCTION, EVENEMENT_CLAVIER);
expect(utilisateur["fonctionsEnregistrees"].length).toEqual(TAILLE_AVANT + 1);
expect(utilisateur["fonctionsEnregistrees"][0].evenement).toEqual(FONCTION_TOUCHE.evenement);
expect(utilisateur["fonctionsEnregistrees"][0].fonction).toEqual(FONCTION_TOUCHE.fonction);
});
it("Devrait supprimer les fonctions", () => {
const TAILLE_AVANT: number = utilisateur["gestionnaire"]["listeRappel"].obtenirFonctions(FONCTION_TOUCHE.evenement).length;
expect(TAILLE_AVANT).toEqual(1);
utilisateur["ngOnDestroy"]();
expect(utilisateur["fonctionsEnregistrees"]).toBe(null);
expect(utilisateur["gestionnaire"]["listeRappel"].obtenirFonctions(FONCTION_TOUCHE.evenement).length).toEqual(TAILLE_AVANT - 1);
});
});
|
96ef393d62192d1ffa8ca4368807b28a1817350b
|
TypeScript
|
nhducit/moai
|
/core/src/tree/utils/remove.ts
| 3.4375
| 3
|
import { TreeNode } from "../tree";
import { isTreeLeaf } from "./leaf";
interface Params {
tree: TreeNode;
deleteId: string;
}
/**
* Remove a node from the tree.
*
* This is a naive implementation that simply traverses all nodes O(n) to
* check for "deleteId". If your "id"s can represent the path, use the
* optimized version which can skip branches O(logN).
*/
export const removeTreeNode = (params: Params): TreeNode => {
const { tree, deleteId } = params;
if (isTreeLeaf(tree)) return tree;
if (tree.children === undefined) return tree;
// @TODO: The performance here is worst
const children = tree.children
.filter((child) => child.id !== deleteId)
.map((child) => removeTreeNode({ tree: child, deleteId }));
return { ...tree, children };
};
|
68a14c13a0bd84f9b5395b0c5f7aee67bf5272c0
|
TypeScript
|
tumachine/image-encrypt
|
/src/app/utils.ts
| 2.5625
| 3
|
// https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
import { Renderer2 } from '@angular/core';
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color
export function invertColor(r: number, g: number, b: number) {
return (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000000' : '#FFFFFF';
}
export function download(renderer: Renderer2, url: string, name: string) {
const a = renderer.createElement('a') as HTMLAnchorElement;
renderer.setStyle(a, 'display', 'hidden');
renderer.appendChild(document.body, a);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
renderer.removeChild(document.body, a);
}
|
2636b222b204079a70aa7bdfa4e7eddf4379685c
|
TypeScript
|
freddy674727/TP2.github.io
|
/src/TP2/relation.ts
| 2.6875
| 3
|
import { DroitProduit } from "./DroitProduit";
const faker = require('faker');
const fs = require('fs');
function relationGen(){
var tableau = [];
for(var index = 0; index < 5 ;index++){
var id = index;
var dateDebut = faker.date.past();
var dateFin = faker.date.future();
var nom = faker.name.firstName();
var description = faker.commerce.productName();
var dp1 = new DroitProduit();
dp1.droit.idDroit = id;
dp1.droit.dateDebut = dateDebut;
dp1.droit.dateFin = dateFin;
dp1.produit.id = id;
dp1.produit.nom = nom;
dp1.produit.description = description;
}
return {"relation": tableau}
}
let dataObj = relationGen();
fs.writeFileSync('tp.json', JSON.stringify(dataObj, null, '\t'));
|