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
|
|---|---|---|---|---|---|---|
ab598cfdf7c14cd32337541c8a92ddeaa6e023bd
|
TypeScript
|
jianhan/tw-syncer
|
/src/users/lookup/Parameters.ts
| 2.84375
| 3
|
import { ArrayMaxSize, ArrayMinSize, ArrayUnique, IsArray, IsBoolean, IsNumber, IsString } from "class-validator";
/**
* Parameters represents twitter api parameters when fetching users, it will be used
* for validations to ensure input parameters all valid before API call.
*
* @export
* @class Parameters
*/
export default class Parameters {
/**
* screen_name is screen_name parameter.
*
* @type string[]
* @memberof Parameters
*/
@IsArray()
@ArrayMaxSize(100)
@ArrayMinSize(1)
@ArrayUnique()
@IsString({ each: true })
// tslint:disable-next-line: variable-name
public screen_name: string[] = [];
/**
* user_id is user_id parameter.
*
* @type number[]
* @memberof Parameters
*/
@IsArray()
@ArrayMaxSize(100)
@ArrayUnique()
@IsNumber({}, { each: true })
// tslint:disable-next-line: variable-name
public user_id: number[] = [];
/**
* include_entities is include_entities parameter.
*
* @type boolean
* @memberof Parameters
*/
@IsBoolean()
// tslint:disable-next-line: variable-name
public include_entities: boolean = false;
/**
* tweet_mode is tweet_mode parameter
*
* @type boolean
* @memberof Parameters
*/
@IsBoolean()
// tslint:disable-next-line: variable-name
public tweet_mode: boolean = false;
}
|
ea1b22db8c2b0575b2409197d32aeae40dd49e1c
|
TypeScript
|
bshawn/sandbox
|
/web-client/src/data/block.ts
| 3.015625
| 3
|
import { GetBlockResult } from "eosjs/dist/eosjs-rpc-interfaces";
interface GetBlockResultWithTransactions extends GetBlockResult {
transactions?: any[];
}
export class Block {
public id: string = "";
public timestamp: string = "";
public previousId: string = "";
public actionCount: number = 0;
public raw: string = "";
public static fromBlockResult(
blockResult: GetBlockResultWithTransactions
): Block {
if (!blockResult) throw new Error("blockResult was null or undefined");
const block = new Block();
block.id = blockResult.id;
block.timestamp = blockResult.timestamp;
block.previousId = blockResult.previous;
block.raw = JSON.stringify(blockResult, null, 2);
block.actionCount = this.calculateActions(blockResult);
return block;
}
private static calculateActions(
blockResult: GetBlockResultWithTransactions
): number {
if (!blockResult.transactions) return 0;
return blockResult.transactions.reduce<number>((prev, current) => {
if (current.trx instanceof Object) {
return current.trx.transaction.actions.length + prev;
}
return 0;
}, 0);
}
}
|
dbaca3c3c279c7f100d221dc00afa91eb12f596d
|
TypeScript
|
aabuhijleh/better-github-profile
|
/src/utils/parseExtendedData.ts
| 2.578125
| 3
|
import { ExtendedData } from "src/types";
export const parseExtendedData = (data: string) => {
try {
return JSON.parse(data) as ExtendedData;
} catch (err) {
console.error("could not parse extended data", err);
return null;
}
};
|
81d4231a027a72ea94c1b01d651e28af0580f0a1
|
TypeScript
|
Edward-Upton/CS261-Software-Engineering
|
/frontend/src/types.d.ts
| 2.796875
| 3
|
export interface IUser {
_id: string;
email: string;
}
export interface IEvent {
_id: string;
name: string;
eventType: string;
start: Date;
end: Date;
host: string | IUser;
participants: string[] | IUser[];
inviteCode: string;
feedback: IField[];
}
export type FieldTypes = "mood" | "rating" | "slider" | "text";
export interface IField {
_id: string;
name: string;
description: string;
fieldType: FieldTypes;
constraints: {
range?: number[];
limit?: number;
}; // This will contain specific constraints for the type of field
data?: {
average: number;
adjFreq?: { word: string; freq: number }[];
keyPhrases?: { phrase: string; date: Date }[];
timeSeries?: { _id: string; value: number; date: Date; num: number }[];
num: number;
};
}
export interface INewField {
// Will have an array of fields
name: string;
description: string;
fieldType: FieldTypes;
constraints: {
range?: number[];
limit?: number;
}; // This will contain specific constraints for the type of field
}
|
6e832bb390757076d990124ffa6b17982bf17483
|
TypeScript
|
Miggslopes/vuestic-ui
|
/packages/docs/src/scripts/generators/documentation.ts
| 2.53125
| 3
|
import { NodePlopAPI, CustomActionFunction, AddActionConfig } from 'plop'
/**
* generator/documentation.js
*
* Exports the generators so plop knows them
*/
// eslint-disable-next-line
const fs = require('fs')
// eslint-disable-next-line
const { execSync } = require('child_process')
// eslint-disable-next-line
const docspageGenerator = require('./docspage')
type GeneratorAnswers = { name: string, category: string, }
const getDirectoryNames = (source: string) => {
return fs.readdirSync(source, { withFileTypes: true })
.filter((dirent: any) => dirent.isDirectory())
.map((dirent: any) => dirent.name)
}
const readFrom = (path: string) => {
const file = fs.readFileSync(path).toString()
return JSON.parse(file)
}
module.exports = (plop: NodePlopAPI) => {
plop.setGenerator('docspage', docspageGenerator)
plop.setActionType('addTranslations', (answers: any, config: any) => {
const directoryNames = getDirectoryNames(config.path)
directoryNames.forEach((language: string) => {
const translationsFilePath = `${config.path}/${language}/${language}.json`
const translationKey = plop.getHelper('camelCase')(answers.name)
const translations = readFrom(translationsFilePath)
const translationsUpdated = {
...translations,
menu: {
...translations.menu,
[translationKey]: plop.getHelper('titleCase')(answers.name),
},
[translationKey]: {
title: '-- Here is the title --',
},
}
fs.writeFileSync(translationsFilePath, JSON.stringify(translationsUpdated, null, 2))
})
return 'Added translations'
})
plop.setActionType('addRoutes', ((answers: GeneratorAnswers, config: AddActionConfig) => {
const navigationSchemePath = `${config.path}/components/sidebar/navigationRoutes.ts`
const navigationScheme = fs.readFileSync(navigationSchemePath).toString()
const routeName = plop.getHelper('kebabCase')(answers.name)
const navItemTranslationString = `menu.${plop.getHelper('camelCase')(answers.name)}`
if (navigationScheme.includes(routeName)) {
throw new Error(`Route ${routeName} already exists.`)
}
const replaceString = `// GENERATOR_ADD - ${answers.category}`
const routeItemString = `{
name: '${routeName}',
displayName: '${navItemTranslationString}',
},
${replaceString}`
const replacedNavigationScheme = navigationScheme.replace(replaceString, routeItemString)
fs.writeFileSync(navigationSchemePath, replacedNavigationScheme)
return 'Added routes'
}) as CustomActionFunction)
plop.setActionType('gitCheck', () => {
const result = execSync('git status --porcelain').toString()
if (result) {
throw new Error('Working tree is dirty: you might want to commit your changes before running the script')
}
return 'Working tree is clean'
})
}
|
60fde774fd1b1c8ba48a327e41e3b1798327d7b7
|
TypeScript
|
brandonpsmith/validasaur
|
/tests/rules/min_length.test.ts
| 2.703125
| 3
|
import { minLength } from "../../src/rules/min_length.ts";
import { invalid } from "../../src/utils.ts";
import { assertInvalid, assertValid, fakeUtils } from "../utils.ts";
import { Validity } from "../../src/types.ts";
Deno.test("rules.minLength(4)(5) should be invalid", () => {
assertInvalid(
minLength(4)(5, fakeUtils) as Validity,
invalid("minLength", { value: 5, minValue: 4 }),
);
});
Deno.test("rules.minLength(4)('foo') should be invalid", () => {
assertInvalid(
minLength(4)("foo", fakeUtils) as Validity,
invalid("minLength", { value: "foo", minValue: 4 }),
);
});
Deno.test("rules.minLength(6)('foobar') should be valid", () => {
assertValid(minLength(6)("foobar", fakeUtils) as Validity);
});
Deno.test("rules.minLength(6)('foobarbaz') should be valid", () => {
assertValid(minLength(6)("foobarbaz", fakeUtils) as Validity);
});
|
0c9346965ce16a900367c51fccfe5f15553e92c0
|
TypeScript
|
koleg-core/api
|
/src/app/organisation.service.ts
| 2.546875
| 3
|
import { Organisation } from "domain/organisation";
import { OrganisationRepository } from "../domain/repos/organisation.repository";
import { Job } from "../domain/user/Job";
import { ReturnCodes } from "../domain/enums/return-codes.enum";
import { ReadableUser } from "../domain/user/ReadableUser";
import { StatelessUser } from "../domain/user/StatelessUser";
import { Group } from "domain/group/Group";
export class OrganisationService {
private _organisation: Organisation;
constructor(
private repository: OrganisationRepository
) { }
// ORGANISATION
public async getName(): Promise<string> {
await this._updateOrganisation();
return this._organisation.getId();
}
// JOBS
public async getJobs(): Promise<Job[]> {
await this._updateOrganisation();
return this._organisation.getJobs();
}
public async getJob(id: string): Promise<Job> {
await this._updateOrganisation();
return this._organisation.getJob(id);
}
public async createJob(job: Job): Promise<{ id: string, error: ReturnCodes }> {
await this._updateOrganisation();
const res = this._organisation.addJob(job);
if (res.id && !res.error) {
this.repository.createJob(job);
}
return res;
}
public async updateJob(job: Job): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.updateJob(job);
if (returnCode === ReturnCodes.UPDATED) {
this.repository.updateJob(job);
}
return returnCode;
}
public async deleteJob(name: string): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.deleteJob(name);
if (returnCode === ReturnCodes.REMOVED) {
this.repository.deleteJob(name);
}
return returnCode;
}
public async getUsersNumberByJob(id: string): Promise<string> {
await this._updateOrganisation();
return this._organisation.getUsersNumberByJob(id)
}
// USERS
public async getUsers(): Promise<ReadableUser[]> {
await this._updateOrganisation();
return this._organisation.getReadableUsers();
}
public async getUserById(id: string): Promise<ReadableUser> {
await this._updateOrganisation();
return this._organisation.getReadableUserById(id);
}
public async getUserByIdWithPassword(id: string): Promise<StatelessUser> {
await this._updateOrganisation();
return this._organisation.getStatelessUserById(id);
}
public async updateUser(user: StatelessUser): Promise<ReturnCodes> {
if (!user) {
throw Error("Invalid user argument user: StatelessUser.");
}
await this._updateOrganisation();
const returnCode = this._organisation.updateUser(user);
if (returnCode === ReturnCodes.UPDATED) {
const userToSave: StatelessUser = this._organisation.getStatelessUserById(user.id);
this.repository.createUser(userToSave);
}
return returnCode;
}
public async updateUserPassword(userId: string, newPassword: string): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.updateUserPassword(userId, newPassword);
if (returnCode === ReturnCodes.UPDATED) {
this.repository.updateUserPassword(userId, newPassword);
return returnCode;
}
}
public async updateUserProfilePictureUrl(userId: string, profilePictureUrl: URL) {
await this._updateOrganisation();
const returnCode = this._organisation.updateUserProfilePictureUrl(userId, profilePictureUrl);
if (returnCode === ReturnCodes.UPDATED) {
const userToSave: StatelessUser = this._organisation.getStatelessUserById(userId);
this.repository.createUser(userToSave);
}
return returnCode;
}
public async findUserByIdentifier(identifier: string): Promise<string> {
await this._updateOrganisation();
return this._organisation.findUserByIdentifier(identifier);
}
public async createUser(user: StatelessUser): Promise<string> {
await this._updateOrganisation();
const userId: string = this._organisation.addUser(user);
if (userId) {
const userToSave: StatelessUser = this._organisation.getStatelessUserById(userId);
this.repository.createUser(userToSave);
return userId;
}
throw new Error("Something was wrong in user creation.");
}
public async deleteUser(id: string): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.deleteUser(id);
if (returnCode === ReturnCodes.REMOVED) {
this.repository.deleteUser(id);
}
return returnCode;
}
public async verifyUserPassword(id: string, password: string): Promise<boolean> {
await this._updateOrganisation();
return this._organisation.verifyUserPassword(id, password);
}
// GROUPS
public async getGroups(): Promise<Group[]> {
await this._updateOrganisation();
return this._organisation.getGroups();
}
public async getGroup(id: string): Promise<Group> {
await this._updateOrganisation();
return this._organisation.getGroup(id);
}
public async createGroup(group: Group): Promise<{ id: string, error: ReturnCodes }> {
await this._updateOrganisation();
const res = this._organisation.addGroup(group);
if (res.id && !res.error) {
this.repository.createGroup(group);
}
return res;
}
public async updateGroup(group: Group): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.updateGroup(group);
if (returnCode === ReturnCodes.UPDATED) {
const groupToSave: Group = this._organisation.getGroupById(group.getId());
this.repository.updateGroup(groupToSave);
}
return returnCode;
}
public async getUsersNumberByGroup(id: string): Promise<string> {
await this._updateOrganisation();
return this._organisation.getUsersNumberByGroup(id)
}
public async deleteGroup(name: string): Promise<ReturnCodes> {
await this._updateOrganisation();
const returnCode = this._organisation.deleteGroup(name);
if (returnCode === ReturnCodes.REMOVED) {
this.repository.deleteGroup(name);
}
return returnCode;
}
public async updateGroupProfilePictureUrl(groupId: string, profilePictureUrl: URL) {
await this._updateOrganisation();
const returnCode = this._organisation.updateGroupProfilePictureUrl(groupId, profilePictureUrl);
if (returnCode === ReturnCodes.UPDATED) {
const groupToSave: Group = this._organisation.getGroupById(groupId);
this.repository.updateGroup(groupToSave);
}
return returnCode;
}
private async _updateOrganisation() {
if (!this._organisation) {
this._organisation = await this.repository.readAsync();
}
}
}
|
f8feec5d409ae8802284df6b88f942c99cdb925c
|
TypeScript
|
ralphschuler/expressions-library-template
|
/src/index.ts
| 2.78125
| 3
|
// Importing object bases (CompBase, LayerBase, PropertyBase)
// TypeScript types (Layer, Comp, Value, Color etc)
// and global functions from 'expression-globals-typescript'
import { Comp, Layer } from 'expression-globals-typescript';
import { fromOtherFile } from './otherFile';
// Creating a new composition object from CompBase
const thisComp = new Comp();
const thisLayer = new Layer();
// Using the expression types in a function
function getLayerDuration(layerName: string) {
const layer: Layer = thisComp.layer(layerName);
return layer.outPoint - layer.inPoint;
}
// Using expressions global functions
function remap(value: number) {
return thisLayer.linear(value, 0, 10, 0, 1);
}
function welcome(name: string): string {
return `Welcome ${name}!`;
}
const someValue: number = 2;
const version: string = '_npmVersion';
// Export values to appear in jsx files
export { getLayerDuration, remap, welcome, someValue, version, fromOtherFile };
|
ac572336fa3e0685a29bf7a4a0cc3a9f520f185d
|
TypeScript
|
htndev/hospital-server
|
/src/common/utils/security.ts
| 2.78125
| 3
|
import { genSalt, hash, compare } from 'bcrypt';
export class Security {
static async cryptPassword(password: string): Promise<string> {
const salt = await genSalt();
return await hash(password, salt);
}
static async comparePasswords(password: string, realPassword: string): Promise<boolean> {
return await compare(password, realPassword);
}
}
|
e02d8549287f3b62c23e3da3f063eb1c8e7da1d5
|
TypeScript
|
cwang22/lean-script
|
/src/index.ts
| 2.859375
| 3
|
import parse from './parser/index'
import compile from './compiler/index'
import Continuation from './util/Continuation'
let stackLength: number
let inExecute: boolean = false
function GUARD(args: Array<any>, f: Function) {
if (--stackLength < 0) throw new Continuation(f, args)
}
function Execute(f: Function, args: Array<any>) {
if (inExecute)
return f.apply(null, args)
inExecute = true
while (true) {
try {
stackLength = 200
f.apply(null, args)
break
} catch (ex) {
if (ex instanceof Continuation) {
f = ex.f
args = ex.args
} else {
inExecute = false
throw ex
}
}
}
inExecute = false
}
export default function (code: string): string {
let res: string
const AST = parse(code)
const jsc = compile(AST)
const func = new Function('LS_TOPLEVEL, GUARD, Execute', jsc)
Execute(func, [
result => {
res = result
},
GUARD,
Execute
])
return res
}
|
1f7bcd5d9b14043120fef94f9442683d6cea6260
|
TypeScript
|
katk0smos/roblox-ts
|
/src/transpiler/spread.ts
| 2.796875
| 3
|
import * as ts from "ts-morph";
import { checkNonAny, transpileCallExpression, transpileExpression } from ".";
import { TranspilerError, TranspilerErrorType } from "../errors/TranspilerError";
import { TranspilerState } from "../TranspilerState";
import {
isArrayType,
isIterableIterator,
isMapType,
isSetType,
isStringType,
isTupleReturnTypeCall,
} from "../typeUtilities";
export function transpileArrayForSpread(state: TranspilerState, expression: ts.Expression) {
const expType = expression.getType();
if (isSetType(expType)) {
state.usesTSLibrary = true;
return `TS.set_values(${transpileExpression(state, expression)})`;
} else if (isMapType(expType)) {
state.usesTSLibrary = true;
return `TS.map_entries(${transpileExpression(state, expression)})`;
} else if (isArrayType(expType)) {
return transpileExpression(state, expression);
} else if (isStringType(expType)) {
return `string.split(${transpileExpression(state, expression)}, "")`;
} else if (isIterableIterator(expType, expression)) {
state.usesTSLibrary = true;
return `TS.iterable_cache(${transpileExpression(state, expression)})`;
} else {
throw new TranspilerError(
`Unable to spread expression of type ${expType.getText()}`,
expression,
TranspilerErrorType.BadSpreadType,
);
}
}
export function transpileSpreadElement(state: TranspilerState, node: ts.SpreadElement) {
const expression = node.getExpression();
checkNonAny(expression, true);
if (ts.TypeGuards.isCallExpression(expression) && isTupleReturnTypeCall(expression)) {
return transpileCallExpression(state, expression, true);
} else {
return `unpack(${transpileArrayForSpread(state, expression)})`;
}
}
|
92b0210c4513f5c4fd3366d7fc58e0a6a42c6a80
|
TypeScript
|
kikarto/zd1
|
/src/libs/board.ts
| 3.015625
| 3
|
import { Model } from '../enums/model';
import { ICard } from '../interfaces/card';
import { IPerson } from '../interfaces/person';
import { IScore } from '../interfaces/score';
import { IStarship } from '../interfaces/starship';
import { checkWhoWin } from './card';
import { Connect } from './connect';
import { parsePerson } from './person';
import { parseStarship } from './starship';
export class Board {
private score: IScore = {
round: 1,
player1: 0,
player2: 0,
};
private model: Model = Model.Person;
private connect: Connect = new Connect();
async play(): Promise<[ICard, ICard]> {
let cards: [ICard, ICard] | undefined;
switch (this.model) {
case Model.Person:
const firstPerson: IPerson = await this.connect.loadPerson();
const secondPerson: IPerson = await this.connect.loadPerson();
if (firstPerson && secondPerson) {
cards = [
parsePerson(firstPerson),
parsePerson(secondPerson),
];
}
break;
case Model.Starship:
const firstStarship: IStarship = await this.connect.loadStarship();
const secondStarship: IStarship = await this.connect.loadStarship();
if (firstStarship && secondStarship) {
cards = [
parseStarship(firstStarship),
parseStarship(secondStarship),
];
}
break;
default:
cards = undefined;
}
if (!cards) {
throw new Error('Models have not been loaded.');
}
// ? checking which card win
const check = checkWhoWin(cards[0], cards[1]);
if (check === 1) {
this.score.player1++;
cards[0].isWin = true;
} else if (check === 2) {
this.score.player2++;
cards[1].isWin = true;
}
this.score.round++;
return cards;
}
refresh(): void {
this.score = {
round: 1,
player1: 0,
player2: 0,
};
}
get getScore(): IScore {
return this.score;
}
get getModel(): Model {
return this.model;
}
set setModel(model: Model) {
this.model = model;
}
}
|
83a59c3a2fa197cedfcc3c3aba290892b95ccca0
|
TypeScript
|
dmarine/SafoodAdmin
|
/src/app/models/food.ts
| 2.765625
| 3
|
export class Food {
id: number
name: string
category_id: number
restaurant_id: number
image: string
description: string
price: number
constructor(name: string, category_id: number, restaurantid: number, description: string, price: number) {
this.name = name
this.category_id = category_id
this.restaurant_id = restaurantid
this.description = description
this.price = price
}
}
|
78be4263743283ed14cfc26ae4f5c1cc45205f5f
|
TypeScript
|
fabrix-app/spool-broadcast
|
/lib/config/spool.ts
| 2.59375
| 3
|
// tslint:disable:max-line-length
/**
* Spool Configuration
*
* @see {@link https://fabrix.app/doc/spool/config
*/
export const spool = {
type: 'misc',
/**
* API and config resources provided by this Spool.
*/
provides: {
resources: ['controllers', 'models', 'services', 'events', 'crons', 'emails'],
api: {
controllers: ['BroadcastController'],
services: [],
models: ['Broadcast'],
events: [],
crons: [],
tasks: []
},
config: ['broadcast']
},
/**
* Configure the lifecycle of this pack; that is, how it boots up, and which
* order it loads relative to other spools.
*/
lifecycle: {
configure: {
/**
* List of events that must be fired before the configure lifecycle
* method is invoked on this Spool
*/
listen: [
'spool:sequelize:configured',
'spool:realtime:configured'
],
/**
* List of events emitted by the configure lifecycle method
*/
emit: []
},
initialize: {
listen: [
'spool:sequelize:initialized',
'spool:realtime:initialized'
],
emit: []
}
}
}
|
a2028f5d23e240cf89527131d5a64efdd525fa7e
|
TypeScript
|
idahopotato1/kilo
|
/test/key-controls.spec.ts
| 2.953125
| 3
|
import { expect } from 'chai'
import { KeyControls } from '../lib/'
describe('KeyControls', () => {
let ctrls: KeyControls
const keyDown = (code: string) => {
const evt = new KeyboardEvent('keydown', { code } as any)
document.dispatchEvent(evt)
}
const keyUp = (code: string) => {
const evt = new KeyboardEvent('keyup', { code } as any)
document.dispatchEvent(evt)
}
it('allows certain keys to bubble their events', () => {
ctrls = new KeyControls()
keyDown('F5')
expect(ctrls.key('F5')).to.equal(true)
keyUp('F5')
expect(ctrls.key('F5')).to.equal(false)
})
describe('Accessors', () => {
beforeEach(() => {
ctrls = new KeyControls()
})
it('has get accessor action', () => {
expect(ctrls.action).to.be.undefined
keyDown('Space')
expect(ctrls.action).to.equal(true)
})
it('has set accessor action', () => {
expect(ctrls.action).to.be.undefined
ctrls.action = true
expect(ctrls.action).to.equal(true)
})
it('has get accessor actionB', () => {
expect(ctrls.actionB).to.be.undefined
})
it('has get accessor x', () => {
keyDown('KeyA')
expect(ctrls.x).to.equal(-1)
keyUp('KeyA')
expect(ctrls.x).to.equal(0)
keyDown('ArrowLeft')
expect(ctrls.x).to.equal(-1)
keyUp('ArrowLeft')
expect(ctrls.x).to.equal(0)
keyDown('KeyD')
expect(ctrls.x).to.equal(1)
keyUp('KeyD')
expect(ctrls.x).to.equal(0)
keyDown('ArrowRight')
expect(ctrls.x).to.equal(1)
keyUp('ArrowRight')
expect(ctrls.x).to.equal(0)
})
it('has get accessor y', () => {
keyDown('KeyW')
expect(ctrls.y).to.equal(-1)
keyUp('KeyW')
expect(ctrls.y).to.equal(0)
keyDown('ArrowUp')
expect(ctrls.y).to.equal(-1)
keyUp('ArrowUp')
expect(ctrls.y).to.equal(0)
keyDown('KeyS')
expect(ctrls.y).to.equal(1)
keyUp('KeyS')
expect(ctrls.y).to.equal(0)
keyDown('ArrowDown')
expect(ctrls.y).to.equal(1)
keyUp('ArrowDown')
expect(ctrls.y).to.equal(0)
})
})
describe('Methods', () => {
beforeEach(() => {
ctrls = new KeyControls()
})
it('has method key', () => {
expect(ctrls.key).to.be.a('function')
let val = ctrls.key('Space')
expect(val).to.equal(false)
val = ctrls.key('Space', true)
expect(val).to.equal(true)
})
it('has method reset', () => {
expect(ctrls.reset).to.be.a('function')
ctrls.action = true
expect((ctrls as any).keys.Space).to.equal(true)
ctrls.reset()
expect((ctrls as any).keys.Space).to.equal(undefined)
})
})
})
|
aa9d6f6fcec1f8669f3b022bada55847eb7e8cea
|
TypeScript
|
Sean-Char/angular2-hello-world
|
/src/app/courses.component.ts
| 2.609375
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'courses',
template: `
{{ text | summary:25 }}
` // can also interpulate methods
})
export class CoursesComponent {
text = `
Lorem Ipsum simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy.
`
// class dependency injection .. need to include into providers in app module
// constructor(service: CoursesService) {
// this.courses = service.getCourses();
// }
// getTitle() {
// return this.title;
// }
}
// <td [attr.colspan]="colSpan" ></td> --> attribute binding
// <button class="btn btn-primary" [class.active]="isActive">Save</button> --> class binding
// <button [style.backgroundColor="isActive ? 'blue' : 'white'"] --> style binding
// <button (click)="onSave($event)" >Save</button> --> event binding
// <input (keyup.enter)="onKeyUp()" /> --> event filtering
// <input #email (keyup.enter)="onKeyUp(email.value)" /> --> template variables
// <input [(ngModel)]="email" (keyup.enter)="onKeyUp()" /> --> two way binding
// PIPES
// { { course.title | uppercase | lowercase } } <br/>
// { { course.students | number } } <br/>
// { { course.rating | number:'1.1-1' } } <br/>
// { { course.price | currency:'AUD': true:'3.2-2' } } <br/>
// { { course.releaseDate | date: 'shortDate' } }
//CUSTOM PIPES
|
8eb6cd72c841497f7184b7b8496f1c119def1ebf
|
TypeScript
|
tuftjs/tuft
|
/__tests__/pre-handlers/body-parser.test.ts
| 2.921875
| 3
|
import { requestSymbol } from '../../src/context';
import { createBodyParser } from '../../src/pre-handlers/body-parser';
import { HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_LENGTH } from '../../src/constants';
import { PassThrough } from 'stream';
type MockTuftContext = {
request: {
headers: {
[key: string]: string;
};
[key: string]: any;
};
[requestSymbol]: PassThrough;
};
function createMockContext(): MockTuftContext {
return {
request: {
headers: {},
},
[requestSymbol]: new PassThrough(),
};
}
const textChunks = [
Buffer.from('foo'),
Buffer.from('bar'),
Buffer.from('baz'),
];
const jsonChunks = [
Buffer.from('{"abc"'),
Buffer.from(':123}'),
];
const urlEncodedChunks = [
Buffer.from('abc='),
Buffer.from('123'),
Buffer.from('&'),
Buffer.from('def='),
Buffer.from('456'),
];
/**
* createBodyParser('text')
*/
describe('createBodyParser(`raw`)', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('raw');
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(textChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('adds a `body` property set to the expected value to the request object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).toHaveProperty('body', expectedBody);
});
});
describe('when passed a stream without a `content-length` header', () => {
const context = createMockContext();
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'LENGTH_REQUIRED' });
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream without a valid `content-length` header', () => {
const context = createMockContext();
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = 'this is not a number';
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'BAD_REQUEST' });
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data of size greater than `content-length`', () => {
const context = createMockContext();
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = '1';
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'PAYLOAD_TOO_LARGE' });
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data of size less than `content-length`', () => {
const context = createMockContext();
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = '10';
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'BAD_REQUEST' });
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('raw') with second argument set to 0
*/
describe('createBodyParser(`raw`) with second argument set to 0', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('raw', 0);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('raw') with second argument set to 1
*/
describe('createBodyParser(`raw`) with second argument set to 1', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('raw', 1);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data that exceeds the set body size limit', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(textChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/octet-stream';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'PAYLOAD_TOO_LARGE' });
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('text')
*/
describe('createBodyParser(`text`)', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('text');
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(textChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'text/plain';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('adds a `body` property set to the expected value to the request object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).toHaveProperty('body', expectedBody.toString());
});
});
});
});
/**
* createBodyParser('text') with second argument set to 0
*/
describe('createBodyParser(`text`) with second argument set to 0', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('text', 0);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('text') with second argument set to 1
*/
describe('createBodyParser(`text`) with second argument set to 1', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('text', 1);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data that exceeds the set body size limit', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(textChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'text/plain';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('resolves with an HTTP error response object', async () => {
const promise = bodyParser(context);
textChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'PAYLOAD_TOO_LARGE' });
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('json')
*/
describe('createBodyParser(`json`)', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('json');
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(jsonChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/json';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('adds a `body` property set to the expected value to the request object', async () => {
const promise = bodyParser(context);
jsonChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).toHaveProperty('body', { abc: 123 });
});
});
});
});
/**
* createBodyParser('json') with second argument set to 0
*/
describe('createBodyParser(`json`) with second argument set to 0', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('json', 0);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('json') with second argument set to 1
*/
describe('createBodyParser(`json`) with second argument set to 1', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('json', 1);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data that exceeds the set body size limit', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(jsonChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/json';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('rejects with an error', async () => {
const promise = bodyParser(context);
jsonChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'PAYLOAD_TOO_LARGE' });
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('urlEncoded')
*/
describe('createBodyParser(`urlEncoded`)', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('urlEncoded');
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data', () => {
const context = createMockContext();
const chunks = urlEncodedChunks.slice(0, 2);
const expectedBody = Buffer.concat(chunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/x-www-form-urlencoded';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('adds a `body` property set to the expected value to the request object', async () => {
const promise = bodyParser(context);
chunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).toHaveProperty('body', { abc: '123' });
});
});
});
describe('when passed a stream with data that includes two key/value pairs', () => {
const context = createMockContext();
const expectedBody = Buffer.concat(urlEncodedChunks);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/x-www-form-urlencoded';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = expectedBody.length.toString();
test('adds a `body` property set to the expected value to the request object', async () => {
const promise = bodyParser(context);
urlEncodedChunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).toHaveProperty('body', { abc: '123', def: '456' });
});
});
});
/**
* createBodyParser('urlEncoded') with second argument set to 0
*/
describe('createBodyParser(`urlEncoded`) with second argument set to 0', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('urlEncoded', 0);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
});
});
/**
* createBodyParser('urlEncoded') with second argument set to 1
*/
describe('createBodyParser(`urlEncoded`) with second argument set to 1', () => {
let bodyParser: (t: MockTuftContext) => Promise<void>;
test('returns a function named `bodyParser`', () => {
//@ts-expect-error
bodyParser = createBodyParser('urlEncoded', 1);
expect(typeof bodyParser).toBe('function');
expect(bodyParser.name).toBe('bodyParser');
});
describe('bodyParser()', () => {
describe('when passed a stream with NO data', () => {
const context = createMockContext();
test('does not add a `body` property to the request object', async () => {
const promise = bodyParser(context);
context[requestSymbol].end();
await expect(promise).resolves.toBeUndefined();
expect(context.request).not.toHaveProperty('body');
});
});
describe('when passed a stream with data that exceeds the set body size limit', () => {
const context = createMockContext();
const chunks = urlEncodedChunks.slice(0, 2);
context.request.headers[HTTP_HEADER_CONTENT_TYPE] = 'application/x-www-form-urlencoded';
context.request.headers[HTTP_HEADER_CONTENT_LENGTH] = chunks.length.toString();
test('rejects with an error', async () => {
const promise = bodyParser(context);
chunks.forEach(chunk => context[requestSymbol].write(chunk));
context[requestSymbol].end();
await expect(promise).resolves.toEqual({ error: 'PAYLOAD_TOO_LARGE' });
expect(context.request).not.toHaveProperty('body');
});
});
});
});
|
041010b356c672e897ca07b893df6bcc9f6ad4a4
|
TypeScript
|
sass/embedded-host-node
|
/lib/src/value/calculations.ts
| 2.984375
| 3
|
// Copyright 2023 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import {hash, List, ValueObject} from 'immutable';
import {Value} from './index';
import {SassNumber} from './number';
import {SassString} from './string';
export type CalculationValue =
| SassNumber
| SassCalculation
| SassString
| CalculationOperation
| CalculationInterpolation;
type CalculationValueIterable = CalculationValue[] | List<CalculationValue>;
function assertCalculationValue(value: CalculationValue): void {
if (value instanceof SassString && value.hasQuotes) {
throw new Error(`Expected ${value} to be an unquoted string.`);
}
}
const isValidClampArg = (value: CalculationValue): boolean =>
value instanceof CalculationInterpolation ||
(value instanceof SassString && !value.hasQuotes);
/* A SassScript calculation */
export class SassCalculation extends Value {
readonly arguments: List<CalculationValue>;
private constructor(
readonly name: string,
args: CalculationValueIterable
) {
super();
this.arguments = List(args);
}
static calc(argument: CalculationValue): SassCalculation {
assertCalculationValue(argument);
return new SassCalculation('calc', [argument]);
}
static min(args: CalculationValueIterable): SassCalculation {
args.forEach(assertCalculationValue);
return new SassCalculation('min', args);
}
static max(args: CalculationValueIterable): SassCalculation {
args.forEach(assertCalculationValue);
return new SassCalculation('max', args);
}
static clamp(
min: CalculationValue,
value?: CalculationValue,
max?: CalculationValue
): SassCalculation {
if (
(value === undefined && !isValidClampArg(min)) ||
(max === undefined && ![min, value].some(x => x && isValidClampArg(x)))
) {
throw new Error(
'Argument must be an unquoted SassString or CalculationInterpolation.'
);
}
const args = [min];
if (value !== undefined) args.push(value);
if (max !== undefined) args.push(max);
args.forEach(assertCalculationValue);
return new SassCalculation('clamp', args);
}
assertCalculation(): SassCalculation {
return this;
}
equals(other: unknown): boolean {
return (
other instanceof SassCalculation &&
this.name === other.name &&
this.arguments.equals(other.arguments)
);
}
hashCode(): number {
return hash(this.name) ^ this.arguments.hashCode();
}
toString(): string {
return `${this.name}(${this.arguments.join(', ')})`;
}
}
const operators = ['+', '-', '*', '/'] as const;
export type CalculationOperator = (typeof operators)[number];
export class CalculationOperation implements ValueObject {
constructor(
readonly operator: CalculationOperator,
readonly left: CalculationValue,
readonly right: CalculationValue
) {
if (!operators.includes(operator)) {
throw new Error(`Invalid operator: ${operator}`);
}
assertCalculationValue(left);
assertCalculationValue(right);
}
equals(other: unknown): boolean {
return (
other instanceof CalculationOperation &&
this.operator === other.operator &&
this.left === other.left &&
this.right === other.right
);
}
hashCode(): number {
return hash(this.operator) ^ hash(this.left) ^ hash(this.right);
}
}
export class CalculationInterpolation implements ValueObject {
constructor(readonly value: string) {}
equals(other: unknown): boolean {
return (
other instanceof CalculationInterpolation && this.value === other.value
);
}
hashCode(): number {
return hash(this.value);
}
}
|
b53c2b05a971e390437296e398f3c8019cd85e6f
|
TypeScript
|
lennonc/puz-parser
|
/lib/crossword.ts
| 2.578125
| 3
|
import fs from 'fs';
import Header from './header';
export default class Crossword {
public header?: any;
public puzzle?: any;
public details?: any;
public board?: any;
constructor(options?: any) {
this.header = new Header();
this.puzzle = {};
this.details = {};
this.board = {};
if (options?.fileName) {
this.decodeSync(options.fileName);
}
}
toJson() {
return this;
}
// private methods
private decodeSync(fileName: string) {
const data = fs.readFileSync(fileName);
return this.decode(data);
}
private decode(data: any) {
this.header.checksum = data.slice(0x00, 0x00 + 0x02).readInt16LE(0);
this.header.fileMagic = data.slice(0x02, 0x02 + 0x0B).toString();
this.header.cibChecksum = data.slice(0x0E, 0x0E + 0x02).readInt16LE(0);
this.header.maskedLowCheckSums = data.slice(0x10, 0x10 + 0x04).toString('hex');
this.header.maskedHighCheckSums = data.slice(0x14, 0x14 + 0x04).toString('hex');
this.header.version = data.slice(0x18, 0x18 + 0x04).toString();
this.header.reserved1C = data.slice(0x1C, 0x1C + 0x02).toString('hex');
this.header.scrambledChecksum = data.slice(0x1E, 0x1E + 0x02).readInt16LE(0);
this.header.reserved20 = data.slice(0x20, 0x20 + 0x0C).toString('hex');
this.header.width = data.slice(0x2C, 0x2C + 0x01).readInt8(0);
this.header.height = data.slice(0x2D, 0x2D + 0x01).readInt8(0);
this.header.scrambled = data.slice(0x32, 0x32 + 0x01).readInt8(0) !== 0;
this.header.numberOfClues = data.slice(0x2E, 0x2E + 0x02).readInt16LE(0);
this.header.unknownBitmask = data.slice(0x30, 0x30 + 0x02).readInt16LE(0);
this.header.scambledtag = data.slice(0x32, 0x32 + 0x02).readInt16LE(0);
// ********************* PUZZLE LAYOUT AND STATE *********************
const cells = this.header.width * this.header.height;
const solutionStart = 0x34;
const solutionEnd = solutionStart + cells;
const stateStart = solutionEnd;
const stateEnd = stateStart + cells;
this.puzzle.solution = data.slice(solutionStart, solutionEnd).toString();
this.puzzle.state = data.slice(stateStart, stateEnd).toString();
// ********************* STRING SECTION *********************
var stringStart = stateEnd;
var remainder = data.slice(stringStart);
var fields = ['title', 'author', 'copyright'];
var clueStart = 0;
for (var i = 0, j = 0, fieldIndex = 0; i < remainder.length && fieldIndex < fields.length; i++) {
var caret = remainder[i];
if (caret === 0) {
this.header[fields[fieldIndex]] = remainder.slice(j, i).toString();
j = i + 1;
fieldIndex++;
}
if (fieldIndex === 2) {
clueStart = i + 1;
}
};
// this.details = {};
// remainder = data.slice(stringStart + clueStart + 1)
// remainder = Crossword.splitBufferAtNulls(remainder, 0x00);
// this.details.clues = [];
// for (var i = 0; i < this.header.numberOfClues; i++) {
// this.details.clues.push(remainder[i].toString());
// }
}
};
|
830f0e4af335d9cdd5d2179d7ada1be5de61cfe5
|
TypeScript
|
Ralphvanderneut/100dayscodeprojects
|
/ralph-portfolio/src/composables/ItemSelected.ts
| 2.59375
| 3
|
export function ItemSelected(emit: any){
const OnItemSelected = (id: number): void =>{
emit("selected",id);
}
return { OnItemSelected }
}
|
eb25082526b008611bde9629ebab57c006289f66
|
TypeScript
|
donmahallem/nadezhda-server
|
/src/routes/users/users-endpoints.ts
| 2.5625
| 3
|
import {
Request,
Response,
NextFunction,
RequestHandler
} from "express";
import {
Validator,
Schema,
ValidatorResult
} from "jsonschema";
import {
UserDatabase
} from "./../../database/user-database";
import {
RouteError
} from "./../";
export class UsersEndpoints {
public static updateUser: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
if (!req.hasOwnProperty("body")) {
next(new Error("No body provided"));
return;
}
const validator: Validator = new Validator();
const updateUserDataSchema: Schema = {
"id": "/UpdateUserDataSubmission",
"type": "object",
"properties": {
"id": {
"type": "string",
minLength: 5,
maxLength: 100
}
},
"required": ["id"]
};
res.json({
"message": "not implemented"
})
};
public static createUser: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
if (!req.hasOwnProperty("body")) {
next(new Error("No body provided"));
return;
}
const validator: Validator = new Validator();
const loginDataSchema: Schema = {
"id": "/CreateUserDataSubmission",
"type": "object",
"properties": {
"username": {
"type": "string",
maxLength: 140,
minLength: 6
},
"password1": {
"type": "string",
minLength: 8,
maxLength: 1024
},
"password2": {
"type": "string",
minLength: 8,
maxLength: 1024
}
},
"required": ["username", "password1", "password2"]
};
if (req.body.password1 != req.body.password2) {
next(new RouteError(400, "The provided passwords dont match"));
return;
}
const validatorResult: ValidatorResult = validator.validate(req.body, loginDataSchema);
if (validatorResult.valid) {
UserDatabase.createUser(req.body.username, req.body.password1)
.then(result => {
res.json(result);
}).catch(err => {
if (parseInt(err.code) == 23505) {
// Unique Violation
next(new RouteError(400, "Username already taken"));
} else {
next(err);
}
});
} else {
next(new Error(validatorResult.errors[0].message));
}
};
public static getUser: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
UserDatabase.getUser(req.params.userId)
.then(result => {
res.json(result);
})
.catch(error => {
next(error);
});
};
}
|
e7ffd82e7b20fa775bbe6d54d91d8bcf1951149a
|
TypeScript
|
BlokDust/BlokDust
|
/app/lib/utils/src/StorageType.ts
| 2.6875
| 3
|
module Utils {
export class StorageType {
static memory = new StorageType("memory");
static session = new StorageType("session");
static local = new StorageType("local");
constructor(public value:string) {
}
toString() {
return this.value;
}
}
}
|
6d6cab442eacdcfcc77ec3fbef726821143832fb
|
TypeScript
|
peterkhayes/pitchfinder
|
/src/detectors/acf2plus.ts
| 3.140625
| 3
|
import { PitchDetector } from './types';
export interface ACF2Config {
sampleRate: number;
}
const DEFAULT_PARAMS: ACF2Config = {
sampleRate: 44100,
};
export function ACF2PLUS(params: Partial<ACF2Config> = DEFAULT_PARAMS): PitchDetector {
const config = {
...DEFAULT_PARAMS,
...params,
};
const { sampleRate } = config;
// Implements the ACF2+ algorithm
return function ACF2PLUSDetector(float32AudioBuffer: Float32Array): number {
const maxShift = float32AudioBuffer.length;
let rms = 0;
let i, j, u, tmp;
for (i = 0; i < maxShift; i++) {
tmp = float32AudioBuffer[i];
rms += tmp * tmp;
}
rms = Math.sqrt(rms / maxShift);
if (rms < 0.01)
// not enough signal
return -1;
/* Trimming cuts the edges of the signal so that it starts and ends near zero.
This is used to neutralize an inherent instability of the ACF version I use.*/
let aux1 = 0;
let aux2 = maxShift - 1;
const thres = 0.2;
for (i = 0; i < maxShift / 2; i++)
if (Math.abs(float32AudioBuffer[i]) < thres) {
aux1 = i;
break;
}
for (i = 1; i < maxShift / 2; i++)
if (Math.abs(float32AudioBuffer[maxShift - i]) < thres) {
aux2 = maxShift - i;
break;
}
const frames = float32AudioBuffer.slice(aux1, aux2);
const framesLength = frames.length;
const calcSub = new Array<number>(framesLength).fill(0);
for (i = 0; i < framesLength; i++)
for (j = 0; j < framesLength - i; j++)
calcSub[i] = calcSub[i] + frames[j] * frames[j + i];
u = 0;
while (calcSub[u] > calcSub[u + 1]) u++;
let maxval = -1,
maxpos = -1;
for (i = u; i < framesLength; i++) {
if (calcSub[i] > maxval) {
maxval = calcSub[i];
maxpos = i;
}
}
let T0 = maxpos;
/* Interpolation is parabolic interpolation. It helps with precision.
We suppose that a parabola pass through the three points that comprise the peak.
'a' and 'b' are the unknowns from the linear equation system
and b/(2a) is the "error" in the abscissa.
y1,y2,y3 are the ordinates.*/
const y1 = calcSub[T0 - 1],
y2 = calcSub[T0],
y3 = calcSub[T0 + 1];
const a = (y1 + y3 - 2 * y2) / 2;
const b = (y3 - y1) / 2;
if (a) T0 = T0 - b / (2 * a);
return sampleRate / T0;
};
}
|
5585c8a7f31cb418dcc75ec145464972b1bf24af
|
TypeScript
|
sevenClover/typescript
|
/05.联合类型.ts
| 2.640625
| 3
|
{
let a:string|number|boolean = "123"
a=123;
let b:number=123;
let bb:Number=new Number(123)
b.toLocaleString()
console.log(b.toLocaleString())
}
|
63f5cfbeb3ed13968f4c390a849bb7ac15a2bc0a
|
TypeScript
|
berapakinibmembunuhks/one
|
/src/core/tasks/task-spec.impl.ts
| 2.8125
| 3
|
import type { ZTaskSpec } from './task-spec';
export function addZTaskAttr(target: Record<string, string[] | null>, name: string, value: string): void {
const subIdx = name.lastIndexOf(':');
if (subIdx >= 0) {
addZTaskAttr(target, name.substr(0, subIdx), name.substr(subIdx + 1));
}
const values = target[name];
if (values) {
values.push(value);
} else {
target[name] = [value];
}
}
export function removeZTaskAttr(target: Record<string, string[] | null>, name: string): void {
target[name] = null;
}
export function addZTaskAttrs(target: Record<string, string[] | null>, attrs: ZTaskSpec.Attrs): void {
Object.entries(attrs).forEach(
([name, values]) => values?.forEach(
value => addZTaskAttr(target, name, value),
),
);
}
|
8c88dff5b8ba5b2e44fafec6fcc60427130f5f56
|
TypeScript
|
scottspiller/StarWarsVue
|
/src/models/People.ts
| 2.9375
| 3
|
import {Person} from '../models/Person';
export class People {
public count: number = 0;
public next: string = '';
public previous: string = '';
public persons: Person[] = [];
constructor(obj: any = null) {
if (obj) {
this.count = obj.count || 0;
this.next = obj.next || '';
this.previous = obj.previous || '';
this.persons = (obj.results || []).map((x: any) => new Person(x));
}
}
}
|
eabd7f54c8c21270c815263414907812f970ca78
|
TypeScript
|
pooltogether/contracts
|
/test/lists/DoubleLinkedList.test.ts
| 2.828125
| 3
|
import { should } from 'chai';
import { DoubleLinkedListInstance } from '../../types/truffle-contracts';
const DoubleLinkedList = artifacts
.require('./lists/DoubleLinkedList.sol') as Truffle.Contract<DoubleLinkedListInstance>;
should();
const emptyData = '0x0000000000000000000000000000000000000000';
const headData = '0x0000000000000000000000000000000000000001';
const middleData = '0x0000000000000000000000000000000000000002';
const tailData = '0x0000000000000000000000000000000000000003';
/** @test {DoubleLinkedList} contract */
contract('DoubleLinkedList - add', (accounts) => {
let doubleLinkedList: DoubleLinkedListInstance;
beforeEach(async () => {
doubleLinkedList = await DoubleLinkedList.new();
});
/**
* Test the two contract methods
* @test {DoubleLinkedList#set} and {DoubleLinkedList#get}
*/
it('Constructor variables.', async () => {
(await doubleLinkedList.idCounter()).toNumber().should.be.equal(1);
});
it('get on a non existing object returns (0,0,0,0).', async () => {
const result = (await doubleLinkedList.get(0));
result[0].toNumber().should.be.equal(0);
result[1].toNumber().should.be.equal(0);
result[2].toNumber().should.be.equal(0);
result[3].should.be.equal(emptyData);
});
it('adds an object at the head - event emission.', async () => {
const objectEvent = (
await doubleLinkedList.addHead(headData)
).logs[0];
objectEvent.args.id.toNumber().should.be.equal(1);
objectEvent.args.data.should.be.equal(headData);
});
it('adds an object at the head - data storage.', async () => {
const objectId = (
await doubleLinkedList.addHead(headData)
).logs[0].args.id.toNumber();
const result = (await doubleLinkedList.get(objectId));
result[0].toNumber().should.be.equal(objectId);
result[1].toNumber().should.be.equal(0);
result[2].toNumber().should.be.equal(0);
result[3].should.be.equal(headData);
});
it('adds two objects from the head.', async () => {
const objectOneId = (
await doubleLinkedList.addHead(middleData)
).logs[0].args.id.toNumber();
const objectTwoId = (
await doubleLinkedList.addHead(headData)
).logs[0].args.id.toNumber();
const objectOne = (await doubleLinkedList.get(objectOneId));
objectOne[0].toNumber().should.be.equal(objectOneId);
objectOne[1].toNumber().should.be.equal(0);
objectOne[2].toNumber().should.be.equal(objectTwoId);
objectOne[3].should.be.equal(middleData);
const objectTwo = (await doubleLinkedList.get(objectTwoId));
objectTwo[0].toNumber().should.be.equal(objectTwoId);
objectTwo[1].toNumber().should.be.equal(objectOneId);
objectTwo[2].toNumber().should.be.equal(0);
objectTwo[3].should.be.equal(headData);
((await doubleLinkedList.head()).toNumber()).should.be.equal(objectTwoId);
});
it('adds an object at the tail - event emission.', async () => {
const objectEvent = (
await doubleLinkedList.addTail(headData)
).logs[0];
objectEvent.args.id.toNumber().should.be.equal(1);
objectEvent.args.data.should.be.equal(headData);
});
it('adds an object at the tail - data storage.', async () => {
const objectId = (
await doubleLinkedList.addTail(headData)
).logs[0].args.id.toNumber();
const result = (await doubleLinkedList.get(objectId));
result[0].toNumber().should.be.equal(objectId);
result[1].toNumber().should.be.equal(0);
result[2].toNumber().should.be.equal(0);
result[3].should.be.equal(headData);
});
it('adds two objects from the tail.', async () => {
const objectOneId = (
await doubleLinkedList.addTail(middleData)
).logs[0].args.id.toNumber();
const objectTwoId = (
await doubleLinkedList.addTail(headData)
).logs[0].args.id.toNumber();
const objectOne = (await doubleLinkedList.get(objectOneId));
objectOne[0].toNumber().should.be.equal(objectOneId);
objectOne[1].toNumber().should.be.equal(objectTwoId);
objectOne[2].toNumber().should.be.equal(0);
objectOne[3].should.be.equal(middleData);
const objectTwo = (await doubleLinkedList.get(objectTwoId));
objectTwo[0].toNumber().should.be.equal(objectTwoId);
objectTwo[1].toNumber().should.be.equal(0);
objectTwo[2].toNumber().should.be.equal(objectOneId);
objectTwo[3].should.be.equal(headData);
((await doubleLinkedList.head()).toNumber()).should.be.equal(objectOneId);
});
});
contract('DoubleLinkedList - find', (accounts) => {
let doubleLinkedList: DoubleLinkedListInstance;
let headId: number;
let middleId: number;
let tailId: number;
beforeEach(async () => {
doubleLinkedList = await DoubleLinkedList.new();
tailId = (
await doubleLinkedList.addHead(tailData)
).logs[0].args.id.toNumber();
middleId = (
await doubleLinkedList.addHead(middleData)
).logs[0].args.id.toNumber();
headId = (
await doubleLinkedList.addHead(headData)
).logs[0].args.id.toNumber();
});
it('finds an id for given data.', async () => {
let resultId = (await doubleLinkedList.findIdForData(headData));
resultId.toNumber().should.be.equal(headId);
resultId = (await doubleLinkedList.findIdForData(middleData));
resultId.toNumber().should.be.equal(middleId);
resultId = (await doubleLinkedList.findIdForData(tailData));
resultId.toNumber().should.be.equal(tailId);
});
});
/** @test {doubleLinkedList} contract */
contract('DoubleLinkedList - remove', (accounts) => {
let doubleLinkedList: DoubleLinkedListInstance;
let headId: number;
let middleId: number;
let tailId: number;
beforeEach(async () => {
doubleLinkedList = await DoubleLinkedList.new();
tailId = (
await doubleLinkedList.addHead(tailData)
).logs[0].args.id.toNumber();
middleId = (
await doubleLinkedList.addHead(middleData)
).logs[0].args.id.toNumber();
headId = (
await doubleLinkedList.addHead(headData)
).logs[0].args.id.toNumber();
});
it('removes the head.', async () => {
const removedId = (
await doubleLinkedList.remove(headId)
).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(tailId);
middleObject[2].toNumber().should.be.equal(0);
middleObject[3].should.be.equal(middleData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(middleId);
tailObject[3].should.be.equal(tailData);
});
it('removes the tail.', async () => {
const removedId = (
await doubleLinkedList.remove(tailId)
).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(middleId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(0);
middleObject[2].toNumber().should.be.equal(headId);
middleObject[3].should.be.equal(middleData);
});
it('removes the middle.', async () => {
const removedId = (
await doubleLinkedList.remove(middleId)
).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(tailId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(headId);
tailObject[3].should.be.equal(tailData);
});
it('removes all.', async () => {
(await doubleLinkedList.remove(headId)).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId);
(await doubleLinkedList.remove(tailId)).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(middleId);
((await doubleLinkedList.tail()).toNumber()).should.be.equal(middleId);
(await doubleLinkedList.remove(middleId)).logs[1].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(0);
((await doubleLinkedList.tail()).toNumber()).should.be.equal(0);
});
});
/** @test {doubleLinkedList} contract */
contract('DoubleLinkedList - insert', (accounts) => {
const insertedData = '0x0000000000000000000000000000000000000004';
let doubleLinkedList: DoubleLinkedListInstance;
let headId: number;
let middleId: number;
let tailId: number;
beforeEach(async () => {
doubleLinkedList = await DoubleLinkedList.new();
tailId = (
await doubleLinkedList.addHead(tailData)
).logs[0].args.id.toNumber();
middleId = (
await doubleLinkedList.addHead(middleData)
).logs[0].args.id.toNumber();
headId = (
await doubleLinkedList.addHead(headData)
).logs[0].args.id.toNumber();
});
it('inserts after the head.', async () => {
const insertedId = (
await doubleLinkedList.insertAfter(headId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(insertedId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(middleId);
insertedObject[2].toNumber().should.be.equal(headId);
insertedObject[3].should.be.equal(insertedData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(tailId);
middleObject[2].toNumber().should.be.equal(insertedId);
middleObject[3].should.be.equal(middleData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(middleId);
tailObject[3].should.be.equal(tailData);
});
it('inserts after the tail.', async () => {
const insertedId = (
await doubleLinkedList.insertAfter(tailId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(middleId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(tailId);
middleObject[2].toNumber().should.be.equal(headId);
middleObject[3].should.be.equal(middleData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(insertedId);
tailObject[2].toNumber().should.be.equal(middleId);
tailObject[3].should.be.equal(tailData);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(0);
insertedObject[2].toNumber().should.be.equal(tailId);
insertedObject[3].should.be.equal(insertedData);
});
it('inserts after the middle.', async () => {
const insertedId = (
await doubleLinkedList.insertAfter(middleId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(middleId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(insertedId);
middleObject[2].toNumber().should.be.equal(headId);
middleObject[3].should.be.equal(middleData);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(tailId);
insertedObject[2].toNumber().should.be.equal(middleId);
insertedObject[3].should.be.equal(insertedData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(insertedId);
tailObject[3].should.be.equal(tailData);
});
it('inserts before the head.', async () => {
const insertedId = (
await doubleLinkedList.insertBefore(headId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(insertedId);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(headId);
insertedObject[2].toNumber().should.be.equal(0);
insertedObject[3].should.be.equal(insertedData);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(middleId);
headObject[2].toNumber().should.be.equal(insertedId);
headObject[3].should.be.equal(headData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(tailId);
middleObject[2].toNumber().should.be.equal(headId);
middleObject[3].should.be.equal(middleData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(middleId);
tailObject[3].should.be.equal(tailData);
});
it('inserts before the tail.', async () => {
const insertedId = (
await doubleLinkedList.insertBefore(tailId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(middleId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(insertedId);
middleObject[2].toNumber().should.be.equal(headId);
middleObject[3].should.be.equal(middleData);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(tailId);
insertedObject[2].toNumber().should.be.equal(middleId);
insertedObject[3].should.be.equal(insertedData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(insertedId);
tailObject[3].should.be.equal(tailData);
});
it('inserts before the middle.', async () => {
const insertedId = (
await doubleLinkedList.insertBefore(middleId, insertedData)
).logs[0].args.id.toNumber();
((await doubleLinkedList.head()).toNumber()).should.be.equal(headId);
const headObject = (await doubleLinkedList.get(headId));
headObject[0].toNumber().should.be.equal(headId);
headObject[1].toNumber().should.be.equal(insertedId);
headObject[2].toNumber().should.be.equal(0);
headObject[3].should.be.equal(headData);
const insertedObject = (await doubleLinkedList.get(insertedId));
insertedObject[0].toNumber().should.be.equal(insertedId);
insertedObject[1].toNumber().should.be.equal(middleId);
insertedObject[2].toNumber().should.be.equal(headId);
insertedObject[3].should.be.equal(insertedData);
const middleObject = (await doubleLinkedList.get(middleId));
middleObject[0].toNumber().should.be.equal(middleId);
middleObject[1].toNumber().should.be.equal(tailId);
middleObject[2].toNumber().should.be.equal(insertedId);
middleObject[3].should.be.equal(middleData);
const tailObject = (await doubleLinkedList.get(tailId));
tailObject[0].toNumber().should.be.equal(tailId);
tailObject[1].toNumber().should.be.equal(0);
tailObject[2].toNumber().should.be.equal(middleId);
tailObject[3].should.be.equal(tailData);
});
});
/* contract('DoubleLinkedList - gas tests', (accounts) => {
let doubleLinkedList: DoubleLinkedListInstance;
const dummyData = '0x0000000000000000000000000000000000000001';
beforeEach(async () => {
doubleLinkedList = await DoubleLinkedList.new();
for (let i = 0; i < 100; i++) {
await doubleLinkedList.addHead(dummyData);
}
});
it('Add Head.', async () => {
await doubleLinkedList.addHead(dummyData);
});
it('Add Tail.', async () => {
await doubleLinkedList.addTail(dummyData);
});
it('Insert After.', async () => {
const tailId = await doubleLinkedList.tail();
await doubleLinkedList.insertAfter(tailId, dummyData);
});
it('Insert Before.', async () => {
const tailId = await doubleLinkedList.tail();
await doubleLinkedList.insertBefore(tailId, dummyData);
});
it('Remove.', async () => {
const tailId = await doubleLinkedList.tail();
await doubleLinkedList.remove(tailId);
});
}); */
|
5f53ba551e5602c381dc03f828058a24f8e2b901
|
TypeScript
|
GhostfromTexas/mixer-wrapper
|
/source/ChatWrapper.ts
| 2.828125
| 3
|
import BeamClient = require("beam-client-node");
import BeamSocket = require("beam-client-node/lib/ws");
// Internal Objects for Beam Module
import * as Chat from "beam-client-node/defs/chat";
import { Event } from "./common/utils/Event";
export interface ChatClearMessages {
clearer: {
user_name: string;
user_id: number;
user_roles: string[];
user_level: number;
};
}
export interface ChatMessage extends Chat.ChatMessage {
text: string
}
export class ChatWrapper {
// Beam-Client Socket
private client: BeamClient;
private socket: BeamSocket;
private channelID: number;
private client_id: string;
private accessToken: string;
private tokenExpires: number;
// The current outgoing command queue
private commandQueue: Function[] = [];
private commandQueueInterval: NodeJS.Timer;
/**
* Event called when new user joins the chat.
*/
onChatUserJoin: Event<(id: number, username: string, data: Chat.UserConnection) => void> = new Event<any>();
/**
* Event called when user leaves the chat.
*/
onChatUserLeave: Event<(id: number, username: string, data: Chat.UserConnection) => void> = new Event<any>();
/**
* Event called when chat is cleared.
*/
onChatClearMessages: Event<(data: ChatClearMessages) => void> = new Event<any>();
/**
* Event called when message is deleted.
*/
onChatDeleteMessage: Event<(data: Chat.DeleteMessage) => void> = new Event<any>();
/**
* Event called when messages from a specific user are purged.
*
* Example: when user gets timed out or banned.
*/
onChatPurgeMessage: Event<(data: Chat.PurgeMessage) => void> = new Event<any>();
/**
* Event called when user is updated.
*/
onChatUserUpdate: Event<(data: Chat.UserUpdate) => void> = new Event<any>();
/**
* Event called when bot receives a new message.
*/
onChatMessage: Event<(data: ChatMessage) => void> = new Event<any>();
/**
* Event called the ChatWrapper is ready.
*/
onBotReady: Event<(client: BeamClient) => void> = new Event<any>();
constructor(channelID: number, client_id: string, accessToken: string, tokenExpires: number) {
this.channelID = channelID;
this.client_id = client_id;
this.accessToken = accessToken;
this.tokenExpires = tokenExpires;
}
/**
* Add an outgoing command to the command-queue
*/
private addToQueue(f: Function, pushFront: boolean = false) {
if (pushFront) {
this.commandQueue.unshift(f);
} else {
this.commandQueue.push(f);
}
}
/**
* Send a global chat message
*/
sendChatMessage(message: string, pushFront: boolean = false) {
this.addToQueue(() => {
this.socket.call("msg", [message]).catch((reason) => {
if (reason === "Please wait before sending more messages." || reason === "Please wait a moment before sending more messages.") {
this.sendChatMessage(message, true);
console.log("Re-queuing message to chat " + reason);
} else {
console.log("Error Sending Message to chat for reason: " + reason);
}
});
}, pushFront);
}
static CleanUsername(name: string) {
return name.replace("@", "");
}
/**
* Send a message to a particular user
*/
sendUserMessage(user: string, message: string, pushFront: boolean = false) {
user = ChatWrapper.CleanUsername(user);
this.addToQueue(() => {
this.socket.call("whisper", [user, message]).catch((reason) => {
if (reason === "Please wait before sending more messages." || reason === "Please wait a moment before sending more messages.") {
this.sendUserMessage(user, message, true);
console.log("Re-queuing message to user " + reason);
} else {
console.log("Error Sending Message to user for reason: " + reason);
}
});
}, pushFront);
}
/**
* Remove a particular message from the chat
*/
removeMessage(id: string) {
this.socket.call("deleteMessage", [id]).catch((reason) => {
console.log("Delete Message Error: " + reason);
});
}
/**
* Start processing the command queue to funnel outgoing messages
*/
startCommandQueue() {
setTimeout(() => {
let hasFunc = false;
// Start an interval that every 100ms attempts to send a beam-chat-api command
this.commandQueueInterval = setInterval(() => {
if (this.socket) {
let fn = this.commandQueue.shift();
if (fn) {
fn();
hasFunc = true;
} else if (hasFunc) {
console.log("Queue is Empty");
hasFunc = false;
}
}
}, 100);
}, 1000);
}
async start() {
this.client = new BeamClient();
// With OAuth we don"t need to login, the OAuth Provider will attach
// the required information to all of our requests after this call.
console.log("Bot: Setting up OAUTH");
this.client.use("oauth", {
clientId: this.client_id,
tokens: {
access: this.accessToken,
expires: this.tokenExpires
},
});
console.log("Bot: Connecting to Beam");
// Get"s the user we have access to with the token
let currentUser = await this.client.request("GET", `users/current`, {});
let userInfo = currentUser.body;
let joinResponse = await this.client.chat.join(this.channelID);
const body = joinResponse.body;
console.log("Bot: Creating Chat Socket");
// Chat connection
this.socket = new BeamSocket(body.endpoints).boot();
// React to our !pong command
this.socket.on("ChatMessage", (data: ChatMessage) => {
let text = "";
for (let i = 0; i < data.message.message.length; i++) {
text += data.message.message[i].text;
}
text = text.split(/\s+/).join(" ");
data.text = text;
this.onChatMessage.execute(data);
});
this.socket.on("UserJoin", (data) => {
this.onChatUserJoin.execute(data.id, data.username, data);
});
this.socket.on("UserLeave", (data) => {
this.onChatUserLeave.execute(data.id, data.username, data);
});
this.socket.on("ClearMessages", (data: ChatClearMessages) => {
this.onChatClearMessages.execute(data);
});
this.socket.on("DeleteMessage", (data) => {
this.onChatDeleteMessage.execute(data);
});
this.socket.on("PurgeMessage", (data) => {
this.onChatPurgeMessage.execute(data);
});
this.socket.on("UserUpdate", (data) => {
this.onChatUserUpdate.execute(data);
});
// Handle errors
this.socket.on("error", error => {
console.error("Socket error", error);
});
await this.socket.auth(this.channelID, userInfo.id, body.authkey);
console.log("Login successful");
this.onBotReady.execute(this.client);
this.startCommandQueue();
}
async stop() {
this.client = undefined;
this.socket.removeAllListeners();
this.socket.close();
clearInterval(this.commandQueueInterval);
return true;
}
}
|
10aab3b46d8e9da24ceb3aef8ff5786817ef6105
|
TypeScript
|
juliocesarcsc/marvel-test
|
/src/app/models/character.model.ts
| 2.578125
| 3
|
export class Character {
public id: number;
public name: string;
public description: string;
public comics: Comics;
public thumbnail: Thumbnail;
}
export class Thumbnail {
public path: string;
public extension: string;
}
export class Comics {
public available: number;
}
|
67d31f3df96f5f36dcaffbf317f1b56ac5ef692b
|
TypeScript
|
tavaresl/soul-collector
|
/src/assets/scripts/core/geometry/Rectangle.ts
| 3.078125
| 3
|
import { game } from "../Game.js";
export class Rectangle {
static draw(
x: number,
y: number,
width: number,
height: number,
rotationDegrees: number = 0,
backgroundColor: string = '#000000',
): void {
const context = game.drawContext;
context.save();
context.translate(x + width / 2, y + height / 2);
context.rotate((Math.PI / 180) * rotationDegrees);
context.translate(-(x + width / 2), -(y + height / 2));
context.fillStyle = backgroundColor;
context.fillRect(
x,
y,
width,
height,
);
// Temporary solution to see which way the rectangle is facing
context.fillStyle = '#00FF44';
context.fillRect(
x + width - 5,
y,
5,
height,
);
context.restore();
}
}
|
63ba2937ba64344eb9c5a66de13f91126064ef87
|
TypeScript
|
JoacoAllende/ventas
|
/frontend/src/app/components/product/product-filter-description.pipe.ts
| 2.65625
| 3
|
import { PipeTransform, Pipe } from '@angular/core';
import { Product } from 'src/app/models/product';
@Pipe({
name: 'descriptionFilter'
})
export class ProductFilterDescriptionPipe implements PipeTransform {
transform(products: Product[], searchDescription: string): Product[] {
if (!products || !searchDescription) {
return products;
}
return products.filter(product => product.description.toLocaleLowerCase().indexOf(searchDescription.toLowerCase()) !== -1);
}
}
|
87a01d154f12f98b66946a99778028fbf18ee3a1
|
TypeScript
|
zr8091/common-core-swagger-ui
|
/src/app/common/ApiFilter.ts
| 2.609375
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'apiFilter',
pure: false
})
export class ApiFilter implements PipeTransform {
transform(items2: any[], filter: String): any {
if (!items2 || !filter) {
return items2;
}
let items =JSON.parse(JSON.stringify(items2));
let res = items.filter(function(item) {
let filterKey = filter.toLocaleLowerCase();
if(-1 != item.name.toLocaleLowerCase().indexOf(filter.toLocaleLowerCase())
||-1 != item.description.toLocaleLowerCase().indexOf(filterKey)) {
return true;
}
if(Array.isArray(item.childs)) {
item.childs = item.childs.filter(function(item) {
if(-1 != item.summary.toLocaleLowerCase().indexOf(filterKey)
||-1 != item.description.toLocaleLowerCase().indexOf(filterKey)) {
return true;
}
})
return item.childs.length
}
})
return res;
}
}
|
cf998eca9875a2112da9f9be17a1a8e8155cc91c
|
TypeScript
|
qqqdu/bingo
|
/src/component/popClass.ts
| 2.671875
| 3
|
/*
弹窗类
**/
class PopClass extends egret.Sprite{
private image:egret.Bitmap = new egret.Bitmap();
private img;
public width:number;
public height:number;
public listen;
private buttonWidth = 47;
private type;
private hadConstructor;
private label1;
private label2;
private parentWidth
/**
* type: 0 成功
* type: 1 失败
*/
public constructor(x,y,width,height,type,label1,label2){
super();
this.width = 502;
this.height = 658;
this.x = width/2 - this.width/2;
this.y = height/2 - this.height/2;
this.type = type;
this.label1 = label1;
this.label2 = label2;
this.parentWidth = width
this.addEventListener(egret.Event.ADDED_TO_STAGE,this.drawProps,this);
}
private taxNum:TaxButton;
private drawProps(){
if(this.hadConstructor)
return;
this.hadConstructor = true;
this.taxNum = new TaxButton();
this.taxNum.skinName="resource/eui_skins/EndingSkin.exml"
this.taxNum.label =this.label1;
this.taxNum.label2 = this.label2;
this.addChild(this.taxNum)
if(this.type===0)
this.nextTax(this.x);
else
this.shareFriend();
this.againGame(this.x);
this.homeGame();
this.scaleX = .1;
this.scaleY = .1;
this.x = this.parentWidth/2 - (this.width * .1)/2
egret.Tween.get( this ).to( { x: this.parentWidth/2 - this.width/2, scaleX: 1,scaleY: 1 }, 300, egret.Ease.sineIn ).call(()=>{
});
}
//下一关
private async nextTax(x) {
let sky:eui.Image = await GameConfig.createBitmapByName("next.png");
sky.width = sky.height = this.buttonWidth;
sky.x = x + this.width - 117 - sky.width;
sky.y =this.height - 120;
this.addChild(sky);
let fn = ()=>{
let dataEvent:DateEvent = new DateEvent('myPrivateEvent');
dataEvent._type = 'next';
console.log("点击下一次了");
this.dispatchEvent(dataEvent);
}
sky.addEventListener('touchEnd',fn,this);
}
private async shareFriend() {
let sky:any = await GameConfig.createBitmapByName("share.png");
sky.width = sky.height = this.buttonWidth;
sky.x = this.width/2 - sky.width/2;
sky.y =this.height - 120;
this.addChild(sky);
sky.addEventListener('touchEnd',()=>{
let dataEvent:DateEvent = new DateEvent('myPrivateEvent');
dataEvent._type = 'share';
console.log("share");
this.dispatchEvent(dataEvent);
},this);
}
private async homeGame() {
let sky:any = await GameConfig.createBitmapByName("home.png");
sky.width = sky.height = this.buttonWidth;
sky.x = 60;
sky.y =this.height - 120;
this.addChild(sky);
sky.addEventListener('touchEnd',()=>{
let dataEvent:DateEvent = new DateEvent('myPrivateEvent');
dataEvent._type = 'home';
console.log("next");
this.dispatchEvent(dataEvent);
},this);
}
private async againGame(x) {
let sky:any = await GameConfig.createBitmapByName("again.png");
sky.width = sky.height = this.buttonWidth;
if(this.type===0)
sky.x = this.width/2 - sky.width/2;
else
sky.x = x + this.width - 117 - sky.width;
sky.y =this.height - 120;
this.addChild(sky);
sky.addEventListener('touchEnd',()=>{
let dataEvent:DateEvent = new DateEvent('myPrivateEvent');
dataEvent._type = 'again';
console.log("next");
this.dispatchEvent(dataEvent);
},this);
}
}
|
24ede48d74e481a09c052e8132e1a4d05fdadb90
|
TypeScript
|
tkuye/Streamer
|
/src/reducers/streamReducer.ts
| 2.890625
| 3
|
import _ from "lodash"
import {
FETCH_STREAM,
FETCH_STREAMS,
CREATE_STREAM,
EDIT_STREAM,
DELETE_STREAM
} from '../actions/types'
const streamReducer = (state:object={}, action:any) => {
switch (action.type) {
case FETCH_STREAMS:
return {...state, ..._.mapKeys(action.payload, 'id')}
case FETCH_STREAM:
return {...state, [action.payload.id]: action.payload};
case CREATE_STREAM:
return {...state, [action.payload.id]: action.payload};
case EDIT_STREAM:
return {...state, [action.payload.id]: action.payload};
case DELETE_STREAM:
return _.omit(state, action.payload);
default:
return state
}
}
export default streamReducer
|
97591f829f60285c89cf95ec17e767dd0c5baa28
|
TypeScript
|
1337programming/angular2-sample-starter
|
/server/src/product-schema.ts
| 2.796875
| 3
|
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
GraphQLFloat,
GraphQLNonNull
} from 'graphql';
// In memory data store
const ProductStore = require('./product-database.json');
console.log(ProductStore);
const OtherData = new GraphQLObjectType({
name: 'OtherData',
fields: () => ({
name: {type: GraphQLString},
offerType: {type: GraphQLString},
brand: {type: GraphQLString},
businessUnit: {type: GraphQLString},
priority: {type: GraphQLInt},
totalReviews: {type: GraphQLString},
totalReviewsRate: {type: GraphQLString},
})
});
// Root level queries
const ProductType = new GraphQLObjectType({
name: 'Product',
fields: () => ({
familyId: {type: GraphQLString},
familyName: {type: GraphQLString},
categories: {type: GraphQLString},
categoryName: {type: GraphQLString},
offerType: {type: GraphQLString},
offerSubType: {type: GraphQLString},
offerLevel: {type: GraphQLString},
productType: {type: GraphQLString},
productSubType: {type: GraphQLString},
url: {type: GraphQLString},
productName: {type: GraphQLString},
productManufacturer: {type: GraphQLString},
description: {type: GraphQLString},
longDescription: {type: GraphQLString},
priority: {type: GraphQLString},
operatingSystem: {type: GraphQLString},
screenSizes: {type: GraphQLString},
conditions: {type: GraphQLString},
internalMemorySizes: {type: GraphQLString},
features: {type: GraphQLString},
tacCodes: {type: GraphQLString},
bestSeller: {type: GraphQLString},
isFeatured: {type: GraphQLString},
rating: {type: GraphQLString},
reviewCount: {type: GraphQLString},
pageViews: {type: GraphQLString},
otherData: {type: OtherData}
})
});
const ProductQuery = new GraphQLObjectType({
name: 'ProductQuery',
fields: {
product: {
type: ProductType,
// `args` describes the arguments that the `product` query accepts
args: {
id: { type: GraphQLString }
},
// The resolve function describes how to "resolve" or fulfill
// the incoming query.
// In this case we use the `id` argument from above as a key
// to get the Product from `data`
resolve: function (_, args:any) {
return ProductStore[args.id];
}
}
}
});
// Mutations @TODO
const ProductMutations = new GraphQLObjectType({
name: 'ProductMutations',
fields: () => ({
addProduct: {
type: GraphQLString,
description: 'Add a new product',
args: {
item: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(parent, {item}) {
if (ProductStore.length >= 10) {
// Remove the third time by keeping the first two
ProductStore.splice(2, 1);
}
ProductStore.push(item);
return item;
}
}
})
});
// Schema
export const ProductSchema = new GraphQLSchema({
query: ProductQuery,
mutation: ProductMutations
});
|
57788fc58e72352014acd9e7a9cf5a298347aff5
|
TypeScript
|
pnp/sp-dev-fx-webparts
|
/samples/react-property-bag-editor/src/webparts/shared/utils.ts
| 2.71875
| 3
|
import * as _ from "lodash";
import { Web } from "sp-pnp-js";
require("sp-init");
require("microsoft-ajax");
require("sp-runtime");
require("sharepoint");
import DisplayProp from "./DisplayProp";
/**
* Various utilitty functions used by the React-ProprtyBag* Webparts
*
* @export
* @class utils
*/
export default class utils {
//http://vipulkelkar.blogspot.com/2015/09/index-web-property-bag-using-javascript.html
/**
* See ://http://vipulkelkar.blogspot.com/2015/09/index-web-property-bag-using-javascript.html
* Encodes a PropertyKey so that it can be included in the Sharepoint vti_indexedpropertykeys property
*
* @static
* @param {any} propKey The unencoded Property Key
* @returns
*
* @memberOf utils
*/
public static EncodePropertyKey(propKey) {
var bytes = [];
for (var i = 0; i < propKey.length; ++i) {
bytes.push(propKey.charCodeAt(i));
bytes.push(0);
}
var b64encoded = window.btoa(String.fromCharCode.apply(null, bytes));
return b64encoded;
}
/**
* See ://http://vipulkelkar.blogspot.com/2015/09/index-web-property-bag-using-javascript.html
* Decodes a PropertyKey retrieved from the Sharepoint vti_indexedpropertykeys property
*
* @static
* @param {any} propKey The encoded Property Key
* @returns
*
* @memberOf utils
*/
public static DecodePropertyKey(propKey) {
const encoded = window.atob(propKey);
let decoded = "";
for (let x = 0; x < encoded.length; x = x + 2) {
decoded = decoded + encoded.substr(x, 1);
}
return decoded;
}
/**
* Decodes all the searchable Properities recived from Sharepoint
*
* @static
* @param {string} sp The encoded Sarchable Properties String
* @returns {Array<string>} An array of the names of all the searchable properties
*
* @memberOf utils
*/
public static decodeSearchableProps(sp: string): Array<string> {
const searchableprops: Array<string> = [];
if (sp) {
const encodedPropNames = sp.split("|");
for (const encodedPropName of encodedPropNames) {
searchableprops.push(this.DecodePropertyKey(encodedPropName));
}
}
return searchableprops;
}
/**
* AllProperties- the resullsts from web.select("Title", "AllProperties").expand("AllProperties").get()
* propertiesToSelect- The properties you waant to select out of AllProperties
* searchableProperties-- and araay of properties which are known to be searchjable
*
*/
/**
* Extracts a Array of DisplayProp's from AllProperties
*
* @static
* @param {*} AllProperties
* @param {Array<string>} propertiesToSelect The Properties to Select from AllProperties
* @param {Array<string>} searchableProperties An Array of Searchable Properties. These will be marked as seartchable in the results
* @param {boolean} [addMissingProps] Indicates if the method should add a empty property if it is in propertiesToSelect but not in AllProperties
* @returns {Array<DisplayProp>}
*
* @memberOf utils
*/
public static SelectProperties(AllProperties: any, propertiesToSelect: Array<string>, searchableProperties: Array<string>, addMissingProps?: boolean): Array<DisplayProp> {
const DisplayProps: Array<DisplayProp> = [];
for (const propToSelect of propertiesToSelect) {
const displayProp: DisplayProp = new DisplayProp(propToSelect);
displayProp.value = AllProperties[propToSelect];
if (_.find(searchableProperties, sp => { return sp === propToSelect; })) {
displayProp.searchable = true;
}
else {
displayProp.searchable = false;
}
DisplayProps.push(displayProp);
}
return DisplayProps;
}
/**
* Saves a Property into the SharePoint PropertyBag
*
* @static
* @param {string} name The name of the property to set
* @param {string} value The value to set
* @param {string} siteUrl The SPSite to set it in
* @returns
*
* @memberOf utils
*/
public static setSPProperty(name: string, value: string, siteUrl: string) {
return new Promise((resolve, reject) => {
let webProps;
const clientContext = new SP.ClientContext(siteUrl);
const web = clientContext.get_web();
webProps = web.get_allProperties();
webProps.set_item(name, value);
web.update();
webProps = web.get_allProperties();
clientContext.load(web);
clientContext.load(webProps);
clientContext.executeQueryAsync(
(sender, args) => { resolve(); },
(sender, args) => { reject(args.get_message()); }
);
});
}
/**
* Sets the values of the propnames parameter to be searchable in the selected site
*
* @static
* @param {string} siteUrl
* @param {Array<string>} propnames
* @returns {Promise<any>}
*
* @memberOf utils
*/
public static saveSearchablePropertiesToSharePoint(siteUrl: string, propnames: Array<string>): Promise<any> {
const encodedPropNames: Array<string> = [];
for (const propname of propnames) {
if (propname != "") {
encodedPropNames.push(this.EncodePropertyKey(propname));
}
}
return this.setSPProperty("vti_indexedpropertykeys", encodedPropNames.join("|") + "|", siteUrl);//need the pipe at the end too?
}
/**
* Forces a full crawl of a site by incrementing the vti_searchversion property
*
* @static
* @param {string} siteUrl The site to force a full crawl on
* @returns {Promise<any>}
*
* @memberOf utils
*/
public static forceCrawl(siteUrl: string): Promise<any> {
const web = new Web(siteUrl);
return web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
let version: number = r.AllProperties["vti_x005f_searchversion"];
if (version) {
version++;
this.setSPProperty("AllProperties", version.toString(), siteUrl);
}
});
}
/**
* Adds the siteTemplates as filter parameters to queryText
*
* @static
* @param {Array<string>} siteTemplates The Site templates to be included
* @param {string} querytext The queryText to add the filter to
* @returns {string} The new queryText with the filter included
*
* @memberOf utils
*/
public static addSiteTemplatesToSearchQuery(siteTemplates: Array<string>, querytext: string): string {
let newQueryText = querytext.valueOf();
if (siteTemplates.length > 0 && siteTemplates[0] !== "") {
newQueryText += " AND (";
for (const siteTemplate of siteTemplates) {
const siteTemplateParts = siteTemplate.split("#");
if (!siteTemplateParts[1]) {
newQueryText += "SiteTemplate=" + siteTemplateParts[0];
}
else {
newQueryText += "(SiteTemplate=" + siteTemplateParts[0] + " AND SiteTemplateId=" + siteTemplateParts[1] + ")";
}
if (siteTemplates.indexOf(siteTemplate) !== siteTemplates.length - 1) {
newQueryText += " OR ";
}
}
newQueryText += " )";
}
return newQueryText;
}
/**
* Adds filters to the querytext. Filters are OR'd together
*
* @static
* @param {Array<string>} filters The filters to add (in the form ManagedPropertyName=Value)
* @param {string} querytext
* @returns {string}
*
* @memberOf utils
*/
public static addFiltersToSearchQuery(filters: Array<string>, querytext: string): string {
let newQueryText = querytext.valueOf();
if (filters.length > 0 && filters[0] !== "") {
newQueryText += " AND ( ";
for (const filter of filters) {
newQueryText += " " + filter + " ";
if (filters.indexOf(filter) !== filters.length - 1) {
newQueryText += " OR ";
}
}
newQueryText += " )";
}
return newQueryText;
}
/**
* Parses a string that is returned from an SPFX Multiline Input Paramater inito an array of strings,
* removinng blank entries
*
*
* @static
* @param {string} value The value from the SPFX Multiline Input Paramater
* @returns {Array<string>}
*
* @memberOf utils
*/
public static parseMultilineTextToArray(value: string): Array<string> {
if (!value) {
return [];
}
return value.split('\n').filter(val => { return val.trim() != ""; });
}
}
|
a40dd3cf431af3348cb26a1a2c0473166d7a6feb
|
TypeScript
|
vadimnevinskiy/kama
|
/src/redux/profile-reducer.ts
| 2.703125
| 3
|
import {profileAPI, usersAPI} from '../api/api'
import {FORM_ERROR} from 'final-form'
import {ContactsType, PhotoType, PostType, ProfileType} from '../types/types'
import {AppStateType} from "./redux-store";
import {Dispatch} from "redux";
import {ThunkAction} from "redux-thunk";
const ADD_POST = 'ADD-POST'
const DELETE_POST = 'DELETE_POST'
const SET_USER_PROFILE = 'SET_USER_PROFILE'
const SET_STATUS = 'SET_STATUS'
const SET_PHOTO = 'SET_PHOTO'
type InitialStateProfileType = {
posts: PostType[]
postText: string
profile: ProfileType | null
status: string
}
let initialState: InitialStateProfileType = {
posts: [
{id: 0, text: 'Lorem ipsum dolor sit.', likes: 12},
{id: 1, text: 'Mecessitatibus numquam obcaecati officia porro quia quis vel.', likes: 1},
{id: 2, text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', likes: 2},
{id: 3, text: 'Consequatur deleniti libero nam.', likes: 334}
],
postText: '',
profile: null as ProfileType | null,
status: ''
}
const profileReducer = (
state: InitialStateProfileType = initialState,
action: ActionsTypes
): InitialStateProfileType => {
switch (action.type) {
case ADD_POST: {
let newPost = {
id: state.posts.length + 1,
text: action.postText,
likes: 0
}
return {
...state,
postText: '',
posts: [...state.posts, newPost]
}
}
case DELETE_POST: {
return {
...state,
posts: state.posts.filter(p => p.id !== action.postId)
}
}
case SET_USER_PROFILE: {
return {
...state,
profile: action.profile
}
}
case SET_STATUS: {
return {
...state,
status: action.status
}
}
case SET_PHOTO: {
return {
...state,
profile: {...state.profile, photos: action.photos} as ProfileType // https://youtu.be/7s8RJw6uWsQ?list=PLcvhF2Wqh7DM3z1XqMw0kPuxpbyMo3HvN&t=3252
}
}
default:
return state
}
}
type ActionsTypes = addPostActionCreatorType | deletePostActionCreatorType |
setUserProfileActionType | setStatusActionType | savePhotoSuccessActionType
type addPostActionCreatorType = {
type: typeof ADD_POST,
postText: string
}
type deletePostActionCreatorType = {
type: typeof DELETE_POST,
postId: number
}
type setUserProfileActionType = {
type: typeof SET_USER_PROFILE,
profile: ProfileType
}
type setStatusActionType = {
type: typeof SET_STATUS,
status: string
}
type savePhotoSuccessActionType = {
type: typeof SET_PHOTO,
photos: PhotoType
}
export const addPostActionCreator = (postText: string): addPostActionCreatorType => {
return {
type: ADD_POST,
postText: postText
}
}
export const deletePostActionCreator = (postId: number): deletePostActionCreatorType => {
return {
type: DELETE_POST,
postId: postId
}
}
export const setUserProfile = (profile: ProfileType): setUserProfileActionType => {
return {
type: SET_USER_PROFILE,
profile: profile
}
}
export const setStatus = (status: string): setStatusActionType => {
return {
type: SET_STATUS,
status: status
}
}
export const savePhotoSuccess = (photos: PhotoType): savePhotoSuccessActionType => {
return {
type: SET_PHOTO,
photos: photos
}
}
type GetStateType = () => AppStateType
type DispatchType = Dispatch<ActionsTypes>
type ThunkType = ThunkAction<Promise<any | void>, AppStateType, unknown, ActionsTypes>
// THUNK CREATORS
export const getProfile = (userId: number | null): ThunkType => async (dispatch) => {
let response = await usersAPI.getProfile(userId)
if (response) {
dispatch(setUserProfile(response))
}
}
export const getStatus = (userId: number): ThunkType => async (dispatch) => {
let response = await profileAPI.getStatus(userId)
if (response) {
dispatch(setStatus(response.data))
}
}
export const updateStatus = (status: string): ThunkType => async (dispatch) => {
try {
let response = await profileAPI.updateStatus(status)
if (response && response.data.resultCode === 0) {
dispatch(setStatus(status))
}
} catch (e) {
if (e.message) {
alert(e.message)
}
}
}
export const savePhoto = (file: any): ThunkType => async (dispatch) => {
let response = await profileAPI.savePhoto(file)
if (response.resultCode === 0) {
dispatch(savePhotoSuccess(response.data.photos))
}
}
export const saveProfile = (profile: ProfileType): ThunkType => async (dispatch, getState) => {
const userId = getState().auth.userId
const response = await profileAPI.saveProfile(profile)
if (response.data.resultCode === 0) {
dispatch(getProfile(userId))
} else {
return {[FORM_ERROR]: response.data.messages[0]}
}
}
export default profileReducer
|
aa215077baaacbea38ac7fd3de35942903495731
|
TypeScript
|
kiwicom/orbit
|
/packages/orbit-components/src/primitives/ButtonPrimitive/common/getSizeToken.ts
| 2.59375
| 3
|
import { SIZE_OPTIONS, TOKENS } from "./consts";
import type { Size } from "../types";
import type { Theme } from "../../../defaultTheme";
const getSizeToken = (
size: Size,
theme: Theme,
): {
height: string;
fontSize: string;
} => {
const tokens = {
[TOKENS.heightButton]: {
[SIZE_OPTIONS.LARGE]: theme.orbit.heightButtonLarge,
[SIZE_OPTIONS.NORMAL]: theme.orbit.heightButtonNormal,
[SIZE_OPTIONS.SMALL]: theme.orbit.heightButtonSmall,
},
[TOKENS.fontSizeButton]: {
[SIZE_OPTIONS.LARGE]: theme.orbit.fontSizeButtonLarge,
[SIZE_OPTIONS.NORMAL]: theme.orbit.fontSizeButtonNormal,
[SIZE_OPTIONS.SMALL]: theme.orbit.fontSizeButtonSmall,
},
[TOKENS.spinnerWidth]: {
[SIZE_OPTIONS.LARGE]: theme.orbit.widthIconMedium,
[SIZE_OPTIONS.NORMAL]: theme.orbit.widthIconMedium,
[SIZE_OPTIONS.SMALL]: theme.orbit.widthIconSmall,
},
[TOKENS.spinnerHeight]: {
[SIZE_OPTIONS.LARGE]: theme.orbit.heightIconMedium,
[SIZE_OPTIONS.NORMAL]: theme.orbit.heightIconMedium,
[SIZE_OPTIONS.SMALL]: theme.orbit.heightIconSmall,
},
};
return {
height: tokens[TOKENS.heightButton][size],
fontSize: tokens[TOKENS.fontSizeButton][size],
};
};
export default getSizeToken;
|
7f23ba469ccad2d72effdbfe612369fb95c37c62
|
TypeScript
|
jcteague/efate
|
/packages/efate/src/utils.ts
| 2.9375
| 3
|
const isOfType =
<T>(type: string) =>
(value: any): value is T =>
typeof value === type;
export const isObject = isOfType<object>('object');
export const isFunction = isOfType<Function>('function');
export const isString = isOfType<string>('string');
|
1a3913eef85126d7cbb31c16c97736ec07182e4b
|
TypeScript
|
LuisAntonioDeMelo/AngularStudy
|
/Object-paradigm/Carro.ts
| 2.65625
| 3
|
import Veiculo from './Veiculo'
export default class Carro extends Veiculo {
private numeroDePortas : number
constructor(modelo:string,numeroDePortas :number,velocidade :number){
super()
this.modelo = modelo
this.velocidade = velocidade
this.numeroDePortas = numeroDePortas
}
public getModelo(): string {
return this.modelo
}
public setModelo(modelo : string):void {
this.modelo = modelo
}
}
|
f47de529bef35f6374605baa5bf6d3e1a8cbc077
|
TypeScript
|
tajpouria/GOF-design-pattenrs
|
/Patternts/Behavioral_Patterns/Strategy/ConceptualStrategy.ts
| 3.4375
| 3
|
namespace conceptualStrategy {
export class Context {
constructor(private strategy: Strategy) {}
doSth(data: any[]) {
return this.strategy.doAlgorithm(data);
}
}
interface Strategy {
doAlgorithm<T = string>(data: T[]): T[];
}
class ConcreteStrategyA implements Strategy {
doAlgorithm<T = string>(data: T[]): T[] {
return data.sort();
}
}
class ConcreteStrategyB implements Strategy {
doAlgorithm<T = string>(data: T[]): T[] {
return data.reverse();
}
}
export const strategies = { ConcreteStrategyA, ConcreteStrategyB };
}
namespace clientCode {
const {
Context,
strategies: { ConcreteStrategyA, ConcreteStrategyB },
} = conceptualStrategy;
const contextA = new Context(new ConcreteStrategyA());
const contextB = new Context(new ConcreteStrategyB());
console.info(contextA.doSth([1, 2, 0, 3]), contextB.doSth([12, 3, 4]));
}
|
8381f15ab7015c208dfd5566226d8bc5dc8ef784
|
TypeScript
|
js-works/js-cockpit
|
/boxroom/stuff/i18n-2022-06-21/localize/localize.ts
| 2.859375
| 3
|
import {
formatDate,
formatNumber,
formatRelativeTime,
getCalendarWeek,
getDirection,
getFirstDayOfWeek,
getWeekendDays,
parseDate,
parseNumber
} from './localize-utils'
export {
validateTranslations,
AbstractLocalizer,
Adapter,
Category,
DateFormat,
DayNameFormat,
Direction,
Locale,
Localizer,
MonthNameFormat,
NumberFormat,
RelativeTimeFormat,
RelativeTimeUnit,
TermKey,
TermValue,
Translation,
Translations,
PartialTranslation,
PartialTranslations
}
type Locale = string
type Category = string
type TermKey = string
type Direction = 'ltr' | 'rtl'
type TermValue = string | ((params: any, localizer: Localizer<any>) => string)
type Translation = {
[C: Category]: {
[K: TermKey]: TermValue
}
}
type Translations<T extends Translation = any> = Record<Locale, T>
type PartialTranslation<T extends Translation> = {
[C in keyof T]?: {
[K in keyof T[C]]?: T[C][K]
}
}
type PartialTranslations<T extends Translation> = Record<
Locale,
PartialTranslation<T>
>
interface NumberFormat extends Intl.NumberFormatOptions {}
interface DateFormat extends Intl.DateTimeFormatOptions {}
type RelativeTimeFormat = Intl.RelativeTimeFormatOptions
type RelativeTimeUnit = Intl.RelativeTimeFormatUnit
type DayNameFormat = 'long' | 'short' | 'narrow'
type MonthNameFormat = 'long' | 'short' | 'narrow'
interface Localizer<T extends Translation = any> {
getLocale(): Locale
getDirection(): Direction
translate<U extends Translation>(): <C extends keyof U, K extends keyof U[C]>(
category: C,
termKey: K,
params?: FirstArgument<U[C][K]>
) => string
translate<C extends keyof T>(
category: C
): <K extends keyof T[C]>(
termKey: K,
params?: FirstArgument<T[C][K]>
) => string
translate<C extends keyof T, K extends keyof T[C]>(
category: C,
termKey: keyof T[C],
params?: FirstArgument<T[C][K]>
): string
parseNumber(numberString: string): number | null
parseDate(dateString: string): Date | null
formatNumber(value: number, format?: NumberFormat): string
formatDate(value: Date, format?: DateFormat | null): string
formatRelativeTime(
value: number,
unit: RelativeTimeUnit,
format?: RelativeTimeFormat
): string
// 0 to 6, 0 means Sunday
getFirstDayOfWeek(): number
// array of integer form 0 to 6
getWeekendDays(): Readonly<number[]>
getCalendarWeek(date: Date): number // 1 to 53
getDayName(index: number, format?: DayNameFormat): string
getDayNames(format?: DayNameFormat): string[]
getMonthName(index: number, format?: MonthNameFormat): string
getMonthNames(format?: MonthNameFormat): string[]
}
type Adapter = {
translate: (
locale: Locale,
category: Category,
termKey: TermKey,
params?: Record<string, any>,
i18n?: Localizer
) => string
}
// === local types ===================================================
type FirstArgument<T> = T extends (firstArg: infer A, ...rest: any[]) => any
? A
: never
// === constants =====================================================
const regexCategory = /^[a-z][a-zA-Z0-9\.]*$/
const regexTermKey = /^[a-z][a-zA-Z0-9]*$/
// === validateTranslations ==========================================
function validateTranslations(translations: Translations): null | Error {
let ret: null | Error = null
try {
for (const locale of Object.keys(translations)) {
const translation = translations[locale]
for (const category of Object.keys(translation)) {
if (!category.match(regexCategory)) {
throw Error(`Illegal translations category name "${category}"`)
}
for (const termKey of Object.keys(translation[category])) {
if (!termKey.match(regexTermKey)) {
throw Error(`Illegal translation key "${termKey}"`)
}
}
}
}
} catch (error) {
ret = error as Error
}
return ret
}
// === AbstractLocalizer =============================================
abstract class AbstractLocalizer<T extends Translation>
implements Localizer<T>
{
#getLocale: () => Locale
#adapter: Adapter
constructor(getLocale: () => Locale, adapter: Adapter) {
this.#getLocale = getLocale
this.#adapter = adapter
}
getLocale(): Locale {
return this.#getLocale()
}
getDirection(): Direction {
return getDirection(this.#getLocale())
}
translate<U extends Translation>(): <C extends keyof U, K extends keyof U[C]>(
category: C,
termKey: K,
params?: FirstArgument<U[C][K]>
) => string
translate<C extends keyof T>(
category: C
): <K extends keyof T[C]>(
termKey: K,
params?: FirstArgument<T[C][K]>
) => string
translate<C extends keyof T, K extends keyof T[C]>(
category: C,
termKey: keyof T[C],
params?: FirstArgument<T[C][K]>
): string
translate(category?: any, termKey?: any, params?: any): any {
if (arguments.length === 0) {
return (category: any, key: any, params: any) =>
this.translate(category, key, params)
} else if (arguments.length === 1) {
return (key: any, params?: any) => this.translate(category, key, params)
}
return this.#adapter.translate(
this.#getLocale(),
category as string,
termKey as string,
(params as any) || null,
this as any // TODO!!!
)
}
parseNumber(numberString: string): number | null {
return parseNumber(this.#getLocale(), numberString)
}
parseDate(dateString: string): Date | null {
return parseDate(this.#getLocale(), dateString)
}
formatNumber(value: number, format?: NumberFormat): string {
return formatNumber(this.#getLocale(), value, format || {})
}
formatDate(value: Date, format?: DateFormat | null): string {
return formatDate(this.#getLocale(), value, format || {})
}
formatRelativeTime(
value: number,
unit: RelativeTimeUnit,
format?: RelativeTimeFormat
): string {
return formatRelativeTime(this.#getLocale(), value, unit, format || {})
}
// 0 to 6, 0 means Sunday
getFirstDayOfWeek(): number {
return getFirstDayOfWeek(this.#getLocale())
}
// array of integer form 0 to 6
getWeekendDays(): Readonly<number[]> {
return getWeekendDays(this.#getLocale())
}
// 1 to 53
getCalendarWeek(date: Date): number {
return getCalendarWeek(this.#getLocale(), date)
}
getDayName(index: number, format?: DayNameFormat): string {
const date = new Date(1970, 0, 4 + (index % 7))
return new Intl.DateTimeFormat(this.#getLocale(), {
weekday: format
}).format(date)
}
getDayNames(format?: DayNameFormat): string[] {
const arr: string[] = []
for (let i = 0; i < 7; ++i) {
arr.push(this.getDayName(i, format))
}
return arr
}
getMonthName(index: number, format?: MonthNameFormat): string {
const date = new Date(1970, index % 12, 1)
return new Intl.DateTimeFormat(this.#getLocale(), { month: format }).format(
date
)
}
getMonthNames(format?: MonthNameFormat): string[] {
const arr: string[] = []
for (let i = 0; i < 12; ++i) {
arr.push(this.getMonthName(i, format))
}
return arr
}
}
|
4b3ee347a3784ee7451b64fdf41574e7f8062498
|
TypeScript
|
YutoHayashi/web-hosting-app
|
/view/www/pages/api/hello.ts
| 2.515625
| 3
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string;
email: string;
password: string;
}
export const org = {
register: async ( params: Data ): Promise<object> => {
let data = {};
return new Promise( ( resolve, reject ) => {
try {
} catch( e ) {
reject( e );
} finally {
resolve( data );
}
} )
}
}
|
4c05e67f1196a6029137d52b1693f0f885cbfa8f
|
TypeScript
|
sylingd/SimpleVideoWeb
|
/src/api/video/submit.ts
| 2.53125
| 3
|
import { IVideo } from 'src/types';
import ajax from 'src/ajax';
const URL = "video";
interface IResponse {
id: number;
}
export default async function(req: IVideo) {
const res = await ajax({
url: URL,
post: {
name: req.name,
image: req.image,
aid: req.aid,
category: req.category
}
});
if (res.success) {
const data = (res.data as IResponse);
return data;
} else {
return new Error(res.error);
}
}
|
a9bc3d2f56f58acc777bd11a671c24793b2420d6
|
TypeScript
|
nexus-devtools/nydus
|
/src/versioned.ts
| 2.859375
| 3
|
/// <reference types="node" />
// Goal: Convert https://github.com/Blizzard/heroprotocol/blob/ffb1e5d53cce1a90a46febf44614c9c11bd3ed12/decoders.py#L168 to TypeScript
//
import { isArray } from "util";
import { BitPackedBuffer } from "./bitbuffer";
import * as NydusError from "./errors";
export class VersionedDecoder {
[key: string]: any;
protected typeInfos: Array<[string, any[]]>;
protected buffer: BitPackedBuffer;
constructor(contents: Buffer, typeInfos: Array<[string, any[]]>) {
this.buffer = new BitPackedBuffer(contents);
this.typeInfos = typeInfos;
}
public toString(): string {
return this.buffer.toString();
}
public instance(typeId: number): any {
if(typeId >= this.typeInfos.length) {
throw new NydusError.CorruptedError(`typeId ${typeId} is outside of typeInfo range ${this.typeInfos.length}`);
}
const typeInfo: [string, any[]] = this.typeInfos[typeId];
return this[typeInfo[0]](...typeInfo[1]);
}
public byteAlign(): void {
this.buffer.byteAlign();
}
public done(): boolean {
return this.buffer.done();
}
public usedBits(): number {
return this.buffer.usedBits();
}
public _expect_skip(expected: number): void {
const bits = this.buffer.readBits(8);
if(bits !== expected) {
throw new NydusError.CorruptedError(`Expected ${expected}, got ${bits}`);
}
}
public _vint(): number {
let b: number = this.buffer.readBits(8);
const negative: boolean = (b & 1) > 0;
let result: number = (b >> 1) & 0x3F;
let bits = 6;
while((b & 0x80) !== 0) {
b = this.buffer.readBits(8);
result |= (b & 0x7F) << bits;
bits += 7;
}
if(negative) {
return -result;
} else {
return result;
}
}
public _array(bounds: [number, number], typeId: number) {
this._expect_skip(0);
const length: number = this._vint();
const ret: any[] = [];
for(let i = 0; i < length; ++i) {
ret[i] = this.instance(typeId);
}
return ret;
}
public _bitarray(bounds: [number, number]): [number, Buffer] {
this._expect_skip(1);
const length: number = this._vint();
return [length, this.buffer.readAlignedBytes((length + 7) / 8)];
}
public _blob(bounds: [number, number]): Buffer {
this._expect_skip(2);
const length: number = this._vint();
return this.buffer.readAlignedBytes(length);
}
public _bool(): boolean {
this._expect_skip(6);
return this.buffer.readBits(8) !== 0;
}
public _choice(bounds: [number, number], fields: {[key: number]: any}): any {
this._expect_skip(3);
const tag: number = this._vint();
if(!(tag in fields)) {
this._skip_instance();
return {};
}
const field: any = fields[tag];
const ret: any = {};
ret[field[0]] = this.instance(field[1]);
return ret;
}
public _fourcc(): Buffer {
this._expect_skip(7);
return this.buffer.readAlignedBytes(4);
}
public _int(bounds:[number, number]): number {
this._expect_skip(9);
return this._vint();
}
public _null(): null {
return null;
}
public _optional(typeId: number): any {
this._expect_skip(4);
const exists = this.buffer.readBits(8) !== 0;
if(exists) {
return this.instance(typeId);
}
return this._null();
}
public _real32(): number {
this._expect_skip(7);
return this.buffer.readAlignedBytes(4).readFloatBE(0);
}
public _real64(): number {
this._expect_skip(8);
return this.buffer.readAlignedBytes(8).readDoubleBE(0);
}
public _struct(fields: any[]): any {
this._expect_skip(5);
let result: any = {};
const length: number = this._vint();
for(let i = 0; i < length; ++i) {
const tag: number = this._vint();
let field: any[] | null = null;
for(const f of fields) {
if(f[2] === tag) {
field = f;
break;
}
}
if(field === null) {
this._skip_instance();
continue;
}
if(field[0] === "__parent") {
const parent: any = this.instance(field[1]);
if(typeof parent === "object" && !isArray(parent)) {
for(const key in parent) {
if(key in parent) {
result[key] = parent[key];
}
}
} else if(fields.length === 1) {
result = parent;
} else {
result[field[0]] = parent;
}
} else {
result[field[0]] = this.instance(field[1]);
}
}
return result;
}
public _skip_instance(): void {
const skip: number = this.buffer.readBits(8);
switch(skip) {
case 0: {
const length: number = this._vint();
for(let i = 0; i < length; ++i) {
this._skip_instance();
}
break;
}
case 1: {
const length: number = this._vint();
this.buffer.readAlignedBytes((length + 7) / 8);
break;
}
case 2: {
const length: number = this._vint();
this.buffer.readAlignedBytes(length);
break;
}
case 3: {
this._vint();
this._skip_instance();
break;
}
case 4: {
const exists: boolean = this.buffer.readBits(8) !== 0;
if(exists) {
this._skip_instance();
}
break;
}
case 5: {
const length: number = this._vint();
for(let i = 0; i < length; ++i) {
this._vint();
this._skip_instance();
}
break;
}
case 6: {
this.buffer.readAlignedBytes(1);
}
case 7: {
this.buffer.readAlignedBytes(4);
}
case 8: {
this.buffer.readAlignedBytes(8);
}
case 9: {
this._vint();
}
}
}
}
|
914e787b42f5a27f01e0b1282b8a4d38278d328a
|
TypeScript
|
daledeleo/comunitarias
|
/src/app/clases/centro-acopio/centro-acopio-class.ts
| 2.59375
| 3
|
export class CentroAcopioClass {
id?:string;
name: string;
address?: string;
contactName:string;
contactPhone:string;
photo:File;
latitude?: number;
longitude?: number;
createdBy: string;
constructor(){}
public setCreateBy(createdBy:string){
this.createdBy=createdBy;
}
public setId(id:string){
this.id=id;
}
public setaddress(address:string){
this.address=address;
}
public setlatitude(latitude:number){
this.latitude=latitude;
}
public setlongitude(longitude:number){
this.longitude=longitude;
}
public setName(name:string){
this.name=name;
}
}
export interface Centro_Acopio{
Categorias: Array<CentroAcopioClass>
}
|
b8623c37d7ff1ac06d666319c19524663735081d
|
TypeScript
|
frydlewicz/AutoComplete
|
/public/js/stopwatch.ts
| 2.875
| 3
|
class Stopwatch {
private time: number;
public start(): void {
this.time = Date.now();
}
public end(): number {
return Date.now() - this.time;
}
}
|
078e110474089c7849c749448de9a381d5627acb
|
TypeScript
|
lebronjs/mini-utils
|
/src/utils/verify.ts
| 2.6875
| 3
|
export default {
/**
* 判断是不是数组
*/
isArrayLike: (param: any): boolean => {
return {}.toString.apply(param).slice(8, -1) === 'Array';
}
};
|
f6c75974a9bb7316469c420b76630657734ca969
|
TypeScript
|
penkong/devref-full-ts-graph-cra-auth
|
/app/services/list/src/database/access/connectDb.ts
| 2.53125
| 3
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { MongoClient } from 'mongodb'
import { config } from '../../config'
import { Database, Listing } from '../../@types/types'
// ---
const { DBURL, MONGOUSER, MONGOPASS, DBNAME } = config
const url = DBURL!
.replace('<MONGOUSER>', MONGOUSER!)
.replace('<MONGOPASS>', MONGOPASS!)
let client: MongoClient
// ---
export const connectDB = async (): Promise<Database> => {
try {
//
client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const con = await client.connect()
if (!con.isConnected()) throw new Error('DATABASE IS NOT connected!')
const db = client.db(DBNAME)
return {
listings: db.collection<Listing>('listing'),
client
}
//
} catch (error) {
//
console.log(error)
await client.close()
throw new Error('DB ERROR!')
}
}
|
fc3d55e94b5fd9aec267eb3764534791ae9793a3
|
TypeScript
|
abdiUNO/Feather-Backend
|
/src/database/factories/PostFactory.ts
| 2.53125
| 3
|
import { define } from 'typeorm-seeding';
import { Post } from '../../entity/post.entity';
import Faker from 'faker';
import { User } from '../../entity/user.entity';
declare global {
interface Date {
subHours: any;
subMinutes: any;
subDate: any;
}
}
define(Post, (faker: typeof Faker, settings: { userId }) => {
const CATEGORIES = ['Music', 'Gaming', 'Movies'];
const post = new Post();
post.text = faker.lorem.words(Math.floor(Math.random() * 20 + 5));
post.category = CATEGORIES[Math.floor(Math.random() * CATEGORIES.length)];
post.userId = settings.userId;
post.votesCount = Math.floor(Math.random() * 100) + 1;
post.commentsCount = Math.floor(Math.random() * 100) + 1;
return post;
});
|
b4a391fe3a35bdec2d09008e91006f9968476794
|
TypeScript
|
haridevelops/OpenThoughtsApp
|
/src/app/shared/registration.modal.ts
| 2.578125
| 3
|
export class Registration {
public username: string;
public password: string;
constructor(name, password) {
this.password = password;
this.username = name;
}
}
|
f64af27bef698a08d2e3566c6d4d0b35fc7b3a16
|
TypeScript
|
ithiris/Angular-crud-Application
|
/crud/src/app/employee.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {EventEmitter} from '@angular/core';
import {Employee} from "./employeemodel";
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
startedEditing = new Subject<number>();
employeeChanged =new EventEmitter<Employee[]>();
private employees:Employee[]=[
new Employee('abdul' ,'programmer'),
new Employee('umar' ,'java'),
]
Employee=JSON.parse(localStorage.getItem("employees"));
constructor() {
}
getEmployee(){
return this.employees.slice();
}
getEmployeeData(index:number){
return this.employees[index]
}
// getIngredient(index:number){
// return this.ingredients[index];
//
// }
addEmployee(employee:Employee){
this.employees.push(employee)
this.employeeChanged.emit(this.employees.slice());
let newNote = JSON.stringify(this.employees);
localStorage.setItem("employees", newNote);
}
updateEmployee(index:number,newEmployee:Employee){
this.employees[index]=newEmployee;
this.employeeChanged.next(this.employees.slice())
}
deleteEmployee(index:number){
this.employees.splice(index,1);
this.employeeChanged.next(this.employees.slice())
}
}
|
188e4860e70231183f67d1cac21cc1a1ac3683fc
|
TypeScript
|
christianscott/ts_get_imported_files
|
/src/resolver.ts
| 2.59375
| 3
|
import * as tsConfigPaths from "tsconfig-paths";
import { Dependency } from "./parse";
import { Preconditions } from "./preconditions";
export class Resolver {
private readonly matchPath: tsConfigPaths.MatchPath;
constructor(
tsConfigFilePath: string,
private readonly resolvableExtensions: readonly string[]
) {
const loadResult = tsConfigPaths.loadConfig(tsConfigFilePath);
if (loadResult.resultType === "failed") {
throw new Error(loadResult.message);
}
this.matchPath = tsConfigPaths.createMatchPath(
loadResult.absoluteBaseUrl,
loadResult.paths
);
}
resolve(dep: Dependency): string | undefined {
const path = Preconditions.checkExists(dep.path.lexeme);
return this.matchPath(
path,
undefined,
undefined,
this.resolvableExtensions
);
}
}
|
7dc06317e109fba2df2780e054a81a92fcadae46
|
TypeScript
|
famedzeus/flexReporter
|
/src/app/store/utils.ts
| 3.21875
| 3
|
import { Injectable } from '@angular/core'
import { orderBy as orderFn } from 'lodash'
import * as deepFreeze from 'deep-freeze'
@Injectable()
export class PaginationService {
orderBy = orderFn
sortDataset (dataset: Array<any> = [], sortField: string = '', page: number = 0, size: number = 20) {
if (dataset.length === 0) return []
const { sort, order } = this.getSort(sortField)
const sortedData = this.orderBy(dataset, sort, order)
return this.pageDataset(sortedData, page, size)
}
pageDataset (dataset: Array<any> = [], page: number = 0, size: number = 20) {
const { first, last } = this.getTotals(page, size, dataset.length)
return dataset.slice(first, last + 1)
}
/**
*
* @param page Current page number
* @param size Items per page
* @param itemCount Expected total items in data
*/
private getTotals (page: number, size: number, itemCount: number) {
const first = page * size
const last = ((page + 1) * size) - 1
return {
first,
last: last > itemCount ? itemCount - 1 : last
}
}
private getSort (sortKey: string) {
if (sortKey[0] === '-') {
return {
sort: [sortKey.substr(1, sortKey.length - 1)],
order: ['desc']
}
}
return {
sort: [sortKey],
order: ['asc']
}
}
}
export const indexAsId = (obj, index) => Object.assign(obj, { __id: index })
export const withoutId = obj => objN => obj.__id !== objN.__id
/**
* Naive counter based Id generator
*/
export const getIdGen = () => {
let i = 0
return () => i++
}
/**
* Attempt to get results from function, provide fallback value if error
*/
export const invokeSafe = <T, U>(fn: (...args) => T, fallback: U = void 0) => {
return function (...args) {
try {
return fn(...args)
} catch (e) {
return fallback
}
}
}
/**
* Produces a reducer(or another type) function which
* freezes the state argument to ensure that mutation does not occur.
* Use only tests to as it will affect runtime performance
* @param reducer
*/
export const deepFreezeReducer =
<T, U>(reducer: (T, U) => T) =>
(state: T, action: U) =>
(state === undefined || state === null)
? reducer(state, action)
: reducer(deepFreeze(state), action)
|
abfb751457e7529a57b5aa32e3f408f2865cb991
|
TypeScript
|
roopertti/yearly-album-challenge
|
/src/routes/AuthRoutes.ts
| 2.53125
| 3
|
import express from 'express';
import passport from 'passport';
import { User as UserReduxType } from '../client/types/userTypes';
import { IUser } from '../models/User';
const AuthRouter: express.Router = express.Router();
/* Spotify User API scopes */
const SpotifyScopes = ['user-read-email', 'user-read-private'];
AuthRouter.get('/', passport.authenticate('spotify', { scope: SpotifyScopes }));
AuthRouter.get('/callback', passport.authenticate('spotify', { failureRedirect: '/404' }), (req, res) => {
const { id, spotifyId, username, displayName } = req.user as IUser;
const userData: UserReduxType = { id, spotifyId, username, displayName };
res.send(userData);
});
AuthRouter.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
export default AuthRouter;
|
fd1bf7507435caea74595e1a758619cbf3b2dcfb
|
TypeScript
|
ReseauEntourage/entourage-webapp
|
/src/core/useCases/authUser/authUser.selectors.ts
| 2.53125
| 3
|
import { createSelector } from 'reselect'
import { AuthUserState } from './authUser.reducer'
interface AppState {
authUser: AuthUserState;
}
export function selectIsLogging(state: AppState) {
return state.authUser.isLogging
}
export function selectStep(state: AppState) {
return state.authUser.step
}
export function selectIsLogged(state: AppState) {
return !!state.authUser.user
}
export function selectUser(state: AppState) {
return state.authUser.user
}
export function selectUserIsUpdating(state: AppState) {
return state.authUser.userUpdating
}
export function selectUserInfosAreIncomplete(state: AppState) {
const { user } = state.authUser
if (user) {
const { firstName, lastName, address } = user
return !(firstName?.trim()) || !(lastName?.trim()) || !address
}
return true
}
export function selectErrors(state: AppState) {
return state.authUser.errors
}
export function selectLoginIsCompleted(state: AppState) {
return state.authUser.loginIsCompleted
}
export function selectShowSensitizationPopup(state: AppState) {
return state.authUser.showSensitizationPopup
}
export const selectHasNoSetupPopupToShow = createSelector(
selectIsLogged,
selectUserInfosAreIncomplete,
selectShowSensitizationPopup,
(isLogged, userInfosAreIncompleted, showSensitizationPopup) => {
const willOpenAnotherPopup = isLogged && (userInfosAreIncompleted || showSensitizationPopup)
return !willOpenAnotherPopup
},
)
|
5456f749174d7e94e9a7de233a30eab5d4318c99
|
TypeScript
|
monetha/claims-js-sdk
|
/dist/models/claim.d.ts
| 2.84375
| 3
|
import BigNumber from 'bignumber.js';
export interface IClaim {
/**
* Dispute id
*/
id: number;
/**
* Id of the deal which dispute was opened for
*/
dealId: number;
/**
* Dispute's requester id
*/
requesterId: string;
/**
* Dispute's respondent id
*/
respondentId: string;
/**
* Dispute requester's wallet address
*/
requesterAddress: string;
/**
* Dispute respondent's wallet address
*/
respondentAddress: string;
/**
* Requester's description of the problem the dispute was opened for
*/
reasonNote: string;
/**
* Respondent's provided resolution note to the problem
*/
resolutionNote: string;
/**
* Amount of staked MTH tokens
*/
requesterStaked: BigNumber;
/**
* Dispute's state
*/
stateId: ClaimStatus;
/**
* Date when dispute was last modified
*/
modifiedAt: string;
/**
* Claim handler's contract address that dispute is stored in
*/
contractAddress: string;
}
export declare enum ClaimStatus {
Null = 0,
/**
* Dispute was opened by requester and awaits respondent's acceptance
*/
AwaitingAcceptance = 1,
/**
* Dispute was accepted by respondent and awaits for respondent's resolution
*/
AwaitingResolution = 2,
/**
* Dispute was resolved by respondent and awaits for requester's confirmation
*/
AwaitingConfirmation = 3,
/**
* Dispute was closed by requester after acceptance period has expired
*/
ClosedAfterAcceptanceExpired = 4,
/**
* Dispute was closed by requester after resolution period has expired
*/
ClosedAfterResolutionExpired = 5,
/**
* Dispute was closed by requester after confirmation period has expired
*/
ClosedAfterConfirmationExpired = 6,
/**
* Dispute was closed by requester after respondent's resolution
*/
Closed = 7
}
|
25d260fa3299e92dacc7c1051555e14364815927
|
TypeScript
|
kkpgarcia/luna-imgui
|
/src/engine-dev/Loader.ts
| 2.8125
| 3
|
import { Resource, Directory, AppCache, CacheType } from "@luna-engine/utility";
export default class Loader
{
private _loaderError = false;
private _loadersCount = 0;
private _progress = 0;
private _currentLoaded = 0;
constructor(loadMap: { textures, shaders }, onComplete: Function, onError: Function)
{
let loaderFunctions: Function[] = [];
//Add textures
let texLoaders = this.CreateLoaderArray(loadMap.textures, (name) => {
Resource.instance.GetImage(Directory.TEXTURE_DIR, name, (data: any) => {
AppCache.instance.AddTexture(name, data);
console.log(data);
})
});
//Add shaders
let shaderLoaders = this.CreateLoaderArray(loadMap.shaders, (name) => {
Resource.instance.GetText(Directory.SHADER_DIR, name, (data: string) => {
AppCache.instance.AddShader(name, data);
})
});
loaderFunctions = loaderFunctions.concat(texLoaders);
loaderFunctions = loaderFunctions.concat(shaderLoaders);
this._loadersCount = loaderFunctions.length;
this.UpdateProgress();
const loader = this.CreateLoaderPromise(loaderFunctions);
loader.then(async (value: number) => {
let delayedStart = () => {
if (value == 0)
{
//Sanity check for resources
const allLoaded =
AppCache.instance.CheckContains(CacheType.TEXTURE, loadMap.textures) &&
AppCache.instance.CheckContains(CacheType.SHADER, loadMap.shaders);
if (allLoaded)
{
//Start Application
onComplete ? onComplete() : () => {};
}
else
{
onError ? onError("Some resources was not loaded.") : () => {};
}
}
else
{
onError ? onError("Some resources had errors while loading.") : () => {};
}
};
await (new Promise(((resolve, reject) => setTimeout(delayedStart, 1000))));
})
}
private CreateLoaderArray(resource: string[], action: Function): Function[]
{
let retVal: Function[] = [];
for (let i = 0; i < resource.length; i++)
{
retVal.push(() => action(resource[i]));
}
return retVal;
}
//TODO: Change to monad/promise chain/task
private CreateLoaderPromise(loaders: Function[]): Promise<number>
{
return new Promise((resolve, reject) => {
if(!this._loaderError)
{
for (let i = 0; i < loaders.length; i++)
{
const handler = loaders[i];
//TODO: Do reject checks here
handler();
this._currentLoaded++;
this.UpdateProgress();
}
resolve(0);
}
else
{
reject(404);
}
});
}
private UpdateProgress(): void
{
this._progress = this._currentLoaded / this._loadersCount;
console.log("Loading in progress: " + (this._progress * 100) + "%");
}
}
|
4128a10fe5b3cccd98ea341d2a345106793f47b0
|
TypeScript
|
oromano/nestjs-response-utils
|
/src/response-transformer/response-codes/meta-response-generator.ts
| 2.859375
| 3
|
import { MetaResponse } from './meta-response';
import { ResponseCode } from './response-code';
import { HttpStatus } from '@nestjs/common';
export class MetaResponseGenerator {
/**
*
*
* @static
* @template resultType
* @param {resultType} value
* @param {ResponseCode} responseCode
* @memberof MetaResponseGenerator
*/
static generateFull<resultType>(
value: resultType,
responseCode: ResponseCode) {
const instance = new MetaResponse();
instance.value = value;
instance.addResponseCode(responseCode)
}
/**
*
*
* @static
* @template resultType
* @param {resultType} value
* @param {ResponseCode} responseCode
* @returns {MetaResponse<resultType>}
* @memberof MetaResponseGenerator
*/
static generateByResponseCode<resultType>(
value: resultType,
responseCode: ResponseCode,
): MetaResponse<resultType> {
const instance = new MetaResponse<resultType>();
instance.value = value;
instance.addResponseCode(responseCode);
return instance;
}
/**
*
*
* @static
* @template resultType
* @param {ResponseCode} responseCode
* @returns {MetaResponse<resultType>}
* @memberof MetaResponseGenerator
*/
static generateAnErrorResponse<resultType>(
responseCode: ResponseCode,
): MetaResponse<resultType> {
return this.generateByResponseCode(null, responseCode);
}
/**
*
*
* @static
* @template resultType
* @param {HttpStatus} httpStatus
* @param {*} error
* @returns
* @memberof MetaResponseGenerator
*/
static generateErrorByStatus<resultType>(httpStatus: HttpStatus, error: any) {
return this.generateByResponseCode(null, new ResponseCode(httpStatus, undefined, undefined, undefined, undefined, error));
}
}
|
d36fad729f9dfbb616e1db15a048dae9c80ae17a
|
TypeScript
|
OlehBabiak/typescript
|
/home_work_ts/Parlament.ts
| 3.125
| 3
|
import {Party} from "./Party";
import {Deputy} from "./Deputy";
class Parlament {
country: string;
city: string;
parties: Party[]
constructor(country: string, city: string, parties: Party[]) {
this.country= country
this.city=city
this.parties =parties
}
addParty(parties: Party[]){
parties.push()
console.log('New Parl: ', parties)
}
deleteParty(parties: Party[]){
parties.pop()
console.log('New Parl: ', parties)
}
allParties(){
}
someParty(parties: Party[]){
}
}
let Deputy1 = new Deputy('Чорновіл','Петро', 44,'male' ,0.1, 12000, 'OPZG', true )
let Deputy2 = new Deputy('Popovich','Ivan', 32,'male', 0.4, 12000, 'OPZG', false )
let Deputy3 = new Deputy('Kazinak','Petro', 65,'male', 0.6, 8000, 'ZE', true )
let Deputy4 = new Deputy('Chereshnja','Andrij', 37,'male', 0.8, 7000, 'ZE', false )
let Deputy1Status = Deputy1.giveBribe(0.1, 12000, 'Петро', 'Чорновіл')
let Deputy2Status = Deputy2.giveBribe(0.4, 9000, 'Ivan', 'Popovich')
let Deputy3Status = Deputy3.giveBribe(0.6, 12000, 'Petro', 'Kazinak')
let Deputy4Status = Deputy4.giveBribe(0.8, 2000, 'Andrij', 'Chereshnja')
let Party1 = new Party('OPZG', Deputy1, [Deputy1, Deputy2])
let Party2 = new Party('ZE', Deputy3, [Deputy3, Deputy4])
let Party3 = new Party('OZ', Deputy2, [Deputy2, Deputy3])
let UkraineParlament = new Parlament('Ukraine', 'Kyiv', [])
console.log('UK p: ', UkraineParlament)
UkraineParlament.addParty([Party1, Party2, Party3])
// - додати\видалити фракцію +
// - вивести всі фракції
// - вивести конкретну фракцію
//// - додати\видалити депутата з фракції
// // - вивести всіх хабарників фракції
// // - вивести найбільшого хабарника у фрації
// //вивести фсіх депутатів фракції
// Сума при якій депутат перестає вагатись рівна "мінімальна сума * % чесності". +
// Тобто, якщо депутат чесний на 10% і сума взяти рівна 1000, а видаєте 1200, то депатут перестає вагатись, +
// та бере хабар.
// Але якщо при таких самих усовах хабар складає 1050, то він буде вагатись.+
// !!! Хабарником рахується людина, в якої рівень чесності нижчий за 50 !!!+
// Якщо сума взяти менша за мінімальку, тоді хабарь дати не можливо + (як це поєднати з умовою !!! +
// Хабарником рахується людина, в якої рівень чесності нижчий за 50 !!!) +
|
77a851d2128e7acf953871a670e580e09c474dc8
|
TypeScript
|
JoseAngelGallardoPerez/wallet-frontend
|
/src/app/core/helpers/options.helper.ts
| 3.046875
| 3
|
import { OptionModel } from '@models/option.model';
import { OptionsPrefixes } from '@app/core/constants/optionsPrefixes';
import { camelCaseToSnakeCase, snakeToCamelCase } from '@helpers/stringHelpers';
export class OptionsHelper {
private readonly fieldPrefix: string;
private readonly fieldRegExp: RegExp;
private trueValue = 'yes';
private falseValue = 'no';
constructor(fieldPrefix: OptionsPrefixes) {
this.fieldPrefix = fieldPrefix;
this.fieldRegExp = new RegExp(`^${this.fieldPrefix}(\\w+)$`);
}
public optionToPureObject(option: OptionModel): { [key: string]: boolean | string } | null {
const key: string | null = this.parsePath(option.path);
return key ? { [key]: this.parseValue(option.value) } : null;
}
public optionsArrayToPureObject(options: OptionModel[]): { [key: string]: boolean | string } {
const result: { [key: string]: any } = {};
options.forEach((option) => {
const parsedKey = this.parsePath(option.path);
if (parsedKey) {
result[this.parsePath(option.path)] = this.parseValue(option.value);
}
});
return result;
}
public serializePureObjectToOptionsArray(pureObject: { [key: string]: boolean | string }): OptionModel[] {
return Object.keys(pureObject).map((key): OptionModel => {
return new OptionModel({
path: this.serializePath(key),
value: this.serializeValue(pureObject[key])
});
});
}
public parseValue(value: string): boolean | string {
if (value === this.trueValue) {
return true;
}
if (value === this.falseValue) {
return false;
}
return value;
}
private parsePath(path: string): string | null {
const data = path.match(this.fieldRegExp);
return data ? snakeToCamelCase(data[1]) : null;
}
private serializePath(path: string): string {
return `${this.fieldPrefix}${camelCaseToSnakeCase(path)}`.replace('iso_2', 'iso2'); // @TODO: refactor this temporary solution
}
private serializeValue(value: boolean | string): string {
if (typeof value === 'boolean') {
return value ? this.trueValue : this.falseValue;
}
return value;
}
}
|
47f3cbd206514c2117480b2f6ff40fdede5de934
|
TypeScript
|
HRashidi/webpay-bahamta
|
/index.d.ts
| 2.546875
| 3
|
// Payment Interfaces
export interface IPaymentResult {
payment_url : string
}
export type IPaymentError =
| 'INVALID_API_CALL'
| 'INVALID_API_KEY'
| 'NOT_AUTHORIZED'
| 'INVALID_AMOUNT'
| 'LESS_THAN_WAGE_AMOUNT'
| 'TOO_LESS_AMOUNT'
| 'TOO_MUCH_AMOUNT'
| 'INVALID_REFERENCE'
| 'INVALID_TRUSTED_PAN'
| 'INVALID_CALLBACK'
| 'INVALID_PARAM'
| 'ALREADY_PAID'
| 'MISMATCHED_DATA'
| 'NO_REG_TERMINAL'
| 'NO_AVAILABLE_GATEWAY'
| 'SERVICE_ERROR'
| 'NETWORK_ERROR';
export interface IPaymentSuccesResponse {
ok : boolean,
result : IWebpayResult,
}
export interface IPaymentErrorResponse {
ok : boolean,
error : IPaymentError
}
export type IPaymentResponse = IPaymentSuccesResponse | IPaymentErrorResponse;
/**
* @param {string} api_key - The bahamta api-key: 'webpay:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz'
* @param {string} reference - The order number (should be unique): 'order#1004'
* @param {number} amount_irr - The amount of money in Rials: 100000
* @param {string} callback_url - Call back url for bahamta recall (should start with http or https) : 'https://mydomain.ir/checkout/order#1004'
* @param {string} payer_mobile - The payer mobile number: '98912*******'
* @param {string} trusted_pan - The trusted credit cards number list: '6219234531241234,623254******5645,5453612376879876'
* @returns {Promise} - Promise object represents server response success=({ok: true, result}), failure = ({ok: false, error})
*/
export function payment(api_key: string, reference: string, amount_irr: number, callback_url: string, payer_mobile?: string, trusted_pan?: string): Promise<IPaymentResponse>;
// Verify InterFaces
export type IVerifyError =
| 'INVALID_API_CALL'
| 'INVALID_API_KEY'
| 'NOT_AUTHORIZED'
| 'INVALID_AMOUNT'
| 'INVALID_REFERENCE'
| 'INVALID_PARAM'
| 'UNKNOWN_BILL'
| 'MISMATCHED_DATA'
| 'NOT_CONFIRMED'
| 'SERVICE_ERROR'
| 'NETWORK_ERROR';
export interface IVerifyResult {
state : string,
total : number,
wage : number,
gateway : string,
terminal : string,
pay_ref : string,
pay_trace : string,
pay_pan : string,
pay_cid : string,
pay_time : Date
}
export interface IVerifySuccesResponse {
ok : boolean,
result : IVerifyResult,
}
export interface IVerifyErrorResponse {
ok : boolean,
error : IVerifyError
}
export type IVerifyResponse = IVerifySuccesResponse | IVerifyErrorResponse;
/**
* @param {string} api_key - The bahamta api-key: 'webpay:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz'
* @param {string} reference - The order number (should be unique): 'order#1004'
* @param {number} amount_irr - The amount of money in Rials: 100000
* @returns {Promise} - Promise object represents server response success=({ok: true, result}), failure = ({ok: false, error})
*/
export function verify(api_key: string, reference: string, amount_irr: number): Promise<IVerifyResponse>;
|
d2929c059bea8a84c1d5c28fcc34e03a10f2a741
|
TypeScript
|
AnsarSamad/MeanStack
|
/client/app/model/Task.ts
| 2.84375
| 3
|
export class Task {
title: string;
activity: string;
assignto: string;
sprint: string;
hours: number;
status: string;
isDone: boolean;
content: string
constructor(title: string, done: boolean) {
this.title = title;
this.isDone = done;
}
setContent(content: string) {
this.content = content;
}
}
|
5f5ed88ee8c628cd550d07e8182438f02ad9b3f8
|
TypeScript
|
PinkiNice/billy_sharer
|
/src/api/index.ts
| 2.546875
| 3
|
import { User } from '@/db/models/User';
export async function createNewUser(id, username) {
let existingUser = User.findOne({ id });
if (existingUser) {
return;
}
let user = new User({
username: username,
id: id,
});
await user.save();
return user;
}
export async function syncUserUsername(id, username) {
User.updateOne({ id }, { username });
}
export async function getUser(id, username) {
let promise = User.findOne({ id });
let user = await promise;
if (user) {
user.update({ username });
} else {
user = new User({
id,
username,
});
}
await user.save();
return user;
}
export async function getUserByUsername(username) {
console.log('searching for', username);
let user = await User.findOne({ username });
console.log('User: ', user);
return user;
}
export const Api = {
getUser,
};
export async function getAllUsers() {
return User.find();
}
|
a61fc0b93785393c7c69db6aee8f5998b66e0ab8
|
TypeScript
|
adamkekesi/VaccinationHelper
|
/backend/src/auth/dto/doctor-register.dto.ts
| 2.625
| 3
|
import {
IsBoolean,
IsDate,
IsEmail,
IsNotEmpty,
IsPhoneNumber,
MaxLength,
} from "class-validator";
import { Serializable, JsonProperty } from "typescript-json-serializer";
import { PasswordRestrictions } from "src/shared/decorators/validation/password-restrictions.decorator";
@Serializable()
export default class DoctorRegisterDto {
@JsonProperty()
@IsNotEmpty({
message: "fullName-empty",
context: { skipOthers: true },
})
public fullName: string;
@JsonProperty()
@IsNotEmpty({
message: "email-empty",
context: { skipOthers: true },
})
@IsEmail(undefined, { message: "invalid-email" })
public email: string;
@JsonProperty()
@IsNotEmpty({
message: "phoneNumber-empty",
context: { skipOthers: true },
})
@IsPhoneNumber("HU", { message: "phoneNumber-invalid" })
public phoneNumber: string;
@JsonProperty()
@IsNotEmpty({
message: "city-empty",
context: { skipOthers: true },
})
public city: string;
@JsonProperty()
@PasswordRestrictions()
public password: string;
@JsonProperty()
@IsBoolean({ message: "isHomeDoctor-invalid" })
public isHomeDoctor: boolean;
@JsonProperty()
@IsBoolean({ message: "isVaccinatorDoctor-invalid" })
public isVaccinatorDoctor: boolean;
}
|
0f68f96d838341224500b3702987b55069374a1b
|
TypeScript
|
backupforks/tsql
|
/src/expr-library/assert/throw-if-null.ts
| 2.5625
| 3
|
import * as tm from "type-mapping";
import {AnyBuiltInExpr, BuiltInExprUtil} from "../../built-in-expr";
import {ExprUtil} from "../../expr";
import {OperatorNodeUtil} from "../../ast";
import {OperatorType} from "../../operator-type";
export type ThrowIfNullExpr<
ArgT extends AnyBuiltInExpr
> =
ExprUtil.Intersect<
Exclude<BuiltInExprUtil.TypeOf<ArgT>, null>,
ArgT
>
;
export function throwIfNull<
ArgT extends AnyBuiltInExpr
> (
arg : ArgT
) : (
ThrowIfNullExpr<ArgT>
) {
return ExprUtil.intersect<Exclude<BuiltInExprUtil.TypeOf<ArgT>, null>, ArgT>(
tm.notNull(BuiltInExprUtil.mapper(arg)),
[arg],
OperatorNodeUtil.operatorNode1(
OperatorType.THROW_IF_NULL,
[
BuiltInExprUtil.buildAst(arg)
],
undefined
)
);
}
|
134de7f91d1adbd2349d3f4edebddf43a2042b15
|
TypeScript
|
amidos2006/SokobanGeneration
|
/src/Global.ts
| 3.203125
| 3
|
declare interface Math{
randObj:any;
setRandomObject(randObj:any):void;
randInt(maxValue:number):number;
sign(value:number):number;
}
Math.setRandomObject = function(randObj:any):void{
Math.randObj = randObj;
}
Math.random = function (): number {
return Math.randObj.real(0, 1, false);
}
Math.randInt = function(maxValue:number):number {
return Math.randObj.integer(0, maxValue - 1);
}
Math.sign = function(value:number):number{
if(value < 0){
return -1;
}
if(value > 0){
return 1;
}
return 0;
}
class Global{
public static getDirection(input:number):any{
switch(input){
case 0:
return {x:-1, y:0};
case 1:
return {x:1, y:0};
case 2:
return {x:0, y:-1};
case 3:
return {x:0, y:1};
}
return {x:0, y:0};
}
public static getInput(x:number, y:number):number{
if(x == 0){
if(y > 0){
return 3;
}
else if(y < 0){
return 2;
}
}
else if(y == 0){
if (x > 0) {
return 1;
}
else if (x < 0) {
return 0;
}
}
return -1;
}
public static getDistance(p1, p2){
return Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y);
}
private static getNearestObject(box, Objects){
let boxLoc = box.getTile();
let index = 0;
let minDistance = Global.getDistance(boxLoc, Objects[index].getTile());
for(let i=1; i<Objects.length; i++){
let currentDistance = Global.getDistance(boxLoc, Objects[i].getTile());
if(currentDistance < minDistance){
minDistance = currentDistance;
index = i;
}
}
return index;
}
public static stringfy(sokoban):string{
let result:string = "";
let p = sokoban.player.getTile();
result += p.x + "," + p.y;
for(let b of sokoban.boulders){
p = b.getTile();
result += "," + p.x + "," + p.y;
}
return result;
}
public static stepsHeuristic(depth, sokoban):number{
let result = depth / 10 + Global.averageDistance(sokoban) * sokoban.boulders.length;
return 1 / (Math.log(result + 1) + 1);
}
public static solutionDistance(sol1:number[], sol2:number[]){
let short: number[] = sol1;
let long: number[] = sol2;
if (long.length < short.length) {
let temp = short;
short = long;
long = temp;
}
let minValue: number = Number.MAX_VALUE;
let currentValue: number = 0;
for (let i: number = 0; i < long.length - short.length + 1; i++) {
currentValue = 0;
for (let j: number = 0; j < short.length; j++) {
if (short[j] != long[j + i]) {
currentValue += 1;
}
}
if (currentValue < minValue) {
minValue = currentValue;
}
}
return minValue;
}
public static averageDistance(sokoban:any):number{
let targets: any[] = [];
for (let t of sokoban.targets) {
targets.push(t);
}
let boxes: any[] = [];
for (let b of sokoban.boulders) {
boxes.push(b);
}
let result: number = 0;
boxes.sort((a, b) => {
let i1 = Global.getNearestObject(a, targets);
let i2 = Global.getNearestObject(b, targets);
return Global.getDistance(a.getTile(), targets[i1].getTile()) -
Global.getDistance(b.getTile(), targets[i2].getTile());
});
for (let b of boxes) {
let index = Global.getNearestObject(b, targets);
result += Global.getDistance(b.getTile(), targets[index].getTile());
targets.splice(index, 1);
}
return result / boxes.length;
}
public static rotateInput(sol:number[], angle:number):number[] {
let mirror:number[] = [];
for(let input of sol){
let p: any = Global.getDirection(input);
let np: any = {x:0, y:0};
np.x = p.x * Math.cos(angle * Math.PI / 180) - p.y * Math.sin(angle * Math.PI / 180);
np.y = p.x * Math.sin(angle * Math.PI / 180) + p.y * Math.cos(angle * Math.PI / 180);
if(Math.abs(np.x) < 0.1){
np.x = 0;
}
else{
np.x = Math.sign(np.x);
}
if(Math.abs(np.y) < 0.1){
np.y = 0;
}
else{
np.y = Math.sign(np.y);
}
mirror.push(Global.getInput(np.x, np.y));
}
return mirror;
}
public static mirrorInput(sol: number[], hor: boolean, ver:boolean):number[] {
let mirror:number[] = [];
for(let input of sol){
let p:any = Global.getDirection(input);
if(hor){
if(p.y == 0){
p.x *= -1;
}
}
if(ver){
if(p.x == 0){
p.y *= -1;
}
}
mirror.push(Global.getInput(p.x, p.y));
}
return mirror;
}
public static sleep(amount) {
var start = new Date().getTime();
while (new Date().getTime() - start < amount);
}
}
|
ac123c9e94b0a34281afb0da1f67260986762b47
|
TypeScript
|
sirian/js
|
/packages/workflow/src/MarkingStore/MultipleStateMarkingStore.ts
| 2.84375
| 3
|
import {Marking, MarkingPlaces} from "../Marking";
import {MarkingStoreInterface} from "../MarkingStoreInterface";
export class MultipleStateMarkingStore<K extends string> implements MarkingStoreInterface<any> {
public readonly property: K;
constructor(property: K) {
this.property = property;
}
public getMarking<S extends string>(subject: Record<K, MarkingPlaces<S>>) {
return new Marking(subject[this.property]);
}
public setMarking<S extends string>(subject: { [P in K]?: MarkingPlaces<S> }, marking: Marking<S>) {
subject[this.property] = marking.getPlaces();
}
}
|
cd9c1b441ce5388afd94ea86fdc871d914d3c664
|
TypeScript
|
Granjow/launchpad-mini
|
/types/lib/brightness.d.ts
| 2.953125
| 3
|
/**
* This method finds the best duty cycle match for the given brightness.
* @param {Number} t Brightness level between 0 and 1
* @returns {Array.<Number>} Array [ numerator, denominator, fraction ]
*/
export function getNumDen(t: number): Array<number>;
|
65adfc8a701be89a7dd452454462fc76bb8eb062
|
TypeScript
|
David-Orson/Voice-Assistant
|
/src/components/renderers.ts
| 2.75
| 3
|
export function objDelete(message: any, todoObj: any) {
let itemIndex = message.slice(23);
console.log(`item index ${itemIndex}`);
delete todoObj[itemIndex];
}
export function objRender(todoObj: any, todoList: any) {
for (let i: number = 0; i < Object.keys(todoObj).length; i++) {
let ul = document.createElement("ul");
let body = document.createElement("li");
let title = document.createElement("h4");
let content = document.createElement("p");
title.textContent = Object.keys(todoObj)[i];
content.textContent = todoObj[Object.keys(todoObj)[i]];
body.setAttribute("class", `item-${Object.keys(todoObj)[i]}`);
ul.setAttribute("class", "rendered");
body.setAttribute("class", "rendered");
title.setAttribute("class", "rendered");
content.setAttribute("class", "rendered");
body.appendChild(title);
body.appendChild(content);
ul.appendChild(body);
todoList.appendChild(ul);
}
}
export function clearScreen() {
let elements = document.querySelectorAll(".rendered");
elements.forEach((element) => element.remove());
}
|
4cee125a7a0d0b3a05a9b122b437feb6c16acae7
|
TypeScript
|
Benjaminyuan/UniqueSSO
|
/dashboard/src/api/rest.ts
| 2.65625
| 3
|
import { LoginType } from "@/constant/loginType";
import {
EmailForm,
LoginResponse,
OauthForm,
PhoneForm,
SMSForm,
} from "@/model/form";
import axios, { AxiosInstance } from "axios";
class Endpoint {
static emailLogin = (service: string) =>
`/cas/login?type=${LoginType.Email}&service=${service}`;
static phoneLogin = (service: string) =>
`/cas/login?type=${LoginType.Phone}&service=${service}`;
static smsLogin = (service: string) =>
`/cas/login?type=${LoginType.SMS}&service=${service}`;
static larkLogin = (service: string) =>
`/cas/login?type=${LoginType.LarkOauth}&service=${service}`;
}
export class RestClient {
instance: AxiosInstance;
constructor(public baseURL: string) {
this.instance = axios.create({
baseURL: baseURL,
headers: {
"Content-Type": "application/json",
},
});
}
private async wrapLoginRequest(
url: string,
jsonData: Record<string, unknown>
): Promise<string> {
// const resp = await this.instance
// .post(url, { json: data })
try {
const { data } = await this.instance.post<LoginResponse>(url, jsonData);
if (data.serviceResponse.authenticationSuccess !== undefined) {
return data.serviceResponse.authenticationSuccess.redirectService;
} else {
throw Error("response");
}
} catch ({ response }) {
//FIXME
console.log(response);
// response.code;
throw Error("axios error");
}
// if (resp.serviceResponse.authenticationSuccess) {
// return resp.serviceResponse.authenticationSuccess.redirectService;
// }
// if (resp.serviceResponse.authenticationFailure) {
// throw new Error(resp.serviceResponse.authenticationFailure.description);
// }
// throw new Error("send http request failed");
}
async loginByEmail(form: EmailForm, service: string): Promise<string> {
return this.wrapLoginRequest(Endpoint.emailLogin(service), {
email: form.Email,
password: form.Password,
});
}
async loginByPhone(form: PhoneForm, service: string): Promise<string> {
return this.wrapLoginRequest(Endpoint.phoneLogin(service), {
phone: form.Phone,
password: form.Password,
});
}
async loginBySMS(form: SMSForm, service: string): Promise<string> {
return this.wrapLoginRequest(Endpoint.smsLogin(service), {
phone: form.Phone,
code: form.Code,
});
}
async LoginByOauth(form: OauthForm, service: string): Promise<string> {
return this.wrapLoginRequest(Endpoint.larkLogin(service), {
qrcode_src: form.QRCodeSrc,
});
}
}
|
808c49a2818f007d94ef48194d82e7d741ea817f
|
TypeScript
|
lmd-dev/lmd-dev-lmd-ant
|
/src/views/view-ants.ts
| 2.71875
| 3
|
import { ControllerAnts } from "../controllers/controller-ants";
import { View } from "./view";
/**
* View responsible for ants
*/
export class ViewAnts extends View
{
//Controller responsible for ants
private readonly _controllerAnts: ControllerAnts;
/**
* Constructor
* @param controllerAnts Controller responsible for ants
*/
constructor(controllerAnts: ControllerAnts)
{
super();
this._controllerAnts = controllerAnts;
this._controllerAnts.addObserver(this);
this.initMainEvents();
}
/**
* Notify fonction of the view
*/
notify()
{
this.displayAntsQuantity();
}
/**
* Init main events on the web page
*/
initMainEvents()
{
document.querySelector("#btn-add-ant").addEventListener("click", () => { this._controllerAnts.createAnt(); });
document.querySelector("#btn-remove-ant").addEventListener("click", () => { this._controllerAnts.removeAnt(); });
}
/**
* Display ants quantity
*/
private displayAntsQuantity()
{
this.setNumberField("#txt-ant-number", this._controllerAnts.ants.length);
}
}
|
6341a7f98ddc3f42e17e5db85d50fac740515574
|
TypeScript
|
iskilber/adk
|
/react/http/src/lib/errors/http-request.error.ts
| 2.578125
| 3
|
import { HttpRequest } from '../http-request';
export class HttpRequestError extends Error {
constructor(
public readonly request: HttpRequest,
public readonly origError: any
) {
super(origError && origError.message ? origError.message : 'Http request failed!');
}
}
|
c06807b105a5f2ae60e51e408512627abc8b1769
|
TypeScript
|
gmahi/abaplint
|
/src/abap/syntax/_inline.ts
| 2.703125
| 3
|
import {Scope} from "./_scope";
import {ExpressionNode, StatementNode} from "../nodes";
import * as Expressions from "../expressions";
import * as Statements from "../statements";
import {INode} from "../nodes/_inode";
import {Registry} from "../../registry";
import {Table, View} from "../../objects";
import {TypedIdentifier} from "../types/_typed_identifier";
import {UnknownType} from "../types/basic";
export class Inline {
private readonly variables: Scope;
private readonly reg: Registry;
constructor(reg: Registry, variables: Scope) {
this.variables = variables;
this.reg = reg;
}
private addVariable(expr: ExpressionNode | undefined, filename: string) {
if (expr === undefined) { throw new Error("syntax_check, unexpected tree structure"); }
const token = expr.getFirstToken();
this.variables.addIdentifier(new TypedIdentifier(token, filename, new UnknownType("todo")));
}
public update(node: INode, filename: string): boolean {
if (node instanceof StatementNode) {
for (const inline of node.findAllExpressions(Expressions.InlineData)) {
const field = inline.findFirstExpression(Expressions.Field);
if (field === undefined) { throw new Error("syntax_check, unexpected tree structure"); }
this.addVariable(field, filename);
}
for (const inline of node.findAllExpressions(Expressions.InlineFS)) {
const field = inline.findFirstExpression(Expressions.FieldSymbol);
if (field === undefined) { throw new Error("syntax_check, unexpected tree structure"); }
this.addVariable(field, filename);
}
for (const inline of node.findAllExpressions(Expressions.InlineFieldDefinition)) {
const field = inline.findFirstExpression(Expressions.Field);
if (field !== undefined) {
this.addVariable(field, filename);
// todo, these also have to be popped after the statement
}
}
for (const inline of node.findAllExpressions(Expressions.InlineLoopDefinition)) {
const field = inline.findFirstExpression(Expressions.Field); // todo, this can take the field after IN
if (field !== undefined) {
this.addVariable(field, filename);
// todo, these also have to be popped after the statement
}
const fs = inline.findFirstExpression(Expressions.FieldSymbol);
if (fs !== undefined) {
this.addVariable(fs, filename);
}
}
for (const inline of node.findAllExpressions(Expressions.InlineField)) {
const field = inline.findFirstExpression(Expressions.Field);
if (field !== undefined) {
this.addVariable(field, filename);
// todo, these also have to be popped after the statement
}
}
if (node.get() instanceof Statements.Select || node.get() instanceof Statements.SelectLoop) {
const fromList = node.findAllExpressions(Expressions.SQLFromSource);
for (const from of fromList) {
const dbtab = from.findFirstExpression(Expressions.DatabaseTable);
if (dbtab === undefined) {
continue;
}
let name = dbtab.getFirstToken().getStr();
const fields = this.findFields(name);
if (fields.length === 0) {
return true; // skip the statement, it uses things outside of checked namespace
}
const asName = from.findFirstExpression(Expressions.SQLAsName);
if (asName) {
name = asName.getFirstToken().getStr();
}
for (const field of fields) {
this.variables.addName(name + "~" + field);
}
// todo, these also have to be popped after the statement
}
}
}
return false;
}
private findFields(name: string): string[] {
const table = this.reg.getObject("TABL", name) as Table | undefined;
if (table !== undefined) {
return table.getFieldNames();
}
const view = this.reg.getObject("VIEW", name) as View | undefined;
if (view !== undefined) {
return view.getFields();
}
// const reg = new RegExp(this.reg.getConfig().getSyntaxSetttings().errorNamespace, "i");
// if (name.match(reg)) {
if (this.reg.inErrorNamespace(name)) {
throw new Error("Database table or view \"" + name + "\" not found");
} else {
return [];
}
}
}
|
e6b5f6711350fce151d72f1446d9d6b49a880bec
|
TypeScript
|
andreofner/torchsim
|
/js/src/torchsim/observers/ClusterObserver/Helpers/CatmullRom.ts
| 3.015625
| 3
|
// import * as THREE from 'three';
import { Vector3 } from 'three';
import { InvalidStateException } from '../../../exceptions';
export class CatmullRom {
// private splineCoefs: number[][];
// private tangentCoefs: number[][];
private p0: Vector3;
private p1: Vector3;
private p2: Vector3;
private p3: Vector3;
private pointsSet: boolean = false;
constructor() {
}
// constructor(nPoints: number) {
// this.splineCoefs = Array.from({length: nPoints}, () => );
// }
public setPoints = (p0: Vector3, p1: Vector3, p2: Vector3, p3: Vector3) => {
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.pointsSet = true;
}
public spline = (t: number, out: Vector3) => {
if (!this.pointsSet) {
throw new InvalidStateException(`CatmullRom.spline called without points being set.`);
}
const t2 = t * t;
const t3 = t2 * t;
const c0 = -t3 + 2*t2 - t;
const c1 = 3*t3 - 5*t2 + 2;
const c2 = -3*t3 + 4*t2 + t;
const c3 = t3 - t2;
this.combine(c0, c1, c2, c3, out);
// return 0.5 * ((-t3 + 2*t2 - t)*p0 + (3*t3 - 5*t2 + 2)*p1 + (-3*t3 + 4*t2 + t)*p2 + (t3 - t2)*p3);
}
public tangent = (t: number, out: Vector3) => {
if (!this.pointsSet) {
throw new InvalidStateException(`CatmullRom.tangent called without points being set.`);
}
const t2 = t * t;
const c0 = -3*t2 + 4*t - 1;
const c1 = 9*t2 - 10*t;
const c2 = -9*t2 + 8*t + 1;
const c3 = 3*t2 - 2*t;
this.combine(c0, c1, c2, c3, out);
// return 0.5 * ((-3*t2 + 4*t - 1)*p0 + (9*t2 - 10*t)*p1 + (-9*t2 + 8*t + 1)*p2 + (3*t2 - 2*t)*p3);
}
private combine = (c0: number, c1: number, c2: number, c3: number, out: Vector3) => {
out.copy(this.p0).multiplyScalar(c0);
out.addScaledVector(this.p1, c1);
out.addScaledVector(this.p2, c2);
out.addScaledVector(this.p3, c3);
out.multiplyScalar(0.5);
}
}
|
cc14d7bb6a02ba1ffe437c4d245193fe4b730f62
|
TypeScript
|
kkoon9/SwimintheServer-nestJS
|
/src/dayRecord/dayRecord.controller.ts
| 2.546875
| 3
|
import { Body, Controller, Post, ValidationPipe } from "@nestjs/common";
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
import { RecordDailyFilterDto } from "./dto/dayRecord.request.dto";
import { RecordDailyListResponseDto } from "./dto/dayRecord.response.dto";
import { DayRecordService } from "./dayRecord.service";
@ApiTags("dayRecord")
@Controller("dayRecord")
export class DayRecordController {
constructor(private dayRecordService: DayRecordService) {}
@Post("/list")
@ApiOperation({
summary: "일간 랩스 기록 조회 API",
description: "유저의 일간 일간 랩스 기록을 조회하는 API.",
})
@ApiOkResponse({
description: "일간 랩스 기록을 조회한다.",
type: RecordDailyListResponseDto,
})
async findRecordDailyList(
@Body(ValidationPipe) recordDailyFilterDto: RecordDailyFilterDto
): Promise<RecordDailyListResponseDto> {
// TODO response type 정하고 변경
return await this.dayRecordService.findDailyRecordList(
recordDailyFilterDto
);
}
}
|
c49a93f252d70b1b6a7c2a14f351c82ebd881bd6
|
TypeScript
|
slim-gears/rxrpc-js
|
/src/lib/data/invocation.ts
| 3.046875
| 3
|
import {InvocationType} from './invocation-type';
export interface HasInvocationType {
type: InvocationType
}
export interface HasInvocationId {
invocationId: number;
}
export interface Subscription extends HasInvocationType, HasInvocationId {
type: InvocationType.Subscription;
method: string;
arguments: Map<string, any>;
}
export interface Unsubscription extends HasInvocationType, HasInvocationId {
type: InvocationType.Unsubscription;
}
export interface KeepAlive extends HasInvocationType {
type: InvocationType.KeepAlive;
}
export interface Aggregation extends HasInvocationId {
type: InvocationType.Aggregation;
invocations: Invocation[];
}
export type Invocation = Subscription | Unsubscription | KeepAlive | Aggregation
export class Invocations {
public static subscription(id: number, method: string, args: Map<string, any>): Subscription {
return { type: InvocationType.Subscription, invocationId: id, method: method, arguments: args };
}
public static unsubscription(id: number): Unsubscription {
return { type: InvocationType.Unsubscription, invocationId: id };
}
public static keepAlive(): KeepAlive {
return {type: InvocationType.KeepAlive}
}
public static aggregation(...invocations: Invocation[]): Aggregation {
return {type: InvocationType.Aggregation, invocations} as Aggregation;
}
}
|
f887decfef99551850d379ff0fb3b0e49e95a09f
|
TypeScript
|
Spudnik-Group/Spudnik
|
/src/extras/data.ts
| 2.515625
| 3
|
export const smiff = [
'Will enjoys playing chess.',
"As an early actor on 'The Fresh Prince of Bel-Air' Will would memorize the entire script and lip everyone's lines while filming.",
"For one of Jada Pinkett Smith's birthdays, Will Smith created a DVD message telling his wife there were clothes upstairs and a car would pick her up in 20 minutes. She was taken to the airport and flown to San Francisco, where Will was waiting for her at a restaurant she'd been reading about. He told PEOPLE, 'That's how Big Will does it!'",
"'We are who we choose to be.' - Will Smiff",
'Smiff attended Overbrook High School in West Philadelphia for the majority of his high school years. However, he also spent a short time attending Archbishop John Carroll High School in Radnor.',
'Smith has been married twice. His first marriage in 1992 lasted only three years but produced a son, Willard Smith III, who is also known as Trey.',
'Will Smith could bench 385 pounds while filming I, Robot',
"A millionaire by age 20, Will Smith admits to spending lavishly on jewelry, a house and luxury cars early in his career. He and his buddies once convinced the salespeople at Gucci to close the store so they could enjoy a private shopping spree. 'Being able to buy anything you want makes you a little crazy,' Smith later told PEOPLE.",
'Will Smith turned down MIT to pursue a music career',
"Known for his boundless confidence, Will Smith was worried about making the leap from rapper to actor. When called in to audition for The Cosby Show and A Different World, Smith was a no-show. 'I realized later how scared I was to take that step,' he told PEOPLE.",
'Will Smith speaks fluent Spanish',
"Will Smith paid for each of his Fresh Prince of Bel-Air costars to upgrade their onset dressing rooms in 1995. 'Mine was called Daphne's little bordello,' Daphne Maxwell Reid, who played Smith's Aunt Viv, told PEOPLE. 'It had a gold brocade chair with cupids on it.'",
'Will Smith turned down the role of Neo in The Matrix',
"Will Smith wrote the children's book Just the Two of Us",
"Will Smith met wife Jada Pinkett Smith when she tried out for the role of his girlfriend on 'The Fresh Prince of Bel-Air' (1990). The role eventually went to Nia Long.",
'Will Smith has three children. Son, Willard Smith III (Trey Smith) born in November 11, 1992, with Sheree Fletcher. Son, Jaden Christopher Syre Smith (Jaden Smith) born July 8, 1998 and daughter, Willow Camille Reign Smith (Willow Smith) born October 31, 2000 with Jada Pinkett Smith.',
'Will Smith has said he based his character Captain Steven Hiller in Independence Day (1996) on his favorite big screen hero, Harrison Ford, most notably his performances of Han Solo in Star Wars (1977) and its sequels.',
"Will's siblings are: Pam Smith (born in 1964), and twins Ellen and Harry Smith (born in 1971).",
"Will Smith won a Grammy Award for the song 'Summertime' during his rap career.",
"Will Smith received the first ever Grammy Award for Best Rap Performance, for the song 'Parents Just Don't Understand' in 1989 with his partner Jeffrey A. Townes (aka Jazzy Jeff).",
'Will Smith was chosen by People magazine as one of the 50 Most Beautiful People in the World. [1998]',
"Smith's pilot test show for 'The Fresh Prince of Bel-Air' (1990) was directed by Debbie Allen.",
"Will Smith met his first wife, Sheree Fletcher, at a taping of 'A Different World' (1987) in 1991.",
'As a public role model, Will Smith hosted the Presidential Inaugural Celebration for Youth, as part of the Gala for President Bill Clinton. [January 1993]',
"Will Smith is a graduate of Philly's legendary Overbrook High School, whose alumni include Wilt Chamberlain, Hal Lear, Wali 'Wonder' Jones, Walt Hazzard, The Dovells, The Orlons, DeeDee Sharp, etc. and, in tribute to his student years there, his production company is called Overbrook Entertainment.",
'Will Smith attended the prestigious Julia Reynolds Masterman Laboratory and Demonstration School in Philadelphia.',
'Will Smith turned down the role of Neo in The Matrix (1999).',
'Will Smith is the first hip-hop artist to be nominated for an Academy Award.',
'Will Smith speaks fluent Spanish.',
"Will Smith is ranked #2 on Star TV's Top Ten Box Office stars of the 1990s (2003).",
'Will Smith had a chart-hit together with DJ Jazzy Jeff (aka Jeffrey A. Townes.)',
'Will Smith dropped from Columbia Records as an artist after lackluster sales of his third solo album, which was self-titled, and greatest hits compilation. [Summer 2003]',
"Will Smith incorporates the line 'Aw, hell no!' into all his movies as a running catch phrase like Arnold Schwarzenegger's 'I'll be back!'.",
"Will Smith is ranked #15 in TV Guide's list of 'TV's 25 Greatest Teen Idols' (23 January 2005 issue).",
"Will Smith gained a place in the Guinness World Records book for most public appearances in 12 hours, by attending three red carpet 'premieres' for Hitch (2005/I) on 22nd February 2005. He walked the red carpet and introduced the film at Manchester, Birmingham, and finally for the premiere in London, England.",
'Will Smith once stated that in his whole career, he most regrets turning down the part of Neo in The Matrix (1999) and the film that he most regrets making was Wild Wild West (1999).',
"Will Smith has been at his adult height of 6' 2 since he was 13, although he is now about 60 pounds heavier than he first was when he reached this height.",
'Premiere Magazine ranked Will Smith as #44 on a list of the Greatest Movie Stars of All Time in their Stars in Our Constellation feature (2005).',
"Will Smith sang a few lines 'Wild Wild West' to his on screen cousin Carleton, a movie in which he starred 6 years later.",
'Will Smith hosted the MTV Movie Awards in 1994.',
"Will Smith considered for the role of 'Mr. Smith' in Mr. & Mrs. Smith (2005) before Brad Pitt was cast.",
'Will Smith is supposedly a huge fan of the Swedish well-known (but barely known in the U.S.) melodic heavy metal band Soilwork.',
"Will Smith is ranked #66 in VH1's 100 greatest Teen Stars.",
'Will Smith holds the record for most Kids Choice Awards with a whopping six wins.',
"Will Smith is ranked #14 on Premiere's 2006 'Power 50' list. Had ranked #18 in 2005. He is the second-highest ranked actor, behind only Tom Cruise.",
'Will Smith and Jada Pinkett Smith were forced to leave their home in California because a bush fire threatened to destroy it and several other houses in the same area. [October 2005]',
"Will Smith's 1995 divorce from ex-wife Sheree Fletcher led to a $900,000 lump sum divorce settlement for Zampino plus $24,000 per month in alimony and child support; this equals $288,000 a year.",
'Will Smith lost his place in the Guiness World Records book for most public appearances in 12 hours to German actors Jürgen Vogel and Daniel Brühl, who attended four red carpet premieres of their movie Ein Freund von mir (2006), one more than Will (22 October 2006).',
"In the 1998 rap lyrics of 'Gettin' Jiggy', Will Smith says that Muhammad Ali would call him 'The Greatest.' Two and a half years later, he played the title role in Ali (2001).",
"An animated caricature of Will Smith appeared in 'Men in Black: The Series' (1997) (the animated series adaptation of Men in Black (1997)), alongside a caricature of his MIB co-star Tommy Lee Jones, set against a shot that parodied one of the famous low angle shots of a building being threatened by a flying saucer, an in-joke reference to Smith's 1996 hit 'Men in Black: The Series' (1997), which preceded Men in Black (1997).",
"Will Smith's character from Men in Black (1997), Agent Jay, was not originally written to specifically be a black man. In fact, the role was offered to Caucasian actors Chris O'Donnell and David Schwimmer before Smith accepted the part.",
'Will Smith had to undergo treatment on his shoulder in a New York hospital after he suffered a strain. [March 2007]',
"Will Smith was among the guests at Tom Cruise's and Katie Holmes's wedding ceremony in Italy.",
"Will Smith was ranked #30 on VH1's 50 Greatest Hip Hop Artists along with DJ Jazzy Jeff & The Fresh Prince.",
"Will Smith ranked #29 on VH1's 100 Sexiest Artists.",
"In 2007, Will Smith ranked #5 on Entertainment Weekly's The 50 Smartest People in Hollywood.",
"December 2007 - According to Forbes, for each dollar he got paid, Smith's movies averaged $10 of gross income.",
'Will Smith was a millionaire before the age of 20.',
"In 2004, Will Smith's net worth was estimated to be $188 million.",
"In 2007, Forbes Magazine estimated Will Smith's earnings for the year at $31 million.",
'Will Smith is good friends with Ken Foree.',
'Will Smith is a huge fan of Professional Wrestling.',
"Will Smith is often called 'Mr. July' by the media due to the fact that most of his summer blockbusters open in July.",
'As of Hancock (2008), Will Smith holds the record for the actor to star in the most consecutive $100 million-grossing movies (8).',
'Will Smith and his daughter Willow Smith both had movies opening 2 July, 2008. His was Hancock (2008), hers was Kit Kittredge: An American Girl (2008).',
"Will Smith has appeared in two films starting with the word 'I', I, Robot (2004) and I Am Legend (2007).",
"Will Smith wrote and performed the song, 'Just the Two of Us', about his first son, Trey Smith.",
'Will Smith was considered for the role of Detective James Carter in Rush Hour (1998).',
'Will Smith holds the record of appearing in the most consecutive $100 million-grossing movies (8).',
'Will Smith was in consideration for the part of Curtis Taylor Jr in Dreamgirls (2006). However Jamie Foxx was cast instead.',
"Will Smith's Birth Card is the Queen of Hearts.",
"Will Smith has solved Rubik's cubes in both The Fresh Prince of Bel Air and The Pursuit of Happiness. This is a real talent of his; he has shown on live TV that he can solve a Rubik's Cube in under 55 seconds.",
"The Bridge On The River Kwai is Will Smith's favorite movie."
];
export const bacon = [
'http://i.imgur.com/Z9mlWN4.gif',
'https://media.giphy.com/media/bOxL3wXCzANhe/giphy.gif',
'https://media.giphy.com/media/HKx5p4APGBxi8/giphy.gif',
'https://media.giphy.com/media/11sFH7QYAzLE0E/giphy.gif',
'https://media.giphy.com/media/qZiUOutzxgfKM/giphy.gif',
'https://media.giphy.com/media/3oEdvcywVUmu0aSFkk/giphy.gif',
'https://media.giphy.com/media/b9oyqJ6dLVXaw/giphy.gif'
];
export const eightBall = [
'As I see it, yes',
'Better not tell you now',
'Cannot predict now',
'Don"t count on it',
'If you say so',
'In your dreams',
'It is certain',
'Most likely',
'My CPU is saying no',
'My CPU is saying yes',
'Out of psychic coverage range',
'Signs point to yes',
'Sure, sure',
'Very doubtful',
'When life gives you rice, you make rice',
'Without a doubt',
'Wow, Much no, very yes, so maybe',
'Yes, definitely',
'Yes, unless you run out of memes',
'You are doomed',
'You can"t handle the truth'
];
export const coinflip = [
{
text: 'Heads',
image: 'https://i.imgur.com/pnyfjwd.png'
},
{
text: 'Tails',
image: 'https://i.imgur.com/WXujZjZ.png'
}
];
|
9a6472bbcffa28c08d9e1ae8fb040a118a5fcf89
|
TypeScript
|
MamoruDS/telegram_bot_utils
|
/src/utils.ts
| 2.984375
| 3
|
import * as _ from 'lodash'
const idFormat = {
ts_radix: 16,
prefix_length_min: 1,
prefix_length_max: 4,
suffix_length_min: 10,
suffix_length_max: 10,
phrase_1_length: 6,
phrase_2_length: 6,
group_length: 10,
}
const regStr = `((^\\w{${idFormat.prefix_length_min},${idFormat.prefix_length_max}})-|^)((\\w{1,${idFormat.phrase_1_length}})-([A-F\\d]{1,})-(\\w{1,${idFormat.phrase_1_length}}))(-(\\w{${idFormat.suffix_length_min},${idFormat.suffix_length_max}})$|$)`
export const genRandom = (length: number): string => {
if (length < 1 || length > 10) {
throw new RangeError()
}
return _.random(36 ** (length - 1), 36 ** length - 1).toString(36)
}
export const genId = (prefix?: string, suffix?: string) => {
return `${prefix ? `${prefix}-` : ''}${genRandom(
idFormat.phrase_1_length
)}-${Date.now().toString(idFormat.ts_radix)}-${genRandom(
idFormat.phrase_2_length
)}${suffix ? `-${suffix}` : ''}`.toUpperCase()
}
export interface IdInfo {
match: boolean
body?: string
ts?: number
prefix?: string
suffix?: string
}
export const parseId = (id: string): IdInfo => {
let _res = { match: false } as IdInfo
const _regex = new RegExp(regStr, 'gm').exec(id)
if (_regex === null) return _res
_res.match = true
_res.body = _regex[3]
_res.ts = parseInt(_regex[4], idFormat.ts_radix)
_res.prefix = _regex[2]
_res.suffix = _regex[8]
return _res
}
export class GroupId {
private readonly _prefix?: string
public readonly group: string
constructor(prefix?: string) {
this.group = genRandom(idFormat.group_length).toUpperCase()
this._prefix = prefix
}
genId(suffix: boolean = true): string {
return genId(this._prefix, suffix ? this.group : undefined)
}
isMember(id: string): boolean {
const idInfo = parseId(id)
if (idInfo.match) {
return idInfo.suffix === this.group
} else {
return false
}
}
import(id: string): string {
const idInfo = parseId(id)
if (!idInfo.match) {
return undefined
}
return `${this._prefix}-${idInfo.body}-${this.group}`.toUpperCase()
}
}
export const wait = async (timeout: number): Promise<void> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, timeout)
})
}
export const copy = <T>(source: T): T => {
if (source === null) return source
if (Array.isArray(source)) {
const _t = [] as any[]
source.map((v) => {
_t.push(copy(v))
})
return _t as any
}
if (typeof source === 'object') {
if (source.constructor.name !== 'Object') {
return source
}
const _t = {} as T
for (const key of Object.keys(source)) {
_t[key] = copy(source[key])
}
return _t
}
return source
}
export const compObjCopy = <T extends object>(source: object): T => {
if (typeof source != 'object' || source === null || Array.isArray(source)) {
throw new TypeError()
}
if (source == {}) {
return {} as T
}
const _t = {} as T
for (const key of Object.keys(source)) {
_t[key] = copy(source[key])
}
return _t
}
type Optional<T extends object> = {
[key in keyof T]?: T[key] extends object ? Optional<T[key]> : T[key]
}
export const assignDefault = <T extends object>(
defaultOptions: Required<T>,
inputOptions: Optional<T>
): Required<T> => {
if (
typeof inputOptions !== 'object' ||
inputOptions === null ||
Array.isArray(inputOptions)
) {
throw new TypeError('Input options expect an object to be entered')
}
const _options = copy(defaultOptions)
assign(_options, inputOptions)
return _options
}
const assign = <T extends object>(
target: Required<T>,
input: Optional<T>,
assignExistOnly?: boolean
): void => {
for (const key of Object.keys(target)) {
const _val = input[key]
if (typeof _val != 'undefined') {
if (_val == null) {
target[key] = null
continue
}
if (Array.isArray(_val)) {
for (const i in target[key]) {
const __val = _val[i]
if (typeof __val == 'undefined') continue
if (
typeof target[key][i] == 'object' &&
!Array.isArray(target) &&
target != null
) {
assign(target[key][i], _val[i])
} else {
target[key][i] = __val
}
}
if (target[key].length < _val.length && !assignExistOnly) {
let _i = target[key].length
while (_i < _val.length) {
target[key][_i] = _val[_i]
_i++
}
}
continue
}
if (typeof _val == 'object' && _val != {}) {
assign(target[key], _val)
continue
}
target[key] = _val
continue
}
}
for (const key of Object.keys(input)) {
if (typeof target[key] == 'undefined' && !assignExistOnly) {
target[key] = copy(input[key])
}
}
}
|
79aeb510cc6a9d2e580ad0938f7e1746a5319881
|
TypeScript
|
ccollado0307/TPE-Grupo6
|
/src/asistencia/asistencia.entity.ts
| 2.578125
| 3
|
import { Grado } from "src/grado/grado.entity";
import { Motivo } from "src/motivo/motivo.entity";
import { Personal } from "src/personal/personal.entity";
import { Column, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { Entity } from "typeorm/decorator/entity/Entity";
@Entity('asistencia')
export class Asistencia {
@PrimaryGeneratedColumn()
idAsist: number;
@Column()
private fecha: Date;
@ManyToOne((type) => Motivo, motivo => motivo.asistencias)
@JoinColumn({name: 'idMotivo'})
public motivo: Motivo;
@ManyToOne((type) => Grado, grado => grado.asistencias)
@JoinColumn({name: 'idGrado'})
public grado: Grado;
@ManyToOne((type) => Personal, personal => personal.asistencias)
@JoinColumn({name: 'idPers'})
public personal: Personal;
public constructor(fecha?: Date) {
this.fecha = fecha;
}
public getIdAsist():number{
return this.idAsist;
}
public getFecha():Date{
return this.fecha;
}
public setFecha(fecha: Date){
this.fecha = fecha;
}
public setIdAsist(id: number): void {
this.idAsist = id;
}
public getMotivo(): Motivo {
return this.motivo;
}
public setMotivo(motivo: Motivo):void {
this.motivo = motivo;
}
public setPersonal(personal:Personal): void {
this.personal=personal;
}
public getPersonal():Personal {
return this.personal;
}
public setGrado(grado:Grado):void{
this.grado=grado;
}
public getGrado():Grado{
return this.grado;
}
}
|
6e1ca9797113fa9f382acbb61ff0e8880430f280
|
TypeScript
|
lyf103104/wechat_project
|
/zhongmian/src/services/store-url-analyzer.ts
| 2.6875
| 3
|
import { isArray, isString } from 'lodash';
const storeRegex = /.*?[\?\&]cdfgappstore=(\d+).*?$/;
/**
* 从二维码链接中解析门店信息
* @param url 二维码链接
*/
export default function(url: string): number | false {
const matchs = url.match(storeRegex);
if (!isArray(matchs) || !isString(matchs[1])) {
return false;
}
return parseInt(matchs[1]);
}
|
195712ab1fc5a2e155a2fbd53668244aecfecbee
|
TypeScript
|
loganm/sfdx-changeset
|
/src/lib/sfdx.ts
| 2.625
| 3
|
import { SfdxError } from '@salesforce/core';
import { Dictionary, get } from '@salesforce/ts-types';
import { spawn, SpawnOptions } from 'child_process';
export const runCommand = (fullCommand: string): Promise<Dictionary> => {
const error = new Error(); // Get stack here to use for later
if (!fullCommand.includes('--json')) {
fullCommand += ' --json';
}
//const parts = fullCommand.split(' ');
// Split string, handle quote marks
// https://stackoverflow.com/questions/2817646/javascript-split-string-on-space-or-on-quotes-to-array
const parts = fullCommand.match(/\\?.|^$/g).reduce((p, c) => {
if(c === '"'){
p.quote ^= 1;
}else if(!p.quote && c === ' '){
p.a.push('');
}else{
p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
}
return p;
}, {quote: null, a: ['']}).a
const commandName = parts[0];
const args = parts.slice(1);
const spawnOpt: SpawnOptions = {
// Always use json in stdout
env: Object.assign({ SFDX_JSON_TO_STDOUT: 'true' }, process.env)
};
return new Promise((resolve, reject) => {
const cmd = spawn(commandName, args, spawnOpt);
let stdout = '';
cmd.stdout.on('data', data => {
stdout += data;
});
cmd.stderr.on('data', data => {
console.warn('srderr', data);
});
cmd.on('error', data => {
console.error('err', data);
});
cmd.on('close', code => {
let json;
try { json = JSON.parse(stdout); } catch (e) {
console.warn(`No parsable results from command "${fullCommand}"`);
}
if (code > 0) {
// Get non-promise stack for extra help
const sfdxError = SfdxError.wrap(error);
sfdxError.message = `Command ${commandName} failed with ${get(json, 'message')}`;
sfdxError.setData(json);
reject(sfdxError);
} else {
resolve(json.result);
}
});
});
};
|
3cd7d9d8c5e1b26bf1c98af36e2848816e06c41a
|
TypeScript
|
k3ith-fowl3r/grapesjs
|
/src/device_manager/model/Device.ts
| 3.296875
| 3
|
import { Model } from '../../common';
/** @private */
export interface DeviceProperties {
id?: string;
/**
* Device name.
* @example 'Mobile'
*/
name: string;
/**
* Width to set for the editor iframe.
* @example '900px'
*/
width: string | null;
/**
* Height to set for the editor iframe.
* @example '600px'
*/
height?: string;
/**
* The width which will be used in media queries, if empty the `width` will be used.
* @example '900px'
*/
widthMedia?: string | null;
/**
* Setup the order of media queries
* @example 1
*/
priority?: number | null;
}
/**
* @typedef Device
* @property {String} [name=''] Device type, eg. `Mobile`
* @property {String} [width] Width to set for the editor iframe, eg. '900px'
* @property {String} [height=''] Height to set for the editor iframe, eg. '600px'
* @property {String} [widthMedia=''] The width which will be used in media queries, If empty the width will be used
* @property {Number} [priority=null] Setup the order of media queries
*/
export default class Device extends Model<DeviceProperties> {
defaults() {
return {
name: '',
width: null,
height: '',
widthMedia: null,
priority: null,
};
}
initialize() {
this.get('widthMedia') === null && this.set('widthMedia', this.get('width'));
this.get('width') === null && this.set('width', this.get('widthMedia'));
!this.get('priority') && this.set('priority', parseFloat(this.get('widthMedia')!) || 0);
const toCheck: (keyof DeviceProperties)[] = ['width', 'height', 'widthMedia'];
toCheck.forEach(prop => this.checkUnit(prop));
}
checkUnit(prop: keyof DeviceProperties) {
const pr = (this.get(prop) || '') as string;
const noUnit = (parseFloat(pr) || 0).toString() === pr.toString();
noUnit && this.set(prop, `${pr}px`);
}
getName() {
return this.get('name') || this.get('id');
}
getWidthMedia() {
return this.get('widthMedia') || '';
}
}
|
87cad9b0d9f53e67e811c256b2f1b6030e4ca8b8
|
TypeScript
|
david-shortman/ngrx-strict-mode
|
/src/app/store/scoreboard.reducer.ts
| 2.625
| 3
|
import { Action, createReducer, on } from '@ngrx/store';
import * as ScoreboardPageActions from './scoreboard.actions';
export const scoreboardFeatureKey = 'game';
export interface GameState {
home: number;
away: number;
}
export const initialState: GameState = {
home: 0,
away: 0,
};
const scoreboardReducer = createReducer(
initialState,
on(ScoreboardPageActions.homeScore, (state) => ({
...state,
home: state.home + 1,
})),
on(ScoreboardPageActions.awayScore, (state) => ({
...state,
away: state.away + 1,
})),
on(ScoreboardPageActions.resetScore, (state) => ({ home: 0, away: 0 })),
on(ScoreboardPageActions.setScores, (state, { game }) => ({
home: game.home,
away: game.away,
}))
);
export function reducer(
state: GameState | undefined,
action: Action
): GameState {
return scoreboardReducer(state, action);
}
|
5a83faa0dd6f5e65b284454012360bad378c53c0
|
TypeScript
|
WillCS/rest-api-test
|
/app/src/inventory/inventoryStore.ts
| 2.828125
| 3
|
import { observable } from 'mobx';
import ApiService from 'src/services/apiService';
import { InventoryModel, Item, Slot } from './inventoryModel';
const enum ResponseStatus {
Unset,
OK = 200,
NetworkError,
NotFound = 404,
Unauthorized = 401,
ServerError = 500
}
class InventoryStore {
@observable
public inventory?: InventoryModel;
@observable
public isLoading: boolean = false;
@observable
public status: ResponseStatus = ResponseStatus.Unset;
public reset(): void {
this.inventory = undefined;
this.isLoading = false;
this.status = ResponseStatus.Unset;
}
public async fetchInventory(): Promise<void> {
try {
this.isLoading = true;
const fetchData: Response = await ApiService.get('/inventory');
const body: object = await fetchData.json();
this.status = fetchData.status;
if(this.status === ResponseStatus.OK) {
this.inventory = InventoryModel.fromJson(body);
}
} catch(error) {
this.status = ResponseStatus.NetworkError;
}
this.isLoading = false;
}
public getItemInSlot(slot: number): Item | undefined {
return this.inventory!.slots.find(i => i.slotNumber === slot)!.item;
}
public getSlotWithIndex(index: number): Slot {
return this.inventory!.slots[index];
}
public slotHasItem(slot: number): boolean {
return this.getItemInSlot(slot) !== undefined;
}
}
export default new InventoryStore();
|
aa233e457dbc03e8f526625316c7431b248acc52
|
TypeScript
|
weizai118/spring-cloud-dataflow-ui
|
/ui/src/app/streams/stream/stream.component.ts
| 2.53125
| 3
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
/**
* Component that shows the details of a Stream Definition
*
* @author Janne Valkealahti
* @author Gunnar Hillert
* @author Glenn Renfro
* @author Damien Vitrac
*/
@Component({
selector: 'app-stream',
templateUrl: 'stream.component.html',
styleUrls: ['styles.scss'],
encapsulation: ViewEncapsulation.None
})
export class StreamComponent implements OnInit {
/**
* Stream ID
*/
id: string;
/**
* Constructor
* @param {ActivatedRoute} route
*/
constructor(private route: ActivatedRoute) {
}
/**
* Initialiaze component
*/
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params.id;
// TODO: check if stream exist
});
}
}
|
ef75f0876ed8a70ac8559f0e07ba2bb93669b4c0
|
TypeScript
|
highsummer/foamfile
|
/src/case/caseVectorField.ts
| 2.84375
| 3
|
import {predicate, Vector} from "./helpers";
export namespace CaseVectorField {
export const TypeSignature = "case.vectorField" as const;
export const is = predicate(TypeSignature)<Type>();
export interface Type {
type: typeof TypeSignature,
header: {
version: string,
format: string,
className: "vectorField",
object: string,
},
data: Vector[];
}
export function build(version: string, format: string, object: string, data: Vector[]): Type {
return {
type: TypeSignature,
header: {
version: version,
format: format,
className: "vectorField",
object: object,
},
data: data,
}
}
// export function print(x: Type): string {
// return `/*--------------------------------*- C++ -*----------------------------------*\\
// ========= |
// \\\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
// \\\\ / O peration | Website: https://openfoam.org
// \\\\ / A nd | Version: 7
// \\\\/ M anipulation |
// \\*---------------------------------------------------------------------------*/
//
// FoamFile {
// version ${x.header.version};
// format ${x.header.format};
// class ${x.header.className};
// object ${x.header.object};
// }
//
// ${x.data.length}
// (
// ${x.data.map(v => `(${v.join(" ")})`).join("\n")}
// )
// `
// }
}
|
c0e49ef6b7ee4257c8fb55c5ce0d8a0b484f2410
|
TypeScript
|
alexander-shipilov/positron
|
/types/array/types/ArrayLast.ts
| 4.28125
| 4
|
/**
* Returns type of the last element in the array / tuple type `T`
*
* @remarks
*
* If `T` is not array / tuple type result type will be `never`
*
* ```ts
* type T = ArrayLast<string>
* // type T = never
* ```
*
* Also result will be `never` if `T` is empty tuple type
*
* ```ts
* type T = ArrayLast<[]>
* // type T = never
* ```
*
* @example
*
* ```ts
* type T = ArrayLast<[string, number, boolean]>;
* // type T1 = boolean
*
* type T = ArrayLast<string[]>;
* // type T2 = string
* ```
*/
export type ArrayLast<T> = T extends [...unknown[], infer E]
? E
: T extends Array<infer E>
? E
: never;
|
e13d85202d9c1c894f01e431655a71b6541fecd5
|
TypeScript
|
tabuckner/tabuckner-subsink
|
/projects/tabuckner/subsink/src/lib/sub-sink.ts
| 2.703125
| 3
|
import { isFunction } from './helpers/is-function';
export function SubSink({ debug = false } = {}) {
return function(constructor: any) {
const ogOnDestroy = constructor.prototype.ngOnDestroy;
if (!isFunction(ogOnDestroy)) {
throw new Error(`${constructor.name} is using @SubSink but does not implement OnDestroy`);
}
constructor.prototype.ngOnDestroy = function() {
const usesSubSink = this.subSink && this.subSink.unsubscribe && isFunction(this.subSink.unsubscribe);
if (usesSubSink) {
if (debug) {
console.warn(`${constructor.name} is using 'subSink' and is being automatically unsubscribed.`);
}
this.subSink.unsubscribe();
}
const usesSubs = this.subs && this.subs.unsubscribe && isFunction(this.subs.unsubscribe);
if (usesSubs) {
if (debug) {
console.warn(`${constructor.name} is using 'subs' and is being automatically unsubscribed.`);
}
this.subs.unsubscribe();
}
// Execute ogOnDestroy ngOnDestroy
if (ogOnDestroy && typeof ogOnDestroy === 'function') {
ogOnDestroy.apply(this, arguments);
}
};
};
}
|
363458c665000dc28fe19bc8bb320547f414046c
|
TypeScript
|
DiegoLing33/WBL
|
/client/src/UI/components/Button.ts
| 2.90625
| 3
|
import CoreUIElement from "../CoreUIElement";
export default class Button extends CoreUIElement<HTMLElement> {
constructor(buttonId: string) {
super(buttonId);
}
/**
* Sets on click event
* @param closure
*/
public onClick(closure: () => void) {
this.getRaw().onclick = () => closure();
return this;
}
}
|
93ceb5cec67b204c93d5cf897dde73c3a23cddb3
|
TypeScript
|
IT-Highmore/Angular8-Cloud-Music-App
|
/src/app/utils/tools.ts
| 2.65625
| 3
|
export function isEmptyObject(obj: Object): boolean {
return JSON.stringify(obj) === '{}';
}
|
d9a31e43492e5e40fd6d37ffb4c5c87a6a7aa47a
|
TypeScript
|
LauraPachecoValbuena/Ejercicios-React
|
/crud/src/reducers/myUserReducer.ts
| 2.796875
| 3
|
import { TAction } from "../actionsTypes";
export interface IMyUser {
token?: string;
exp?: number;
iat?: number;
id?: string;
isAdmin?: boolean;
username?: string;
}
const initialState: IMyUser = {};
export const myUserReducer = (
state: IMyUser = initialState,
action: TAction
): IMyUser => {
if (action.type === "SAVE_MY_USER") {
return action.myUser;
}
return state;
};
|
76031f1554832c082fe28cdf37e1fbd8423b46f6
|
TypeScript
|
sorensj1/TextMaker
|
/TextMaker.App/src/app/shared/services/text-data.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Project } from '../models';
@Injectable({
providedIn: 'root'
})
export class TextDataService {
private baseUri = 'api/projects';
constructor(
private httpClient: HttpClient
) { }
getKeys(handler: (keys: string[]) => void) {
const observable = this.httpClient.get(this.baseUri);
observable.subscribe(result => handler(result as string[]));
}
get(key: string, handler: (project: Project) => void) {
const observable = this.httpClient.get(`${this.baseUri}/${key}`);
observable.subscribe(result => handler(result as Project));
}
create(project: Project, handler: (result: string) => void) {
const key = this.getKey(project.name);
const observable = this.httpClient.post(`${this.baseUri}/${key}`, project);
observable.subscribe(result => handler(result as string));
}
update(key: string, project: Project, handler: (result: string) => void): void {
const observable = this.httpClient.put(`${this.baseUri}/${key}`, project);
observable.subscribe(result => handler(result as string));
}
private getKey(projectName: string): string {
// remove whitespace
return projectName.replace(/\s/g, '');
}
}
|
73f006839ce0fc317eafbe1e890dc6baa34d2d50
|
TypeScript
|
AlexandreFontanie/AsynchronousServerTechnologies
|
/TP3/bin/populate.ts
| 2.53125
| 3
|
#!/usr/bin/env ts-node
import { Metric, MetricsHandler } from '../src/metrics'
import { User, UserHandler } from '../src/users'
const dbMet = new MetricsHandler("./db/metrics");
const dbUser = new UserHandler("./db/users");
// Premier utilisateur
const met = [
new Metric(`${new Date("2013-11-04 14:00 UTC").getTime()}`, 11),
new Metric(`${new Date("2013-11-04 14:15 UTC").getTime()}`, 4),
new Metric(`${new Date("2013-11-04 14:30 UTC").getTime()}`, 8)
];
const met2 = [
new Metric(`${new Date("2013-11-04 15:00 UTC").getTime()}`, 13),
new Metric(`${new Date("2013-11-04 15:15 UTC").getTime()}`, 11),
new Metric(`${new Date("2013-11-04 15:30 UTC").getTime()}`, 9)
];
const user1 = new User("test1", "test1@test.com", "test1");
dbUser.save(user1, (err: Error | null) => {
if (err) throw err;
console.log("Utilisateur intégré, identifiants :");
console.log("login : test1");
console.log("mot de passe : test1")
});
dbMet.saveMetric("test1", "0", met, (err: Error | null) => {
if (err) throw err;
console.log("Metrics pour test1");
});
dbMet.saveMetric("test1", "1", met2, (err: Error | null) => {
if (err) throw err;
console.log("Metrics pour test1");
});
/// Deuxième utilisateur
const met3 = [
new Metric(`${new Date("2014-03-24 16:00 UTC").getTime()}`, 19),
new Metric(`${new Date("2014-03-24 16:15 UTC").getTime()}`, 23),
new Metric(`${new Date("2014-03-24 16:30 UTC").getTime()}`, 14)
];
const met4 = [
new Metric(`${new Date("2014-03-24 17:00 UTC").getTime()}`, 6),
new Metric(`${new Date("2014-03-24 17:15 UTC").getTime()}`, 9),
new Metric(`${new Date("2014-03-24 17:30 UTC").getTime()}`, 15)
];
const user2 = new User("test2", "test2@test.com", "test2");
dbUser.save(user2, (err: Error | null) => {
if (err) throw err;
console.log("Utilisateur intégré, identifiants :");
console.log("login : test2");
console.log("mot de passe : test2")
});
dbMet.saveMetric("test2", "0", met3, (err: Error | null) => {
if (err) throw err;
console.log("Metrics pour test2");
});
dbMet.saveMetric("test2", "1", met4, (err: Error | null) => {
if (err) throw err;
console.log("Metrics pour test2");
});
|
b588ac83b26cc20c38bf5dfa14e6fd96e7c502cd
|
TypeScript
|
narainsagar/angular2-demos
|
/src/app/angular2-multi-component-form-builder/shared/form-field/shared/validator.spec.ts
| 2.546875
| 3
|
import {
describe,
ddescribe,
expect,
iit,
it
} from '@angular/core/testing';
import {Validator, RequiredValidator, PatternValidator, MinLengthValidator, MaxLengthValidator} from './validator';
describe('Validator', () => {
it('should create an instance', () => {
expect(new Validator('Something')).toBeTruthy();
});
});
describe('RequiredValidator', () => {
it('should create an instance', () => {
expect(new RequiredValidator('Something')).toBeTruthy();
});
});
describe('PatternValidator', () => {
it('should create an instance', () => {
expect(new PatternValidator('^([0-9]*)$', 'Something')).toBeTruthy();
});
});
describe('MinLengthValidator', () => {
it('should create an instance', () => {
expect(new MinLengthValidator(5, 'Something')).toBeTruthy();
});
});
describe('MaxLengthValidator', () => {
it('should create an instance', () => {
expect(new MaxLengthValidator(5, 'Something')).toBeTruthy();
});
});
|
d62d61f8374341cb780dfad3468febb1eeb2828e
|
TypeScript
|
yi-ge/ts-doc-gen-md
|
/src/ts-ast-utils/jsDoc/getJSDocTagValue/getJSDocTagValue.test.ts
| 2.984375
| 3
|
import { tagUnindent } from "../../../es-utils/index";
import { createMockSourceFile } from "../../../test-utils/createMockSourceFile";
import { getJSDocTagValue } from "./getJSDocTagValue";
const s = createMockSourceFile(tagUnindent`
/**
* I am the tag less comment
* @customTag
* hello world
* @description
* no description
* @customTag
* @customTag
* bye world
*/
declare type = number;
`).statements[0];
describe(getJSDocTagValue.name, () => {
it("returns the value of the specified jsDoc tag", () => {
expect(getJSDocTagValue(s, "customTag")).toEqual(["hello world", undefined, "bye world"]);
});
it("returns the tag less comment for provided jsDoc tag name being `null`", () => {
expect(getJSDocTagValue(s, null)).toEqual([`I am the tag less comment`]);
});
it("throws when the provided ast node does not have the specified jsDoc tag", () => {
const tagName = "myCustomTag";
expect(getJSDocTagValue(s, tagName)).toBe(undefined);
});
});
|
0ec75c6704b700f3c94ba10f33f11d3553ec04aa
|
TypeScript
|
cryptoless/BitGoJS
|
/modules/core/src/v2/coins/celoToken.ts
| 2.625
| 3
|
/**
* @prettier
*/
import { BitGo } from '../../bitgo';
import { Celo } from './celo';
import { CoinConstructor } from '../coinFactory';
import { coins } from '@bitgo/statics';
export interface CeloTokenConfig {
name: string;
type: string;
coin: string;
network: string;
tokenContractAddress: string;
decimalPlaces: number;
}
export class CeloToken extends Celo {
public readonly tokenConfig: CeloTokenConfig;
constructor(bitgo: BitGo, tokenConfig: CeloTokenConfig) {
const staticsCoin = tokenConfig.network === 'Mainnet' ? coins.get('celo') : coins.get('tcelo');
super(bitgo, staticsCoin);
this.tokenConfig = tokenConfig;
}
static createTokenConstructor(config: CeloTokenConfig): CoinConstructor {
return (bitgo: BitGo) => new CeloToken(bitgo, config);
}
get type() {
return this.tokenConfig.type;
}
get name() {
return this.tokenConfig.name;
}
get coin() {
return this.tokenConfig.coin;
}
get network() {
return this.tokenConfig.network;
}
get tokenContractAddress() {
return this.tokenConfig.tokenContractAddress;
}
get decimalPlaces() {
return this.tokenConfig.decimalPlaces;
}
getChain() {
return this.tokenConfig.type;
}
getBaseChain() {
return this.coin;
}
getFullName() {
return 'Celo Token';
}
getBaseFactor() {
return Math.pow(10, this.tokenConfig.decimalPlaces);
}
/**
* Flag for sending value of 0
* @returns {boolean} True if okay to send 0 value, false otherwise
*/
valuelessTransferAllowed() {
return false;
}
/**
* Flag for sending data along with transactions
* @returns {boolean} True if okay to send tx data (CELO), false otherwise
*/
transactionDataAllowed() {
return false;
}
}
|
f4baa5c38ee2cfea1ad10d6c464aa7951183df9a
|
TypeScript
|
VasoTracker/VasoTracker
|
/VasoTracker_Software/VasoTracker1.2.0/lib/bokeh/server/static/js/types/core/util/bbox.d.ts
| 2.890625
| 3
|
import { Arrayable, Rect, Box, Interval } from "../types";
export declare function empty(): Rect;
export declare function positive_x(): Rect;
export declare function positive_y(): Rect;
export declare function union(a: Rect, b: Rect): Rect;
export declare type HorizontalPosition = {
left: number;
width: number;
} | {
width: number;
right: number;
} | {
left: number;
right: number;
} | {
hcenter: number;
width: number;
};
export declare type VerticalPosition = {
top: number;
height: number;
} | {
height: number;
bottom: number;
} | {
top: number;
bottom: number;
} | {
vcenter: number;
height: number;
};
export declare type Position = HorizontalPosition & VerticalPosition;
export interface CoordinateTransform {
compute: (v: number) => number;
v_compute: (vv: Arrayable<number>) => Arrayable<number>;
}
export declare class BBox implements Rect {
readonly x0: number;
readonly y0: number;
readonly x1: number;
readonly y1: number;
constructor(box?: Rect | Box | Position);
toString(): string;
readonly left: number;
readonly top: number;
readonly right: number;
readonly bottom: number;
readonly p0: [number, number];
readonly p1: [number, number];
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly rect: Rect;
readonly box: Box;
readonly h_range: Interval;
readonly v_range: Interval;
readonly ranges: [Interval, Interval];
readonly aspect: number;
readonly hcenter: number;
readonly vcenter: number;
contains(x: number, y: number): boolean;
clip(x: number, y: number): [number, number];
union(that: Rect): BBox;
equals(that: Rect): boolean;
readonly xview: CoordinateTransform;
readonly yview: CoordinateTransform;
}
|
f75b6a20ce390f4dbf67a00e86cc63216d9667a3
|
TypeScript
|
sheenm/task-time-management
|
/src/utils/neverReached.ts
| 2.546875
| 3
|
/**
* use this function to on type-checking step forbid to execute code there
* (useful in switch)
*/
export const neverReached = (never: never) => {
throw new Error('did not set all action types in reducer')
}
|
edb0c3f11855b800b636de0801b24b0f6f28ca37
|
TypeScript
|
BulbProject/bulb-project-api
|
/src/shared/entity/category/item.entity.ts
| 2.59375
| 3
|
import { Type } from 'class-transformer';
import { IsArray, IsOptional, IsString, ArrayMinSize, ValidateNested, IsObject } from 'class-validator';
import { Classification } from './classification.entity';
export class Item {
@IsString()
public id: string;
@IsString()
public description: string;
@IsObject()
@Type(() => Classification)
@ValidateNested()
public classification: Classification;
@IsArray()
@ArrayMinSize(1)
@Type(() => Classification)
@ValidateNested({
each: true,
})
@IsOptional()
public additionalClassifications?: Classification[];
}
|