Datasets:

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
8cdc47a51a44d403594d37cb5d2c313bf43c9efd
TypeScript
laszlokiraly/functional-ts
/src/averageSalary.ts
3.015625
3
import {Employee} from './employee'; import {Department} from './department'; import {Predicate, and} from './predicate'; import {average} from './util'; function averageSalaryBEFORE(employees: Employee[], minSalary: number, department?: Department): number { let total = 0; let count = 0; employees.forEach((e) => { if (minSalary <= e.salary && (department === undefined || department.works(e))) { total += e.salary; count += 1; } }); return total === 0 ? 0 : total / count; } function employeeSalaries(employees: Employee[], conditions: Predicate[]): number[] { const filteredEmployees = employees.filter(and(conditions)); return filteredEmployees.map(employee => employee.salary); } function averageSalaryAFTER(employees: Employee[], conditions: Predicate[]): number { return average(employeeSalaries(employees, conditions)); } export {averageSalaryAFTER, averageSalaryBEFORE};
215b87dd853ba2d387eefd983723db5e498d3ee3
TypeScript
supasympa/ts-webpack-monorepo
/components/services/hello-world-service/src/adapters/ExpressRoutes.ts
2.53125
3
import {Customer, Person} from '@foo/domain'; import * as Express from 'express'; import {HelloWorldService} from '../HelloWorldService'; export interface HelloWorldServiceResponse { reply: string; } export function applyHelloWorldRouteHandlersTo(app: Express.Application): void { app.post('/hello', (req: Express.Request, res: Express.Response) => { const hws = new HelloWorldService(); const person = req.body as Person; res.status(200).send({ reply: hws.hello(Customer.from(person)), } as HelloWorldServiceResponse); }); }
de465b73dd3aaa814426181f6126ff4893219f95
TypeScript
bodekbeska/securityadmin
/src/app/sorter.service.ts
2.65625
3
import { Injectable } from '@angular/core'; @Injectable() export class SorterService { ascdesc : boolean; constructor() { } private dynamicSort(property) { var sortOrder = 1; if(property[0] === "-") { sortOrder = -1; property = property.substr(1); } return function (a,b) { var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; return result * sortOrder; } } sort(table, column){ this.ascdesc=!this.ascdesc; this.ascdesc ? column=column : column='-'+column; table.sort(this.dynamicSort(column)); } }
6a1e5602ed34a3abf013ad73569b3e82c52180a6
TypeScript
MunChanggyun/Muns
/letmeknow/back/src/lib/common.ts
3.1875
3
export const getDateYYYYMMDD = (addDate: number, addType:string, oriDate:Date) => { const year = addType === "Y" ? oriDate.getFullYear() + addDate : oriDate.getFullYear(); const month = addType === "M" ? oriDate.getMonth() + 1 + addDate : oriDate.getMonth() + 1; const day = addType === "M" ? oriDate.getDay() + addDate : oriDate.getDay(); const returnDate = year + "" + (month < 10 ? "0" + month : month) + "" + (day < 10 ? "0" + day : day) return returnDate; }
2d7a3aa00ee09a75c61e0404f5e90f677e6bb083
TypeScript
olivmonnier/composition
/src/String/capitalize.ts
3.484375
3
/** * @description * capitalizes the first letter of a string. * @example * capitalize('fooBar'); // 'FooBar' * capitalize('fooBar', true); // 'Foobar' */ export function capitalize([first, ...rest]: string): string { return first.toUpperCase() + rest.join(""); }
98f0283f987226f1db595afafd0c2fae9c72600f
TypeScript
capricorn86/happy-dom
/packages/happy-dom/src/fetch/utilities/FetchBodyUtility.ts
2.9375
3
import MultipartFormDataParser from '../multipart/MultipartFormDataParser.js'; import Stream from 'stream'; import { URLSearchParams } from 'url'; import FormData from '../../form-data/FormData.js'; import Blob from '../../file/Blob.js'; import DOMException from '../../exception/DOMException.js'; import DOMExceptionNameEnum from '../../exception/DOMExceptionNameEnum.js'; import IRequestBody from '../types/IRequestBody.js'; import IResponseBody from '../types/IResponseBody.js'; import Request from '../Request.js'; /** * Fetch body utility. */ export default class FetchBodyUtility { /** * Parses body and returns stream and type. * * Based on: * https://github.com/node-fetch/node-fetch/blob/main/src/body.js (MIT) * * @param body Body. * @returns Stream and type. */ public static getBodyStream(body: IRequestBody | IResponseBody): { contentType: string; contentLength: number | null; stream: Stream.Readable; buffer: Buffer | null; } { if (body === null || body === undefined) { return { stream: null, buffer: null, contentType: null, contentLength: null }; } else if (body instanceof URLSearchParams) { const buffer = Buffer.from(body.toString()); return { buffer, stream: Stream.Readable.from(Buffer.from(buffer)), contentType: 'application/x-www-form-urlencoded;charset=UTF-8', contentLength: buffer.length }; } else if (body instanceof Blob) { const buffer = (<Blob>body)._buffer; return { buffer, stream: Stream.Readable.from(buffer), contentType: (<Blob>body).type, contentLength: body.size }; } else if (Buffer.isBuffer(body)) { return { buffer: body, stream: Stream.Readable.from(body), contentType: null, contentLength: body.length }; } else if (body instanceof ArrayBuffer) { const buffer = Buffer.from(body); return { buffer, stream: Stream.Readable.from(buffer), contentType: null, contentLength: body.byteLength }; } else if (ArrayBuffer.isView(body)) { const buffer = Buffer.from(body.buffer, body.byteOffset, body.byteLength); return { buffer, stream: Stream.Readable.from(buffer), contentType: null, contentLength: body.byteLength }; } else if (body instanceof Stream.Stream) { return { buffer: null, stream: <Stream.Readable>body, contentType: null, contentLength: null }; } else if (body instanceof FormData) { return MultipartFormDataParser.formDataToStream(body); } const buffer = Buffer.from(String(body)); return { buffer, stream: Stream.Readable.from(buffer), contentType: 'text/plain;charset=UTF-8', contentLength: buffer.length }; } /** * Clones a request body stream. * * @param request Request. * @returns Stream. */ public static cloneRequestBodyStream(request: Request): Stream.Readable { if (request.bodyUsed) { throw new DOMException( `Failed to clone body stream of request: Request body is already used.`, DOMExceptionNameEnum.invalidStateError ); } const p1 = new Stream.PassThrough(); const p2 = new Stream.PassThrough(); request.body.pipe(p1); request.body.pipe(p2); // Sets the body of the cloned request to the first pass through stream. (<Stream.Readable>request.body) = p1; // Returns the clone. return p2; } /** * Consume and convert an entire Body to a Buffer. * * Based on: * https://github.com/node-fetch/node-fetch/blob/main/src/body.js (MIT) * * @see https://fetch.spec.whatwg.org/#concept-body-consume-body * @param body Body stream. * @returns Promise. */ public static async consumeBodyStream(body: Stream.Readable | null): Promise<Buffer> { if (body === null || !(body instanceof Stream.Stream)) { return Buffer.alloc(0); } const chunks = []; let bytes = 0; try { for await (const chunk of body) { bytes += chunk.length; chunks.push(chunk); } } catch (error) { if (error instanceof DOMException) { throw error; } throw new DOMException( `Failed to read response body. Error: ${error.message}.`, DOMExceptionNameEnum.encodingError ); } if ( (<Stream.Readable>body).readableEnded === false || (<Stream.Readable>body)['_readableState']?.ended === false ) { throw new DOMException( `Premature close of server response.`, DOMExceptionNameEnum.invalidStateError ); } try { if (typeof chunks[0] === 'string') { return Buffer.from(chunks.join('')); } return Buffer.concat(chunks, bytes); } catch (error) { throw new DOMException( `Could not create Buffer from response body. Error: ${error.message}.`, DOMExceptionNameEnum.invalidStateError ); } } }
f0af70f00b2f467a70a2a2500cd3b3742333bb0e
TypeScript
blslade-neumont/turbo-winner
/frontend/src/utils/get-cookie.ts
2.578125
3
export function getCookie(name: string): string | null { let cookieValue = '; ' + document.cookie; let parts = cookieValue.split(`; ${name}=`); if (parts.length === 2) return parts[1].split(';')[0]; return null; }
99f5b5497c8745110c0da71b240a0243da35c114
TypeScript
AeternaEst/Frontend-Experiments
/React/Redux-Saga/src/services/property-service.ts
2.71875
3
/* eslint-disable max-len */ import { Property } from "../types/property"; import { Comment } from "../types/comment"; import sleep from "../utils/general-utils"; import { cityNames, propertyDatabase, streetNames, zipCodes, } from "../data/database"; export default class PropertyService { getProperties = (): Promise<Property[]> => new Promise((resolve) => { setTimeout(() => { resolve(propertyDatabase); }, 2000); }); addFavoriteProperty = (propertyId: number): Promise<void> => new Promise((resolve, reject) => { setTimeout(() => { const propertyToFavorite = propertyDatabase.find( (property) => property.id === propertyId ); if (propertyToFavorite) { propertyToFavorite.isFavorite = true; resolve(); } reject(new Error("Property not found")); }, 2000); }); addPropertyComment = (propertyId: number, comment: Comment): Promise<void> => new Promise((resolve, reject) => { setTimeout(() => { const propertyToAddComment = propertyDatabase.find( (property) => property.id === propertyId ); if (propertyToAddComment) { propertyToAddComment.comments = [ ...propertyToAddComment.comments, comment, ]; resolve(); } reject(new Error("Property not found")); }, 2000); }); getStreetName = async (propertyId: number): Promise<string> => { const sleepTime = Math.random() * 2000; await sleep(sleepTime); return streetNames[propertyId + -1]; }; getCity = async (propertyId: number): Promise<string> => { const sleepTime = Math.random() * 2000; await sleep(sleepTime); return cityNames[propertyId + -1]; }; getZip = async (propertyId: number): Promise<string> => { const sleepTime = Math.random() * 5000; await sleep(sleepTime); return zipCodes[propertyId + -1]; }; }
5e1af64040fde31629ac8f7b16568ce8bbb2e3d9
TypeScript
wesherwo/dynamic-forms
/src/app/services/control.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { Dropdown } from '../controls/dropdown'; import { Textbox } from '../controls/textbox'; import { Radio } from '../controls/radio'; import { StarRating } from '../controls/star-rating'; import { ControlBase } from '../controls/control-base'; import { DateRange } from '../controls/date-range'; import { Checkbox } from '../controls/checkbox'; import { DatePicker } from '../controls/date-picker'; import { Slider } from '../controls/slider'; import { Toggle } from '../controls/toggle'; @Injectable() export class ControlService { getControls(jsonData) { let controls: ControlBase<any>[] = []; for (let i = 0; i < jsonData.length; i++) { let type = jsonData[i].type; if (type == "Textbox") { controls.push(new Textbox(jsonData[i].options)); } if (type == "Dropdown") { controls.push(new Dropdown(jsonData[i].options)); } if (type == "Radio") { controls.push(new Radio(jsonData[i].options)); } if (type == "StarRating") { controls.push(new StarRating(jsonData[i].options)); } if (type == "DateRange") { controls.push(new DateRange(jsonData[i].options)); } if (type == "Checkbox") { controls.push(new Checkbox(jsonData[i].options)); } if (type == "Datepicker") { controls.push(new DatePicker(jsonData[i].options)); } if (type == "Slider") { controls.push(new Slider(jsonData[i].options)); } if (type == "Toggle") { controls.push(new Toggle(jsonData[i].options)); } } return controls.sort((a, b) => a.order - b.order); } }
490b04b6b145facaef09ffdfe28de3e3ae06b54d
TypeScript
MichaelBone/district_council_of_streaky_bay_sa_development_applications
/scraper.ts
2.9375
3
// Parses the development applications at the South Australian District Council of Streaky Bay web // site and places them in a database. // // Michael Bone // 15th March 2019 "use strict"; import * as fs from "fs"; import * as cheerio from "cheerio"; import * as request from "request-promise-native"; import * as sqlite3 from "sqlite3"; import * as urlparser from "url"; import * as moment from "moment"; import * as pdfjs from "pdfjs-dist"; import didYouMean, * as didyoumean from "didyoumean2"; sqlite3.verbose(); const DevelopmentApplicationsUrl = "https://www.streakybay.sa.gov.au/council-services/development"; const CommentUrl = "mailto:dcstreaky@streakybay.sa.gov.au"; declare const process: any; // All valid street names, street suffixes, suburb names and hundred names. let StreetNames = null; let StreetSuffixes = null; let SuburbNames = null; let HundredNames = null; // Sets up an sqlite database. async function initializeDatabase() { return new Promise((resolve, reject) => { let database = new sqlite3.Database("data.sqlite"); database.serialize(() => { database.run("create table if not exists [data] ([council_reference] text primary key, [address] text, [description] text, [info_url] text, [comment_url] text, [date_scraped] text, [date_received] text)"); resolve(database); }); }); } // Inserts a row in the database if the row does not already exist. async function insertRow(database, developmentApplication) { return new Promise((resolve, reject) => { let sqlStatement = database.prepare("insert or replace into [data] values (?, ?, ?, ?, ?, ?, ?)"); sqlStatement.run([ developmentApplication.applicationNumber, developmentApplication.address, developmentApplication.description, developmentApplication.informationUrl, developmentApplication.commentUrl, developmentApplication.scrapeDate, developmentApplication.receivedDate ], function(error, row) { if (error) { console.error(error); reject(error); } else { console.log(` Saved application \"${developmentApplication.applicationNumber}\" with address \"${developmentApplication.address}\", description \"${developmentApplication.description}\" and received date \"${developmentApplication.receivedDate}\" to the database.`); sqlStatement.finalize(); // releases any locks resolve(row); } }); }); } // A bounding rectangle. interface Rectangle { x: number, y: number, width: number, height: number } // An element (consisting of text and a bounding rectangle) in a PDF document. interface Element extends Rectangle { text: string } // Constructs a rectangle based on the intersection of the two specified rectangles. function intersect(rectangle1: Rectangle, rectangle2: Rectangle): Rectangle { let x1 = Math.max(rectangle1.x, rectangle2.x); let y1 = Math.max(rectangle1.y, rectangle2.y); let x2 = Math.min(rectangle1.x + rectangle1.width, rectangle2.x + rectangle2.width); let y2 = Math.min(rectangle1.y + rectangle1.height, rectangle2.y + rectangle2.height); if (x2 >= x1 && y2 >= y1) return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }; else return { x: 0, y: 0, width: 0, height: 0 }; } // Calculates the fraction of an element that lies within a rectangle (as a percentage). For // example, if a quarter of the specifed element lies within the specified rectangle then this // would return 25. function getPercentageOfElementInRectangle(element: Element, rectangle: Rectangle) { let elementArea = getArea(element); let intersectionArea = getArea(intersect(rectangle, element)); return (elementArea === 0) ? 0 : ((intersectionArea * 100) / elementArea); } // Calculates the area of a rectangle. function getArea(rectangle: Rectangle) { return rectangle.width * rectangle.height; } // Parses the details from the elements associated with a single page of the PDF (corresponding // to a single development application). function parseOldFormatApplicationElements(elements: Element[], informationUrl: string) { // Get the application number (by finding all elements that are at least 10% within the // calculated bounding rectangle). let applicationHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "applicationnumber:"); let applicationFeesHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "applicationfees:"); let applicationDateHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "applicationdate:"); let developmentCompletedHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "developmentcompleted:"); let propertyAddressHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "propertyaddress:"); let developmentDescriptionHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "developmentdescription:"); let relevantAuthorityHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "relevantauthority:"); // Get the development application number. if (applicationHeadingElement === undefined) { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the "Application Number" heading is missing. Elements: ${elementSummary}`); return undefined; } let applicationNumber = ""; let applicationNumberBounds = { x: applicationHeadingElement.x + applicationHeadingElement.width, y: applicationHeadingElement.y, width: (applicationFeesHeadingElement === undefined) ? (applicationHeadingElement.width * 3) : (applicationFeesHeadingElement.x - applicationHeadingElement.x - applicationHeadingElement.width), height: applicationHeadingElement.height }; let applicationNumberElement = elements.find(element => getPercentageOfElementInRectangle(element, applicationNumberBounds) > 10); applicationNumber = (applicationNumberElement === undefined) ? "" : applicationNumberElement.text.replace(/\s/g, ""); if (applicationNumber === "") { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the development application number text is missing. Elements: ${elementSummary}`); return undefined; } console.log(` Found \"${applicationNumber}\".`); // Get the received date. let receivedDate = moment.invalid(); if (applicationDateHeadingElement !== undefined) { let receivedDateBounds = { x: applicationDateHeadingElement.x + applicationDateHeadingElement.width, y: applicationDateHeadingElement.y, width: (developmentCompletedHeadingElement === undefined) ? (applicationDateHeadingElement.width * 3) : (developmentCompletedHeadingElement.x - applicationDateHeadingElement.x - applicationDateHeadingElement.width), height: applicationDateHeadingElement.height }; let receivedDateElement = elements.find(element => getPercentageOfElementInRectangle(element, receivedDateBounds) > 10); if (receivedDateElement !== undefined) receivedDate = moment(receivedDateElement.text.trim(), "D/M/YYYY", true); // allows the leading zero of the day or month to be omitted } // Get the address. if (propertyAddressHeadingElement === undefined) { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the "Property Address" heading is missing. Elements: ${elementSummary}`); return undefined; } let addressBounds = { x: propertyAddressHeadingElement.x + propertyAddressHeadingElement.width, y: propertyAddressHeadingElement.y, width: (applicationFeesHeadingElement === undefined) ? (propertyAddressHeadingElement.width * 3) : (applicationFeesHeadingElement.x - propertyAddressHeadingElement.x - propertyAddressHeadingElement.width), height: propertyAddressHeadingElement.height }; let address = elements.filter(element => getPercentageOfElementInRectangle(element, addressBounds) > 10).map(element => element.text).join(" ").trim().replace(/\s\s+/g, " "); address = formatAddress(applicationNumber, address); if (address === "") { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Could not find an address for the current development application ${applicationNumber}. The development application will be ignored. Elements: ${elementSummary}`); return undefined; } // Get the description. let description = ""; if (developmentDescriptionHeadingElement !== undefined) { let descriptionBounds = { x: developmentDescriptionHeadingElement.x + developmentDescriptionHeadingElement.width, y: developmentDescriptionHeadingElement.y, width: (applicationFeesHeadingElement === undefined) ? (developmentDescriptionHeadingElement.width * 3) : (applicationFeesHeadingElement.x - developmentDescriptionHeadingElement.x - developmentDescriptionHeadingElement.width), height: (relevantAuthorityHeadingElement === undefined) ? Number.MAX_VALUE : (relevantAuthorityHeadingElement.y - developmentDescriptionHeadingElement.y) }; description = elements.filter(element => getPercentageOfElementInRectangle(element, descriptionBounds) > 10).map(element => element.text).join(" ").trim().replace(/\s\s+/g, " "); } return { applicationNumber: applicationNumber, address: address, description: (description === "") ? "No description provided" : description, informationUrl: informationUrl, commentUrl: CommentUrl, scrapeDate: moment().format("YYYY-MM-DD"), receivedDate: receivedDate.isValid() ? receivedDate.format("YYYY-MM-DD") : "" } } // Parses the details from the elements associated with a single page of the PDF (corresponding // to a single development application). function parseNewFormatApplicationElements(elements: Element[], informationUrl: string) { // Get the application number (by finding all elements that are at least 10% within the // calculated bounding rectangle). let applicationHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "").startsWith("development")); let applicationDateHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "applicationdate"); let assessmentNumberHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "assessmentnumber"); let developmentDescriptionHeadingElement = elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "developmentdescription"); // Get the development application number. if (applicationHeadingElement === undefined) { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the "Development" heading is missing. Elements: ${elementSummary}`); return undefined; } let applicationNumber = ""; let tokens = applicationHeadingElement.text.trim().replace(/\s\s+/g, " ").split(" "); if (tokens.length >= 2) applicationNumber = tokens[1]; else { let applicationNumberBounds = { x: applicationHeadingElement.x + applicationHeadingElement.width, y: applicationHeadingElement.y, width: (applicationDateHeadingElement === undefined) ? (applicationHeadingElement.width * 3) : (applicationDateHeadingElement.x - applicationHeadingElement.x - applicationHeadingElement.width), height: applicationHeadingElement.height }; let applicationNumberElement = elements.find(element => getPercentageOfElementInRectangle(element, applicationNumberBounds) > 10); applicationNumber = (applicationNumberElement === undefined) ? "" : applicationNumberElement.text.replace(/\s/g, ""); } if (applicationNumber === "") { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the development application number text is missing. Elements: ${elementSummary}`); return undefined; } console.log(` Found \"${applicationNumber}\".`); // Get the received date. let receivedDate = moment.invalid(); if (applicationDateHeadingElement !== undefined) { let receivedDateBounds = { x: applicationDateHeadingElement.x + applicationDateHeadingElement.width, y: applicationDateHeadingElement.y, width: Number.MAX_VALUE, height: applicationDateHeadingElement.height }; let receivedDateElement = elements.find(element => getPercentageOfElementInRectangle(element, receivedDateBounds) > 10); if (receivedDateElement !== undefined) receivedDate = moment(receivedDateElement.text.trim(), "D/M/YYYY", true); // allows the leading zero of the day or month to be omitted } // Get the address. if (assessmentNumberHeadingElement === undefined) { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Ignoring the page because the "Assessment Number" heading is missing. Elements: ${elementSummary}`); return undefined; } let addressBounds = { x: assessmentNumberHeadingElement.x + assessmentNumberHeadingElement.width, y: assessmentNumberHeadingElement.y + assessmentNumberHeadingElement.height, width: Number.MAX_VALUE, height: (developmentDescriptionHeadingElement === undefined) ? 2 * assessmentNumberHeadingElement.height : (developmentDescriptionHeadingElement.y - (assessmentNumberHeadingElement.y + assessmentNumberHeadingElement.height)) }; let address = elements.filter(element => getPercentageOfElementInRectangle(element, addressBounds) > 10).map(element => element.text).join(" ").trim().replace(/\s\s+/g, " "); address = formatAddress(applicationNumber, address); if (address === "") { let elementSummary = elements.map(element => `[${element.text}]`).join(""); console.log(`Could not find an address for the current development application ${applicationNumber}. The development application will be ignored. Elements: ${elementSummary}`); return undefined; } // Get the description. let description = ""; if (developmentDescriptionHeadingElement !== undefined) { let descriptionBounds = { x: developmentDescriptionHeadingElement.x + developmentDescriptionHeadingElement.width, y: developmentDescriptionHeadingElement.y, width: Number.MAX_VALUE, height: developmentDescriptionHeadingElement.height }; description = elements.filter(element => getPercentageOfElementInRectangle(element, descriptionBounds) > 10).map(element => element.text).join(" ").trim().replace(/\s\s+/g, " "); } return { applicationNumber: applicationNumber, address: address, description: (description === "") ? "No description provided" : description, informationUrl: informationUrl, commentUrl: CommentUrl, scrapeDate: moment().format("YYYY-MM-DD"), receivedDate: receivedDate.isValid() ? receivedDate.format("YYYY-MM-DD") : "" } } // Formats (and corrects) an address. function formatAddress(applicationNumber: string, address: string) { address = address.trim().replace(/[-–]+$/, "").replace(/\s\s+/g, " ").trim(); // remove trailing dashes and multiple white space characters if (address.replace(/[\s,0-]/g, "") === "" || address.startsWith("No Residential Address")) // ignores addresses such as "0 0, 0" and "-" return ""; // Remove the comma in house numbers larger than 1000. For example, the following addresses: // // 4,665 Princes HWY MENINGIE 5264 // 11,287 Princes HWY SALT CREEK 5264 // // would be converted to the following: // // 4665 Princes HWY MENINGIE 5264 // 11287 Princes HWY SALT CREEK 5264 if (/^\d,\d\d\d/.test(address)) address = address.substring(0, 1) + address.substring(2); else if (/^\d\d,\d\d\d/.test(address)) address = address.substring(0, 2) + address.substring(3); let tokens = address.split(" "); let postCode = undefined; let token = tokens.pop(); if (token === undefined) return address; if (/^\d\d\d\d$/.test(token)) postCode = token; else tokens.push(token); // Ensure that a state code is added before the post code if a state code is not present. let state = "SA"; token = tokens.pop(); if (token === undefined) return address; if ([ "ACT", "NSW", "NT", "QLD", "SA", "TAS", "VIC", "WA" ].includes(token.toUpperCase())) state = token.toUpperCase(); else tokens.push(token); // Construct a fallback address to be used if the suburb name cannot be determined later. let fallbackAddress = (postCode === undefined) ? address : [ ...tokens, state, postCode].join(" ").trim(); // Pop tokens from the end of the array until a valid suburb name is encountered (allowing // for a few spelling errors). Note that this starts by examining for longer matches // (consisting of four tokens) before examining shorter matches. This approach ensures // that the following address: // // 2,800 Woods Well RD COLEBATCH 5266 // // is correctly converted to the following address: // // 2800 WOODS WELL ROAD, COLEBATCH SA 5266 // // rather than (incorrectly) to the following address (notice that the street name has "BELL" // instead of "WELL" because there actually is a street named "BELL ROAD"). // // 2800 Woods BELL ROAD, COLEBATCH SA 5266 // // This also allows for addresses that contain hundred names such as the following: // // Sec 26 Hd Palabie // Lot no 1, Standley Road, Sect 16, Hundred of Pygery let suburbName = undefined; let hasHundredName = false; for (let index = 4; index >= 1; index--) { let tryHundredName = tokens.slice(-index).join(" ").toUpperCase(); if (tryHundredName.startsWith("HD OF ") || tryHundredName.startsWith("HUNDRED OF") || tryHundredName.startsWith("HD ") || tryHundredName.startsWith("HUNDRED ")) { tryHundredName = tryHundredName.replace(/^HD OF /, "").replace(/^HUNDRED OF /, "").replace(/^HD /, "").replace(/^HUNDRED /, "").trim(); let hundredNameMatch = <string>didYouMean(tryHundredName, Object.keys(HundredNames), { caseSensitive: false, returnType: didyoumean.ReturnTypeEnums.FIRST_CLOSEST_MATCH, thresholdType: didyoumean.ThresholdTypeEnums.EDIT_DISTANCE, threshold: 1, trimSpaces: true }); if (hundredNameMatch !== null) { hasHundredName = true; let suburbNames = HundredNames[hundredNameMatch]; if (suburbNames.length === 1) { // if a unique suburb exists for the hundred then use that suburb suburbName = SuburbNames[suburbNames[0]]; tokens.splice(-index, index); // remove elements from the end of the array } break; } } } // Only search for a suburb name if there was no hundred name (because a suburb name is // unlikely to appear before a hundred name). if (!hasHundredName) { for (let index = 4; index >= 1; index--) { let trySuburbName = tokens.slice(-index).join(" "); let suburbNameMatch = <string>didYouMean(trySuburbName, Object.keys(SuburbNames), { caseSensitive: false, returnType: didyoumean.ReturnTypeEnums.FIRST_CLOSEST_MATCH, thresholdType: didyoumean.ThresholdTypeEnums.EDIT_DISTANCE, threshold: 1, trimSpaces: true }); if (suburbNameMatch !== null) { suburbName = SuburbNames[suburbNameMatch]; tokens.splice(-index, index); // remove elements from the end of the array break; } } } // Expand any street suffix (for example, this converts "ST" to "STREET"). token = tokens.pop(); if (token !== undefined) { token = token.trim().replace(/,+$/, "").trim(); // removes trailing commas let streetSuffix = StreetSuffixes[token.toUpperCase()]; if (streetSuffix === undefined) streetSuffix = Object.values(StreetSuffixes).find(streetSuffix => streetSuffix === token.toUpperCase()); // the street suffix is already expanded if (streetSuffix === undefined) tokens.push(token); // unrecognised street suffix else tokens.push(streetSuffix); // add back the expanded street suffix } // Pop tokens from the end of the array until a valid street name is encountered (allowing // for a few spelling errors). Similar to the examination of suburb names, this examines // longer matches before examining shorter matches (for the same reason). let streetName = undefined; for (let index = 5; index >= 1; index--) { let tryStreetName = tokens.slice(-index).join(" ").trim().replace(/,+$/, "").trim(); // allows for commas after the street name let streetNameMatch = <string>didYouMean(tryStreetName, Object.keys(StreetNames), { caseSensitive: false, returnType: didyoumean.ReturnTypeEnums.FIRST_CLOSEST_MATCH, thresholdType: didyoumean.ThresholdTypeEnums.EDIT_DISTANCE, threshold: 1, trimSpaces: true }); if (streetNameMatch !== null) { streetName = streetNameMatch; let suburbNames = StreetNames[streetNameMatch]; tokens.splice(-index, index); // remove elements from the end of the array // If the suburb was not determined earlier then attempt to obtain the suburb based // on the street (ie. if there is only one suburb associated with the street). For // example, this would automatically add the suburb to "22 Jefferson CT 5263", // producing the address "22 JEFFERSON COURT, WELLINGTON EAST SA 5263". if (suburbName === undefined && suburbNames.length === 1) suburbName = SuburbNames[suburbNames[0]]; break; } } // If a post code was included in the original address then use it to override the post code // included in the suburb name (because the post code in the original address is more likely // to be correct). if (postCode !== undefined && suburbName !== undefined) suburbName = suburbName.replace(/\s+\d\d\d\d$/, " " + postCode); // Do not allow an address that does not have a suburb name. if (suburbName === undefined) { console.log(`Ignoring the development application "${applicationNumber}" because a suburb name could not be determined for the address: ${address}`); return ""; } // Reconstruct the address with a comma between the street address and the suburb. if (suburbName === undefined || suburbName.trim() === "") address = fallbackAddress; else { if (streetName !== undefined && streetName.trim() !== "") tokens.push(streetName); let streetAddress = tokens.join(" ").trim().replace(/,+$/, "").trim(); // removes trailing commas address = streetAddress + (streetAddress === "" ? "" : ", ") + suburbName; } // Ensure that the address includes the state "SA". if (address !== "" && !/\bSA\b/g.test(address)) address += " SA"; return address; } // Parses the development applications in the specified date range. async function parsePdf(url: string) { console.log(`Reading development applications from ${url}.`); let developmentApplications = []; // Read the PDF. let buffer = await request({ url: url, encoding: null, proxy: process.env.MORPH_PROXY }); await sleep(2000 + getRandom(0, 5) * 1000); // Parse the PDF. Each page has the details of multiple applications. Note that the PDF is // re-parsed on each iteration of the loop (ie. once for each page). This then avoids large // memory usage by the PDF (just calling page._destroy() on each iteration of the loop appears // not to be enough to release all memory used by the PDF parsing). for (let pageIndex = 0; pageIndex < 100; pageIndex++) { // limit to an arbitrarily large number of pages (to avoid any chance of an infinite loop) let pdf = await pdfjs.getDocument({ data: buffer, disableFontFace: true, ignoreErrors: true }); if (pageIndex >= pdf.numPages) break; console.log(`Reading and parsing applications from page ${pageIndex + 1} of ${pdf.numPages}.`); let page = await pdf.getPage(pageIndex + 1); let textContent = await page.getTextContent(); let viewport = await page.getViewport(1.0); let elements: Element[] = textContent.items.map(item => { let transform = pdfjs.Util.transform(viewport.transform, item.transform); // Work around the issue https://github.com/mozilla/pdf.js/issues/8276 (heights are // exaggerated). The problem seems to be that the height value is too large in some // PDFs. Provide an alternative, more accurate height value by using a calculation // based on the transform matrix. let workaroundHeight = Math.sqrt(transform[2] * transform[2] + transform[3] * transform[3]); return { text: item.str, x: transform[4], y: transform[5], width: item.width, height: workaroundHeight }; }); // Release the memory used by the PDF now that it is no longer required (it will be // re-parsed on the next iteration of the loop for the next page). await pdf.destroy(); if (global.gc) global.gc(); // Sort the elements by Y co-ordinate and then by X co-ordinate. let elementComparer = (a, b) => (a.y > b.y) ? 1 : ((a.y < b.y) ? -1 : ((a.x > b.x) ? 1 : ((a.x < b.x) ? -1 : 0))); elements.sort(elementComparer); let developmentApplication = undefined; if (elements.find(element => element.text.toLowerCase().replace(/\s/g, "") === "applicationfees:") === undefined) developmentApplication = parseNewFormatApplicationElements(elements, url); else developmentApplication = parseOldFormatApplicationElements(elements, url); if (developmentApplication !== undefined) if (!developmentApplications.some(otherDevelopmentApplication => otherDevelopmentApplication.applicationNumber === developmentApplication.applicationNumber)) // ignore duplicates developmentApplications.push(developmentApplication); } return developmentApplications; } // Gets a random integer in the specified range: [minimum, maximum). function getRandom(minimum: number, maximum: number) { return Math.floor(Math.random() * (Math.floor(maximum) - Math.ceil(minimum))) + Math.ceil(minimum); } // Pauses for the specified number of milliseconds. function sleep(milliseconds: number) { return new Promise(resolve => setTimeout(resolve, milliseconds)); } // Parses the development applications. async function main() { // Ensure that the database exists. let database = await initializeDatabase(); // Read the files containing all possible street names, street suffixes, suburb names and // hundred names. Note that these are not currently used. StreetNames = {}; for (let line of fs.readFileSync("streetnames.txt").toString().replace(/\r/g, "").trim().split("\n")) { let streetNameTokens = line.toUpperCase().split(","); let streetName = streetNameTokens[0].trim(); let suburbName = streetNameTokens[1].trim(); (StreetNames[streetName] || (StreetNames[streetName] = [])).push(suburbName); // several suburbs may exist for the same street name } StreetSuffixes = {}; for (let line of fs.readFileSync("streetsuffixes.txt").toString().replace(/\r/g, "").trim().split("\n")) { let streetSuffixTokens = line.toUpperCase().split(","); StreetSuffixes[streetSuffixTokens[0].trim()] = streetSuffixTokens[1].trim(); } SuburbNames = {}; for (let line of fs.readFileSync("suburbnames.txt").toString().replace(/\r/g, "").trim().split("\n")) { let suburbTokens = line.toUpperCase().split(","); SuburbNames[suburbTokens[0].trim()] = suburbTokens[1].trim(); } HundredNames = {}; for (let line of fs.readFileSync("hundrednames.txt").toString().replace(/\r/g, "").trim().split("\n")) { let hundredNameTokens = line.toUpperCase().split(","); HundredNames[hundredNameTokens[0].trim()] = hundredNameTokens[1].trim().split(";"); } // Read the main page that has links to each year of development applications. console.log(`Retrieving page: ${DevelopmentApplicationsUrl}`); let body = await request({ url: DevelopmentApplicationsUrl, rejectUnauthorized: false, proxy: process.env.MORPH_PROXY }); await sleep(2000 + getRandom(0, 5) * 1000); let $ = cheerio.load(body); let yearPageUrls: string[] = []; for (let element of $("div.unityHtmlArticle p a").get()) { let yearPageUrl = new urlparser.URL(element.attribs.href, DevelopmentApplicationsUrl).href if ($(element).text().toLowerCase().includes("register")) if (!yearPageUrls.some(url => url === yearPageUrl)) yearPageUrls.push(yearPageUrl); } if (yearPageUrls.length === 0) { console.log("No PDF files were found to examine."); return; } // Select the current year and randomly select one other year (this is purposely allowed to // even be the same year as the current year). let currentYearPageUrl = yearPageUrls[0]; let randomYearPageUrl = yearPageUrls[getRandom(0, yearPageUrls.length)]; let selectedPdfUrls: string[] = []; // Read the current year page and select the most recent PDF. console.log(`Retrieving current year page: ${currentYearPageUrl}`); body = await request({ url: currentYearPageUrl, rejectUnauthorized: false, proxy: process.env.MORPH_PROXY }); await sleep(2000 + getRandom(0, 5) * 1000); $ = cheerio.load(body); let currentYearPdfUrls: string[] = []; for (let element of $("div.unityHtmlArticle p a").get()) { let pdfUrl = new urlparser.URL(element.attribs.href, DevelopmentApplicationsUrl).href if ($(element).text().toLowerCase().includes("register") && pdfUrl.toLowerCase().includes(".pdf")) if (!currentYearPdfUrls.some(url => url === pdfUrl)) currentYearPdfUrls.push(pdfUrl); } if (currentYearPdfUrls.length > 0) { let currentYearPdfUrl = currentYearPdfUrls.pop(); selectedPdfUrls.push(currentYearPdfUrl); console.log(`Selected current year PDF: ${currentYearPdfUrl}`); } // Read the random year page and randomly select a PDF from that page. console.log(`Retrieving random year page: ${randomYearPageUrl}`); body = await request({ url: randomYearPageUrl, rejectUnauthorized: false, proxy: process.env.MORPH_PROXY }); await sleep(2000 + getRandom(0, 5) * 1000); $ = cheerio.load(body); let randomYearPdfUrls: string[] = []; for (let element of $("div.unityHtmlArticle p a").get()) { let pdfUrl = new urlparser.URL(element.attribs.href, DevelopmentApplicationsUrl).href if ($(element).text().toLowerCase().includes("register") && pdfUrl.toLowerCase().includes(".pdf")) if (!randomYearPdfUrls.some(url => url === pdfUrl)) randomYearPdfUrls.push(pdfUrl); } if (randomYearPdfUrls.length > 0) { let randomYearPdfUrl = randomYearPdfUrls[getRandom(0, randomYearPdfUrls.length)]; selectedPdfUrls.push(randomYearPdfUrl); console.log(`Selected random year PDF: ${randomYearPdfUrl}`); } // Parse the selected PDFs (avoid processing all PDFs at once because this may use too much // memory, resulting in morph.io terminating the current process). if (selectedPdfUrls.length === 0) { console.log("No PDF files were selected to be examined."); return; } for (let pdfUrl of selectedPdfUrls) { console.log(`Parsing document: ${pdfUrl}`); let developmentApplications = await parsePdf(pdfUrl); console.log(`Parsed ${developmentApplications.length} development application(s) from document: ${pdfUrl}`); // Attempt to avoid reaching 512 MB memory usage (this will otherwise result in the // current process being terminated by morph.io). if (global.gc) global.gc(); console.log(`Saving development applications to the database.`); for (let developmentApplication of developmentApplications) await insertRow(database, developmentApplication); } } main().then(() => console.log("Complete.")).catch(error => console.error(error));
411eb0a27fe303979abb456fba7c43bad0bd5fa7
TypeScript
benjamim015/WhyHome-api-2.0
/src/modules/lists/services/RemoveSeriesFromListService.ts
2.53125
3
import { inject, injectable } from 'tsyringe'; import Series from '@modules/whys/infra/typeorm/entities/Series'; import ISeriesRepository from '@modules/whys/repositories/ISeriesRepository'; import AppError from '@shared/errors/AppError'; import IListsRepository from '../repositories/IListsRepository'; interface IRequest { userId: string; seriesId: string; } @injectable() class RemoveSeriesToListService { constructor( @inject('SeriesRepository') private seriesRepository: ISeriesRepository, @inject('ListsRepository') private listsRepository: IListsRepository, ) {} public async execute({ userId, seriesId }: IRequest): Promise<Series> { const series = await this.seriesRepository.findById(seriesId); if (!series) { throw new AppError('This series does not exits!'); } const list = await this.listsRepository.findById(userId); if (!list) { throw new AppError('This list does not exits!'); } const findWhyIndex = list.whys.findIndex(why => why.id === seriesId); if (findWhyIndex <= -1) { throw new AppError('This series is not on your list'); } list.whys.splice(findWhyIndex, 1); await this.listsRepository.save(list); return series; } } export default RemoveSeriesToListService;
0da3b3f57a907cb607b8288b881ce7a81f7ab94b
TypeScript
vikaspotluri123/plant-health-monitor
/components/wrapper/lib/drone-connection.ts
2.78125
3
import {EventEmitter} from 'events'; import {isIPv4} from 'net'; import ping from './ping'; // @const POLLING_INTERVAL = 15; const POLLING_INTERVAL = 1; export class DroneConnection { public events: EventEmitter = new EventEmitter(); private connectionAddr: string; private connected = false; constructor(ip: string) { if (!isIPv4(ip)) { throw new Error('Invalid ip'); } this.connectionAddr = ip; this.ping(); } get isConnected() { return this.connected; } async ping(): Promise<void> { let canConnect = await ping(this.connectionAddr); // @todo: remove randomness // canConnect = Math.random() <= 0.5; if (canConnect) { if (!this.connected) { this.connected = true; this.events.emit('connection.restored'); } } else if (this.connected) { this.connected = false; this.events.emit('connection.lost'); } // @todo: check if we need to unref this setTimeout(() => this.ping(), 1000 * POLLING_INTERVAL); } } const instance = new DroneConnection('192.168.137.157'); export default instance;
0523467e3489d4f0eeb5330e3e55e9734a6bb91d
TypeScript
jsaunie/Restful-api-nodejs-postgresql-typescript
/src/http/controller/UserController.ts
2.890625
3
import {Request, Response} from 'express'; import {UserInstance} from "../../types/models/User"; import User from "../../database/models/User"; export default class UserController { /** * Show all users * @method GET * @param {Request} req * @param {Response} res * @return void */ public static index(req: Request, res: Response): void { User.findAll().then((users: UserInstance[]) => { res.status(200).send({ message: `All user`, users, }); }); } /** * Show user according by hid id and the id parameter * @method GET * @param {Request} req * @param {Response} res * @return void */ public static show(req: Request, res: Response): void { User.findById(req.params.id).then((user: UserInstance | null) => res.status(200).send(user)); } /** * Save a new user * @method POST * @param {Request} req * @param {Response} res * @return void */ public static add(req: Request, res: Response): void { const data = req.body; // Create User User.create(data).then(() => { res.status(200).send({ message: `User was successfully added !`, data, }); }); } /** * Update user * @method PUT * @param {Request} req * @param {Response} res * @return void */ public static update(req: Request, res: Response): void { const data = req.body; User.findById(req.params.id).then((user: UserInstance | null) => { if (user == null) { return res.status(200).send({ message: `User ${req.params.id} was not found !`, data }); } user.update(data).then(() => { res.status(200).send({ message: `User ${req.params.id} was successfully updated !`, user, data }); }); }); } /** * Delete user * @method DELETE * @param {Request} req * @param {Response} res * @return void */ public static delete(req: Request, res: Response): void { User.findById(req.params.id).then((user: UserInstance | null) => { if (user == null) { return res.status(200).send({ message: `User ${req.params.id} was not found !`, }); } user.destroy().then(() => { res.status(200).send({ message: `User ${req.params.id} was successfully deleted !` }) }); }) } }
cb0f9fefc07c6c63f3adde21004399c7cab14b08
TypeScript
AndrewVdovichenko/battle-city-game
/front/src/game/gameObjects/tree.ts
2.53125
3
import GameObject from '../gameClasses/gameObject'; import EntitySkins from '../gameEngine/engineModules/constObjects/entitySkins'; class Tree extends GameObject { size = 50; constructor(x: number, y: number, type: 'o' | 'a') { super(x, y); if (type === 'o') { this.skin = EntitySkins.treeOak; } else { this.skin = EntitySkins.treeApple; } } } export default Tree;
796f1a35bc0e06753d5ff60611fa1f937dc82d50
TypeScript
doc22940/rough-charts
/packages/react-rough-charts/stories/colors.ts
2.640625
3
const shuffle = (xs = []) => { let { length } = xs while (length > 0) { const randomIndex = Math.floor(Math.random() * length) length -= 1 const temp = xs[randomIndex] xs[randomIndex] = xs[length] // eslint-disable-line xs[length] = temp // eslint-disable-line } return xs } export const colors = shuffle([ '#fe4a49', '#2ab7ca ', '#fed766', '#fe9c8f', '#feb2a8 ', '#fec8c1', '#fad9c1', '#f9caa7', '#ee4035', '#f37736', '#fdf498 ', '#7bc043', '#0392cf', '#f6abb6', '#03396c', ])
a50555b4f83a1ad36fc6795c0ee005acd0c65a92
TypeScript
yingding/server-ml-examples
/playWithSparkMlExample/webClient/src/app/private/binding-examples/binding-child/binding-child.component.ts
2.765625
3
import { Component, OnInit, OnChanges, SimpleChange, Input } from '@angular/core'; @Component({ selector: 'app-binding-child', templateUrl: './binding-child.component.html', styleUrls: ['./binding-child.component.scss'] }) export class BindingChildComponent implements OnInit, OnChanges { // Define the property, which can be bind from the parent component // with Input property @Input() childText: string; @Input() childNumber: number; @Input() clearLog: boolean; // String Array to stage the changes triggered from parent component changeLogList: string[] = []; constructor() { } ngOnInit() { } // ngOnChanges Interface ngOnChanges(changes: {[propKey: string]: SimpleChange}) { // show the changes structure in console console.log(changes); // local log variables, created by every onChange let log: string[] = []; let needClear = false; let changedProp: SimpleChange; // get all the 3 property from the changes array for (let propertyName in changes) { if (propertyName === 'clearLog') { // set the clear flag needClear = true; } else { // get the SimpleChange object by the propertyName changedProp = changes[propertyName]; let to = JSON.stringify(changedProp.currentValue); if (changedProp.isFirstChange()) { log.push(`Initial value of ${propertyName} set to ${to}`); } else { let from = JSON.stringify(changedProp.previousValue); log.push(`${propertyName} changed from ${from} to ${to}`); } } } // concat multiply changes in log to one string and push as a new log // to the global changeLogList if (!needClear || changedProp != null && changedProp.isFirstChange) { // Fixed bug if only clearLog change is invoked, the changedProp is null // and changedProp.isFirstChange is breaking the script. this.changeLogList.push(log.join(', ')); } else { // clear this.changeLogList = []; } } }
6359f4614d5611a55f6ec8924bf844699babe84e
TypeScript
psumal/angular-dynamic-forms
/src/app/modules/dynamic-form-addons/payment/sepa/formatter-parser/sepa.service.ts
2.515625
3
export class SepaService { constructor() { } getCountryFromIban(iban:string):string { iban = iban || ''; let country = ''; //get char from pos 0 to 2 or less if (iban.length >= 2) { country = iban[0] + iban[1]; } else { country = (iban) ? iban.substring(0, iban.length) : ''; } country = country.toUpperCase(); return country; } getIbanMask(countryCode) { const a = /[A-Z]/i; const d = /\d/; const IBAN_MASKS = { 'default': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'AD': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'AL': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'AT': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'BA': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'BE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'BG': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'CH': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d], 'CY': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'CZ': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'DE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'DK': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'EE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'ES': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'FI': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'FO': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'FR': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'GB': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'GE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'GG': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'GI': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'GL': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'GR': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'HR': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d], 'HU': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'IE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'IS': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'IT': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'LI': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d], 'LT': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'LU': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'LV': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d], 'MC': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'MD': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'ME': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'MK': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'MT': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'NL': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'NO': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'PL': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'PT': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d], 'RO': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'RS': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d], 'SE': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'SI': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'SK': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d], 'SM': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d], 'UA': [a,a,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d,d,d,d,' ',d] }; return IBAN_MASKS[countryCode] || IBAN_MASKS['default']; } }
78721ecd8fa985199cc6e3d05ab39bf73deb9294
TypeScript
winverse/typeorm-sample
/src/entity/Post.ts
2.609375
3
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Index } from 'typeorm'; import User from './User'; @Entity('posts') export default class Post { @PrimaryGeneratedColumn('uuid') id!: string; @Column({ length: 255 }) title!: string; @Column('text') body!: string; @Column({ length: 255, nullable: true }) thumbnail!: string; @Column() is_markdown!: boolean; @Column() is_temp!: boolean; @ManyToOne(type => User, { cascade: true }) @JoinColumn({ name: 'fk_user_id' }) user!: User; @Column('uuid') fk_user_id!: string; @Index() @Column({ length: 255 }) url_slug!: string; @Index() @Column() likes!: number; }
02d91f5a85a8faa6c0a8c8c4a547dccb40319d58
TypeScript
green-fox-academy/hojpaat
/week-02/day-03/function-to-center.ts
3.46875
3
'use strict'; const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement; const ctx = canvas.getContext('2d'); // DO NOT TOUCH THE CODE ABOVE THIS LINE // create a line drawing function that takes 2 parameters: // The x and y coordinates of the line's starting point // and draws a line from that point to the center of the canvas. // Fill the canvas with lines from the edges, every 20 px, to the center. function drawLineCenter (x: number = 0, y: number = 0) { ctx.beginPath() ctx.moveTo(x, y); ctx.lineTo(300, 200); ctx.stroke(); } function drawLines (distance: number = 20){ let coordinateX = 0; let coordinateY = 0; for (let i: number = 0; i < (600 / distance); i++) { //upper lines drawLineCenter(coordinateX, coordinateY); coordinateX += distance; } for (let j: number = 0; j < 400 / distance; j++) { //right side lines drawLineCenter(coordinateX, coordinateY); coordinateY += distance; } for (let i: number = 0; i < (600 / distance); i++) { //bottom lines drawLineCenter(coordinateX, coordinateY); coordinateX -= distance; } for (let j: number = 0; j < 400 / distance; j++) { //left side lines drawLineCenter(coordinateX, coordinateY); coordinateY -= distance; } } drawLines(20);
c9c6621154405f755e0ca564e458e4ac278177eb
TypeScript
denoland/deno
/ext/node/polyfills/_fs/_fs_common.ts
2.5625
3
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // TODO(petamoriken): enable prefer-primordials for node polyfills // deno-lint-ignore-file prefer-primordials import { O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, } from "ext:deno_node/_fs/_fs_constants.ts"; import { validateFunction } from "ext:deno_node/internal/validators.mjs"; import type { ErrnoException } from "ext:deno_node/_global.d.ts"; import { BinaryEncodings, Encodings, notImplemented, TextEncodings, } from "ext:deno_node/_utils.ts"; export type CallbackWithError = (err: ErrnoException | null) => void; export interface FileOptions { encoding?: Encodings; flag?: string; signal?: AbortSignal; } export type TextOptionsArgument = | TextEncodings | ({ encoding: TextEncodings } & FileOptions); export type BinaryOptionsArgument = | BinaryEncodings | ({ encoding: BinaryEncodings } & FileOptions); export type FileOptionsArgument = Encodings | FileOptions; export type ReadOptions = { buffer: Buffer | Uint8Array; offset: number; length: number; position: number | null; }; export interface WriteFileOptions extends FileOptions { mode?: number; } export function isFileOptions( fileOptions: string | WriteFileOptions | undefined, ): fileOptions is FileOptions { if (!fileOptions) return false; return ( (fileOptions as FileOptions).encoding != undefined || (fileOptions as FileOptions).flag != undefined || (fileOptions as FileOptions).signal != undefined || (fileOptions as WriteFileOptions).mode != undefined ); } export function getEncoding( optOrCallback?: | FileOptions | WriteFileOptions // deno-lint-ignore no-explicit-any | ((...args: any[]) => any) | Encodings | null, ): Encodings | null { if (!optOrCallback || typeof optOrCallback === "function") { return null; } const encoding = typeof optOrCallback === "string" ? optOrCallback : optOrCallback.encoding; if (!encoding) return null; return encoding; } export function checkEncoding(encoding: Encodings | null): Encodings | null { if (!encoding) return null; encoding = encoding.toLowerCase() as Encodings; if (["utf8", "hex", "base64", "ascii"].includes(encoding)) return encoding; if (encoding === "utf-8") { return "utf8"; } if (encoding === "binary") { return "binary"; // before this was buffer, however buffer is not used in Node // node -e "require('fs').readFile('../world.txt', 'buffer', console.log)" } const notImplementedEncodings = ["utf16le", "latin1", "ucs2"]; if (notImplementedEncodings.includes(encoding as string)) { notImplemented(`"${encoding}" encoding`); } throw new Error(`The value "${encoding}" is invalid for option "encoding"`); } export function getOpenOptions( flag: string | number | undefined, ): Deno.OpenOptions { if (!flag) { return { create: true, append: true }; } let openOptions: Deno.OpenOptions = {}; if (typeof flag === "string") { switch (flag) { case "a": { // 'a': Open file for appending. The file is created if it does not exist. openOptions = { create: true, append: true }; break; } case "ax": case "xa": { // 'ax', 'xa': Like 'a' but fails if the path exists. openOptions = { createNew: true, write: true, append: true }; break; } case "a+": { // 'a+': Open file for reading and appending. The file is created if it does not exist. openOptions = { read: true, create: true, append: true }; break; } case "ax+": case "xa+": { // 'ax+', 'xa+': Like 'a+' but fails if the path exists. openOptions = { read: true, createNew: true, append: true }; break; } case "r": { // 'r': Open file for reading. An exception occurs if the file does not exist. openOptions = { read: true }; break; } case "r+": { // 'r+': Open file for reading and writing. An exception occurs if the file does not exist. openOptions = { read: true, write: true }; break; } case "w": { // 'w': Open file for writing. The file is created (if it does not exist) or truncated (if it exists). openOptions = { create: true, write: true, truncate: true }; break; } case "wx": case "xw": { // 'wx', 'xw': Like 'w' but fails if the path exists. openOptions = { createNew: true, write: true }; break; } case "w+": { // 'w+': Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). openOptions = { create: true, write: true, truncate: true, read: true }; break; } case "wx+": case "xw+": { // 'wx+', 'xw+': Like 'w+' but fails if the path exists. openOptions = { createNew: true, write: true, read: true }; break; } case "as": case "sa": { // 'as', 'sa': Open file for appending in synchronous mode. The file is created if it does not exist. openOptions = { create: true, append: true }; break; } case "as+": case "sa+": { // 'as+', 'sa+': Open file for reading and appending in synchronous mode. The file is created if it does not exist. openOptions = { create: true, read: true, append: true }; break; } case "rs+": case "sr+": { // 'rs+', 'sr+': Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. openOptions = { create: true, read: true, write: true }; break; } default: { throw new Error(`Unrecognized file system flag: ${flag}`); } } } else if (typeof flag === "number") { if ((flag & O_APPEND) === O_APPEND) { openOptions.append = true; } if ((flag & O_CREAT) === O_CREAT) { openOptions.create = true; openOptions.write = true; } if ((flag & O_EXCL) === O_EXCL) { openOptions.createNew = true; openOptions.read = true; openOptions.write = true; } if ((flag & O_TRUNC) === O_TRUNC) { openOptions.truncate = true; } if ((flag & O_RDONLY) === O_RDONLY) { openOptions.read = true; } if ((flag & O_WRONLY) === O_WRONLY) { openOptions.write = true; } if ((flag & O_RDWR) === O_RDWR) { openOptions.read = true; openOptions.write = true; } } return openOptions; } export { isUint32 as isFd } from "ext:deno_node/internal/validators.mjs"; export function maybeCallback(cb: unknown) { validateFunction(cb, "cb"); return cb as CallbackWithError; } // Ensure that callbacks run in the global context. Only use this function // for callbacks that are passed to the binding layer, callbacks that are // invoked from JS already run in the proper scope. export function makeCallback( this: unknown, cb?: (err: Error | null, result?: unknown) => void, ) { validateFunction(cb, "cb"); return (...args: unknown[]) => Reflect.apply(cb!, this, args); }
54a6f9227b8b186b38025588a3d49ed965438276
TypeScript
gamejolt/gamejolt
/src/_common/content/content-object.ts
2.84375
3
import { ContentNode } from './content-node'; import { LINK_LENGTH } from './content-rules'; import { MarkObject } from './mark-object'; export type ContentObjectType = | 'text' | 'paragraph' | 'table' | 'tableRow' | 'tableCell' | 'hr' | 'codeBlock' | 'gjEmoji' | 'blockquote' | 'hardBreak' | 'embed' | 'mediaItem' | 'orderedList' | 'bulletList' | 'listItem' | 'spoiler' | 'heading' | 'gif' | 'sticker' | 'chatInvite'; export class ContentObject extends ContentNode { public type!: ContentObjectType; public text!: string | null; public attrs!: { [key: string]: any }; public marks!: MarkObject[]; constructor(type: ContentObjectType, content: ContentObject[] = []) { super(content); this.type = type; this.text = null; this.attrs = {}; this.marks = []; } public get hasContent() { // hr and hard break do not count as "content". switch (this.type) { case 'text': return typeof this.text === 'string' && this.text.length > 0; // The following types are automatically considered content: case 'gjEmoji': case 'embed': case 'mediaItem': case 'gif': case 'sticker': return true; } for (const child of this.content) { if (child.hasContent) { return true; } } return false; } public static fromJsonObj(jsonObj: any): ContentObject { const type = jsonObj.type as ContentObjectType; const obj = new ContentObject(type); if (typeof jsonObj.text === 'string') { obj.text = jsonObj.text; } else { obj.text = null; } if (jsonObj.attrs === undefined) { obj.attrs = {}; } else { obj.attrs = jsonObj.attrs; } obj._content = []; if (Array.isArray(jsonObj.content)) { for (const subJsonObj of jsonObj.content) { obj.appendChild(ContentObject.fromJsonObj(subJsonObj)); } } obj.marks = []; if (Array.isArray(jsonObj.marks)) { for (const subJsonObj of jsonObj.marks) { obj.marks.push(MarkObject.fromJsonObj(subJsonObj)); } } return obj; } public toJsonObj(): any { const jsonObj = {} as any; jsonObj.type = this.type; if (this.attrs !== undefined && Object.keys(this.attrs).length > 0) { jsonObj.attrs = this.attrs; } if (this.text !== null) { jsonObj.text = this.text; } if (this.content.length > 0) { jsonObj.content = this.content.map(i => i.toJsonObj()); } if (this.marks.length > 0) { jsonObj.marks = this.marks.map(i => i.toJsonObj()); } return jsonObj; } public getLength() { let length = 0; switch (this.type) { case 'text': if (this.marks.some(m => m.type === 'link')) { length += LINK_LENGTH; } else if (this.text) { // Replace surrogate pairs with "_" // This will count the code points rather than code units. // Based on https://medium.com/@tanishiking/count-the-number-of-unicode-code-points-in-javascript-on-cross-browser-62c32b8d919c length += this.text.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '_').length; } break; case 'listItem': // Include a char for the 1./* at the beginning case 'gjEmoji': case 'hardBreak': case 'hr': case 'paragraph': case 'gif': case 'sticker': case 'chatInvite': length++; break; case 'embed': length += (this.attrs.source as string).length; break; case 'mediaItem': length += (this.attrs.caption as string).length + 1; break; } length += super.getLength(); return length; } }
d4c5d8ee2e7a9a03205b5134d823d07e7eb5ddf7
TypeScript
aviyot/AssigmentsCourseFullStack
/src/app/assigment-data.ts
2.671875
3
export class AssigmentData { numAssigment: number; subject: string; herf: string; ref: number[] = []; constructor(numAssigment: number, subject: string, herf: string, ref: number[]) { this.subject = subject; this.herf = herf; this.numAssigment = numAssigment; this.ref = ref; } }
21a59e06ff5c0006bf84858f1aa37b2ca5111031
TypeScript
babel/babel
/packages/babel-helper-create-class-features-plugin/src/fields.ts
2.625
3
import { template, traverse, types as t } from "@babel/core"; import type { File } from "@babel/core"; import type { NodePath, Visitor, Scope } from "@babel/traverse"; import ReplaceSupers from "@babel/helper-replace-supers"; import environmentVisitor from "@babel/helper-environment-visitor"; import memberExpressionToFunctions from "@babel/helper-member-expression-to-functions"; import type { Handler, HandlerState, } from "@babel/helper-member-expression-to-functions"; import optimiseCall from "@babel/helper-optimise-call-expression"; import annotateAsPure from "@babel/helper-annotate-as-pure"; import { skipTransparentExprWrapperNodes } from "@babel/helper-skip-transparent-expression-wrappers"; import * as ts from "./typescript.ts"; interface PrivateNameMetadata { id: t.Identifier; static: boolean; method: boolean; getId?: t.Identifier; setId?: t.Identifier; methodId?: t.Identifier; initAdded?: boolean; getterDeclared?: boolean; setterDeclared?: boolean; } type PrivateNamesMap = Map<string, PrivateNameMetadata>; export function buildPrivateNamesMap(props: PropPath[]) { const privateNamesMap: PrivateNamesMap = new Map(); for (const prop of props) { if (prop.isPrivate()) { const { name } = prop.node.key.id; const update: PrivateNameMetadata = privateNamesMap.has(name) ? privateNamesMap.get(name) : { id: prop.scope.generateUidIdentifier(name), static: prop.node.static, method: !prop.isProperty(), }; if (prop.isClassPrivateMethod()) { if (prop.node.kind === "get") { update.getId = prop.scope.generateUidIdentifier(`get_${name}`); } else if (prop.node.kind === "set") { update.setId = prop.scope.generateUidIdentifier(`set_${name}`); } else if (prop.node.kind === "method") { update.methodId = prop.scope.generateUidIdentifier(name); } } privateNamesMap.set(name, update); } } return privateNamesMap; } export function buildPrivateNamesNodes( privateNamesMap: PrivateNamesMap, privateFieldsAsProperties: boolean, privateFieldsAsSymbols: boolean, state: File, ) { const initNodes: t.Statement[] = []; for (const [name, value] of privateNamesMap) { // - When the privateFieldsAsProperties assumption is enabled, // both static and instance fields are transpiled using a // secret non-enumerable property. Hence, we also need to generate that // key (using the classPrivateFieldLooseKey helper). // - When the privateFieldsAsSymbols assumption is enabled, // both static and instance fields are transpiled using a // unique Symbol to define a non-enumerable property. // - In spec mode, only instance fields need a "private name" initializer // because static fields are directly assigned to a variable in the // buildPrivateStaticFieldInitSpec function. const { static: isStatic, method: isMethod, getId, setId } = value; const isAccessor = getId || setId; const id = t.cloneNode(value.id); let init: t.Expression; if (privateFieldsAsProperties) { init = t.callExpression(state.addHelper("classPrivateFieldLooseKey"), [ t.stringLiteral(name), ]); } else if (privateFieldsAsSymbols) { init = t.callExpression(t.identifier("Symbol"), [t.stringLiteral(name)]); } else if (!isStatic) { init = t.newExpression( t.identifier(!isMethod || isAccessor ? "WeakMap" : "WeakSet"), [], ); } if (init) { annotateAsPure(init); initNodes.push(template.statement.ast`var ${id} = ${init}`); } } return initNodes; } interface PrivateNameVisitorState { privateNamesMap: PrivateNamesMap; privateFieldsAsProperties: boolean; redeclared?: string[]; } // Traverses the class scope, handling private name references. If an inner // class redeclares the same private name, it will hand off traversal to the // restricted visitor (which doesn't traverse the inner class's inner scope). function privateNameVisitorFactory<S>( visitor: Visitor<PrivateNameVisitorState & S>, ) { // Traverses the outer portion of a class, without touching the class's inner // scope, for private names. const nestedVisitor = traverse.visitors.merge([ { ...visitor, }, environmentVisitor, ]); const privateNameVisitor: Visitor<PrivateNameVisitorState & S> = { ...visitor, Class(path) { const { privateNamesMap } = this; const body = path.get("body.body"); const visiblePrivateNames = new Map(privateNamesMap); const redeclared = []; for (const prop of body) { if (!prop.isPrivate()) continue; const { name } = prop.node.key.id; visiblePrivateNames.delete(name); redeclared.push(name); } // If the class doesn't redeclare any private fields, we can continue with // our overall traversal. if (!redeclared.length) { return; } // This class redeclares some private field. We need to process the outer // environment with access to all the outer privates, then we can process // the inner environment with only the still-visible outer privates. path.get("body").traverse(nestedVisitor, { ...this, redeclared, }); path.traverse(privateNameVisitor, { ...this, privateNamesMap: visiblePrivateNames, }); // We'll eventually hit this class node again with the overall Class // Features visitor, which'll process the redeclared privates. path.skipKey("body"); }, }; return privateNameVisitor; } interface PrivateNameState { privateNamesMap: PrivateNamesMap; classRef: t.Identifier; file: File; noDocumentAll: boolean; innerBinding?: t.Identifier; } const privateNameVisitor = privateNameVisitorFactory< HandlerState<PrivateNameState> & PrivateNameState >({ PrivateName(path, { noDocumentAll }) { const { privateNamesMap, redeclared } = this; const { node, parentPath } = path; if ( !parentPath.isMemberExpression({ property: node }) && !parentPath.isOptionalMemberExpression({ property: node }) ) { return; } const { name } = node.id; if (!privateNamesMap.has(name)) return; if (redeclared && redeclared.includes(name)) return; this.handle(parentPath, noDocumentAll); }, }); // rename all bindings that shadows innerBinding function unshadow( name: string, scope: Scope, innerBinding: t.Identifier | undefined, ) { // in some cases, scope.getBinding(name) === undefined // so we check hasBinding to avoid keeping looping // see: https://github.com/babel/babel/pull/13656#discussion_r686030715 while ( scope?.hasBinding(name) && !scope.bindingIdentifierEquals(name, innerBinding) ) { scope.rename(name); scope = scope.parent; } } export function buildCheckInRHS( rhs: t.Expression, file: File, inRHSIsObject?: boolean, ) { if (inRHSIsObject || !file.availableHelper?.("checkInRHS")) return rhs; return t.callExpression(file.addHelper("checkInRHS"), [rhs]); } const privateInVisitor = privateNameVisitorFactory<{ classRef: t.Identifier; file: File; innerBinding?: t.Identifier; }>({ BinaryExpression(path, { file }) { const { operator, left, right } = path.node; if (operator !== "in") return; if (!t.isPrivateName(left)) return; const { privateFieldsAsProperties, privateNamesMap, redeclared } = this; const { name } = left.id; if (!privateNamesMap.has(name)) return; if (redeclared && redeclared.includes(name)) return; // if there are any local variable shadowing classRef, unshadow it // see #12960 unshadow(this.classRef.name, path.scope, this.innerBinding); if (privateFieldsAsProperties) { const { id } = privateNamesMap.get(name); path.replaceWith(template.expression.ast` Object.prototype.hasOwnProperty.call(${buildCheckInRHS( right, file, )}, ${t.cloneNode(id)}) `); return; } const { id, static: isStatic } = privateNamesMap.get(name); if (isStatic) { path.replaceWith( template.expression.ast`${buildCheckInRHS( right, file, )} === ${t.cloneNode(this.classRef)}`, ); return; } path.replaceWith( template.expression.ast`${t.cloneNode(id)}.has(${buildCheckInRHS( right, file, )})`, ); }, }); interface Receiver { receiver( this: HandlerState<PrivateNameState> & PrivateNameState, member: NodePath<t.MemberExpression | t.OptionalMemberExpression>, ): t.Expression; } const privateNameHandlerSpec: Handler<PrivateNameState & Receiver> & Receiver = { memoise(member, count) { const { scope } = member; const { object } = member.node as { object: t.Expression }; const memo = scope.maybeGenerateMemoised(object); if (!memo) { return; } this.memoiser.set(object, memo, count); }, receiver(member) { const { object } = member.node as { object: t.Expression }; if (this.memoiser.has(object)) { return t.cloneNode(this.memoiser.get(object)); } return t.cloneNode(object); }, get(member) { const { classRef, privateNamesMap, file, innerBinding } = this; const { name } = (member.node.property as t.PrivateName).id; const { id, static: isStatic, method: isMethod, methodId, getId, setId, } = privateNamesMap.get(name); const isAccessor = getId || setId; if (isStatic) { // NOTE: This package has a peerDependency on @babel/core@^7.0.0, but these // helpers have been introduced in @babel/helpers@7.1.0. const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodGet" : "classStaticPrivateFieldSpecGet"; // if there are any local variable shadowing classRef, unshadow it // see #12960 unshadow(classRef.name, member.scope, innerBinding); return t.callExpression(file.addHelper(helperName), [ this.receiver(member), t.cloneNode(classRef), t.cloneNode(id), ]); } if (isMethod) { if (isAccessor) { if (!getId && setId) { if (file.availableHelper("writeOnlyError")) { return t.sequenceExpression([ this.receiver(member), t.callExpression(file.addHelper("writeOnlyError"), [ t.stringLiteral(`#${name}`), ]), ]); } console.warn( `@babel/helpers is outdated, update it to silence this warning.`, ); } return t.callExpression(file.addHelper("classPrivateFieldGet"), [ this.receiver(member), t.cloneNode(id), ]); } return t.callExpression(file.addHelper("classPrivateMethodGet"), [ this.receiver(member), t.cloneNode(id), t.cloneNode(methodId), ]); } return t.callExpression(file.addHelper("classPrivateFieldGet"), [ this.receiver(member), t.cloneNode(id), ]); }, boundGet(member) { this.memoise(member, 1); return t.callExpression( t.memberExpression(this.get(member), t.identifier("bind")), [this.receiver(member)], ); }, set(member, value) { const { classRef, privateNamesMap, file } = this; const { name } = (member.node.property as t.PrivateName).id; const { id, static: isStatic, method: isMethod, setId, getId, } = privateNamesMap.get(name); const isAccessor = getId || setId; if (isStatic) { const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodSet" : "classStaticPrivateFieldSpecSet"; return t.callExpression(file.addHelper(helperName), [ this.receiver(member), t.cloneNode(classRef), t.cloneNode(id), value, ]); } if (isMethod) { if (setId) { return t.callExpression(file.addHelper("classPrivateFieldSet"), [ this.receiver(member), t.cloneNode(id), value, ]); } return t.sequenceExpression([ this.receiver(member), value, t.callExpression(file.addHelper("readOnlyError"), [ t.stringLiteral(`#${name}`), ]), ]); } return t.callExpression(file.addHelper("classPrivateFieldSet"), [ this.receiver(member), t.cloneNode(id), value, ]); }, destructureSet(member) { const { classRef, privateNamesMap, file } = this; const { name } = (member.node.property as t.PrivateName).id; const { id, static: isStatic } = privateNamesMap.get(name); if (isStatic) { try { // classStaticPrivateFieldDestructureSet was introduced in 7.13.10 // eslint-disable-next-line no-var var helper = file.addHelper("classStaticPrivateFieldDestructureSet"); } catch { throw new Error( "Babel can not transpile `[C.#p] = [0]` with @babel/helpers < 7.13.10, \n" + "please update @babel/helpers to the latest version.", ); } return t.memberExpression( t.callExpression(helper, [ this.receiver(member), t.cloneNode(classRef), t.cloneNode(id), ]), t.identifier("value"), ); } return t.memberExpression( t.callExpression(file.addHelper("classPrivateFieldDestructureSet"), [ this.receiver(member), t.cloneNode(id), ]), t.identifier("value"), ); }, call(member, args: (t.Expression | t.SpreadElement)[]) { // The first access (the get) should do the memo assignment. this.memoise(member, 1); return optimiseCall(this.get(member), this.receiver(member), args, false); }, optionalCall(member, args: (t.Expression | t.SpreadElement)[]) { this.memoise(member, 1); return optimiseCall(this.get(member), this.receiver(member), args, true); }, delete() { throw new Error( "Internal Babel error: deleting private elements is a parsing error.", ); }, }; const privateNameHandlerLoose: Handler<PrivateNameState> = { get(member) { const { privateNamesMap, file } = this; const { object } = member.node; const { name } = (member.node.property as t.PrivateName).id; return template.expression`BASE(REF, PROP)[PROP]`({ BASE: file.addHelper("classPrivateFieldLooseBase"), REF: t.cloneNode(object), PROP: t.cloneNode(privateNamesMap.get(name).id), }); }, set() { // noop throw new Error("private name handler with loose = true don't need set()"); }, boundGet(member) { return t.callExpression( t.memberExpression(this.get(member), t.identifier("bind")), // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion [t.cloneNode(member.node.object as t.Expression)], ); }, simpleSet(member) { return this.get(member); }, destructureSet(member) { return this.get(member); }, call(member, args) { return t.callExpression(this.get(member), args); }, optionalCall(member, args) { return t.optionalCallExpression(this.get(member), args, true); }, delete() { throw new Error( "Internal Babel error: deleting private elements is a parsing error.", ); }, }; export function transformPrivateNamesUsage( ref: t.Identifier, path: NodePath<t.Class>, privateNamesMap: PrivateNamesMap, { privateFieldsAsProperties, noDocumentAll, innerBinding, }: { privateFieldsAsProperties: boolean; noDocumentAll: boolean; innerBinding: t.Identifier; }, state: File, ) { if (!privateNamesMap.size) return; const body = path.get("body"); const handler = privateFieldsAsProperties ? privateNameHandlerLoose : privateNameHandlerSpec; memberExpressionToFunctions<PrivateNameState>(body, privateNameVisitor, { privateNamesMap, classRef: ref, file: state, ...handler, noDocumentAll, innerBinding, }); body.traverse(privateInVisitor, { privateNamesMap, classRef: ref, file: state, privateFieldsAsProperties, innerBinding, }); } function buildPrivateFieldInitLoose( ref: t.Expression, prop: NodePath<t.ClassPrivateProperty>, privateNamesMap: PrivateNamesMap, ) { const { id } = privateNamesMap.get(prop.node.key.id.name); const value = prop.node.value || prop.scope.buildUndefinedNode(); return inheritPropComments( template.statement.ast` Object.defineProperty(${ref}, ${t.cloneNode(id)}, { // configurable is false by default // enumerable is false by default writable: true, value: ${value} }); `, prop, ); } function buildPrivateInstanceFieldInitSpec( ref: t.Expression, prop: NodePath<t.ClassPrivateProperty>, privateNamesMap: PrivateNamesMap, state: File, ) { const { id } = privateNamesMap.get(prop.node.key.id.name); const value = prop.node.value || prop.scope.buildUndefinedNode(); if (!process.env.BABEL_8_BREAKING) { if (!state.availableHelper("classPrivateFieldInitSpec")) { return inheritPropComments( template.statement.ast`${t.cloneNode(id)}.set(${ref}, { // configurable is always false for private elements // enumerable is always false for private elements writable: true, value: ${value}, })`, prop, ); } } const helper = state.addHelper("classPrivateFieldInitSpec"); return inheritPropComments( template.statement.ast`${helper}( ${t.thisExpression()}, ${t.cloneNode(id)}, { writable: true, value: ${value} }, )`, prop, ); } function buildPrivateStaticFieldInitSpec( prop: NodePath<t.ClassPrivateProperty>, privateNamesMap: PrivateNamesMap, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { id, getId, setId, initAdded } = privateName; const isAccessor = getId || setId; if (!prop.isProperty() && (initAdded || !isAccessor)) return; if (isAccessor) { privateNamesMap.set(prop.node.key.id.name, { ...privateName, initAdded: true, }); return inheritPropComments( template.statement.ast` var ${t.cloneNode(id)} = { // configurable is false by default // enumerable is false by default // writable is false by default get: ${getId ? getId.name : prop.scope.buildUndefinedNode()}, set: ${setId ? setId.name : prop.scope.buildUndefinedNode()} } `, prop, ); } const value = prop.node.value || prop.scope.buildUndefinedNode(); return inheritPropComments( template.statement.ast` var ${t.cloneNode(id)} = { // configurable is false by default // enumerable is false by default writable: true, value: ${value} }; `, prop, ); } function buildPrivateMethodInitLoose( ref: t.Expression, prop: NodePath<t.ClassPrivateMethod>, privateNamesMap: PrivateNamesMap, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { methodId, id, getId, setId, initAdded } = privateName; if (initAdded) return; if (methodId) { return inheritPropComments( template.statement.ast` Object.defineProperty(${ref}, ${id}, { // configurable is false by default // enumerable is false by default // writable is false by default value: ${methodId.name} }); `, prop, ); } const isAccessor = getId || setId; if (isAccessor) { privateNamesMap.set(prop.node.key.id.name, { ...privateName, initAdded: true, }); return inheritPropComments( template.statement.ast` Object.defineProperty(${ref}, ${id}, { // configurable is false by default // enumerable is false by default // writable is false by default get: ${getId ? getId.name : prop.scope.buildUndefinedNode()}, set: ${setId ? setId.name : prop.scope.buildUndefinedNode()} }); `, prop, ); } } function buildPrivateInstanceMethodInitSpec( ref: t.Expression, prop: NodePath<t.ClassPrivateMethod>, privateNamesMap: PrivateNamesMap, state: File, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { getId, setId, initAdded } = privateName; if (initAdded) return; const isAccessor = getId || setId; if (isAccessor) { return buildPrivateAccessorInitialization( ref, prop, privateNamesMap, state, ); } return buildPrivateInstanceMethodInitialization( ref, prop, privateNamesMap, state, ); } function buildPrivateAccessorInitialization( ref: t.Expression, prop: NodePath<t.ClassPrivateMethod>, privateNamesMap: PrivateNamesMap, state: File, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { id, getId, setId } = privateName; privateNamesMap.set(prop.node.key.id.name, { ...privateName, initAdded: true, }); if (!process.env.BABEL_8_BREAKING) { if (!state.availableHelper("classPrivateFieldInitSpec")) { return inheritPropComments( template.statement.ast` ${id}.set(${ref}, { get: ${getId ? getId.name : prop.scope.buildUndefinedNode()}, set: ${setId ? setId.name : prop.scope.buildUndefinedNode()} }); `, prop, ); } } const helper = state.addHelper("classPrivateFieldInitSpec"); return inheritPropComments( template.statement.ast`${helper}( ${t.thisExpression()}, ${t.cloneNode(id)}, { get: ${getId ? getId.name : prop.scope.buildUndefinedNode()}, set: ${setId ? setId.name : prop.scope.buildUndefinedNode()} }, )`, prop, ); } function buildPrivateInstanceMethodInitialization( ref: t.Expression, prop: NodePath<t.ClassPrivateMethod>, privateNamesMap: PrivateNamesMap, state: File, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { id } = privateName; if (!process.env.BABEL_8_BREAKING) { if (!state.availableHelper("classPrivateMethodInitSpec")) { return inheritPropComments( template.statement.ast`${id}.add(${ref})`, prop, ); } } const helper = state.addHelper("classPrivateMethodInitSpec"); return inheritPropComments( template.statement.ast`${helper}( ${t.thisExpression()}, ${t.cloneNode(id)} )`, prop, ); } function buildPublicFieldInitLoose( ref: t.Expression, prop: NodePath<t.ClassProperty>, ) { const { key, computed } = prop.node; const value = prop.node.value || prop.scope.buildUndefinedNode(); return inheritPropComments( t.expressionStatement( t.assignmentExpression( "=", t.memberExpression(ref, key, computed || t.isLiteral(key)), value, ), ), prop, ); } function buildPublicFieldInitSpec( ref: t.Expression, prop: NodePath<t.ClassProperty>, state: File, ) { const { key, computed } = prop.node; const value = prop.node.value || prop.scope.buildUndefinedNode(); return inheritPropComments( t.expressionStatement( t.callExpression(state.addHelper("defineProperty"), [ ref, computed || t.isLiteral(key) ? key : t.stringLiteral((key as t.Identifier).name), value, ]), ), prop, ); } function buildPrivateStaticMethodInitLoose( ref: t.Expression, prop: NodePath<t.ClassPrivateMethod>, state: File, privateNamesMap: PrivateNamesMap, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { id, methodId, getId, setId, initAdded } = privateName; if (initAdded) return; const isAccessor = getId || setId; if (isAccessor) { privateNamesMap.set(prop.node.key.id.name, { ...privateName, initAdded: true, }); return inheritPropComments( template.statement.ast` Object.defineProperty(${ref}, ${id}, { // configurable is false by default // enumerable is false by default // writable is false by default get: ${getId ? getId.name : prop.scope.buildUndefinedNode()}, set: ${setId ? setId.name : prop.scope.buildUndefinedNode()} }) `, prop, ); } return inheritPropComments( template.statement.ast` Object.defineProperty(${ref}, ${id}, { // configurable is false by default // enumerable is false by default // writable is false by default value: ${methodId.name} }); `, prop, ); } function buildPrivateMethodDeclaration( prop: NodePath<t.ClassPrivateMethod>, privateNamesMap: PrivateNamesMap, privateFieldsAsProperties = false, ) { const privateName = privateNamesMap.get(prop.node.key.id.name); const { id, methodId, getId, setId, getterDeclared, setterDeclared, static: isStatic, } = privateName; const { params, body, generator, async } = prop.node; const isGetter = getId && !getterDeclared && params.length === 0; const isSetter = setId && !setterDeclared && params.length > 0; let declId = methodId; if (isGetter) { privateNamesMap.set(prop.node.key.id.name, { ...privateName, getterDeclared: true, }); declId = getId; } else if (isSetter) { privateNamesMap.set(prop.node.key.id.name, { ...privateName, setterDeclared: true, }); declId = setId; } else if (isStatic && !privateFieldsAsProperties) { declId = id; } return inheritPropComments( t.functionDeclaration( t.cloneNode(declId), // @ts-expect-error params for ClassMethod has TSParameterProperty params, body, generator, async, ), prop, ); } type ReplaceThisState = { classRef: t.Identifier; needsClassRef: boolean; innerBinding: t.Identifier | null; }; type ReplaceInnerBindingReferenceState = ReplaceThisState; const thisContextVisitor = traverse.visitors.merge<ReplaceThisState>([ { UnaryExpression(path) { // Replace `delete this` with `true` const { node } = path; if (node.operator === "delete") { const argument = skipTransparentExprWrapperNodes(node.argument); if (t.isThisExpression(argument)) { path.replaceWith(t.booleanLiteral(true)); } } }, ThisExpression(path, state) { state.needsClassRef = true; path.replaceWith(t.cloneNode(state.classRef)); }, MetaProperty(path) { const { node, scope } = path; // if there are `new.target` in static field // we should replace it with `undefined` if (node.meta.name === "new" && node.property.name === "target") { path.replaceWith(scope.buildUndefinedNode()); } }, }, environmentVisitor, ]); const innerReferencesVisitor: Visitor<ReplaceInnerBindingReferenceState> = { ReferencedIdentifier(path, state) { if ( path.scope.bindingIdentifierEquals(path.node.name, state.innerBinding) ) { state.needsClassRef = true; path.node.name = state.classRef.name; } }, }; function replaceThisContext( path: PropPath, ref: t.Identifier, innerBindingRef: t.Identifier | null, ) { const state: ReplaceThisState = { classRef: ref, needsClassRef: false, innerBinding: innerBindingRef, }; if (!path.isMethod()) { // replace `this` in property initializers and static blocks path.traverse(thisContextVisitor, state); } // todo: use innerBinding.referencePaths to avoid full traversal if ( innerBindingRef != null && state.classRef?.name && state.classRef.name !== innerBindingRef.name ) { path.traverse(innerReferencesVisitor, state); } return state.needsClassRef; } export type PropNode = | t.ClassProperty | t.ClassPrivateMethod | t.ClassPrivateProperty | t.StaticBlock; export type PropPath = NodePath<PropNode>; function isNameOrLength({ key, computed }: t.ClassProperty) { if (key.type === "Identifier") { return !computed && (key.name === "name" || key.name === "length"); } if (key.type === "StringLiteral") { return key.value === "name" || key.value === "length"; } return false; } /** * Inherit comments from class members. This is a reduced version of * t.inheritsComments: the trailing comments are not inherited because * for most class members except the last one, their trailing comments are * the next sibling's leading comments. * * @template T transformed class member type * @param {T} node transformed class member * @param {PropPath} prop class member * @returns transformed class member type with comments inherited */ function inheritPropComments<T extends t.Node>(node: T, prop: PropPath) { t.inheritLeadingComments(node, prop.node); t.inheritInnerComments(node, prop.node); return node; } /** * ClassRefFlag records the requirement of the class binding reference. * * @enum {number} */ const enum ClassRefFlag { None, /** * When this flag is enabled, the binding reference can be the class id, * if exists, or the uid identifier generated for class expression. The * reference is safe to be consumed by [[Define]]. */ ForDefine = 1 << 0, /** * When this flag is enabled, the reference must be a uid, because the outer * class binding can be mutated by user codes. * E.g. * class C { static p = C }; const oldC = C; C = null; oldC.p; * we must memoize class `C` before defining the property `p`. */ ForInnerBinding = 1 << 1, } export function buildFieldsInitNodes( ref: t.Identifier | null, superRef: t.Expression | undefined, props: PropPath[], privateNamesMap: PrivateNamesMap, file: File, setPublicClassFields: boolean, privateFieldsAsProperties: boolean, constantSuper: boolean, innerBindingRef: t.Identifier | null, ) { let classRefFlags = ClassRefFlag.None; let injectSuperRef: t.Identifier; const staticNodes: t.Statement[] = []; const instanceNodes: t.Statement[] = []; // These nodes are pure and can be moved to the closest statement position const pureStaticNodes: t.FunctionDeclaration[] = []; let classBindingNode: t.ExpressionStatement | null = null; const getSuperRef = t.isIdentifier(superRef) ? () => superRef : () => { injectSuperRef ??= props[0].scope.generateUidIdentifierBasedOnNode(superRef); return injectSuperRef; }; const classRefForInnerBinding = ref ?? props[0].scope.generateUidIdentifier("class"); ref ??= t.cloneNode(innerBindingRef); for (const prop of props) { prop.isClassProperty() && ts.assertFieldTransformed(prop); // @ts-expect-error: TS doesn't infer that prop.node is not a StaticBlock const isStatic = !t.isStaticBlock?.(prop.node) && prop.node.static; const isInstance = !isStatic; const isPrivate = prop.isPrivate(); const isPublic = !isPrivate; const isField = prop.isProperty(); const isMethod = !isField; const isStaticBlock = prop.isStaticBlock?.(); if (isStatic) classRefFlags |= ClassRefFlag.ForDefine; if (isStatic || (isMethod && isPrivate) || isStaticBlock) { new ReplaceSupers({ methodPath: prop, constantSuper, file: file, refToPreserve: innerBindingRef, getSuperRef, getObjectRef() { classRefFlags |= ClassRefFlag.ForInnerBinding; if (isStatic || isStaticBlock) { return classRefForInnerBinding; } else { return t.memberExpression( classRefForInnerBinding, t.identifier("prototype"), ); } }, }).replace(); const replaced = replaceThisContext( prop, classRefForInnerBinding, innerBindingRef, ); if (replaced) { classRefFlags |= ClassRefFlag.ForInnerBinding; } } // TODO(ts): there are so many `ts-expect-error` inside cases since // ts can not infer type from pre-computed values (or a case test) // even change `isStaticBlock` to `t.isStaticBlock(prop)` will not make prop // a `NodePath<t.StaticBlock>` // this maybe a bug for ts switch (true) { case isStaticBlock: { const blockBody = (prop.node as t.StaticBlock).body; // We special-case the single expression case to avoid the iife, since // it's common. if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) { staticNodes.push(inheritPropComments(blockBody[0], prop)); } else { staticNodes.push( t.inheritsComments( template.statement.ast`(() => { ${blockBody} })()`, prop.node, ), ); } break; } case isStatic && isPrivate && isField && privateFieldsAsProperties: staticNodes.push( // @ts-expect-error checked in switch buildPrivateFieldInitLoose(t.cloneNode(ref), prop, privateNamesMap), ); break; case isStatic && isPrivate && isField && !privateFieldsAsProperties: staticNodes.push( // @ts-expect-error checked in switch buildPrivateStaticFieldInitSpec(prop, privateNamesMap), ); break; case isStatic && isPublic && isField && setPublicClassFields: // Functions always have non-writable .name and .length properties, // so we must always use [[Define]] for them. // It might still be possible to a computed static fields whose resulting // key is "name" or "length", but the assumption is telling us that it's // not going to happen. // @ts-expect-error checked in switch if (!isNameOrLength(prop.node)) { // @ts-expect-error checked in switch staticNodes.push(buildPublicFieldInitLoose(t.cloneNode(ref), prop)); break; } // falls through case isStatic && isPublic && isField && !setPublicClassFields: staticNodes.push( // @ts-expect-error checked in switch buildPublicFieldInitSpec(t.cloneNode(ref), prop, file), ); break; case isInstance && isPrivate && isField && privateFieldsAsProperties: instanceNodes.push( // @ts-expect-error checked in switch buildPrivateFieldInitLoose(t.thisExpression(), prop, privateNamesMap), ); break; case isInstance && isPrivate && isField && !privateFieldsAsProperties: instanceNodes.push( buildPrivateInstanceFieldInitSpec( t.thisExpression(), // @ts-expect-error checked in switch prop, privateNamesMap, file, ), ); break; case isInstance && isPrivate && isMethod && privateFieldsAsProperties: instanceNodes.unshift( buildPrivateMethodInitLoose( t.thisExpression(), // @ts-expect-error checked in switch prop, privateNamesMap, ), ); pureStaticNodes.push( buildPrivateMethodDeclaration( // @ts-expect-error checked in switch prop, privateNamesMap, privateFieldsAsProperties, ), ); break; case isInstance && isPrivate && isMethod && !privateFieldsAsProperties: instanceNodes.unshift( buildPrivateInstanceMethodInitSpec( t.thisExpression(), // @ts-expect-error checked in switch prop, privateNamesMap, file, ), ); pureStaticNodes.push( buildPrivateMethodDeclaration( // @ts-expect-error checked in switch prop, privateNamesMap, privateFieldsAsProperties, ), ); break; case isStatic && isPrivate && isMethod && !privateFieldsAsProperties: staticNodes.unshift( // @ts-expect-error checked in switch buildPrivateStaticFieldInitSpec(prop, privateNamesMap), ); pureStaticNodes.push( buildPrivateMethodDeclaration( // @ts-expect-error checked in switch prop, privateNamesMap, privateFieldsAsProperties, ), ); break; case isStatic && isPrivate && isMethod && privateFieldsAsProperties: staticNodes.unshift( buildPrivateStaticMethodInitLoose( t.cloneNode(ref), // @ts-expect-error checked in switch prop, file, privateNamesMap, ), ); pureStaticNodes.push( buildPrivateMethodDeclaration( // @ts-expect-error checked in switch prop, privateNamesMap, privateFieldsAsProperties, ), ); break; case isInstance && isPublic && isField && setPublicClassFields: // @ts-expect-error checked in switch instanceNodes.push(buildPublicFieldInitLoose(t.thisExpression(), prop)); break; case isInstance && isPublic && isField && !setPublicClassFields: instanceNodes.push( // @ts-expect-error checked in switch buildPublicFieldInitSpec(t.thisExpression(), prop, file), ); break; default: throw new Error("Unreachable."); } } if (classRefFlags & ClassRefFlag.ForInnerBinding && innerBindingRef != null) { classBindingNode = t.expressionStatement( t.assignmentExpression( "=", t.cloneNode(classRefForInnerBinding), t.cloneNode(innerBindingRef), ), ); } return { staticNodes: staticNodes.filter(Boolean), instanceNodes: instanceNodes.filter(Boolean), pureStaticNodes: pureStaticNodes.filter(Boolean), classBindingNode, wrapClass(path: NodePath<t.Class>) { for (const prop of props) { // Delete leading comments so that they don't get attached as // trailing comments of the previous sibling. // When transforming props, we explicitly attach their leading // comments to the transformed node with `inheritPropComments` // above. prop.node.leadingComments = null; prop.remove(); } if (injectSuperRef) { path.scope.push({ id: t.cloneNode(injectSuperRef) }); path.set( "superClass", t.assignmentExpression("=", injectSuperRef, path.node.superClass), ); } if (classRefFlags !== ClassRefFlag.None) { if (path.isClassExpression()) { path.scope.push({ id: ref }); path.replaceWith( t.assignmentExpression("=", t.cloneNode(ref), path.node), ); } else { if (innerBindingRef == null) { // export anonymous class declaration path.node.id = ref; } if (classBindingNode != null) { path.scope.push({ id: classRefForInnerBinding }); } } } return path; }, }; }
4f292f76b1ca7b6675c942c518f89221069c449d
TypeScript
hansellramos/TweetReader
/e2e/src/app.e2e-spec.ts
2.640625
3
import { AppPage } from './app.po'; import {browser} from 'protractor'; describe('e2e Tests', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); page.navigateTo(); }); browser.ignoreSynchronization = true; browser.waitForAngularEnabled(false); /** * App Component Tests */ it('should display title', () => { expect(page.getTitleText()).toEqual('Tweets Reader'); }); it('should display default subtitle', () => { expect(page.getSubtitleText()).toEqual('#nowPlaying in San Francisco'); }); it('should display default description', () => { expect(page.getDescription()).toEqual( 'This page show #nowPlaying tweets in San Francisco ' + 'that contain a YouTube link. It also allows you to post a nowPlaying tweet via YouTube link' ); }); /** * Tweet Form Component tests */ it('should display tweet form', () => { expect(page.getTweetForm().isPresent()).toBeTruthy(); }); it('tweet form should display video url widget', () => { const videoUrlWidgetElement = page.getTweetFormVideoUrlWidget(); expect(videoUrlWidgetElement.isPresent()).toBeTruthy(); }); it('tweet form should display video url placeholder as "Video URL:"', () => { const videoUrlWidgetElement = page.getTweetFormVideoUrlWidget(); expect(videoUrlWidgetElement.getAttribute('placeholder')).toEqual('Video URL:'); }); it('tweet form video url widget should display default value as youtube.com/', () => { const videoUrlWidgetElement = page.getTweetFormVideoUrlWidget(); expect(videoUrlWidgetElement.getAttribute('value')).toEqual('youtube.com/'); }); it('tweet form video url widget label should be equal to "Video URL:"', () => { const videoUrlWidgetElementLabel = page.getTweetFormVideoUrlWidgetLabel(); expect(videoUrlWidgetElementLabel.getText()).toEqual('Video URL:'); }); it('tweet form should display comment widget', () => { const commentWidgetElement = page.getTweetFormCommentWidget(); expect(commentWidgetElement.isPresent()).toBeTruthy(); }); it('tweet form should display comment widget label', () => { const commentWidgetElementLabel = page.getTweetFormCommentWidgetLabel(); expect(commentWidgetElementLabel.isPresent()).toBeTruthy(); }); it('tweet form comment widget label should be equal to "Comment:"', () => { const commentWidgetElementLabel = page.getTweetFormCommentWidgetLabel(); expect(commentWidgetElementLabel.getText()).toEqual('Comment:'); }); it('tweet form should display tweet link button', () => { const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.isPresent()).toBeTruthy(); }); it('tweet form tweet link button should have target=_blank attribute', () => { const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.getAttribute('target')).toEqual('_blank'); }); it('tweet form tweet link button should display "Tweet to #nowPlaying" comment', () => { expect(page.getTweetFormTweetLinkWidgetText()).toEqual('Tweet to #nowPlaying'); }); it('tweet form tweet link button default href value should be ' + 'https://twitter.com/intent/tweet?text=yotube.com/&hashtags=nowPlaying', () => { const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.getAttribute('href')).toEqual( 'https://twitter.com/intent/tweet?text=youtube.com/&hashtags=nowPlaying' ); }); it('tweet form tweet link button default href value should be ' + 'https://twitter.com/intent/tweet?text=youtube.com/testing&hashtags=nowPlaying ' + 'when change video url value', () => { const videoUrlWidgetElement = page.getTweetFormVideoUrlWidget(); videoUrlWidgetElement.clear(); videoUrlWidgetElement.sendKeys('youtube.com/testing'); const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.getAttribute('href')).toEqual( 'https://twitter.com/intent/tweet?text=youtube.com/testing&hashtags=nowPlaying' ); }); it('tweet form tweet link button default href value should be ' + 'https://twitter.com/intent/tweet?text=Hello%20World%20youtube.com/&hashtags=nowPlaying ' + 'when change comment value', () => { const commentWidgetElement = page.getTweetFormCommentWidget(); commentWidgetElement.sendKeys('Hello world'); const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.getAttribute('href')).toEqual( 'https://twitter.com/intent/tweet?text=Hello%20world%20youtube.com/&hashtags=nowPlaying' ); }); it('tweet form tweet link button default href value should be ' + 'https://twitter.com/intent/tweet?text=Hello%20World%20youtube.com/testing&hashtags=nowPlaying ' + 'when change comment and video url values', () => { const commentWidgetElement = page.getTweetFormCommentWidget(); commentWidgetElement.sendKeys('Hello world'); const videoUrlWidgetElement = page.getTweetFormVideoUrlWidget(); videoUrlWidgetElement.clear(); videoUrlWidgetElement.sendKeys('youtube.com/testing'); const tweetLinkWidgetElement = page.getTweetFormTweetLinkWidget(); expect(tweetLinkWidgetElement.getAttribute('href')).toEqual( 'https://twitter.com/intent/tweet?text=Hello%20world%20youtube.com/testing&hashtags=nowPlaying' ); }); /** * Tweet Results Tests */ it('should display 5 tweet results widgets', () => { expect(page.getAllTweetResults().count()).toEqual(5); }); it('tweet result should display a title with content', () => { browser.sleep(5000); // wait for youtube videos load const element = page.getTweetResultWidgetTitle(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).not.toEqual(''); }); it('tweet result should display a video widget', () => { browser.sleep(5000); // wait for youtube videos load const element = page.getTweetResultVideoWidget(); expect(element.isPresent()).toBeTruthy(); }); it('tweet result video widget should come from youtube', () => { browser.sleep(5000); // wait for youtube videos load const element = page.getTweetResultVideoWidget(); expect(element.getAttribute('src')).toMatch('^(https?\\:\\/\\/)?(www\\.)?(youtube\\.com|youtu\\.?be)\\/.+$'); }); it('tweet result should display a content widget', () => { const element = page.getTweetResultContentWidget(); expect(element.isPresent()).toBeTruthy(); }); it('tweet result content should display a twitter logo', () => { const element = page.getTweetResultContentTwitterLogo(); expect(element.isPresent()).toBeTruthy(); }); it('tweet result content should display a user profile image with source', () => { const element = page.getTweetResultContentUserProfilePicture(); expect(element.isPresent()).toBeTruthy(); expect(element.getAttribute('src')).toContain('https://pbs.twimg.com/profile_images/'); }); it('tweet result content should display username', () => { const element = page.getTweetResultContentUsernameWidget(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).not.toEqual(''); expect(element.getAttribute('target')).toEqual('_blank'); }); it('tweet result content should display screen name', () => { const element = page.getTweetResultContentUserScreenNameWidget(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).not.toEqual(''); }); it('tweet result content should display follow button with Follow label', () => { const element = page.getTweetResultContentUserFollowButtonLink(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).toContain('Follow'); expect(element.getAttribute('target')).toEqual('_blank'); }); it('tweet result content should display tweet text with content', () => { const element = page.getTweetResultContentTweet(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).not.toEqual(''); }); it('tweet result content should display reply button', () => { const element = page.getTweetResultContentUserReplyButtonLink(); expect(element.isPresent()).toBeTruthy(); expect(element.getAttribute('target')).toEqual('_blank'); }); it('tweet result content should display retweet button', () => { const element = page.getTweetResultContentUserRetweetButtonLink(); expect(element.isPresent()).toBeTruthy(); expect(element.getAttribute('target')).toEqual('_blank'); }); it('tweet result content should display like button', () => { const element = page.getTweetResultContentUserLikeButtonLink(); expect(element.isPresent()).toBeTruthy(); expect(element.getAttribute('target')).toEqual('_blank'); }); it('tweet result content should display tweet date with content', () => { const element = page.getTweetResultContentUserDateWidget(); expect(element.isPresent()).toBeTruthy(); expect(element.getText()).not.toEqual(''); }); });
5ddc775691104f7206a124fa049dc7f067e7c0fd
TypeScript
VladAlmazov/friday
/src/bll/reducer.ts
2.828125
3
type StateType = { } // type ActionsType = const initState: StateType = { } export const reducer = (state: StateType = initState, action: any): StateType => { switch (action.type) { case '': { return state } default: { return state } } } export const actionCreator = () => {}
89d78ef914a5beea82d7976aa6331b77913bb020
TypeScript
qivass/pet
/src/store/ducks/tweet/saga.ts
2.546875
3
import {call, put, takeLatest} from 'redux-saga/effects' import { TWEETS_API } from '../../../services/api/tweetsApi'; import { LoadingState } from '../common/constants'; import { Tweet } from '../tweets/contracts/state'; import {FetchTweetDataActionInterface, TweetActions, TweetActionsType} from "./actions"; function* fetchTweetDataSaga({payload}:FetchTweetDataActionInterface){ try { const data: Tweet = yield call(TWEETS_API.fetchTweetData, payload); yield put(TweetActions.setTweetData(data)); }catch (error) { yield put(TweetActions.setTweetLoadingState(LoadingState.ERROR)); } } export default function* tweetSaga() { yield takeLatest(TweetActionsType.FETCH_TWEET_DATA, fetchTweetDataSaga); }
0b0c3a44aba7ce7a683149effdf936dd53b1f481
TypeScript
JimSchofield/julia
/src/index.ts
2.828125
3
import { CNumber } from "./lib/complex"; import { getComplexNumber, getCoords } from "./lib/coords"; import { doesDiverge } from "./lib/iterate"; import { debounce } from "./lib/util"; let CANVAS_WIDTH = 600; let CANVAS_HEIGHT = 400; let MAX_ITER = 1000; let C = { x: -0.04, y: -0.12 }; const heightInput = document.querySelector<HTMLInputElement>("#height"); const widthInput = document.querySelector<HTMLInputElement>("#width"); const cImageValueInput = document.querySelector<HTMLInputElement>("#cImagValue"); const cRealValueInput = document.querySelector<HTMLInputElement>("#cRealValue"); const maxIterInput = document.querySelector<HTMLInputElement>("#maxIter"); const inputs = [ cImageValueInput, cRealValueInput, maxIterInput, heightInput, widthInput, ]; const canvasEl = document.querySelector<HTMLCanvasElement>("#canvas"); const ctx = canvasEl.getContext("2d"); let newImageData = ctx.createImageData(CANVAS_WIDTH, CANVAS_HEIGHT); function draw(C: CNumber, MAX_ITER: number) { for (let i = 0; i <= newImageData.width * newImageData.height; i++) { let j = i * 4; const { row, col } = getCoords(j, CANVAS_WIDTH); const cNum = getComplexNumber(row, col, CANVAS_WIDTH, CANVAS_HEIGHT); // iterate, and if greater -> diverges if (!doesDiverge(cNum, C, MAX_ITER)) { newImageData.data[j] = 0; newImageData.data[j + 1] = 0; newImageData.data[j + 2] = 0; newImageData.data[j + 3] = 255; } else { newImageData.data[j] = 255; newImageData.data[j + 1] = 255; newImageData.data[j + 2] = 255; newImageData.data[j + 3] = 255; } } ctx.clearRect(0, 0, newImageData.width, newImageData.height); ctx.putImageData(newImageData, 0, 0); } draw(C, MAX_ITER); inputs.forEach((inputEl) => { inputEl.addEventListener( "click", debounce(() => { CANVAS_WIDTH = widthInput.valueAsNumber; CANVAS_HEIGHT = heightInput.valueAsNumber; canvasEl.setAttribute("height", String(CANVAS_HEIGHT)); canvasEl.setAttribute("width", String(CANVAS_WIDTH)); newImageData = ctx.createImageData(CANVAS_WIDTH, CANVAS_HEIGHT); C = { x: cRealValueInput.valueAsNumber, y: cImageValueInput.valueAsNumber, }; MAX_ITER = maxIterInput.valueAsNumber; draw(C, MAX_ITER); }, 500) ); });
d86f1197d783e3967af30ca09a1259f1364b7491
TypeScript
theerapatk/pokedex
/pokedex-client/app/components/test/test.component.spec.ts
2.5625
3
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TestComponent } from './test.component'; describe('TestComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [TestComponent] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); const testCases = [ { inputs: [4, 1, 2], results: [3] }, { inputs: undefined, results: [] }, { inputs: [], results: [] }, { inputs: [1, 2, 3], results: [] }, { inputs: [8, 1, 5, 3], results: [2, 4, 6, 7] }, { inputs: [2], results: [1] }, { inputs: [1], results: [] } ]; testCases.forEach(testCase => { it(`should findMissingNumber given the input is ${testCase.inputs}`, () => { const results = component.findMissingNumber(testCase.inputs); expect(results).toEqual(testCase.results); }); }); });
9ff943236da79ac89c3c9d1d2daef74865e621a8
TypeScript
pedaars/jina-ui
/packages/jinajs/src/jinaClient.ts
2.71875
3
import axios, { AxiosInstance } from "axios"; import { serializeRequest, serializeResponse } from "./serializer"; import MockedClient from './MockedClient' import { AnyObject, BaseURL, RawDocumentData, RequestSerializer, ResponseSerializer, SimpleQueries, SimpleResults, } from "./types"; import { OpenAPIV3 } from "openapi-types"; export class JinaClient<IRequestBody = AnyObject ,IResponseData = AnyObject> { private baseURL: string; private client: AxiosInstance; private serializeRequest: RequestSerializer<IRequestBody> private serializeResponse: ResponseSerializer<IResponseData> private schema: OpenAPIV3.Document | undefined private debugMode: boolean constructor(baseURL: BaseURL, schema?: OpenAPIV3.Document, debugMode?: boolean, customSerializeRequest?: RequestSerializer<IRequestBody>, customSerializeResponse?: ResponseSerializer<IResponseData> ) { this.schema = schema this.debugMode = debugMode || false this.serializeRequest = customSerializeRequest || serializeRequest this.serializeResponse = customSerializeResponse || serializeResponse this.baseURL = baseURL; if(debugMode && this.schema) this.client = new MockedClient<IResponseData>(this.schema) as unknown as AxiosInstance else this.client = axios.create({ baseURL }) this.init(); } /** * Initializes JinaClient. * Makes a request to endpoint/status to check if service is up */ async init() { try { const response = await this.client.get("status"); if (response?.data?.jina?.jina) console.log("connected!") } catch (e) { console.log(e, this.baseURL) if(this.debugMode) console.log("jina client started in debug mode!") } } /** * * @param documents can be for type Base64 encoded URI, strings or files * * ```typescript * const { results, queries } = await jinaClient.search('searchQuery') * ``` */ async search( ...documents: RawDocumentData[] ): Promise<{ results: SimpleResults[]; queries: SimpleQueries }> { const requestBody = await this.serializeRequest(documents); console.log("request body:", requestBody); const response = await this.client.post("search", requestBody, { headers: { 'content-type': '' } }); console.log("response:", response); return this.serializeResponse(response); } async searchWithParameters( documents: RawDocumentData[], parameters: AnyObject ): Promise<{ results: SimpleResults[]; queries: SimpleQueries }> { console.log(parameters) const requestBody = await this.serializeRequest(documents); console.log("request body:", requestBody); const response = await this.client.post("search", requestBody, { headers: { 'content-type': '' } }); console.log("response:", response); return this.serializeResponse(response.data); } }
bc8501fb554a643d1ece3d663b67da317580c661
TypeScript
nutheory/challenges_js
/src/wave.ts
2.796875
3
export const wave = (str:string) => str.split("").map((char, i) => char !== " " ? str.split("").map((ic,idx) => ic === char && i === idx ? ic.toUpperCase() : ic ).join("") : " " ).filter(item => item !== " ")
4e2db09ddb5446195c1ed5cd6e440ffa648d039f
TypeScript
Juanes-GH/curso-javascript-2019
/tema6/ejem8/maps.ts
2.6875
3
{ let properties = {}; properties['email'] = "name@example.com"; let email = properties['email']; //Value has any type } { let properties: any = {}; properties['email'] = "name@example.com"; let email = properties['email']; //Value has any type } { let properties: { [k: string]: string } = {}; properties['email'] = "name@example.com"; let email = properties['email']; //Value has string type } { let counts: { [k: string]: number } = {}; counts['lunes'] = 35; let lunesCount = counts['lunes']; //Value has number type }
911727f7405d650ca4a5e4bc2a9d98204bdddbc1
TypeScript
fal-works/p5js-sketches
/lines-of-data/src/common/easing.ts
3.53125
4
/** * ---- Common easing utility ------------------------------------------------ */ import { sq, cubic } from "./math"; /** * Linear easing function. * @param ratio */ export const easeLinear = (ratio: number): number => ratio; /** * easeInQuad. * @param ratio */ export const easeInQuad = sq; /** * easeOutQuad. * @param ratio */ export const easeOutQuad = (ratio: number): number => -sq(ratio - 1) + 1; /** * easeInCubic. * @param ratio */ export const easeInCubic = cubic; /** * easeOutCubic. * @param ratio */ export const easeOutCubic = (ratio: number): number => cubic(ratio - 1) + 1; /** * easeInQuart. * @param ratio */ export const easeInQuart = (ratio: number): number => Math.pow(ratio, 4); /** * easeOutQuart. * @param ratio */ export const easeOutQuart = (ratio: number): number => -Math.pow(ratio - 1, 4) + 1; const EASE_OUT_BACK_DEFAULT_COEFFICIENT = 1.70158; /** * easeOutBack. * @param ratio */ export const easeOutBack = (ratio: number): number => { const r = ratio - 1; return ( (EASE_OUT_BACK_DEFAULT_COEFFICIENT + 1) * cubic(r) + EASE_OUT_BACK_DEFAULT_COEFFICIENT * sq(r) + 1 ); }; /** * Easing function. */ export interface Easing { (ratio: number): number; } /** * Returns an easeOut function. * @param exponent - Integer from 1 to 4. */ export function getEasingFunction(exponent: number): Easing { switch (Math.floor(exponent)) { default: case 1: return easeLinear; case 2: return easeOutQuad; case 3: return easeOutCubic; case 4: return easeOutQuart; } }
c75ef07940ebb47d4958bdf0f5d6423e971ed47e
TypeScript
UriyDR/listOfFilms
/src/app/number.pipe.ts
3.1875
3
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'number' }) export class NumberPipe implements PipeTransform { transform(number: number = 0): string { const abs: number = Math.abs(number); let resultNumber: any; if (abs >= Math.pow(10, 8)) { // billion resultNumber = parseFloat((number / Math.pow(10, 9)).toFixed(2)) + 'B'; } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 5)) { // million resultNumber = parseFloat((number / Math.pow(10, 6)).toFixed(2)) + 'M'; } else if (abs < Math.pow(10, 6) && abs >= 1000) { // thousand resultNumber = parseFloat((number / Math.pow(10, 3)).toFixed(1)) + 'K'; } else { // less than a 1000 resultNumber = number.toString(); } return resultNumber; } }
4e27a3edd1368a0f2fcd6ee703bf2feffd7e41ef
TypeScript
fieldyang/nodom3.1
/extend/defineelementinit.ts
2.5625
3
import { DefineElement } from "../core/defineelement"; import { DefineElementManager } from "../core/defineelementmanager"; import { NError } from "../core/error"; import { NodomMessage } from "../core/nodom"; import { Element } from "../core/element"; import { Directive } from "../core/directive"; import { Module } from "../core/module"; /** * module 元素 */ class MODULE extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); //类名 let clazz = node.getProp('name'); if (!clazz) { throw new NError('itemnotempty', NodomMessage.TipWords['element'], 'MODULE', 'className'); } node.delProp('name'); new Directive('module',clazz,node); } } /** * for 元素 */ class FOR extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); //条件 let cond = node.getProp('cond'); if (!cond) { throw new NError('itemnotempty', NodomMessage.TipWords['element'], 'FOR', 'cond'); } node.delProp('cond'); new Directive('repeat',cond,node,module); } } class IF extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); //条件 let cond = node.getProp('cond'); if (!cond) { throw new NError('itemnotempty', NodomMessage.TipWords['element'], 'IF', 'cond'); } node.delProp('cond'); new Directive('if',cond,node,module); } } class ELSE extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); new Directive('else','',node,module); } } class ELSEIF extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); //条件 let cond = node.getProp('cond'); if (!cond) { throw new NError('itemnotempty', NodomMessage.TipWords['element'], 'ELSEIF', 'cond'); } node.delProp('cond'); new Directive('elseif',cond,node,module); } } class ENDIF extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); new Directive('endif','',node,module); } } /** * 替代器 */ class SWAP extends DefineElement{ constructor(node: Element,module:Module){ super(node,module); //条件 let cond = node.getProp('name') || 'default'; node.delProp('name'); new Directive('swap',cond,node,module); } } DefineElementManager.add([MODULE,FOR,IF,ELSE,ELSEIF,ENDIF,SWAP]);
d9a48d41fce4598ea68b54699aebe826f80f45b6
TypeScript
hellivan/docker-snapshot-image
/src/lib/docker-utils.ts
2.515625
3
import axios from 'axios'; import { spawnCmd } from './cmd-utils'; import { BasicCredentials } from './credentials'; async function createDockerImage(tag: string, testMode: boolean, silentDockerMode: boolean): Promise<string> { const command = 'docker'; const args = ['build', '--force-rm', '-t', tag, './']; console.log(`Creating image using command '${command} ${args.join(' ')}'`); if (!testMode) { await spawnCmd(command, args, silentDockerMode); } return tag; } async function tagImage( existingTag: string, newTag: string, testMode: boolean, silentDockerMode: boolean ): Promise<string> { const command = 'docker'; const args = ['tag', existingTag, newTag]; console.log(`Tagging image using command '${command} ${args.join(' ')}'`); if (!testMode) { await spawnCmd(command, args, silentDockerMode); } return existingTag; } export function createOrTag( existingTag: string | null, newTag: string, testMode: boolean, silentDockerMode: boolean ): Promise<string> { if (!existingTag) return createDockerImage(newTag, testMode, silentDockerMode); return tagImage(existingTag, newTag, testMode, silentDockerMode); } /** * Replace invalid characters with underscore and minus * * @param tagName */ export function sanitizeTagName(tagName: string): string { return tagName.replace(/[/\\]/g, '-').replace(/[^A-Za-z0-9_\-\.]/g, '_'); } /** * Replace invalid characters with underscore and minus * * @param imageName */ export function sanitizeImageName(imageName: string): string { return imageName.replace(/[/\\]/g, '-').replace(/[^A-Za-z0-9_\-\.]/g, '_'); } // curl -XGET --unix-socket /var/run/docker.sock http://localhost/images/json // curl -i -XPOST -H "X-Registry-Auth: Base64({"username": "foo", "password": "bar"})" --unix-socket /var/run/docker.sock http://localhost/images/docker.solunio.com/common/hitower-service.data-producer:7.0.4/push export async function pushImage(existingTag: string, credentials: BasicCredentials | undefined): Promise<void> { const headers = credentials != null ? { 'X-Registry-Auth': encodeRegistryAuth(credentials) } : undefined; const result = await axios .create({ socketPath: '/var/run/docker.sock', timeout: 10 * 60 * 1000 }) .post<string>(`http://localhost/v1.41/images/${existingTag}/push`, {}, { headers }); for (const line of result.data.split('\n')) { // skip empty lines if (line.trim().length > 0) { const parsed = JSON.parse(line); if (parsed.error != null) { throw new Error(`Error while pushing image "${existingTag}": "${parsed.error}"`); } } } console.log(`Pushed image "${existingTag}"`); } interface DockerRegistryAuthData { readonly username: string; readonly password: string; } function encodeRegistryAuth(credentials: BasicCredentials): string { const dockerRegistryAuthData: DockerRegistryAuthData = credentials; return Buffer.from(JSON.stringify(dockerRegistryAuthData)).toString('base64'); }
5317f8e4029d5eac8b4626f2e764ba18d84a93dc
TypeScript
zcorky/zodash
/packages/logger/src/format/nginx.ts
2.703125
3
/** * Nginx Log Format * * log_format main '$remote_addr - $remote_user [$time_local] "$request" ' * '$request_time $request_length ' * '$status $body_bytes_sent "$http_referer" ' * '"$http_user_agent"'; */ export interface D { method: string; path: string; status: number; userAgent?: string; addr?: string; user?: string; datetime: string; version: string; requestTime: number; contentLength?: number; bodyBytesSent?: number; referer?: string; } export function format(data: D) { return ( `${data.addr} - ${data.user || '-'} [${data.datetime}] "${data.method} ${ data.path } HTTP/${data.version || '-'}" ` + `${data.requestTime} ${data.contentLength} ` + `${data.status} ${data.bodyBytesSent} "${data.referer || '-'}" ` + `"${data.userAgent || '-'}"` ); }
2e943999e683cf372e3efd71dceaa50a96371241
TypeScript
Hambo3/WebGL
/Instancing/model.ts
3.09375
3
export type Model = Float32Array; export function load(path: string): Promise<Array<Model>> { return fetch(path) .then((response) => response.arrayBuffer()) .then((buffer) => { let buffer_array = new Uint16Array(buffer); let model_data: Array<Model> = []; let i = 0; while (i < buffer_array.length) { let size: number[] = [0, 0, 0]; let model_start = i + 1; let model_length = buffer_array[i]; let model_end = model_start + model_length; let model = []; for (i = model_start; i < model_end; i++) { let voxel = buffer_array[i]; model.push( (voxel & 15) >> 0, (voxel & 240) >> 4, (voxel & 3840) >> 8, (voxel & 61440) >> 12 ); } for (let j = 0; j < model.length; j++) { if (size[j % 4] < model[j] + 1) { size[j % 4] = model[j] + 1; } } model_data.push( new Float32Array(model).map((val, idx) => { switch (idx % 4) { case 0: return val - size[0] / 2 + 0.5; case 1: return val - size[1] / 2 + 0.5; case 2: return val - size[2] / 2 + 0.5; default: return val; } }) ); } return model_data; }); }
92dcfece62ddeaefbd18c1febf2d67691d08b5fb
TypeScript
mzxyz/Mentemia
/src/epics/chainEpic.ts
2.6875
3
import { of } from 'rxjs'; import R from 'ramda'; import { mergeMap } from 'rxjs/operators'; import { ofType } from 'redux-observable'; import { ActionsObservable } from './types'; const chainEpics = R.curry((fromType: string, toType: string, action$: ActionsObservable) => action$.pipe( ofType(fromType), mergeMap(() => of({ type: toType })), ), ); export const chainEpicsWithAction = R.curry( (fromType: string, toType: string, action$: ActionsObservable) => action$.pipe( ofType(fromType), mergeMap((action) => of({ ...action, type: toType })), ), ); export default chainEpics;
23212c0497e7acea169a27c35b4940d446af31f9
TypeScript
aderx/algo_practice
/2021-01/xfu/6.棒球比赛.ts
3.84375
4
// 682. 棒球比赛 // 你现在是一场采用特殊赛制棒球比赛的记录员。这场比赛由若干回合组成,过去几回合的得分可能会影响以后几回合的得分。 // 比赛开始时,记录是空白的。你会得到一个记录操作的字符串列表 ops,其中 ops[i] 是你需要记录的第 i 项操作,ops 遵循下述规则: // 整数 x - 表示本回合新获得分数 x // "+" - 表示本回合新获得的得分是前两次得分的总和。题目数据保证记录此操作时前面总是存在两个有效的分数。 // "D" - 表示本回合新获得的得分是前一次得分的两倍。题目数据保证记录此操作时前面总是存在一个有效的分数。 // "C" - 表示前一次得分无效,将其从记录中移除。题目数据保证记录此操作时前面总是存在一个有效的分数。 // 请你返回记录中所有得分的总和。 // 示例 1: // 输入:ops = ["5","2","C","D","+"] // 输出:30 // 解释: // "5" - 记录加 5 ,记录现在是 [5] // "2" - 记录加 2 ,记录现在是 [5, 2] // "C" - 使前一次得分的记录无效并将其移除,记录现在是 [5]. // "D" - 记录加 2 * 5 = 10 ,记录现在是 [5, 10]. // "+" - 记录加 5 + 10 = 15 ,记录现在是 [5, 10, 15]. // 所有得分的总和 5 + 10 + 15 = 30 // 示例 2: // 输入:ops = ["5","-2","4","C","D","9","+","+"] // 输出:27 // 解释: // "5" - 记录加 5 ,记录现在是 [5] // "-2" - 记录加 -2 ,记录现在是 [5, -2] // "4" - 记录加 4 ,记录现在是 [5, -2, 4] // "C" - 使前一次得分的记录无效并将其移除,记录现在是 [5, -2] // "D" - 记录加 2 * -2 = -4 ,记录现在是 [5, -2, -4] // "9" - 记录加 9 ,记录现在是 [5, -2, -4, 9] // "+" - 记录加 -4 + 9 = 5 ,记录现在是 [5, -2, -4, 9, 5] // "+" - 记录加 9 + 5 = 14 ,记录现在是 [5, -2, -4, 9, 5, 14] // 所有得分的总和 5 + -2 + -4 + 9 + 5 + 14 = 27 // 示例 3: // 输入:ops = ["1"] // 输出:1 // 提示: // 1 <= ops.length <= 1000 // ops[i] 为 "C"、"D"、"+",或者一个表示整数的字符串。整数范围是 [-3 * 104, 3 * 104] // 对于 "+" 操作,题目数据保证记录此操作时前面总是存在两个有效的分数 // 对于 "C" 和 "D" 操作,题目数据保证记录此操作时前面总是存在一个有效的分数 // 通过次数34,578提交次数50,138 function calPoints(ops: string[]): number { let score: number[] = []; ops.forEach(op => { const sLen = score.length; const prev = score[sLen-1]; switch(op){ case '+' : const pPrev = score[sLen-2]; score.push(prev + pPrev);break; case 'D': score.push(2*prev);break; case 'C': score.pop();break; default: score.push(Number(op)); } }); return score.reduce((total, num) => total + num, 0); };
cd5d797db603e4de20f1dec7115a4b8261713f37
TypeScript
zeng-ge/router-configuration
/src/components/Menu/index.ts
2.703125
3
import $ from 'jquery' import { menus } from '../../constants/menu' import './index.scss' export default class Menu{ element: JQuery activeItem: any onSelectItem: Function tpl: string = `<ul class="router-menu"></ul>` constructor(activeItem: string, onSelectItem: Function) { this.element = $(this.tpl) this.activeItem = activeItem this.onSelectItem = onSelectItem this.bindEvents() } onSelectMenu = (event: any) => { const currentTarget = $(event.currentTarget) const type = currentTarget.attr('type') if (type !== this.activeItem.name) { const activeItem = this.getMenuItemByType(type) this.activeItem = activeItem this.updateActiveMenu() this.onSelectItem(activeItem) } } getMenuItemByType(type:string){ let menuItem = null for(let index = 0, length = menus.length; index < length; index++){ const menu = menus[index] if(menu.name === type){ menuItem = menu break } } return menuItem } bindEvents(){ this.element.on('click', '.router-menu-item', this.onSelectMenu) } updateActiveMenu() { const oldActiveMenuItem: JQuery = this.element.find('.active') oldActiveMenuItem.removeClass('active') const activeItem: JQuery = this.element.find(`[type=${this.activeItem.name}]`) activeItem.addClass('active') } renderItems() { const lis = [] for(let index = 0, length = menus.length; index < length; index++) { const menu = menus[index] lis.push(` <li type="${menu.name}" class="router-menu-item"> <div class="router-menu-item-content">${menu.text}</div> </li> `) } this.element.append(lis.join('')) } render() { this.renderItems() this.updateActiveMenu() return this.element } }
cd6e3a04d954b13eeb1f7e021fe1981898272d28
TypeScript
KUMJC29th/mjc-db-tenho
/src/view_models/grids/ColumnDefinition.ts
2.671875
3
/* Copyright © 2020 matcher-ice * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. * This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. */ export type SingleColumnDefinition<T> = { readonly field: string, readonly headerName: string, readonly cellClass?: string, readonly comparator?: (valueA: T | null, valueB: T | null) => number, readonly pinned?: "left" | "right", readonly sortable?: boolean, readonly sortingOrder?: readonly ("asc" | "desc" | null)[], readonly unSortIcon?: boolean, readonly valueFormatter?: (params: { readonly value: T | null }) => string, readonly width?: number } export type GroupColumnDefinition<T> = { readonly headerName: string, readonly children: readonly SingleColumnDefinition<T>[] } export type ColumnDefinition<T> = SingleColumnDefinition<T> | GroupColumnDefinition<T> export type DistributedColumnDefinition<T> = T extends infer R ? ColumnDefinition<R> : never;
56e23a8dd9a358ba8bb06779d36d22bd625d3ea7
TypeScript
fsicardir/apod
/src/clients/ApodClient.ts
2.859375
3
import { format } from 'date-fns' export interface ApodInfo { title: string, date: Date, url: string, hdurl: string, explanation: string, copyright?: string, } export interface ApodError { status: number, statusMsg: string, } const buildRequest = (date: Date): RequestInfo => { const baseUrl = 'https://api.nasa.gov/planetary/apod?api_key=A8KCEUDMveXLJNGDlsTpZ0k3VNtI4b8kosZ8wIpJ&hd=True&date='; const url = baseUrl.concat(format(date, 'yyyy-MM-dd')); const init: RequestInit = { method: 'GET', cache: 'force-cache', mode: 'cors', }; return new Request(url, init); }; const mapToError = (response: Response): ApodError => { return {status: response.status, statusMsg: response.statusText} }; export const getCard = async (date: Date): Promise<ApodInfo> => { return fetch(buildRequest(date)) .then((response) => { if (response.ok) return response.json(); throw mapToError(response); }) .catch((error) => { console.error('Error requesting data: ', error); throw error; }) };
683c5684e3e874bca8c73e5d7ede9d38b910ff47
TypeScript
PriyankaWagh1/root
/ES2015/es62.ts
3.5
4
//1 console.log('Fibonacci series'); const next = Symbol(); class Fibonacci{ previousNo:number currentNo:number value:number constructor(){ this.previousNo=0; this.currentNo=1; } [next](){ this.value = this.previousNo+this.currentNo this.previousNo = this.currentNo this.currentNo = this.value return this.value } } let f= new Fibonacci(); console.log(f.previousNo); console.log(f.currentNo); console.log(f[next]()); console.log(f[next]()); console.log(f[next]()); console.log(f[next]()); //2 console.log('Armstrong Number'); function isArmstrong(num){ let sum=0 let temp=num; const len= String(temp).split("").length; while(temp > 0){ let remainder=temp % 10; sum += remainder ** len; temp = Math.floor(temp/10); } if(sum==num) return true; else return false; } function getnextArmstrong(num1){ while(num1<Number.MAX_SAFE_INTEGER){ num1++; if(isArmstrong(num1)){ return num1; } } } console.log(getnextArmstrong(4)); //3 console.log("Adding functionality to getnextArtmstrong()"); function isArmstrong3(num){ let sum=0 let temp=num; const len= String(temp).split("").length; while(temp > 0){ let remainder=temp % 10; sum += Math.pow(remainder,len) temp = Math.floor(temp/10); } if(sum==num) return true; else return false; } let nums=0; function reset(){ nums=0; return nums; } function getnextArmstrong1(){ while(nums<10001){ if(nums<1000){ nums++; if(isArmstrong3(nums)) return nums; else{ reset(); return "Number is above 1000"; } } } } console.log(getnextArmstrong1()); //4 console.log("Chatroom using set and map"); const chatroom1=new Map(); chatroom1.set('c11','Hello World!'); chatroom1.set('c12','Hello there!'); chatroom1.set('c13','C13 here'); console.log(chatroom1); const chatroom2=new Map(); chatroom2.set('c21','Are you there?'); chatroom2.set('c22','Connecting...'); chatroom2.set('c23','Good morning'); console.log(chatroom2); function users(chatroom_name){ chatroom_name.forEach((value,key) => { console.log(`${key}`); }); } function messages(chatroom_name){ chatroom_name.forEach((value,key) => { console.log(`${value}`); }); } users(chatroom1); messages(chatroom1); users(chatroom2); messages(chatroom2);
11c69ce4942442bdb4029452bae418b76b891e11
TypeScript
SolAZDev/html2pug
/src/Options.ts
2.53125
3
/** * Defines all the options for html2pug. */ export interface Options { caseSensitive: boolean; collapseBooleanAttributes: boolean; collapseWhitespace: boolean; commas: boolean; doubleQuotes: boolean; fragment: boolean; preserveLineBreaks: boolean; removeEmptyAttributes: boolean; tabs: boolean; } // Default options for html2pug. export const defaultOptions = { caseSensitive: true, collapseBooleanAttributes: true, collapseWhitespace: true, commas: true, doubleQuotes: false, fragment: false, preserveLineBreaks: true, removeEmptyAttributes: true, tabs: false, };
483f2c53e2580b89eed9fee7b170274ca9113526
TypeScript
f-w/MyGovBC-MSP
/src/app/components/msp/common/birthdate/birthdate.component.ts
2.515625
3
import {Component, Input, ViewChild, Output, EventEmitter, AfterViewInit, OnInit, ChangeDetectorRef} from '@angular/core' import {NgForm} from "@angular/forms"; import {Person} from "../../model/person.model"; import {Relationship} from "../../model/status-activities-documents"; import * as moment from 'moment'; require('./birthdate.component.less'); @Component({ selector: 'msp-birthdate', templateUrl: './birthdate.component.html' }) export class MspBirthDateComponent implements OnInit, AfterViewInit{ lang = require('./i18n'); // Create today for comparison in check later today:any; constructor(private cd: ChangeDetectorRef){ this.today = moment(); } @Input() person: Person; @Input() showError: boolean; @Output() onChange = new EventEmitter<any>(); @Output() isFormValid = new EventEmitter<boolean>(); @Output() registerBirthDateComponent = new EventEmitter<MspBirthDateComponent>(); @ViewChild('formRef') form: NgForm; ngOnInit(): void { this.registerBirthDateComponent.emit(this); this.form.valueChanges.subscribe(values => { this.onChange.emit(this.form.valid); this.isFormValid.emit(this.form.valid); }); } ngAfterViewInit():void{ } setYearValueOnModel(value:number){ let org:string = value + ''; let trimmed = org.substring(0, 4); if(/[^\d]+/.test(trimmed)){ trimmed = trimmed.replace(/[^\d]/g, ''); } this.person.dob_year = parseInt(trimmed); } setDayValueOnModel(value:string){ let org:string = value + ''; let trimmed = org.substring(0, 2); if(/[^\d]+/.test(trimmed)){ trimmed = trimmed.replace(/[^\d]/g, ''); } this.person.dob_day = parseInt(value); } /** * Determine if date of birth is valid for the given person * * @returns {boolean} */ isValid(): boolean { // Validate if (!this.person.dob.isValid()) { return false; }else{ return true; } } isInTheFuture(): boolean { return this.person.dob.isAfter(this.today); } tooFarInThePast(): boolean { let far = (this.today.get('y') - this.person.dob.get('y')) > 150; return far; } ageCheck(): boolean { // Applicant rules if (this.person.relationship === Relationship.Applicant) { // must be 16 or older for applicant let tooYoung = this.person.dob.isAfter(moment().subtract(16, 'years')) return !tooYoung; } // ChildUnder19 rules else if (this.person.relationship === Relationship.ChildUnder19) { // must be less than 19 if not in school let lessThan19 = this.person.dob.isAfter(moment().subtract(19, 'years')) return lessThan19; } else if (this.person.relationship === Relationship.Child19To24) { // if child student must be between 19 and 24 let tooYoung = this.person.dob.isAfter(moment().subtract(19, 'years')); let tooOld = this.person.dob.isBefore(moment().subtract(24, 'years')); if(tooYoung){ // console.log('This child is less than 19 years old.') } if(tooOld){ // console.log('This child is older than 24.') } let ageInRange = !tooYoung && !tooOld; return ageInRange; }else{ return true; } } }
bc9ebf8403e86c6fb4ce9e0041a48a6357c7586b
TypeScript
Michele9122/PSC
/ClientApp/app/components/newStudent/newStudent.component.ts
2.609375
3
import { Component } from '@angular/core'; import { Response } from '@angular/http'; import { StudentServices } from '../../services/service'; import { FormGroup, FormControl, Validators, FormsModule, ReactiveFormsModule } from '@angular/forms'; @Component({ selector: 'new-student', templateUrl: './newStudent.component.html' }) export class newStudentComponent { public CourseList = []; public formData: FormGroup; public constructor(private empService: StudentServices) { this.empService.getCourseList() .subscribe( (data: Response) => (this.CourseList = data.json()) ); this.formData = new FormGroup({ 'Nome': new FormControl('', [Validators.required]), 'Cognome': new FormControl('', Validators.required), 'Matricola': new FormControl('', Validators.required), 'Corso': new FormControl(0, Validators.required) }); } /* customValidator(control: FormControl): { [s: string]: boolean } { if(control.value == "0") return { data: true }; else { return { data: false }; } } */ submitData() { if (this.formData.valid) { var Obj = { Nome: this.formData.value.Nome, Cognome: this.formData.value.Cognome, Matricola: this.formData.value.Matricola, CorsoId: this.formData.value.Corso, }; this.empService.postData(Obj).subscribe(); alert("Studente Inserito con Successo"); } } }
81fb4fae4e9097a78b2a151be840bf0fe2eb5b51
TypeScript
monurakkaya/ionic-capacitor-restaurant-list-example
/src/app/restaurant/models/filter.ts
2.703125
3
export class Filter { skip: number; limit: number; latitude: number; longitude: number; constructor(skip = 0, limit = 10, latitude = 0, longitude = 0) { Object.assign(this, {skip, limit, latitude, longitude}); } }
4c8ab1c8ffd40f152accbe4501b3617c0451db99
TypeScript
adamf92/ts-oo-api
/src/framework/abstract.controller.ts
2.546875
3
import { NextFunction, Request, Response, RequestParamHandler } from "express"; import { ControllerRoute, Route } from "./interface/route.interface"; import { Controllers } from "./controllers"; export abstract class AbstractController { [key: string]: Function; abstract routes(): ControllerRoute[]; abstract mainPath(): string; protected errorHandler(error: any) { // TODO } public getRoutes() { return this.routes().map<Route>(r => this._createRoute(r)); } private _createRoute(route: ControllerRoute): Route { let result: any = {}; result.method = route.method; if (this.mainPath() !== '') { result.path = '/' + this.mainPath() + '/' + route.path; } else { result.path = '/' + route.path; } result.controller = Controllers[this._parseControllerName()][route.use]; return result as Route; } private _parseControllerName() { let name: string = (<any> this.__proto__.constructor).name; name = name.substring(0, name.indexOf('Controller')); return name.replace(/([A-Z])/g, (s) => `-${s[0].toLowerCase()}`).substring(1); } }
e753995e8622d98b02eb6c117699fffde5ac2f9c
TypeScript
galenscook/algorithms
/javascript/src/sum.ts
2.515625
3
// Sample file ensuring test setup export default function sum(firstNum: number, secondNum: number) { return firstNum + secondNum; }
c1c800b22fc950e112cbd4b8c5a7e82bc9d7bca5
TypeScript
wgml/aoc-2018-typescript
/src/__tests__/day14.test.ts
3.125
3
import { first, second } from '../day14'; describe('First', () => { it('Score after 9 recipes', () => { const input: string = `9`; expect(first(input)).toBe('5158916779'); }); }); describe('First', () => { it('Score after 5 recipes', () => { const input: string = `5`; expect(first(input)).toBe('0124515891'); }); }); describe('First', () => { it('Score after 18 recipes', () => { const input: string = `18`; expect(first(input)).toBe('9251071085'); }); }); describe('First', () => { it('Score after 2018 recipes', () => { const input: string = `2018`; expect(first(input)).toBe('5941429882'); }); }); describe('Second', () => { it('Score appears 9 recipes', () => { const input: string = `51589`; expect(second(input)).toBe(9); }); }); describe('Second', () => { it('Score appears 5 recipes', () => { const input: string = `01245`; expect(second(input)).toBe(5); }); }); describe('Second', () => { it('Score appears 18 recipes', () => { const input: string = `92510`; expect(second(input)).toBe(18); }); }); describe('Second', () => { it('Score appears 2018 recipes', () => { const input: string = `59414`; expect(second(input)).toBe(2018); }); });
272e69498b78dea7c7ebdcbf9fe239c9b36f4b39
TypeScript
harlyq/deckmaker
/src/location.ts
2.859375
3
// Copyright 2014 Reece Elliott /// <reference path="_dependencies.ts" /> module DeckMaker { //--------------------------------- export enum LayoutType { Stack, FanHorizontal, FanVertical, Grid, Row, Column } //--------------------------------- export class Location extends Shape { cards: Card[] = []; layout: LayoutType = LayoutType.Stack; constructor(width: number, height: number) { super(); this.width = width; this.height = height; } private addCard(card: Card) { if (card.location) { if (card.location === this) return; // already added card.location.removeCard(card); } card.location = this; this.cards.push(card); } private removeCard(card: Card) { var i = this.cards.indexOf(card); if (i !== -1) { this.cards.splice(i, 1); card.location = null; } } addCards(cards: Card[]) { for (var i = 0; i < cards.length; ++i) this.addCard(cards[i]); } removeCards(cards: Card[]) { for (var i = 0; i < cards.length; ++i) this.removeCard(cards[i]); } draw(ctx: CanvasRenderingContext2D, transform: Transform) { ctx.save(); ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle = 'blue'; drawRect(ctx, transform, this.width, this.height); ctx.stroke(); var cardTransform = new Transform(); for (var i = 0; i < this.cards.length; ++i) { var card = this.cards[i]; cardTransform.copy(transform); cardTransform.postMultiply(card.getTransform()); card.draw(ctx); } ctx.restore(); } } //--------------------------------- export var locationDefinition = PropertyPanel.createDefinition({ type: Location, parent: Shape, properties: { layout: { editorType: 'list', getList: function(): { [key: string]: any } { return enumToList(LayoutType); } } } }); }
2868bb925795e1f58ba9084f898651c23e116b3a
TypeScript
liriliri/luna
/src/box-model/index.ts
2.671875
3
import map from 'licia/map' import isNum from 'licia/isNum' import isStr from 'licia/isStr' import { exportCjs, pxToNum } from '../share/util' import Component, { IComponentOptions } from '../share/Component' /** IOptions */ export interface IOptions extends IComponentOptions { /** Target element. */ element?: HTMLElement } /** * Css box model metrics. * * @example * const boxModel = new LunaBoxModel(container) * boxModel.setOption('element', document.getElementById('target')) */ export default class BoxModel extends Component<IOptions> { constructor(container: HTMLElement, options: IOptions = {}) { super(container, { compName: 'box-model' }) this.initOptions(options) if (this.options.element) { this.render() } this.bindEvent() } private bindEvent() { this.on('optionChange', (name) => { switch (name) { case 'element': this.render() break } }) } private render() { const { c } = this const boxModel = this.getBoxModelData() // prettier-ignore this.$container.html([boxModel.position ? `<div class="${c('position')}">` : '', boxModel.position ? `<div class="${c('label')}">position</div><div class="${c('top')}">${boxModel.position.top}</div><br><div class="${c('left')}">${boxModel.position.left}</div>` : '', `<div class="${c('margin')}">`, `<div class="${c('label')}">margin</div><div class="${c('top')}">${boxModel.margin.top}</div><br><div class="${c('left')}">${boxModel.margin.left}</div>`, `<div class="${c('border')}">`, `<div class="${c('label')}">border</div><div class="${c('top')}">${boxModel.border.top}</div><br><div class="${c('left')}">${boxModel.border.left}</div>`, `<div class="${c('padding')}">`, `<div class="${c('label')}">padding</div><div class="${c('top')}">${boxModel.padding.top}</div><br><div class="${c('left')}">${boxModel.padding.left}</div>`, `<div class="${c('content')}">`, `<span>${boxModel.content.width}</span>&nbsp;×&nbsp;<span>${boxModel.content.height}</span>`, '</div>', `<div class="${c('right')}">${boxModel.padding.right}</div><br><div class="${c('bottom')}">${boxModel.padding.bottom}</div>`, '</div>', `<div class="${c('right')}">${boxModel.border.right}</div><br><div class="${c('bottom')}">${boxModel.border.bottom}</div>`, '</div>', `<div class="${c('right')}">${boxModel.margin.right}</div><br><div class="${c('bottom')}">${boxModel.margin.bottom}</div>`, '</div>', boxModel.position ? `<div class="${c('right')}">${boxModel.position.right}</div><br><div class="${c('bottom')}">${boxModel.position.bottom}</div>` : '', boxModel.position ? '</div>' : ''].join('')) } private getBoxModelData() { const { element } = this.options const computedStyle = window.getComputedStyle(element) function getBoxModelValue(type: string) { let keys = ['top', 'left', 'right', 'bottom'] if (type !== 'position') { keys = map(keys, (key) => `${type}-${key}`) } if (type === 'border') { keys = map(keys, (key) => `${key}-width`) } return { top: boxModelValue(computedStyle[keys[0] as any], type), left: boxModelValue(computedStyle[keys[1] as any], type), right: boxModelValue(computedStyle[keys[2] as any], type), bottom: boxModelValue(computedStyle[keys[3] as any], type), } } const boxModel: any = { margin: getBoxModelValue('margin'), border: getBoxModelValue('border'), padding: getBoxModelValue('padding'), content: { width: boxModelValue(computedStyle['width']), height: boxModelValue(computedStyle['height']), }, } if (computedStyle['position'] !== 'static') { boxModel.position = getBoxModelValue('position') } return boxModel } } function boxModelValue(val: any, type?: string) { if (isNum(val)) return val if (!isStr(val)) return '‒' const ret = pxToNum(val) if (isNaN(ret)) return val if (type === 'position') return ret return ret === 0 ? '‒' : ret } if (typeof module !== 'undefined') { exportCjs(module, BoxModel) }
2ba3ba132cecb010c16010614c3098b409fab13c
TypeScript
hannesbraun/badenair
/frontend-customers/src/app/services/util/DateUtil.ts
2.9375
3
const iso8601 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/; export function convertToDate(body: any) { if (body === null || body === undefined) { return body; } if (typeof body !== 'object') { return body; } for (const key of Object.keys(body)) { const value = body[key]; if (isIso8601(value)) { body[key] = new Date(value); } else if (typeof value === 'object') { convertToDate(value); } } } export function isIso8601(value: any) { if (value === null || value === undefined) { return false; } return iso8601.test(value); }
4b09b81f1e09e5f14bc97c4a77303ef2efb442d6
TypeScript
microsoft/bedrock-cli
/src/lib/traefik/middleware.test.ts
2.65625
3
import { create } from "./middleware"; describe("TraefikIngressRoute", () => { test("the right name with service name is created", () => { const middlewareWithoutRing = create("my-service", "", [ "/home", "/info", "/data", ]); expect(middlewareWithoutRing.metadata.name).toBe("my-service"); expect(middlewareWithoutRing.metadata.namespace).toBe(undefined); expect(middlewareWithoutRing.spec.stripPrefix.forceSlash).toBe(false); expect(middlewareWithoutRing.spec.stripPrefix.prefixes.length).toBe(3); expect(middlewareWithoutRing.spec.stripPrefix.prefixes[0]).toBe("/home"); expect(middlewareWithoutRing.spec.stripPrefix.prefixes[1]).toBe("/info"); expect(middlewareWithoutRing.spec.stripPrefix.prefixes[2]).toBe("/data"); const middlewareWithRing = create("my-service", "prod", ["/home"]); expect(middlewareWithRing.metadata.name).toBe("my-service-prod"); expect(middlewareWithRing.spec.stripPrefix.prefixes.length).toBe(1); expect(middlewareWithRing.spec.stripPrefix.prefixes[0]).toBe("/home"); }); test("optional parameters", () => { const middlewareWithRing = create( "my-service", "prod", ["/home", "/away"], { forceSlash: true, namespace: "prod-ring" } ); expect(middlewareWithRing.metadata.name).toBe("my-service-prod"); expect(middlewareWithRing.metadata.namespace).toBe("prod-ring"); expect(middlewareWithRing.spec.stripPrefix.forceSlash).toBe(true); expect(middlewareWithRing.spec.stripPrefix.prefixes.length).toBe(2); expect(middlewareWithRing.spec.stripPrefix.prefixes[0]).toBe("/home"); expect(middlewareWithRing.spec.stripPrefix.prefixes[1]).toBe("/away"); }); });
cff98574615b0902650949548753a3fb8e8f504e
TypeScript
silky/refscript
/tests/pos/simple/intersection-00.ts
3.296875
3
/*@ foo :: ([Immutable]{ f: ({ string | v = "aaa"})=>string })=>void */ function foo(f: { f: any }) { } /*@ x :: [Immutable] { f: /\ ({ string | v = "aaa"})=>string /\ ({ number | v > 0 })=>number } */ declare var x; foo(x);
2c3101a9c1bdd7c9b990bf75a6782d03d1414a4a
TypeScript
unional/type-plus
/type-plus/ts/nominal/brand.spec.ts
3.40625
3
import { expect, it } from '@jest/globals' import { brand, flavor, testType, type Brand } from '../index.js' it('branded type does not resolve to never', () => { testType.never<Brand<'test', undefined>>(false) testType.never<Brand<'test', null>>(false) testType.never<Brand<'test', boolean>>(false) testType.never<Brand<'test', true>>(false) testType.never<Brand<'test', false>>(false) testType.never<Brand<'test', number>>(false) testType.never<Brand<'test', 0>>(false) testType.never<Brand<'test', 1>>(false) testType.never<Brand<'test', string>>(false) testType.never<Brand<'test', 'a'>>(false) const uniSym = Symbol() testType.never<Brand<'test', symbol>>(false) testType.never<Brand<'test', typeof uniSym>>(false) testType.never<Brand<'test', bigint>>(false) testType.never<Brand<'test', 1n>>(false) testType.never<Brand<'test', object>>(false) testType.never<Brand<'test', {}>>(false) testType.never<Brand<'test', { a: 1 }>>(false) testType.never<Brand<'test', []>>(false) testType.never<Brand<'test', Function>>(false) testType.never<Brand<'test', () => void>>(false) }) it('cannot assign from unbranded type', () => { const a = brand('a', { a: 1 }) const b = { a: 1 } testType.canAssign<typeof b, typeof a>(false) }) it('can assign to unbranded type', () => { const a = { a: 1 } const b = brand('a', { a: 1 }) testType.canAssign<typeof b, typeof a>(true) }) it('cannot assign between null and undefined brand', () => { type N = Brand<'b', null> type U = Brand<'b', undefined> testType.canAssign<N, U>(false) }) it('cannot assign between two different brand', () => { const a = brand('a', { a: 1 as const }) const b = brand('b', { b: 'b' }) testType.canAssign<typeof a, typeof b>(false) testType.equal<typeof a.a, 1>(true) testType.equal<typeof b.b, string>(true) }) it('can assign betwen same brand of the same type', () => { const a = brand('a', { a: 1 }) let b = brand('a', { a: 2 }) b = a expect(b.a).toBe(1) }) it('cannot assign betwen same brand with different type', () => { const a = brand('a', { a: 1 }) const b = brand('a', { b: 2 }) testType.canAssign<typeof a, typeof b>(false) }) it('cannot assign from flavor with the same name', () => { const b = brand('x', { a: 1 }) const f = flavor('x', { a: 1 }) testType.canAssign<typeof f, typeof b>(false) }) it('can assign to flavor with the same name (this is a feature of flavor)', () => { const b = brand('x', { a: 1 }) const f = flavor('x', { a: 1 }) testType.canAssign<typeof b, typeof f>(true) }) it('creates a typed brand ceator when invoke without subject', () => { const createPerson = brand('person') let person1 = createPerson(1) let person2 = createPerson(2) const createBlogPost = brand('Blog') const blogPost = createBlogPost(1) person1 = person2 person2 = person1 testType.equal<typeof blogPost, typeof person1>(false) }) it('accepts null as subject', () => { const b = brand('x', null) testType.never<typeof b>(false) }) it('accepts undefined as subject', () => { const b = brand('x', undefined) testType.never<typeof b>(false) }) it('accepts function as subject', () => { const b = brand('x', function boo() {}) const c = brand('x', function coo() {}) testType.never<typeof b>(false) testType.canAssign<typeof b, typeof c>(true) testType.canAssign<typeof c, typeof b>(true) }) it('can assign to another function brand based on function assignment logic', () => { function af() {} function bf(_: string) {} function cf(_: number) {} const a = brand('x', af) const b = brand('x', bf) const c = brand('x', cf) testType.canAssign<typeof af, typeof bf>(true) testType.canAssign<typeof a, typeof b>(true) testType.canAssign<typeof bf, typeof af>(false) testType.canAssign<typeof b, typeof a>(false) testType.canAssign<typeof cf, typeof bf>(false) testType.canAssign<typeof c, typeof b>(false) })
1be06a2fdcbbda5b908b8d794702903217aed447
TypeScript
liangjiancang/globalSpeed
/src/utils/migrateSchema.ts
2.859375
3
import { State } from "../types" import { getDefaultState } from "../defaults" import { randomId } from "./helper" export function migrateGrainData(state: State) { if (state.version < 7) { return getDefaultState() } if (state.version === 7) { state = sevenToEight(state) } /* if (state.version === 8) { state = eightToNine(state) } */ if (state.version !== 8) { return getDefaultState() } return state } // These migration functions should be self contained. function sevenToEight(state: State) { state.version = 8 state.rules.forEach(rule => { rule.condition = { parts: [{type: (rule as any).matchType || "CONTAINS", id: randomId(), value: (rule as any).match || ""}] } delete (rule as any).matchType delete (rule as any).match }) return state } /* function eightToNine(state: State) { state.version = 9 return state } */
0743da63a3e70f1e2be77213ab72d4383eacb7b4
TypeScript
ShipEngine/connect-sdk
/src/internal/carriers/tracking/tracking-info.ts
2.546875
3
import { ShipmentStatus, TrackingInfo as TrackingInfoPOJO } from "../../../public"; import { App, DateTimeZone, hideAndFreeze, Joi, _internal } from "../../common"; import { ShipmentIdentifierBase, ShipmentIdentifier } from "../shipments/shipment-identifier"; import { PackageTrackingInfo } from "./package-tracking-info"; import { TrackingEvent } from "./tracking-event"; export class TrackingInfo extends ShipmentIdentifierBase { public static readonly [_internal] = { label: "tracking info", schema: ShipmentIdentifier[_internal].schema.keys({ deliveryDateTime: DateTimeZone[_internal].schema, packages: Joi.array().items(PackageTrackingInfo[_internal].schema).optional(), events: Joi.array().min(1).items(TrackingEvent[_internal].schema), }), }; public readonly deliveryDateTime?: DateTimeZone; public readonly packages: readonly PackageTrackingInfo[]; public readonly events: readonly TrackingEvent[]; public get package(): PackageTrackingInfo | undefined { return this.packages[0]; } public get latestEvent(): TrackingEvent { const events = this.events; let latestEvent = events[0]; for (let i = 1; i < events.length; i++) { if (events[i].dateTime.getTime() > latestEvent.dateTime.getTime()) { latestEvent = events[i]; } } return latestEvent; } public get status(): ShipmentStatus { return this.latestEvent.status; } public get hasError(): boolean { return this.events.some((event) => event.isError); } public get shipDateTime(): DateTimeZone | undefined { for (const event of this.events) { if (event.status === ShipmentStatus.Accepted) { return event.dateTime; } } } public constructor(pojo: TrackingInfoPOJO, app: App) { super(pojo); this.deliveryDateTime = pojo.deliveryDateTime ? new DateTimeZone(pojo.deliveryDateTime) : undefined; this.packages = pojo.packages ? pojo.packages.map((parcel) => new PackageTrackingInfo(parcel, app)) : []; this.events = pojo.events.map((event) => new TrackingEvent(event)); // Make this object immutable hideAndFreeze(this); } }
7a8e766365f043ca2a4fbba596d8d8d352a22587
TypeScript
MissThee/page
/doc/learn-project/typescript-learn-project/ts-learn-doc/c18_decorators/metadataTest.ts
3.671875
4
import "reflect-metadata";//引入依赖,使编译后的js文件可使用 Reflect.defineMetadata() 等方法 namespace metadataTest { let target = {a: 1}; //给指定对象设置元数据 metadataValue Reflect.defineMetadata('metaKey1', "哈哈哈", target); Reflect.defineMetadata('metaKey2', "嘿嘿嘿", target, "laugh"); //从指定对象获取元数据 console.log(Reflect.getMetadata('metaKey1', target));//哈哈哈 console.log(Reflect.getMetadata('metaKey2', target, 'laugh'));//嘿嘿嘿 function d1(metadataValue: string): ClassDecorator { return function (target) {//装饰器 Reflect.defineMetadata('metaKey1', metadataValue, target); }; } function d2(metadataValue: string) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { Reflect.defineMetadata('metaKey2', metadataValue, target, propertyKey); }; } @d1('admin') class Post { param1: string = "123"; constructor() { this.param1 = 'hahaha'; } // @Reflect.metadata('metaKey2', 'zxc')//设置一个meta值:key为metaKey2,目标为new Post(),propertyKey为param1Value,value为zxc @d2("zxc") public param1Value() { return this.param1; } } //获取meta值,参数(metaKey, target) const metadata = Reflect.getMetadata('metaKey1', Post); //获取meta值,参数(metaKey, target, propertyKey) const metadata1 = Reflect.getMetadata('metaKey2', new Post(), 'param1Value'); console.log(metadata); console.log(metadata1); // 几个默认的元数据键 // 类型元数据使用元数据键"design:type" // 参数类型元数据使用元数据键"design:paramtypes" // 返回值类型元数据使用元数据键"design:returntype" function logType(target: any, key: string) { var t = Reflect.getMetadata("design:type", target, key); console.log(key, t, t.name); } class Demo { @logType public attr1: string = "zxc1"; @logType @Reflect.metadata("design:type", Number)//自行注入类型信息,此时logType中使用getMetadata方法获取类型,为此处注入的类型,而不是属性本身的类型 public attr2: string = "asd2"; } }
9bc26f160d0ae2eed3facb17256d74594bde95c8
TypeScript
mjfusa/react-native-windows
/packages/react-native-platform-override/src/UpgradeStrategy.ts
2.71875
3
/** * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. * * @format */ import GitReactFileRepository from './GitReactFileRepository'; import {OverrideFileRepository} from './FileRepository'; export interface UpgradeResult { hasConflicts: boolean; } /** * An UpgradeStrategy describes the process to upgrade an individual override * to a new version of the React Native source tree. */ export default interface UpgradeStrategy { upgrade( gitReactRepo: GitReactFileRepository, overrideRepo: OverrideFileRepository, newVersion: string, allowConflicts: boolean, ): Promise<UpgradeResult>; } export const UpgradeStrategies = { /** * No work needed to upgrade */ assumeUpToDate: (): UpgradeStrategy => ({ upgrade: async () => ({hasConflicts: false}), }), /** * Perform a three way merge of the original base file, the overriden version * of it, and the base file from a newwer version of React Native. */ threeWayMerge: ( override: string, baseFile: string, baseVersion: string, ): UpgradeStrategy => ({ upgrade: async (gitReactRepo, overrideRepo, newVersion, allowConflicts) => { const ovrContent = await overrideRepo.getFileContents(override); if (ovrContent === null) { throw new Error(`Could not read ${override}`); } const ovrAsPatch = await gitReactRepo.generatePatch( baseFile, baseVersion, ovrContent, ); const patched = (await gitReactRepo.getPatchedFile( baseFile, newVersion, ovrAsPatch, )) .replace(/<<<<<<< ours/g, '<<<<<<< Upstream') .replace(/>>>>>>> theirs/g, '>>>>>>> Override'); const hasConflicts = patched.includes('<<<<<<<'); if (!hasConflicts || allowConflicts) { await overrideRepo.setFileContents(override, patched); } return {hasConflicts}; }, }), /** * Overwrite our override with base file contents */ copyFile: (override: string, baseFile: string): UpgradeStrategy => ({ upgrade: async (gitReactRepo, overrideRepo, newVersion) => { const newContent = await gitReactRepo.getFileContents( baseFile, newVersion, ); if (newContent === null) { throw new Error(`Could not read ${baseFile}@${newVersion}`); } await overrideRepo.setFileContents(override, newContent); return {hasConflicts: false}; }, }), };
4cb0883d799d0c6010d23d74f0501bd57707a0ad
TypeScript
proteus-cpi/openmos-HMI
/src/app/angular/Data/execution-table.ts
2.71875
3
import { ExecutionTableRow } from './execution-table-row'; export class ExecutionTable { uniqueId: string; name: string; description: string; rows: ExecutionTableRow[]; registered: Date; constructor(et: ExecutionTable) { console.log("loaded execution table: " + JSON.stringify(et)); this.uniqueId = et.uniqueId; this.name = et.name; this.rows = et.rows; this.registered = et.registered; this.rows = new Array<ExecutionTableRow>(et.rows.length); for (let i = 0; i < et.rows.length; i++) { this.rows[i] = new ExecutionTableRow(et.rows[i]); } } }
35aec76a2d371214219c9c30b2fcdf0a8c2209f9
TypeScript
hyowe/ultravnc_repeater.js
/src/http/test-api-1.ts
2.515625
3
import {UltraVNCRepeater} from '../index'; import express from 'express'; export interface IConnectedPairItem { viewerConnectionId: string; serverConnectionId: string; } export interface IViewerConnection { remoteAddress: string; vncRemoteIdentity: string; } export interface IReverseServerConnection { remoteAddress: string; vncRemoteIdentity: string; } export interface IAllConnectionInfo { pairs: IConnectedPairItem[]; viewerConnections: Record<string, IViewerConnection>; reverseServerConnections: Record<string, IReverseServerConnection>; } export function showAllConnections(repeater: UltraVNCRepeater, req: express.Request, res: express.Response, next: () => void) { const viewerConnections = repeater.viewerConnections; const reverseServerConnections = repeater.reverseServerConnections; const connectedPairs = repeater.connectedPairs; const payload: IAllConnectionInfo = { pairs: Object.keys(connectedPairs) .map(key => { const item = connectedPairs[key]; return { viewerConnectionId: item.viewer.uniqueId, serverConnectionId: item.server.uniqueId }; }), viewerConnections: Object.entries(viewerConnections.primaryMap) .reduce((result, cur) => { const socket = cur[1]; result[cur[0]] = { remoteAddress: socket.value.socket.socket.remoteAddress && socket.value.socket.socket.remoteAddress.toString() || '', vncRemoteIdentity: socket.value.socket.vncRemoteIdentity }; return result; }, {} as Record<string, IViewerConnection>), reverseServerConnections: Object.entries(reverseServerConnections.primaryMap) .reduce((result, cur) => { const socket = cur[1]; result[cur[0]] = { remoteAddress: socket.value.socket.socket.remoteAddress && socket.value.socket.socket.remoteAddress.toString() || '', vncRemoteIdentity: socket.value.socket.vncRemoteIdentity }; return result; }, {} as Record<string, IViewerConnection>) }; res .status(200) .send(payload); }
29c5aabda4e17f51742e91460097d8446a40263b
TypeScript
Buhaiyang/deeplyAssign
/src/utils.ts
3.015625
3
// const curry = (fn: Function) => { // const curryN = (n, fn) => (...args: any[]) => // args.length >= n // ? fn(...args) // : curryN(n-args.length, (...innerArgs) => fn(...args, ...innerArgs)) // // Rest param do not count in function.length // return curryN(fn.length, fn) // } const isShadowNested = (obj: Object, ...props: string[]) => { const loops = props.length ? props : Object.keys(obj) for (let i in loops) { if (obj[Object(loops[i])] === obj) return true } return false } export { isShadowNested }
9d176ae85f01ed1812c57a63b14eaa57471bf9eb
TypeScript
Happy-Creater/SEO-Diagnostic-Warnings-Youtube
/src/app/_inherit/session-storage-handler.ts
3.046875
3
export abstract class SessionStorageHandler { constructor() { this.initSession(); } /** * Initialize session. */ abstract initSession(); /** * Save session. */ abstract saveSession(); /** * Get item of session. * @param key key of session */ protected getSessionItem(key: string): string { return window.sessionStorage.getItem(key); } /** * Set item of session. * @param key key of session * @param item item of session */ protected setSessionItem(key: string, item: string) { window.sessionStorage.setItem(key, item); } /** * Remove item of session. * @param key key of session */ protected removeSessionItem(key: string) { window.sessionStorage.removeItem(key); } }
6bd7f98bda337e29e14b00fd5161719e2550ff61
TypeScript
doc22940/offix
/packages/offix-conflicts-server/src/api/ObjectState.ts
3.453125
3
import { ObjectStateData } from "./ObjectStateData"; import { ObjectConflictError } from "./ObjectConflictError"; /** * Interface for handling changing state of the object. * Implementors can extend this interface to provide reliable way to * determine if object is in conflict and calculate next state * (version/hash etc.) that object should have after modification. */ export interface ObjectState { /** * Check for conflict for the data. If conflict existing error will be thrown to client to handle * the case * * @param serverState the data currently on the server * @param clientState the data the client wishes to perform some mutation with * @return ObjectConflictError when conflict happens or undefined otherwise */ checkForConflict(serverState: ObjectStateData, clientState: ObjectStateData): ObjectConflictError | undefined; }
d5eee86149b8a265d55f4cd2dedee2325d95cdf1
TypeScript
biggyspender/set-operations
/src/index.ts
3.40625
3
type SubSuperOp = <T>(arrA: T[], arrB: T[]) => boolean; const isSuperSet: SubSuperOp = (arrA, arrB) => { const setA = new Set(arrA); const setB = new Set(arrB); for (let item of setB) { if (!setA.has(item)) { return false } } return true }; const isSubSet: SubSuperOp = (arrA, arrB) => { return isSuperSet(arrB, arrA); }; function union<T>(arrA: T[], arrB: T[]): Set<T>; function union<T>(arrA: T[], arrB: T[], returnAsArray: true): T[]; function union<T>(arrA: T[], arrB: T[], returnAsArray: false): Set<T>; function union<T>(arrA:T[], arrB:T[], returnAsArray = false):T[]|Set<T> { const setA = new Set(arrA); const setB = new Set(arrB); const union = new Set([...setA, ...setB]); if (returnAsArray) { return [...union]; } else { return union; } }; function intersection<T>(arrA: T[], arrB: T[]): Set<T>; function intersection<T>(arrA: T[], arrB: T[], returnAsArray: true): T[]; function intersection<T>(arrA: T[], arrB: T[], returnAsArray: false): Set<T>; function intersection<T>(arrA:T[], arrB:T[], returnAsArray = false):T[]|Set<T> { const setA = new Set(arrA); const setB = new Set(arrB); const intersection = new Set([...setA].filter(x => setB.has(x))); if (returnAsArray) { return [...intersection]; } else { return intersection; } }; function difference<T>(arrA: T[], arrB: T[]): Set<T>; function difference<T>(arrA: T[], arrB: T[], returnAsArray: true): T[]; function difference<T>(arrA: T[], arrB: T[], returnAsArray: false): Set<T>; function difference<T>(arrA:T[], arrB:T[], returnAsArray = false):T[]|Set<T> { const setA = new Set(arrA); const setB = new Set(arrB); const difference = new Set([...setA].filter(x => !setB.has(x))); if (returnAsArray) { return [...difference]; } else { return difference; } } function symmetricDifference<T>(arrA: T[], arrB: T[]): Set<T>; function symmetricDifference<T>(arrA: T[], arrB: T[], returnAsArray: true): T[]; function symmetricDifference<T>(arrA: T[], arrB: T[], returnAsArray: false): Set<T>; function symmetricDifference<T>(arrA:T[], arrB:T[], returnAsArray = false):T[]|Set<T> { const symmetricDifference = new Set([...difference(arrA, arrB), ...difference(arrB, arrA)]); if (returnAsArray) { return [...symmetricDifference]; } else { return symmetricDifference; } }; export {isSubSet, isSuperSet, union, intersection, difference, symmetricDifference};
cd23b7f687489c9972b008b1859d3a4391bd1bb1
TypeScript
BlunterMonk/Jimbot
/src/commands/helper.ts
2.625
3
////////////////////////////////////////// // Author: Dahmitri Stephenson // Discord: Jimoori#2006 // Jimbot: Discord Bot ////////////////////////////////////////// import "../util/string-extension.js"; import * as fs from "fs"; import { log, debug, error } from "../global.js"; import { Config } from "../config/config.js"; const wikiEndpoint = "https://exvius.gamepedia.com/"; const ffbegifEndpoint = "http://www.ffbegif.com/"; const exviusdbEndpoint = "https://exvius.gg/gl/units/205000805/animations/"; const linkFilter = [ /\|Trial/, /\|Event/, /\|Quest/, /\]\]/, /\[\[/, /\[\[.*\]\]/, /\(/, /\)/ ]; export function getMentionID(search): string { if (search && !search.empty()) { log("Getting friend code for mentioned user: ", search); search = search.replace("<", ""); search = search.replace(">", ""); search = search.replace("!", ""); search = search.replace("@", ""); if (!search.isNumber()) return null; return search; } return null; } export function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } export function isLetter(str) { return str.length === 1 && str.match(/[a-z]/i); } export function convertSearchTerm(search) { var s = search; var alias = Config.getAlias(s.replaceAll(" ", "_")); if (alias) { //log("Found Alias: " + alias); return alias.replaceAll(" ", "_"); } //search = search.toLowerCase(); search = search.replaceAll(" ", "_"); return search; } export function convertValueToLink(value) { var link = value; linkFilter.forEach(filter => { link = link.replace(filter, ""); }); var title = link.toTitleCase("_"); title = title.replace("Ss_", "SS_"); title = title.replace("Cg_", "CG_"); title = title.replaceAll("_", " "); link = `[${title}](${wikiEndpoint + link.replaceAll(" ", "_")}) `; //log("Converted Link: " + link); return link; } export function getQuotedWord(str) { if (str.replace(/[^\""]/g, "").length < 2) { return null; } var start = str.indexOf('"'); var end = str.indexOfAfterIndex('"', start + 1); var word = str.substring(start + 1, end); log(start); log(end); log("Quoted Word: " + word); if (word.empty()) { return null; } return word; } export function getFileExtension(link) { return link.substring(link.lastIndexOf("."), link.length); }
2b2f2eeeae3f8d083ada610fe28b32032776f8f1
TypeScript
wpilibsuite/wpilib-ws-robot
/src/examples/debug-accelerometer.ts
2.921875
3
import SimDevice, { FieldDirection } from "../sim-device"; export default class SimAccelerometer extends SimDevice { private _sensitivity: number = 2; constructor() { super("BuiltInAccelerometer"); this.registerField("accelX", FieldDirection.BIDIR, 0); // fieldIdent: <>accelX this.registerField("accelY", FieldDirection.BIDIR, 0); // fieldIdent: <>accelY this.registerField("accelZ", FieldDirection.BIDIR, 0); // fieldIdent: <>accelZ this.registerField("sensitivity", FieldDirection.OUTPUT_FROM_ROBOT_CODE, 2); // fieldIdent: <sensitivity } public set x(value: number) { this.setValue("accelX", value); } public get x(): number { return this.getValue("accelX"); } public set y(value: number) { this.setValue("accelY", value); } public get y(): number { return this.getValue("accelY"); } public set z(value: number) { this.setValue("accelZ", value); } public get z(): number { return this.getValue("accelZ"); } _onSetValue(field: string, value: any) { if (field === "sensitivity") { this._sensitivity = value; console.log("Setting sensitivity: ", value); } } }
b7ef90341149190ffc59f36e759d1155c987b5a2
TypeScript
thanhn51/angular_b6_reactive_form_bt1
/src/app/register/gender.ts
2.609375
3
export interface Gender { Male: string; Female: string; }
bdcc637c779120d5e0a9a937c7b3606d7b1c26c5
TypeScript
shellywhen/measure-flow
/visualizations/widgets/legend.ts
2.53125
3
class Legend{ data:any[] margin={ left:10, top:20 } height:number constructor(data:networkcube.LegendElement[], handlerFunction?:Function){ this.data = data; } setClickCallBack(handlerFunction){ this.clickCallBack = handlerFunction; } legendEntries; clickCallBack:Function; appendTo(svg:SVGSVGElement){ this.legendEntries = d3.select'#legendSvg') .selectAll('.legend') .data(this.data) .enter().append('g') .attr('transform', (d,i)=>{ return 'translate('+this.margin.left+','+(this.margin.top+i*20)+')' }) this.height = this.margin.top+this.data.length*20 $(svg).height(this.height); this.legendEntries.append('circle') .attr('r', 5) .style('opacity', .7) .style('fill', function(d){ if(d.color) return d.color; else return '#000'; }) .style('stroke', function(d){ if(d.color) return d.color; else return '#000'; }) .style('stroke-width', 2) .on('click', this.clickCallBack); this.legendEntries.append('text') .text(function(d){ return d.name; }) .attr('x', 20) .attr('y', 5) } }
8f6b458cad8b35449d4c682d40ca170aca3fd366
TypeScript
aditya43/typescript
/04-Advanced-Types/06-Function-Overloads.ts
3.65625
4
type Combinable = string | number; function add(a: number, b: number): number; // Function overload function add(a: string, b: string): string; // Function overload function add(a: number, b: string): string; // Function overload function add(a: string, b: number): string; // Function overload function add(a: Combinable, b: Combinable) { if (typeof a === 'string' || typeof b === 'string') { return a.toString() + b.toString(); } return a + b; } console.log(add(2, 2)); console.log(add('2', '2')); console.log(add('2', 2)); console.log(add(2, '2'));
a32a42c80afd754ebab7e480212542d9520c5111
TypeScript
pedromsilvapt/data-async-iterator
/src/errors/dropErrors.ts
2.625
3
import { AsyncIterableLike, toAsyncIterator } from "../core"; import { safe } from "../transformers/safe"; export function dropErrors<I> ( iterable : AsyncIterableLike<I> ) : AsyncIterable<I> { return safe( { [ Symbol.asyncIterator ] () : AsyncIterableIterator<I> { const iterator = toAsyncIterator( iterable ); return { [ Symbol.asyncIterator ] () { return this; }, next ( input : any ) : Promise<IteratorResult<I>> { return iterator.next( input ).catch( err => this.next( input ) ); }, throw ( reason : any ) : Promise<IteratorResult<I>> { if ( iterator.throw ) { return iterator.throw( reason ) as Promise<IteratorResult<unknown>> as Promise<IteratorResult<I>>; } else { return Promise.reject( reason ); } }, return ( value : any ) : Promise<IteratorResult<I>> { if ( iterator.return ) { return iterator.return( value ) as Promise<IteratorResult<unknown>> as Promise<IteratorResult<I>> } else { return Promise.resolve( { done: true, value } ); } } }; } } ); }
6ef3286424d2834e6215ea01cc333cf7cab4ecec
TypeScript
rubio41/Recognizers-Text
/JavaScript/packages/recognizers-number/src/number/chinese/parsers.ts
2.53125
3
import { BaseNumberParser, ParseResult, IParser } from "../parsers"; import { ChineseNumberParserConfiguration } from "./parserConfiguration"; import { Constants } from "../constants"; import { LongFormatType } from "../models"; import { ChineseNumeric } from "../../resources/chineseNumeric"; import { ExtractResult } from "../extractors"; import { CultureInfo, Culture } from "../../culture"; import { RegExpUtility, StringUtility } from "../../utilities"; import { BigNumber } from 'bignumber.js'; import trimEnd = require("lodash.trimend"); import sortBy = require("lodash.sortby"); export class ChineseNumberParser extends BaseNumberParser { readonly config: ChineseNumberParserConfiguration; constructor(config: ChineseNumberParserConfiguration) { super(config); this.config = config; } private toString(value: any): string { return this.config.cultureInfo ? this.config.cultureInfo.format(value) : value.toString(); } parse(extResult: ExtractResult): ParseResult | null { let extra = ''; let result: ParseResult; extra = extResult.data; let simplifiedExtResult: ExtractResult = { start: extResult.start, length: extResult.length, data: extResult.data, text: this.replaceTraditionalWithSimplified(extResult.text), type: extResult.type } if (!extra) { return result; } if (extra.includes("Per")) { result = this.perParseChs(simplifiedExtResult); } else if (extra.includes("Num")) { simplifiedExtResult.text = this.replaceFullWithHalf(simplifiedExtResult.text); result = this.digitNumberParse(simplifiedExtResult); result.resolutionStr = this.toString(result.value); } else if (extra.includes("Pow")) { simplifiedExtResult.text = this.replaceFullWithHalf(simplifiedExtResult.text); result = this.powerNumberParse(simplifiedExtResult); result.resolutionStr = this.toString(result.value); } else if (extra.includes("Frac")) { result = this.fracParseChs(simplifiedExtResult); } else if (extra.includes("Dou")) { result = this.douParseChs(simplifiedExtResult); } else if (extra.includes("Integer")) { result = this.intParseChs(simplifiedExtResult); } else if (extra.includes("Ordinal")) { result = this.ordParseChs(simplifiedExtResult); } if (result) { result.text = extResult.text; } return result; } private replaceTraditionalWithSimplified(value: string): string { if (StringUtility.isNullOrWhitespace(value)) { return value; } let result = ''; for(let index = 0; index < value.length; index++) { result = result.concat(this.config.tratoSimMapChs.get(value.charAt(index)) || value.charAt(index)); } return result; } private replaceFullWithHalf(value: string): string { if (StringUtility.isNullOrWhitespace(value)) { return value; } let result = ''; for(let index = 0; index < value.length; index++) { result = result.concat(this.config.fullToHalfMapChs.get(value.charAt(index)) || value.charAt(index)); } return result; } private replaceUnit(value: string): string { if (StringUtility.isNullOrEmpty(value)) return value; let result = value; this.config.unitMapChs.forEach((value: string, key: string) => { result = result.replace(new RegExp(key, 'g'), value); }); return result; } private perParseChs(extResult: ExtractResult): ParseResult { let result = new ParseResult(extResult); let resultText = extResult.text; let power = 1; if (extResult.data.includes("Spe")) { resultText = this.replaceFullWithHalf(resultText); resultText = this.replaceUnit(resultText); if (resultText === "半折") { result.value = 50; } else if (resultText === "10成") { result.value = 100; } else { let matches = RegExpUtility.getMatches(this.config.speGetNumberRegex, resultText); let intNumber: number; if (matches.length === 2) { let intNumberChar = matches[0].value.charAt(0); if (intNumberChar === "对") { intNumber = 5; } else if (intNumberChar === "十" || intNumberChar === "拾") { intNumber = 10; } else { intNumber = this.config.zeroToNineMapChs.get(intNumberChar); } let pointNumberChar = matches[1].value.charAt(0); let pointNumber: number; if (pointNumberChar === "半") { pointNumber = 0.5; } else { pointNumber = this.config.zeroToNineMapChs.get(pointNumberChar) * 0.1; } result.value = (intNumber + pointNumber) * 10; } else { let intNumberChar = matches[0].value.charAt(0); if (intNumberChar === "对") { intNumber = 5; } else if (intNumberChar === "十" || intNumberChar === "拾") { intNumber = 10; } else { intNumber = this.config.zeroToNineMapChs.get(intNumberChar); } result.value = intNumber * 10; } } } else if (extResult.data.includes("Num")) { let doubleMatch = RegExpUtility.getMatches(this.config.percentageRegex, resultText).pop(); let doubleText = doubleMatch.value; if (doubleText.includes("k") || doubleText.includes("K") || doubleText.includes("k") || doubleText.includes("K")) { power = 1000; } if (doubleText.includes("M") || doubleText.includes("M")) { power = 1000000; } if (doubleText.includes("G") || doubleText.includes("G")) { power = 1000000000; } if (doubleText.includes("T") || doubleText.includes("T")) { power = 1000000000000; } result.value = this.getDigitValueChs(resultText, power); } else { let doubleMatch = RegExpUtility.getMatches(this.config.percentageRegex, resultText).pop(); let doubleText = this.replaceUnit(doubleMatch.value); let splitResult = RegExpUtility.split(this.config.pointRegexChs, doubleText); if (splitResult[0] === "") { splitResult[0] = "零" } let doubleValue = this.getIntValueChs(splitResult[0]); if (splitResult.length === 2) { if (RegExpUtility.isMatch(this.config.symbolRegex, splitResult[0])) { doubleValue -= this.getPointValueChs(splitResult[1]); } else { doubleValue += this.getPointValueChs(splitResult[1]); } } result.value = doubleValue; } result.resolutionStr = this.toString(result.value) + "%"; return result; } private fracParseChs(extResult: ExtractResult): ParseResult { let result = new ParseResult(extResult); let resultText = extResult.text; let splitResult = RegExpUtility.split(this.config.fracSplitRegex, resultText); let intPart = ""; let demoPart = ""; let numPart = ""; if (splitResult.length === 3) { intPart = splitResult[0] || ""; demoPart = splitResult[1] || ""; numPart = splitResult[2] || ""; } else { intPart = "零"; demoPart = splitResult[0] || ""; numPart = splitResult[1] || ""; } let intValue = this.isDigitChs(intPart) ? this.getDigitValueChs(intPart, 1.0) : this.getIntValueChs(intPart); let numValue = this.isDigitChs(numPart) ? this.getDigitValueChs(numPart, 1.0) : this.getIntValueChs(numPart); let demoValue = this.isDigitChs(demoPart) ? this.getDigitValueChs(demoPart, 1.0) : this.getIntValueChs(demoPart); if (RegExpUtility.isMatch(this.config.symbolRegex, intPart)) { result.value = intValue - numValue / demoValue; } else { result.value = intValue + numValue / demoValue; } result.resolutionStr = this.toString(result.value); return result; } private douParseChs(extResult: ExtractResult): ParseResult { let result = new ParseResult(extResult); let resultText = extResult.text; if (RegExpUtility.isMatch(this.config.doubleAndRoundChsRegex, resultText)) { resultText = this.replaceUnit(resultText); let power = this.config.roundNumberMapChs.get(resultText.charAt(resultText.length - 1)); result.value = this.getDigitValueChs(resultText.substr(0, resultText.length - 1), power); } else { resultText = this.replaceUnit(resultText); let splitResult = RegExpUtility.split(this.config.pointRegexChs, resultText); if (splitResult[0] === "") { splitResult[0] = "零"; } if (RegExpUtility.isMatch(this.config.symbolRegex, splitResult[0])) { result.value = this.getIntValueChs(splitResult[0]) - this.getPointValueChs(splitResult[1]); } else { result.value = this.getIntValueChs(splitResult[0]) + this.getPointValueChs(splitResult[1]); } } result.resolutionStr = this.toString(result.value); return result; } private intParseChs(extResult: ExtractResult): ParseResult { let result = new ParseResult(extResult); result.value = this.getIntValueChs(extResult.text); result.resolutionStr = this.toString(result.value); return result; } private ordParseChs(extResult: ExtractResult): ParseResult { let result = new ParseResult(extResult); let resultText = extResult.text.substr(1); if (RegExpUtility.isMatch(this.config.digitNumRegex, resultText)) { result.value = this.getDigitValueChs(resultText, 1); } else { result.value = this.getIntValueChs(resultText); } result.resolutionStr = this.toString(result.value); return result; } private getDigitValueChs(value: string, power: number): number { let isLessZero = false; let resultStr = value; if (RegExpUtility.isMatch(this.config.symbolRegex, resultStr)) { isLessZero = true; resultStr = resultStr.substr(1); } resultStr = this.replaceFullWithHalf(resultStr); let result = this.getDigitalValue(resultStr, power); if (isLessZero) { result = - result; } return result; } private getIntValueChs(value: string): number { let resultStr = value; let isDozen = false; let isPair = false; if (RegExpUtility.isMatch(this.config.dozenRegex, resultStr)) { isDozen = true; resultStr = resultStr.substr(0, resultStr.length - 1); } else if (RegExpUtility.isMatch(this.config.pairRegex, resultStr)) { isPair = true; resultStr = resultStr.substr(0, resultStr.length - 1); } resultStr = this.replaceUnit(resultStr); let intValue = 0; let partValue = 0; let beforeValue = 1; let isRoundBefore = false; let roundBefore = -1; let roundDefault = 1; let isLessZero = false; if (RegExpUtility.isMatch(this.config.symbolRegex, resultStr)) { isLessZero = true; resultStr = resultStr.substr(1); } for(let index = 0; index < resultStr.length; index++) { let resultChar = resultStr.charAt(index); if (this.config.roundNumberMapChs.has(resultChar)) { let roundRecent = this.config.roundNumberMapChs.get(resultChar); if (roundBefore !== -1 && roundRecent > roundBefore) { if (isRoundBefore) { intValue += partValue * roundRecent; isRoundBefore = false; } else { partValue += beforeValue * roundDefault; intValue += partValue * roundRecent; } roundBefore = -1; partValue = 0; } else { isRoundBefore = true; partValue += beforeValue * roundRecent; roundBefore = roundRecent; if ((index === resultStr.length - 1) || this.config.roundDirectListChs.some(o => o === resultChar)) { intValue += partValue; partValue = 0; } } roundDefault = roundRecent / 10; } else if (this.config.zeroToNineMapChs.has(resultChar)) { if (index !== resultStr.length - 1) { if ((resultChar === "零") && !this.config.roundNumberMapChs.has(resultStr.charAt(index + 1))) { beforeValue = 1; roundDefault = 1; } else { beforeValue = this.config.zeroToNineMapChs.get(resultChar); isRoundBefore = false; } } else { partValue += this.config.zeroToNineMapChs.get(resultChar) * roundDefault; intValue += partValue; partValue = 0; } } } if (isLessZero) { intValue = - intValue; } if (isDozen) { intValue = intValue * 12; } if (isPair) { intValue = intValue * 2; } return intValue; } private getPointValueChs(value: string): number { let result = 0; let scale = 0.1; for(let index = 0; index < value.length; index++) { result += scale * this.config.zeroToNineMapChs.get(value.charAt(index)); scale *= 0.1; } return result; } private isDigitChs(value: string): boolean { return !StringUtility.isNullOrEmpty(value) && RegExpUtility.isMatch(this.config.digitNumRegex, value); } }
d9294c6a1175838969378343bb809b835255662e
TypeScript
yangxin1994/web-components-1
/packages/field-base/src/delegate-input-state-mixin.d.ts
2.515625
3
/** * @license * Copyright (c) 2021 Vaadin Ltd. * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/ */ import { DelegateStateMixin } from './delegate-state-mixin.js'; import { InputMixin } from './input-mixin.js'; import { ValidateMixin } from './validate-mixin.js'; /** * A mixin to forward properties to the input element. */ declare function DelegateInputStateMixin<T extends new (...args: any[]) => {}>( base: T ): T & DelegateInputStateMixinConstructor; interface DelegateInputStateMixinConstructor { new (...args: any[]): DelegateInputStateMixin; } interface DelegateInputStateMixin extends DelegateStateMixin, ValidateMixin, InputMixin { /** * The name of this field. */ name: string; /** * A hint to the user of what can be entered in the field. */ placeholder: string; /** * When present, it specifies that the field is read-only. */ readonly: boolean; /** * The text usually displayed in a tooltip popup when the mouse is over the field. */ title: string; } export { DelegateInputStateMixinConstructor, DelegateInputStateMixin };
7a0d15bb8f56bedde30f8c9c97f20d04fb7d1ce9
TypeScript
TrigenSoftware/weather
/src/App/services/weather/adapters.ts
2.578125
3
import { format } from 'date-fns'; import { parseFromTimeZone } from 'date-fns-timezone'; import WeatherData from '~/models/WeatherData'; export function weatherDataFromResponseData(responseData) { return WeatherData({ date: formatDate(responseData.dt_txt), temp: Math.round(responseData.main.temp), description: responseData.weather[0].description, humidity: responseData.main.humidity, clouds: responseData.clouds ? responseData.clouds.all : 0, precipitation: responseData.rain && responseData.rain['3h'] ? responseData.rain['3h'] : (responseData.snow && responseData.snow['3h'] ? responseData.snow['3h'] : 0) }); } function formatDate(utcDateString: string) { if (!utcDateString) { return ''; } const date = parseFromTimeZone(utcDateString, 'YYYY-MM-DD HH:mm:ss', { timeZone: 'Etc/UTC' }); return format(date, 'dd.MM.yyyy'); }
f7dd8a7edd3b1d71665622952f96c92d0300b294
TypeScript
IdentiTree/app
/backend/src/controllers/areaControllers.ts
2.703125
3
import { Area } from '../models/Area'; import { User } from '../models/User'; import asyncHandler from "express-async-handler"; import { Request, Response } from 'express'; import { estimateBiomeCarbonCapture } from '../util/treeUtils'; import { biomes as biomesData} from '../data/sampleData/biomeData'; /** * Get all areas * @route GET /api/area * @return all the areas */ const getAllAreas = asyncHandler(async (req: Request, res: Response) => { const areas = await Area.find({}); if (areas) { res.json(areas) } else { res.status(404); throw new Error('Areas not found'); } }); /** * get area by ID * * @route GET /api/area/id/:id * @return Area Object */ const areaInfo = asyncHandler(async (req: Request, res: Response) => { const id = req.params.id; const area: any = await Area.findById(id); if (area) { res.json({ area }); } else { res.status(400); throw new Error('Incorrect area ID'); } }); /** * Create a new area * * @route POST /api/area/ * @return area JSON */ const createArea = asyncHandler(async (req: Request, res: Response) => { const { name, coordinates, area, biomes }: any = req.body; const user: any = await User.findOne({}); const carbonCapture = estimateBiomeCarbonCapture(biomes, area); const landmass = await Area.create({ name, coordinates, area, biomes, carbonCapture, owner: user._id }).catch((error: any) => { res.status(400); throw new Error('Bad request, missing data'); }); res.json(landmass); }); /** * Get all the biome types * * @route GET /api/area/types * @return list of all the biomes */ const getBiomeTypes = asyncHandler(async (req: Request, res: Response) => { res.json(biomesData); }) const indexArea = asyncHandler(async (req: Request, res: Response) => { const areas: any = await Area.find(); if (areas) { res.json({ areas }); } else { res.status(403); throw new Error('Incorrect area name'); } }); export { areaInfo, createArea, indexArea, getBiomeTypes, getAllAreas };
b6f4f49df67340c4d796cf2d6f355c72de4560ad
TypeScript
ibanjb/pokemon-api
/client/src/redux/reducers/pokemons.ts
3.109375
3
import * as types from '../types/pokemons'; import IPokemon from '../../interfaces/IPokemon'; interface IState { list: Array<IPokemon>; deck: Array<String>; sortAscending: Boolean; loading: Boolean; } export const initialState: IState = { list: [], deck: [], sortAscending: true, loading: false, }; const pokemons = (state = initialState, action: any) => { switch (action.type) { case types.FETCH_POKEMONS_REQUEST: return { ...state, loading: true }; case types.FETCH_POKEMONS_SUCCESS: return { ...state, loading: false, list: action.pokemons, deck: [], }; case types.FETCH_POKEMONS_FAILURE: return { ...state, loading: false, list: [], deck: [] }; case types.ADD_POKEMON_TO_DECK: if (state.deck.length < 5) { const deckAdd = [...state.deck]; deckAdd.push(action.id); return { ...state, deck: deckAdd }; } return { ...state }; case types.REMOVE_POKEMON_TO_DECK: const removeDeck = [...state.deck]; var index = removeDeck.indexOf(action.id); if (index !== -1) { removeDeck.splice(index, 1); } return { ...state, deck: removeDeck }; case types.SORT_ASCENDING: const ascendingList = [...state.list]; ascendingList.sort((a, b) => a.name > b.name ? 1 : b.name > a.name ? -1 : 0 ); return { ...state, list: ascendingList, sortAscending: true }; case types.SORT_DESCENDING: const descendingList = [...state.list]; descendingList.sort((a, b) => b.name > a.name ? 1 : a.name > b.name ? -1 : 0 ); return { ...state, list: descendingList, sortAscending: false }; default: return { ...state }; } }; export default pokemons;
1a9aa2f4fb8ea7578ba1477c78bafbd38f3731dd
TypeScript
KimHunJin/Study-Book
/algorithm/src/leetcode/LC_2357.ts
3.28125
3
function minimumOperations(nums: number[]): number { let result = 0 const sortedArr = [...nums].sort((a,b) => a-b) for (let i=0;i<sortedArr.length; i++) { const n = sortedArr[i]; if (n <= 0) { continue } for (let j=i+1; j<sortedArr.length; j++) { sortedArr[j] = sortedArr[j] - n } for (let j=0; j<nums.length; j++) { if (nums[j] > 0) { nums[j] = nums[j] - n } } result++ } return result };
8af97472dba46f832f9376466da511bb9f98f8eb
TypeScript
yamacraft/SampRa-android
/firebase/functions/src/index.ts
2.546875
3
// https://github.com/FirebaseExtended/custom-auth-samples/blob/master/Line/server/app.js 'use strict'; import * as functions from 'firebase-functions'; import { FirebaseError } from 'firebase-admin'; // Modules imports const rp = require('request-promise'); const express = require('express'); const bodyParser = require('body-parser'); // Firebase Setup // service-account.jsonはlib配下に置く const admin = require('firebase-admin'); const serviceAccount = require('./service-account.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); function generateTwitchApiRequest(apiEndpoint: string, accessToken: string) { return { url: apiEndpoint, headers: { 'Authorization': `OAuth ${accessToken}` }, json: true }; } // Firebase登録情報の取得 function getFirebaseUser(uid: string, accessToken: string) { return admin.auth().getUser(uid).catch((error: FirebaseError) => { // まだ作成されていない場合は、下記の処理を実施 if (error.code === 'auth/user-not-found') { const getProfileOptions = generateTwitchApiRequest('https://id.twitch.tv/oauth2/validate', accessToken); return rp(getProfileOptions).then((response: {login:string, user_id:string}) => { const twitchUid = response.user_id; const displayName = response.login; console.log(`Twitch displayName:${displayName}`) console.log('Create new Firebase user for Twitch user uid = "', twitchUid,'"'); // 作成したUser情報を登録して返却 return admin.auth().createUser({ uid: twitchUid, displayName: displayName }); }); } throw error; }); } // accessToken検証 function verifyTwitchToken(accessToken: string) { // 外部アクセスするので有料プラン(Flame or Blaze)必須 const verifyTokenOptions = generateTwitchApiRequest('https://id.twitch.tv/oauth2/validate', accessToken); return rp(verifyTokenOptions) .then((response: { user_id: string; }) => { // 本来ならClientIdのチェックを行う const uid = response.user_id; return getFirebaseUser(uid, accessToken); }) .then((userRecord: { uid: string; }) => { // Firebase AuthenticationのaccessTokenを取得して返す const tokenPromise = admin.auth().createCustomToken(userRecord.uid); tokenPromise.then( (token: string) => { console.log( 'Created Custom token for UID "', userRecord.uid, '" Token:', token); }); return tokenPromise; }); } // ExpressJS setup const app = express(); app.use(bodyParser.json()); // POST /verifyTwitch export const verifyTwitch = functions.https.onRequest((request, response) => { if(request.body.token === undefined) { const ret = { error_message: 'Access Token not found' }; return response.status(400).send(ret); } const reqToken = request.body.token; verifyTwitchToken(reqToken) .then((customAuthToken: string) => { const ret = { firebase_token: customAuthToken }; return response.status(200).send(ret); }) .catch((err: FirebaseError)=> { const ret = { error_message: 'Authentication error: Cannot verify access token.' }; return response.status(403).send(ret); }); return response.status(400); }); export const helloWorld = functions.https.onRequest((request, response) => { response.send('Hello from Firebase!\n\n'); });
ae29b97b421e28c990653705aa7a33513cd00ec5
TypeScript
jani-nykanen/unnamed-dungeon-crawler
/src/enemycontainer.ts
2.703125
3
/** * Project Island 2021 * * (c) 2021 Jani Nykänen */ class EnemyContainer { private objects : Array<Enemy>; private types : Array<Function>; public readonly maxEnemyTypeIndex : number; private readonly flyingText : ObjectGenerator<FlyingText>; private readonly collectibles : ObjectGenerator<Collectible>; private readonly bullets : ObjectGenerator<Bullet>; constructor(types : Array<Function>, flyingText : ObjectGenerator<FlyingText>, collectibles : ObjectGenerator<Collectible>, bullets : ObjectGenerator<Bullet>) { this.objects = new Array<Enemy> (); this.types = Array.from(types); this.maxEnemyTypeIndex = this.types.length -1; this.flyingText = flyingText; this.collectibles = collectibles; this.bullets = bullets; } public initialCameraCheck(cam : Camera) { for (let o of this.objects) { o.cameraCheck(cam); } } public spawnEnemy(type : number, x : number, y : number, flyingText : ObjectGenerator<FlyingText>, collectibles : ObjectGenerator<Collectible>) { this.objects.push((new this.types[type].prototype.constructor( x, y, flyingText, collectibles)).passGenerators( this.flyingText, this.collectibles, this.bullets )); } public update(cam : Camera, stage : Stage, pl : Player, bullets : ObjectGenerator<Bullet>, ev : GameEvent) { for (let o of this.objects) { if (!o.doesExist()) continue; o.cameraCheck(cam); if (!o.isInCamera()) continue; stage.objectCollisions(o, cam, ev); o.playerCollision(pl, ev); o.update(ev); if (!o.isDying()) { for (let e of this.objects) { o.enemyToEnemyCollision(e); } bullets.applyBooleanEvent((a : any, ev : GameEvent) => o.bulletCollision(a, ev), ev); } } } public pushObjectsToArray(arr : Array<GameObject>) { for (let o of this.objects) { arr.push(o); } } }
a41ee8c11c25c18f9992b7e4f119d8a3d5cc1458
TypeScript
tobyhinloopen/bonaroo-totp-express
/test/support/testMiddleware.ts
3.015625
3
import * as express from "express"; import { Request, Response, NextFunction } from "express"; import supertest = require("supertest"); import bodyParser = require("body-parser"); /** * Test an express middleware by creating an express app & sending a request to * the app. The `test`-callback is invoked inside a request handler handling the * request. * @param middleware The middleware to add to the request app * @param test A function to test the request and/or response with inside a * request handler. * @param options */ export function testMiddleware( middleware: testMiddleware.Middleware|testMiddleware.Middleware[], test: (req: Request, res: Response) => Promise<void>, options: Partial<testMiddleware.Options> = {}, ): Promise<supertest.Response> { const { path, method, data } = { ...testMiddleware.DEFAULT_OPTIONS, ...options }; const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(...(Array.isArray(middleware) ? middleware : [middleware])); // Create a request handler to test the middleware with. // If the test didn't fail, render a 200 OK response. app[method](path, async (req, res, next) => { try { await test(req, res); res.type("txt").send("Hi"); } catch (error) { next(error); } }); return new Promise((resolve, reject) => { // Register an error handler to capture errors in the request handler. // If an error is caught, reject the promise to indicate a test failure. // To ensure the express request will finish, we'll also pass the same error // back to express. app.use((error, req, res, next) => { reject(error); next(error); }); // Invoke the request handler by sending a request to the express app. supertest(app)[method](path).send(data).expect(200).then(resolve, reject); }); } export namespace testMiddleware { export type Middleware = (req: Request, res: Response, next: NextFunction) => void; export const DEFAULT_OPTIONS: Options = { path: "/", method: "get", data: {}, } export interface Options { path: string; method: "get" | "post"; data: string | object; } }
48c359c8ee9493a47b7547f169d38bf185d8e703
TypeScript
mikel512/chat-app
/src/app/app.component.ts
2.5625
3
import { Component, OnInit, AfterViewInit} from '@angular/core'; /* The @Component decorator specifies the following: - selector: this specifies how the component will be called within an HTML file. For this specific component the HTML will look like: <app-root></app-root> You can observe this yourself in the index.html file. - templateUrl: specifies the path for the corresponding HTML file - styleUrls: specifies the paths for the CSS filesto be used within the HTML file. Note the array notation. */ @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) /* This is the root component. Currently, the fuctions used here are for setting the size so that the app is responsive. The template(and HTML file is referred as a template in Angular) file for this component only includes the router outlet: <router-outlet></router-outlet> this specifies Angular to render routed components here. */ export class AppComponent implements OnInit, AfterViewInit{ title = 'chat-app'; heightWindow: number = window.innerHeight; navHeight: number = 0; contentHeight: number = 0; footerHeight: number = 0; constructor() { } ngOnInit() { } ngAfterViewInit() { this.contentHeight = this.heightWindow - (this.navHeight + this.footerHeight); } getNavSize(size: number) { this.navHeight = size; } getFooterSize(size: number) { this.footerHeight = size; } }
93e3849ca6a1916b67f85cbcbe155fa9db1c4b7d
TypeScript
paychex/core
/spec/tracker.ts
2.671875
3
import * as expect from 'expect'; import { set, unset } from 'lodash'; import { spy } from './index'; import { create } from '../trackers/index'; import { withNesting, withReplacement } from '../trackers/utils'; import { NestedStart, NestedTimingTracker, Tracker, TrackingSubscriber } from '../trackers/index'; import { Spy } from './index'; describe('trackers', () => { describe('create', () => { describe('createTracker', () => { it('returns Tracker instance', () => { const tracker = create(); ['child', 'context', 'event', 'error', 'start'].forEach( (method: keyof Tracker) => expect(tracker[method]).toBeInstanceOf(Function)); }); it('uses specified subscriber', () => { const subscriber: any = spy(); create(subscriber).event('message'); expect(subscriber.called).toBe(true); }); }); describe('Tracker', () => { let tracker: Tracker, subscriber: Spy; beforeEach(() => { subscriber = spy(); tracker = create(subscriber as any); }); describe('child', () => { it('delegates to root subscriber', () => { const child = tracker.child(); child.event('message'); expect(subscriber.called).toBe(true); expect(subscriber.args[0].type).toBe('event'); }); it('defaults data using ancestor contexts', () => { const child = tracker.child(); const grandchild = child.child(); tracker.context({ a: 1, b: 2, c: 3 }); child.context({ b: 1 }); grandchild.event('message', { c: 1 }); const info = subscriber.args[0]; expect(info.data).toMatchObject({ a: 1, b: 1, c: 1 }); }); }); describe('context', () => { it('overwrites existing values', () => { tracker.context({ a: 1 }); tracker.context({ a: 2 }); tracker.event('message'); expect(subscriber.args[0].data).toMatchObject({ a: 2 }); }); it('merges array values', () => { tracker.context({ a: [1] }); tracker.context({ a: [2] }); tracker.event('message'); expect(subscriber.args[0].data).toMatchObject({ a: [1, 2] }); }); it('does not use references', () => { const ref = Object.create(null); tracker.context(ref); ref.a = 1; ref.b = 2; tracker.event('message'); expect(subscriber.args[0].data).toEqual({}); }); }); describe('event', () => { it('creates event info', () => { tracker.event('message'); const info = subscriber.args[0]; expect(info).toMatchObject({ type: 'event', label: 'message' }); expect(typeof info.stop).toBe('number'); expect(typeof info.start).toBe('number'); expect(info.duration).toBe(0); }); it('includes context and data', () => { tracker.context({ a: 1, b: 1 }); tracker.event('message', { b: 2, c: 3 }); expect(subscriber.args[0].data).toMatchObject({ a: 1, b: 2, c: 3 }); }); }); describe('error', () => { it('creates error info', () => { const err = new Error('test error'); tracker.context({ a: 1 }); tracker.error(Object.assign(err, { key: 'value' })); expect(subscriber.args[0]).toMatchObject({ type: 'error', label: 'test error', duration: 0, count: 1, data: { a: 1, key: 'value', name: expect.any(String), stack: expect.any(String) } }); }); it('increments count', () => { const err = new Error('test error'); tracker.error(err); tracker.error(err); tracker.error(err); expect(subscriber.callCount).toBe(3); expect((err as any).count).toBe(3); expect(subscriber.args[0].count).toBe(3); }); it('warns on non-Errors', () => { const warn = console.warn; console.warn = spy(); ['non-error', null, undefined, 123].forEach(value => tracker.error.call(tracker, value)); expect(subscriber.called).toBe(false); expect((console.warn as Spy).callCount).toBe(4); console.warn = warn; }); }); describe('start', () => { it('returns function', () => { expect(tracker.start.call(tracker)).toBeInstanceOf(Function); }); it('creates timer info', async () => { const stop = tracker.start('label'); await new Promise(resolve => setTimeout(resolve, 10)); stop({ key: 'value' }); const info = subscriber.args[0]; expect(info).toMatchObject({ type: 'timer', label: 'label', count: 1, data: { key: 'value' } }); expect(info.duration).toBeGreaterThan(0); }); it('increments count', () => { const stop = tracker.start('label'); stop(); stop(); expect(subscriber.args[0].count).toBe(2); }); it('includes context and data', () => { tracker.context({ a: 1, b: 1 }); tracker.start('timer')({ b: 2, c: 3 }); expect(subscriber.args[0].data).toMatchObject({ a: 1, b: 2, c: 3 }); }); }); describe('browser compatibility', () => { it('times correctly using Date.now', () => { const now = Date.now(); const performance = globalThis.performance; unset(globalThis, 'performance'); tracker.event.call(tracker); expect(subscriber.args[0].start).not.toBeLessThan(now); set(globalThis, 'performance', performance); }); it('times correctly using Date#getTime', () => { const orig = Date.now; const performance = globalThis.performance; const now = new Date().getTime(); unset(Date, 'now'); unset(globalThis, 'performance'); tracker.event.call(tracker); expect(subscriber.args[0].start).not.toBeLessThan(now); set(Date, 'now', orig); set(globalThis, 'performance', performance); }); }); }); }); describe('utils', () => { describe('withNesting', () => { let tracker: NestedTimingTracker, subscriber: Spy; function delay(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } beforeEach(() => { subscriber = spy(); tracker = withNesting(create(subscriber as any)); }); it('has tracker methods', () => { ['child', 'context', 'event', 'error', 'start'].forEach( (method: keyof NestedTimingTracker) => expect(tracker[method]).toBeInstanceOf(Function)); }); it('creates tree correctly', async () => { async function loadSecurity(start: NestedStart) { const [stop] = start('load user roles'); await delay(5); // pretend data call stop({ role: 'admin' }); } async function loadFeatures(start: NestedStart, product: string) { const [stop] = start(`load ${product} features`); await delay(5); stop({ features: [ `${product}-feat-a`, `${product}-feat-b` ] }); } async function loadProducts(start: NestedStart) { const [stop, nest] = start('loading products'); await delay(5); await Promise.all([ loadFeatures(nest, 'prod-a'), loadFeatures(nest, 'prod-b') ]); stop({ products: ['prod-a', 'prod-b'] }); } async function loadClientData(clientId: string) { const [stop, nest] = tracker.start('load client data'); await loadProducts(nest); await loadSecurity(nest); stop({ clientId }); } await loadClientData('client-123'); expect(subscriber.args[0]).toMatchObject({ "count": 1, "type": "timer", "label": "load client data", "id": expect.any(String), "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [ { "count": 1, "label": "loading products", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [ { "count": 1, "label": "load prod-a features", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [], "features": [ "prod-a-feat-a", "prod-a-feat-b" ] } }, { "count": 1, "label": "load prod-b features", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [], "features": [ "prod-b-feat-a", "prod-b-feat-b" ] } } ], "products": [ "prod-a", "prod-b" ] } }, { "count": 1, "label": "load user roles", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [], "role": "admin" } } ], "clientId": "client-123" } }); }); it('only completed timings are tracked', async () => { const [stop, start] = tracker.start('load data'); start('child timing'); await delay(10); stop(); expect(subscriber.args[0]).toMatchObject({ "count": 1, "type": "timer", "label": "load data", "id": expect.any(String), "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [] } }); }); it('creates sibling for each stop', async () => { async function makeParallelCalls(start: NestedStart) { const [end] = start('parallel calls'); await Promise.all([ delay(10).then(() => end()), delay(15).then(() => end()), delay(20).then(() => end()) ]); } const [stop, nest] = tracker.start('load data'); await makeParallelCalls(nest); stop(); expect(subscriber.args[0]).toMatchObject({ "count": 1, "type": "timer", "label": "load data", "id": expect.any(String), "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [ { "count": 1, "label": "parallel calls", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [] } }, { "count": 2, "label": "parallel calls", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [] } }, { "count": 3, "label": "parallel calls", "start": expect.any(Number), "stop": expect.any(Number), "duration": expect.any(Number), "data": { "children": [] } } ] } }); }); it('tracks root twice if stopped twice', () => { const [stop, start] = tracker.start('root'); const [stop_child] = start('child'); stop_child(); stop(); stop(); expect(subscriber.callCount).toBe(2); expect(subscriber.calls[0].args[0].count).toBe(1); expect(subscriber.calls[1].args[0].count).toBe(2); }); }); describe('utils', () => { describe('withReplacement', () => { let map: Map<RegExp, string>, collector: Spy, replace: TrackingSubscriber; beforeEach(() => { map = new Map([ [/\ben\b/, 'English'], [/^lang$/, 'Language'], ]); collector = spy(); replace = withReplacement(collector as any, map); }); it('returns function', () => { expect(replace).toBeInstanceOf(Function); }); it('delegates to wrapped function', () => { replace({} as any); expect(collector.called).toBe(true); }); it('clones original object', () => { const object = { lang: 'en' }; replace(object as any); expect(object.lang).toBe('en'); }); it('ignores top-level keys', () => { replace({ lang: 'en' } as any); const info = collector.args[0]; expect('lang' in info).toBe(true); expect(info.lang).toBe('English'); }); it('replaces top-level values', () => { replace({ label: 'lang' } as any); expect(collector.args[0].label).toBe('Language'); }); it('replaces data keys', () => { replace({ data: { lang: 'en' }} as any); const info = collector.args[0]; expect(info).toMatchObject({ data: { Language: 'English' } }); }); it('replaces data values', () => { replace({ data: { lang: 'en' } } as any); const info = collector.args[0]; expect(info).toMatchObject({ data: { Language: 'English' } }); }); it('does not replace values if specified', () => { replace = withReplacement(collector as any, map, true); replace({ data: { lang: 'en' }, key: 'en' } as any); const info = collector.args[0]; expect(info).toMatchObject({ key: 'en', data: { Language: 'en' }, }); }); it('does not replace substrings', () => { replace({ lang: 'eng', data: { lang: 'len' } } as any); const info = collector.args[0]; expect(info).toMatchObject({ lang: 'eng', data: { Language: 'len' } }); }); it('skips non-strings', () => { replace({ id: 123, data: { val: 123, lang: null } } as any); const info = collector.args[0]; expect(info).toMatchObject({ id: 123, data: { val: 123, Language: null } }); }); it('skips keys missing from dictionary', () => { const object = { id: 'abc', data: { key: 'value' } }; replace(object as any); expect(collector.args[0]).toMatchObject(object); }); it('works with arrays', () => { replace({ lang: ['es', 'en'] } as any); expect(collector.args[0]).toMatchObject({ lang: ['es', 'English'] }); }); it('works with nested objects', () => { replace({ lang: ['es', 'en'], data: { lang: { avail: ['en', 'es'], selected: 'en', } } } as any); expect(collector.args[0]).toMatchObject({ lang: ['es', 'English'], data: { Language: { avail: ['English', 'es'], selected: 'English' } } }); }); it('respects position tokens', () => { replace({ label: 'lang', action: 'change lang', } as any); expect(collector.args[0]).toMatchObject({ label: 'Language', action: 'change lang', }); }); }); }); }); });
c6a7682ce02201aab24b8534035fc0a4c3787534
TypeScript
cockroach54/pyeongchang
/front/src/news/info.service.ts
2.625
3
import { Injectable } from '@angular/core'; declare var Materialize: any; @Injectable() export class InfoService { static player: string; static game: string; static cursor: number = 0; // 현재 뉴스 종류 인덱스. 아래 newsList의 index static gameKind: string; // 게임 세부종목 ex) 1500m, 5000m // static newsList: string[] = ['텍스트(선택)','카드(선택)','동영상(선택)','텍스트(전체)','카드(전체)','동영상(전체)']; static newsList: string[] = ['text','card','movie','text2','card2','movie2']; constructor(){ } static show(){ console.log('$$$$$$$' , this.cursor); } static plusCursor(){ // if(this.cursor == this.newsList.length-1) return; if(this.cursor==1 && !this.player){ var ment = '선수를 선택하지 않았습니다. 선수를 선택해 주세요.'; Materialize.toast(ment, 3000) // 3000 is the duration of the toast return; } if(this.cursor==this.newsList.length) alert('마지막 뉴스입니다. 감사합니다.'); else this.cursor++; console.log('cursor: ', this.cursor); } static minusCursor(){ if(this.cursor == 0 ) alert('첫번째 탭입니다.'); else this.cursor--; console.log('cursor: ', this.cursor); } }
5a796b84c98421343fc24eba64b86554ce94d5da
TypeScript
ramyfarid922/knapsack-ts
/tests/packer.spec.ts
2.703125
3
import { Packer } from "../src/packer" import * as fs from "fs" import * as path from "path" // I used the separate test cases samples to try the pack functions on multiple inputs // during the test driving // I have tested the implemenetd algorithm and it passes 3 of the test cases while one of them fails // I currently might not have enough time to debug why the algorithm fails at this sample specifically describe("Packer's pack API function works correctly", () => { it('Should work correctly for input1.txt', () => { expect(Packer.pack(path.join(__dirname, "./samples/input1.txt"))).toEqual("4") }); it('Should work correctly for input2.txt', () => { expect(Packer.pack(path.join(__dirname, "./samples/input2.txt"))).toEqual("") }); it('Should work correctly for input3.txt', () => { expect(Packer.pack(path.join(__dirname, "./samples/input3.txt"))).toEqual("2,7") }); it('Should work correctly for input4.txt', () => { expect(Packer.pack(path.join(__dirname, "./samples/input4.txt"))).toEqual("8,9") }); })
cc2d26b85afe0536e5380dc610890483a2d95c0e
TypeScript
gpa/MediaCrawler
/src/util/FileSaver.ts
2.859375
3
import { writeFile } from 'fs'; import { join } from 'path'; export default class FileSaver { private path: string; private fileWritePromises: Promise<void>[]; private writtenFilesCount: number; public constructor(path: string) { this.path = path; } public async waitForWrittingFinished() : Promise<void> { await Promise.all(this.fileWritePromises); } public save(name: string, content: string, encoding: string) { this.fileWritePromises.push(this.saveFileAsync(name, content, encoding)); } private saveFileAsync(name: string, content: string, encoding: string): Promise<void> { return new Promise(function (resolve, reject) { writeFile(join(this.path, name), content, encoding, function (err) { if (err) { console.log(err); reject(err); } else { resolve(); } }); }); } }
c0499756ff9c86a97538878210736b1001963e4d
TypeScript
gmalkas/genovesa
/client/ui/timeline/resume.ts
2.953125
3
/// <reference path="../../definitions/references.d.ts"/> /// <reference path="./resume-sections.ts"/> /// <reference path="../iview.ts"/> /// <reference path="../../template-factory.ts"/> module Genovesa.UI.Timeline { /** * A simple resume for a person that can be embedded into the timeline panel. * * @class * @param {Genovesa.Models.Person} person The person you want a resume for. */ export class Resume implements IView { /** @var {Genovesa.Models.Person} The person you a resume for. */ private person: Genovesa.Models.Person = null; /** @var {JQuery} The HTML body of this resume. */ private body: JQuery = null; /** @var {Genovesa.UI.Timeline.ResumeSection} The resume section for the identity of the person. */ private identity: ResumeSection = null; /** @var {Genovesa.UI.Timeline.ResumeSection} The resume section for the other details of the person. */ private other: ResumeSection = null; /** @var {JQuery} Underlying JQuery view. */ private _view: JQuery = null; /** * Creates an instance of Resume. * * @constructor * @param {Genovesa.Models.Person} person The person you want a resume for. */ constructor(person: Genovesa.Models.Person) { this._view = TemplateFactory.create('timeline/resume', person); this.person = person; this.body = this.view.find('#resume-body'); this.generateSections(); } /** * Generate all sections for this resum (like familly section, person characteristic, ...). * * @method */ private generateSections(): void { this.identity = new ResumeSection(this.person.fullname); this.other = new ResumeSection('Autres annotations'); var identityKeys = ['Nom', 'Prénom', 'Date de naissance', 'Lieu de naissance', 'Date du décès', 'Lieu du décès']; // TODO Refactor this if needed later on this.person.attributes.forEach(attribute => { if (identityKeys.indexOf(attribute.key) >= 0) { this.identity.addProperty(attribute.key, attribute.references); } else { this.other.addProperty(attribute.key, attribute.references); } }); this.addSection(this.identity.view); this.addSection(this.other.view); } /** * Add a new section into the resume. * * @method {Object} section The new section. */ private addSection(section: JQuery) { this.body.append(section); } /** * Get the underlying JQuery view of this component. * * @method * @override * @return The underkying JQuery view of this component. */ public get view(): JQuery { return this._view; } } }
f3376983f5e2479bde3caaa5a4395b6735c2bb21
TypeScript
qumeta/GameDevStudyOf3DHtml5
/StudyDemos/Demo3/SoftEngine.ts
2.78125
3
/// <reference path="./Math.ts" /> module SoftEngine { export class Camera { constructor(public Position = Qumeta.Vector3.Zero(), public Target = Qumeta.Vector3.Zero()) { } } export class Mesh { public Vertices: Array<Qumeta.Vector3> = []; public Faces: Array<Qumeta.Vector3> = []; public Rotation: Qumeta.Vector3; public Position: Qumeta.Vector3; constructor(public name: string, verticesCount: number, facesCount: number) { this.Vertices = new Array(verticesCount); this.Faces = new Array(facesCount); this.Rotation = Qumeta.Vector3.Zero(); this.Position = Qumeta.Vector3.Zero(); } } export class Device { private workingWidth: number; private workingHeight: number; private workingContext: CanvasRenderingContext2D; private backbuffer: ImageData | undefined; private backbufferdata: Uint8ClampedArray | undefined; constructor(private workingCanvas: HTMLCanvasElement) { this.workingWidth = this.workingCanvas.width; this.workingHeight = this.workingCanvas.height; this.workingContext = this.workingCanvas.getContext("2d")!; } clear() { this.workingContext.clearRect(0, 0, this.workingWidth, this.workingHeight); this.backbuffer = this.workingContext.getImageData(0, 0, this.workingWidth, this.workingHeight); } present() { this.workingContext.putImageData(this.backbuffer!, 0, 0); } private putPixel(x: number, y: number, color: Qumeta.Color4) { this.backbufferdata = this.backbuffer!.data; var index = ((x >> 0) + (y >> 0) * this.workingWidth) * 4; // pixel this.backbufferdata[index] = color.r * 255; this.backbufferdata[index + 1] = color.g * 255; this.backbufferdata[index + 2] = color.b * 255; this.backbufferdata[index + 3] = color.a * 255; } private project(coord: Qumeta.Vector3, transMat: Qumeta.Matrix) { var point = Qumeta.Vector3.TransformCoordinates(coord, transMat); var x = point.x * this.workingWidth + this.workingWidth / 2.0 >> 0; var y = -point.y * this.workingHeight + this.workingHeight / 2.0 >> 0; return (new Qumeta.Vector2(x, y)); } private drawPoint(point: Qumeta.Vector2) { if (point.x >= 0 && point.y >= 0 && point.x < this.workingWidth && point.y < this.workingHeight) { this.putPixel(point.x, point.y, new Qumeta.Color4(1, 0, 0, 1)); } } private drawLine(point0: Qumeta.Vector2, point1: Qumeta.Vector2) { var dist = point1.subtract(point0).length(); if (dist < 2) { return; } var middlePoint = point0.add((point1.subtract(point0)).scale(0.5)); this.drawPoint(middlePoint); this.drawLine(point0, middlePoint); this.drawLine(middlePoint, point1); } render(camera: Camera, meshes: Array<Mesh>) { // 视图矩阵 var viewMatrix = Qumeta.Matrix.LookAtLH(camera.Position, camera.Target, Qumeta.Vector3.Up()); // 投影矩阵 var projectionMatrix = Qumeta.Matrix.PerspectiveFovLH(45 * Math.PI / 180, this.workingWidth / this.workingHeight, 0.01, 1.0); for (var index = 0; index < meshes.length; index++) { var cMesh = meshes[index]; // 世界矩阵 var worldMatrix = Qumeta.Matrix.RotationYawPitchRoll(cMesh.Rotation.y, cMesh.Rotation.x, cMesh.Rotation.z).multiply(Qumeta.Matrix.Translation(cMesh.Position.x, cMesh.Position.y, cMesh.Position.z)); // 变换矩阵 var transformMatrix = worldMatrix.multiply(viewMatrix).multiply(projectionMatrix); for (var indexFaces = 0; indexFaces < cMesh.Faces.length; indexFaces++) { var currentFace = cMesh.Faces[indexFaces]; var vertexA = cMesh.Vertices[currentFace.x]; var vertexB = cMesh.Vertices[currentFace.y]; var vertexC = cMesh.Vertices[currentFace.z]; var pixelA = this.project(vertexA, transformMatrix); var pixelB = this.project(vertexB, transformMatrix); var pixelC = this.project(vertexC, transformMatrix); this.drawLine(pixelA, pixelB); this.drawLine(pixelB, pixelC); this.drawLine(pixelC, pixelA); } } } LoadJSONFileAsync(fileName: string, callback: Function) { var jsonObject = { }; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", fileName, true); var that = this; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { jsonObject = JSON.parse(xmlhttp.responseText); callback(that.createMeshesFromJSON(jsonObject)); } }; xmlhttp.send(null); } createMeshesFromJSON(jsonObject: any): Array<Mesh> { var meshes = []; for (var meshIndex = 0; meshIndex < jsonObject.meshes.length; meshIndex++) { var verticesArray = jsonObject.meshes[meshIndex].vertices; var indicesArray = jsonObject.meshes[meshIndex].indices; var uvCount = jsonObject.meshes[meshIndex].uvCount; var verticesStep = 1; switch (uvCount) { case 0: verticesStep = 6; break; case 1: verticesStep = 8; break; case 2: verticesStep = 10; break; } var verticesCount = verticesArray.length / verticesStep; var facesCount = indicesArray.length / 3; var mesh = new SoftEngine.Mesh(jsonObject.meshes[meshIndex].name, verticesCount, facesCount); for (var index = 0; index < verticesCount; index++) { var x = verticesArray[index * verticesStep]; var y = verticesArray[index * verticesStep + 1]; var z = verticesArray[index * verticesStep + 2]; mesh.Vertices[index] = new Qumeta.Vector3(x, y, z); } for (var index = 0; index < facesCount; index++) { var a = indicesArray[index * 3]; var b = indicesArray[index * 3 + 1]; var c = indicesArray[index * 3 + 2]; mesh.Faces[index] = new Qumeta.Vector3(a, b, c); } var position = jsonObject.meshes[meshIndex].position; mesh.Position = new Qumeta.Vector3(position[0], position[1], position[2]); meshes.push(mesh); } return meshes; } } }
2f332fa7f523b3e9b68b37f89fd82ea19a4ec34f
TypeScript
vuescape/vuescape
/src/http/Axios.ts
2.765625
3
import axios, { AxiosAdapter, AxiosInstance, AxiosPromise } from 'axios' export interface CacheOptions { maxAgeMinutes: number maxSize: number shouldCacheAllRequests: boolean cacheFlag: string } export class Axios { private static shouldUseCache = false private static cacheAdapterFactory: () => AxiosAdapter private static axiosInstance: AxiosInstance private constructor() { } public static get instance() { if (!Axios.axiosInstance) { let axiosConfig = {} if (Axios.shouldUseCache) { axiosConfig = { adapter: Axios.cacheAdapterFactory() } } this.axiosInstance = axios.create(axiosConfig) } return this.axiosInstance } // tslint:disable-next-line: member-ordering public static useAuthenticationToken(authToken: string) { Axios.instance.defaults.headers.common.Authorization = `Bearer ${authToken}` } // tslint:disable-next-line: member-ordering public static useAuthorizationToken(authToken: string) { // tslint:disable-next-line: no-string-literal Axios.instance.defaults.headers.common['AuthZ'] = authToken } // tslint:disable-next-line: member-ordering public static async initCaching(cacheOptions: CacheOptions) { const cacheAdapter = (await import(/* webpackChunkName: 'axios-extensions' */ 'axios-extensions')).cacheAdapterEnhancer const Cache = (await import(/* webpackChunkName: 'lru-cache' */'lru-cache')).default Axios.cacheAdapterFactory = () => cacheAdapter(axios.defaults.adapter!, { enabledByDefault: cacheOptions.shouldCacheAllRequests, cacheFlag : cacheOptions.cacheFlag, defaultCache : new Cache<string, AxiosPromise>({ maxAge: cacheOptions.maxAgeMinutes * 60 * 1000, max : cacheOptions.maxSize, }), }) Axios.shouldUseCache = true } }
5b66ce28d4f3cac4e48dd8e8cd0fb055bd60a183
TypeScript
dreamerdihe/ricebook-frontend
/src/app/user.ts
2.890625
3
export class User { public accountName: string; public email: string; public phoneNumber: string; public dateOfBirth: string; public zipcode: string; public password: string; public headline?: string; public displayName?: string; public portrait?: string; constructor( accountName: string, email: string, phoneNumber: string, dateOfBirth: string, zipcode: string, password: string, displayName?: string, headline?: string, portrait?: string ) { this.accountName = accountName; this.email = email; this.phoneNumber = phoneNumber; this.dateOfBirth = dateOfBirth; this.zipcode = zipcode; this.password = password; this.displayName = displayName; this.headline = headline; this.portrait = portrait; } updateHeadline (headline: string) { this.headline = headline; } }
0913ac7718288e75271b67caff2d23be20e522f9
TypeScript
ezzooozz/trellis-app
/src/classes/AsyncInterval.ts
3.34375
3
type AsyncCallback = (...args: any[]) => PromiseLike<any|void> class AsyncIntervalInstance { private timeoutId: number private args: any[] private isRunning: boolean = true /** * An equivalent function to setInterval, but it waits for any asynchronous operations to complete before starting * queueing the next interval. This is important to prevent overlapping with long asynchronous processes. * @param callback * @param delay * @param args */ constructor (private callback: AsyncCallback, private delay: number, private id: number, args: any[]) { this.args = args this.queueNext() } private queueNext () { this.timeoutId = setTimeout(this.loop.bind(this), this.delay) } private async loop () { this.timeoutId = null await this.callback(...this.args) if (this.isRunning) { this.queueNext() } } /** * Call to stop the interval */ cancel () { this.isRunning = false if (this.timeoutId) { clearTimeout(this.timeoutId) } if (this.id && activeIntervals.has(this.id)) { activeIntervals.delete(this.id) } } } const activeIntervals: Map<number, AsyncIntervalInstance> = new Map() let lastIntervalId = 0 export function setAsyncInterval (callback: AsyncCallback, delay: number = 0, ...args: any[]): number { lastIntervalId++ const a = new AsyncIntervalInstance(callback, delay, lastIntervalId, args) activeIntervals.set(lastIntervalId, a) return lastIntervalId } export function clearAsyncInterval (intervalId: number) { const a = activeIntervals.get(intervalId) a.cancel() }
daf4a39b33a969fb8f8d25ce04a71e3a1a652742
TypeScript
chrisbtong/app-config-loader
/test/SecretService.test.ts
2.609375
3
import AzureSecretService from '../src/secretService/AzureSecretService'; import SecretService from '../src/secretService/SecretService'; describe('SecretService.ts', () => { describe('getSecret', () => { it('should reject with error if no .env file exist', () => { const secretService = new SecretService(); expect(secretService.getSecret('CloudProvider')).rejects.toEqual( new Error('There is no .env/default value for CloudProvider'), ); }); it('should use azure key vault if its name exist in .env', async () => { process.env.AzureKeyVaultName = 'SomeKeyVaultName'; const secretService = new SecretService(); jest.mock('../src/secretService/AzureSecretService'); AzureSecretService.prototype.getSecret = jest.fn().mockImplementation((key) => key); const cloudProvider = await secretService.getSecret('CloudProvider'); expect(cloudProvider).toEqual('CloudProvider'); }); it('should use env file if no azure key vault name provided', async () => { process.env.CloudProvider = 'Azure'; const secretService = new SecretService(); const cloudProvider = await secretService.getSecret('CloudProvider'); expect(cloudProvider).toEqual('Azure'); }); afterEach(() => { jest.resetAllMocks(); delete process.env.AzureKeyVaultName; delete process.env.CloudProvider; }); }); });
c8319e09f19ca49d2c31f4c986ca9eb94dd1e7f7
TypeScript
nervosnetwork/neuron
/packages/neuron-ui/src/tests/validators/tokenName/fixtures.ts
2.640625
3
import { ErrorCode } from 'utils/enums' const fixtures = { 'Should throw an error when token name is required but not provided': { params: { tokenName: '', required: true, isCKB: false, }, exception: ErrorCode.FieldRequired, }, 'Should pass when token name is not required and not provided': { params: { tokenName: '', required: false, isCKB: false, }, exception: null, }, 'Should throw an error when isCKB is false and the token name is Unknown which is reserved': { params: { tokenName: 'Unknown', required: false, isCKB: false, }, exception: ErrorCode.ValueReserved, }, 'Should throw an error when isCKB is false and the token name is CKBytes which is reserved': { params: { tokenName: 'CKBytes', required: false, isCKB: false, }, exception: ErrorCode.ValueReserved, }, 'Should pass when isCKB is true and the token name is CKBytes': { params: { tokenName: 'CKBytes', required: false, isCKB: true, }, exception: null, }, 'Should throw an error when isCKB is true and the token name is Unknown which is reserved': { params: { tokenName: 'Unknown', required: false, isCKB: true, }, exception: ErrorCode.ValueReserved, }, 'Should throw an error when token name is longer than 201 chars': { params: { tokenName: 't'.repeat(201), required: false, isCKB: true, }, exception: ErrorCode.FieldTooLong, }, 'Should pass when token name is less than or equal to 200 chars': { params: { tokenName: 't'.repeat(200), required: false, isCKB: true, }, exception: null, }, } export default fixtures
b6d0e455b66b079d6dfd3943903325c48d2f3d76
TypeScript
jeffersonest/express-typescript
/src/helpers/ErrorListHelper.ts
2.5625
3
import ErrorList from '../interfaces/IErrorList' class ErrorListHelper { protected readonly errors: Array<ErrorList> = [ { code: 0, message: 'success' } ] public getError (code: number): ErrorList { return this.errors[code] } } export default new ErrorListHelper()
3eb46c954d72f6a1feca60fce958f3fab486b128
TypeScript
b4dnewz/string-template
/src/index.ts
3.515625
4
interface IReplacements { [key: string]: any; } interface IFormatOptions { pattern?: string; ignoreErrors?: boolean; } const wordPattern = "(?!\\.)([a-zA-Z0-9_.]+)(?<!\\.)"; const defaultPattern = "{%s}"; /** * Gets an object property with dot notation support */ function get(object: any, path: string | string[]): any { path = Array.isArray(path) ? path : path.replace(/(\[(\d)\])/g, ".$2").split("."); object = object[path[0]]; if (object && path.length > 1) { return get(object, path.slice(1)); } return object; } /** * Replace template variables found in string with object name mapped values */ export function template(str: string, props: IReplacements, options: IFormatOptions = {}) { const matches: any = {}; const pattern = options.pattern || defaultPattern; const capturePattern = pattern.replace("%s", wordPattern); const reg = new RegExp(capturePattern, "gm"); let match = null; do { match = reg.exec(str); if (match !== null) { const [, key] = match; if (typeof matches[key] !== "undefined") { continue; } const val = get(props, key); if (typeof val === "undefined" && !options.ignoreErrors) { throw new Error(`Found invalid property "${key}" value is missing from replacements.`); } matches[key] = val; } } while (match); // When no replace matches are found return the string as it is if (Object.keys(matches).length === 0) { return str; } // Iterate through matches and replace them for (const key in matches) { if (matches.hasOwnProperty(key)) { const keyPattern = pattern.replace("%s", key); str = str.replace(new RegExp(keyPattern, "g"), matches[key]); } } return str; } /** * Creates a new template engine function with default parameters */ export function engine(options: IFormatOptions) { return (str: string, props: IReplacements, opts?: IFormatOptions) => { return template(str, props, { ...options, ...opts, }); }; } export default template;
e38906356fe906083fe711db62103ab16c07689a
TypeScript
EditionsENI/javascript-3e-edition
/ionic3-infos_hardware/src/pages/home/home.ts
2.703125
3
// Import de classes (système) import { Component } from '@angular/core'; import { Device } from '@ionic-native/device'; // Décorateur @Component // Description de la page (composant Angular) : // - selector = Page SCSS associée au script TypeScript // - templateUrl = Page HTML associée au script TypeScript @Component({ selector: 'page-home', templateUrl: 'home.html' }) // Classe de la page HomePage export class HomePage { // Variables de la classe private id: string; private modele: string; private cordova: string; private platforme: string; private version: string; private fabricant: string; private numeroSerie: string; private modeEmulation: boolean; // Constructeur de la classe // NB : Classe héritant d'une ou de plusieurs superclasses : // - Device : Gestion du hardware du périphérique constructor(private device: Device) {} // Fonction recupInfos // NB : Récupération des caractériqiques du périphérique recupInfos() { // Identifiant du périphérique this.id = this.device.uuid; // Modèle this.modele = this.device.model; // Information sur Cordova this.cordova = this.device.cordova; // Information sur la plateforme this.platforme = this.device.platform; // Version this.version = this.device.version; // Fabricant this.fabricant = this.device.manufacturer; // Numéro de série this.numeroSerie = this.device.serial; // Appareil virtuel ou non this.modeEmulation = this.device.isVirtual; } }
038aebf85bb55c16610ecbd63c5cc17fb834a361
TypeScript
vitarn/tdv
/test/schema.test.ts
3.046875
3
import Joi from 'joi' import { Schema } from '../src/schema' import { required, optional, reference, createDecorator } from '../src/decorator' describe('Schema', () => { describe('Joi', () => { it('use a copy version Joi', () => { expect(Schema.Joi).not.toBe(Joi) }) }) describe('merged metadata', () => { class FirstSchema extends Schema { @required(Joi => Joi.string().uuid({ version: 'uuidv4' })) id: string @optional(j => j.string()) name?: string } class SecondSchema extends FirstSchema { } class ThirdSchema extends SecondSchema { @required(j => j.string().min(5).max(40)) name: string @optional(j => j.number().min(1).max(199)) age?: number @optional active?: boolean } it('has no metadata in Schema', () => { expect(Object.keys(Schema.metadata)).toEqual([]) }) it('have metadata in FirstSchema', () => { expect(Object.keys(FirstSchema.metadata)).toEqual(['id', 'name']) }) it('have metadata in SecondSchema same as FirstSchema', () => { expect(Object.keys(SecondSchema.metadata)).toEqual(['id', 'name']) }) it('have metadata in ThirdSchema', () => { expect(Object.keys(ThirdSchema.metadata)).toEqual(['name', 'age', 'active', 'id']) }) }) describe('constructor', () => { class Profile extends Schema { @required name: string @optional(j => j.number().default(1)) age?: number } class User extends Schema { @required id: string @required profile: Profile } it('new plain instance', () => { const profile = new Profile() expect('name' in profile).toBe(false) expect('age' in profile).toBe(false) }) it('new default instance', () => { const profile = new Profile({}) expect('name' in profile).toBe(true) expect('age' in profile).toBe(true) expect(profile.name).toBeUndefined() expect(profile.age).toBe(1) }) it('new empty instance', () => { const profile = new Profile({}, { convert: false }) expect('name' in profile).toBe(true) expect('age' in profile).toBe(true) expect(profile.name).toBeUndefined() expect(profile.age).toBeUndefined() }) it('have 3 ways instance Schema with props', () => { const props = { id: '1', profile: { name: 'foo' } } const newUser = new User(props) const buildUser = User.build(props) const parseUser = new User().parse(props) expect(newUser.profile).toBeInstanceOf(Profile) expect(buildUser).toEqual(newUser) expect(parseUser).toEqual(newUser) }) }) describe('parse', () => { class Pet extends Schema { @optional name?: string } class Address extends Schema { @optional province?: string @optional city?: string } // WARN: If put Profile late than User. User#profile design:type is undefined class Profile extends Schema { @required name: string @optional(j => j.number().default(1)) age?: number @optional address?: Address } class User extends Schema { @required id: string @optional profile?: Profile @reference({ type: [Pet] }) pets?: Pet[] } it('parse object and init child', () => { const user = new User().parse({ id: '1', profile: { name: 'foo', age: 10, address: { province: 'gz', city: 'sz', }, }, }) expect(user.profile).toBeInstanceOf(Profile) expect(user.profile.address).toBeInstanceOf(Address) expect(user.profile.address.city).toBe('sz') }) it('skip child if not provide props', () => { const user = new User().parse({ id: '1', profile: { name: 'foo', }, }) expect(user.profile.address).toBeUndefined() }) it('accept child instance', () => { const address = new Address() const user = new User().parse({ id: '1', profile: { name: 'foo', address, }, }) expect(user.profile.address).toBe(address) }) it('leave null for child', () => { expect(new User().parse({ id: '1', profile: { name: 'foo', address: null, }, }).profile.address).toBeNull() }) it('leave undefined for child', () => { expect(new User().parse({ id: '1', profile: { name: 'foo', address: undefined, }, }).profile.address).toBeUndefined() }) it('init child even props is empty', () => { expect(new User().parse({ id: '1', profile: { name: 'foo', address: {}, }, }).profile.address).toBeInstanceOf(Address) }) it('apply joi default value', () => { const user = new User().parse({ id: '1', profile: { name: 'foo', }, }) expect(user.profile.age).toBe(1) }) it('cast value type by joi', () => { const user = new User().parse({ id: '1', profile: { name: 'foo', age: ' 10 ' as any, }, }) expect(user.profile.age).toBe(10) }) it('leave wrong type value there', () => { const user = new User().parse({ id: '1', profile: { name: 'foo', age: '10y' as any, }, }) expect(user.profile.age).toBe('10y') }) it('correct handle Schema[] type', () => { expect(new User().parse({ id: '1', pets: [{ name: 'qq' }] }).pets[0].name).toBe('qq') expect(new User().parse({ id: '1', pets: [{ name: 'qq' }] }).pets[0]).toBeInstanceOf(Pet) let pet = new Pet({ name: 'qq' }) expect(new User().parse({ id: '1', pets: [pet] }).pets[0]).toBe(pet) }) }) describe('toJSON', () => { class Pet extends Schema { @optional name?: string } class Profile extends Schema { @required name: string } class User extends Schema { @required id: number @required profile: Profile @reference({ type: [Pet] }) pets?: Pet[] } it('output json include refs', () => { let profile = new Profile({ name: 'Joe' }) let pet = new Pet({ name: 'qq' }); (pet as any).bad = true let user = new User({ id: 1, profile, pets: [pet], }) expect(user.toJSON()).toEqual({ id: 1, profile: { name: 'Joe', }, pets: [{ name: 'qq', }], }) }) }) describe('validate', () => { class Pet extends Schema { @optional name?: string } class Profile extends Schema { @optional(j => j.string()) name?: string @optional(j => j.number().default(1)) age?: number } class User extends Schema { @required(j => j.number()) id: number @optional profile?: Profile @reference({ type: [Pet] }) pets?: Pet[] } it('contain error if invalid', () => { let user = new User({ id: 'abc', profile: new Profile({ name: 'Joe' }) }) expect(user.validate().error).toBeTruthy() }) it('without error if valid', () => { let user = new User({ id: '123', profile: new Profile({ name: 'Joe' }) }) expect(user.validate().error).toBeNull() }) it('return joi default', () => { let user = new User({ id: '1', profile: new Profile() }) expect(user.validate().value.profile.age).toBe(1) }) it('apply validate value', () => { let user = User.build({ id: 1, profile: new Profile() }, { convert: false }) expect(user.validate().value.profile.age).toBe(1) expect(user.profile.age).toBeUndefined() user.validate({ apply: true }) expect(user.profile.age).toBe(1) }) it('raise error if invalid', () => { let user = new User({ id: 'abc', profile: new Profile({ name: 'Joe' }) }) expect(() => user.validate({ raise: true })).toThrow() }) it('return json if valid', () => { let user = new User({ id: '123', profile: new Profile({ name: 'Joe' }) }) expect(user.validate({ raise: true }).value).toEqual({ id: 123, profile: { name: 'Joe', age: 1, }, }) }) it('validate Child[] type', () => { expect(new User({ id: 1, pets: [{ name: 'qq' }] }).validate().error).toBeNull() }) }) describe('joi default', () => { class Foo extends Schema { @optional(j => j.number().default(() => 1, '1')) age: number } class Bar extends Foo { @optional(j => j.number().default(() => 2, '2')) height: number } it('has default value', () => { expect(new Foo(({ age: undefined })).validate().value.age).toBe(1) }) it('has default value in sub class', () => { expect(new Foo().validate().value).toEqual({ age: 1 }) expect(new Bar().validate().value).toEqual({ age: 1, height: 2 }) }) }) describe('without joi', () => { class Foo extends Schema { @((...args) => createDecorator((target, [one]) => { target['mark'] = true }, args)) age: number } it('validate no error', () => { expect(new Foo().validate().error).toBeNull() }) }) })
afc648b0302aaaa40320fd7af7824ff26365882e
TypeScript
tdrcork/Enterprise-Application-Seed
/src/app/core/permissions/state/permissions.actions.ts
2.515625
3
import { Action } from '@ngrx/store'; export const SET_USER_CLEARANCE = 'SET_USER_CLEARANCE'; export const SET_USER_KEYS = 'SET_USER_KEYS'; export const ADD_USER_KEY = 'ADD_USER_KEY'; export const DELETE_USER_KEY = 'DELETE_USER_KEY'; export const CLEAR_PERMISSIONS = 'CLEAR_PERMISSIONS'; export class SetUserClearance implements Action { readonly type = SET_USER_CLEARANCE; constructor(public payload: number) {} } export class SetUserKeys implements Action { readonly type = SET_USER_KEYS; constructor(public payload: string[]) {} } export class AddUserKey implements Action { readonly type = ADD_USER_KEY; constructor(public payload: string) {} } export class DeleteUserKey implements Action { readonly type = DELETE_USER_KEY; constructor(public payload: string) {} } export class ClearPermissions implements Action { readonly type = CLEAR_PERMISSIONS; } export type PermissionsActions = SetUserClearance | SetUserKeys | AddUserKey | DeleteUserKey | ClearPermissions;
71dc953af8bb83bcd4f765778f8f93852b855506
TypeScript
NewEraCodeRepo/sf-datapipeline-lib
/src/logger.ts
2.859375
3
import * as colors from "colors/safe"; import { format } from "logform"; import * as winston from "winston"; import { Event, IDelivery } from "./index"; const safeStringify = require("fast-safe-stringify"); // keeping for backwards compatibility export function logEvent(delivery: IDelivery<Event>, topic: string = "") { const printedTopic: string = topic === "" ? "" : `Topic: ${topic}, `; return `${printedTopic}key: ${delivery.key}, offset: ${delivery.offset},\ event: ${JSON.stringify(delivery.event, null, "\t")}`; } export function safeJSON(obj) { function replacer(key, value) { if (value === "[Circular]") { return; } return value; } const serialized = safeStringify(obj, replacer, 2); console.log(serialized); } /* tslint:disable:max-line-length */ /** * Winston Logger * * formatted logger * @exaples: * import { WinstonLogger } from "datapipeline-lib" * const logger = WinstonLogger.getLogger("SOMETOPIC") * logger.info("Some Message") * * Output in the console will look like: * 2018-05-17T22:11:27.545Z [info][SOMETOPIC] : Some Message * * For profiling: * import { WinstonLogger } from "datapipeline-lib" * const logger = WinstonLogger.getLogger("SOMETOPIC") * * logger.profiler("Some message", { test: "start" }) <- put this where you want to start the time * * Some complex operation * * logger.profiler("Some message", { test: "end" }) <- Put this where you want to end the time * * Output in the console will look like: * 2018-05-18T22:04:50.624Z [profiler][SOMETOPIC-PROFILER] : Some Message started * 2018-05-18T22:04:50.625Z [profiler][SOMETOPIC-PROFILER] : Some Message done in (hr): 1.051085ms */ export class WinstonLogger { public static getLogger( label: string, ): winston.Logger { const logger = new WinstonLogger(label); return logger.getLogger(); } private startTime: [number, number]; private label: string; constructor(label: string) { this.label = label; } public getLogger() { // custom coloring and addition of new profiler log level const config = { colors: { debug: "blue", error: "red", info: "green", profiler: "blue", silly: "magenta", verbose: "cyan", warn: "yellow", }, levels: { debug: 4, error: 0, info: 2, profiler: 6, silly: 5, verbose: 3, warn: 1, }, }; const loggerFormat = format.combine( format.colorize(), format.timestamp(), format.align(), format((info, opts) => { return info; })(), format.json(), format.printf((info) => { const logMessageBase = `${info.timestamp} [${info.level}][${this.label.toUpperCase()}`; const missingStartTimeMessage = "Log profiler has" + " not been started yet." + " Make sure to add \"logger.info(\"my message\"," + " { profiler: \"start\" })\""; const wrongProfilerLevel = `Log profiler is initialized by using "logger.profile", not "logger.${colors.white(info.level)}"`; const wrongPropertyOrValues = `Log profiler requires the following options: "{ test: "start" }" or "{ test: "end" }"`; if (info[Symbol.for("level")] !== "profiler" && info.test) { return `${info.timestamp} [${colors.red("profiler-error")}][${this.label.toUpperCase()}-PROFILER] : ${wrongProfilerLevel}`; } if (info[Symbol.for("level")] === "profiler") { if (info.test === "start") { this.startTime = process.hrtime(); return `${logMessageBase}-PROFILER] : ${info.message.trim()} started`; } else if (info.test === "end") { if (!this.startTime) { return `${info.timestamp} [${colors.red("profiler-error")}][${this.label.toUpperCase()}-PROFILER] : ${missingStartTimeMessage}`; } const endTime = process.hrtime(this.startTime); const endTimeInMs = endTime[0] * 1000 + endTime[1] / 1000000; return `${logMessageBase}-PROFILER] : ${info.message.trim()} done in (hr): ${endTimeInMs}ms`; } return `${info.timestamp} [${colors.red("profiler-error")}][${this.label.toUpperCase()}-PROFILER] : ${wrongPropertyOrValues}`; } return `${logMessageBase}] : ${info.message.trim()}`; }), ); const transports = { console: new winston.transports.Console({ handleExceptions: true, level: "profiler", }), }; winston.addColors(config.colors); return winston.createLogger({ exitOnError: false, format: loggerFormat, levels: config.levels, transports: [ transports.console, ], }); } }
a4bf2bdd5a5618fdb0a3783bca58b8fe3a6df187
TypeScript
derrickp/dented-lotus
/src/stores/UserStore.ts
2.546875
3
import { User } from "../../common/models/User"; import { PublicUser } from "../../common/responses/PublicUser"; import { UserResponse } from "../../common/responses/UserResponse"; import { Store } from "./Store"; import { saveUserInfo, getUser as serverGetUser, getAllPublicUsers } from "../utilities/server/users"; export class UserStore implements Store<User> { private _initializePromise: Promise<void>; private _googleAuth: gapi.auth2.GoogleAuth; private _userMap: Map<string, User> = new Map<string,User>(); getToken: () => string; constructor(getToken: () => string) { this.get = this.get.bind(this); this.refreshUser = this.refreshUser.bind(this); this.initialize = this.initialize.bind(this); this.get = this.get.bind(this); this.getAll = this.getAll.bind(this); this.save = this.save.bind(this); this.create = this.create.bind(this); this.refreshAllUsers = this.refreshAllUsers.bind(this); this.getToken = getToken; } initialize(): Promise<void> { this._initializePromise = this._initializePromise ? this._initializePromise : new Promise<void>((resolve, reject) => { const promises: Promise<void>[] = []; promises.push(this.refreshAllUsers()); return Promise.all(promises).then(() => { resolve(); }).catch(error => { console.error(error.message); reject(error); }); }); return this._initializePromise; } getAll(): User[] { return Array.from(this._userMap.values()); } create(response: UserResponse) { return Promise.reject(new Error("Not implemented")); } save(model: User) { return Promise.reject(new Error("Not implemented")); } get(key: string) { if (this._userMap.has(key)) return this._userMap.get(key); return null; } refreshUser(key: string): Promise<void> { return new Promise<void>((resolve, reject) => { return serverGetUser(key, this.getToken()).then(userResponse => { const user = new User(userResponse, "", null); if (this._userMap.has(key)) this._userMap.delete(key); this._userMap.set(key, user); resolve(); }).catch(reject); }); } refreshAllUsers(): Promise<void> { return new Promise<void>((resolve, reject) => { return getAllPublicUsers().then((users: PublicUser[]) => { for (const publicUser of users) { const user = new User(publicUser, "", null); if (this._userMap.has(publicUser.key)) this._userMap.delete(publicUser.key); this._userMap.set(publicUser.key, user); } resolve(); }); }); } }