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
|
|---|---|---|---|---|---|---|
b367ddb70bc5542f298d1eb5d060c1a7377d0aa1
|
TypeScript
|
l3eto/angular-star-wars
|
/src/app/models/flash.ts
| 2.59375
| 3
|
export class Flash {
constructor(message: string, type: string, keepAfterLocationChange: boolean) {
this.message = message;
this.type = type;
this.keepAfterLocationChange = keepAfterLocationChange;
}
message: string;
type: string;
keepAfterLocationChange: boolean;
}
|
ed288c984d3665cb120752305a593b60ff00dd29
|
TypeScript
|
alesluca00/PW2021
|
/ITS.Allan.ProjectWork/ITS.Allan.ProjectWork.WebApp/ClientApp/src/app/shared/services/classroom.service.ts
| 2.5625
| 3
|
import { Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import Classroom from '../models/Classroom';
export default class ClassroomService {
public classroomUrl = '';
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
this.classroomUrl = this.baseUrl + 'api/Classrooms';
}
getAll(): Observable<Array<Classroom>> {
return this.http.get<Array<Classroom>>(this.classroomUrl);
}
get(id: string): Observable<Classroom> {
return this.http.get<Classroom>(`${this.classroomUrl}/${id}`);
}
save(classroom: Classroom): Observable<Classroom> {
let result: Observable<Classroom>;
if (classroom.idClassroom) {
result = this.http.put<Classroom>(
`${this.classroomUrl}/${classroom.idClassroom}`,
classroom
);
} else {
result = this.http.post<Classroom>(this.classroomUrl, classroom);
}
return result;
}
remove(id: number) {
return this.http.delete(`${this.classroomUrl}/${id.toString()}`);
}
}
|
bab786bf4fde6163b49911a704e5f6e08933d10f
|
TypeScript
|
areller/denogent
|
/src/lib/runtime/runtime.ts
| 2.8125
| 3
|
import { runCommand as runCommandInternal } from "../../internal/helpers/cmd.ts";
import type { CommandArgs } from "./args.ts";
import type { Extension } from "../core/extension.ts";
import { Args, dotenv, parseArgs } from "../../../deps.ts";
import { isWindows } from "../../internal/helpers/env.ts";
class Runtime {
private _args: Args;
constructor() {
dotenv();
this._args = parseArgs(Deno.args);
}
/**
* Runs a command and returns status and output.
* @param args command arguments
*/
public async command(args: CommandArgs): Promise<[boolean, string]> {
const originalCmd = args.cmd instanceof Array ? args.cmd : args.cmd.split(" ");
let cmd = originalCmd;
if (isWindows()) {
cmd = ["cmd", "/c", ...cmd];
}
const res = (await runCommandInternal(
cmd,
(line) => {
if (args.logger) {
args.logger.debug(line);
}
},
args.path,
false,
)) as [boolean, string];
if (!res[0] && (args.throwOnFailure ?? true)) {
throw new Error(`Command '${originalCmd.join(" ")}' has failed.`);
}
return res;
}
/**
* Gets the values of an argument.
* @param name the name of the argument
*/
public argValues(name: string): string[] {
const envValues = this.envArgValues(name);
if (envValues.length > 0) {
return envValues;
}
const cliValues = this.cliArgValues(name);
return cliValues;
}
/**
* Gets the value of an argument or throws an error.
* @param name the name of the argument
*/
public argValue(name: string): string {
const value = this.argValueOrDefault(name);
if (value === undefined) {
throw new Error(`Expected argument '${name}' to have a value.`);
}
return value;
}
/**
* Gets the value of an argument.
* @param name the name of the argument
*/
public argValueOrDefault(name: string): string | undefined {
const values = this.argValues(name);
if (values.length === 0) {
return undefined;
}
return values[0];
}
/**
* Declares a dependency on an environment secret.
* @param name the name of the secret
*/
public secret(name: string): Extension {
return {
name: "secret",
key: `secret_${name}`,
enrich: (t) => {
let secrets = t.properties["secrets"] as string[];
if (secrets === undefined) {
secrets = [];
t.properties["secrets"] = secrets;
}
secrets.push(name);
},
};
}
private cliArgValues(name: string): string[] {
const arg = this._args[name];
if (!arg) {
return [];
}
if (arg instanceof Array) {
return arg.map((a) => a.toString());
} else {
return [arg.toString()];
}
}
private envArgValues(name: string): string[] {
const arg = Deno.env.get(name);
if (!arg) {
return [];
}
return [arg];
}
}
const runtime = new Runtime();
export default runtime;
|
fafb64768da76fced96c29c4042cbb0e220a1be2
|
TypeScript
|
GSto/advent-of-code-2020
|
/day02/index.ts
| 3.53125
| 4
|
import fs from 'fs'
import { xor } from '../lib'
interface PasswordPolicy {
start: number,
end: number,
substring: string,
password: string
}
interface Range {
start: number,
end: number,
}
const contents = fs.readFileSync(__dirname+'/passwords.txt', 'utf8')
const passwords: string[] = contents.split('\n')
const policyList: PasswordPolicy[] = passwords.map(buildPolicy)
function inRange(num: number, range: Range): boolean {
return (num - range.start) * (num - range.end) <= 0
}
function countSubstring(string: string, subString: string): number {
if (!string || !subString) return 0
const pattern: RegExp = new RegExp(subString, 'g')
const matches: RegExpMatchArray | null = string.match(pattern)
return matches ? matches.length : 0
}
// example string 5-6 x: xxxxxmxf
function buildPolicy(row: string): PasswordPolicy {
// extract password
const passwordSplit = row.split(':')
if(passwordSplit.length !== 2) throw new Error('invalid policy type')
const prefix: string = passwordSplit[0]
const password: string = passwordSplit[1].trim()
//extract substring
const substringSplit = prefix.split(' ')
if(substringSplit.length !== 2) throw new Error('invalid policy type')
const range: string = substringSplit[0]
const substring: string = substringSplit[1]
//convert range to numbers
const rangeSplit = range.split('-')
if(rangeSplit.length !== 2) throw new Error('invalid policy type')
const start = parseInt(rangeSplit[0])
const end = parseInt(rangeSplit[1])
return {
start,
end,
substring,
password
}
}
//instances of substring must be between 'start' and 'end'
function isValidPolicyByLength(policy: PasswordPolicy): boolean {
const instances = countSubstring(policy.password, policy.substring)
return inRange(instances, policy)
}
// substring must appear at exactly one of the start and end positions.
// start and end are not zero-indexed, so start=1 is first chatacter.
function isValidPolicyByExclusivePosition(policy: PasswordPolicy): boolean {
const atStart = policy.password.charAt(policy.start - 1) === policy.substring
const atEnd = policy.password.charAt(policy.end - 1) === policy.substring
return xor(atStart, atEnd)
}
function countValidPasswords(passwords:PasswordPolicy[], validationRule: (p: PasswordPolicy) => boolean) : number {
return passwords.reduce((acc: number, policy: PasswordPolicy): number => {
if(validationRule(policy)) {
return acc + 1
}
return acc
}, 0)
}
const firstAnswer: number = countValidPasswords(policyList, isValidPolicyByLength)
const secondAnswer: number = countValidPasswords(policyList, isValidPolicyByExclusivePosition)
console.log('part 1:', firstAnswer)
console.log('part 2:', secondAnswer)
|
94685b43b2e82138e592be5999917bb1f09d8900
|
TypeScript
|
strangerintheq/hare-and-carrots
|
/src/reborn/objects/CellObject.ts
| 2.546875
| 3
|
import {Object3D} from "three";
import {CellObjectType} from "../data/CellObjectType";
import {Carrot} from "./Carrot";
import {Bush1} from "./Bush1";
import {Tree2} from "./Tree2";
import {Tree1} from "./Tree1";
import {Obj} from "../renderer/Obj";
import {Poo} from "./Poo";
import {Bush2} from "./Bush2";
import {Poo1} from "./Poo1";
import {PooSteps} from "./PooSteps";
import {Cell} from "../data/Cell";
export class CellObject extends Obj{
constructor(cell: Cell) {
super();
let o = cell.object;
if (o === CellObjectType.CARROT)
this.add(new Carrot());
if (o === CellObjectType.BUSH1)
this.add(new Bush1());
if (o === CellObjectType.BUSH2)
this.add(new Bush2());
if (o === CellObjectType.TREE1)
this.add(new Tree1());
if (o === CellObjectType.TREE2)
this.add(new Tree2());
if (o === CellObjectType.POO)
this.add(new Poo());
if (o === CellObjectType.POO1)
this.add(new Poo1());
if (o === CellObjectType.POO_STEPS)
this.add(new PooSteps());
this.rotation.set(0,cell.cellObjectRotation, 0);
}
}
|
1d249ef6f9cc7828260df3d8b6bbed505ca6a162
|
TypeScript
|
Patrick-Wang/LoanMgr
|
/collection/collection/src/main/webapp/jsp/sdk/protocol.ts
| 2.734375
| 3
|
import ServerContext = collection.protocol.ServerContext;
module collection.protocol {
export let carLoanTitle:string[] = [];
export let creditLoanTitle:string[] = [];
export let creditCardTitle:string[] = [];
export function getTitles(type):string[]{
let titles = undefined;
if (type == collection.protocol.EntrustedCaseType.carLoan){
titles = collection.protocol.carLoanTitle;
}else if(type == collection.protocol.EntrustedCaseType.creditCard){
titles = collection.protocol.creditCardTitle;
}else if(type == collection.protocol.EntrustedCaseType.creditLoan){
titles = collection.protocol.creditLoanTitle;
}
return titles;
}
function getPhone(ec, index){
if (index >= 0){
return ec[1 + index];
}
}
function getCommonPhone(lxr :string, titles:string[], clientName:string, ec:string[], nums :string[]){
let name = getPhone(ec, titles.indexOf(lxr + '姓名'));
let num = getPhone(ec, titles.indexOf(lxr + '家庭电话'));
if (num && name){
nums.push(lxr + " " + name + " 家庭电话:" + num);
}
num = getPhone(ec, titles.indexOf(lxr + '单位电话'));
if (num && name){
nums.push(lxr + " " + name + " 单位电话:" + num);
}
num = getPhone(ec, titles.indexOf(lxr + '手机'));
if (num && name){
nums.push(lxr + " " + name + " 手机:" + num);
}
}
function getCommonNums(titles:string[], clientName:string, ec:string[], nums :string[]){
getCommonPhone("联系人1", titles, clientName, ec, nums);
getCommonPhone("联系人2", titles, clientName, ec, nums);
getCommonPhone("联系人3", titles, clientName, ec, nums);
getCommonPhone("联系人4", titles, clientName, ec, nums);
getCommonPhone("联系人5", titles, clientName, ec, nums);
getCommonPhone("联系人6", titles, clientName, ec, nums);
getCommonPhone("联系人7", titles, clientName, ec, nums);
getCommonPhone("联系人8", titles, clientName, ec, nums);
getCommonPhone("联系人9", titles, clientName, ec, nums);
getCommonPhone("联系人10", titles, clientName, ec, nums);
}
function getCarloanPhone(ec:string[]): string[]{
let clientName =getPhone(ec, collection.protocol.carLoanTitle.indexOf('客户姓名'));
let nums = [];
let num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('客户手机'));
if (num){
nums.push(clientName + " 手机:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('客户宅电'));
if (num){
nums.push(clientName + " 宅电:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('客户公司电话'));
if (num){
nums.push(clientName + " 公司电话:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('配偶手机'));
if (num){
nums.push(clientName + " 配偶手机:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('配偶公司电话'));
if (num){
nums.push(clientName + " 配偶公司电话:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('担保人手机'));
if (num){
nums.push(clientName + " 担保人手机:" + num);
}
num = getPhone(ec, collection.protocol.carLoanTitle.indexOf('担保人公司电话'));
if (num){
nums.push(clientName + " 担保人公司电话:" + num);
}
getCommonNums(collection.protocol.carLoanTitle, clientName, ec, nums);
return nums;
}
function getCreditLoanPhone(ec:string[]): string[]{
let clientName =getPhone(ec, collection.protocol.creditLoanTitle.indexOf('客户姓名'));
let nums = [];
let num = getPhone(ec, collection.protocol.creditLoanTitle.indexOf('户籍电话'));
if (num){
nums.push(clientName + " 户籍电话:" + num);
}
num = getPhone(ec, collection.protocol.creditLoanTitle.indexOf('手机号码'));
if (num){
nums.push(clientName + " 手机:" + num);
}
num = getPhone(ec, collection.protocol.creditLoanTitle.indexOf('住宅电话'));
if (num){
nums.push(clientName + " 住宅电话:" + num);
}
num = getPhone(ec, collection.protocol.creditLoanTitle.indexOf('公司电话'));
if (num){
nums.push(clientName + " 公司电话:" + num);
}
getCommonNums(collection.protocol.creditLoanTitle, clientName, ec, nums);
return nums;
}
function getCreditCardPhone(ec:string[]): string[]{
let clientName =getPhone(ec, collection.protocol.creditCardTitle.indexOf('姓名'));
let nums = [];
let num = getPhone(ec, collection.protocol.creditCardTitle.indexOf('手机'));
if (num){
nums.push(clientName + " 手机:" + num);
}
num = getPhone(ec, collection.protocol.creditCardTitle.indexOf('家庭号码'));
if (num){
nums.push(clientName + " 家庭号码:" + num);
}
num = getPhone(ec, collection.protocol.creditCardTitle.indexOf('单位号码'));
if (num){
nums.push(clientName + " 单位号码:" + num);
}
getCommonNums(collection.protocol.creditCardTitle, clientName, ec, nums);
return nums;
}
export function getPhoneNums(type, ec:string[]):string[]{
let nums = [];
if (type == collection.protocol.EntrustedCaseType.carLoan){
nums = getCarloanPhone(ec);
}else if(type == collection.protocol.EntrustedCaseType.creditCard){
nums = getCreditCardPhone(ec);
}else if(type == collection.protocol.EntrustedCaseType.creditLoan){
nums = getCreditLoanPhone(ec);
}
return nums;
}
export class PhoneRecordName {
ecId:number;
numb:string;
time:string;
static isPhoneAttach(attach:string):boolean {
return attach.indexOf("phone:") == 0;
}
toName():string {
return this.ecId + "_" + this.numb + "_" + this.time;
}
}
export enum UseStatus{
inuse,
stop
}
export let ROLE = ["none", "管理员","内勤管理员","业务管理员","内勤","业务员"];
export enum RoleEN{
NONE, ADMIN, INSIDE_MGR, OUTSIDE_MGR, INSIDE, OUTSIDE
}
export interface User {
id:number;
name?:string;
orgId:number;
orgName?:string;
password?:string;
roles?:number[];
position:string;
status?:UseStatus;
}
export interface CreateUser {
name:string;
password:string;
orgId:number;
position:string;
roles:number[];
}
export interface Organization {
id:number;
name:string;
status:UseStatus;
subOrgs?:Organization[];
}
export interface Role {
id:number;
name:string;
}
export interface IF {
id:number;
address:string;
description:string;
}
export interface Result {
code:number;
msg:string;
}
export enum EntrustedCaseType{
carLoan,
creditLoan,
creditCard
}
export enum ECStatus{
unassign,
assign,
complete
}
export interface EntrustedCaseManageInfo {
id:number;
ownerId?:number;
ownerName?:string;
assigneeId?:number;
assigneeName?:string;
}
export interface EntrustedCaseReport {
id?:number;
entrustedCaseId:number;
date?:string;//2012-3-4
title?:string;
content?:string;
phoneRecId?:number;
attachements?:Attachement[];
}
export interface Attachement{
id?:number;
fileAddress?:string;
display?:string;
uploadTime?:string;
}
export enum MessageStatus{
unread,
read
}
export interface Message {
msgId:number
ecCode:string;
ecType:number;
ecMgrId:number;
fromId:number;
fromName:string;
toId:number;
toName:string;
title:string;
content:string;
attachements:Attachement[];
sendTime:string;//2013-12-11 58:11:23
read:MessageStatus;
}
export interface EC {
reports:EntrustedCaseReport[];
messages:Message[];
managerId:number;
owner?:string;
ownerId?:number;
assignee?:string;
assigneeId?:number;
pageCount?:number;
pageNum?:number;
records?:number;
loan:any[];
}
export interface QueryOption {
name?:string;
PIN?:string;
code?:string;//卡号,客户号、车牌号
wwrq?:string;//委外日期
wwjg?:string;//委外机构
wwzt?:string;//委外状态:未分配、工作中、已结案
mgrId?:number;
assignToMe?:boolean;
myOwn?:boolean;
limit?:number;
pageNum?:number;
pageSize?:number;
yqtsStartOpen?:number;
yqtsEndClose?:number;
assignee?:number;
pch?:string;
shuffle?:boolean;
}
export interface Promise<S> {
done(sFn:(sResult:S)=>void):Promise<S>;
fail(fFn:(fResult:any)=>void):Promise<S>;
}
export enum CallStatus{
callin,
callout,
missed,
missedSkip,
missedNotifySkip
}
export interface PhoneRecord {
recId:number;
status : CallStatus;
phoneNum:string;
time:string;
ecId:number;
ecCode:string;
ecType:number;
}
export interface ServerContext {
userName:string;
userId:number;
position:string;
org:string;
pOrg:string;
sipServerIP:string;
}
export interface AssignSummary {
total:number;
unassign:number;
assign:number;
complete:number;
}
export interface AcceptSummary {
total:number;
complete:number;
}
export interface ManagerSummary {
ljje:number;
yhje:number;
ygs:number;
}
}
declare var context:ServerContext;
|
5cc9a3ec62753496bf96e57394f92388c1636dfd
|
TypeScript
|
Eveble/core
|
/test/unit/utils/helpers.test.ts
| 3
| 3
|
import { expect } from 'chai';
import { PropTypes } from 'typend';
import {
isSerializable,
resolveSerializableFromPropType,
} from '../../../src/utils/helpers';
import { define } from '../../../src/decorators/define';
/* eslint-disable @typescript-eslint/no-empty-function */
describe('helpers', () => {
@define('SerializableStub')
class SerializableStub {
typeName(): void {}
toJSONValue(): void {}
}
describe('isSerializable', () => {
it('returns true for defined(@define) class instances implementing Serializable interface', () => {
@define('MySerialziable', { isRegistrable: false })
class MySerializable extends SerializableStub {}
expect(isSerializable(new MySerializable())).to.be.true;
});
it('returns false for not defined(@define) class instances that implementing Serializable interface', () => {
class MySerializable extends SerializableStub {}
expect(isSerializable(new MySerializable())).to.be.false;
});
it('returns false for nil', () => {
expect(isSerializable(null)).to.be.false;
expect(isSerializable(undefined)).to.be.false;
});
it('returns false for other arguments', () => {
class InvalidSerializable {}
expect(isSerializable(InvalidSerializable)).to.be.false;
});
});
describe('resolveSerializableFromPropType', () => {
it('resolves serializable type from root-level list', () => {
const propType = PropTypes.arrayOf(SerializableStub);
expect(resolveSerializableFromPropType(propType)).to.be.equal(
SerializableStub
);
});
it('resolves serializable type from root-level list with nested instance of', () => {
const propType = PropTypes.arrayOf(
PropTypes.instanceOf(SerializableStub)
);
expect(resolveSerializableFromPropType(propType)).to.be.equal(
SerializableStub
);
});
it('resolves serializable type from root-level optional list with nested instance of', () => {
const propType = PropTypes.arrayOf(
PropTypes.instanceOf(SerializableStub)
).isOptional;
expect(resolveSerializableFromPropType(propType)).to.be.equal(
SerializableStub
);
});
it('returns undefined for non-list serializable types', () => {
const propType = PropTypes.instanceOf(SerializableStub);
expect(resolveSerializableFromPropType(propType)).to.be.undefined;
});
it('returns undefined for nil prop type', () => {
expect(resolveSerializableFromPropType(null)).to.be.undefined;
expect(resolveSerializableFromPropType(undefined)).to.be.undefined;
});
});
});
|
da55f1e89cad528cb3d973aa3f25e9f6dfa82eac
|
TypeScript
|
moepyxxx/practice-ts-pokemon
|
/src/model/statusAilment/SaFreeze.ts
| 2.515625
| 3
|
import { StatusAilment } from './StatusAilment';
export class SaFreeze extends StatusAilment {
/**
* 名前
*/
protected _name: string = 'こおり';
/**
* 状態異常になった時のメッセージ
*/
protected _sickedMessage: string = 'こおりづけになった';
/**
* すでに状態異常だったときのメッセージ
*/
protected _alreadySickedMessage: string = 'すでにこおっている';
/**
* 状態異常のままターンになったときのメッセージ
*/
protected _sickedTurnMessage: string = 'こおってしまってうごけない';
/**
* 状態異常が回復したときのメッセージ
*/
protected _sickedRecoceryMessage = 'こおりがとけた';
}
|
a0e6053f09e82e2a70f4a13505d973f6c009cb74
|
TypeScript
|
daniel1433/app-reactjs
|
/src/services/api_servise.ts
| 2.59375
| 3
|
import { param } from "jquery";
interface paramsGet {
key: string;
value: string | number;
}
export default class API {
private requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'authorization': sessionStorage.getItem("session") ? '1' : '0' },
body: ""
};
private requestOptionsGET = {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'authorization': sessionStorage.getItem("session") ? '1' : '0' }
};
async get(uri: string, params?: paramsGet[], providerOrigin?: boolean, origin?: string) {
let allUri: string = `${process.env.REACT_APP_API_URL}/${providerOrigin && origin ? origin : 'API'}${uri}`;
if (params) {
if (param.length > 0) {
allUri += `?${params.map((val: paramsGet) => val.value ? `${val.key}=${val.value}` : '')}`.replace(/\,/gi, '&')
}
}
return fetch(allUri, this.requestOptionsGET).then(result => result.json());
}
async post(uri: string, body: any) {
let allUri: string = `${process.env.REACT_APP_API_URL}/${uri}`;
this.requestOptions.body = body ? JSON.stringify(body) : "";
this.requestOptions.method = "POST";
return fetch(allUri, this.requestOptions).then(result => result.json());
}
async put(uri: string, body: any) {
let allUri: string = `${process.env.REACT_APP_API_URL}/${uri}`;
this.requestOptions.body = body ? JSON.stringify(body) : "";
this.requestOptions.method = "PUT";
return fetch(allUri, this.requestOptions).then(result => result.json());
}
}
|
75a30eeec32f19b5a7507ec803bbbde7752b149c
|
TypeScript
|
envoy/loglevel-file-logger
|
/src/defaultFormatter.ts
| 3.3125
| 3
|
/// Default formatter for formatting log message
export default (
loggerName: string,
methodName: string,
objects: Array<any>,
now?: () => Date
) => {
const withDate = [
now ? now().toISOString() : new Date().toISOString(),
loggerName,
`[${methodName.toUpperCase()}]`,
...objects
]
return withDate
.map(object => {
if (object === undefined) {
return '[object Undefined]'
} else if (object === null) {
return '[object Null]'
} else if (
Object.prototype.toString.call(object) === '[object Object]' ||
Array.isArray(object)
) {
return JSON.stringify(object)
}
return object.toString()
})
.join(' ')
}
|
5a0e1b4632b2f6f9709e644cb2658f9fad8fb836
|
TypeScript
|
erezbm/javascript-dynalist-api-wrapper
|
/src/api-types/document-level/changes.ts
| 2.78125
| 3
|
import { BackgroundColor, HeadingLevel } from '.';
import { Id } from '..';
import { ChangeAction } from '../changes';
export type DocumentLevelInsertParams = {
/** The ID of the parent node to insert under. */
parent_id: Id;
/** The zero-indexed position the node should be in the parent node's children, supply -1 to place it at the end. */
index: number;
/** The new node's content. */
content: string;
/** The new node's note. */
note?: string;
/** Whether the new node should be checked off. */
checked?: boolean;
/** Whether the new node should have a checkbox. */
checkbox?: boolean;
/** The new node's heading level. */
heading?: HeadingLevel;
/** The new node's background color. */
color?: BackgroundColor;
};
export type DocumentLevelEditParams = {
/** The ID of the node to edit. */
node_id: Id;
/** The new content. */
content?: string;
/** The new note. */
note?: string;
/** Whether the node should be checked off. */
checked?: boolean;
/** Whether the node should have a checkbox. */
checkbox?: boolean;
/** The new heading level. */
heading?: HeadingLevel;
/** The new background color. */
color?: BackgroundColor;
};
export type DocumentLevelMoveParams = {
/** The ID of the node to move. */
node_id: Id;
/** The ID of the parent node to move under. */
parent_id: Id;
/** The zero-indexed position the node should be in the parent node's children, supply -1 to place it at the end. */
index: number;
};
export type DocumentLevelDeleteParams = {
/** The Id of the node to delete. */
node_id: Id;
};
type DocumentLevelInsert = ChangeAction<'insert'> & DocumentLevelInsertParams;
type DocumentLevelEdit = ChangeAction<'edit'> & DocumentLevelEditParams;
type DocumentLevelMove = ChangeAction<'move'> & DocumentLevelMoveParams;
type DocumentLevelDelete = ChangeAction<'delete'> & DocumentLevelDeleteParams;
export type DocumentLevelChange = DocumentLevelInsert | DocumentLevelEdit | DocumentLevelMove | DocumentLevelDelete;
|
ac10f86cd603ac580c5cea70ae24db91d48e6be6
|
TypeScript
|
teuncortooms/Quizinator_TypeScript
|
/server/services/SpreadsheetHandler.ts
| 2.953125
| 3
|
class SpreadsheetHandler {
private spreadsheetId: any;
private sheet: any;
public constructor() {
this.spreadsheetId = SpreadsheetApp.getActive();
this.sheet = this.spreadsheetId.getActiveSheet();
}
get Data(): string[][] { return this.sheet.getDataRange().getValues(); };
get Units(): string[] {
let data = this.Data;
// Find all unique units in sheet (for user selection in sidebar)
let unitCol = 3;
let units = [];
let uniqueunits;
let excludes = ["", "unit", "units", "Unit", "Units"];
// get every unit of every row
for (let i = 0; i < data.length; i++) {
let unit = data[i][unitCol];
units.push(unit);
};
// filter unique units
uniqueunits = units.filter(function (value, index, arr) {
return arr.indexOf(value) === index;
});
// filter out non-units
for (let j = 0; j < excludes.length; j++) {
let index = uniqueunits.indexOf(excludes[j]);
if (index > -1) {
uniqueunits.splice(index, 1);
}
}
return uniqueunits;
}
public createExampleSheet() {
let exampleSheet = this.spreadsheetId.getSheetByName("Example sheet");
if (exampleSheet != null) {
this.sheet = exampleSheet;
}
else {
this.sheet = this.spreadsheetId.insertSheet('Example sheet');
}
this.spreadsheetId.setActiveSheet(this.sheet);
let values = [
["Word", "Translation", "Example sentence", "Unit"],
["nice adj", "mooi, lekker", "If the weather isn’t going to be nice, let’s stay in.", "Unit 1"],
["spell v", "spellen, schrijven", "Do you spell ‘grey’ with an ‘a’ or an ‘e’?", "Unit 1"],
["student n", "student", "Say hello to the other students in the class.", "Unit 1"],
["surname n", "achternaam", "What is your surname?", "Unit 1"],
["what pron", "wat", "What is your name?", "Unit 1"],
["where adv", "waar", "Where are you from?", "Unit 1"],
["Excuse me", "beleefdsheidsuitdrukking", "Excuse me, sir, could you help me find my brain?", "Unit 3"],
["flowers", "bloemen", "Let me tell you about the birds and the bees, and the flowers and the trees.", "Unit 3"],
["evening", "avond", "I pack my bag in the evening, so I don’t need to in the morning.", "Unit 3"],
["happy", "blij", "If you’re happy and you know it clap your hands.", "Unit 3"],
["Wednesday", "woensdag", "I met my new best friend in the city centre last Wednesday.", "Unit 3"],
["always", "altijd", "I should get up earlier, because I am always late.", "Unit 3"],
["little", "kleine", "You can't go to bed without a cup of tea. I'm in love with you and all these little things. (One Direction!)", "Unit 3"],
["swimming", "zwemmen", "I love to go swimming, because I’m too sexy for sports that need clothes.", "Unit 3"],
["cycling", "fietsen", "My dad says he wants to go cycling with me, but I don’t want to go outside.", "Unit 3"],
["bath", "bad", "If you put a frog in a pot and slowly turn up the heat, it will enjoy the nice warm bath until it is cooked to death.", "Unit 3"],
["finish", "klaar zijn met", "You should do your homework as soon as you can, so you don’t finish it too late.", "Unit 3"],
["listen", "luisteren", "Talk to the hand! I won’t listen.", "Unit 3"],
["chicken", "kip", "A chicken slurps grass like spaghetti. Yes, you read that right!", "Unit 3"],
["foreign", "vreemd/buitendlands", "It's fun to learn about foreign cultures.", "Unit 3"],
["takeaway", "afhaalmaaltijd", "If I can’t be bothered cooking, I send out for a takeaway.", "Unit 3"],
["Thursday", "donderdag", "On Thursday, it is my job to do the dishes.", "Unit 3"],
["exercise", "oefening", "The teacher has given us an exercise to do for homework.", "Unit 3"],
["cinema", "bioscoop", "I really want to see that movie. Did you buy tickets for the cinema tonight?", "Unit 3"],
["cook", "koken", "My father usually prepares dinner, but sometimes my mother and I cook.", "Unit 3"],
["often", "vaak", "I fight with my brother very often - almost every day, in fact.", "Unit 3"],
["music", "muziek", "I hate loud music, but I love soft rock.", "Unit 3"],
["holiday", "vakantie", "The beaches are busy in August because everyone is on holiday then.", "Unit 3"],
["enjoy", "genieten", "It’s nice to do tests. I really enjoy the silence.", "Unit 3"],
["competence", "compententie", "I regard him as a man of integrity and high professional competence.", "Unit 3"],
["compendium", "compendium", "His book is a delightful compendium of important questions.", "Unit 3"],
["compassion", "mededogen", "There is no need to show compassion for him.", "Unit 3"],
["libidinous", "wellustig", "The child should be kept away from libidinous movies.", "Unit 3"],
["revelry", "feestvreugde", "I called the police when my neighbours refused to settle down and end their revelry.", "Unit 3"]
];
this.sheet.getRange("A1:D35").setValues(values);
if (this.sheet.getFilter() == null) {
this.sheet.getRange("1:35").createFilter();
}
this.sheet.getRange("A2")
.setNote("lexical info like (v), (n), (adj) does not need to be removed for the addon to function");
this.sheet.setFrozenRows(1);
this.sheet.autoResizeColumn(1);
this.sheet.autoResizeColumn(2);
this.sheet.setColumnWidth(3, 400);
this.sheet.autoResizeColumn(4);
}
}
|
14197e24197008837222414afd40b02a35a13d33
|
TypeScript
|
dangphu2412/Example-nestjs-boilerplate
|
/src/packages/restBuilder/modules/Validator/entity/LengthValidator.ts
| 3.21875
| 3
|
import {BadRequestException} from '@common/exceptions';
import {OptionalValidator} from '@packages/restBuilder/modules/Validator/OptionalValidator';
export class LengthValidator implements OptionalValidator<string[]> {
private readonly message: string;
private readonly lengthValidate: number;
constructor(lengthValidate: number, message?: string) {
this.lengthValidate = lengthValidate;
message ? this.message = message
: this.message = `Input format should be contain ${this.lengthValidate} character`;
}
validate(obj: string[]): void {
if (obj.length !== this.lengthValidate) {
throw new BadRequestException(this.message);
}
}
}
|
8fdf85dbcb5127794b67791c654b46597b6ea114
|
TypeScript
|
wu-yu-xuan/parseJson
|
/interface.d.ts
| 2.984375
| 3
|
export interface ValidJsonString {
type:
| 'false'
| 'true'
| 'null'
| 'number'
| 'string'
| 'object'
| 'array'
| 'error';
value: string;
}
export type Json = boolean | null | number | string | JsonObject | JsonArray;
export interface JsonArray extends Array<Json> {}
export interface JsonObject {
[key: string]: Json;
}
|
5260978bde4bb7b2a6cc5468b2a66cd028893635
|
TypeScript
|
djek88/noteappangular2
|
/src/app/notes/shared/note.ts
| 2.859375
| 3
|
export class Note {
constructor(
public id: number = null,
public title: string = '',
public content: string = '',
public updatedAt: Date = new Date(),
public createdAt: Date = new Date()
) {}
static clone(note: Note) {
return new Note(
note.id,
note.title,
note.content,
note.updatedAt,
note.createdAt
);
}
}
|
3d9a0e7e1a6c890911019f6a14c1a1443982b1eb
|
TypeScript
|
kwoncharles/fp-modules
|
/src/core/Monad.ts
| 2.78125
| 3
|
import Functor from './Functor';
export default interface Monad<T> extends Functor<T> {
flatMap<R>(mapperFn: (wrapped: T) => Monad<R>): Monad<R>;
}
|
1b561880d47e96803cb98a26413d5f53c885e0b5
|
TypeScript
|
d-kostov-dev/JavaScript-OOP
|
/TypeScriptHomework/Battlefield/baseclasses/Soldier.ts
| 3.515625
| 4
|
module BaseClasses {
export class Soldier implements Interfaces.ISoldier {
name: string;
health: number;
damage: number;
constructor(name: string, health: number, damage: number) {
this.name = name;
this.health = health;
this.damage = damage;
}
greet() : string{
return "Hi my name is " + this.name;
}
attack(): void {
console.log(name + "started an attack");
}
}
}
|
9e7e20fcc847cde201af12d33cf4eae6adb9c3ff
|
TypeScript
|
JesusCarm/wsa
|
/classes/Core/engine/Vector/Vector2.ts
| 3.390625
| 3
|
module WSA {
export class Vector2 {
private c: Array<number> = [0,0];
public constructor(x: number = 0, y: number = 0){
this.x = x;
this.y = y;
}
/*
GETTERS / SETTERS
*/
public get x(): number {
return this.c[0];
}
public get y(): number{
return this.c[1];
}
public set x(x: number){
this.c[0] = x;
}
public set y(y: number){
this.c[1] = y;
}
public getX(): number {
return this.x;
}
public getY(): number{
return this.y;
}
public get(i: number): number{
return this.c[i];
}
public getCoordinates(): Array<number>{
return this.c;
}
public setX(x: number): Vector2 {
this.x = x;
return this;
}
public setY(y: number): Vector2 {
this.y = y;
return this;
}
public set(x: number, y: number): Vector2{
this.x = x;
this.y = y;
return this;
}
/*
OPERATIONS ON VECTOR
*/
public add(v: Vector2): Vector2;
public add(v1: Vector2,v2: Vector2): Vector2;
public add(x: number, y: number): Vector2;
add(){
if(arguments[0] instanceof Vector2){
if(arguments[1] instanceof Vector2){
return new Vector2(
arguments[0].x + arguments[1].x,
arguments[0].y + arguments[1].y
);
}else{
this.x += arguments[0].x;
this.y += arguments[0].y;
}
}else{
this.x += arguments[0];
this.y += arguments[1];
}
return this;
}
public subtract(v: Vector2): Vector2;
public subtract(v1: Vector2, v2: Vector2): Vector2;
public subtract(x: number, y: number): Vector2;
subtract(){
if(arguments[0] instanceof Vector2){
if(arguments[1] instanceof Vector2){
return new Vector2(
arguments[0].x - arguments[1].x,
arguments[0].y - arguments[1].y
);
} else{
this.x -= arguments[0].x;
this.y -= arguments[0].y;
}
}else{
this.x -= arguments[0];
this.y -= arguments[1];
}
return this;
}
public multiply(s: number): Vector2;
public multiply(v: Vector2): Vector2;
public multiply(v1: Vector2, v2: Vector2): Vector2;
public multiply(x: number, y: number): Vector2;
multiply(){
if(typeof arguments[0] === "number" && arguments[1] === undefined){
this.x *= arguments[0];
this.y *= arguments[0];
}
else if(arguments[0] instanceof Vector2){
if(arguments[1] instanceof Vector2){
return new Vector2(
arguments[0].x * arguments[1].x,
arguments[0].y * arguments[1].y
);
}else{
this.x *= arguments[0].x;
this.y *= arguments[0].y;
}
}else{
this.x *= arguments[0];
this.y *= arguments[1];
}
return this;
}
public divide(v: Vector2): Vector2;
public divide(v1: Vector2,v2: Vector2): Vector2;
public divide(x: number, y: number): Vector2;
divide(){
if(arguments[0] instanceof Vector2){
if(arguments[1] instanceof Vector2){
return new Vector2(
arguments[0].x / arguments[1].x,
arguments[0].y / arguments[1].y
)
}else{
this.x /= arguments[0].x;
this.y /= arguments[0].y;
}
}else{
this.x /= arguments[0];
this.y /= arguments[1];
}
return this;
}
public scale(n: number): Vector2 {
this.x *= n;
this.y *= n;
return this;
}
public negate(): Vector2 {
return this.scale(-1);
}
public normalize(): Vector2 {
var length = this.getLength();
if(length===0)
return this.set(0,0);
return this.scale(1.0/length);
}
/*
ADDITIONAL FUNCTIONS
*/
public getLength(): number {
return Math.sqrt(this.getSquaredLength());
}
public getSquaredLength(): number {
return this.x*this.x + this.y*this.y;
}
public copy(): Vector2{
return new Vector2(this.x, this.y);
}
public equals(v: Vector2): boolean{
return v.x==this.x && v.y==this.y;
}
public toString(): string{
return "["+this.x+", "+this.y+"]";
}
/*
STATIC FUNCTIONS
*/
public static dot(v1: Vector2, v2: Vector2): number {
return (v1.x*v2.x + v1.y*v2.y);
}
public static cross(v1: Vector2, v2: Vector2): number{
return (v1.x*v2.y - v1.y*v2.x);
}
public static distance(v1: Vector2, v2: Vector2): number{
var x = v2.x - v1.x;
var y = v2.y - v1.y;
return Math.sqrt(x*x + y*y);
}
// a1 is line1 start, a2 is line1 end, b1 is line2 start, b2 is line2 end
public static intersection(a1: Vector2, a2: Vector2, b1: Vector2, b2: Vector2): Vector2 {
let vector2 = new Vector2();
let b: Vector2 = vector2.subtract(a2,a1); //a2 - a1;
let d: Vector2 = vector2.subtract(b2,b1); // b2 - b1;
let bDotDPerp = b.x * d.y - b.y * d.x;
// if b dot d == 0, it means the lines are parallel so have infinite intersection points
if (bDotDPerp == 0)
return null;
let c: Vector2 = vector2.subtract(b1,a1) //b1 - a1;
let t: number = (c.x * d.y - c.y * d.x) / bDotDPerp;
if (t < 0 || t > 1)
return null;
let u = (c.x * b.y - c.y * b.x) / bDotDPerp;
if (u < 0 || u > 1)
return null;
return vector2.add(a1, b.multiply(t));// + t * b;
}
/*
STATIC VARIABLES
*/
public static get ZERO(){
return new Vector2(0,0);
}
public static get ONE(){
return new Vector2(1,1);
}
public static get RIGHT(){
return new Vector2(1,0);
}
public static get LEFT(){
return new Vector2(-1,0);
}
public static get UP(){
return new Vector2(0,1);
}
public static get DOWN(){
return new Vector2(0,-1);
}
}
}
|
292c57178d0d75df9c61a6b7e8567c4aef1d411d
|
TypeScript
|
kamsac/js13k-2018
|
/src/world/World.ts
| 2.53125
| 3
|
import Size from '../helpers/Size';
import {canvasSize} from '../render/GameRenderer';
import MainCharacter from '../main-character/MainCharacter';
import AABB from '../helpers/AABB';
import Flyswat from '../flyswat/Flyswat';
import Insect from '../insect/Insect';
import Cable from '../cable/Cable';
import Point from '../helpers/Point';
import CableBuilder from '../cable/CableBuilder';
import Game, {GameState} from '../Game';
import Computer from '../cable/Computer';
export const worldSize: Size = canvasSize;
export default class World {
public game: Game;
public tick: number;
public ticksSurvivedFor: number;
public player: MainCharacter;
public roomWalls: AABB[];
public flyswat: Flyswat;
public walkingArea: AABB;
public insects: Insect[];
public cables: Cable[];
public computers: Computer[];
public score: number;
public cableBites: number;
public cableTreads: number;
public constructor(game: Game) {
this.game = game;
this.tick = 0;
this.ticksSurvivedFor = 0;
this.player = new MainCharacter(this);
this.flyswat = new Flyswat(this);
this.walkingArea = this.getWallkingArea();
this.roomWalls = this.getRoomWalls();
this.insects = [];
this.cables = [];
this.computers = [];
this.score = 0;
this.cableBites = 0;
this.cableTreads = 0;
for (let i = 0; i < 4; i++) {
this.spawnInsect();
}
this.spawnCables();
}
public update(): void {
this.tick++;
this.insects.forEach((insect) => {
insect.update();
});
this.player.update();
this.flyswat.update();
this.cables.forEach((cable) => {
cable.update();
});
if (this.game.state !== GameState.GameOver) {
this.ticksSurvivedFor = this.tick;
}
}
public spawnInsect(): void {
this.insects.push(new Insect(this));
}
private spawnCables(): void {
const cableBuilder: CableBuilder = new CableBuilder(this);
const cable1Computers: Computer[] = [
new Computer(this, this.getWalkingAreaPoint(new Point(0, 200)), 'right'),
new Computer(this, this.getWalkingAreaPoint(new Point(300, -5)), 'down'),
];
const cable1: Cable[] = cableBuilder.createCables(
[
new Point(0, 200),
new Point(50, 200),
new Point(100, 200),
new Point(100, 150),
new Point(150, 150),
new Point(150, 100),
new Point(200, 100),
new Point(250, 100),
new Point(300, 100),
new Point(300, 50),
new Point(300, 0),
],
cable1Computers,
);
const cable2Computers: Computer[] = [
new Computer(this, this.getWalkingAreaPoint(new Point(200, -5)), 'down'),
new Computer(this, this.getWalkingAreaPoint(new Point(300, 395)), 'up'),
];
const cable2: Cable[] = cableBuilder.createCables(
[
new Point(200, 0),
new Point(200, 50),
new Point(200, 100),
new Point(200, 150),
new Point(200, 200),
new Point(250, 200),
new Point(250, 250),
new Point(250, 300),
new Point(250, 350),
new Point(300, 350),
new Point(300, 400),
],
cable2Computers,
);
const cable3Computers: Computer[] = [
new Computer(this, this.getWalkingAreaPoint(new Point(200, 395)), 'up'),
new Computer(this, this.getWalkingAreaPoint(new Point(650, 150)), 'left'),
];
const cable3: Cable[] = cableBuilder.createCables(
[
new Point(200, 400),
new Point(200, 350),
new Point(200, 300),
new Point(250, 300),
new Point(300, 300),
new Point(350, 300),
new Point(400, 300),
new Point(400, 250),
new Point(450, 250),
new Point(450, 200),
new Point(450, 150),
new Point(500, 150),
new Point(550, 150),
new Point(600, 150),
new Point(650, 150),
],
cable3Computers,
);
const cable4Computers: Computer[] = [
new Computer(this, this.getWalkingAreaPoint(new Point(600, 395)), 'up'),
new Computer(this, this.getWalkingAreaPoint(new Point(0, 300)), 'right'),
];
const cable4: Cable[] = cableBuilder.createCables(
[
new Point(600, 400),
new Point(600, 350),
new Point(550, 350),
new Point(500, 350),
new Point(450, 350),
new Point(400, 350),
new Point(350, 350),
new Point(350, 300),
new Point(350, 250),
new Point(300, 250),
new Point(250, 250),
new Point(200, 250),
new Point(150, 250),
new Point(100, 250),
new Point(100, 300),
new Point(50, 300),
new Point(0, 300),
],
cable4Computers,
);
const cable5Computers: Computer[] = [
new Computer(this, this.getWalkingAreaPoint(new Point(500, -5)), 'down'),
new Computer(this, this.getWalkingAreaPoint(new Point(650, 250)), 'left'),
];
const cable5: Cable[] = cableBuilder.createCables(
[
new Point(500, 0),
new Point(500, 50),
new Point(500, 100),
new Point(500, 150),
new Point(500, 200),
new Point(500, 250),
new Point(550, 250),
new Point(600, 250),
new Point(650, 250),
],
cable5Computers,
);
this.cables.push(
...cable1,
...cable2,
...cable3,
...cable4,
...cable5,
);
this.computers.push(
...cable1Computers,
...cable2Computers,
...cable3Computers,
...cable4Computers,
...cable5Computers,
);
}
private getWallkingArea(): AABB {
return {
x: leftMargin + wallDepth,
y: topMargin + wallDepth,
width: worldSize.width - leftMargin - rightMargin - wallDepth*2,
height: worldSize.height - topMargin - bottomMargin - wallDepth*2,
};
}
private getRoomWalls(): AABB[] {
return [
{ // left
x: leftMargin,
y: topMargin,
width: wallDepth,
height: worldSize.height - topMargin - bottomMargin,
},
{ // top
x: leftMargin,
y: topMargin,
width: worldSize.width - leftMargin - rightMargin,
height: wallDepth,
},
{ // right
x: worldSize.width - rightMargin - wallDepth,
y: topMargin,
width: wallDepth,
height: worldSize.height - topMargin - bottomMargin,
},
{ // bottom
x: leftMargin,
y: worldSize.height - bottomMargin - wallDepth,
width: worldSize.width - leftMargin - rightMargin,
height: wallDepth,
}
];
}
private getWalkingAreaPoint(point: Point): Point {
return new Point(
point.x + this.walkingArea.x,
point.y + this.walkingArea.y,
);
}
}
const wallDepth: number = 20;
const topMargin: number = 150;
const leftMargin: number = 55;
const rightMargin: number = leftMargin;
const bottomMargin: number = 10;
|
5ff6f320a9d23faf9e1f4d1fe6cb4f4cf76c1120
|
TypeScript
|
SINTEF-9012/mobileMaster
|
/test/spec/filters/distance.ts
| 2.546875
| 3
|
/// <reference path="./../../../app/bower_components/DefinitelyTyped/angularjs/angular-mocks.d.ts" />
/// <reference path="./../../../app/bower_components/DefinitelyTyped/jasmine/jasmine.d.ts" />
'use strict';
describe('Filter: distance', function () {
// load the filter's module
beforeEach(module('mobileMasterApp'));
// initialize a new instance of the filter before each test
var distance;
beforeEach(inject(function ($filter) {
distance = $filter('distance');
}));
it('should return an undefined value when the input is incorrect', function () {
expect(distance(null)).toBe(undefined);
expect(distance({})).toBe(undefined);
expect(distance({from: {}, to: {}})).toBe(undefined);
});
it('should return a distance', function () {
// Just one test because it doesn't make sense to test Leaflet
expect(distance({from: {lat: 0.0, lng:0.0}, to: {lat: 1.1, lng:1.1}})).toBeGreaterThan(10)
});
});
|
ec2a23acb17ca6919452a4f8e795b4478bf78ad1
|
TypeScript
|
fazilathfathima5656/cloud-tool
|
/toolbox_2.0/packages/nodes-base/credentials/ZendeskOAuth2Api.credentials.ts
| 2.578125
| 3
|
import {
ICredentialType,
NodePropertyTypes,
} from '@toolbox/toolbox-workflow';
const scopes = [
'read',
'write',
];
export class ZendeskOAuth2Api implements ICredentialType {
name = 'zendeskOAuth2Api';
extends = [
'oAuth2Api',
];
displayName = 'Zendesk OAuth2 API';
documentationUrl = 'zendesk';
properties = [
{
displayName: 'Subdomain',
name: 'subdomain',
type: 'string' as NodePropertyTypes,
default: '',
placeholder: 'toolbox',
description: 'The subdomain of your Zendesk work environment.',
required: true,
},
{
displayName: 'Authorization URL',
name: 'authUrl',
type: 'string' as NodePropertyTypes,
default: 'https://{SUBDOMAIN_HERE}.zendesk.com/oauth/authorizations/new',
description: 'URL to get authorization code. Replace {SUBDOMAIN_HERE} with your subdomain.',
required: true,
},
{
displayName: 'Access Token URL',
name: 'accessTokenUrl',
type: 'string' as NodePropertyTypes,
default: 'https://{SUBDOMAIN_HERE}.zendesk.com/oauth/tokens',
description: 'URL to get access token. Replace {SUBDOMAIN_HERE} with your subdomain.',
required: true,
},
{
displayName: 'Client ID',
name: 'clientId',
type: 'string' as NodePropertyTypes,
default: '',
required: true,
},
{
displayName: 'Client Secret',
name: 'clientSecret',
type: 'string' as NodePropertyTypes,
default: '',
required: true,
},
{
displayName: 'Scope',
name: 'scope',
type: 'hidden' as NodePropertyTypes,
default: scopes.join(' '),
},
{
displayName: 'Auth URI Query Parameters',
name: 'authQueryParameters',
type: 'hidden' as NodePropertyTypes,
default: '',
description: 'For some services additional query parameters have to be set which can be defined here.',
placeholder: '',
},
{
displayName: 'Authentication',
name: 'authentication',
type: 'hidden' as NodePropertyTypes,
default: 'body',
description: 'Resource to consume.',
},
];
}
|
792f47221ba581d5d2965f7ed1f25eeca1889aa5
|
TypeScript
|
TrelloVol2-Bravo1/TrelloVol2-FrontEnd
|
/src/models/card.model.ts
| 2.734375
| 3
|
export class CardModel {
constructor(private card_id: number, private list_id: number, private card_name: string, private card_description: string) {
}
getCardID(): number {
return this.card_id;
}
getCardName(): string {
return this.card_name;
}
getCardListID(): number {
return this.list_id;
}
getCardDescription(): string {
return this.card_description
}
}
|
61d79d9712ae3713ea4d2c39d1f710201f828a7b
|
TypeScript
|
akhilsarasan/hydrogen
|
/packages/cli/src/commands/create/app/templates/Index-server-jsx.ts
| 2.546875
| 3
|
import {Feature} from '../../../../utilities/feature';
import {TemplateOptions} from '../../../../types';
export default function ({features, name}: TemplateOptions) {
const featuresMarkup = features.length
? `
<h2>Features:</h2>
<ul>
${features
.map(
(feature) =>
`<li ${
features.includes(Feature.Tailwind)
? `className="text-blue-700"`
: ''
}>${feature}</li>`
)
.join('')}
</ul>
`
: '';
return `
import Link from '../components/Link.client';
export default function Index() {
return (
<div className="Page">
<p>
<Link className="link" to="/about">
About
</Link>
</p>
<h1>
Welcome to{' '}
<a target="_blank" href="https://github.com/Shopify/hydrogen">
Hydrogen
</a>{' '}
💦
</h1>
<p>
Hydrogen is a{' '}
<a target="_blank" href="https://reactjs.org/">
React
</a>{' '}
framework and a SDK for building custom{' '}
<a target="_blank" href="https://shopify.com">
Shopify
</a>{' '}
storefronts.
</p>
<p>
Get started by editing <strong>pages/Index.server.jsx</strong>
<br /> or reading our{' '}
<a target="_blank" href="https://hydrogen.docs.shopify.io/">
getting started guide
</a>
.
</p>
<h2 className="appName">${name}</h2>
${featuresMarkup}
</div>
);
}
`;
}
|
d231c2b281da8c757e8c96197e23653b0b1e4f2d
|
TypeScript
|
msgpack/msgpack-javascript
|
/src/utils/int.ts
| 3.109375
| 3
|
// Integer Utility
export const UINT32_MAX = 0xffff_ffff;
// DataView extension to handle int64 / uint64,
// where the actual range is 53-bits integer (a.k.a. safe integer)
export function setUint64(view: DataView, offset: number, value: number): void {
const high = value / 0x1_0000_0000;
const low = value; // high bits are truncated by DataView
view.setUint32(offset, high);
view.setUint32(offset + 4, low);
}
export function setInt64(view: DataView, offset: number, value: number): void {
const high = Math.floor(value / 0x1_0000_0000);
const low = value; // high bits are truncated by DataView
view.setUint32(offset, high);
view.setUint32(offset + 4, low);
}
export function getInt64(view: DataView, offset: number): number {
const high = view.getInt32(offset);
const low = view.getUint32(offset + 4);
return high * 0x1_0000_0000 + low;
}
export function getUint64(view: DataView, offset: number): number {
const high = view.getUint32(offset);
const low = view.getUint32(offset + 4);
return high * 0x1_0000_0000 + low;
}
|
a97cc0b8570b3bd5470f38c999cf2a4a5de068b2
|
TypeScript
|
aws/aws-cdk
|
/packages/aws-cdk-lib/core/lib/validation/validation.ts
| 2.796875
| 3
|
import { PolicyValidationPluginReportBeta1 } from './report';
/**
* Represents a validation plugin that will be executed during synthesis
*
* @example
* /// fixture=validation-plugin
* class MyPlugin implements IPolicyValidationPluginBeta1 {
* public readonly name = 'MyPlugin';
*
* public validate(context: IPolicyValidationContextBeta1): PolicyValidationPluginReportBeta1 {
* // First read the templates using context.templatePaths...
*
* // ...then perform the validation, and then compose and return the report.
* // Using hard-coded values here for better clarity:
* return {
* success: false,
* violations: [{
* ruleName: 'CKV_AWS_117',
* description: 'Ensure that AWS Lambda function is configured inside a VPC',
* fix: 'https://docs.bridgecrew.io/docs/ensure-that-aws-lambda-function-is-configured-inside-a-vpc-1',
* violatingResources: [{
* resourceLogicalId: 'MyFunction3BAA72D1',
* templatePath: '/home/johndoe/myapp/cdk.out/MyService.template.json',
* locations: ['Properties/VpcConfig'],
* }],
* }],
* };
* }
* }
*/
export interface IPolicyValidationPluginBeta1 {
/**
* The name of the plugin that will be displayed in the validation
* report
*/
readonly name: string;
/**
* The version of the plugin, following the Semantic Versioning specification (see
* https://semver.org/). This version is used for analytics purposes, to
* measure the usage of different plugins and different versions. The value of
* this property should be kept in sync with the actual version of the
* software package. If the version is not provided or is not a valid semantic
* version, it will be reported as `0.0.0`.
*/
readonly version?: string;
/**
* The list of rule IDs that the plugin will evaluate. Used for analytics
* purposes.
*
* @default - No rule is reported
*/
readonly ruleIds?: string[];
/**
* The method that will be called by the CDK framework to perform
* validations. This is where the plugin will evaluate the CloudFormation
* templates for compliance and report and violations
*/
validate(context: IPolicyValidationContextBeta1): PolicyValidationPluginReportBeta1;
}
/**
* Context available to the validation plugin
*/
export interface IPolicyValidationContextBeta1 {
/**
* The absolute path of all templates to be processed
*/
readonly templatePaths: string[];
}
|
fe22b981db97975fa58fc3d1e8c8e08713ba34b8
|
TypeScript
|
molstar/molstar
|
/src/mol-util/monadic-parser.ts
| 2.859375
| 3
|
/**
* Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
* @author Koya Sakuma <koya.sakuma.work@gmail.com>
**
* Adapted from Parsimmon (https://github.com/jneen/parsimmon)
* Copyright (c) 2011-present J. Adkisson (http://jneen.net).
**/
export class MonadicParser<A> {
constructor(public _: MonadicParser.Action<A>) { }
parse(input: string): MonadicParser.ParseResult<A> {
const result = this.skip(MonadicParser.eof)._(input, 0);
if (result.status) {
return { success: true, value: result.value };
}
return { success: false, index: makeLineColumnIndex(input, result.furthest), expected: result.expected };
};
tryParse(str: string) {
const result = this.parse(str);
if (result.success) {
return result.value;
} else {
const msg = formatError(str, result);
const err = new Error(msg);
throw err;
}
}
or<B>(alternative: MonadicParser<B>): MonadicParser<A | B> {
return MonadicParser.alt(this, alternative);
}
trim<B>(parser: MonadicParser<B> | string): MonadicParser<A> {
return this.wrap(parser, parser);
}
wrap<L, R>(leftParser: MonadicParser<L> | string, rightParser: MonadicParser<R> | string): MonadicParser<A> {
return seqPick(1,
typeof leftParser === 'string' ? MonadicParser.string(leftParser) : leftParser,
this,
typeof rightParser === 'string' ? MonadicParser.string(rightParser) : rightParser);
}
thru<B>(wrapper: (p: MonadicParser<A>) => MonadicParser<B>) {
return wrapper(this);
}
then<B>(next: MonadicParser<B>): MonadicParser<B> {
return seqPick(1, this, next);
}
many() {
return new MonadicParser((input, i) => {
const accum: A[] = [];
let result: MonadicParser.Result<A> | undefined = void 0;
while (true) {
result = mergeReplies(this._(input, i), result);
if (result.status) {
if (i === result.index) {
throw new Error('infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause');
}
i = result.index;
accum.push(result.value);
} else {
return mergeReplies(makeSuccess(i, accum), result);
}
}
});
};
times(min: number, _max?: number): MonadicParser<A[]> {
const max = typeof _max === 'undefined' ? min : _max;
return new MonadicParser((input, i) => {
const accum: A[] = [];
let result: MonadicParser.Result<A> | undefined = void 0;
let prevResult: MonadicParser.Result<A> | undefined = void 0;
let times: number;
for (times = 0; times < min; times++) {
result = this._(input, i);
prevResult = mergeReplies(result, prevResult);
if (result.status) {
i = result.index;
accum.push(result.value);
} else {
return prevResult as any;
}
}
for (; times < max; times += 1) {
result = this._(input, i);
prevResult = mergeReplies(result, prevResult);
if (result.status) {
i = result.index;
accum.push(result.value);
} else {
break;
}
}
return mergeReplies(makeSuccess(i, accum), prevResult);
});
};
result<B>(res: B) {
return this.map(() => res);
};
atMost(n: number) {
return this.times(0, n);
};
atLeast(n: number) {
return MonadicParser.seq(this.times(n), this.many()).map(r => [...r[0], ...r[1]]);
};
map<B>(f: (a: A) => B): MonadicParser<B> {
return new MonadicParser((input, i) => {
const result = this._(input, i);
if (!result.status) {
return result;
}
return mergeReplies(makeSuccess(result.index, f(result.value)), result);
});
}
skip<B>(next: MonadicParser<B>): MonadicParser<A> {
return seqPick(0, this, next);
}
mark(): MonadicParser<MonadicParser.Mark<A>> {
return MonadicParser.seq(MonadicParser.index, this, MonadicParser.index).map(r => ({ start: r[0], value: r[1], end: r[2] }));
}
node(name: string): MonadicParser<MonadicParser.Node<A>> {
return MonadicParser.seq(MonadicParser.index, this, MonadicParser.index).map(r => ({ name, start: r[0], value: r[1], end: r[2] }));
};
sepBy<B>(separator: MonadicParser<B>): MonadicParser<A[]> {
return MonadicParser.sepBy(this, separator);
}
sepBy1<B>(separator: MonadicParser<B>): MonadicParser<A[]> {
return MonadicParser.sepBy1(this, separator);
}
lookahead<B>(x: MonadicParser<B>) {
return this.skip(MonadicParser.lookahead(x));
};
notFollowedBy<B>(x: MonadicParser<B>) {
return this.skip(MonadicParser.notFollowedBy(x));
};
desc(expected: string) {
return new MonadicParser((input, i) => {
const reply = this._(input, i);
if (!reply.status) {
reply.expected = [expected];
}
return reply;
});
};
fallback<B>(result: B) {
return this.or(MonadicParser.succeed(result));
};
ap<B>(other: MonadicParser<(x: A) => B>): MonadicParser<B> {
return MonadicParser.seq(other, this).map(([f, x]) => f(x));
};
chain<B>(f: (a: A) => MonadicParser<B>): MonadicParser<B> {
return new MonadicParser<B>((input, i) => {
const result = this._(input, i);
if (!result.status) {
return result as any;
}
const nextParser = f(result.value);
return mergeReplies(nextParser._(input, result.index), result);
});
};
}
export namespace MonadicParser {
export type Action<T> = (input: string, i: number) => MonadicParser.Result<T>
export type ParseResult<T> = ParseSuccess<T> | ParseFailure;
export interface Index {
/** zero-based character offset */
offset: number;
/** one-based line offset */
line: number;
/** one-based column offset */
column: number;
}
export interface ParseSuccess<T> {
success: true,
value: T
}
export interface ParseFailure {
success: false,
index: Index,
expected: string[],
}
export interface Mark<T> {
start: Index;
end: Index;
value: T;
}
export interface Node<T> extends Mark<T> {
name: string
}
export interface Success<T> {
status: true,
value: T,
index: number
}
export interface Failure {
status: false,
furthest: number,
expected: string[]
}
export type Result<T> = Success<T> | Failure
export function seqMap<A, B>(a: MonadicParser<A>, b: MonadicParser<B>, c: any) {
const args = [].slice.call(arguments);
if (args.length === 0) {
throw new Error('seqMap needs at least one argument');
}
const mapper = args.pop();
assertFunction(mapper);
return seq.apply(null, args).map(function (results: any) {
return mapper.apply(null, results);
});
}
export function createLanguage(parsers: any) {
const language: any = {};
for (const key of Object.keys(parsers)) {
(function (key) {
language[key] = lazy(() => parsers[key](language));
})(key);
}
return language;
}
export function seq<A>(a: MonadicParser<A>): MonadicParser<[A]>
export function seq<A, B>(a: MonadicParser<A>, b: MonadicParser<B>): MonadicParser<[A, B]>
export function seq<A, B, C>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>): MonadicParser<[A, B, C]>
export function seq<A, B, C, D>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>, d: MonadicParser<D>): MonadicParser<[A, B, C, D]>
export function seq<A, B, C, D, E>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>, d: MonadicParser<D>, e: MonadicParser<E>): MonadicParser<[A, B, C, D, E]>
export function seq<T>(...parsers: MonadicParser<T>[]): MonadicParser<T[]>
export function seq(...parsers: MonadicParser<any>[]): MonadicParser<any[]> {
const numParsers = parsers.length;
return new MonadicParser<any[]>((input, index) => {
let result: MonadicParser.Result<any> | undefined;
const accum = new Array(numParsers);
let i = index;
for (let j = 0; j < numParsers; j++) {
result = mergeReplies(parsers[j]._(input, i), result);
if (!result.status) {
return result;
}
accum[j] = result.value;
i = result.index;
}
return mergeReplies(makeSuccess(i, accum), result);
});
}
export function alt<A>(a: MonadicParser<A>): MonadicParser<A>
export function alt<A, B>(a: MonadicParser<A>, b: MonadicParser<B>): MonadicParser<A | B>
export function alt<A, B, C>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>): MonadicParser<A | B | C>
export function alt<A, B, C, D>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>, d: MonadicParser<D>): MonadicParser<A | B | C | D>
export function alt<A, B, C, D, E>(a: MonadicParser<A>, b: MonadicParser<B>, c: MonadicParser<C>, d: MonadicParser<D>, e: MonadicParser<E>): MonadicParser<A | B | C | D | E>
export function alt<T>(...parsers: MonadicParser<T>[]): MonadicParser<T[]>
export function alt(...parsers: MonadicParser<any>[]): MonadicParser<any> {
const numParsers = parsers.length;
if (numParsers === 0) {
return fail('zero alternates');
}
return new MonadicParser((input, i) => {
let result: MonadicParser.Result<any> | undefined;
for (let j = 0; j < parsers.length; j++) {
result = mergeReplies(parsers[j]._(input, i), result);
if (result.status) {
return result;
}
}
return result!;
});
}
export function sepBy<A, B>(parser: MonadicParser<A>, separator: MonadicParser<B>): MonadicParser<A[]> {
return sepBy1(parser, separator).or(succeed([]));
}
export function sepBy1<A, B>(parser: MonadicParser<A>, separator: MonadicParser<B>) {
const pairs = separator.then(parser).many();
return seq(parser, pairs).map(r => [r[0], ...r[1]]);
}
export function string(str: string) {
const expected = `'${str}'`;
if (str.length === 1) {
const code = str.charCodeAt(0);
return new MonadicParser((input, i) => input.charCodeAt(i) === code ? makeSuccess(i + 1, str) : makeFailure(i, expected));
}
return new MonadicParser((input, i) => {
const j = i + str.length;
if (input.slice(i, j) === str) return makeSuccess(j, str);
else return makeFailure(i, expected);
});
}
function flags(re: RegExp) {
const s = '' + re;
return s.slice(s.lastIndexOf('/') + 1);
}
function anchoredRegexp(re: RegExp) {
return RegExp('^(?:' + re.source + ')', flags(re));
}
export function regexp(re: RegExp, group = 0) {
const anchored = anchoredRegexp(re);
const expected = '' + re;
return new MonadicParser((input, i) => {
const match = anchored.exec(input.slice(i));
if (match) {
if (0 <= group && group <= match.length) {
const fullMatch = match[0];
const groupMatch = match[group];
return makeSuccess(i + fullMatch.length, groupMatch);
}
const message = `invalid match group (0 to ${match.length}) in ${expected}`;
return makeFailure(i, message);
}
return makeFailure(i, expected);
});
}
export function succeed<A>(value: A) {
return new MonadicParser((input, i) => makeSuccess(i, value));
}
export function fail(expected: string): MonadicParser<any> {
return new MonadicParser((input, i) => makeFailure(i, expected));
}
export function lookahead<A>(x: MonadicParser<A> | string | RegExp): MonadicParser<null> {
if (isParser(x)) {
return new MonadicParser((input, i) => {
const result = x._(input, i);
if (result.status) {
result.index = i;
result.value = null as any;
}
return result as any;
});
} else if (typeof x === 'string') {
return lookahead(string(x));
} else if (x instanceof RegExp) {
return lookahead(regexp(x));
}
throw new Error('not a string, regexp, or parser: ' + x);
}
export function notFollowedBy<A>(parser: MonadicParser<A>): MonadicParser<null> {
return new MonadicParser((input, i) => {
const result = parser._(input, i);
return result.status
? makeFailure(i, 'not "' + input.slice(i, result.index) + '"')
: makeSuccess(i, null);
});
}
export function test(predicate: (char: string) => boolean): MonadicParser<string> {
return new MonadicParser((input, i) => {
const char = input.charAt(i);
if (i < input.length && predicate(char)) {
return makeSuccess(i + 1, char);
} else {
return makeFailure(i, 'a character ' + predicate);
}
});
}
export function oneOf(str: string) {
return test(ch => str.indexOf(ch) >= 0);
}
export function noneOf(str: string) {
return test(ch => str.indexOf(ch) < 0);
}
export function range(begin: string, end: string) {
return test(ch => begin <= ch && ch <= end).desc(begin + '-' + end);
}
export function takeWhile(predicate: (ch: string) => boolean) {
return new MonadicParser((input, i) => {
let j = i;
while (j < input.length && predicate(input.charAt(j))) {
j++;
}
return makeSuccess(j, input.slice(i, j));
});
}
export function lazy<T>(f: () => MonadicParser<T>) {
const parser = new MonadicParser((input, i) => {
const a = f()._;
parser._ = a;
return a(input, i);
});
return parser;
}
export function empty() {
return fail('empty');
}
export const index = new MonadicParser(function (input, i) {
return makeSuccess(i, makeLineColumnIndex(input, i));
});
export const anyChar = new MonadicParser<string>((input, i) => {
if (i >= input.length) {
return makeFailure(i, 'any character');
}
return makeSuccess(i + 1, input.charAt(i));
});
export const all = new MonadicParser(function (input, i) {
return makeSuccess(input.length, input.slice(i));
});
export const eof = new MonadicParser(function (input, i) {
if (i < input.length) {
return makeFailure(i, 'EOF');
}
return makeSuccess(i, null);
});
export const digit = regexp(/[0-9]/).desc('a digit');
export const digits = regexp(/[0-9]*/).desc('optional digits');
export const letter = regexp(/[a-z]/i).desc('a letter');
export const letters = regexp(/[a-z]*/i).desc('optional letters');
export const optWhitespace = regexp(/\s*/).desc('optional whitespace');
export const whitespace = regexp(/\s+/).desc('whitespace');
export const cr = string('\r');
export const lf = string('\n');
export const crlf = string('\r\n');
export const newline = alt(crlf, lf, cr).desc('newline');
export const end = alt(newline, eof);
export function of<A>(value: A) {
return succeed(value);
}
export function regex(re: RegExp) {
return regexp(re);
}
}
function seqPick(idx: number, ...parsers: MonadicParser<any>[]): MonadicParser<any> {
const numParsers = parsers.length;
return new MonadicParser<any[]>((input, index) => {
let result: MonadicParser.Result<any> | undefined;
let picked: any;
let i = index;
for (let j = 0; j < numParsers; j++) {
result = mergeReplies(parsers[j]._(input, i), result);
if (!result.status) {
return result;
}
if (idx === j) picked = result.value;
i = result.index;
}
return mergeReplies(makeSuccess(i, picked), result);
});
}
function makeSuccess<T>(index: number, value: T): MonadicParser.Success<T> {
return { status: true, index, value };
}
function makeFailure(index: number, expected: string): MonadicParser.Failure {
return { status: false, furthest: index, expected: [expected] };
}
function mergeReplies<A, B>(result: MonadicParser.Result<A>, last?: MonadicParser.Result<B>): MonadicParser.Result<A> {
if (!last || result.status || last.status || result.furthest > last.furthest) {
return result;
}
const expected = result.furthest === last.furthest
? unsafeUnion(result.expected, last.expected)
: last.expected;
return { status: result.status, furthest: last.furthest, expected };
}
function makeLineColumnIndex(input: string, i: number): MonadicParser.Index {
const lines = input.slice(0, i).split('\n');
// Note that unlike the character offset, the line and column offsets are
// 1-based.
const lineWeAreUpTo = lines.length;
const columnWeAreUpTo = lines[lines.length - 1].length + 1;
return { offset: i, line: lineWeAreUpTo, column: columnWeAreUpTo };
}
function formatExpected(expected: string[]) {
if (expected.length === 1) {
return expected[0];
}
return 'one of ' + expected.join(', ');
}
function formatGot(input: string, error: MonadicParser.ParseFailure) {
const index = error.index;
const i = index.offset;
if (i === input.length) {
return ', got the end of the input';
}
const prefix = i > 0 ? '\'...' : '\'';
const suffix = input.length - i > 12 ? '...\'' : '\'';
return ` at line ${index.line} column ${index.column}, got ${prefix}${input.slice(i, i + 12)}${suffix}`;
}
function formatError(input: string, error: MonadicParser.ParseFailure) {
return `expected ${formatExpected(error.expected)}${formatGot(input, error)}`;
}
function unsafeUnion(xs: string[], ys: string[]) {
const xn = xs.length;
const yn = ys.length;
if (xn === 0) return ys;
else if (yn === 0) return xs;
const set = new Set<string>();
const ret: string[] = [];
for (let i = 0; i < xn; i++) {
if (!set.has(xs[i])) {
ret[ret.length] = xs[i];
set.add(xs[i]);
}
}
for (let i = 0; i < yn; i++) {
if (!set.has(ys[i])) {
ret[ret.length] = ys[i];
set.add(ys[i]);
}
}
ret.sort();
return ret;
}
function isParser(obj: any): obj is MonadicParser<any> {
return obj instanceof MonadicParser;
}
function assertFunction(x: any) {
if (typeof x !== 'function') {
throw new Error('not a function: ' + x);
}
}
|
43cdeb1f40f338e573c715eaf5a95478f0738724
|
TypeScript
|
Fxdpt/discord-bot
|
/src/handlers/ProfilePictureHandler.ts
| 2.765625
| 3
|
import { Client, Message, User } from 'discord.js'
import Handler from './Handler'
import parsingHelper from '../helpers/parsingHelper'
class ProfilePictureHandler extends Handler {
validate (client: Client, msg: Message): boolean {
return super.validate(client, msg) && msg.content.startsWith('!pp')
}
async process(client: Client, msg: Message): Promise<boolean> {
const { user, nearestUsers } = parsingHelper.parseProfilePictureMessage(msg)
if (user && user.avatarURL) {
msg.channel.send(user.avatarURL)
} else if (user) {
msg.channel.send('Cet utilisateur n\'a pas d\'avatar ☹')
} else {
const nearestNameUsersStr = nearestUsers.map((nearestUser: User): string => nearestUser.username).join(', ')
msg.channel.send(`Utilisateur non trouvé 🧐 ${nearestUsers.length ? `Veux tu parler de l'une de ces personnes : ${nearestNameUsersStr} ?` : ''}`)
}
return true
}
}
export default ProfilePictureHandler
|
b8d556eb1b2a32643567c1db044a86ba12b1a49f
|
TypeScript
|
atellmer/dark
|
/packages/core/src/ref/types.ts
| 3.078125
| 3
|
export type MutableRef<T = unknown> = {
current: T;
};
export type FunctionRef<T = unknown> = (ref: T) => void;
export type Ref<T = unknown> = MutableRef<T> | FunctionRef<T>;
|
b13952836c54ff3b150e8edc38d1b9e2f33b455a
|
TypeScript
|
SkynetRTN/afterglow-access
|
/src/app/utils/deep-copy.ts
| 3.234375
| 3
|
export class DeepCopy {
static copy(data: any, objMap?: WeakMap<any, any>) {
if (!objMap) {
// Map for handle recursive objects
objMap = new WeakMap();
}
// recursion wrapper
const deeper = value => {
if (value && typeof value === 'object') {
return DeepCopy.copy(value, objMap);
}
return value;
};
// Array value
if (Array.isArray(data)) return data.map(deeper);
// Object value
if (data && typeof data === 'object') {
// Same object seen earlier
if (objMap.has(data)) return objMap.get(data);
// Date object
if (data instanceof Date) {
const result = new Date(data.valueOf());
objMap.set(data, result);
return result;
}
// Use original prototype
const node = Object.create(Object.getPrototypeOf(data));
// Save object to map before recursion
objMap.set(data, node);
for (const [key, value] of Object.entries(data)) {
node[key] = deeper(value);
}
return node;
}
// Scalar value
return data;
}
}
|
fe378bfc7c31f2c82812e88e4ce49ee9c6810220
|
TypeScript
|
Guezin/Cute-Burguer
|
/server/src/modules/users/useCases/CreateUserUseCases.ts
| 2.578125
| 3
|
import { inject, injectable } from 'tsyringe'
import AppError from '@shared/errors/AppError'
import User from '@modules/users/infra/typeorm/entities/User'
import IUserRepository from '@modules/users/repositories/IUserRepository'
import IBcrypt from '@shared/infra/container/providers/Bcrypt/models/IBcryptProvider'
interface IRequest {
name: string
email: string
password: string
provider?: boolean
}
@injectable()
class CreateUserUseCases {
constructor(
@inject('UserRepository')
private userRepository: IUserRepository,
@inject('Bcrypt')
private bcrypt: IBcrypt
) {}
public async execute({
name,
email,
password,
provider = true
}: IRequest): Promise<User> {
const userAlreadyExists = await this.userRepository.findByEmail(email)
if (userAlreadyExists) {
throw new AppError(
'Sorry, there is already a user with this email. Try another!',
401
)
}
const passwordHash = await this.bcrypt.generateHash(password)
const user = await this.userRepository.create({
name,
email,
password: passwordHash,
provider
})
return user
}
}
export default CreateUserUseCases
|
9d17d9ff4dc60c518fe4c48ed8e221b703a30c65
|
TypeScript
|
diss1dent/finder
|
/src/app/reducers/login.reducer.ts
| 2.515625
| 3
|
import { ActionReducer, Action } from '@ngrx/store';
import ACTIONTYPES from "../actions/types";
export const LoginReducer: ActionReducer<any> = (state: {}, action: Action) => {
switch (action.type) {
case ACTIONTYPES.login:
return Object.assign({}, state, {
isLoggedIn: action.payload.isLoggedIn
});
case ACTIONTYPES.shake:
return Object.assign({}, state, {
shakeForm: action.payload.shakeForm
});
default:
return state;
}
};
|
ee7c539b238470371e0a4f70dd27681be9afe201
|
TypeScript
|
obniz/obniz
|
/src/obniz/libs/wscommand/WSCommandWiFi.ts
| 2.515625
| 3
|
/**
* @packageDocumentation
* @ignore
*/
import { JsonBinaryConverter } from './jsonBinaryConverter';
import { WSCommandAbstract } from './WSCommandAbstract';
export class WSCommandWiFi extends WSCommandAbstract {
module = 14;
_CommandScan = 0;
public scan(params: any, index: any) {
this.sendCommand(this._CommandScan, null);
}
public parseFromJson(json: any) {
const module = json.wifi;
if (module === undefined) {
return;
}
const schemaData = [{ uri: '/request/wifi/scan', onValid: this.scan }];
const res = this.validateCommandSchema(schemaData, module, 'wifi');
if (res.valid === 0) {
if (res.invalidButLike.length > 0) {
throw new Error(res.invalidButLike[0].message);
} else {
throw new this.WSCommandNotFoundError(`[network]unknown command`);
}
}
}
public notifyFromBinary(objToSend: any, func: number, payload: Uint8Array) {
switch (func) {
case this._CommandScan: {
enum ScanState {
SCAN_SSID_LEN,
SCAN_SSID,
SCAN_MAC,
SCAN_RSSI,
}
let mode: ScanState = ScanState.SCAN_SSID_LEN;
let tmpIndex = 0;
let ssid = '';
let macAddress = '';
let rssi = 0;
const scanArray = [];
for (let i = 0; i < payload.length; i++) {
switch (mode) {
case ScanState.SCAN_SSID_LEN:
tmpIndex = payload[i];
mode = ScanState.SCAN_SSID;
break;
case ScanState.SCAN_SSID:
ssid += String.fromCharCode(payload[i]);
tmpIndex--;
if (tmpIndex === 0) {
mode = ScanState.SCAN_MAC;
tmpIndex = 0;
}
break;
case ScanState.SCAN_MAC:
macAddress += String.fromCharCode(payload[i]);
tmpIndex++;
if (tmpIndex === 12) {
mode = ScanState.SCAN_RSSI;
}
break;
case ScanState.SCAN_RSSI:
rssi = JsonBinaryConverter.signedNumberFromBinary([payload[i]]);
mode = ScanState.SCAN_SSID_LEN;
scanArray.push({
ssid,
macAddress,
rssi,
});
ssid = '';
macAddress = '';
rssi = 0;
break;
}
}
objToSend.wifi = {
scan: scanArray,
};
break;
}
}
}
}
|
cde93325ddb827a2c90c701d8b40f8570ca8a035
|
TypeScript
|
zhoubudian/lottery
|
/web-src/src/lib/utils.ts
| 2.890625
| 3
|
interface IAssert {
name: string
source: string
}
async function loadImage(url: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
if (url.indexOf("/") === -1) {
img.src = "http://localhost:14422/avatar/" + url;
}
img.onload = function () {
return resolve(img)
};
img.onerror = function (e) {
img.src = "/demo.jpg";
img.onload = function () {
return resolve(img)
};
img.onerror = function (e) {
console.log(e)
reject(new Error(`load ${url} fail`))
}
// console.log(e)
// reject(new Error(`load ${url} fail`))
}
})
}
// 资源加载器
export async function loadAsserts(list: Array<IAssert>, cb?: Function): Promise<Map<string, HTMLImageElement>> {
const asserts = new Map<string, HTMLImageElement>()
for (let i = 0; i < list.length; i++) {
const item = list[i];
if (item.source === "") {
item.source = "/demo.jpg"
}
try {
const itemBg: HTMLImageElement = await loadImage(item.source)
asserts.set(item.name, itemBg)
} catch (e) {
}
cb && cb()
}
console.log("资源加载完成!")
return asserts
}
|
c0c4fad14487ff138b934c75963374b65280af0f
|
TypeScript
|
sabman/toolkit
|
/packages/viz/src/lib/style/deck-styles.ts
| 2.875
| 3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import { hexToRgb } from './helpers/utils';
import { GeometryType } from '../sources/Source';
import { defaultStyles } from './default-styles';
import { colorValidation } from './validators';
import { CartoStylingError, stylingErrorTypes } from '../errors/styling-error';
const POINTS_WIDTH_FACTOR = 2;
function pointStyles(opts: any) {
return {
opacity: getStyleValue('opacity', 'Point', opts),
filled: true,
getFillColor: hexToRgb(getStyleValue('color', 'Point', opts)),
pointRadiusMinPixels: 0,
pointRadiusMaxPixels: Number.MAX_SAFE_INTEGER,
getRadius: getStyleValue('size', 'Point', opts),
pointRadiusScale: 1 / POINTS_WIDTH_FACTOR,
pointRadiusUnits: 'pixels',
stroked: true,
getLineColor: hexToRgb(getStyleValue('strokeColor', 'Point', opts)),
getLineWidth: getStyleValue('strokeWidth', 'Point', opts),
lineWidthUnits: 'pixels'
};
}
function lineStyles(opts: any) {
return {
opacity: getStyleValue('opacity', 'Line', opts),
getLineColor: hexToRgb(getStyleValue('color', 'Line', opts)),
getLineWidth: getStyleValue('size', 'Line', opts),
lineWidthMinPixels: 1,
lineWidthUnits: 'pixels'
};
}
function polygonStyles(opts: any) {
return {
opacity: getStyleValue('opacity', 'Polygon', opts),
getFillColor: hexToRgb(getStyleValue('color', 'Polygon', opts)),
filled: true,
stroked: true,
getLineColor: hexToRgb(getStyleValue('strokeColor', 'Polygon', opts)),
getLineWidth: getStyleValue('strokeWidth', 'Polygon', opts),
lineWidthMinPixels: 0,
lineWidthUnits: 'pixels'
};
}
export function getStyleValue(
variable: string,
geometryType: GeometryType,
options: any
) {
const opts = { ...defaultStyles[geometryType], ...options };
return opts[variable];
}
export interface BasicOptionsStyle {
// Color: hex, rgb or named color value.
// Defaults is '#EE4D5A' points, '#4CC8A3'lines and '#826DBA' polygons
color: string;
// Size of point or line features. 10 for points and 4 for lines.
size: number;
// Opacity value. Default is 1 for points and lines and 0.9 for polygons.
opacity: number;
// Color of the stroke. Default is '#222'.
strokeColor: string;
// Size of the stroke
strokeWidth: number;
}
export function getStyles(
geometryType: GeometryType,
options: Partial<BasicOptionsStyle> = {}
) {
validateBasicParameters(options);
let styles;
switch (geometryType) {
case 'Point':
styles = pointStyles(options);
break;
case 'Line':
styles = lineStyles(options);
break;
case 'Polygon':
styles = polygonStyles(options);
break;
default:
throw new Error('Unsupported geometry type');
}
// Return a copy
return { ...styles };
}
function validateBasicParameters(options: Partial<BasicOptionsStyle>) {
if (options.color && !colorValidation(options.color)) {
throw new CartoStylingError(
`color '${options.color}' is not valid`,
stylingErrorTypes.PROPERTY_MISMATCH
);
}
if (options.size && options.size < 1) {
throw new CartoStylingError(
`size '${options.size}' must be greater or equal to 1`,
stylingErrorTypes.PROPERTY_MISMATCH
);
}
if (options.opacity && (options.opacity > 1 || options.opacity < 0)) {
throw new CartoStylingError(
`opacity '${options.opacity}' must be a number between 0 and 1`,
stylingErrorTypes.PROPERTY_MISMATCH
);
}
if (options.strokeColor && !colorValidation(options.strokeColor)) {
throw new CartoStylingError(
`strokeColor '${options.strokeColor}' is not valid`,
stylingErrorTypes.PROPERTY_MISMATCH
);
}
if (options.strokeWidth && options.strokeWidth < 0) {
throw new CartoStylingError(
`strokeWidth '${options.opacity}' must be greater or equal to 0`,
stylingErrorTypes.PROPERTY_MISMATCH
);
}
}
|
f64a23fc88c536332314ab188e90be3e6b5ca895
|
TypeScript
|
samenc99/cruz-lama-back
|
/src/model/Tickets.ts
| 2.6875
| 3
|
export type TicketDTO = {
name: any,
value : any,
showId : any,
ticketsQuantity : any
}
export type TicketData = {
name : string,
value : number,
show_id : string,
tickets_quantity : number,
id : string
}
export const toTicketsData = (input : TicketDTO, id : string):TicketData=>{
return {
name: input.name,
value: input.value,
show_id: input.showId,
tickets_quantity: input.ticketsQuantity,
id
}
}
export type TicketBuyDTO = {
name: any,
ticketsQuantity : any
}
|
1cc52cfe2af9875734a807e6a8b9b25d635a9130
|
TypeScript
|
Kernell/Hayate-Server-RAGEMP
|
/Globals/Array.ts
| 3.03125
| 3
|
/*********************************************************
*
* Copyright © 2017, Raybit Games.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification,
* is permitted only for authors.
*
*********************************************************/
interface Array< T >
{
remove( value : T ) : Array< T >;
}
Array.prototype.remove = function( value )
{
let idx = this.indexOf( value );
if( idx != -1 )
{
return this.splice( idx, 1 );
}
return null;
}
module.exports = Array;
|
47d25c3e63855ccb5681401d5ddf913ebe341b0d
|
TypeScript
|
soltrinox/k8s-roman-numerals
|
/server/__mocks__/graphql-redis-subscriptions.ts
| 2.640625
| 3
|
export class RedisPubSub {
public static ConstructorSpy = jest.fn();
public static SubscribeSpy = jest.fn();
public static PublishSpy = jest.fn();
public static AsyncIteratorSpy = jest.fn();
public static MockValue = {
arabic: 10,
roman: '10'
};
public constructor(param: any) {
RedisPubSub.ConstructorSpy(param);
}
public async subscribe(channel: string, callback) {
RedisPubSub.SubscribeSpy(channel, callback);
await callback(RedisPubSub.MockValue);
}
public publish(channel: string, value: any) {
RedisPubSub.PublishSpy(channel, value);
}
public asyncIterator(channel: string) {
return channel;
}
}
|
a3254200aeeb83ed808e7729cf3322ffc4b37742
|
TypeScript
|
tkmagesh/Fidelity-Angular-Feb-2018
|
/first-app/src/app/calculator/CalculatorModel.ts
| 3.375
| 3
|
export class CalculatorModel{
n1 : number = 0;
n2 : number = 0;
result : number = 0;
add(){
this.result = this.n1 + this.n2;
}
subtract(){
this.result = this.n1 - this.n2;
}
multiply(){
this.result = this.n1 * this.n2;
}
divide(){
this.result = this.n1 / this.n2;
}
}
export function f1(){
console.log('f1 is invoked');
}
function f2(){
console.log('f2 is invoked');
}
|
84e88626cb11c8788d53b1245a6b498356663bc4
|
TypeScript
|
Sort-It/ServerUtils
|
/functions/src/sendOtptoClient.ts
| 2.640625
| 3
|
const express = require("express");
const router = express.Router();
const otpService = require('../otpService/otpServices.ts');
router.post('/sendOtp/', async (req: any , res: any ) => {
try{
var phoneNo = req.body.phoneNo as string;
if(!(phoneNo.length === 12 && isNumeric(phoneNo))){
return res.status(400).json({"message":"Invalid Phone Number","otp":""});
}
if(!(phoneNo.substring(0,2)==='91')){
return res.status(400).json({"message":"Invalid Country Code","otp":""});
}
var otp = "";
//create an otp of 6 letters
for(var i=0;i<6;i++){
otp = otp + Math.floor(Math.random() * 10);
}
console.log(otp);
var Rawresult = await otpService.sendOtpToClient(otpService.createOtpRequestBody(phoneNo,otp));
var result = Rawresult.data;
//console.log(result);
if(result.Data[0].MessageErrorCode === 0){
// Sucess Scenario
return res.status(200).json({"message":result.Data[0].MessageErrorDescription,"otp":otp});
}
else{
return res.status(500).json({"message":result.Data[0].MessageErrorDescription,"otp":""});
}
}catch (error) { return res.status(501).json({"message":error.message,"otp":""}); }
});
function isNumeric(num: any){
return !isNaN(num);
}
export { router as sendOtp };
|
25c82e4be05c9c21901315bca4b9bbe10847f55a
|
TypeScript
|
nipe0324/learning-js
|
/react-recoil-realworld/src/types.ts
| 2.53125
| 3
|
export interface AuthProps {
email: string;
password: string;
username?: string;
}
export interface UserProps {
email: string;
password: string;
username: string;
bio: string;
image: string;
}
export interface ProfileProps {
username: string;
bio: string;
image: string;
following: boolean;
}
export interface ArticleProps {
slug: string;
title: string;
description: string;
tagsList: string[];
createdAt: string;
favorited: boolean;
favoritesCount: number;
author: ProfileProps;
body?: string;
}
export interface CommentProps {
id: number;
createdAt: string;
body: string;
author: ProfileProps;
}
|
05f3e054c61de68d0c4e40262915d86a81c15072
|
TypeScript
|
marsprince/leetcode-typescript
|
/base/algorithm/sort.ts
| 4.09375
| 4
|
export function lessThan(a, b) {
return a < b;
}
export function equal(a, b) {
return a === b;
}
export function checkArray(originalArray) {
return originalArray.length <= 1 ? originalArray : [...originalArray];
}
// Bubble sort, sometimes referred to as sinking sort,
// is a simple sorting algorithm that repeatedly steps through the list to be sorted,
// compares each pair of adjacent items and swaps them if they are in the wrong order (ascending or descending arrangement).
// The pass through the list is repeated until no swaps are needed,
// which indicates that the list is sorted.Bubble sort,
// sometimes referred to as sinking sort,
// is a simple sorting algorithm that repeatedly steps through the list to be sorted,
// compares each pair of adjacent items and swaps them if they are in the wrong order (ascending or descending arrangement).
// The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
// 冒泡排序
// 每一次沉一个最大的到最后
export function BubbleSort(originalArray) {
// Flag that holds info about whether the swap has occur or not.
let swapped = false;
// Clone original array to prevent its modification.
const array = [...originalArray];
// 最小次数n-1,最大次数是从 n-1 到 1 做和 = (n-1)n/2
// 次数是n-1次,因为每次都会找出一个最大值
for (let i = 1; i < array.length; i += 1) {
swapped = false;
// 每次的比较,因为每次最后一个都是最大值
for (let j = 0; j < array.length - i; j += 1) {
// Swap elements if they are in wrong order.
if (lessThan(array[j + 1], array[j])) {
[array[j], array[j + 1]] = [array[j + 1], array[j]];
// Register the swap.
swapped = true;
}
}
// If there were no swaps then array is already sorted and there is
// no need to proceed.
if (!swapped) {
return array;
}
}
return array;
}
// 选择排序
// 每趟选择一个最小的,记录索引,最后交换
export function SelectionSort(originArray) {
const arr = [...originArray];
for (let i = 0; i < arr.length; i++) {
let min = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) min = j;
}
if (min !== i) {
[arr[i], arr[min]] = [arr[min], arr[i]];
}
}
return arr;
}
// 插入排序
// 相当于向前冒泡
export function InsertionSort(originalArray) {
const array = [...originalArray];
// Go through all array elements...
for (let i = 0; i < array.length; i += 1) {
let currentIndex = i;
// Go and check if previous elements and greater then current one.
// If this is the case then swap that elements.
for (let j = i - 1; j >= 0; j--) {
if (lessThan(array[currentIndex], array[j])) {
[array[currentIndex], array[j]] = [array[j], array[currentIndex]];
currentIndex = j;
} else {
break;
}
}
}
return array;
}
console.log(InsertionSort([4, 2, 1, 5, 3]));
|
d7395f4d2af46f33e284ff7eecfe512781d03fec
|
TypeScript
|
Motakjuq/hntest
|
/backend/src/services/news/tasks.ts
| 2.6875
| 3
|
import request from "request";
import { Story } from "./models";
interface IStory {
story_id: number;
objectID: string;
title: string;
story_title: string;
author: string;
story_url: string;
url: string;
created_at_i: number;
created_at: Date;
}
const fetchData = (onComplete?: any, onError?: any) => {
const url = "https://hn.algolia.com/api/v1/search_by_date?query=nodejs";
let count = 0;
let hits = 0;
let req = request
.get(url, { json: true }, (error, response, body) => {
hits = body.hits.length;
body.hits.forEach((e: IStory) => {
const {
story_id,
objectID,
title,
story_title,
author,
story_url,
url,
created_at_i,
created_at
} = e;
const story = {
story_id,
objectID,
title,
story_title,
author,
story_url,
url,
created_at,
created_at_i: created_at_i * 1000
};
let result = Story.updateOne(
{ objectID: objectID },
story,
{ upsert: true },
(err, raw) => {}
);
});
})
.on("complete", () => {
if (onComplete) {
onComplete();
}
})
.on("error", (err: Error) => {
console.error("Sync fails");
if (onError) {
onError();
}
});
return req;
};
export default fetchData;
|
5e43fa71da9b08ffff77f1e2f9f8551133683f66
|
TypeScript
|
Amirus/RxJS-1
|
/src/operators/observeOn.ts
| 3.078125
| 3
|
import Operator from '../Operator';
import Observer from '../Observer';
import Scheduler from '../Scheduler';
import Observable from '../Observable';
import Subscriber from '../Subscriber';
export default function observeOn<T>(scheduler: Scheduler, delay: number = 0): Observable<T> {
return this.lift(new ObserveOnOperator(scheduler, delay));
}
export class ObserveOnOperator<T, R> implements Operator<T, R> {
delay: number;
scheduler: Scheduler;
constructor(scheduler: Scheduler, delay: number = 0) {
this.delay = delay;
this.scheduler = scheduler;
}
call(observer: Observer<T>): Observer<T> {
return new ObserveOnSubscriber(observer, this.scheduler, this.delay);
}
}
export class ObserveOnSubscriber<T> extends Subscriber<T> {
static dispatch({ type, value, destination }) {
destination[type](value);
}
delay: number;
scheduler: Scheduler;
constructor(destination: Observer<T>, scheduler: Scheduler, delay: number = 0) {
super(destination);
this.delay = delay;
this.scheduler = scheduler;
}
_next(x) {
this.add(this.scheduler.schedule(this.delay,
new ScheduledNotification("next", x, this.destination),
ObserveOnSubscriber.dispatch)
);
}
_error(e) {
this.add(this.scheduler.schedule(this.delay,
new ScheduledNotification("error", e, this.destination),
ObserveOnSubscriber.dispatch));
}
_complete() {
this.add(this.scheduler.schedule(this.delay,
new ScheduledNotification("complete", void 0, this.destination),
ObserveOnSubscriber.dispatch));
}
}
class ScheduledNotification {
type: string;
value: any;
destination: Observer<any>;
constructor(type: string, value: any, destination: Observer<any>) {
this.type = type;
this.value = value;
this.destination = destination;
}
}
|
de61d1a76b0d71ab665fa7787b0192f7f3215c0a
|
TypeScript
|
datagrok-ai/public
|
/packages/Chem/src/utils/chem-common.ts
| 2.71875
| 3
|
import BitArray from '@datagrok-libraries/utils/src/bit-array';
export const defaultMorganFpRadius = 2;
export const defaultMorganFpLength = 2048;
const lockPromiseForKey: any = {};
const unlockFunctionForKey: any = {};
export enum Fingerprint {
Morgan = 'Morgan',
RDKit = 'RDKit',
Pattern = 'Pattern'
}
// By https://github.com/mistval/locko
export async function criticalSectionBegin(key: string): Promise<any> {
if (!lockPromiseForKey[key])
lockPromiseForKey[key] = Promise.resolve();
const takeLockPromise = lockPromiseForKey[key];
lockPromiseForKey[key] = takeLockPromise.then(() => new Promise((fulfill) => {
unlockFunctionForKey[key] = fulfill;
}));
return takeLockPromise;
}
export function criticalSectionEnd(key: string): void {
if (unlockFunctionForKey[key]) {
unlockFunctionForKey[key]();
delete unlockFunctionForKey[key];
}
}
const CHEM_TOKEN = 'CHEM_TOKEN';
export async function chemBeginCriticalSection(token = CHEM_TOKEN): Promise<void> {
let warned = false;
if (unlockFunctionForKey[token]) {
console.warn('Chem | Is already in a critical section, waiting...');
warned = true;
}
await criticalSectionBegin(token);
if (warned)
console.warn('Chem | Left the critical section');
}
export function chemEndCriticalSection(token = CHEM_TOKEN): void {
criticalSectionEnd(token);
}
export function rdKitFingerprintToBitArray(fp: Uint8Array): BitArray | null {
return fp ? BitArray.fromBytes(fp) : fp;
}
export function isMolBlock(s: string) {
return s.includes('M END');
}
|
8e568e68c3add30fa238cfe79d4c03b1ad436037
|
TypeScript
|
TheColorRed/query-builder
|
/src/DB.ts
| 2.5625
| 3
|
import * as mysql from 'mysql'
import { packetCallback, Query, Connection as MysqlConnection } from "mysql";
import { Builder } from './Builder';
import { QueryBuilder } from './QueryBuilder';
export interface DatabaseConnection {
default?: boolean
safeAlter?: boolean
dumpQueries?: boolean
saveNonDirtyRows?: boolean
connection: {
host: string
user: string
password: string
database: string
}
}
export type DatabaseConnections<T> = {
[name: string]: T
}
export interface InsertInfo {
fieldCount: number
affectedRows: number
insertId: number
serverStatus: number
warningCount: number
message: string,
protocol41: boolean
changedRows: number
}
export class DB {
private static _connections: Connection[] = []
public static get connections(): Connection[] { return this._connections }
public static getConnection(name: string) {
let conn = this._connections.find(c => c.name == name)
if (!conn) throw new Error(`The connection "${name}" does not exist`)
return conn
}
public static getDefaultConnection() {
let conn = this._connections.find(c => c.config.default === true)
if (!conn && this._connections[0]) conn = this._connections[0]
if (!conn) throw new Error('There are no connections setup')
return conn
}
public static init(config: DatabaseConnections<DatabaseConnection>, throwError: boolean = true) {
for (let name in config) {
let conn = mysql.createConnection(config[name].connection)
conn.connect((err) => {
if (err && !throwError) console.error(new Error().stack)
if (err && throwError) throw err
})
this._connections.push(new Connection(name, conn, config[name]))
}
return this
}
public static connect(connection?: string, throwError: boolean = true) {
if (!connection) {
for (let conn of this._connections) {
if (!conn.conn) {
let c = mysql.createConnection(conn.config.connection)
c.connect((err) => {
if (err && !throwError) console.error(new Error().stack)
if (err && throwError) throw err
})
}
}
} else {
let conn = this._connections.find(c => c.name == connection)
if (conn) {
let c = mysql.createConnection(conn.config.connection)
c.connect((err) => {
if (err && !throwError) console.error(new Error().stack)
if (err && throwError) throw err
})
}
}
}
public static disconnect(connection?: string) {
if (!connection) {
for (let conn of this._connections) {
conn.conn.destroy()
}
} else {
let conn = this._connections.find(c => c.name == connection)
if (conn) conn.conn.destroy()
}
}
public static connection(name?: string) {
let conn = name ? this._connections.find(c => c.name == name) : this._connections.find(c => c.config.default === true)
if (!conn) conn = this._connections[0]
if (!conn) { throw new Error('No connection avalible') }
return new Builder(conn)
}
public static table(tableName: string) {
return this.connection().table(tableName)
}
public static async select<T>(query: string, params?: any[]): Promise<T[] | null>
public static async select<T>(conn: string, query: string, params: any[]): Promise<T[] | null>
public static async select<T>(...args: any[]): Promise<T[] | null> {
let conn: Connection | null = null, query: string = '', params: any[] = []
if (args.length == 3) {
conn = (<Connection>this.getConnection(args[0]))
query = args[1]
params = args[2]
} else if (args.length == 2) {
let c = this._connections.find(c => c.config.default === true)
conn = c ? c : null
query = args[0]
params = args[1]
} else if (args.length == 1) {
query = args[0]
} else {
throw new Error('Invalid number of aguments for select')
}
if (!conn) return null
return await <Promise<T[] | null>>QueryBuilder.query(conn, query, params)
}
public static async insert(query: string, params?: any[]): Promise<packetCallback | null>
public static async insert(conn: string, query: string, params?: any[]): Promise<packetCallback | null>
public static async insert(...args: any[]): Promise<packetCallback | null> {
let conn: Connection | null = null, query: string = '', params: any[] = []
if (args.length == 3) {
conn = (<Connection>this.getConnection(args[0]))
query = args[1]
params = args[2]
} else if (args.length == 2) {
let c = this._connections.find(c => c.config.default === true)
conn = c ? c : null
query = args[0]
params = args[1]
} else if (args.length == 1) {
query = args[0]
} else {
throw new Error('Invalid number of aguments for insert')
}
if (conn) {
let insert = await QueryBuilder.query<Query>(conn, query, params)
if (insert) {
return insert.OkPacket ? insert.OkPacket : insert.ErrorPacket
}
}
return null
}
public static async delete(query: string, params?: any[]): Promise<packetCallback | null>
public static async delete(conn: string, query: string, params: any[]): Promise<packetCallback | null>
public static async delete(...args: any[]): Promise<packetCallback | null> {
let conn: Connection | null = null, query: string = '', params: any[] = []
if (args.length == 3) {
conn = (<Connection>this.getConnection(args[0]))
query = args[1]
params = args[2]
} else if (args.length == 2) {
let c = this._connections.find(c => c.config.default === true)
conn = c ? c : null
query = args[0]
params = args[1]
} else if (args.length == 1) {
query = args[0]
} else {
throw new Error('Invalid number of aguments for delete')
}
if (!conn) return null
let del = await QueryBuilder.query<Query>(conn, query, params)
if (del) {
return del.OkPacket ? del.OkPacket : del.ErrorPacket
}
return null
}
}
export class Connection {
public name: string = ''
public conn: MysqlConnection
public config: DatabaseConnection
public constructor(name: string, conn: MysqlConnection, config: DatabaseConnection) {
this.name = name
this.conn = conn
this.config = config
}
}
|
6a1a77e6cee7d9d7020aa6989a9bbd86e95d2150
|
TypeScript
|
ForbesLindesay/graphql-schema
|
/packages/document/src/types/Location.ts
| 2.765625
| 3
|
import type LocationSource from './LocationSource';
interface LocationRange {
readonly kind: 'LocationRange';
readonly source: LocationSource;
/**
* The character offset at which this Node begins.
*/
readonly start: number;
/**
* The character offset at which this Node ends.
*/
readonly end?: number;
}
type Location = LocationRange | LocationSource;
export default Location;
|
ffa6a1b72f7a7f9afc1942b88cf10180b0424e28
|
TypeScript
|
Sapioweb/authentication
|
/lib/common/validatePassword.d.ts
| 3.03125
| 3
|
/**
* The password string will start this way.
* (?=.*[a-z]) The string must contain at least 1 lowercase alphabetical character.
* (?=.*[A-Z]) The string must contain at least 1 uppercase alphabetical character.
* (?=.*[0-9]) The string must contain at least 1 numeric character.
* (?=.*[!@#\$%\^&\*]) The string must contain at least one special character, but we are escaping reserved RegEx characters to avoid conflict.
* (?=.{8,}) The string must be eight characters or longer.
*
* @param password
*/
export declare const validatePassword: (password: string) => boolean;
|
01fba5fa6e30c0d612fa44557cb5061688a28cac
|
TypeScript
|
jmtalarn/rpi_index
|
/src/utils/file-utils.ts
| 2.625
| 3
|
export const isVideoFile = (filename: string | undefined) => {
if (!filename) {
return false;
}
const extensions = ['MP4', 'AVI', 'MOV', 'FLV', 'WMV'];
var lastIndex = filename.lastIndexOf('.');
const extension = filename.substr(lastIndex + 1).toUpperCase();
return extensions.indexOf(extension) > -1;
};
export const isPdfFile = (filename: string | undefined) => {
if (!filename) {
return false;
}
var lastIndex = filename.lastIndexOf('.');
const extension = filename.substr(lastIndex + 1).toUpperCase();
return extension === 'PDF';
};
|
d88f002ac56529428bcd9a8ed20d9a97886b6680
|
TypeScript
|
adafruit/pyright
|
/server/src/parser/characters.ts
| 2.53125
| 3
|
/*
* characters.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Based on code from vscode-python repository:
* https://github.com/Microsoft/vscode-python
*
* Utility routines used by tokenizer.
*/
import * as unicode from './unicode';
export const enum Char {
// C0 control codes
Null = 0,
StartOfHeading = 1,
StartOfText = 2,
EndOfText = 3,
EndOfTransmission = 4,
Enquiry = 5,
Acknowledge = 6,
Bell = 7,
Backspace = 8,
Tab = 9,
LineFeed = 0xa,
VerticalTab = 0xb,
FormFeed = 0xc,
CarriageReturn = 0xd,
ShiftOut = 0xe,
ShirtIn = 0xf,
DataLineEscape = 0x10,
DeviceControl1 = 0x11,
DeviceControl2 = 0x12,
DeviceControl3 = 0x13,
DeviceControl4 = 0x14,
NegativeAcknowledgement = 0x15,
SynchronousIdle = 0x16,
EndOfTransmitBlock = 0x17,
Cancel = 0x18,
EndOfMedium = 0x19,
Substitute = 0x1a,
Escape = 0x1b,
FileSeparator = 0x1c,
GroupSeparator = 0x1d,
RecordSeparator = 0x1e,
UnitSeparator = 0x1f,
// Printable characters
Space = 0x20,
ExclamationMark = 0x21,
DoubleQuote = 0x22,
Hash = 0x23,
$ = 0x24,
Percent = 0x25,
Ampersand = 0x26,
SingleQuote = 0x27,
OpenParenthesis = 0x28,
CloseParenthesis = 0x29,
Asterisk = 0x2a,
Plus = 0x2b,
Comma = 0x2c,
Hyphen = 0x2d,
Period = 0x2e,
Slash = 0x2f,
_0 = 0x30,
_1 = 0x31,
_2 = 0x32,
_3 = 0x33,
_4 = 0x34,
_5 = 0x35,
_6 = 0x36,
_7 = 0x37,
_8 = 0x38,
_9 = 0x39,
Colon = 0x3a,
Semicolon = 0x3b,
Less = 0x3c,
Equal = 0x3d,
Greater = 0x3e,
QuestionMark = 0x3f,
At = 0X40,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4a,
K = 0x4b,
L = 0x4c,
M = 0x4d,
N = 0x4e,
O = 0x4f,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5a,
OpenBracket = 0x5b,
Backslash = 0x5c,
CloseBracket = 0x5d,
Caret = 0x5e,
Underscore = 0x5f,
Backtick = 0x60,
a = 0x61,
b = 0x62,
c = 0x63,
d = 0x64,
e = 0x65,
f = 0x66,
g = 0x67,
h = 0x68,
i = 0x69,
j = 0x6a,
k = 0x6b,
l = 0x6c,
m = 0x6d,
n = 0x6e,
o = 0x6f,
p = 0x70,
q = 0x71,
r = 0x72,
s = 0x73,
t = 0x74,
u = 0x75,
v = 0x76,
w = 0x77,
x = 0x78,
y = 0x79,
z = 0x7a,
OpenBrace = 0x7b,
Bar = 0x7c,
CloseBrace = 0x7d,
Tilde = 0x7e,
Delete = 0x7f,
// Other space characters
NonBreakingSpace = 0xa0,
EnQuad = 0x2000,
EmQuad = 0x2001,
EnSpace = 0x2002,
EmSpace = 0x2003,
ThreePerEmSpace = 0x2004,
FourPerEmSpace = 0x2005,
SixPerEmSpace = 0x2006,
FigureSpace = 0x2007,
PunctuationSpace = 0x2008,
ThinSpace = 0x2009,
HairSpace = 0x200a,
ZeroWidthSpace = 0x200b,
NarrowNoBreakSpace = 0x202f,
IdeographicSpace = 0x3000,
MathematicalSpace = 0x205f,
Ogham = 0x1680
};
enum CharCategory {
// Character cannot appear in identifier
NotIdentifierChar = 0,
// Character can appear at beginning or within identifier
StartIdentifierChar = 1,
// Character can appear only within identifier, not at beginning
IdentifierChar = 2
}
// Table of first 256 character codes (the most common cases).
const _identifierCharFastTableSize = 256;
const _identifierCharFastTable: CharCategory[] = new Array(_identifierCharFastTableSize);
// Map of remaining characters that can appear within identifier.
const _identifierCharMap: { [code: number]: CharCategory } = {};
// We do lazy initialization of this map because it's rarely used.
let _identifierCharMapInitialized = false;
export function isIdentifierStartChar(ch: number) {
if (ch < _identifierCharFastTableSize) {
return _identifierCharFastTable[ch] === CharCategory.StartIdentifierChar;
}
// Lazy initialize the char map. We'll rarely get here.
if (!_identifierCharMapInitialized) {
_buildIdentifierLookupTable(false);
_identifierCharMapInitialized = true;
}
return _identifierCharMap[ch] === CharCategory.StartIdentifierChar;
}
export function isIdentifierChar(ch: number) {
if (ch < _identifierCharFastTableSize) {
return _identifierCharFastTable[ch] === CharCategory.StartIdentifierChar ||
_identifierCharFastTable[ch] === CharCategory.IdentifierChar;
}
return _identifierCharMap[ch] === CharCategory.StartIdentifierChar ||
_identifierCharMap[ch] === CharCategory.IdentifierChar;
}
export function isWhiteSpace(ch: number): boolean {
return ch === Char.Space || ch === Char.Tab || ch === Char.FormFeed;
}
export function isLineBreak(ch: number): boolean {
return ch === Char.CarriageReturn || ch === Char.LineFeed;
}
export function isNumber(ch: number): boolean {
return ch >= Char._0 && ch <= Char._9 || ch === Char.Underscore;
}
export function isDecimal(ch: number): boolean {
return ch >= Char._0 && ch <= Char._9 || ch === Char.Underscore;
}
export function isHex(ch: number): boolean {
return isDecimal(ch) || (ch >= Char.a && ch <= Char.f) || (ch >= Char.A && ch <= Char.F) || ch === Char.Underscore;
}
export function isOctal(ch: number): boolean {
return ch >= Char._0 && ch <= Char._7 || ch === Char.Underscore;
}
export function isBinary(ch: number): boolean {
return ch === Char._0 || ch === Char._1 || ch === Char.Underscore;
}
// Underscore is explicitly allowed to start an identifier.
// Characters with the Other_ID_Start property.
const _specialStartIdentifierChars: unicode.UnicodeRangeTable = [Char.Underscore,
0x1885, 0x1886, 0x2118, 0x212E, 0x309B, 0x309C];
const _startIdentifierCharRanges = [_specialStartIdentifierChars, unicode.unicodeLu,
unicode.unicodeLl, unicode.unicodeLt, unicode.unicodeLo, unicode.unicodeLm, unicode.unicodeNl];
// Characters with the Other_ID_Start property.
const _specialIdentifierChars: unicode.UnicodeRangeTable = [0x00B7, 0x0387, 0x1369,
0x136A, 0x136B, 0x136C, 0x136D, 0x136E, 0x136F, 0x1370, 0x1371, 0x19DA];
const _identifierCharRanges = [_specialIdentifierChars, unicode.unicodeMn, unicode.unicodeMc,
unicode.unicodeNd, unicode.unicodePc];
function _buildIdentifierLookupTableFromUnicodeRangeTable(table: unicode.UnicodeRangeTable,
category: CharCategory, fastTableOnly: boolean) {
for (let entryIndex = 0; entryIndex < table.length; entryIndex++) {
const entry = table[entryIndex];
let rangeStart: number;
let rangeEnd: number;
if (Array.isArray(entry)) {
rangeStart = entry[0];
rangeEnd = entry[1];
} else {
rangeStart = rangeEnd = entry;
}
for (let i = rangeStart; i <= rangeEnd; i++) {
if (i < _identifierCharFastTableSize) {
_identifierCharFastTable[i] = category;
} else {
_identifierCharMap[i] = category;
}
}
if (fastTableOnly && rangeStart >= _identifierCharFastTableSize) {
break;
}
}
}
// Build a lookup table for to speed up tokenization of identifiers.
function _buildIdentifierLookupTable(fastTableOnly: boolean) {
_identifierCharFastTable.fill(CharCategory.NotIdentifierChar);
_identifierCharRanges.forEach(table => {
_buildIdentifierLookupTableFromUnicodeRangeTable(
table, CharCategory.IdentifierChar, fastTableOnly);
});
_startIdentifierCharRanges.forEach(table => {
_buildIdentifierLookupTableFromUnicodeRangeTable(
table, CharCategory.StartIdentifierChar, fastTableOnly);
});
}
_buildIdentifierLookupTable(true);
|
9d1996a0e1b5cd7bfb610a05b16aeca774adcb00
|
TypeScript
|
Harshul-Vijay/calculatorV2
|
/src/global/test/tokenizer.ts
| 3.453125
| 3
|
interface TokenInterface {
type: string;
value: string;
}
class Token implements TokenInterface {
type: string;
value: string;
constructor(type: string, value: string) {
this.type = type;
this.value = value;
}
}
export class Tokenizer {
private letterBuffer: Array<any> = [];
private numberBuffer: Array<any> = [];
private tokens: Array<any> = [];
private functions: Array<any> = [{
name: 'sin'
}];
/* private tokens: Array<Token> = []; */
// private expression: string;
constructor(expression: string) {
// Remove all whitespaces
expression = expression.replace(/\s+/ig, '');
expression.split('').map((value) => {
if (this.type(value) === 'Number') {
this.numberBuffer.push(new Token('Number', value));
this.joinLB();
} else if (this.type(value) === 'Literal') {
this.letterBuffer.push(new Token('Literal', value));
this.joinNB();
} else if (this.type(value) === 'LeftParenthesis') {
if (this.functions.find((fn) => fn.name ===
this.joinLB({ returnValue: true }).value)) {
this.tokens.push(new Token('Operator', '*'));
this.joinLB();
} else {
this.joinNB();
this.tokens.push(new Token('Operator', '*'));
}
this.tokens.push(new Token(this.type(value), value));
} else if (this.type(value) === 'RightParenthesis') {
this.joinNB();
this.joinLB({ pushAs: 'lit' });
this.tokens.push(new Token(this.type(value), value));
} else if (this.type(value) === 'Operator') {
this.joinLB({ pushAs: 'lit' });
this.joinNB();
this.tokens.push(new Token(this.type(value), value));
} else {
this.joinLB();
this.joinNB();
this.tokens.push(new Token(this.type(value), value));
}
});
this.joinNB();
this.joinLB({ pushAs: 'lit' });
//console.log(this.tokens);
this.tokens.map((token, index) => {
console.log(index + "=> " + token.type + "(" + token.value + ")");
});
// console.log(tokens);
// this.expression = expression;
/* const tokens: Array<Token|string> = [];
let prev = undefined;
let buffer = []; */
/* expression.split('').map((value, index) => {
// tokens.push(new Token('Type', value));
if (prev !== undefined) {
if (this.type(value) === this.type(prev.v)) {
if (!buffer.find(prev => prev.i == index - 1)) {
buffer.push(prev);
}
buffer.push({ v: value, i: index });
} else {
if (buffer.length) {
let fn = buffer.reduce((previous, current) => {
return { v: previous.v + current.v };
});
fn = fn.v;
tokens.push(fn);
} else {
tokens.push(value);
}
buffer = [];
}
}
prev = { v: value, i: index };
});
console.log(tokens.join(``)); */
// this.tokens = expression.split('');
}
private joinLB(config: { pushAs?: string, returnValue?: boolean } = {
pushAs: 'fn'
}) {
/* if (config.pushAs === undefined) {
config.pushAs = 'fn';
} */
if (this.letterBuffer.length) {
let lc = this.letterBuffer.reduce((prev, curr) => {
return { value: prev.value + curr.value };
});
if (config.returnValue) {
return lc;
} else {
let type = 'Literal';
if (config.pushAs === 'fn') {
type = 'Function';
this.tokens.pop();
this.tokens.push(new Token(type, lc.value));
this.tokens.push(new Token('LeftParenthesis', '('));
} else if (config.pushAs === 'lit') {
this.letterBuffer.map((letter) => {
this.tokens.push(new Token('Operator', '*'));
this.tokens.push(new Token(type, letter.value));
});
}
}
this.letterBuffer = [];
}
}
private joinNB(returnValue: boolean = false) {
if (this.numberBuffer.length) {
let nc = this.numberBuffer.reduce((prev, curr) => {
return { value: prev.value + curr.value };
});
if (returnValue) {
return nc;
} else {
this.tokens.push(new Token('Number', nc.value));
this.numberBuffer = [];
}
}
}
private type(value: any) {
if (value.match(/[A-z]/gi)) {
return 'Literal';
} else if (value.match(/[0-9.]/gi)) {
return 'Number';
} else if (value.match(/[+-/*=]/gi)) {
return 'Operator';
} else if (value.match(/[(]/gi)) {
return 'LeftParenthesis';
} else if (value.match(/[)]/gi)) {
return 'RightParenthesis';
}
}
/* private nextChar(index: number) {
let char = `x00`, i = index;
if (i < this.expression.length) {
char = this.expression.charAt(i);
index++;
}
return char;
}
private peek(index: number) {
let i = index;
if (i < this.expression.length) {
return this.expression.charAt(i);
} else {
return `x00`;
}
}
private isIdentifierStart(char) {
return (char === '_') || char.match(/[a-zA-Z]/gi);
}
private isIdentifierPart(char) {
return this.isIdentifierStart(char) || char.match(/[0-9]/gi);
}
scanOperators() {
if (this.expression.match(/[+-/*()=]/gi)) {
const token: Token = {
type: 'Operator',
value: this.nextChar(0)
};
return token;
}
return undefined;
}
scanIdentifiers() {
let char, identifier;
char = this.nextChar(0);
if (!this.isIdentifierStart(char)) {
return undefined;
}
identifier = this.nextChar(0);
while (true) {
char = this.peek(0);
if (!this.isIdentifierPart(char)) {
break;
}
identifier += this.nextChar(0);
}
const token: Token = {
type: 'Identifier',
value: identifier
};
return token;
} */
}
|
f6d77cb0efbfa0193ecb9aeb51e9693011c33f41
|
TypeScript
|
waltonseymour/vermeer
|
/src/interaction.ts
| 3.03125
| 3
|
import { Datum, Chart } from "./chart";
interface InteractionOptions {
plot: Chart;
handler: (point: Datum) => void;
}
export class ClickInteraction {
plot: Chart;
handler: (d: Datum) => void;
constructor(options: InteractionOptions) {
this.handler = options.handler;
this.plot = options.plot;
this.plot.canvasElement.addEventListener("click", this.handle);
}
handle = (e: MouseEvent) => {
const x = this.plot.xAxis.reverseScale(e.x);
const y = this.plot.yAxis.reverseScale(e.y);
this.handler({ x, y });
};
destroy() {
this.plot.canvasElement.removeEventListener("click", this.handle);
}
}
|
24d9dae0b9e11a0fbebb33a3ae155a04522df9e3
|
TypeScript
|
MadManLabs/arrivals-osx
|
/src/lib/dispatcher.ts
| 2.609375
| 3
|
import { AbstractBatch } from 'abstract-leveldown';
import glob from 'glob';
import LevelJobs from 'level-jobs';
import { LevelUp } from 'levelup';
import path from 'path';
import { promisify } from 'util';
import logger from 'winston';
import { FileJobStatus, FileJobType } from './enums';
import { Tag } from './tag';
import { FileJobPayload, FilePayload } from './typings';
import { prettyPrint } from './utils';
const globPromise = promisify(glob);
export interface DispatcherOptions {
readonly queue: LevelJobs;
readonly files: LevelUp;
readonly watchPaths: string[];
}
export class Dispatcher {
private files: LevelUp;
private queue: LevelJobs;
private options: DispatcherOptions;
constructor(options: DispatcherOptions) {
this.queue = options.queue;
this.files = options.files;
this.options = options;
}
public async init(): Promise<void> {
try {
logger.info('Starting dispatcher ...');
// Build existing file DB here ...
const existingPaths = this.options.watchPaths.map(watchPath =>
this.buildExistingFilesDb(watchPath)
);
const existingPathsAdded = await Promise.all(existingPaths);
const existingPathsCount = existingPathsAdded.reduce(
(p: number, c: number) => p + c,
0
);
logger.info('%s existing paths added', existingPathsCount);
logger.info('Dispatcher started!');
} catch (err) {
logger.error(err);
throw err;
}
}
public async buildExistingFilesDb(watchPath: string): Promise<number> {
try {
const cwd = watchPath;
const files = await globPromise(`**/*`, {
cwd
});
const filePayload: FilePayload = {
jobStatus: FileJobStatus.Existing,
jobType: FileJobType.Unknown
};
const existingFiles = files.map(
(filepath: string): AbstractBatch => ({
key: path.resolve(cwd, filepath),
type: 'put',
value: filePayload
})
);
await this.files.batch(existingFiles);
return existingFiles.length;
} catch (error) {
throw error;
}
}
public async isNewFile(filepath: string): Promise<boolean> {
try {
await this.files.get(filepath);
return false;
} catch (err) {
switch (err.notFound) {
case true:
return true;
default:
throw err;
}
}
}
public async enqueueFile(
filepath: string,
filetype: FileJobType
): Promise<boolean> {
try {
const tag = new Tag(filepath);
const jobType = filetype;
const jobStatus = FileJobStatus.Pending;
const filePayload: FilePayload = {
jobStatus,
jobType
};
await this.files.put(filepath, filePayload);
const fileJobPayload: FileJobPayload = {
filepath,
jobType
};
const jobId = await this.queue.pushPromise(fileJobPayload);
logger.debug('File enqueued with jobId: %s', jobId);
await tag.addTag('Yellow');
return true;
} catch (err) {
logger.error('Error in enqueue\n%s', prettyPrint(err));
return false;
}
}
}
export function createDispatcher(options: DispatcherOptions): Dispatcher {
return new Dispatcher(options);
}
|
ed45e3573aafb0845edfb3215b7e52cf0f5b413d
|
TypeScript
|
jdunkerley/AlteryxScript
|
/src/services/Operators/Assignment.ts
| 2.828125
| 3
|
import { BaseNode, AssignmentNode } from "../Nodes"
import { Evaluator } from "../evaluator"
export default (node:BaseNode, evaluator: Evaluator) => {
const assignmentNode: AssignmentNode | null = node as AssignmentNode
if (!assignmentNode) {
throw new SyntaxError("Assignment not understood")
}
if (assignmentNode.Children.length > 1) {
throw new SyntaxError("Assignment not understood (multi term)")
}
if (assignmentNode.Children.length === 0) {
throw new SyntaxError("Assignment not understood (no children)")
}
const childValue = evaluator.evaluateStatement(assignmentNode.Children[0])
evaluator.variables[assignmentNode.Identifier] = childValue
return childValue
}
|
970c7e1e2f0eb3fdea00c6e51fbb596e1d38d766
|
TypeScript
|
avadev/AvaTax-REST-V2-JS-SDK
|
/lib/models/TaxRateModel.ts
| 2.625
| 3
|
/*
* AvaTax Software Development Kit for JavaScript
*
* (c) 2004-2022 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Jonathan Wenger <jonathan.wenger@avalara.com>
* @author Sachin Baijal <sachin.baijal@avalara.com>
* @copyright 2004-2018 Avalara, Inc.
* @license https://www.apache.org/licenses/LICENSE-2.0
* @link https://github.com/avadev/AvaTax-REST-V2-JS-SDK
*/
import * as Enums from '../enums/index';
import { RateModel } from "./RateModel";
import { JsonObject, JsonProperty } from "json2typescript";
import { DateConverter } from "../utils/dateConverter";
/**
* Contains information about the general tangible personal property sales tax rates for this jurisdiction.
This rate is calculated by making assumptions about the tax calculation process. It does not account for:
* Sourcing rules, such as origin-and-destination based transactions.
* Product taxability rules, such as different tax rates for different product types.
* Nexus declarations, where some customers are not obligated to collect tax in specific jurisdictions.
* Tax thresholds and rate differences by amounts.
* And many more custom use cases.
To upgrade to a fully-featured and accurate tax process that handles these scenarios correctly, please
contact Avalara to upgrade to AvaTax!
* @export
* @class TaxRateModel
*/
@JsonObject("TaxRateModel")
export class TaxRateModel {
/**
* @type {number}
* @memberof TaxRateModel
*/
@JsonProperty("totalRate", Number, true)
totalRate?: number | undefined = undefined;
/**
* @type {RateModel[]}
* @memberof TaxRateModel
*/
@JsonProperty("rates", [RateModel], true)
rates?: RateModel[] | undefined = undefined;
}
|
209596f755549dedea30359281de007631a8f23a
|
TypeScript
|
mvezer/tuya-home-control
|
/src/models/device/DevicesRepository.ts
| 2.75
| 3
|
import * as mongoose from 'mongoose';
import BaseDevice, {TDeviceData} from './BaseDevice';
import DeviceFactory from './DeviceFactory';
import Logger from '../../handlers/Logger';
const DEVICE_TYPES = ['rgb_bulb', 'plug'];
const DeviceModel = mongoose.model('Device', new mongoose.Schema({
deviceId: { type: String, required: true, unique: true },
key: { type: String, required: true },
type: { type: String, enum: DEVICE_TYPES, required: true },
name: { type: String, required: true },
}));
export default class DevicesRepository {
private devices:Array<BaseDevice> = [];
private _isInitialized:boolean;
private logger:Logger;
constructor() {
this.logger = new Logger('DevicesRepository');
this._isInitialized = false;
}
async init():Promise<void> {
try {
(await this.loadAllFromDb()).map(device => this.initDevice(device), this);
} catch (error: any) {
this.logger.error(`init failed: ${error.message}`);
}
this._isInitialized = true;
}
async initDevice(device:BaseDevice): Promise<void> {
await device.connect();
this.devices.push(device);
}
async addDevice(newDeviceData:TDeviceData):Promise<BaseDevice> {
if (this.getDeviceById(newDeviceData.deviceId)) {
throw new Error(`cannot add device, device (deviceId: $newDeviceData.deviceId}) already exists`);
return null;
}
const newDevice = DeviceFactory.fromObject(newDeviceData);
await this.initDevice(newDevice);
await (new DeviceModel(newDevice.toObject())).save();
return newDevice;
}
async updateDevice(deviceId: string, updateDeviceData:{[index:string]:any}):Promise<BaseDevice> {
const device:BaseDevice = this.getDeviceById(deviceId);
for (const [k, v] of Object.entries(updateDeviceData)) {
switch (k) {
case 'name':
device.name = v;
break;
}
}
await DeviceModel.updateOne({ deviceId}, updateDeviceData);
return device;
}
async deleteDevice(deviceId: string):Promise<void> {
const device = this.getDeviceById(deviceId);
if (device) {
await device.disconnect();
this.devices = this.devices.filter(d => d.deviceId !== deviceId );
await DeviceModel.deleteOne({ deviceId });
}
}
getAllDevices():Array<BaseDevice> {
return this.devices;
}
getDeviceById(deviceId:string):BaseDevice {
return this.devices.find(device => device.deviceId === deviceId);
}
async loadAllFromDb():Promise<BaseDevice[]> {
let devices:Array<BaseDevice> = [];
try {
devices = (await DeviceModel.find())
.map(deviceDocument => DeviceFactory.fromObject({
deviceId: deviceDocument.get('deviceId'),
name: deviceDocument.get('name'),
key: deviceDocument.get('key'),
type: deviceDocument.get('type'),
status: {},
isConnected: false
})
);
} catch (error: any) {
this.logger.error(`cannot load devices: ${error.message}`);
}
return devices;
}
get isInitialized():boolean {
return this._isInitialized;
}
}
|
491ec4c0e66a79313d8f256202bf9232dd21bdc1
|
TypeScript
|
robert-harbison/super-validator
|
/lib/validators/Required.test.ts
| 2.765625
| 3
|
import { setConfig } from '..'
import required from './Required'
beforeEach(() => {
setConfig(null)
})
describe('Required:required()', () => {
test('Should return error if value is null or undefined.', () => {
expect(required()('theField', null)).toEqual('`theField` is required.')
expect(required()('theField', undefined)).toEqual('`theField` is required.')
})
test('Should not return error if value is defined.', () => {
expect(required()('theField', 'test')).toEqual(null)
expect(required()('theField', 'test')).toEqual(null)
})
test('Should return custom message if provided when values are null or undefined', () => {
expect(required('Custom')('theField', null)).toEqual('Custom')
expect(required('Custom')('theField', undefined)).toEqual('Custom')
})
test('Should return config message if set as error', () => {
setConfig({ language: { required: 'CONFIG CUSTOM!' } })
expect(required()('theField', null)).toEqual('CONFIG CUSTOM!')
})
test('Provided message should override config message.', () => {
setConfig({ language: { required: 'CONFIG CUSTOM!' } })
expect(required('msg')('theField', null)).toEqual('msg')
})
})
|
16bdceb5923cbe009d17c4029c2fca79b5ad6a44
|
TypeScript
|
tec8297729/z-swagger-to-apidoc
|
/src/processing.ts
| 2.796875
| 3
|
import * as fs from 'fs';
import { TransformOptions, Parameters } from './interface';
const emptyApiText = '无'; // 描述空占位符
const initData = {
treeLevelIndex: 1,
};
class Processing {
constructor(opts: TransformOptions, definitions) {
this.opts = opts;
this.definitions = definitions;
}
private opts: TransformOptions;
private definitions;
// 生成apidoc基础配置文件
initApiJson = (rootDir: string, info) => {
const apidocBaseData = {
name: info.title || '标题',
version: info.version || '0.0.1',
description: info.description || '',
title: this.opts.title || info.title || '',
url: this.opts.baseUrl || '', // 请求前缀
};
fs.writeFileSync(`${rootDir}/apidoc.json`, JSON.stringify(apidocBaseData));
// console.log('apidoc.json文件已更新');
}
// 版本号处理
regVersion = (info) => {
const reg = /\..*\..*/g.test(info.version);
const newInfo = info;
if (!reg) {
newInfo.version = `${newInfo.version}.0`;
}
return newInfo;
}
// 生成jwt信息
addJwt = (securityArr = [], opts) => {
let newText = '';
const jwtDes = opts.jwtDes || '登录、注册接口返回的jwt';
const jwtName = opts.jwt || opts.bearer.name || 'jwt';
// 带有指定bearer字段才添加jwt信息
const addFlag = securityArr.some(item => item.bearer);
if (addFlag) {
newText += `* @apiHeader {String} ${jwtName} ${jwtDes}\n`;
}
return newText;
}
// 生成组标签
addApiGroup = (tags: string[] = []) => {
let newText = '';
tags.forEach(tagItem => {
newText += `* @apiGroup ${tagItem}\n`;
});
if (tags.length === 0) {
newText = `* @apiGroup default\n`;
}
return newText;
}
// 生成请求参数标签
addApiParam = (parameters: Parameters[] = []) => {
let newText = '';
// 循环处理swagger请求响应字段
parameters!.forEach(item => {
const { required, description, type, schema } = item;
let { name } = item;
initData.treeLevelIndex = 1; // 重置层级记录
name = required ? name : `[${name}]`; // 改造成可选参数结构
newText += `* @apiParam {${type}} ${name} ${description || emptyApiText}\n`;
// 处理映射类型
if (schema) {
newText = this.handleSchema('apiParam', { schema });
}
});
return newText;
}
// 生成响应参数标签
addApiResponse = (responses) => {
let newText = '';
// 处理响应字段参数
Object.keys(responses).forEach(item => {
const { type, name, description, schema } = responses[item];
initData.treeLevelIndex = 1;
if (schema) {
newText = this.handleSchema(`apiSuccess (Success ${item})`, { schema }); // 处理映射类型
} else {
// 无映射情况下、无多字段
newText += `* @apiSuccess (Success ${item}) {${type || 'string'}} ${name || 'success'} ${description || emptyApiText}\n`;
// let res = `
// * @apiSuccess {Boolean} succeed 成功标识
// * @apiSuccess {String} errorCode 结果码
// * @apiSuccess {String} errorMessage 消息说明`;
}
});
return newText;
}
// 获取映射ref的名称
matchRefName = (ref: string) => {
try {
const reg = /(#\/definitions\/)(?<name>.*)/;
return reg.exec(ref).groups.name;
} catch (error) {
return null;
}
}
// 验证是否是ref字符串形式
regRefNameFlag = (ref: string) => {
return /(#\/definitions\/)(?<name>.*)/.test(ref);
}
// 生成映射出来的类型
handleSchema = (apidocName, opts) => {
// 映射节点层、数据字典、递归拼接前缀
const { schema, oldMergeDefName, oldDes } = opts;
const { type, items, $ref } = schema;
let mergeApiParam = '';
let defName;
// console.log('处理次数', initData.treeLevelIndex);
if (type === 'array') {
// 多个映射类处理
Object.values(items).forEach((v: string) => {
defName = this.matchRefName(v);
mergeApiParam += this.handleSchemaDef(apidocName, {
defName, oldMergeDefName, oldDes,
});
});
} else {
// 单个映射类情况
defName = this.matchRefName($ref);
mergeApiParam = this.handleSchemaDef(apidocName, {
defName, oldMergeDefName, oldDes,
});
}
return mergeApiParam;
}
// 处理映射类生成文档注释(文档注释前缀、映射的名称、数据字典、递归的字段文档前缀)
handleSchemaDef = (apidocName, opts) => {
const { defName, oldMergeDefName, oldDes } = opts;
const { type, properties, required } = this.definitions[defName]; // 当前类结构
let mergeApiParam = '';
const fieldReqired = {};
// 必填字段处理
if (required) {
required.forEach(item => {
fieldReqired[item] = true;
});
}
// body注释
// mergeApiParam += `* @${apidocName} {${type}} ${defName} ${oldDes || emptyApiText}\n`;
Object.keys(properties).forEach(key => {
let mergeName = `${key}`;
// 组合前缀(递归过来的前缀)
if (oldMergeDefName) {
mergeName = `${oldMergeDefName}.${key}`;
}
mergeApiParam += this.schemaDefProperties(apidocName, {
key, mergeName, properties, fieldReqired,
});
});
return mergeApiParam;
}
// 映射类中的映射类(文档前缀名称)
schemaDefProperties = (apidocName, opts) => {
// 字段名、组合前缀名、当前字段数据集合、必传参数集合
const { key, mergeName, properties, fieldReqired } = opts;
const data = properties[key]; // 映射的具体字段相关参数
const reqiredName = `[${mergeName}]`; // 字段名(默认是可选)
let newType = data.type; // 字段类型
let mergeApiParam = '';
// 处理带有allOf字段,赋值描述及类型
if (!data.description && data.allOf) {
// console.log();
// 获取字典指定key中的type字段
newType = this.definitions[this.getDataAllOfParamter(data, 'refName')].type;
data.description = this.getDataAllOfParamter(data, 'des'); // 获取allOf的des字段
}
// 处理单层映射字段
mergeApiParam += `* @${apidocName} {${newType}} ${fieldReqired[key] ? mergeName : reqiredName} ${data.description || emptyApiText}\n`;
// 还有映射层递归处理
if (data.title) {
const defName = this.matchRefName(data.allOf[0].$ref);
newType = this.getMapingType(defName); // 获取映射级类型
if (initData.treeLevelIndex < this.opts.treeLevel) {
initData.treeLevelIndex += 1; // 记录层级次数
mergeApiParam += this.handleSchema(apidocName, {
schema: this.getDataAllOfParamter(data),
oldMergeDefName: mergeName,
oldDes: this.getDataAllOfParamter(data, 'des'),
});
}
}
// 集合类型处理,例如 array[string number]
if (data!.items) {
let mappingName;
const text = Object.values(data.items).map((typeName: string) => {
mappingName = this.matchRefName(typeName);
if (mappingName) {
return this.getMapingType(mappingName);
}
return typeName;
}).join(' ');
newType = `${newType}[${text}]`;
}
return mergeApiParam;
}
// 获取allOf参数上的指定属性值
getDataAllOfParamter = (data, field: string = 'refDom') => {
try {
const typeData = {
refDom: data.allOf!.filter(item => item.$ref)[0], // ref节点
refName: this.matchRefName(data.allOf!.filter(item => item.$ref)[0].$ref), // ref处理后的名称
des: data.allOf.filter(item => item.description)[0].description,
};
return typeData[field];
} catch (error) {
return null;
}
}
// 返回指定字典中的类型
getMapingType = (name: string) => {
try {
return this.definitions[name].type;
} catch (error) {
return null;
}
}
}
export default Processing;
|
57de12cd34bf86af441cf9828a48259a21d8fefe
|
TypeScript
|
bryan-jones/game
|
/node/server/classes/map/map.ts
| 3.40625
| 3
|
/**
* Create a base character class.
*/
class Map {
protected name: string;
/**
* Constructor.a
*
* @param name string
*/
constructor(name: string = '') {
this.name = name;
}
/**
* Save a map.
*/
save(name: string) {
// Saving operations.
}
load(name: string) {
// Loading operations.
}
};
|
09a5730b4bb3092a9d8f07351d45842a9ec3f163
|
TypeScript
|
BabylonJS/Babylon.js
|
/packages/tools/viewer/src/optimizer/custom/extended.ts
| 2.546875
| 3
|
import type { DefaultRenderingPipeline } from "core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline";
import { Scalar } from "core/Maths/math.scalar";
import type { SceneManager } from "../../managers/sceneManager";
/**
* A custom upgrade-oriented function configuration for the scene optimizer.
* @param sceneManager
*/
export function extendedUpgrade(sceneManager: SceneManager): boolean {
const defaultPipeline = <DefaultRenderingPipeline>sceneManager.defaultRenderingPipeline;
// if (!this.Scene.BackgroundHelper) {
// this.Scene.EngineScene.autoClear = false;
// this.Scene.BackgroundHelper = true;
// Would require a dedicated clear color;
// return false;
// }
if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
const scaling = Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
return false;
}
if (!sceneManager.scene.postProcessesEnabled) {
sceneManager.scene.postProcessesEnabled = true;
return false;
}
if (!sceneManager.groundEnabled) {
sceneManager.groundEnabled = true;
return false;
}
if (defaultPipeline && !sceneManager.fxaaEnabled) {
sceneManager.fxaaEnabled = true;
return false;
}
const hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
const scaling = Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
return false;
}
if (!sceneManager.processShadows) {
sceneManager.processShadows = true;
return false;
}
if (defaultPipeline && !sceneManager.bloomEnabled) {
sceneManager.bloomEnabled = true;
return false;
}
if (!sceneManager.groundMirrorEnabled) {
sceneManager.groundMirrorEnabled = true;
return false;
}
return true;
}
/**
* A custom degrade-oriented function configuration for the scene optimizer.
* @param sceneManager
*/
export function extendedDegrade(sceneManager: SceneManager): boolean {
const defaultPipeline = <DefaultRenderingPipeline>sceneManager.defaultRenderingPipeline;
if (sceneManager.groundMirrorEnabled) {
sceneManager.groundMirrorEnabled = false;
return false;
}
if (defaultPipeline && sceneManager.bloomEnabled) {
sceneManager.bloomEnabled = false;
return false;
}
if (sceneManager.processShadows) {
sceneManager.processShadows = false;
return false;
}
if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
const scaling = Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
return false;
}
if (defaultPipeline && sceneManager.fxaaEnabled) {
sceneManager.fxaaEnabled = false;
return false;
}
if (sceneManager.groundEnabled) {
sceneManager.groundEnabled = false;
return false;
}
if (sceneManager.scene.postProcessesEnabled) {
sceneManager.scene.postProcessesEnabled = false;
return false;
}
if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
const scaling = Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
return false;
}
// if (this.Scene.BackgroundHelper) {
// this.Scene.EngineScene.autoClear = true;
// this.Scene.BackgroundHelper = false;
// Would require a dedicated clear color;
// return false;
// }
return true;
}
|
5e9640401945df589e0625593f5a320c29b7e159
|
TypeScript
|
gabrielcolson/acacia
|
/db/index.ts
| 2.53125
| 3
|
import { PrismaClient, User, Space, Expense } from "@prisma/client"
export * from "@prisma/client"
let prisma: PrismaClient
if (process.env.NODE_ENV === "production") {
prisma = new PrismaClient()
} else {
// Ensure the prisma instance is re-used during hot-reloading
// Otherwise, a new client will be created on every reload
// @ts-ignore
globalThis["prisma"] = globalThis["prisma"] || new PrismaClient()
// @ts-ignore
prisma = globalThis["prisma"]
}
export type PublicUser = Pick<User, "name" | "id" | "displayName" | "pictureURL" | "role">
export const PUBLIC_USER_FIELDS: Record<keyof PublicUser, boolean> = {
id: true,
name: true,
displayName: true,
pictureURL: true,
role: true,
}
export type SpaceWithUsers = Space & {
owner: PublicUser
members: PublicUser[]
}
export type ExpenseWithPayer = Expense & {
payer: PublicUser
}
export default prisma
|
2aac8701398e099a3a5103aa49d653196a408b3a
|
TypeScript
|
Laotouy/ms
|
/packages/bukkit/src/typings/org.bukkit.inventory.meta.CrossbowMeta.ts
| 2.78125
| 3
|
declare namespace org {
namespace bukkit {
namespace inventory {
namespace meta {
// @ts-ignore
interface CrossbowMeta extends org.bukkit.inventory.meta.ItemMeta {
/**
* Returns whether the item has any charged projectiles.
*/
hasChargedProjectiles(): boolean;
/**
* Returns an immutable list of the projectiles charged on this item.
*/
getChargedProjectiles(): any[] /*java.util.List*/;
/**
* Sets the projectiles charged on this item.
* Removes all projectiles when given null.
*/
setChargedProjectiles(projectiles: any[] /*java.util.List*/): void;
/**
* Adds a charged projectile to this item.
*/
addChargedProjectile(item: org.bukkit.inventory.ItemStack): void;
}
}
}
}
}
|
937a109bfb6c97c4517d13ef0babf799d3bf2c52
|
TypeScript
|
yidafu/algorithm
|
/88.merge-sorted-array.ts
| 3.328125
| 3
|
/*
* @lc app=leetcode id=88 lang=typescript
*
* [88] Merge Sorted Array
*/
// @lc code=start
/**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
let i = m-1, j = n-1, idx = m + n - 1;
while(i >= 0 || j >= 0) {
if (j < 0 ||nums1[i] >= nums2[j]) {
nums1[idx--] = nums1[i--];
} else if (i < 0 || nums1[i] < nums2[j]) {
nums1[idx--] = nums2[j--];
}
}
};
// @lc code=end
|
4fad2eae61e8620bf73c6577d99a1284711c6aa5
|
TypeScript
|
cybersemics/em
|
/src/@types/Patch.ts
| 2.546875
| 3
|
import { GetOperation } from 'fast-json-patch'
// Extend fast-json-patch Operation type to include actions list
// See fast-json-patch types: https://github.com/Starcounter-Jack/JSON-Patch/blob/89a09e94e0e6500115789e33586a75c8dd1aea13/module/core.d.ts
// TODO: This should allow any Operation, not just GetOperation. But how to extend?
interface ExtendedOperation<T = any> extends GetOperation<T> {
actions: string[]
}
type Patch = ExtendedOperation[]
export default Patch
|
91385742b7bc3f2add31a57994cad122b784f9bf
|
TypeScript
|
TylorS167/167
|
/src/object/dissoc/index.ts
| 3.140625
| 3
|
import { clone } from '../clone'
import { curry2 } from '../../function/curry/curry2'
export const dissoc: Dissoc = curry2(function dissoc<A extends object>(prop: keyof A, obj: A) {
const newObj = {} as A
for (const key in obj) if (key !== prop) newObj[key] = clone(obj[key])
return newObj
})
export interface Dissoc {
<A extends object, B extends object = A>(prop: keyof A, obj: A): B
<A extends object, B extends object = A>(prop: keyof A): (obj: A) => B
}
|
f621b429731844cb09c77732b067c80c2077bd7d
|
TypeScript
|
a158abc/vue-window
|
/src/dom.ts
| 2.875
| 3
|
export function naturalSize(el: HTMLElement) {
const { width, height } = el.style
el.style.width = 'auto'
el.style.height = 'auto'
const rect = contentSize(el)
el.style.width = width
el.style.height = height
return rect
}
export function contentSize(el: HTMLElement) {
const style = window.getComputedStyle(el)
const width = Number(style.width!.split('px')[0])
const height = Number(style.height!.split('px')[0])
const top = Number(style.top!.split('px')[0])
const left = Number(style.left!.split('px')[0])
const right = left + width
const bottom = top + height
return { width, height, top, left, bottom, right }
}
|
08f5dde8467725060b0aca5233a80e229882f8b8
|
TypeScript
|
alexdeassis7/Angular-UTN
|
/Clase 3 Typescript/claseTS/vendingmachine/test.ts
| 3.671875
| 4
|
// class HelloWorld{
// constructor(public message: string){
// }
// }
// var hello = new HelloWorld("hola type Script");
// console.log(hello.message);
//creamos una funcion con todos los libros de nuestra "biblioteca"
function GetAllBooks() {
//creamos un array de libros ,cada libro con 3 propiedades
let books = [
{ title: "ulises", author: "jose vargas", available: false, categoria: Category.biografia },
{ title: "el fuego ", author: "emilialo alorda", available: false, categoria: Category.ficcion },
{ title: "el frio ", author: "RAcing Club", available: true, categoria: Category.historia },
{ title: "el calor", author: "joquin", available: false, categoria: Category.infantiles },
{ title: "macri gato ", author: "juan miron", available: true, categoria: Category.poesia },
{ title: "sionceramente", author: "el corte de luz", available: false, categoria: Category.poesia },
];
//devuelvo los libros
return books;
}
//funcion que recibe un array de libros y registrara en otro array
//el primer libro que este disponible
function LogFirstAvailable(books): void {
//variable que almacenen la cantidad de libros
let numberOfBooks: number = books.length;
//varialble que alamacene el primer tittulo disponible,
let firstAvailable: string = '';
//for que rrecorer la matrix de libros en busca del primero con la propiedad
//available en true ,current sera la variable que representa el
//libro que se examina en cada iteracion
for (let currenteBook of books) {
//valido si el libro esta disponible y asigno
//su titulo a la variable
if (currenteBook.available) {
firstAvailable = currenteBook.title
break;//salgo del bucle for
}
}
// muestro el total de libros
console.log('total de libros' + numberOfBooks);
//Muestro el primer libro que capture dentro del for
console.log('primer libro disponible ' + firstAvailable);
}
//Demostracion de Scope de
function ScopeTest() {
if (true) {
var foo = "use anywhere";//var usamos para variables globales
let bar = ' use in this block';//let usamos para varaibles de bloques
}
console.log(foo);
//console.log(bar);
}
//recibe una categoria como parametro y devuelve un array de string
//con el conjun to de libros
function GetbooksTitlesByCategory(categoryFilter: Category): Array<String> {
//muestro la categoria que recibimos por parametro
console.log('Getting book in category : ' + Category[categoryFilter]);
//alamaceno todos los libros en una constante
const AllBooks = GetAllBooks();
//creo un array de String Vacio , para alamacenar los titulos de los
//libros que coninciden con parametro categoryFilter
const filteredTitles: string[] = [];
//buscamos todos los libros con esa categoria
for (let currenteBook of AllBooks) {
if (currenteBook.categoria === categoryFilter) {
//agregamos a nuestro array de titulos
filteredTitles.push(currenteBook.title);
}
}
//retornamos los titulos filtrados
return filteredTitles;
}
//CREO UN ENUM
enum Category { biografia, poesia, ficcion, historia, infantiles }
//funcion que recibe un array de strimg con titulos
function LogBookTitles(titles: string[]): void {
for (let title of titles)
console.log(title);
}
//declaro una constante y le asigno el valor devuelto por la funcion getallbooks
const todosLosLibros = GetAllBooks();
//veamos como podemos modificart una constante
//la palabra const solo garantiza que el identificador no se modificara para
//hacer referencia a algo completamente diferente
// todosLosLibros.push({ title:"moby moby",author:"jose peres", available:true});
// todosLosLibros.push({ title:"50 sombras de la vecina ",author:"crintian", available:true});
//TEST de Funciones
LogFirstAvailable(todosLosLibros);
ScopeTest();
console.log('+++++++++++++++++++++++++++++++++++++++++');
GetbooksTitlesByCategory(Category.poesia);
const librosDePoesia = GetbooksTitlesByCategory(Category.poesia);
LogBookTitles(librosDePoesia);
const librosDeFiccion = GetbooksTitlesByCategory(Category.ficcion);
LogBookTitles(librosDeFiccion);
|
f3dbf0551bb4f7c9c320102d6840f9c212a4b530
|
TypeScript
|
josemak25/streams_test
|
/src/utils/isTablet.ts
| 2.6875
| 3
|
import {TABLET_DIMENSION} from '@app/constants';
import {Dimensions} from 'react-native';
/**
*
* @description scale a method for scaling app fonts based off the pixel density of the users phone
* @function isTablet
* @returns boolean
*/
export const isTablet = () => {
const {width, height} = Dimensions.get('window');
return Math.min(width, height) > TABLET_DIMENSION;
};
|
4b8824f77878a3900943eb20de8365866b2b5daf
|
TypeScript
|
riceboyler/cv-web-core-bundle
|
/src/mixins/media.ts
| 2.59375
| 3
|
import styled, { css } from "styled-components"
const breakpoints = {
giant: 1199,
xl: 1199,
desktop: 992,
lg: 992,
tablet: 768,
md: 768,
phone: 576,
sm: 576,
smaller: 575,
xs: 575,
}
const media = Object.keys(breakpoints).reduce((acc, label) => {
acc[label] = (...args: Array<any>) => css`
@media (max-width: ${breakpoints[label]}px) {
${css(args[0], ...args)};
}
`
return acc
}, {})
export const MobileOnly = el => {
return styled(el)`
display: none;
${media["md"]`
display:block;
`};
`
}
export const HiddenMobile = el => {
return styled(el)`
${media["md"]`
display:none;
`};
`
}
export default media
|
1f60a15a64db55d2865eefe8bf9f0f41bb39520b
|
TypeScript
|
ajafff/ng-dynamic-component
|
/projects/ng-dynamic-component/src/lib/io/types.ts
| 2.875
| 3
|
export interface InputsType {
[k: string]: any;
}
export interface OutputsType {
[k: string]: OutputExpression | undefined;
}
export interface OutputWithArgs {
handler: AnyFunction;
args?: any[];
}
export type OutputExpression = EventHandler | OutputWithArgs;
export type EventHandler<T = any> = (event: T) => any;
export type AnyFunction = (...args: any[]) => any;
|
cc1fcb8d7c29f4a303fd49bba06808beb4d0eb75
|
TypeScript
|
Krakabek/DevTernityWorkshop
|
/src/stack.ts
| 3.5
| 4
|
export class Stack {
private storage: Array<any>;
constructor() {
this.storage = [];
}
push(object: any) {
this.storage.push(object);
}
pop(): any {
if(!this.storage.length){
throw Error("Can not pop from empty stack");
}
return this.storage.pop();
}
}
|
f47773f39c31da317d118b9ea9892e462b6d0d4a
|
TypeScript
|
Horat1us/react-hooks
|
/src/use-window-size.ts
| 3.015625
| 3
|
import * as React from "react";
export type WindowSize = [number, number] | [undefined, undefined];
export type WindowSizeReducer = React.ReducerWithoutAction<WindowSize>;
export const WindowSizeReducer = (prevState: WindowSize = [undefined, undefined]): WindowSize => {
if ("object" !== typeof window) {
return prevState;
}
if ((prevState !== undefined)
&& (prevState[0] === window.innerWidth)
&& (prevState[1] === window.innerHeight)
) {
return prevState;
}
return [window.innerWidth, window.innerHeight];
};
export function useWindowSize(): WindowSize {
const [size, dispatch] = React.useReducer<WindowSizeReducer, undefined>(
WindowSizeReducer,
undefined,
WindowSizeReducer
);
React.useEffect(() => {
window.addEventListener("resize", dispatch);
return () => window.removeEventListener("resize", dispatch);
}, []);
return size;
}
|
e335fa6b2f527355adbba8b427d495a53a6822d3
|
TypeScript
|
tom-berend/seen_ts
|
/src/model.ts
| 2.984375
| 3
|
// //// Groups
// ------------------
import { Transformable } from './transformable';
import { Light } from './light'
import { Surface } from './surface'
import {Mesh} from './shape'
import {V4} from './vectorMath'
// The object group class. It stores `Shapes`, `Lights`, and sub-Groups
// Notably, models are hierarchical, like a tree. This means you can isolate
// the transformation of groups of shapes in the scene, as well as create
// chains of transformations for creating, for example, articulated skeletons.
export class Group extends Transformable {
public groups: Group[] = []; // sub-groups
public lights: Light[] = [];
public surfaces: Surface[] = [];
public shapes: Mesh[] = []
public barycenter: V4
public normal:V4
/** Add a `Shape`, `Surface`, Light`, and other `Group` */
add(child: Mesh | Surface | Group | Light) {
if (child instanceof Light)
this.lights.push(child)
else if (child instanceof Group)
this.groups.push(child)
else if (child instanceof Surface)
this.surfaces.push(child)
else if (child instanceof Mesh)
this.shapes.push(child)
else // shouldn't get here
throw new Error('Tried to add something strange')
}
// /* Remove a shape, model, or light from the model. NOTE: the scene may still
// * contain a renderGroup in its cache. If you are adding and removing many items,
// * consider calling `.flush()` on the scene to flush its renderGroup cache. */
// remove : (childs...) ->
// for child in childs
// while (i = this.children.indexOf(child)) >= 0
// this.children.splice(i,1)
// while (i = this.lights.indexOf(child)) >= 0
// this.lights.splice(i,1)
// // Create a new child model and return it.
// append: () ->
// model = new seen.Group
// this.add model
// return model
// // Visit each `Shape` in this `Group` and all recursive child `Group`s.
// eachShape (f){
// for child in this.children
// if child instanceof seen.Shape
// f.call(this., child)
// if child instanceof seen.Group
// child.eachShape(f)
//}
}
|
dc912183faf7176fd3fcf1eafb5e9ae416120848
|
TypeScript
|
react-native-styled-paper/react-native-styled-paper
|
/components/Container/utils/helpers.ts
| 2.5625
| 3
|
export const isHidden = (screenSize, props) => {
switch (screenSize) {
case "small":
return props.smHidden ? true : false;
case "medium":
return props.mdHidden ? true : false;
case "large":
return props.lgHidden ? true : false;
default:
return false;
}
};
const toPercent = (num) => (num * 100) + "%";
export const getComponentWidth = (screenSize, props) => {
switch (screenSize) {
case "small":
if (props.sm) {
return toPercent(props.sm / props.rowSize);
} else {
return props.parentWidth;
}
break;
case "medium":
if (props.md) {
return toPercent(props.md / props.rowSize);
} else if (props.sm) {
return toPercent(props.sm / props.rowSize);
} else {
return props.parentWidth;
}
break;
case "large":
if (props.lg) {
return toPercent(props.lg / props.rowSize);
} else if (props.md) {
return toPercent(props.md / props.rowSize);
} else if (props.sm) {
return toPercent(props.sm / props.rowSize);
} else {
return props.parentWidth;
}
break;
default:
return props.parentWidth;
}
};
export const getComponentOffset = (screenSize, props) => {
switch (screenSize) {
case "small":
if (props.smOffset) {
return toPercent(props.smOffset / props.rowSize);
} else {
return 0;
}
break;
case "medium":
if (props.mdOffset) {
return toPercent(props.mdOffset / props.rowSize);
} else if (props.smOffset) {
return toPercent(props.smOffset / props.rowSize);
} else {
return 0;
}
break;
case "large":
if (props.lgOffset) {
return toPercent(props.lgOffset / props.rowSize);
} else if (props.mdOffset) {
return toPercent(props.mdOffset / props.rowSize);
} else if (props.smOffset) {
return toPercent(props.smOffset / props.rowSize);
} else {
return 0;
}
break;
default:
return 0;
}
};
|
62f4eaab572dee3734f9255980a8913c737523fe
|
TypeScript
|
sujanchhetri/ts-snip
|
/Advanced types/indexproperty.ts
| 2.75
| 3
|
// * property is defined as index
interface ErrorChecker{
[prop:string]:string;
}
const errorCheck:ErrorChecker = {
email : 'Not a valid email',
username : 'Must be capital at start'
};
|
5ffcda6bf4a99c15c26fbc99e3697c240faec980
|
TypeScript
|
minhtranin/codebase
|
/src/web/common/log.ts
| 3.28125
| 3
|
/* tslint:disable:no-console */
export enum Level {
All = 0,
Debug,
Warn,
Error,
None
}
let _level: Level = Level.All
function _init (level: Level) {
_level = level
}
export function init (levelName: string) {
const levelsMap: { [name: string]: Level } = {
ALL: Level.All,
DEBUG: Level.Debug,
ERROR: Level.Error,
NONE: Level.None,
WARN: Level.Warn
}
const level = levelsMap[levelName]
// tslint:disable-next-line:strict-type-predicates TSLint bug =(
if (level != null) {
_init(level)
debug(`Log level set to ${levelName} (${level})`)
} else {
_init(Level.None)
error('Unknown log level')
}
}
export function debug (message?: any, ...optionalParams: any[]) {
if (Level.Debug >= _level) {
console.log.call(console, ...arguments)
}
}
export function warn (message?: any, ...optionalParams: any[]) {
if (Level.Warn >= _level) {
console.warn.call(console, ...arguments)
}
}
export function error (message?: any, ...optionalParams: any[]) {
if (Level.Error >= _level) {
console.error.call(console, ...arguments)
}
}
|
51ae89342c229e75d9b2a44d1f44016224843a17
|
TypeScript
|
ChainSafe/incubator-milagro-crypto-js
|
/src/fp.d.ts
| 2.59375
| 3
|
import {BIG, DBIG} from "./big";
import {FpCommon} from "./fp-common";
export class FP extends FpCommon<FP> {
public constructor(x: FP | BIG);
public static logb2(v: number): number;
public static mod(d: DBIG): BIG;
public rcopy(y: FP): void;
public bcopy(y: FP): void;
public cswap(b: FP, d: number): void;
public nres(): FP;
public redc(): BIG;
public norm(): number;
public mul(b: FP): FP;
public sqr(): FP;
public add(b: FP): FP;
public neg(): FP;
public sub(b: FP): FP;
public div2(): FP;
public fpow(): FP;
public inverse(): FP;
public jacobi(): number;
public sqrt(): FP;
}
|
c5ca21d07e960e1d45a7e304950a9d4652b3422a
|
TypeScript
|
navya7gowda/quintype-diamond-sweeper-solution-
|
/src/app/board/board.component.ts
| 2.578125
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-board',
templateUrl: './board.component.html',
styleUrls: ['./board.component.css']
})
export class BoardComponent implements OnInit {
data = [
['diamond', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown'],
['unknown', 'diamond', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown'],
['unknown', 'unknown', 'diamond', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown'],
['unknown', 'unknown', 'unknown', 'diamond', 'unknown', 'unknown', 'unknown', 'unknown'],
['unknown', 'unknown', 'unknown', 'unknown', 'diamond', 'unknown', 'unknown', 'unknown'],
['unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'diamond', 'unknown', 'unknown'],
['unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'diamond', 'unknown'],
['unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'unknown', 'diamond']
];
visited = [
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false],
[false, false, false, false, false, false, false, false]
];
score = 64;
completed = false;
board_view = [
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', ''],
['', '', '', '', '', '', '', '']
];
keys: String[];
constructor() {
this.data.map((row, rowIndex) => {
this.renderRow(row, rowIndex);
});
}
ngOnInit() {
}
renderCell(cell, rowIndex, colIndex) {
const image = this.imageOf(cell, rowIndex, colIndex);
const divData =
image
? `<div class="box"><img src=${image} width="30px" height="30px"/></div>`
: null;
this.board_view[rowIndex][colIndex] = divData;
}
onClick(rowIndex, colIndex) {
if (!this.completed) {
if (this.visited[rowIndex][colIndex] === false) {
if (this.data[rowIndex][colIndex] === 'diamond' && this.visited[rowIndex][colIndex] === false) {
this.board_view[rowIndex][colIndex] = `<div class="box"><img src="/assets/images/diamond.png" width="30px" height="30px"/></div>`;
}
this.visited[rowIndex][colIndex] = true;
if (this.game_completed(rowIndex, colIndex)) {
this.score = this.score - 1;
this.completed = true;
} else {
if (this.data[rowIndex][colIndex] === 'unknown' && this.visited[rowIndex][colIndex] === true) {
this.board_view[rowIndex][colIndex] = `<div class="box" width="30px" height="30px"></div>`;
}
this.score = this.score - 1;
}
}
}
}
game_completed(rowIndex, colIndex) {
const visited = this.visited, score = this.score;
for (let i = 0; i < visited.length; i++) {
for (let j = 0; j < visited.length; j++) {
if (this.data[i][j] === 'diamond' && this.visited[i][j] === false) {
return false;
}
}
}
return true;
}
imageOf(cell, rowIndex, colIndex) {
if (!this.visited[rowIndex][colIndex]) {
return '/assets/images/question.png';
} else if (cell === 'diamond') {
return '/assets/images/diamond.png';
}
}
renderRow(row, rowIndex) {
return row.map((cell, colIndex) => {
return this.renderCell(cell, rowIndex, colIndex);
});
}
}
|
30eb3707d5e3a69e317a2ca0ee54163988a0907a
|
TypeScript
|
Raja-cloud/NgxValidations
|
/projects/ngx-validations/src/lib/ngx-validations.service.ts
| 2.828125
| 3
|
import { Injectable, Inject } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { VALIDATION_CONFIG } from "./ngx-validations.config";
@Injectable()
export class NgxValidationsService {
constructor() {}
getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
const config: any = {
required: "Required",
invalidEmail: "Invalid Email",
invalidYear: "Invalid Year",
invalidPostal: "Invalid Postal Code",
invalidMobile: "Invalid Mobile",
invalidPassword:
"Invalid password. Password must be at least 6 characters long, and contain a number.",
minlength: `Minimum length ${validatorValue.requiredLength}`,
maxlength: `Max length ${validatorValue.requiredLength}`,
invalidToDate: "From Date Time should be less than To Date Time",
passwordMatch: "Password and Confirm Password should match",
};
return config[validatorName];
}
emailValidator(control: any) {
// RFC 2822 compliant regex
// tslint:disable-next-line:max-line-length
if (
control.value &&
control.value.match(
// tslint:disable-next-line:max-line-length
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)
) {
return null;
} else {
return { invalidEmail: true };
}
}
dateLessThan(from: string, to: string) {
return (group: FormGroup): { [key: string]: any } => {
const f = group.controls[from];
const t = group.controls[to];
if (f.value > t.value) {
return { invalidToDate: true };
}
return null;
};
}
mobileValidator(control: any) {
// RFC 2822 compliant regex
// tslint:disable-next-line:max-line-length
if (control.value && control.value.replace(/[^0-9]/g, "").length === 10) {
return null;
} else if (!control.value) {
return null;
} else {
return { invalidMobile: true };
}
}
amountValidator(control: any) {
if (control.value) {
if (Number(control.value) > 0) {
return null;
} else {
return { invalidAmount: true };
}
} else {
return { invalidAmount: true };
}
}
yearValidator(control: any) {
const yearValue = control.value;
if (yearValue < 1900 || yearValue > new Date().getFullYear() + 2) {
return { invalidYear: true };
} else {
return null;
}
}
postalCodeValidator(control: any) {
// RFC 2822 compliant Allowing US and Canada Valid Postal Code
if (
control.value &&
(control.value.match(
/^[ABCEGHJKLMNPRSTVXYabcegjklmnprstvxy][0-9][ABCEGHJKLMNPRSTVWXYZabceghjklmnprstvwxyz][0-9][ABCEGHJKLMNPRSTVWXYZabcegjklmnprstvwxyz][0-9]$/
) ||
control.value.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/))
) {
return null;
} else if (!control.value) {
return null;
} else {
return { invalidPostal: true };
}
}
}
|
92143db80c5cc5b7cdb4db8000cce8c7b0a5fc88
|
TypeScript
|
maciejtutak/tslox
|
/src/Expr.ts
| 2.859375
| 3
|
import { Literal as TLiteral, Token } from "./Token";
import { ExprVisitor } from "./AstPrinter";
export interface Expr {
// accept(visitor: ExprVisitor<R>): R;
// this is much cleaner with:
accept<R>(visitor: ExprVisitor<R>): R;
}
export class Binary implements Expr {
left: Expr;
operator: Token;
right: Expr;
constructor(left: Expr, operator: Token, right: Expr) {
this.left = left;
this.operator = operator;
this.right = right;
}
accept<R>(visitor: ExprVisitor<R>): R {
return visitor.visitBinaryExpr(this);
}
}
export class Unary implements Expr {
operator: Token;
right: Expr;
constructor(operator: Token, right: Expr) {
this.operator = operator;
this.right = right;
}
accept<R>(visitor: ExprVisitor<R>): R {
return visitor.visitUnaryExpr(this);
}
}
export class Grouping implements Expr {
expr: Expr;
constructor(expr: Expr) {
this.expr = expr;
}
accept<R>(visitor: ExprVisitor<R>): R {
return visitor.visitGroupingExpr(this);
}
}
export class Literal implements Expr {
value: TLiteral;
constructor(value: TLiteral) {
this.value = value;
}
accept<R>(visitor: ExprVisitor<R>): R {
return visitor.visitLiteralExpr(this);
}
}
export * as Expression from "./Expr";
|
1ad7d9c964d7ff46fb78b56cf3bc37e14bac4413
|
TypeScript
|
MaxPeak/vue-next-admin
|
/src/utils/random.ts
| 3.953125
| 4
|
/**
* 随机数
* Math.random是一个0-1的左闭右开区间(取得到0取不到1),即 =>>> [0-1)这个样子,为了方便实用,可以利用计算来实现一个取随意区间的方法
*/
export const random = (min: number, max: number) =>
Math.floor(Math.random() * (max + 1 - min) + min);
/**
* 创建一个随机数数组
*/
export const randomArray = (
min: number,
max: number,
leng: number,
isRepeat: boolean
) => {
let result: number[] = [];
while (result.length < leng) {
const num = random(min, max);
result.push(num);
if (isRepeat) result = [...new Set(result)];
}
return result;
};
/**
* 创建一个随机的rgb颜色值
* @returns {String}
*/
export const randomRGB = () =>
`rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
/**
* 创建一个随机的rgba颜色值
* @returns {String}
*/
export const randomRGBA = () => {
return `rgba(${random(0, 255)},${random(0, 255)},${random(
0,
255
)}),${Math.random().toFixed(1)}`;
};
/**
* 创建一个随机的16进制颜色值
* @returns {String}
*/
export const random16 = () => {
//16进制的基本值
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"];
const len = arr.length - 1;
let color = "#";
for (let i = 0; i < 6; i++) {
color += arr[random(0, len)];
}
return color;
};
|
3c25809d51176e1af01616ff77bfb8f9f9a28f96
|
TypeScript
|
cheshirescat/metastream
|
/packages/metastream-app/src/lobby/reducers/mediaPlayer.ts
| 2.5625
| 3
|
import { Reducer } from 'redux'
import { isType } from 'utils/redux'
import {
setMedia,
endMedia,
playPauseMedia,
seekMedia,
queueMedia,
repeatMedia,
updateMedia,
deleteMedia,
updateServerClockSkew,
moveToTop,
lockQueue,
setPendingMedia
} from 'lobby/actions/mediaPlayer'
import { MediaType } from 'media/types'
import { ReplicatedState } from '../../network/types'
import { resetLobby, initLobby } from '../actions/common'
export const enum PlaybackState {
Idle,
Playing,
Paused
}
export interface IMediaItem {
/** Unique ID */
id: string
type: MediaType
url: string
// TODO: Make the following non-optional
title: string
/** Duration in ms */
duration?: number
/** Thumbnail image */
imageUrl?: string
description?: string
/** Original request URL */
requestUrl: string
/** Requester ID */
ownerId?: string
/** Requester name, in case they disconnect */
ownerName?: string
/** Middleware-specific state */
state?: { [key: string]: any }
/** Whether the item should continue as the next media */
hasMore?: boolean
/** Time to start playback at. */
startTime?: number
}
export interface PendingMedia {
url: string
time?: number
source?: string
}
export const enum RepeatMode {
Off = 0,
On,
One,
/** Number of enum constants */
Count
}
export interface IMediaPlayerState {
playback: PlaybackState
repeatMode: RepeatMode
startTime?: number
pauseTime?: number
current?: IMediaItem
queue: IMediaItem[]
queueLocked: boolean
/** Clock time difference between client and server. */
serverClockSkew: number
/** Local session save state. */
localSnapshot?: IMediaPlayerState
/** Media pending to be queued */
pendingMedia?: PendingMedia
}
export const mediaPlayerReplicatedState: ReplicatedState<IMediaPlayerState> = {
playback: true,
repeatMode: true,
startTime: true,
pauseTime: true,
current: true,
queue: true,
queueLocked: true,
serverClockSkew: false
}
const initialState: IMediaPlayerState = {
playback: PlaybackState.Idle,
repeatMode: RepeatMode.Off,
startTime: undefined, // undefined to clear out old data
pauseTime: undefined,
current: undefined,
queue: [],
queueLocked: false,
serverClockSkew: 0
}
const getMediaStartTime = (media: IMediaItem) =>
media.startTime ? Date.now() - media.startTime : Date.now()
export const mediaPlayer: Reducer<IMediaPlayerState> = (
state: IMediaPlayerState = initialState,
action: any
) => {
if (isType(action, setMedia)) {
const media = action.payload
return {
...state,
playback: PlaybackState.Playing,
current: media,
startTime: getMediaStartTime(media)
}
} else if (isType(action, endMedia)) {
let next
let queue = state.queue
const current = state.current
const force = action.payload
if (current) {
if ((force && state.repeatMode !== RepeatMode.Off) || state.repeatMode === RepeatMode.On) {
queue = [...queue, current]
} else if (state.repeatMode === RepeatMode.One) {
queue = [current, ...queue]
}
}
// get next item in the queue
if (queue.length > 0) {
// create queue copy since `shift()` will mutate it
queue = [...queue]
next = queue.shift()
}
return {
...state,
playback: next ? PlaybackState.Playing : PlaybackState.Idle,
current: next,
startTime: next ? getMediaStartTime(next) : undefined,
queue: queue
}
} else if (isType(action, playPauseMedia)) {
switch (state.playback) {
case PlaybackState.Playing:
return {
...state,
playback: PlaybackState.Paused,
pauseTime: action.payload
}
case PlaybackState.Paused:
return {
...state,
playback: PlaybackState.Playing,
startTime: Date.now() - state.pauseTime!,
pauseTime: undefined
}
}
} else if (isType(action, seekMedia)) {
const time = action.payload
switch (state.playback) {
case PlaybackState.Playing:
return {
...state,
startTime: Date.now() - time
}
case PlaybackState.Paused:
return {
...state,
pauseTime: time
}
}
} else if (isType(action, queueMedia)) {
const { media, index } = action.payload
const queue = [...state.queue]
const queueIndex = typeof index === 'number' ? index : queue.length
queue.splice(queueIndex, 0, media)
return { ...state, queue }
} else if (isType(action, repeatMedia)) {
return {
...state,
// cycle through repeat modes
repeatMode: (state.repeatMode + 1) % RepeatMode.Count
}
} else if (isType(action, updateServerClockSkew)) {
return { ...state, serverClockSkew: action.payload }
} else if (isType(action, updateMedia) && state.current) {
const prevDuration = state.current.duration
const nextDuration = action.payload.duration
// Reset start time if media previously had unknown duration
const hasPrevDuration = typeof prevDuration === 'number'
const hasNextDuration = typeof nextDuration === 'number'
const startTime = !hasPrevDuration && hasNextDuration ? Date.now() : state.startTime
return {
...state,
startTime,
current: {
...state.current,
duration: hasNextDuration ? nextDuration : prevDuration
}
}
} else if (isType(action, deleteMedia)) {
const mediaId = action.payload
const mediaIdx = state.queue.findIndex(media => media.id === mediaId)
if (mediaIdx > -1) {
const queue = [...state.queue]
queue.splice(mediaIdx, 1)
return { ...state, queue }
}
} else if (isType(action, moveToTop)) {
const mediaId = action.payload
const mediaIdx = state.queue.findIndex(media => media.id === mediaId)
if (mediaIdx > -1) {
const queue = [...state.queue]
queue.unshift(queue.splice(mediaIdx, 1)[0])
return { ...state, queue }
}
} else if (isType(action, lockQueue)) {
return {
...state,
queueLocked: !state.queueLocked
}
} else if (isType(action, setPendingMedia)) {
return {
...state,
pendingMedia: action.payload
}
}
// Save session snapshot on disconnect
if (isType(action, resetLobby)) {
if (!action.payload.host) {
return state.localSnapshot
? { ...initialState, localSnapshot: state.localSnapshot }
: initialState
}
const isPlaying = state.playback === PlaybackState.Playing
return {
...initialState,
localSnapshot: {
...state,
playback: isPlaying ? PlaybackState.Paused : state.playback,
pauseTime: isPlaying ? Date.now() - state.startTime! : state.pauseTime
}
}
}
// Restore session snapshot
if (isType(action, initLobby)) {
if (action.payload.host && state.localSnapshot) {
const { localSnapshot } = state
return {
...state,
...initialState,
...localSnapshot,
localSnapshot: undefined,
// #227 a bug appeared where the snapshot was restored in an idle playback state with media.
// here we force the state to be paused to ensure media can be skipped.
playback: localSnapshot.current ? PlaybackState.Paused : PlaybackState.Idle,
serverClockSkew: initialState.serverClockSkew
}
} else {
// Clear out old state in case tab shutdown unexpectedly
return { ...state, ...initialState }
}
}
return state
}
|
7ee1f719da3b4c3ec7042462c2623612bd73a5c8
|
TypeScript
|
yiitz/yh-h5-weapp-game-frontend
|
/assets/resources/prefab/script/keyboard.ts
| 2.71875
| 3
|
// Learn TypeScript:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
/**
* 键盘组件
*/
const {ccclass, property} = cc._decorator;
@ccclass
export default class KeyBoard extends cc.Component {
/**
* 内容标签
*/
@property(cc.Label)
Label: cc.Label = null;
/**
* 内容盒子
*/
@property(cc.Node)
ContentBox: cc.Node = null;
/**
* 父级类 调用者this
*/
parentClass: any = {};
start() {
// 展现动画
this.ContentBox.scale = 0;
this.ContentBox.runAction(
cc.scaleTo(0.5, 1, 1).easing(cc.easeBackOut()),
);
cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDown, this);
}
/**
* 键盘按下事件
* @param event - 事件
*/
keyDown(event) {
const code = event.keyCode;
if (code >= 96 && code <= 105) {
this.onClickContent(false, code - 96);
}
if (code === 110) {
this.onClickDecimal(false, '.');
}
if (code === cc.macro.KEY.enter) {
this.onClickSuccess();
}
}
/**
* 点击0-9的数值时
* @param _event - 事件体
* @param content - 内容
*/
onClickContent(_event, content: number) {
this.Label.string += content;
}
/**
* 点击.
* @param _event - 事件体
* @param content - 内容
*/
onClickDecimal(_event, content: string) {
const { Label } = this;
if (Label.string.indexOf('.') === -1 && Label.string.length) {
Label.string += content;
}
}
/**
* 删除键
*/
onClickDelete() {
const { Label } = this;
if (Label.string.length) {
Label.string = Label.string.substr(0, Label.string.length - 1);
}
}
/**
* 完成键
*/
onClickSuccess() {
this.parentClass.emit && this.parentClass.emit(this.Label.string);
}
/**
* 重置键
*/
onClickReset() {
this.Label.string = '';
}
/**
* 关闭键
*/
onClickClose() {
this.parentClass.close && this.parentClass.close();
this.ContentBox.runAction(
cc.sequence(
cc.scaleTo(0.5, .5, .5).easing(cc.easeBackIn()),
cc.callFunc(() => this.node.destroy(), this),
),
);
}
// update (dt) {}
}
|
1e157bc1000121e406f113cafa87bb56930d400d
|
TypeScript
|
loadoff/react-redux-sample
|
/src/states/States.ts
| 2.75
| 3
|
import { reducerWithInitialState } from 'typescript-fsa-reducers';
import { actions } from '../actions/Actions';
export interface State {
name: string;
email: string;
}
const initialState: State = {
name: '',
email: ''
};
export const reducer = reducerWithInitialState(initialState)
.case(actions.updateName, (state, name) => {
return Object.assign({}, state, { name });
})
.case(actions.updateEmail, (state, email) => {
return Object.assign({}, state, { email });
});
|
81ec621226170d7b57e30da06d33b73bd8ccb041
|
TypeScript
|
GhostRealm/rotmg-sandbox
|
/src/common/asset/normal/loaders/TextureAssetLoader.ts
| 2.953125
| 3
|
import { AssetContainer } from "../AssetContainer";
import AssetLoader from "../AssetLoader";
import MapAssetContainer from "../MapAssetContainer";
export default class TextureAssetLoader implements AssetLoader<TextureConfig, AssetContainer<WebGLTexture>> {
gl: WebGLRenderingContext;
constructor(gl: WebGLRenderingContext) {
this.gl = gl;
}
async load(sources: TextureConfig[]): Promise<AssetContainer<WebGLTexture>> {
const { gl } = this;
const textureMap: TextureMap = new Map();
for (const src of sources) {
const img = await this.loadImage(src.src);
const texture = gl.createTexture();
if (texture === null) {
console.error(`Failed to create texture with name '${src.name}'`);
continue;
}
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
textureMap.set(src.name, {
texture,
size: {
width: img.naturalWidth,
height: img.naturalHeight
}
});
}
return new MapAssetContainer(textureMap);
}
async loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((res, rej) => {
const img = new Image();
img.crossOrigin = "";
img.src = src;
img.onload = () => res(img);
})
}
}
export type GLTextureInfo = {
texture: WebGLTexture;
size: {width: number, height: number}
}
export type TextureMap = Map<string, GLTextureInfo>;
export type TextureConfig = {
name: string,
src: string
}
|
a48dc77595e52f80776ea7f4879f3d957f22a87b
|
TypeScript
|
karakulov-web-dev/stalker_test
|
/external/seasonvar/ts/Polyfill/Promise_simple.ts
| 2.90625
| 3
|
export type Promise = {
then(cb);
};
export function Promise_simple(f) {
var returnCb = this.returnCb.bind(this);
f(returnCb);
}
Promise_simple.prototype.then = function(cb) {
this.cb = cb;
};
Promise_simple.prototype.cb = function() {};
Promise_simple.prototype.returnCb = function(q) {
var self = this;
setTimeout(function() {
self.cb(q);
}, 0);
};
|
8eaa0023ca709e9ed9bce66e8dc545b6856eed8c
|
TypeScript
|
juliothomazelli/beautytech-server
|
/src/utils/DateUtils.ts
| 3.078125
| 3
|
import { ObjectUtils } from "./ObjectUtils";
export class DateUtils {
public static formatDateTime(date : Date, initialDate = true){
if (ObjectUtils.isNullOrUndefined(date)){
return '';
}
let result = '';
result = date.getFullYear() + '-' + DateUtils.getMonth(date.getMonth()) + '-' + DateUtils.formatZeronumber(date.getDate().toString()) + ' ';
if (initialDate){
result += DateUtils.formatZeronumber(date.getHours().toString()) + ':' + DateUtils.formatZeronumber(date.getMinutes().toString()) + ':' + DateUtils.formatZeronumber(date.getSeconds().toString());
} else {
result += '23:59:59';
}
return result;
}
private static formatZeronumber(hourMinuteSecond : string){
if (hourMinuteSecond.length != 1){
return hourMinuteSecond;
}
return '0' + hourMinuteSecond;
}
public static getMonth(month : number){
if (month == 0){
return '01';
}
if (month == 1){
return '02';
}
if (month == 2){
return '03';
}
if (month == 3){
return '04';
}
if (month == 4){
return '05';
}
if (month == 5){
return '06';
}
if (month == 6){
return '07';
}
if (month == 7){
return '08';
}
if (month == 8){
return '09';
}
if (month == 9){
return '10';
}
if (month == 10){
return '11';
}
if (month == 11){
return '12';
}
}
public static getNumberDaysOfMonth(date : Date){
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}
}
|
aca671c978f6228304b9493a27ace035342405fc
|
TypeScript
|
alexanderpono/tothink
|
/my-courses/site/ui-src/Backend/Backend.validators.ts
| 2.796875
| 3
|
import Validator from 'schema-validator';
import { LoginAnswer } from './Backend';
interface User {
name: string;
id: number;
}
export interface GetUsersAnswer {
success: boolean;
users: User[];
}
export interface ValidateResult {
errors: { field: string; message: string; received?: string; expected?: string }[];
}
export function getValidateErrors(
errors: unknown[],
validatorErrors,
validatedValue,
prefix: string
): unknown[] {
let newErrors = errors;
if (validatorErrors._error === true) {
newErrors = errors.concat();
for (const key in validatorErrors) {
if (key === '_error') {
continue;
}
const errorInfo = validatorErrors[key];
if (typeof errorInfo.required !== 'undefined') {
newErrors.push({ field: `${prefix}${key}`, message: 'Missing required field' });
}
if (typeof errorInfo.type !== 'undefined') {
if (validatedValue[key] !== null) {
newErrors.push({
field: `${prefix}${key}`,
message: 'Invalid data type',
expected: errorInfo.type.message.split(':')[1].trim(),
received: typeof validatedValue[key]
});
}
}
}
}
return newErrors;
}
export function validateGetUsersAnswer(input: GetUsersAnswer): ValidateResult {
const rootSchema = {
success: {
type: Boolean,
required: true
},
users: {
type: Array,
required: true,
length: {
max: 20
}
}
};
const validator = new Validator(rootSchema);
const check = validator.check(input);
let errors = getValidateErrors([], check, input, '');
if (Array.isArray(input.users)) {
input.users.forEach(function (user: User, index: number) {
if (typeof user !== 'object') {
errors.push({
field: `user[${index}]`,
message: 'invalid data type',
expected: 'Object',
received: typeof user
});
return;
}
const userSchema = {
name: {
type: String,
required: true
},
id: {
type: Number,
required: true
}
};
const validator = new Validator(userSchema);
const check = validator.check(user);
errors = getValidateErrors(errors, check, user, `users[${index}].`);
});
}
return { errors } as ValidateResult;
}
export function validateLoginAnswer(input: LoginAnswer): ValidateResult {
const rootSchema = {
success: {
type: Boolean,
required: true
},
role: {
type: String,
required: true
}
};
const validator = new Validator(rootSchema);
const check = validator.check(input);
const errors = getValidateErrors([], check, input, '');
return { errors } as ValidateResult;
}
|
4762263a284b6fb14473335f02a537b0ddf30a00
|
TypeScript
|
ppeelman/afriguideme
|
/src/accommodation/Accommodation.domain.ts
| 2.671875
| 3
|
import { Photo } from "../domain/Photo.domain";
import Rating from "../rating/Rating.domain";
import { Currency } from "../domain/Currency.domain";
import { IAccommodationBooking } from "../booking/Booking.domain";
import { SelectedOption } from "../domain/Choice.domain";
import Location from "../location/Location.domain";
export interface ConstructorArguments {
id: string;
name: string;
shortDesc: string;
longDesc: string;
location: Location;
rating: Rating;
photos: Photo[];
startingPrice: Currency;
features: string[];
}
export class Accommodation {
readonly id: string;
readonly name: string;
readonly shortDesc: string;
readonly longDesc: string;
readonly location: Location;
readonly rating: Rating;
readonly photos: Photo[];
readonly startingPrice: Currency;
readonly features: string[];
constructor({
id,
name,
shortDesc,
longDesc,
location,
rating,
photos,
startingPrice,
features
}: ConstructorArguments) {
this.id = id;
this.name = name;
this.shortDesc = shortDesc;
this.longDesc = longDesc;
this.location = location;
this.rating = rating;
this.photos = photos;
this.startingPrice = startingPrice;
this.features = features;
}
}
export class AccommodationBooking implements IAccommodationBooking {
constructor(
public id: string,
public accommodationId: string,
public durationInDays: number,
public selectedOptions: SelectedOption<any>[]
) {}
}
|
652c332142732efcfae573de081fc8d40bfbfb5d
|
TypeScript
|
wongkuin/EffectProject
|
/eazax-cases/assets/eazax-ccc/components/RotateAround.ts
| 3
| 3
|
/** 轴 */
export enum Axis {
/** 正 X 轴 */
PositiveX,
/** 正 Y 轴 */
PositiveY,
/** 负 X 轴 */
NegativeX,
/** 负 Y 轴 */
NegativeY
}
const { ccclass, property } = cc._decorator;
/**
* 围绕旋转组件
* @see RotateAround.ts https://gitee.com/ifaswind/eazax-ccc/blob/master/components/RotateAround.ts
* @version 20210611
*/
@ccclass
export default class RotateAround extends cc.Component {
@property({ type: cc.Node, tooltip: CC_DEV && '围绕旋转的目标' })
public target: cc.Node = null;
@property({ tooltip: CC_DEV && '顺时针旋转' })
public clockwise: boolean = true;
@property({ tooltip: CC_DEV && '旋转一圈花费的时间' })
public timePerRound: number = 10;
@property({ tooltip: CC_DEV && '是否始终面向目标节点' })
public faceToTarget: boolean = false;
@property({
type: cc.Enum(Axis),
tooltip: CC_DEV && '面向目标节点的轴:\n- PositiveX:正 X 轴\n- PositiveY:正 Y 轴\n- NegativeX:负 X 轴\n- NegativeY:负 Y 轴',
visible() { return this.faceToTarget }
})
public faceAxis: Axis = Axis.NegativeY;
@property({ tooltip: CC_DEV && '自动开始旋转' })
public autoStart: boolean = false;
/** 相对于目标的角度 */
public angle: number = 0;
/** 半径 */
public radius: number = 0;
/** 标志位,是否正在旋转 */
protected isRotating: boolean = false;
protected start() {
this.autoStart && this.run();
}
protected update(dt: number) {
if (!this.isRotating || !this.target) {
return;
}
// 将角度转换为弧度
let angle = this.angle;
const radian = (Math.PI / 180) * angle;
// 更新节点的位置
const node = this.node,
target = this.target,
radius = this.radius;
node.x = target.x + radius * Math.cos(radian);
node.y = target.y + radius * Math.sin(radian);
// 更新节点的角度
if (this.faceToTarget) {
switch (this.faceAxis) {
case Axis.PositiveX:
node.angle = angle + 180;
break;
case Axis.PositiveY:
node.angle = angle + 90;
break;
case Axis.NegativeX:
node.angle = angle;
break;
case Axis.NegativeY:
node.angle = angle - 90;
break;
}
}
// 计算下一帧的角度
const anglePerFrame = dt * (360 / this.timePerRound);
angle = this.angle += (this.clockwise ? -anglePerFrame : anglePerFrame);
// 重置角度,避免数值过大
if (angle >= 720) {
this.angle %= 360;
} else if (angle <= -720) {
this.angle %= -360;
}
}
/**
* 开始围绕目标节点旋转
* @param target 目标节点
* @param clockwise 是否顺时针旋转
* @param timePerRound 旋转一圈的时间
* @param faceToTarget 是否始终面向目标节点
* @param faceAxis 面向目标节点的轴
*/
public run(target?: cc.Node, clockwise?: boolean, timePerRound?: number, faceToTarget?: boolean, faceAxis?: Axis) {
if (target != undefined) this.target = target;
if (clockwise != undefined) this.clockwise = clockwise;
if (timePerRound != undefined) this.timePerRound = timePerRound;
if (faceToTarget != undefined) this.faceToTarget = faceToTarget;
if (faceAxis != undefined) this.faceAxis = faceAxis;
if (!this.target) {
cc.warn('[RotateAround]', 'No target!');
return;
}
// 计算初始角度和半径
const p1 = this.target.getPosition(),
p2 = this.node.getPosition();
this.angle = this.getAngle(p1, p2);
this.radius = this.getDistance(p1, p2);
// 开始
this.isRotating = true;
}
/**
* 停止旋转
*/
public stop() {
this.isRotating = false;
}
/**
* 获取两点间的角度
* @param p1 点1
* @param p2 点2
* @see MathUtil.ts https://gitee.com/ifaswind/eazax-ccc/blob/master/utils/MathUtil.ts
*/
public getAngle(p1: cc.Vec2, p2: cc.Vec2): number {
return Math.atan((p2.y - p1.y) / (p2.x - p1.x));
}
/**
* 获取两点间的距离
* @param p1 点1
* @param p2 点2
* @see MathUtil.ts https://gitee.com/ifaswind/eazax-ccc/blob/master/utils/MathUtil.ts
*/
public getDistance(p1: cc.Vec2, p2: cc.Vec2): number {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
}
|
467cf80eadcde36d4f0ef5f85bba2ff25e1985d6
|
TypeScript
|
borisKarastanev/stratos
|
/src/frontend/packages/store/src/actions/log.actions.ts
| 2.953125
| 3
|
import { Action } from '@ngrx/store';
export enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR
}
export const LoggerActionTypes = {
DEBUG: '[LOG] Debug',
INFO: '[LOG] Info',
WARN: '[LOG] Warn',
ERROR: '[LOG] Error',
};
export class LoggerAction implements Action {
constructor(
public logLevel: LogLevel = LogLevel.INFO,
public message: string,
public type: string
) {
}
}
export class LoggerDebugAction implements LoggerAction {
constructor(
public message: string
) {
}
logLevel = LogLevel.DEBUG;
type = LoggerActionTypes.DEBUG;
}
export class LoggerInfoAction implements LoggerAction {
constructor(
public message: string
) {
}
logLevel = LogLevel.INFO;
type = LoggerActionTypes.INFO;
}
export class LoggerWarnAction implements LoggerAction {
constructor(
public message: string
) {
}
logLevel = LogLevel.WARN;
type = LoggerActionTypes.WARN;
}
export class LoggerErrorAction implements LoggerAction {
constructor(
public message: string
) {
}
logLevel = LogLevel.ERROR;
type = LoggerActionTypes.ERROR;
}
|
0f9a9449ce4716ee4b141aa3b438c92c62b39b70
|
TypeScript
|
vah7id/kal
|
/src/screens/multiplayer/reducer.ts
| 2.609375
| 3
|
import { GameState } from '../../store/ducks/schema';
import { MULTI_PLAYER_SET_STATUS } from './types';
import { Player } from './interfaces';
const defaultState = {
username: '',
loggedInUserId: '',
status: MULTI_PLAYER_SET_STATUS.lobby,
id: null,
players: [],
created_at: null,
};
// types
export const types = {
CREATE_GAME: '@KAL/CREATE_GAME',
CREATE_PEER: '@KAL/CREATE_PEER',
SET_STATUS: '@KAL/MULTI_PLAYER_SET_STATUS',
SET_USERNAME: '@KAL/SET_USERNAME',
SET_GAME_ID: '@KAL/SET_GAME_ID',
UPDATE_PLAYERS: '@KAL/UPDATE_PLAYERS',
};
// actions
export const actions = {
updateGameStatus: (status: string) => ({ type: types.SET_STATUS, payload: status }),
updatePlayers: (players: Array<Player>) => ({ type: types.UPDATE_PLAYERS, payload: players }),
setGameId: (payload: any) => ({ type: types.SET_GAME_ID, payload }),
setUsername: (payload: string) => ({ type: types.SET_USERNAME, payload }),
createGame: (gameid: string, userid: string) => ({ type: types.CREATE_GAME, payload: {gameid, userid}}),
setStatus: (payload: string) => ({ type: types.SET_STATUS, payload }),
};
// selectors
export const getUsername = (state: GameState) => {
return state.multiplayer.username;
}
export const getUserId = (state: GameState) => {
return state.multiplayer.loggedInUserId;
}
export const getGameId = (state: GameState) => {
return state.multiplayer.id;
}
// reducers
export const multiplayerReducer = (state = defaultState, action: any) => {
switch (action.type) {
case types.CREATE_GAME:
return {
...state,
id: action.payload.gameid,
loggedInUserId: action.payload.userid
};
case types.UPDATE_PLAYERS:
return {
...state,
players: action.payload,
};
case types.SET_GAME_ID:
return {
...state,
roomId: action.payload.name,
sessionId: action.payload.sessionId,
};
case types.SET_USERNAME:
return {
...state,
username: action.payload
};
case types.SET_STATUS:
return {
...state,
status: action.payload
};
default:
return state;
}
};
export default multiplayerReducer;
|
1782270bfabd75efabcc93d942b0a77314c9e222
|
TypeScript
|
dream2023/wangeditor-for-react
|
/src/utils/helper.ts
| 3.40625
| 3
|
/*
* @Author: dongmin
* @LastEditors: donggg
* @Date: 2021-04-02 18:36:57
* @LastEditTime: 2021-07-05 16:05:05
*/
/**
* 简单判断两个值是否相当
* @param {string} 值1
* @param {string} 值2
* @return {boolean} 判断结果
*/
export const isEqualString = (value1: string, value2: string): boolean =>
value1 === value2;
/**
* 判断是否为空
* @param {object|array|string|boolean|null|undefined|NaN} value 待判断值
* @return {boolean} 判断结果
*/
export const isEmpty = (
value:
| Record<string, unknown>
| unknown[]
| string
| number
| null
| undefined,
): boolean => {
// null, undefined
if (value === null || value === undefined) {
return true;
}
// NaN
if (typeof value === 'number' && value !== value) {
return isNaN(value);
}
// array
if (typeof value === 'object' && value.length) {
return value.length === 0;
}
// string
if (typeof value === 'string') {
return value === '';
}
// object
if (typeof value === 'object') {
return Object.keys(value).length === 0;
}
return !value;
};
/**
* 返回给定数组不同的值
* @param {array} array 待过滤数组
* @param {array} values 需要过滤的值组成的数组
* @returns {array} 返回给定数组不同的值
*/
export const difference = <T>(array: Array<T>, values: unknown[]): Array<T> => {
const result: Array<T> = [];
for (const value of array) {
if (!values.includes(value)) {
result.push(value);
}
}
return result;
};
/**
* 判断是否为该对象的键
* @param key object 的键
* @param editor 目标对象
* @returns 是否是该元素的键
*/
export function isValidKey(
key: string | number | symbol,
object: Record<string, unknown>,
): key is keyof typeof object {
return key in object;
}
export default {};
|
cc79cef395a00235291e6ebc6ea9c8d05a175c64
|
TypeScript
|
SD787/dnimtob
|
/server/src/endpoint/ArticleEndpoint.ts
| 2.6875
| 3
|
import { Server } from 'express';
import Sanitizer from 'sanitizer';
import EndpointUtils from './EndpointUtils';
import User from '../data/entity/User';
import Article from '../data/entity/Article';
export default class ArticleEndpoint {
static registerArticleEndpoint(app: Server): void {
app.post('/api/article/create', (req, res) => {
EndpointUtils.getUserByToken(req, res, (user) => {
const text = req.body.text;
if (text == null || typeof text != 'string' || text.length == 0 || text.length > 4096) {
return EndpointUtils.clientError(res, 'error in parameters');
}
// Everything is fine
let secureText = Sanitizer.escape(text);
let secureTextWithLHTMLLines = secureText.replace(/\n/g, '<br/>');
let newArticle = new Article({'text': secureTextWithLHTMLLines, 'user': user.id, 'date': Date.now()});
newArticle.save();
EndpointUtils.success(res);
});
});
app.get('/api/articles', (req, res) => {
EndpointUtils.getUserByToken(req, res, (user) => {
Article.findLast((err, articles) => {
if (err != null) {
return EndpointUtils.serverError(res, err);
}
EndpointUtils.sendJson(res, Article.publicFormat(articles));
});
});
});
app.get('/api/articles/skip/:skip', (req, res) => {
EndpointUtils.getUserByToken(req, res, (user) => {
var skip = req.params.skip;
if (skip == null) {
return EndpointUtils.clientError(res, 'error in parameters');
}
const skipParsed = parseInt(skip, 10);
if (isNaN(skipParsed)) {
return EndpointUtils.clientError(res, 'error in parameters');
}
Article.findSkipped(skip, (err, articles) => {
if (err != null) {
return EndpointUtils.serverError(res, err);
}
EndpointUtils.sendJson(res, Article.publicFormat(articles));
});
});
});
}
}
|
cc6ba5de31ca2b20db07da7e203766e16242d550
|
TypeScript
|
risingstar8030/Smart-Odisha-Hackathon
|
/src/app/components/map/map.component.ts
| 2.625
| 3
|
import { Component, OnInit } from '@angular/core';
import { FcrService} from '../../services/fcr.service';
import { Count} from '../../model/count';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {
constructor(
private fcrService : FcrService
) {
}
ngOnInit() {
}
latitude = 20.9517;
longitude = 85.0985;
locationChosen = false;
onChoseLocation(event) {
this.latitude = event.coords.lat;
this.longitude = event.coords.lng;
this.locationChosen = true;
}
lat: number;
lng: number;
radius : number = 15000;
color : any;
// circle = [
// {lat: 20.2961, lng: 85.8245, radius: 35000, color: 'red'},
// {lat:19.9246, lng: 85.3966, radius: 35000, color: '#551A8B'},
// ];
onSubmit(form){
const patients : Count = {
taluka : form.value.taluka,
disease : form.value.disease
}
if(form.value.taluka == 'bhubaneswar'){
this.lat = 20.2961;
this.lng = 85.8245
}
if(form.value.taluka =='tangi'){
this.lat = 19.9246;
this.lng = 85.3966;
}
this.color = null;
this.fcrService.getCountOfPatients(patients)
.subscribe(
data => {
console.log(data.count)
if(data.count == 1 ){
this.color = 'green';
}
else if(data.count >=2 && data.count <4 ){
this.color = 'yellow'
}
else{
this.color = 'red'
}
}
)
}
}
|
cc04edb3a71ab5ebbf46bd99b57f78c7a7ab7efa
|
TypeScript
|
rthreei/swc-node
|
/packages/integrate/__tests__/super/class-super.spec.ts
| 2.859375
| 3
|
import test from 'ava'
class BadRequestError extends Error {
constructor(public readonly message: string) {
super(message)
}
}
test('should handler class super', (t) => {
const message = 'Bad request'
const e = new BadRequestError(message)
t.is(e.message, message)
})
|
f3452a7f2e46186a605643ba95ad6fd43d8965ee
|
TypeScript
|
molgga/jood-appearer
|
/projects/packages/src/actor/base-actor.spec.ts
| 2.625
| 3
|
import { sleep, createEntry } from '../__testing__';
import { AppearStage } from '../stage/appear-stage'; //"projects/packages/src/stage/appear-stage";
import { AppearEvent } from '../common/types';
import { BaseActor } from './base-actor';
describe('BaseActor', () => {
let stage: AppearStage;
let dom: HTMLElement;
let actor: BaseActor;
let entry: IntersectionObserverEntry | any;
beforeEach(() => {
stage = new AppearStage();
dom = document.createElement('div');
actor = new BaseActor(dom);
entry = createEntry({ target: dom });
});
afterEach(() => {
actor.dispose();
actor = null;
stage.dispose();
stage = null;
});
it('최초 생성시 값 확인', () => {
expect(actor.element).toBe(dom);
expect(actor.isAppear).toBe(null);
});
it('stage observe 등록시 연결된 stage 확인', () => {
stage.init();
stage.observe(actor);
expect(actor.stage).toBe(stage);
});
it('appear, disappear 호출시 진입 여부 상태 확인', () => {
stage.init();
stage.observe(actor);
expect(actor.isAppear).toBe(null);
actor.appear(null);
expect(actor.isAppear).toBe(true);
actor.disappear(null);
expect(actor.isAppear).toBe(false);
});
it('appear, disappear 호출시 이벤트에 전달되는 값 확인', () => {
stage.init();
stage.observe(actor);
let subscription = actor.events.subscribe((evt: AppearEvent) => {
expect(evt.type).toBe(AppearEvent.APPEAR);
expect(evt.actor).toBe(actor);
expect(evt.entry).toBe(entry);
});
actor.appear(entry);
subscription.unsubscribe();
subscription = actor.events.subscribe((evt: AppearEvent) => {
expect(evt.type).toBe(AppearEvent.DISAPPEAR);
expect(evt.actor).toBe(actor);
expect(evt.entry).toBe(entry);
});
entry.isIntersecting = false;
actor.disappear(entry);
subscription.unsubscribe();
});
it('appear, disappear 호출시 stage 등록 상태 확인', () => {
stage.init();
stage.observe(actor);
expect(actor.stage).toBe(stage);
expect(stage.actorSize).toBe(1);
actor.appear(null);
expect(stage.actorSize).toBe(1);
actor.disappear(null);
expect(stage.actorSize).toBe(1);
});
it('appear 중복 진입 안된는것 확인', () => {
stage.init();
stage.observe(actor);
const handle = spyOn(actor, 'dispatch');
actor.appear(null);
expect(handle.calls.count()).toBe(1);
actor.appear(null);
expect(handle.calls.count()).toBe(1);
actor.disappear(null);
expect(handle.calls.count()).toBe(2);
actor.appear(null);
expect(handle.calls.count()).toBe(3);
});
});
|
a7be839abe452605e22d7a3fb4b2f4fdffc7a44a
|
TypeScript
|
planttheidea/fast-equals
|
/__tests__/comparator.ts
| 2.828125
| 3
|
import {
createEqualityComparator,
createInternalEqualityComparator,
} from '../src/comparator';
import {
areArraysEqual,
areDatesEqual,
areMapsEqual,
areObjectsEqual,
arePrimitiveWrappersEqual,
areRegExpsEqual,
areSetsEqual,
areTypedArraysEqual,
} from '../src/equals';
import { createIsCircular } from '../src/utils';
import type { InternalEqualityComparator, State } from '../src/internalTypes';
const STANDARD_COMPARATOR_OPTIONS = {
areArraysEqual,
areDatesEqual,
areMapsEqual,
areObjectsEqual,
arePrimitiveWrappersEqual,
areRegExpsEqual,
areSetsEqual,
areTypedArraysEqual,
};
const CIRCULAR_COMPARATOR_OPTIONS = {
...STANDARD_COMPARATOR_OPTIONS,
areArraysEqual: createIsCircular(areArraysEqual),
areMapsEqual: createIsCircular(areMapsEqual),
areObjectsEqual: createIsCircular(areObjectsEqual),
areSetsEqual: createIsCircular(areSetsEqual),
};
describe('createEqualityComparator', () => {
[
{
createState: <Meta>(
equals: InternalEqualityComparator<undefined>,
meta?: Meta,
) => ({
cache: undefined,
equals,
meta,
strict: false,
}),
name: 'standard',
options: STANDARD_COMPARATOR_OPTIONS,
},
{
createState: <Meta>(
equals: InternalEqualityComparator<undefined>,
meta?: Meta,
) => ({
cache: new WeakMap(),
equals,
meta: meta,
strict: false,
}),
name: 'circular',
options: CIRCULAR_COMPARATOR_OPTIONS,
},
].forEach(({ createState, name, options }) => {
describe(name, () => {
it('should default to a deep-equal setup when no equality comparator is provided', () => {
const comparator = createEqualityComparator(options);
const meta = createState(createInternalEqualityComparator(comparator));
const a = { foo: { bar: 'baz' } };
const b = { foo: { bar: 'baz' } };
expect(comparator(a, b, meta)).toBe(true);
});
it('should provide correct iteration index when comparing Map keys', () => {
const mapA = new Map([
['foo', 'bar'],
['oof', 'baz'],
]);
const mapB = new Map([
['oof', 'baz'],
['foo', 'bar'],
]);
const comparator = createEqualityComparator(options);
const state = createState(
(
a: any,
b: any,
indexOrKeyA: any,
indexOrKeyB: any,
parentA: any,
parentB: any,
state: State<undefined>,
) => {
if (
typeof indexOrKeyA === 'number' &&
typeof indexOrKeyB === 'number'
) {
// Only check key equality comparison
expect(indexOrKeyA).toBe(Array.from(parentA.keys()).indexOf(a));
expect(indexOrKeyB).toBe(Array.from(parentB.keys()).indexOf(b));
}
return comparator(a, b, state);
},
);
comparator(mapA, mapB, state);
});
});
});
describe('custom', () => {
it('should call the custom comparator with the correct params', () => {
const customComparatorMock = jest.fn();
const comparator = createEqualityComparator(STANDARD_COMPARATOR_OPTIONS);
const state: State<'META'> = {
cache: undefined,
equals(...args) {
customComparatorMock(...args);
const [a, b, , , , , meta] = args;
return comparator(a, b, meta);
},
meta: 'META',
strict: false,
};
const a = {
foo: {
bar: ['1', '2'],
baz: new Set().add('x'),
oof: new Map().set('y', 'yes'),
},
};
const b = {
foo: {
bar: ['1', '2'],
baz: new Set().add('x'),
oof: new Map().set('y', 'yes'),
},
};
const expectedParams: any = [
[a.foo, b.foo, 'foo', 'foo', a, b, state],
[a.foo.oof, b.foo.oof, 'oof', 'oof', a.foo, b.foo, state],
['y', 'y', 0, 0, a.foo.oof, b.foo.oof, state], // called with the keys of a Map
[
a.foo.oof.get('y'),
b.foo.oof.get('y'),
'y',
'y',
a.foo.oof,
b.foo.oof,
state,
],
[a.foo.baz, b.foo.baz, 'baz', 'baz', a.foo, b.foo, state],
['x', 'x', 'x', 'x', a.foo.baz, b.foo.baz, state],
[a.foo.bar, b.foo.bar, 'bar', 'bar', a.foo, b.foo, state],
[a.foo.bar[1], b.foo.bar[1], 1, 1, a.foo.bar, b.foo.bar, state],
[a.foo.bar[0], b.foo.bar[0], 0, 0, a.foo.bar, b.foo.bar, state],
];
comparator(a, b, state);
expect(customComparatorMock.mock.calls).toEqual(expectedParams);
});
});
});
|
1b6f48c698865deabc98b95683729352a474e5b0
|
TypeScript
|
a-type/graphql-arangodb
|
/src/errors.ts
| 2.953125
| 3
|
export class FieldMissingError extends Error {
constructor(typeName: string, fieldName: string) {
super(
`Invalid state: field "${fieldName}" does not exist on type "${typeName}"`
);
}
}
|
9964cccc60323667c58defca3638b97edf1730ec
|
TypeScript
|
CodeStompNJ/Hermes-UI
|
/src/app/home/chat.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ChatService {
constructor(private httpClient: HttpClient) {}
// defaulting to group 1 until we have more groups, later we should fail out here.
getHistory(groupID = 1): Observable<any> {
// returns object Object
return this.httpClient
.cache()
.get(`/history/${groupID}`)
.pipe(
map((body: any) => body), // @TODO: convert to message obect here
catchError(() => of('Error, could not load history :-('))
);
}
/**
* Post a new message
* @param message text of message
* @param username name of user
* Right now the data being sent to server is hardcoded
*/
postMessage(message: string, username: string = 'test'): Observable<any> {
return this.httpClient.post('/message', {
email: 'test@test.com',
username,
group: 'general',
message
});
}
}
|
3f584f760366fbfbeeb700e34e425e4268428162
|
TypeScript
|
cortezaproject/corteza-server-corredor
|
/src/services/dependencies.ts
| 2.671875
| 3
|
import { BaseLogger } from 'pino'
import watch from 'node-watch'
import glob from 'glob'
import path from 'path'
import { spawnSync } from 'child_process'
interface CtorArgs {
logger: BaseLogger;
searchPaths: string[];
}
interface WatchCallback {
(path: string): void;
}
/**
* Utility function for flatting w/ Array.reduce
*/
const flatten = (r, p): string => r.concat(p)
export default class Dependencies {
protected searchPaths: string[] = [];
protected readonly log: BaseLogger;
constructor ({ logger, searchPaths }: CtorArgs) {
this.searchPaths = searchPaths
this.log = logger.child({ name: 'services.dependencies' })
this.log.debug('initializing')
}
/**
* Find all package.json files under all search paths
*/
getPackageJsonFiles (): string[] {
const opt = {
// Ignore node_modules
ignore: '**/node_modules/**',
// Only interested in files
nodir: true,
}
return this.searchPaths
// run all paths through glob
.map(sp => glob.sync(path.join(sp, '**', 'package.json'), opt))
// flatten glob results (expanding search paths) of each search path
.reduce(flatten, [])
}
/**
* Installs packages
*
* @todo check what happens with require cache after new yarn install
* it might be a problem
*
* @param pkgJsonPath - path to package.json
*/
install (pkgJsonPath: string): void {
const args = [
'install',
'--json',
'--force',
'--silent',
'--emoji', 'off',
'--no-progress',
]
const opts = {
cwd: path.dirname(pkgJsonPath),
}
const log = this.log.child({ path: pkgJsonPath })
const yarn = spawnSync('yarn', args, opts)
const stderr = yarn.stderr.toString()
const stdout = yarn.stdout.toString()
const nmdir = path.join(path.dirname(pkgJsonPath), 'node_modules')
if (stderr.length > 0) {
log.error('err' + stderr)
} else if (stdout.length > 0) {
stdout
.split('\n')
.filter(line => line.length > 0)
.map(line => JSON.parse(line))
.filter(({ type }) => type === 'step')
.forEach(({ data }) => log.debug(data.message))
}
// Purge require cache -- remove all files that are in the
//
Object
.getOwnPropertyNames(require.cache)
.filter(path => path.substr(0, nmdir.length) === nmdir)
.forEach((filename) => {
delete require.cache[filename]
})
}
/**
* Watches all loaded package.json files
*
* Function installs dependencies on change and resolves
*
* @return path to changed file
*/
watch (callback: WatchCallback): void {
this.log.info('initializing watcher')
process.on('SIGINT', watch(
this.getPackageJsonFiles(),
{
persistent: false,
recursive: false,
delay: 1000,
filter: /\/package\.json$/,
},
(eventType, filename) => {
switch (eventType) {
case 'update':
delete require.cache[require.resolve(filename)]
this.install(filename)
callback(filename)
break
}
},
).close)
}
}
|