language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class SearchBar extends Component {
render() {
return <input onChange={event => console.log(event.target.value)} />;
}
} |
JavaScript | class Misc extends Component {
handleClick = (e) => {
console.log(e.target.name)
this.props.imageClicked(e.target.name)
}
render() {
const { misc } = this.props
return (
<div>
<h1>Misc page</h1>
{Object.keys(misc).map((item) => {
return <img
key={misc[item].name}
name={misc[item].name}
src={misc[item].display_src}
onClick={this.handleClick}
/>
})}
</div>
)
}
} |
JavaScript | class UserTracker {
constructor() {
/**
* The geolocator to track the user
* @type {Geolocator}
* @private
*/
this._geolocator = new Geolocator();
/**
* Compasses discarded after giving some failure or
* being not available.
* @type {int}
* @private
*/
this._discardedCompasses = 0;
/**
* The compass to get the heading for the user
* @type {?Compass}
* @private
*/
this._compass = this._createCompass();
console.log("Using compass", this._discardedCompasses);
/**
* Used to draw the user location on the map,
* once the google maps api is available
* @type {?UserDrawer}
* @private
*/
this._userDrawer = null;
/**
* The position of the user, if known now.
* If the geolocation error is set, this one should be null.
* @type {?Coordinates}
* @private
*/
this._userPosition = null;
/**
* If known, the angle anti-clockwise in degrees from the North, in which
* the user si looking at.
* @type {null}
* @private
*/
this._userHeading = null;
/**
* The geolocation error, if there has been one.
* If the user position is set, this one should be null.
* @type {?PositionError}
* @private
*/
this._geolocationError = null;
/**
* Listeners for changes in the user position availability
* @type {UserLocationAvailabilityChangeListener[]}
* @private
*/
this._changeListeners = [];
/**
* Listener for updates on user position
* @type {UserPositionUpdatedListener[]}
* @private
*/
this._positionListeners = [];
/**
* If the error icon tries to be set before the drawer is created,
* we store it here for later.
* @type {?Element}
* @private
*/
this._savedErrorIcon = null;
}
/**
* Sets the map to draw the user position in
* @param {google.maps.Map} map - The map
*/
setMap(map) {
this._userDrawer = new UserDrawer(map, this._userPosition);
this._userDrawer.setGeolocationErrorIcon(this._savedErrorIcon);
this._userDrawer.showGeolocationError(!this.isUserPositionAvailable());
}
/**
* Sets the geolocation error icon to display
* when an error with the geolocation occurs.
* It simply delegates into the UserDrawer.
* @see {UserDrawer#setGeolocationErrorIcon}
* @param {Element} icon - The element which works as icon
*/
setGeolocationErrorIcon(icon) {
if(this._userDrawer) {
this._userDrawer.setGeolocationErrorIcon(icon);
} else {
this._savedErrorIcon = icon;
}
}
/**
* Starts tracking the user
*/
startTracking() {
this._geolocator.start((...x)=>this._onUserPositionUpdate(...x));
if(this._compass) {
this._compass.start((...x) => this._onUserHeadingUpdate(...x));
}
}
/**
* Obtains the user position, if available.
* @return {?Coordinates}
*/
getUserPosition() {
return this._userPosition;
}
/**
* Checks if the user position is available or not
* @returns {boolean}
*/
isUserPositionAvailable() {
return !this._geolocationError && !!this._userPosition;
}
/**
* Stops tracking the user
*/
stopTracking() {
this._geolocator.stop();
if(this._compass) {
this._compass.stop();
}
}
/**
* It will be called each time the user position is updated
* @param {?Position} data - New data of the geolocation
* @param {?PositionError} error - The error if there has been one
* @private
*/
_onUserPositionUpdate(data, error) {
let previousAvailability = this.isUserPositionAvailable();
this._geolocationError = error || null;
this._userPosition = (error ? null : data.coords);
if(this._userDrawer) {
this._userDrawer.showGeolocationError(!!this._geolocationError);
this._userDrawer.updateUserMarker(this._userPosition, this._userHeading);
}
if(this.isUserPositionAvailable() !== previousAvailability) {
for (let listener of this._changeListeners) {
listener(this.isUserPositionAvailable());
}
}
// Call the position update listeners
for (let listener of this._positionListeners) {
listener();
}
}
/**
* Called when the compass has a new direction to offer
* @param {?number} heading - The direction in which the user is looking (in degrees from the North anti-clockwise)
* @param {boolean} error - True if there has been an error, false if not.
* @private
*/
_onUserHeadingUpdate(heading, error) {
this._userHeading = error ? null : heading;
if(error) this._changeCompass();
else if(this._userDrawer) {
this._userDrawer.updateUserMarker(this._userPosition, this._userHeading);
}
}
/**
* Registers a new listener to listen for changes in the user location
* availability.
* @param {UserLocationAvailabilityChangeListener} listener - The callback listener
*/
registerChangeListener(listener) {
this._changeListeners.push(listener);
}
/**
* Registers a new listener to listen for when the user location
* is updated.
* @param {UserPositionUpdatedListener} listener
* @return {Number} the index to be able to remove this listener later
*/
registerPositionListener(listener) {
let idx = this._positionListeners.length;
this._positionListeners.push(listener);
return idx;
}
/**
* Removes a listener for the user location updates
* @param {Number} index - The index received when registering the listener
*/
removePositionListener(index) {
this._positionListeners.splice(index, 1);
}
/**
* Changes the compass to the next available one
* @private
*/
_changeCompass() {
console.log("Error in compass " + this._discardedCompasses + ", changing to next one.");
this._compass.stop();
this._discardedCompasses++;
this._compass = this._createCompass();
if(this._compass) {
this._compass.start((...x) => this._onUserHeadingUpdate(...x));
console.log("Using compass ", this._discardedCompasses);
} else {
console.log("No more compasses available");
}
}
/**
* Creates a new compass (strategy) for this
* class.
* @return {?Compass} A compass which is able to work in this environment
* @private
*/
_createCompass() {
// Each time we enter all the previously discarded ones are directly
// skipped.
// noinspection FallThroughInSwitchStatementJS
while(true) {
switch (this._discardedCompasses) {
default:
return null; // Nothing more to try
case 0: if (AOSCompass.isAvailable()) return new AOSCompass();
break;
case 1: if (DOACompass.isAvailable()) return new DOACompass();
break;
case 2: if (DOCompass.isAvailable()) return new DOCompass();
break;
}
this._discardedCompasses++;
}
}
} |
JavaScript | class Hook {
/**
* @param {Message} message
*/
handle(message) {}
} |
JavaScript | class Lock {
constructor(opts, log) {
this._blobSvc = createBlobService(opts);
this._blob = opts.name || 'lock';
this._log = log;
}
/**
* If necessary, create an empty text blob that will be used to acquire a lease on.
*/
async init() {
if (this._initialized) {
return;
}
const result = await this._blobSvc.doesBlobExist(this._blob);
if (!result.exists) {
try {
// This access condition makes the call fail if the blob already exists
const accessConditions = { EtagNonMatch: '*' };
await this._blobSvc.createBlockBlobFromText(this._blob, '', { accessConditions });
} catch (e) {
if (e.code !== 'BlobAlreadyExists') {
throw e;
}
}
}
this._initialized = true;
}
/**
* Acquires a lock. Internally, repeatedly tries to acquire a lease on our
* blob until it either succeeds or the timeout expires.
*
* @param {number} timeoutMillis timeout in milliseconds to wait for lock
* @param {number} leaseDuration duration of lease in seconds
* @returns true if lock is successfully acquired, otherwise false.
*/
async acquire(timeoutMillis = 60000, leaseDuration = 60) {
await this.init();
const endTime = Date.now() + timeoutMillis;
while (Date.now() < endTime) {
// eslint-disable-next-line no-await-in-loop
const result = await this.tryAcquire(leaseDuration);
if (result) {
return result;
}
sleep(1000);
}
return false;
}
/**
* Try acquiring a lock. If lock is not available, return immediately.
*
* @param {number} leaseDuration duration of lease in seconds
* @returns true if lock is successfully acquired, otherwise false.
*/
async tryAcquire(leaseDuration = 60) {
await this.init();
try {
const result = await this._blobSvc.acquireLease(this._blob, { leaseDuration });
this._lease = result.id;
return true;
} catch (e) {
if (e.code !== 'LeaseAlreadyPresent') {
throw e;
}
return false;
}
}
/**
* Releases a lock previously acquired.
*
* @returns true if lock was previously acquired, otherwise false
*/
async release() {
const lease = this._lease;
if (lease) {
await this._blobSvc.releaseLease(this._blob, lease);
this._lease = null;
}
return !!lease;
}
} |
JavaScript | class ProgressPie extends Input {
/**
* ProgressPie constructor
* @param {PositionDefinition} positionDefinition - Position of the progress-pie center
* @param {ProgressOptions} options - Specific options
*/
constructor (positionDefinition, options) {
super(positionDefinition, options);
this.background.delete();
this.background = new Circle(undefined, this.options.radius, {
fill: this.options.background,
stroke: this.options.border,
strokeWidth: 2,
cursor: null,
});
this.add(this.background);
this.progress = new Pie(undefined, this.background.radius - 1, 0, 0, {
fill: this.options.fill,
stroke: null,
});
this.background.add(this.progress);
if (this.options.speed < 1) {
this.progress.on(ProgressPie.events.draw, () => {
this.progress.endAngle += (this.value - this.progress.endAngle) * (this.options.speed ** 2);
}, true);
}
/**
* @type {Number}
*/
this[valueKey] = null;
}
/**
* @inheritDoc
*/
click () { // eslint-disable-line class-methods-use-this
// Do nothing
}
/**
* Return this size
* @return {Number}
*/
get radius () {
return this.options.radius;
}
/**
* Change this size
* @param {Number} newRadius - A new size in pixels
*/
set radius (newRadius) {
this.options.radius = newRadius;
this.background.radius = newRadius;
this.progress.radius = newRadius - 1;
}
/**
* Returns this current value
* @return {Number}
*/
get value () {
return this[valueKey];
}
/**
* Change this current value
* @param {Number} newValue - A new value to be set (between 0 and 1)
*/
set value (newValue) {
this[valueKey] = constrain(newValue, 0, 1);
if (this.options.speed >= 1) {
this.progress.endAngle = this.value;
}
}
/**
* @return {ProgressOptions}
*/
static get defaultOptions () {
return {
...super.defaultOptions,
value: 0,
radius: 100,
speed: 0.3,
};
}
} |
JavaScript | class ConsoleLog {
/**
* Possible log levels, from most to least verbose
* @readonly
* @enum {number} */
static Level = {
Extreme: -1,
Tmi: 0,
Verbose: 1,
Info: 2,
Warn: 3,
Error: 4,
Critical: 5
}
/** Display strings for each log {@linkcode Level} */
static #logStrings = ["TMI", "VERBOSE", "INFO", "WARN", "ERROR", "CRITICAL"];
/** Console color definitions for each log {@linkcode Level} */
static #consoleColors = [
// Light Title, Dark Title, Light Text, Dark Text
["#00CC00", "#00AA00", "#AAA", "#888"],
["#c661e8", "#c661e8", "inherit", "inherit"],
["blue", "#88C", "inherit", "inherit"],
["E50", "#C40", "inherit", "inherit"],
["inherit", "inherit", "inherit", "inherit"],
["inherit; font-size: 2em", "inherit; font-size: 2em", "#800; font-size: 2em", "#C33; font-size: 2em"],
["#009900", "#006600", "#AAA", "#888"]
];
/** Trace color definitions for each log level. */
static #traceColors = [
ConsoleLog.#consoleColors[0],
ConsoleLog.#consoleColors[1],
ConsoleLog.#consoleColors[2],
[
"#E50; background: #FFFBE5",
"#C40; background: #332B00",
"inherit; background: #FFFBE5",
"#DFC185; background: #332B00"
],
[
"red; background: #FEF0EF",
"#D76868; background: #290000",
"red; background: #FEF0EF",
"#D76868; background: #290000"
],
[
"red; font-size: 2em",
"red; font-size: 2em",
"#800; font-size: 2em",
"#C33; font-size: 2em"
],
ConsoleLog.#consoleColors[6]
];
/** The current log level. Anything below this will not be logged.
* @type {Level} */
#currentLogLevel;
/** Determine whether we should add a trace to every log event, not just errors.
* @type {number} */
#traceLogging;
/** Tweak colors a bit based on whether the user is using a dark console theme.
* @type {number} 0 for light, 1 for dark. */
#darkConsole;
constructor(window) {
this.window = window;
// We use ConsoleLog both on both the server and client side.
// Server-side, create a stub of localStorage and window so nothing breaks
if (!this.window) {
class LS {
constructor() {
this._dict = {};
}
getItem(item) { return this._dict[item]; }
setItem(item, value) { this._dict[item] = value; }
}
class W {
matchMedia() { return false; }
localStorage = new LS();
}
this.window = new W();
}
/** The current log level. Anything below this will not be logged. */
this.#currentLogLevel = parseInt(this.window.localStorage.getItem("loglevel"));
if (isNaN(this.#currentLogLevel)) {
this.#currentLogLevel = ConsoleLog.Level.Info;
}
/** Determine whether we should add a trace to every log event, not just errors. */
this.#traceLogging = parseInt(this.window.localStorage.getItem("logtrace"));
if (isNaN(this.#traceLogging)) {
this.#traceLogging = 0;
}
/** Tweak colors a bit based on whether the user is using a dark console theme */
this.#darkConsole = parseInt(this.window.localStorage.getItem("darkconsole"));
if (isNaN(this.#darkConsole)) {
// Default to system browser theme (if available)
let mediaMatch = this.window.matchMedia("(prefers-color-scheme: dark)");
mediaMatch = mediaMatch != "not all" && mediaMatch.matches;
this.#darkConsole = mediaMatch ? 1 : 0;
}
}
/** Test ConsoleLog by outputting content for each log level */
testConsolelog() {
const old = this.#currentLogLevel;
this.setLevel(-1);
this.tmi("TMI!");
this.setLevel(0);
this.verbose("Verbose!");
this.info("Info!");
this.warn("Warn!");
this.error("Error!");
this.critical("Crit!");
this.formattedText(ConsoleLog.Level.Info, "%cFormatted%c,%c Text!%c", "color: green", "color: red", "color: orange", "color: inherit");
this.setLevel(old);
};
/**
* Sets the new minimum logging severity.
* @param {Level} level The new log level. */
setLevel(level) {
this.window.localStorage.setItem("loglevel", level);
this.#currentLogLevel = level;
}
/**
* @returns The current minimum logging severity. */
getLevel() {
return this.#currentLogLevel;
}
/**
* Set text to be better suited for dark versus light backgrounds.
* @param {number} dark `1` to adjust colors for dark consoles, `0` for light. */
setDarkConsole(dark) {
this.window.localStorage.setItem("darkconsole", dark);
this.#darkConsole = !!dark ? 1 : 0;
}
/** @returns Whether the current color scheme is best suited for dark consoles. */
getDarkConsole() {
return this.#darkConsole;
}
/**
* Set whether to print stack traces for each log. Helpful when debugging.
* @param {number} trace `1` to enable trace logging, `0` otherwise. */
setTrace(trace) {
this.window.localStorage.setItem("logtrace", trace);
this.#traceLogging = !!trace ? 1 : 0;
}
/** @returns Whether stack traces are printed for each log. */
getTrace() {
return this.#traceLogging;
}
/**
* Log TMI (Too Much Information) output.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
tmi(obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Tmi);
}
/**
* Log Verbose output.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
verbose(obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Verbose);
}
/**
* Log Info level output.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
info = function (obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Info);
}
/**
* Log a warning using `console.warn`.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
warn(obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Warn);
}
/**
* Log a error using `console.error`.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
error(obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Error);
}
/**
* Log a critical error using `console.error`.
* @param {any} obj The object or string to log.
* @param {string} [description] If provided, will be prefixed to the output before `obj`.
* @param {boolean} [freeze] True to freeze the state of `obj` before sending it to the console. */
critical(obj, description, freeze) {
this.log(obj, description, freeze, ConsoleLog.Level.Critical);
}
/**
* Log formatted text to the console.
* @param {Level} level The severity of the log.
* @param {string} text The formatted text string.
* @param {...any} format The arguments for {@linkcode text} */
formattedText(level, text, ...format) {
this.log("", text, false /*freeze*/, level, true /*textOnly*/, ...format);
}
/**
* Core logging routine. Prefixes a formatted timestamp based on the level
* @param {any} obj The object or string to log.
* @param {string} [description] A description for the object being logged.
* Largely used when `obj` is an array/dictionary and not a string.
* @param {boolean} freeze If true, freezes the current state of obj before logging it.
* This prevents subsequent code from modifying the console output.
* @param {Level} level The Log level. Determines the format colors as well as where
* to display the message (info, warn err). If traceLogging is set, always outputs to {@linkcode console.trace}
* @param {boolean} [textOnly] True if only {@linkcode description} is set, and `obj` should be ignored.
* @param {...any} [more] A list of additional formatting to apply to the description.
* Note that this cannot apply to `obj`, only `description`.
*/
log(obj, description, freeze, level, textOnly, ...more) {
if (level < this.#currentLogLevel) {
return;
}
let timestring = ConsoleLog.#getTimestring();
let colors = this.#traceLogging ? ConsoleLog.#traceColors : ConsoleLog.#consoleColors;
let type = (object) => typeof (object) == "string" ? "%s" : "%o";
if (this.#currentLogLevel == ConsoleLog.Level.Extreme) {
this.#write(
console.debug,
`%c[%cEXTREME%c][%c${timestring}%c] Called log with '${description ? description + ": " : ""}${type(obj)},${level}'`,
ConsoleLog.#currentState(obj, freeze),
6,
colors,
...more
);
}
let desc = "";
if (description) {
desc = textOnly ? description : `${description}: ${type(obj)}`;
}
else if (typeof (obj) == "string") {
desc = obj;
obj = "";
}
this.#write(
this.#getOutputStream(level),
`%c[%c${ConsoleLog.#logStrings[level]}%c][%c${timestring}%c] ${desc}`,
ConsoleLog.#currentState(obj, freeze),
level,
colors,
...more);
}
/**
* Internal function that actually writes the formatted text to the console.
* @param {Function} outputStream The method to use to write our message (e.g. console.log, console.warn, etc)
* @param {string} text The text to log.
* @param {*} [object] The raw object to log, if present.
* @param {Level} [logLevel] The log severity.
* @param {Array.<Array.<string>>} colors The color palette to use.
* This will be `traceColors` if trace logging is enabled, otherwise `consoleColors`.
* @param {...any} [more] Any additional formatting properties that will be applied to `text`. */
#write(outputStream, text, object, logLevel, colors, ...more) {
let textColor = `color: ${colors[logLevel][2 + this.#darkConsole]}`;
let titleColor = `color: ${colors[logLevel][this.#darkConsole]}`;
outputStream(text, textColor, titleColor, textColor, titleColor, textColor, ...more, object);
}
/** @returns The log timestamp in the form YYYY.MM.DD HH:MM:SS.000 */
static #getTimestring() {
let padLeft = (str, pad = 2) => ("00" + str).substr(-pad);
let time = new Date();
return `${time.getFullYear()}.${padLeft(time.getMonth() + 1)}.${padLeft(time.getDate())} ` +
`${padLeft(time.getHours())}:${padLeft(time.getMinutes())}:${padLeft(time.getSeconds())}.${padLeft(time.getMilliseconds(), 3)}`;
}
/**
* Retrieve the printed form of the given object.
* @param {Object|string} object The object or string to convert.
* @param {boolean} freeze Freeze the current state of `object`.
* This prevents subsequent code from modifying the console output.
* @param {boolean} [str=false] Whether to convert `object` to a string regardless of its actual type. */
static #currentState(object, freeze, str = false) {
if (typeof (object) == "string") {
return object;
}
if (str) {
return JSON.stringify(object);
}
return freeze ? JSON.parse(JSON.stringify(object)) : object;
}
/** Return the correct output stream for the given log level */
#getOutputStream(level) {
return this.#traceLogging ? console.trace :
level > ConsoleLog.Level.Warn ? console.error :
level > ConsoleLog.Level.Info ? console.warn :
level > ConsoleLog.Level.Tmi ? console.info :
console.debug;
}
/** Prints a help message to the console */
consoleHelp() {
// After initializing everything we need, print a message to the user to give some basic tips
const logLevelSav = this.#currentLogLevel;
this.#currentLogLevel = 2;
this.info(" ");
console.log("Welcome to the console!\n" +
"If you're debugging an issue, here are some tips:\n" +
" 1. Set dark/light mode for the console via Log.setDarkConsole(isDark), where isDark is 1 or 0.\n" +
" 2. Set the log level via Log.setLevel(level), where level is a value from the ConsoleLog.Level dictionary " +
"(e.g. Log.setLevel(ConsoleLog.Level.Verbose);)\n" +
" 3. To view the stack trace for every logged event, call Log.setTrace(1). To revert, Log.setTrace(0)\n\n");
this.#currentLogLevel = logLevelSav;
}
} |
JavaScript | class TalkService {
/**
* Represents a TalkService object
* @constructor
* @param {object} opts - IoC object holding dependencies
*/
constructor(opts) {
this.topicService = opts.topicService;
this.talkScraper = opts.talkScraper;
this.objectValidator = opts.objectValidator;
this.logger = opts.logger;
}
/**
* Get all talks given the source and topics of interest
* @param {string} source - source to query data for (web/cache)
* @param {Array} topics - string array of topics to search for
* @return {Array} - Array of talks matching the query
*/
async getTalks(source, topics) {
let talks = [];
if (this.objectValidator.isValid(topics) && topics.length > 0) {
talks = await this.getTalksByTopics(topics);
} else {
talks = await this.getAllTalks(source);
}
return talks;
};
/**
* Get all talks related to a single topic
* @param {string} topic - string representing the topic of interest
* @return {Talk} - Talks matching the specified topic
*/
async getTalksByTopic(topic) {
const talks = await this.talkScraper.getTalk(topic);
return talks;
}
/**
* Get all talks related to multiple topics
* @param {Array} topics - string topics of interest
* @return {Talk} - Talks matching the specified topics
*/
async getTalksByTopics(topics) {
let talks = [];
for (let i = 0; i < topics.length; i++) {
const topic = topics[i];
const topicTalks = await this.getTalksByTopic(topic);
if (this.objectValidator.isValid(topicTalks)) {
talks = talks.concat(topicTalks);
}
}
return talks;
}
/**
* Get all Talks matching the source
* @async
* @param {string} source - source to query (web/cache)
* @return {Array} - list of all talks from the source
*/
async getAllTalks(source) {
let talks = [];
const topics = await this.topicService.getAllTopics(source);
for (let i = 0; i < topics.length; i++) {
const topic = topics[i];
const topicTalks = await this.getTalksByTopic(topic.tag);
if (this.objectValidator.isValid(topicTalks)) {
talks = talks.concat(topicTalks);
}
}
return talks;
}
/**
* @async
* Sync talks from the web to the database
*/
async sync() {
try {
// Get latest topics from the web
const talks = await this.getTalksByTopic('baptism');
// const values = talks.map((talk) => talk.dataValues);
// Save to the database
await Talk.bulkCreate(talks, {
ignoreDuplicates: true,
include: [{
association: Talk.Speaker,
ignoreDuplicates: true,
}],
});
} catch (error) {
this.logger.error(error);
throw error;
}
}
} |
JavaScript | class Game extends Phaser.Scene {
constructor () {
super({key:"Game"});
}
preload () {
this.load.image('car', carImg);
}
create (data) {
this.demo = data.demo;
const show3d= data.show3d==undefined ? true: data.show3d;
//const demo=true;
//this.demo=true;
//World stuff
this.matter.world.disableGravity();
//Camera Settings
if (!show3d)
this.cameras.main.setBackgroundColor("#337733")
//this.map = Map.defaultMap(this);
const mapIndex = data.mapIndex ||0;
this.map=Map.mapWithIndex(this,mapIndex);
this.road = this.map.road;
this.player = new Player(this, 0xff0000, 100,230,0,"Red");
if (this.demo) {
this.player.shouldAutoDrive=true;
}
this.map.addCar(this.player);
this.opponents = [];
const opponentColors=[0xffff00, 0x00ff00, 0x0000ff,0xff00ff,0x00ffff];
const opponentNames=["Yellow","Green","Blue","Purple","Cyan"]
for (let i=0; i<5;i++) {
const car = new NPC(this, opponentColors[i], 0,0,i+1,opponentNames[i])
this.map.addCar(car);
this.player.addOpponent(car);
car.setOpponents([this.player, ...this.opponents])
for (const opp of this.opponents) {
opp.addOpponent(car);
}
this.opponents.push(car);
}
if (!this.demo) {
this.controller= new Controller(this, this.player)
}
if (!show3d && !this.demo) {
this.cameras.main.startFollow(this.player);
this.cameras.main.setZoom(1)
} else if (!show3d && this.demo) {
const hRatio = this.cameras.main.height/this.map.bounds.h;
const wRatio = this.cameras.main.width/this.map.bounds.w;
const zoom = Math.min(hRatio,wRatio);
this.cameras.main.setZoom(zoom)
const h=this.map.bounds.h*zoom;
const w = this.map.bounds.w*zoom;
this.cameras.main.scrollX=this.map.bounds.x-w/2;
this.cameras.main.scrollY=this.map.bounds.y-h/2;
} else {
let h=200;
const w=300;
const zoom=Math.max(
w/this.map.bounds.w,
0
)
this.cameras.main.setZoom(zoom)
h=this.map.bounds.h*zoom;
this.cameras.main.scrollX=this.map.bounds.x-156;
this.cameras.main.scrollY=this.map.bounds.y-h/2;
this.cameras.main.setViewport(0,0,300,h);
}
this.startTime;
this.lapStartTime;
this.raceActive=false;
this.raceStarted = false;
this.countdown=5;
if (this.demo) {
this.startRace()
} else {
this.proceedCountdown();
}
this.testLabel=this.add.text(50,300,"", {fontSize:50}).setScrollFactor(0);
if (!this.demo) {
this.ui = this.scene.launch("UI",{lapCount:this.map.lapCount});
}
if (show3d) {
this.start3d();
}
//this.customZoom();
}
start3d() {
const scaleBox = scale => {
let box = document.getElementById('c')
if (box) {
box.style.top = this.game.canvas.offsetTop+"px";
box.style.left=this.game.canvas.offsetLeft+"px";
box.style.height=this.scale.displaySize.height+"px";
box.style.width=this.scale.displaySize.width+"px";
}
}
// initial scale
let scale = this.game.scale.displaySize.width / this.game.scale.gameSize.width
scaleBox(scale)
// on resize listener
this.scale.on('resize', (gameSize, baseSize, displaySize, resolution) => {
let scale = displaySize.width / gameSize.width
scaleBox(scale)
})
const oppData=[];
for (const opp of this.opponents) {
oppData.push({id:opp.id,color:opp.tintTopLeft})
}
this.graphics=new Graphics3d({
roadData:this.map.road.roadData,
player:{id:this.player.id,color:this.player.tintTopLeft},
opponents:oppData,
walls:this.map.walls,
finishLine:this.map.finishLine,
bounds:this.map.bounds
});
}
printText(text){
if (this.testLabel)
this.testLabel.text=text;
else
console.log(text)
}
proceedCountdown() {
this.countdown-=1;
const colors=[0x999999,0x00ff00,0xffff00,0xff0000,0x123568];
if (this.countdown===3) {
//this.countdownLight.fillAlpha=1.0
EventsCenter.emit("showCountdown", true)
} else if (this.countdown===1) {
this.startRace()
}
//this.countdownLight.fillColor=colors[this.countdown];
EventsCenter.emit("setCountdownColor",colors[this.countdown])
if (this.countdown>0) {
setTimeout(()=> {
this.proceedCountdown()
}, 1500);
} else {
//this.countdownLight.destroy()
EventsCenter.emit("showCountdown",false)
}
}
startRace() {
this.raceActive=true;
this.raceStarted=true;
this.startTime=this.time.now;
this.player.start(this.startTime);
for (const opp of this.opponents) {
opp.start(this.startTime)
}
}
displayLapTime(time) {
//this.lastLapTimeLabel.text = this.msToString(time);
EventsCenter.emit('setLapTimeLabel', this.msToString(time));
}
msToString(time) {
const totalCents = Math.floor(time/10)
let cents = totalCents%100;
if (cents<10) {
cents="0"+""+cents;
}
const totalSecs = Math.floor(totalCents/100);
let secs= totalSecs%60;
if (secs <10) {
secs = ""+"0"+secs;
}
const mins = Math.floor(totalSecs/60)
return mins+":"+secs+":"+cents;
}
finished() {
if (!this.demo) {
if (this.raceActive){
const sortedCars=[this.player, ...this.opponents].sort((a,b)=>{
return a.finishTime-b.finishTime;
});
const results=[];
for (const car of sortedCars) {
results.push({
name:car.name,
lapTimes:car.lapTimes,
finishTime:car.finishTime
});
}
setTimeout(()=>{this.showRaceOver(results) },1500);
}
this.raceActive = false;
}
}
showRaceOver(results) {
this.scene.stop("UI");
this.scene.launch("RaceOver",{results:results})
}
setLapLabel(lap, total) {
//this.lapLabel.text = "Lap: "+lap+"/"+total;
EventsCenter.emit("setLapLabel","Lap: "+lap+"/"+total);
}
customZoom() {
this.cameras.main.setZoom(0.6)
this.cameras.main.scrollX=-300
this.cameras.main.scrollY=200
}
update(time,delta) {
//if (this.input.activePointer.x>0) this.finished()()
if (this.graphics) {
const oppData=[]
for (const opp of this.opponents) {
oppData.push({
id:opp.id,
x:opp.x,
y:opp.y,
rot:opp.rotation
})
}
this.graphics.update(oppData,
{
x:this.player.x,
y:this.player.y,
rot:this.player.rotation,
dir:this.player.getMovementDirection()
})
}
let raceOver=true;
for (const car of [this.player, ...this.opponents]) {
if (!car.finished) {
raceOver=false;
}
}
if (raceOver) {
this.finished();
}
if (this.raceStarted) {
if (this.controller && !this.player.finished) {
this.controller.update(delta)
}
this.player.update(time, delta);
for (const opp of this.opponents) {
opp.update(time,delta)
}
this.map.update(time, delta);
}
if (this.raceActive) {
const totalElapsed = time-this.startTime;
//this.totalTimeLabel.text=this.msToString(totalElapsed);
EventsCenter.emit("setElapsedTimeLabel",this.msToString(totalElapsed))
//const lapElapsed = time-this.player.lapStartTime;
//this.lapTimeLabel.text = this.msToString(lapElapsed);
}
}
} |
JavaScript | class AttributeBuilder {
/**
* @param {!string} attrName the name of the attribute
*/
constructor(attrName) {
/**
* @ignore
*/
this.data = assign({
attrName,
propName: toCamelCase(attrName),
listeners: []
}, DEFAULT_DATA);
}
/**
* To handle the attribute/property value as a boolean:
* Attribute is present when true and missing when false.
* @returns {AttributeBuilder} the builder
*/
boolean() {
this.data.boolean = true;
return this;
}
/**
* To hide the property name when using <code>Object.keys()</code>.
* @returns {PropertyBuilder} the builder
*/
hidden() {
this.data.enumerable = false;
return this;
}
/**
* To skip the link between the attribute and its property
* @returns {AttributeBuilder} the builder
*/
unbound() {
this.data.bound = false;
return this;
}
/**
* To override the property name.
* @param {!string} propName the property name
* @returns {AttributeBuilder} the builder
*/
property(propName) {
this.data.propName = propName;
return this;
}
/**
* To set a default value.
* @param {*} value the default value
* @returns {PropertyBuilder} the builder
*/
value(value) {
this.data.value = value;
return this;
}
/**
* To be notified when the attribute is updated.
* @param {function(el: HTMLElement, oldVal: string, newVal: string)} listener the listener function
* @returns {AttributeBuilder} the builder
*/
listen(listener) {
this.data.listeners.push(listener);
return this;
}
/**
* Logic of the builder.
* @param {!ElementBuilder.context.proto} proto the prototype
* @param {!ElementBuilder.on} on the method on
*/
build(proto, on) {
let data = this.data,
defaultValue = result(this.data, 'value'),
descriptor = {
enumerable: this.data.enumerable,
configurable: false,
get: this.data.getterFactory(this.data.attrName, this.data.boolean),
set: this.data.setterFactory(this.data.attrName, this.data.boolean)
};
if (data.bound) {
Object.defineProperty(proto, data.propName, descriptor);
}
on('after:createdCallback').invoke(el => {
if (data.bound) {
let attrValue = getAttValue(el, data.attrName, data.boolean);
if (data.boolean) {
el[data.propName] = !!defaultValue ? defaultValue : attrValue;
} else if (!isNull(attrValue) && !isUndefined(attrValue)) {
el[data.propName] = attrValue;
} else if (!isUndefined(defaultValue)) {
el[data.propName] = defaultValue;
}
}
if (data.listeners.length > 0) {
let oldValue = data.boolean ? false : null;
let setValue = el[data.propName];
if (oldValue !== setValue) {
data.listeners.forEach(listener => listener.call(el, el, oldValue, setValue));
}
}
});
on('before:attributeChangedCallback').invoke((el, attName, oldVal, newVal) => {
// Synchronize the attribute value with its properties
if (attName === data.attrName) {
if (data.bound) {
let newValue = data.boolean ? newVal === '' : newVal;
if (el[data.propName] !== newValue) {
el[data.propName] = newValue;
}
}
if (data.listeners.length > 0) {
let oldValue = data.boolean ? oldVal === '' : oldVal;
let setValue = data.boolean ? newVal === '' : newVal;
if (oldValue !== setValue) {
data.listeners.forEach(listener => listener.call(el, el, oldValue, setValue));
}
}
}
});
}
} |
JavaScript | class RegistrationDelegationSettingsProperties {
/**
* Create a RegistrationDelegationSettingsProperties.
* @property {boolean} [enabled] Enable or disable delegation for user
* registration.
*/
constructor() {
}
/**
* Defines the metadata of RegistrationDelegationSettingsProperties
*
* @returns {object} metadata of RegistrationDelegationSettingsProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'RegistrationDelegationSettingsProperties',
type: {
name: 'Composite',
className: 'RegistrationDelegationSettingsProperties',
modelProperties: {
enabled: {
required: false,
serializedName: 'enabled',
type: {
name: 'Boolean'
}
}
}
}
};
}
} |
JavaScript | class Header extends React.Component {
constructor(props) {
super(props);
}
render() {
const handleSignInClick = this.props.handleSignInClick;
const handleSignUpClick = this.props.handleSignUpClick;
return (
<div id="header">
<a href="/" className="headerProjectName">dynalytic</a>
<button className="signInLink" onClick={handleSignInClick}>Sign In</button>
<button className="signUpLink" onClick={handleSignUpClick}>Sign Up</button>
</div>
);
}
} |
JavaScript | class LogicalError {
errorMessage = '';
status = 400;
name = 'LogicalErrorException';
message = 'Validation failed: ';
code = 1001;
type = 'LogicalError';
properties = [];
/**
* Constructor
*
* @param id
*/
constructor(errorMessage, properties) {
this.properties = properties;
this.errorMessage = errorMessage;
this.message = `${this.message} - ${this.errorMessage}`
}
/**
* toString
*
* @returns {string}
*/
toString() {
return this.message;
}
} |
JavaScript | class Action {
static validateConfig({singletons, actions, plugins, fn}) {
if (!isFunction(fn)) throw new Error('Action parameter "fn" have to be a function');
if (singletons && !isStringArray(singletons))
throw new Error('Action parameter "singletons" have to be an array of strings');
if (actions && !isStringArray(actions))
throw new Error('Action parameter "actions" have to be an array of strings');
if (plugins && !isObject(plugins)) throw new Error('Action parameter "plugins" have to be an object');
}
/**
* @param {function} fn
* @param {Array<string>} [singletons]
* @param {Array<string>} [actions]
* @param {Object} [plugins]
*/
constructor({singletons, actions, plugins, fn}) {
Action.validateConfig({singletons, actions, plugins, fn});
this.singletons = singletons || [];
this.actions = actions || [];
this.plugins = plugins || {};
this.fn = fn;
}
getRequiredActions() {
return [...this.actions];
}
getRequiredSingletons() {
return [...this.singletons];
}
getRequiredPlugins() {
return Object.keys(this.plugins);
}
getPluginParams(name) {
return this.plugins[name] && cloneDeep(this.plugins[name]);
}
getAllPluginParams() {
return cloneDeep(this.plugins);
}
} |
JavaScript | class TimeseriesHandler {
// Current data set for the selected layer, set, and location
_selectedData;
//
_currentChart;
/**
* Expands the raw time series JSON and stores it in a format that easier to
* pipe into tables and charts later.
*
* @param {JSONObject[]} entries
*/
parseData(entries) {
this._selectedData = [];
// Parse raw JSON into expanded form
for(var i = 0; i < entries.length; i++) {
var entry = entries[i];
if(entry == null || !entry["data"] || !entry["units"] || !entry["time"] || !entry["values"]){
// Skip if any required properties are missing
continue;
}
// May have multiple data sets with differing units
var tableNames = entry["data"];
var tableUnits = entry["units"];
for(var j = 0; j < tableNames.length; j++) {
// Dependent name
var tableName = tableNames[j];
// Dependent unit
var tableUnit = tableUnits[j];
tableName += " [" + tableUnit + "]";
// Get timestamps
var tableTimes = entry["time"];
for(var t = 0; t < tableTimes.length; t++) {
tableTimes[t] = tableTimes[t].replace("T", " ").replace("Z", "");
}
// Get correct value array
var tableValues = entry["values"][j];
// Store
this._selectedData.push({
"name": tableName,
"id": entry["id"],
"unit": tableUnit,
"times": tableTimes,
"values": tableValues
});
}
}
}
/**
*
* @param {*} containerElement
*/
showData(containerElement) {
// Create dropdowns to change between tables
var selectHTML = this.buildComboBox();
// Setup HTML for results
document.getElementById(containerElement).innerHTML = `
<div id="time-series-control">
` + selectHTML + `
</div>
<div id="time-series-chart-container">
<canvas id="chart-canvas"></canvas>
</div>
<div id="time-series-table-container">
</div>
`;
// Auto-select the first option in the dropdown
document.getElementById("time-series-select").onchange();
}
/**
*
*/
updateTable(setName) {
var tableContainer = document.getElementById("time-series-table-container");
tableContainer.innerHTML = this.buildTable(setName);
}
/**
*
*/
updateChart(setName) {
this.buildChart(setName);
}
/**
*
*/
update(setName) {
this.updateTable(setName);
this.updateChart(setName);
}
/**
*
* @param {*} tableName
*/
buildTable(tableName) {
// Find the correct data entry
var data = null;
this._selectedData.forEach(entry => {
if(entry["name"] === tableName) {
data = entry;
return;
}
});
if(data == null) {
return;
}
// Get the data for the table
var independents = data["times"];
var dependents = data["values"];
// Build the HTML for the table
var tableHTML = `<table class="time-series-table" width="100%">`;
tableHTML += `<tr><th>Time</th><th>` + tableName + `</th></tr>`;
for(var r = 0; r < independents.length; r++) {
// Build HTML for one row
var independent = independents[r];
var dependent = dependents[r];
tableHTML += `
<tr>
<td width="50%">
` + independent + `
</td>
<td width="50%">
` + dependent + `
</td>
</tr>
`;
}
tableHTML += `</table>`;
return tableHTML;
}
buildChart(tableName) {
// Find the correct data entry
var data = null;
this._selectedData.forEach(entry => {
if(entry["name"] === tableName) {
data = entry;
return;
}
});
if(data == null) {
return;
}
// Get data for plotting
var independents = data["times"];
var dependents = [];
for(var i = 0 ; i < independents.length; i++) {
dependents.push({
x: independents[i],
y: (!isNaN(data["values"][i])) ? data["values"][i] : Number(data["values"][i])
});
}
// Destroy the current chart
if(this._currentChart != null) {
this._currentChart.destroy();
}
// Create the new chart element
var ctx = document.getElementById("chart-canvas").getContext("2d");
this._currentChart = new Chart(ctx,
{
type: "line",
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
x: {
type: 'time',
distribution: 'linear',
ticks: {
font: {
weight: 400,
size: 10
}
},
title: {
display: true,
text: "Time",
font: {
weight: 700,
size: 12
}
}
},
y: {
ticks: {
font: {
weight: 400,
size: 10
}
},
title: {
display: true,
text: tableName,
font: {
weight: 700,
size: 12
}
}
}
}
},
data: {
labels: independents,
datasets: [{
label: tableName,
pointBorderColor: "rgba(33, 150, 243, 0.70)",
borderColor: "rgba(33, 150, 243, 0.35)",
data: dependents
}]
}
}
);
}
/**
*
* @returns
*/
buildComboBox() {
var selectHTML = `
<label for="time-series-select">Select a data set:</label>
<select name="time-series-select" id="time-series-select" onchange="manager.updateTimeseries(this.value)">
`;
this._selectedData.forEach(entry => {
selectHTML += `
<option value="` + entry["name"] + `">` + entry["name"] + `</option>
`;
});
selectHTML += `</select>`;
return selectHTML;
}
} |
JavaScript | class BatchBuilder {
/**
* Constructor
*/
constructor() {
}
/**
* Build batch
* @param {*} args transactions arguments
*/
buildBatch(args) {
throw new Error('buildBatch is not implemented for this application!!');
}
/**
* Calculate address
* @param {String} name address name
*/
calculateAddress(name) {
throw new Error('calculateAddress is not implemented for this application!!');
}
} |
JavaScript | class Moderator extends BaseContainer {
constructor(scene, x, y) {
super(scene, x ?? 760, y ?? 480);
// block
const block = scene.add.rectangle(0, 0, 1520, 960);
block.isFilled = true;
block.fillColor = 0;
block.fillAlpha = 0.2;
this.add(block);
// rectangle
const rectangle = scene.add.rectangle(0, -70, 702, 504);
rectangle.isFilled = true;
rectangle.fillColor = 164045;
this.add(rectangle);
// text3
const text3 = scene.add.text(-44, 86, "", {});
text3.setOrigin(0.5, 0);
text3.text = "to ignore them.";
text3.setStyle({ "color": "#ffffffff", "fixedWidth":220,"fixedHeight":60,"fontFamily": "Burbank Small", "fontSize": "28px", "fontStyle": "bold", "shadow.offsetX":2,"shadow.offsetY":2,"shadow.color": "#003366", "shadow.fill":true});
this.add(text3);
// text2
const text2 = scene.add.text(226, -22, "", {});
text2.setOrigin(0.5, 0);
text2.text = "to report";
text2.setStyle({ "color": "#ffffffff", "fixedWidth":200,"fixedHeight":60,"fontFamily": "Burbank Small", "fontSize": "28px", "fontStyle": "bold", "shadow.offsetX":2,"shadow.offsetY":2,"shadow.color": "#003366", "shadow.fill":true});
this.add(text2);
// text1
const text1 = scene.add.text(21, -76, "", {});
text1.setOrigin(0.5, 0);
text1.text = "If someone is breaking the rules, click on\ntheir penguin then click\nthem to a moderator. You can also click\non";
text1.setStyle({ "color": "#ffffffff", "fixedWidth":562,"fixedHeight":220,"fontFamily": "Burbank Small", "fontSize": "28px", "fontStyle": "bold", "shadow.offsetX":2,"shadow.offsetY":2,"shadow.color": "#003366", "shadow.fill":true});
text1.setLineSpacing(20);
this.add(text1);
// safe
const safe = scene.add.text(0, -151, "", {});
safe.setOrigin(0.5, 0);
safe.text = "Help keep the island safe!";
safe.setStyle({ "align": "center", "fixedWidth":600,"fontFamily": "CCFaceFront", "fontSize": "40px", "fontStyle": "bold italic", "stroke": "#003366", "strokeThickness":10});
this.add(safe);
// x_button
const x_button = scene.add.image(300, -268, "main", "blue-button");
this.add(x_button);
// blue_x
const blue_x = scene.add.image(300, -270, "main", "blue-x");
this.add(blue_x);
// report_button
const report_button = scene.add.image(90, -5, "main", "blue-button");
this.add(report_button);
// report_icon
const report_icon = scene.add.image(90, -6, "main", "mod-icon");
this.add(report_icon);
// ignore_button
const ignore_button = scene.add.image(-190, 104, "main", "blue-button");
this.add(ignore_button);
// ignore_icon
const ignore_icon = scene.add.image(-190, 102, "main", "ignore-icon");
this.add(ignore_icon);
// mod
const mod = scene.add.image(0, -222, "main", "mod");
this.add(mod);
// block (components)
new Interactive(block);
// rectangle (components)
const rectangleNineSlice = new NineSlice(rectangle);
rectangleNineSlice.corner = 50;
// x_button (components)
const x_buttonButton = new Button(x_button);
x_buttonButton.spriteName = "blue-button";
x_buttonButton.callback = () => { this.visible = false };
// report_button (components)
const report_buttonButton = new Button(report_button);
report_buttonButton.spriteName = "blue-button";
// ignore_button (components)
const ignore_buttonButton = new Button(ignore_button);
ignore_buttonButton.spriteName = "blue-button";
/* START-USER-CTR-CODE */
/* END-USER-CTR-CODE */
}
/* START-USER-CODE */
/* END-USER-CODE */
} |
JavaScript | class LabReportsTableEntries extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
const promise = getLabReportsListByEHRId(this.props.ehrId);
promise.then((e) => {
this.setState({ reports: e });
});
}
render() {
if (!this.state.reports) return null;
if (this.state.reports.length > 0) {
return this.state.reports.map((e, index) => {
e.index = index;
return LabReportsTableEntry(e);
});
}
return (
<tr key="noLabReports">
<td
key="noLabReports"
colSpan="7"
>
No lab reports records were found
</td>
</tr>
);
}
} |
JavaScript | class CorporateActionType extends Enum {
constructor(code, description) {
super(code, description);
}
/**
* A split.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get SPLIT() {
return split;
}
/**
* A dividend.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get DIVIDEND() {
return dividend;
}
/**
* A stock dividend.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get STOCK_DIVIDEND() {
return stockDividend;
}
/**
* A symbol change.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get SYMBOL_CHANGE() {
return symbolChange;
}
/**
* A name change.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get NAME_CHANGE() {
return nameChange;
}
/**
* A delisting.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get DELIST() {
return delist;
}
/**
* A merging.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get MERGER() {
return merger;
}
/**
* A spinoff.
*
* @public
* @static
* @returns {CorporateActionType}
*/
static get SPINOFF() {
return spinoff;
}
toString() {
return `[CorporateActionType (code=${this.code})]`;
}
} |
JavaScript | class Webpage {
constructor(theme) {
if (!(theme instanceof Theme)) {
throw new TypeError('Param must be a Theme');
}
this.theme = theme;
}
getContent() {
throw new Error('Override is missing');
}
} |
JavaScript | class RecentlyViewedModule extends Module {
/**
* Returns whether the module should be enabled by default. Should
* return a truthy or falsy value.
*
* @returns {boolean}
*/
static isEnabledByDefault = () => {
return true;
};
/**
* Returns the label displayed next to the checkbox on the settings page
*
* @returns {string}
*/
getLabel = () => {
return 'Recently Viewed';
};
/**
* Returns the help text displayed under the label on the settings page
*
* @returns {string}
*/
getHelp = () => {
return 'Displays recently viewed posts in the right sidebar.';
};
/**
* Called when the user exports the extension data
*
* Should return all values that have been saved by the controller or module. Should
* return a falsy value when the controller/module has nothing to export.
*
* @returns {Promise}
*/
exportData = async () => {
return storage.getNamespace('RecentlyViewedModule');
};
/**
* Called when the user imports extension data
*
* Will receive the values saved for the controller or module.
*
* @param {*} data
* @returns {Promise}
*/
importData = async (data) => {
return storage.setNamespace('RecentlyViewedModule', data);
};
/**
* Called from the content script
*
* The content script has access to the chrome extension API but does not
* have access to the ruqqus `window` object.
*/
execContentContext = () => {
this.listen('rp.PopupPostsModule.events', ({ detail }) => {
if (detail.url) {
this.recordView(detail.url, detail.title, detail.thumb);
}
});
this.onDOMReady(() => {
this.addSidebar();
if (document.location.pathname.indexOf('/post') === 0) {
const thumb = document.querySelector('.post-img');
this.recordView(document.location.pathname, document.title, thumb ? thumb.getAttribute('src') : '');
}
});
};
/**
*
*/
addSidebar = () => {
const sidebar = document.querySelector('.sidebar:not(.sidebar-left)');
if (sidebar) {
storage.get('RecentlyViewedModule.history', [])
.then((history) => {
const section = this.html.createElement('div', {
'class': 'sidebar-section rp-recently-viewed-sidebar',
'html': `
<div class="title">
<i class="fas fa-history mr-2"></i>Recently Viewed
</div>
`
});
const body = this.html.createElement('div', {
'class': 'body'
});
section.appendChild(body);
const ul = this.html.createElement('ul', {
'class': 'rp-recently-viewed-list'
});
history.forEach((item) => {
const li = this.html.createElement('li', {
'class': 'mb-2',
'html': `
<h5 class="card-title post-title text-left">
<a href="${item.url}">
<img
src="${item.thumb || '/assets/images/icons/default_thumb_text.png'}"
class="post-img mr-2"
alt="Thumbnail"
/>
</a>
<a href="${item.url}">
${truncateString(item.title, 60)}
</a>
</h5>`
});
ul.appendChild(li);
});
body.appendChild(ul);
const clear = this.html.createElement('div', {
'class': 'btn btn-sm btn-secondary mr-1',
'title': 'Clear history',
'text': 'Clear',
'on': {
'click': this.handleClearClick
}
});
body.appendChild(clear);
const settings = this.html.createElement('div', {
'class': 'btn btn-sm btn-secondary',
'title': 'Settings',
'html': `
<i class="fas fa-cog"></i>
`,
'on': {
'click': this.handleSettingsClick
}
});
body.appendChild(settings);
const sections = sidebar.querySelectorAll('.sidebar-section');
this.html.insertAfter(sections[sections.length - 1], section);
});
}
};
/**
*
*/
handleClearClick = () => {
storage.remove('RecentlyViewedModule.history')
.then(() => {
const section = document.querySelector('.rp-recently-viewed-sidebar');
if (section) {
section.remove();
this.addSidebar();
}
});
};
/**
*
*/
handleSettingsClick = () => {
storage.get('RecentlyViewedModule.settings', { max: 5 })
.then((settings) => {
// eslint-disable-next-line no-alert
const input = window.prompt('Number of posts to keep in history. (1 min, 20 max)', settings.max);
if (input) {
settings.max = parseInt(input, 10) || 1;
if (settings.max < 1) {
settings.max = 1;
} else if (settings.max > 20) {
settings.max = 20;
}
storage.set('RecentlyViewedModule.settings', settings)
.then(() => {
this.toastSuccess('Settings saved!');
});
}
});
};
/**
* @param {string} url
* @param {string} title
* @param {string} thumb
*/
recordView = (url, title, thumb) => {
storage.get('RecentlyViewedModule.settings', { max: 8 })
.then((settings) => {
storage.get('RecentlyViewedModule.history', [])
.then((history) => {
if (searchByObjectKey(history, 'url', url) === -1) {
history.unshift({
thumb,
title,
url
});
history.splice(settings.max);
storage.set('RecentlyViewedModule.history', history);
}
});
});
};
} |
JavaScript | class Info {
constructor(element, options) {
this.$element = $(element)
// @options = $.extend {}, options
let selector = this.$element.data('target')
if (selector == null) { selector = options.target }
this.$target = $(selector)
this.$element.on('click', this, event => event.data.toggle(event))
}
toggle(event) {
event.preventDefault()
this.$target.slideToggle()
return this.$element.toggleClass('is-active')
}
} |
JavaScript | class Login extends Component {
constructor(props){
super(props);
this.login = this.login.bind(this);
this.signup = this.signup.bind(this);
}
componentDidMount(){
appState.$emit('HIDE_LOADER');//hide the loader when the component mounts
}
login(e){
e.preventDefault();
appState.$emit('SHOW_LOADER');
fetch('/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: document.getElementById('email').value,
password: document.getElementById('password').value,
rememberMe: document.getElementById('rememberMe').checked? document.getElementById('rememberMe').value: null
})
}).then((res)=>{
return res.json();
}).then((data) => {
console.log(data)
if(data.loggedIn){
console.log('LOGIN SUCCESS');
appState.$emit('UPDATE_STATE', data);
} else {
console.log('LOGIN FAILED');
appState.$emit('UPDATE_STATE', data);
}
});
}
signup(e){
e.preventDefault();
appState.$emit('SHOW_LOADER');//show the loader while we process this sign up
fetch('/signup', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: document.getElementById('signupEmail').value, //email
password: document.getElementById('signupPassword').value, //signup
confirmPassword: document.getElementById('confirmPassword').value,//confirm password
nickname: document.getElementById('nickname').value//user nickname
})
}).then((res)=>{
return res.json();//handle json response
}).then((data) => {
console.log(data);
if(data.emailSent){//expecting this response from server
console.log('SIGNUP SUCCESS');
appState.$emit('UPDATE_STATE', data);
} else {
console.log('SIGNUP FAILED');
appState.$emit('UPDATE_STATE', data);
}
})
.catch(function(err){
console.log('caught ', err);
});
}
render(){
return(
<div className="login-signup">
<div className="login-signup__content">
<h1 className="text-center">
<img src="/images/logo-sm.png" alt="Pondlebob"/>
</h1>
<LoginForm login={this.login}/>
<SignUpForm signup={this.signup}/>
<div className="text-muted">© 2017-2018</div>
</div>
</div>
)
}
} |
JavaScript | class RestoreKibi {
/**
* @param config the investigate.yml config
* @param backupDir the folder with the backuped indices
*/
constructor(config, backupDir) {
this._config = config;
this._backupDir = backupDir;
this._dump = new Dump(config, backupDir);
}
async restore() {
let dirExists;
try {
await Promise.fromNode(cb => access(this._backupDir, cb));
dirExists = true;
} catch (err) {
dirExists = false;
}
if (!dirExists) {
throw new Error(`Backup folder [${this._backupDir}] does not exist`);
}
const kibiIndex = get(this._config, 'kibana.index', '.siren');
await this._dump.fromFileToElasticsearch(kibiIndex, 'mapping');
await this._dump.fromFileToElasticsearch(kibiIndex, 'data');
if (get(this._config, 'investigate_access_control.acl.enabled')) {
const aclIndex = get(this._config, 'investigate_access_control.acl.index', '.sirenaccess');
await this._dump.fromFileToElasticsearch(aclIndex, 'mapping');
await this._dump.fromFileToElasticsearch(aclIndex, 'data');
}
}
} |
JavaScript | @MJMLColumnElement({
tagName: 'mj-divider',
attributes: {
'border-color': '#000000',
'border-style': 'solid',
'border-width': '4px',
'padding': '10px 25px',
'width': '100%'
}
})
class Divider extends Component {
static baseStyles = {
p: {
fontSize: '1px',
margin: '0 auto'
}
}
styles = this.getStyles()
getStyles() {
const { mjAttribute } = this.props
return _.merge({}, this.constructor.baseStyles, {
p: {
borderTop: `${mjAttribute('border-width')} ${mjAttribute('border-style')} ${mjAttribute('border-color')}`,
width: mjAttribute('width')
}
})
}
outlookWidth() {
const { mjAttribute } = this.props
const parentWidth = parseInt(mjAttribute('parentWidth'))
const {width, unit} = widthParser(mjAttribute('width'))
switch(unit) {
case '%': {
return parentWidth * width / 100
}
default: {
return width
}
}
}
render() {
return (
<p
className="mj-divider-outlook"
data-divider-width={this.outlookWidth()}
style={this.styles.p} />
)
}
} |
JavaScript | class Clause {
constructor(statements, location, test) {
const privates = {
test: test,
statements: statements,
location: location,
}
if (test != null) privates.test = test;
privateProps.set(this, privates);
}
/**
* Returns the test to be applied to see if we execute this clauses's statements
* If test is null or undefined, the statements should be exeuted if this clause is reached.
* @memberof Statement.Conditional.Clause
* @returns {Expression}
*/
get test() { return privateProps.get(this).test; }
/**
* Returns the statements to execute if the test was succesful (or if there is no test)
* @memberof Statement.Conditional.Clause
* @returns {Statement.Base[]} an array of statements to execute
*/
get statements() { return privateProps.get(this).statements; }
} |
JavaScript | class Conditional extends Base {
constructor(clauses, location) {
super(location);
const privates = {
clauses: clauses,
}
privateProps.set(this, privates);
}
/**
* Clauses should be tested in order returned and the first one that passes has it's statements executed
* @memberof Statement.Conditional
* @instance
* @returns {Statement.Conditional.Clause[]} an array of clauses to test and execute. */
get clauses() { return privateProps.get(this).clauses; }
} |
JavaScript | class Gradients {
constructor() { }
createCustom(opts, id) {
const TagName = opts.tagName;
return (
<defs>
<TagName id={id} {...opts.attrs} >
{
opts.stops.map((stopAttrs) => {
return (<stop {...stopAttrs} />);
})
}
</TagName>
</defs>);
}
getType(gradientName, id, fillColor = '#000') {
switch (gradientName) {
case ENUMS.GRADIENT.LINEAR_HORIZONTAL: return (
<defs>
<linearGradient id={id} x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color="rgb(255,255,255)" stop-opacity="0" />
<stop offset="100%" stop-color={fillColor} stop-opacity="1" />
</linearGradient>
</defs>
);
default:
case ENUMS.GRADIENT.LINEAR_HORIZONTAL_REV: return (
<defs>
<linearGradient id={id} x1="0%" y1="0%" x2="0%" y2="100%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color={fillColor} stop-opacity="1" />
<stop offset="100%" stop-color="rgb(255,255,255)" stop-opacity="0" />
</linearGradient>
</defs>
);
case ENUMS.GRADIENT.LINEAR_VERTICAL: return (
<defs>
<linearGradient id={id} x1="0%" y1="0%" x2="100%" y2="0%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color={fillColor} stop-opacity="1" />
<stop offset="100%" stop-color="rgb(255,255,255)" stop-opacity="0" />
</linearGradient>
</defs>
);
case ENUMS.GRADIENT.LINEAR_VERTICAL_REV: return (
<defs>
<linearGradient id={id} x1="0%" y1="0%" x2="100%" y2="0%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color="rgb(255,255,255)" stop-opacity="0" />
<stop offset="100%" stop-color={fillColor} stop-opacity="1" />
</linearGradient>
</defs>
);
case ENUMS.GRADIENT.RADIAL: return (
<defs>
<radialGradient id={id} cx="50%" cy="50%" r="50%" fx="50%" fy="50%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color="rgb(255,255,255)" stop-opacity="0" />
<stop offset="100%" stop-color={fillColor} stop-opacity="1" />
</radialGradient>
</defs>
);
case ENUMS.GRADIENT.RADIAL_REV: return (
<defs>
<radialGradient id={id} cx="50%" cy="50%" r="50%" fx="50%" fy="50%" gradientUnits="objectBoundingBox">
<stop offset="0%" stop-color={fillColor} stop-opacity="1" />
<stop offset="100%" stop-color="rgb(255,255,255)" stop-opacity="0" />
</radialGradient>
</defs>
);
}
}
} |
JavaScript | class Message {
/**
* Create an object used to format localized messages of a local scope.
*
* @param parent - The parent messages object.
* @param key - The key of the message.
* @param message - The localized message.
*/
constructor(parent, key, message) {
this.parent = parent;
this.key = key;
this.message = message;
}
/**
* Format a message identified by a key in a local scope.
*
* @param values - The values of the message's placeholders (e.g., `{name: 'Joe'}`).
*
* @returns The formatted message as a string.
*/
format(values) {
if (values) {
try {
// @see https://formatjs.io/docs/core-concepts/icu-syntax/#quoting--escaping
this.intlMessageFormat = this.intlMessageFormat
? this.intlMessageFormat
: new intl_messageformat_1.default(this.message
.replace(/'/g, '@apostrophe@') // Escape (hide) apostrophes.
.replace(/</g, "'<'") // Smaller than escape.
.replace(/>/g, "'>'") // Greater than escape.
.replace(/''/g, '') // This only happens when two escapable characters are next to each other.
.replace(/@apostrophe@/g, "''"), // Two consecutive ASCII apostrophes represents one ASCII apostrophe.
this.parent.locale);
return String(this.intlMessageFormat.format(values))
.replace(/{/gi, '{') // Unescape curly braces to avoid escaping them with `IntlMessageFormat`.
.replace(/}/gi, '}');
}
catch (error) {
__1.log.warn(`unable to format message with key ${(0, __1.highlight)(this.key)} in ${(0, __1.highlightFilePath)(this.parent.messagesFilePath)}: ${error.message}}`);
return '';
}
}
return this.message;
}
/**
* Format a message identified by a key in a local into a JSX element.
*
* @param values - The values of the message's placeholders and/or JSX elements.
*
* @returns The formatted message as a JSX element.
*/
formatJsx(values) {
const { placeholderValues, jsxValues } = this.splitValuesByType(values);
if (!Object.keys(jsxValues).length) {
__1.log.warn(`unable to format message with key ${(0, __1.highlight)(this.key)} in ${(0, __1.highlightFilePath)(this.parent.messagesFilePath)} since no JSX element was provided`);
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {}, void 0);
}
const formattedMessage = this.format(placeholderValues);
try {
if (this.hasValidXml(formattedMessage)) {
return this.hydrate(formattedMessage, jsxValues);
}
}
catch (error) {
__1.log.warn(`unable to format message with key ${(0, __1.highlight)(this.key)} in ${(0, __1.highlightFilePath)(this.parent.messagesFilePath)}: ${error.message}`);
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, {}, void 0);
}
}
/**
* Split a message's value by type.
*
* @param values - The values of the message's placeholders and/or JSX elements.
*
* @returns A message's values split by type.
*/
splitValuesByType(values) {
const placeholderValues = {};
const jsxValues = {};
if (values !== undefined) {
for (const [key, value] of Object.entries(values)) {
if ((0, _1.isPlaceholderValue)(value)) {
placeholderValues[key] = value;
}
else {
jsxValues[key] = value;
}
}
}
return { placeholderValues, jsxValues };
}
/**
* Check if a message contains valid XML.
*
* @param message - A localized message.
*
* @returns True if the XML is valid, otherwise an error will be thrown.
*
* @throws Error with details in the `message` when the XML tag is not valid.
*/
hasValidXml(message) {
const tagsMatch = message.match(/<.*?>/gm);
if (tagsMatch === null) {
return true;
}
const tagTracker = [];
const uniqueTags = [];
tagsMatch.forEach((tag, position) => {
const tagName = this.getXmlTagName(tag);
if (tag[1] !== '/') {
// Check for unexpected opening tags.
if (uniqueTags.includes(tagName)) {
throw Error(`unexpected duplicate XML tag ${(0, __1.highlight)(tag)}. All tag names must be unique.`);
}
tagTracker.push(tagName);
uniqueTags.push(tagName);
}
else {
// Check for unexpected closing tags.
let unexpectedClosing = false;
if (position === 0) {
unexpectedClosing = true;
}
else {
if (tagTracker[tagTracker.length - 1] !== tagName) {
unexpectedClosing = true;
}
}
if (unexpectedClosing) {
throw Error(`unexpected closing XML tag ${(0, __1.highlight)(tag)}`);
}
// Remove tag from index.
tagTracker.pop();
}
});
if (tagTracker.length) {
throw Error(`unexpected unclosed XML tag ${(0, __1.highlight)(`<${tagTracker[tagTracker.length - 1]}>`)}`);
}
// At this point the XML is deemed valid.
return true;
}
/**
* Get the XML tag name from an XML tag (e.g., for `<div>` the name is `div`).
*
* @param xmlTag - The XML tag from which to get the name
*
* @returns The XML tag name when found, otherwise an error will be thrown.
*
* @throws Error with details in the `message` when the XML tag is not valid.
*/
getXmlTagName(xmlTag) {
const tagNameMatch = xmlTag.match(/<\/?(?<tagName>.*)>/m);
if (tagNameMatch === null) {
throw new Error(`invalid XML tag ${(0, __1.highlight)(xmlTag)}`);
}
// Check if the tag name has any attributes.
let tagName = tagNameMatch.groups['tagName'].trim();
let hasAttributes = false;
if (/\s/.test(tagName)) {
tagName = tagName.split(/\s/).shift();
hasAttributes = true;
}
// Check if the tag name is valid.
if (!/^[a-zA-Z0-9]*$/.test(tagName)) {
throw new Error(`invalid tag name ${(0, __1.highlight)(tagName)} in the XML tag ${(0, __1.highlight)(xmlTag)}. Tag names must only contain alphanumeric characters.`);
}
// If the tag name is valid, check if attributes were found.
if (hasAttributes) {
throw new Error(`attributes found on XML tag ${(0, __1.highlight)(xmlTag)}. Attributes can be set to JSX elements, not in .properties files`);
}
return tagName;
}
/**
* Hydrate a 'string' message into a JSX message.
*
* @param message - A localized message.
* @param values - The values of a message's JSX elements (e.g., `{b: <b></b>}`).
* @param key - The key of a JSX element being hydrated.
*
* @returns The message rehydrated into a JSX element and its child elements.
*/
hydrate(message, values, key) {
let messageSegment = message;
const reactNodes = [];
while (messageSegment !== null && messageSegment.length) {
// Get the next tag from the current message segment.
const tagMatch = messageSegment.match(/[^<]*(?<tag><.*?>).*/m);
if (tagMatch === null) {
reactNodes.push(this.unescapeXml(messageSegment));
break;
}
const { tag } = tagMatch.groups;
const tagName = this.getXmlTagName(tag);
if (values[tagName] === undefined) {
throw new Error(`missing JSX element passed as a value for the XML tag ${(0, __1.highlight)(tag)}`);
}
const nextMatch = messageSegment.match(new RegExp(`(?<startingSegment>.*?)<${tagName}.*?>(?<innerContent>.*?)<\\/${tagName}\\s*>(?<nextSegment>.*)`, 'm'));
const { startingSegment, innerContent, nextSegment } = nextMatch.groups;
if (startingSegment !== null) {
reactNodes.push(this.unescapeXml(startingSegment));
}
const childNode = this.hydrate(innerContent, values, tagName);
if (childNode === undefined) {
return undefined;
}
reactNodes.push(childNode);
messageSegment = nextSegment;
}
if (key !== undefined) {
return this.insertNodes(values[key], ...reactNodes);
}
return (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [...reactNodes] }, void 0);
}
/**
* Insert React nodes into a JSX element (or its deepest child if any).
*
* The target element can have child (no depth limit). But each child can only have one child since those
* will be the elements passed in arguments and they should only contain a single message fragment.
*
* @param element - The target JSX element.
* @param reactNodes - The React nodes being injected.
*
* @returns The JSX element with the nodes inserted.
*/
insertNodes(element, ...reactNodes) {
const elements = this.getElementChain(element);
const injectedElement = (0, react_1.cloneElement)(elements.pop(), null, ...reactNodes);
if (!elements.length) {
return injectedElement;
}
let currentElement = injectedElement;
do {
const parentElement = elements.pop();
currentElement = (0, react_1.cloneElement)(parentElement, null, currentElement);
} while (elements.length);
// Return the cloned elements with the inject message.
return currentElement;
}
/**
* Get an element chain (child list) from a JSX element.
*
* @param element - The target JSX element.
*
* @returns An array of JSX elements where the first one is the top parent and the last one the deepest child.
*
* @throws Error when a JSX element in the chain contains more than one child.
* @throws Error when a JSX element contains a message.
*/
getElementChain(element) {
const elements = [element];
let currentElement = element;
if (!currentElement.props.children) {
return elements;
}
while (currentElement.props.children) {
if (Array.isArray(currentElement.props.children)) {
throw new Error('cannot display message because JSX Elements can only have a single child. To have multiple JSX elements at the same level, use the XML syntax inside the message.');
}
if (typeof currentElement.props.children === 'string') {
throw new Error(`JSX elements cannot contain messages when passed in arguments. Use .properties files instead to make sure messages are localizable.`);
}
elements.push(currentElement.props.children);
currentElement = currentElement.props.children;
}
return elements;
}
/**
* Replaces HTML entities for `<` and `>` by the actual characters.
*
* @param message - A localized message.
*
* @returns The message without escaped XML tags.
*/
unescapeXml(message) {
return message
.replace(/</gi, '<') // Using standard HTML entities (TMS friendly) to escape XML tag delimiters.
.replace(/>/gi, '>');
}
} |
JavaScript | class SymbolValue {
/**
*
* @param {number} bid
* @param {number} ask
*/
constructor(bid, ask) {
this.bid = bid;
this.ask = ask;
}
/**
* @returns {number} - symbol's value
*/
getPrice() {
return Math.round(((this.bid + this.ask) / 2.0) * 100000) / 100000;
}
} |
JavaScript | class UserCheckerInterface {
/**
* Checks the user account before authentication.
*
* @param {Jymfony.Component.Security.User.UserInterface} user
*
* @throws {Jymfony.Component.Security.Exception.AccountStatusException}
*/
checkPreAuth(user) { }
/**
* Checks the user account after authentication.
*
* @param {Jymfony.Component.Security.User.UserInterface} user
*
* @throws {Jymfony.Component.Security.Exception.AccountStatusException}
*/
checkPostAuth(user) { }
} |
JavaScript | class PortfolioStore {
constructor(){
this.state = {
projects: [],
index: false
}
}
addProject(project) {
return this.state.projects.push(project)
}
setProjects(projects) {
return this.state.projects = projects
}
getProjects() {
return this.state.projects
}
getProjectBySlug(slug) {
return this.state.projects.filter((project)=> project.slug == slug)
}
open(index) {
this.state.index = index
}
close() {
this.state.index = false
}
prev() {
if(this.state.index <= 1) {
this.state.index = this.state.projects.length
}
else {
this.state.index--
}
}
next() {
if(this.state.index >= this.state.projects.length){
this.state.index = 1
}
else {
this.state.index++
}
}
} |
JavaScript | class AssignmentActivityUsageEntity extends Entity {
/**
* @returns {string} URL of the assignment entity associated with this assignment activity usage
*/
assignmentHref() {
if (!this._entity || !this._entity.hasLinkByRel(Rels.assignment)) {
return;
}
return this._entity.getLinkByRel(Rels.assignment).href;
}
onAssignmentChange(onChange) {
const assignmentHref = this.assignmentHref();
// _subEntity builds new sub entity and allows this object to track it.
// So all sub entities are dispose when this object is disposed.
assignmentHref && this._subEntity(AssignmentEntity, assignmentHref, onChange);
}
} |
JavaScript | class GeoBox {
/**
* Constructs a new `GeoBox` with the given geo coordinates.
*
* @param southWest - The south west position in geo coordinates.
* @param northEast - The north east position in geo coordinates.
*/
constructor(southWest, northEast) {
this.southWest = southWest;
this.northEast = northEast;
if (this.west > this.east) {
this.northEast.longitude += 360;
}
}
/**
* Returns a `GeoBox` with the given geo coordinates.
*
* @param southWest - The south west position in geo coordinates.
* @param northEast - The north east position in geo coordinates.
*/
static fromCoordinates(southWest, northEast) {
return new GeoBox(southWest, northEast);
}
/**
* Returns a `GeoBox` with the given center and dimensions.
*
* @param center - The center position of geo box.
* @param extent - Box latitude and logitude span
*/
static fromCenterAndExtents(center, extent) {
return new GeoBox(new GeoCoordinates_1.GeoCoordinates(center.latitude - extent.latitudeSpan / 2, center.longitude - extent.longitudeSpan / 2), new GeoCoordinates_1.GeoCoordinates(center.latitude + extent.latitudeSpan / 2, center.longitude + extent.longitudeSpan / 2));
}
/**
* Returns the minimum altitude or `undefined`.
*/
get minAltitude() {
if (this.southWest.altitude === undefined || this.northEast.altitude === undefined) {
return undefined;
}
return Math.min(this.southWest.altitude, this.northEast.altitude);
}
/**
* Returns the maximum altitude or `undefined`.
*/
get maxAltitude() {
if (this.southWest.altitude === undefined || this.northEast.altitude === undefined) {
return undefined;
}
return Math.max(this.southWest.altitude, this.northEast.altitude);
}
/**
* Returns the south latitude in degrees of this `GeoBox`.
*/
get south() {
return this.southWest.latitude;
}
/**
* Returns the north altitude in degrees of this `GeoBox`.
*/
get north() {
return this.northEast.latitude;
}
/**
* Returns the west longitude in degrees of this `GeoBox`.
*/
get west() {
return this.southWest.longitude;
}
/**
* Returns the east longitude in degrees of this `GeoBox`.
*/
get east() {
return this.northEast.longitude;
}
/**
* Returns the center of this `GeoBox`.
*/
get center() {
const latitude = (this.south + this.north) * 0.5;
const { west, east } = this;
const { minAltitude, altitudeSpan } = this;
let altitude;
if (minAltitude !== undefined && altitudeSpan !== undefined) {
altitude = minAltitude + altitudeSpan * 0.5;
}
if (west <= east) {
return new GeoCoordinates_1.GeoCoordinates(latitude, (west + east) * 0.5, altitude);
}
let longitude = (360 + east + west) * 0.5;
if (longitude > 360) {
longitude -= 360;
}
return new GeoCoordinates_1.GeoCoordinates(latitude, longitude, altitude);
}
/**
* Returns the latitude span in radians.
*/
get latitudeSpanInRadians() {
return THREE.MathUtils.degToRad(this.latitudeSpan);
}
/**
* Returns the longitude span in radians.
*/
get longitudeSpanInRadians() {
return THREE.MathUtils.degToRad(this.longitudeSpan);
}
/**
* Returns the latitude span in degrees.
*/
get latitudeSpan() {
return this.north - this.south;
}
get altitudeSpan() {
if (this.maxAltitude === undefined || this.minAltitude === undefined) {
return undefined;
}
return this.maxAltitude - this.minAltitude;
}
/**
* Returns the longitude span in degrees.
*/
get longitudeSpan() {
let width = this.northEast.longitude - this.southWest.longitude;
if (width < 0) {
width += 360;
}
return width;
}
/**
* Returns the latitude span in degrees.
* @deprecated Use [[latitudeSpan]] instead.
*/
get latitudeSpanInDegrees() {
return this.latitudeSpan;
}
/**
* Returns the longitude span in degrees.
* @deprecated Use [[longitudeSpan]] instead.
*/
get longitudeSpanInDegrees() {
return this.longitudeSpan;
}
/**
* Returns `true` if the given geo coordinates are contained in this `GeoBox`.
*
* @param point - The geo coordinates.
*/
contains(point) {
if (point.altitude === undefined ||
this.minAltitude === undefined ||
this.maxAltitude === undefined) {
return this.containsHelper(point);
}
const isFlat = this.minAltitude === this.maxAltitude;
const isSameAltitude = this.minAltitude === point.altitude;
const isWithinAltitudeRange = this.minAltitude <= point.altitude && this.maxAltitude > point.altitude;
// If box is flat, we should check the altitude and containment,
// otherwise we should check also altitude difference where we consider
// point to be inside if alt is from [m_minAltitude, m_maxAltitude) range!
if (isFlat ? isSameAltitude : isWithinAltitudeRange) {
return this.containsHelper(point);
}
return false;
}
/**
* Clones this `GeoBox` instance.
*/
clone() {
return new GeoBox(this.southWest.clone(), this.northEast.clone());
}
/**
* Update the bounding box by considering a given point.
*
* @param point - The point that may expand the bounding box.
*/
growToContain(point) {
this.southWest.latitude = Math.min(this.southWest.latitude, point.latitude);
this.southWest.longitude = Math.min(this.southWest.longitude, point.longitude);
this.southWest.altitude =
this.southWest.altitude !== undefined && point.altitude !== undefined
? Math.min(this.southWest.altitude, point.altitude)
: this.southWest.altitude !== undefined
? this.southWest.altitude
: point.altitude !== undefined
? point.altitude
: undefined;
this.northEast.latitude = Math.max(this.northEast.latitude, point.latitude);
this.northEast.longitude = Math.max(this.northEast.longitude, point.longitude);
this.northEast.altitude =
this.northEast.altitude !== undefined && point.altitude !== undefined
? Math.max(this.northEast.altitude, point.altitude)
: this.northEast.altitude !== undefined
? this.northEast.altitude
: point.altitude !== undefined
? point.altitude
: undefined;
}
containsHelper(point) {
if (point.latitude < this.southWest.latitude || point.latitude >= this.northEast.latitude) {
return false;
}
const { west, east } = this;
let longitude = point.longitude;
if (east > GeoCoordinates_1.MAX_LONGITUDE) {
while (longitude < west) {
longitude = longitude + 360;
}
}
if (longitude > east) {
while (longitude > west + 360) {
longitude = longitude - 360;
}
}
return longitude >= west && longitude < east;
}
} |
JavaScript | class View {
constructor () {
this.document = document
this.section = this.createElement('section', 'section')
this.name = this.createElement('h1', 'post_name')
this.section.append(this.name)
this.description = this.createElement('p', 'post_description')
this.section.append(this.description)
this.avatar = this.createElement('img', 'post_avatar')
this.avatar.className = 'img-fluid img-thumbnail'
this.section.append(this.avatar)
this.post = {}
}
createElement (tag, attribute) {
const element = this.document.createElement(tag)
element.setAttribute('id', attribute)
return element
}
getElement (selector) {
const element = this.section.querySelector('#' + selector)
return element
}
setElement (selector, text) {
const element = this.getElement(selector)
element.innerHTML = text
}
setImage (selector, url) {
const element = this.getElement(selector)
element.src = url
}
appendPost (post) {
console.log(post)
this.setElement('post_name', post.name)
this.setElement('post_description', post.description)
this.setImage('post_avatar', post.avatar)
return this.section.outerHTML
}
} |
JavaScript | class Navigation extends React.Component {
/**
* Constructor
*
* @param {object} props React props
* @param {array} props.assets List of assets to display in a nav dropdown
*/
constructor (props) {
super(props);
this.state = {};
}
/**
* Returns the count for a list of assets
*
* @param {array} assets List of assets
* @returns {mixed} Returns the asset count or '?' if the assets param wasn't an array
*/
getAssetCount (assets) {
let assetCount = '?';
if (_.isArray(assets)) {
assetCount = _.size(assets);
}
return assetCount;
}
/**
* Renders the component
*/
render () {
const assetsIsArray = _.isArray(this.props.assets);
const assetCount = this.getAssetCount(this.props.assets);
return (
<Navbar variant="dark" bg="dark">
<Navbar.Brand href="#">Barovian Activity Map</Navbar.Brand>
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<NavDropdown title={`Assets: ${assetCount}`} id="basic-nav-dropdown">
{assetsIsArray
? (assetCount === 0)
? <NavDropdown.Item href="" key="empty">No Assets</NavDropdown.Item>
: this.props.assets.map((asset) => <NavDropdown.Item href="" key={asset.id}>{asset.name}</NavDropdown.Item>)
: <NavDropdown.Item href="" key="empty">Assets Unknown</NavDropdown.Item>
}
</NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
} |
JavaScript | class ContentNegotiator {
constructor(routeDefinitions) {
this.routeDefinitions = routeDefinitions;
this.mediaTypes = routeDefinitions
.filter((definition) => typeof definition.produces !== 'undefined')
.map((definition) => definition.produces);
const duplicatedMediaType = this.findConflictingRoutes();
if (duplicatedMediaType)
throw new Error(`Conflicting route definitions found. You have registered multiple routes that produces the media type "${duplicatedMediaType}".`);
}
findConflictingRoutes() {
return utils_1.hasDuplicate(this.mediaTypes, (a, b) => a === b);
}
retrieveHandler(accept = '*/*') {
if (this.mediaTypes.length === 0)
return this.routeDefinitions[0];
const negotiator = new negotiator_1.default({ headers: { accept } });
const acceptedMediaTypes = negotiator.mediaTypes(this.mediaTypes);
if (acceptedMediaTypes.length === 0) {
throw new router_error_1.RouterError(406, 'Not Acceptable', `Media type ${accept} is not acceptable. Acceptable media types: ${this.mediaTypes.join(', ')}`);
}
return this.routeDefinitions.find((definition) => definition.produces === acceptedMediaTypes[0]);
}
} |
JavaScript | class GameOfLife extends React.Component {
constructor() {
super();
this.state = {
config: {
width: 70,
height: 50,
totalCells: 3500,
},
cells: [],
clearedCells: [],
running: false,
generation: 0,
speed: 80,
drawMode: 'draw',
currentPattern: [],
customPatterns: {
gliderGun: [500, 501, 570, 571, 510, 580, 650, 721, 441, 372, 373, 792, 793, 445, 725, 516, 586, 656, 587, 584, 380, 381, 450, 451, 520, 521, 312, 592, 244, 314, 594, 664, 394, 395, 464, 465],
switchEngine: [1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1423, 1424, 1425, 1426, 1427, 1431, 1432, 1433, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1448, 1449, 1450, 1451, 1452],
pufferTrain: [906, 907, 908, 975, 976, 977, 978, 979, 1044, 1045, 1047, 1048, 1049, 1115, 1116, 1322, 1324, 1385, 1391, 1394, 1454, 1455, 1456, 1457, 1458, 1462, 1464, 1523, 1524, 1528, 1529, 1531, 1532, 1594, 1602, 1665, 1666, 1669, 1672, 1743, 1805, 1806, 1809, 1812, 1874, 1882, 1943, 1944, 1948, 1949, 1951, 1952, 2014, 2015, 2016, 2017, 2018, 2022, 2024, 2085, 2091, 2094, 2162, 2164, 2375, 2376, 2444, 2445, 2447, 2448, 2449, 2515, 2516, 2517, 2518, 2519, 2586, 2587, 2588],
heart: [1146,1147,1148,1149,1150,1151,1159,1160,1161,1162,1163,1164,1215,1222,1228,1235,1284,1293,1297,1306,1353,1364,1366,1377,1422,1435,1448,1491,1519,1561,1589,1630,1660,1700,1730,1770,1800,1840,1870,1911,1939,1982,2008,2053,2077,2124,2146,2195,2215,2266,2284,2337,2353,2408,2422,2479,2491,2550,2560,2621,2629,2692,2698,2763,2767,2834,2836,2905],
},
};
}
componentDidMount() {
/*
* Perform functions that require window object here to avoid issues with server rendering
*/
// Function to generate config which dictates height/width of grid based on window width.
const makeConfig = () => {
let windowWidth = window.innerWidth;
let width;
let height;
if (this.props.livePreview) {
width = 60;
height = 40;
if (windowWidth < 433) {
width = 30;
height = 45;
}
} else {
if (windowWidth < 768) {
width = 30;
height = 45;
} else if (windowWidth < 1050) {
width = 60;
height = 40;
} else {
width = 70;
height = 50;
}
}
return {
width,
height,
totalCells: width * height,
};
}
const config = makeConfig()
/**
* FIXME: dynamically resizing canvas adds a whole host of problems
* - clearedCells array doesnt update with resize
* - using pause doesnt updat cells when scaling up
* - patterns in reset wont work when scaling down
*/
// window.addEventListener('resize', () => {
// const { running } = this.state;
// const config = makeConfig();
//
// if (config.width !== this.state.config.width) {
// this.clear();
//
// this.setState({
// cells: this.setupCells('random'),
// config: makeConfig(),
// });
//
// if (running) {
// this.start();
// }
// }
// });
// Setup a initial cells array for creating patterns.
const clearedCells = [];
let x = 0;
let y = 0;
for (let cellID = 0, totalCells = config.totalCells; cellID < totalCells; cellID++) {
clearedCells.push(this.createCellNode(cellID, false, undefined, x, y));
// Move to the next cell
x += 12;
// Move to the next row
if (x >= config.width * 12) {
x = 0;
y += 12;
}
}
this.setState({
clearedCells,
config,
customPatterns: Object.assign(this.state.customPatterns, this.getLocalStorage()),
});
const grid = this.refs.grid;
if (grid.getContext) {
this.grid = grid.getContext('2d');
/**
* The following provides the ability to drag the mouse to create a pattern,
* rather than clicking individual cells.
*/
let prevCellID;
const moveListener = ev => {
const currCellID = this.getCanvasClickedCellID(ev);
if (currCellID === prevCellID) {
return;
}
prevCellID = currCellID;
this.handleCellClick(currCellID);
};
grid.addEventListener('mousedown', ev => {
const cellID = this.getCanvasClickedCellID(ev);
prevCellID = cellID;
this.handleCellClick(cellID);
// Drawing only works when game isnt running, to prevent lag.
if (!this.state.running) {
grid.addEventListener('mousemove', moveListener);
}
});
window.addEventListener('mouseup', ev => {
grid.removeEventListener('mousemove', moveListener);
});
}
// Allows clearedCells array to be put into state before random cells are setup
setTimeout(() => {
this.setupCells('random');
this.props.livePreview || this.start();
})
}
componentWillUnmount() {
this.clearTimer();
}
checkNeighbours = position => {
const cells = this.state.cells;
const w = this.state.config.width;
const l = cells.length;
let neighbours = 0;
// Checks nodes in the top left corner
if (position === 0) {
if (cells[l - 1].alive) neighbours += 1;
if (cells[l - w].alive) neighbours += 1;
if (cells[l - w + 1].alive) neighbours += 1;
if (cells[w - 1].alive) neighbours += 1;
if (cells[1].alive) neighbours += 1;
if (cells[w * 2 - 1].alive) neighbours += 1;
if (cells[w].alive) neighbours += 1;
if (cells[w + 1].alive) neighbours += 1;
// Checks nodes in the top right corner
} else if (position === w - 1) {
if (cells[l - 2].alive) neighbours += 1;
if (cells[l - 1].alive) neighbours += 1;
if (cells[l - w].alive) neighbours += 1;
if (cells[w - 2].alive) neighbours += 1;
if (cells[0].alive) neighbours += 1;
if (cells[w * 2 - 2].alive) neighbours += 1;
if (cells[w * 2 - 1].alive) neighbours += 1;
if (cells[w].alive) neighbours += 1;
// Checkes nodes in the bottom left corner
} else if (position === l - w) {
if (cells[l - w - 1].alive) neighbours += 1;
if (cells[position - w].alive) neighbours += 1;
if (cells[position - w + 1].alive) neighbours += 1;
if (cells[l - 1].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
if (cells[w - 1].alive) neighbours += 1;
if (cells[0].alive) neighbours += 1;
if (cells[1].alive) neighbours += 1;
// Checks nodes in the bottom right corner
} else if (position === l - 1) {
if (cells[l - w - 2].alive) neighbours += 1;
if (cells[l - w - 1].alive) neighbours += 1;
if (cells[l - w * 2].alive) neighbours += 1;
if (cells[l - 2].alive) neighbours += 1;
if (cells[l - w].alive) neighbours += 1;
if (cells[w - 2].alive) neighbours += 1;
if (cells[w - 1].alive) neighbours += 1;
if (cells[0].alive) neighbours += 1;
// Checks nodes in top row (excluding the corners)
} else if (position >= 1 && position <= w - 2) {
if (cells[l - w + position].alive) neighbours += 1;
if (cells[l - w - 1 + position].alive) neighbours += 1;
if (cells[l - w + 1 + position].alive) neighbours += 1;
if (cells[position - 1].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
if (cells[position + w + 1].alive) neighbours += 1;
if (cells[position + w].alive) neighbours += 1;
if (cells[position + w - 1].alive) neighbours += 1;
// Checks nodes in bottom row (excluding corners)
} else if (position >= l - w + 1 && position <= l - 2) {
if (cells[position - w - 1].alive) neighbours += 1;
if (cells[position - w].alive) neighbours += 1;
if (cells[position - w + 1].alive) neighbours += 1;
if (cells[position - 1].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
if (cells[w - (l - position) - 1].alive) neighbours += 1;
if (cells[w - (l - position)].alive) neighbours += 1;
if (cells[w - (l - position) + 1].alive) neighbours += 1;
// Checks nodes in the left column (excluding corners)
} else if (position % w === 0) {
if (cells[position - 1].alive) neighbours += 1;
if (cells[position - w].alive) neighbours += 1;
if (cells[position - w + 1].alive) neighbours += 1;
if (cells[position + w - 1].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
if (cells[position + w * 2 - 1].alive) neighbours += 1;
if (cells[position + w].alive) neighbours += 1;
if (cells[position + w + 1].alive) neighbours += 1;
// Checks nodes in the right column (excluding corners)
} else if (position % w === w - 1) {
if (cells[position - w - 1].alive) neighbours += 1;
if (cells[position - w].alive) neighbours += 1;
if (cells[position - w * 2 + 1].alive) neighbours += 1;
if (cells[position - 1].alive) neighbours += 1;
if (cells[position - w + 1].alive) neighbours += 1;
if (cells[position + w - 1].alive) neighbours += 1;
if (cells[position + w].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
// Checks all other nodes in the middle
} else {
if (cells[position - w - 1].alive) neighbours += 1;
if (cells[position - w].alive) neighbours += 1;
if (cells[position - w + 1].alive) neighbours += 1;
if (cells[position - 1].alive) neighbours += 1;
if (cells[position + 1].alive) neighbours += 1;
if (cells[position + w - 1].alive) neighbours += 1;
if (cells[position + w].alive) neighbours += 1;
if (cells[position + w + 1].alive) neighbours += 1;
}
return neighbours;
}
updateCanvasGrid = cells => {
if (this.grid) {
function getFillStyle(cell) {
if (!cell.alive) {
return '#37474f';
}
if (cell.old) {
return '#1565c0';
}
if (cell.alive) {
return '#29b6f6';
}
}
for (let cell = 0, length = cells.length; cell < length; cell++) {
let x = cells[cell].x;
let y = cells[cell].y;
// Draw the cell
this.grid.fillStyle = getFillStyle(cells[cell]);
this.grid.fillRect(x, y, 12, 12);
// Give the cell a border
this.grid.strokeStyle = '#263238';
this.grid.strokeRect(x, y, 12, 12);
}
}
}
getCanvasClickedCellID = ev => {
const rect = this.refs.grid.getBoundingClientRect();
const x = ev.clientX - rect.left;
const y = ev.clientY - rect.top;
return this.state.cells.findIndex((cell) => (
x >= cell.x
&& x <= cell.x + 12
&& y >= cell.y
&& y <= cell.y + 12
));
}
getLocalStorage = () => (
JSON.parse(localStorage.getItem('fccGameOfLife'))
)
setLocalStorage = data => {
localStorage.setItem('fccGameOfLife', JSON.stringify(data));
}
start = () => {
if (!this.state.running) {
const startFn = () => {
// If all cells are dead, stop the game and reset generation.
if (this.checkIfAllCellsDead()) {
return this.clear();
}
const { nextCells, changedCells } = this.changeCells();
this.setState({
cells: nextCells,
generation: this.state.generation += 1
});
this.updateCanvasGrid(changedCells);
this.clearTimer();
this.generationTimer = setTimeout(startFn, this.state.speed);
};
this.setState({
running: true,
currentPattern: this.getPatternIDS(),
});
this.generationTimer = setTimeout(startFn, this.state.speed)
}
}
pause = () => {
this.setState({ running: false });
this.clearTimer();
}
clear = () => {
this.clearTimer();
this.setState({
cells: this.state.clearedCells,
running: false,
generation: 0,
});
this.updateCanvasGrid(this.state.clearedCells);
}
reset = () => {
this.clear();
this.setupCells(this.state.currentPattern);
}
clearTimer = () => {
clearTimeout(this.generationTimer);
}
setupCells = pattern => {
const nextCells = this.state.clearedCells.map(cell => (
this.createCellNode(
cell.id,
pattern === 'random'
? Math.random() <= 0.2
: pattern.some(id => id === cell.id)
)
));
this.setState({ cells: nextCells });
this.updateCanvasGrid(nextCells);
}
changeCells = () => {
const cells = this.state.cells;
let nextCells = [];
let changedCells = [];
for (let cellID = 0, length = this.state.config.totalCells; cellID < length; cellID++) {
let aliveNeighbours = this.checkNeighbours(cellID);
if (cells[cellID].alive) {
if (aliveNeighbours >= 4 || aliveNeighbours <= 1) {
let cell = this.createCellNode(cellID, false);
nextCells.push(cell);
changedCells.push(cell);
} else {
let cell = this.createCellNode(cellID, true, true);
nextCells.push(cell);
changedCells.push(cell);
}
} else if (aliveNeighbours === 3) {
let cell = this.createCellNode(cellID, true);
nextCells.push(cell);
changedCells.push(cell);
} else {
nextCells.push(cells[cellID]);
}
}
return { nextCells, changedCells };
}
checkIfAllCellsDead = () => {
for (let cell = 0, length = this.state.config.totalCells; cell < length; cell++) {
if (this.state.cells[cell].alive) {
return;
}
}
return true;
}
changeGridPattern = pattern => {
this.clear();
this.setupCells(
typeof pattern === 'string'
? this.state.customPatterns[pattern]
: pattern
);
}
createCellNode = (id, alive, old = false, x, y) => {
x = x !== undefined ? x : this.state.clearedCells[id].x;
y = y !== undefined ? y : this.state.clearedCells[id].y;
return {
id,
alive,
old,
x,
y,
};
}
getPatternIDS = () => (
this.state.cells
.filter(cell => cell.alive)
.map(cell => cell.id)
)
savePattern = () => {
const newCustomPatterns = Object.assign(
this.state.customPatterns, {
[this.camelCase(this.refs.patternNameInput.value)]: this.getPatternIDS()
}
);
this.setState({ customPatterns: newCustomPatterns});
this.setLocalStorage(newCustomPatterns);
this.refs.patternNameInput.value = '';
}
deletePattern = () => {
const pattern = this.refs.patternSelector.value;
const customPatterns = this.state.customPatterns
const newCustomPatterns = {};
if (pattern && confirm(`
Are you sure you want to delete the pattern: "${this.unCamelCase(pattern)}"?
`)) {
for (let key in customPatterns) {
if (pattern !== key) {
newCustomPatterns[key] = customPatterns[key]
}
}
this.setState({ customPatterns: newCustomPatterns })
this.setLocalStorage(newCustomPatterns);
}
}
importPattern = () => {
const pattern = prompt('Please paste the pattern below and press ok.');
if (pattern) {
this.clear();
this.changeGridPattern(JSON.parse(pattern));
}
}
exportPattern = () => {
alert(
`Please copy the below:
${JSON.stringify(this.getPatternIDS())}`
)
}
camelCase = text => (
text
.replace(/\s(.)/g, match => match.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, match => match.toLowerCase())
)
unCamelCase = text => (
text
.split(/(?=[A-Z])/g)
.map(word => `${word[0].toUpperCase()}${word.substring(1)}`)
.join(' ')
)
handleCellClick = cellID => {
// Only runs if the click/drag is within the canvas borders
if (cellID) {
const cell = this.createCellNode(cellID, this.state.drawMode === 'draw' || false);
const nextCells = [
...this.state.cells.slice(0, cellID),
cell,
...this.state.cells.slice(cellID + 1)
]
this.setState({ cells: nextCells });
this.updateCanvasGrid([cell]);
}
}
renderCanvasBackup = () => (
this.state.cells.map(cell => (
<section
key={cell.id}
id={cell.id}
onClick={() => this.handleCellClick(cell.id)}
className={classNames({
'GameOfLife__grid__cell': true,
'GameOfLife__grid__cell--dead': !cell.alive,
'GameOfLife__grid__cell--alive': cell.alive,
'GameOfLife__grid__cell--old': cell.old
})}
/>
))
)
render() {
return (
<section>
<section className="GameOfLife">
<h1 className="GameOfLife__generation">Generations: {this.state.generation}</h1>
<canvas
className="GameOfLife__grid"
ref="grid"
width={this.state.config.width * 12}
height={this.state.config.height * 12}
>
<section className="GameOfLife__grid GameOfLife__grid--canvas-backup">
{this.grid ? null : this.renderCanvasBackup()}
</section>
</canvas>
<section className="GameOfLife__options">
<section className="GameOfLife__options__controls">
<Button onClick={this.start} className="GameOfLife__options__controls__start">Start</Button>
<Button onClick={this.pause} className="GameOfLife__options__controls__pause">Pause</Button>
<Button onClick={this.reset} className="GameOfLife__options__controls__reset">Reset</Button>
<Button onClick={this.clear} className="GameOfLife__options__controls__clear">Clear</Button>
<label htmlFor="speed-input">
<span className="title">Speed</span>
<span className="speed">{`${this.state.speed}ms`}</span>
</label>
<div>
<input
id="speed-input"
onChange={ev => this.setState({ speed: ev.target.value })}
value={this.state.speed}
min={10}
max={150}
type="range"
/>
</div>
</section>
<section className="GameOfLife__options__draw">
<i
onClick={() => this.setState({ drawMode: 'draw' })}
className={classNames({
'material-icons': true,
'GameOfLife__options__draw__mode': true,
'GameOfLife__options__draw__mode--active': this.state.drawMode === 'draw',
})}
>
create
</i>
<i
onClick={() => this.setState({ drawMode: 'erase' })}
className={classNames({
'material-icons': true,
'GameOfLife__options__draw__mode': true,
'GameOfLife__options__draw__mode--active': this.state.drawMode === 'erase',
})}
>
brightness_1
</i>
</section>
<section className="GameOfLife__options__patterns">
<select ref="patternSelector" onChange={ev => this.changeGridPattern(ev.target.value)}>
<option value="" disabled selected>Please select a pattern</option>
<option value="random">Random</option>
{Object.keys(this.state.customPatterns).map(pattern => (
<option key={pattern} value={pattern}>{this.unCamelCase(pattern)}</option>
))}
</select>
<i
onClick={this.deletePattern}
className="material-icons GameOfLife__options__patterns__delete"
>
delete
</i>
<input
className="GameOfLife__options__patterns__name-input"
ref="patternNameInput"
placeholder="Enter pattern name..."
/>
<Button onClick={this.savePattern}>Save</Button>
{/* <section className="GameOfLife__options__patterns__import-export">
<Button onClick={this.importPattern}>Import</Button>
<Button onClick={this.exportPattern}>Export</Button>
</section> */}
</section>
</section>
</section>
<ProjectNotes
title="Game of Life"
js="abdf881648a7528e5c0dbf9574cda692"
css="40e5b740742fec49259b55dd230658df"
titleLink="https://www.freecodecamp.com/challenges/build-the-game-of-life"
objective="Build a working version of John Conway's Game of Life. It should be functionally similar to: "
objectiveLink="https://codepen.io/FreeCodeCamp/full/reGdqx/"
userStories={[
'I can start and stop the board.',
'I can set up the board.',
'I can clear the board.',
'When I press start, the game will play out.',
'Each time the board changes, I can see how many generations have gone by.'
]}
/>
</section>
);
}
} |
JavaScript | class User extends React.Component {
render(){
return(
<tr>
<td>{this.props.user.id}</td>
<td>{this.props.user.firstName}</td>
<td>{this.props.user.lastName}</td>
<td>{moment(this.props.user.date).format("MM-DD-YYYY")}</td>
<td>{moment(this.props.user.FromHour).format("hh:mm:ss")}</td>
<td>{moment(this.props.user.ToHour).format("hh:mm:ss")}</td>
<td>{moment(this.props.user.sum).format("hh")}</td>
</tr>
);
}
} |
JavaScript | class BaseModel extends BaseEntity_1.BaseEntity {
constructor(type, id) {
super(id);
this.type = type;
this.selected = false;
}
getParent() {
return this.parent;
}
setParent(parent) {
this.parent = parent;
}
getSelectedEntities() {
if (this.isSelected()) {
return [this];
}
return [];
}
deSerialize(ob, engine) {
super.deSerialize(ob, engine);
this.type = ob.type;
this.selected = ob.selected;
}
serialize() {
return _.merge(super.serialize(), {
type: this.type,
selected: this.selected
});
}
getType() {
return this.type;
}
getID() {
return this.id;
}
isSelected() {
return this.selected;
}
setSelected(selected = true) {
this.selected = selected;
this.iterateListeners((listener, event) => {
if (listener.selectionChanged) {
listener.selectionChanged(Object.assign({}, event, { isSelected: selected }));
}
});
}
remove() {
this.iterateListeners((listener, event) => {
if (listener.entityRemoved) {
listener.entityRemoved(event);
}
});
}
} |
JavaScript | class API {
constructor() {
/**
* @property {string} this.domain - url string of the domain + root url path.
* Is used as base url to be extended while making API requests
*/
this.domain =
process.env.REACT_APP_NODE_ENV === 'production'
? process.env.REACT_APP_BACKEND_PRODUCTION_URL + '/api/'
: process.env.REACT_APP_BACKEND_DEVELOPMENT_URL + '/api/';
}
/**
* @method request - Constructs the request object and sends it to the backend
* @author Raymond Ndibe <[email protected]>
*
* @param {string} url - the api endpoint
* @param {string} method - the http method of the request to be constructed
* @param {string} token - the user auth token if provided
* @param {string} body - request body
* @param {string} content_type - content type to be used for the request
* @returns {Promise<>}
*/
request = ({
url = '/',
method = 'GET',
token,
body,
content_type = 'application/json',
}) => {
if (method === 'GET' && !token) {
return fetch(this.domain + url, {
method,
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: 'true',
headers: new Headers({
'Content-Type': content_type,
'Accept-Language': `${i18next.language},en;q=0.5`,
}),
});
} else if (token && body) {
return fetch(this.domain + url, {
method,
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: 'true',
headers: content_type
? new Headers({
Authorization: `Token ${token}`,
'Content-Type': content_type,
'Accept-Language': `${i18next.language},en;q=0.5`,
})
: new Headers({
Authorization: `Token ${token}`,
'Accept-Language': `${i18next.language},en;q=0.5`,
}),
body,
});
} else if (token) {
return fetch(this.domain + url, {
method,
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: 'true',
headers: new Headers({
Authorization: `Token ${token}`,
'Content-Type': content_type,
'Accept-Language': `${i18next.language},en;q=0.5`,
}),
});
} else if (body) {
return fetch(this.domain + url, {
method,
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: 'true',
headers: new Headers({
'Content-Type': content_type,
'Accept-Language': `${i18next.language},en;q=0.5`,
}),
body,
});
}
};
/**
* @method login - login with email and password
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
login = ({ username, password }) => {
const url = 'rest-auth/login/';
const method = 'POST';
const body = JSON.stringify({ username, password });
return this.request({ url, method, body }).then(res => res.json());
};
/**
* @method logout - logout a user with the user's token
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
logout = token => {
const url = 'rest-auth/logout/';
const method = 'POST';
return this.request({ url, method, token }).then(res => res.json());
};
/**
* @method signup - create an account for a user with the user's details
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
signup = ({
username,
email,
phone,
dateOfBirth,
user_location,
password1,
password2,
bio,
subscribe,
}) => {
const url = 'creators/register/';
const method = 'POST';
const body = JSON.stringify({
username,
email,
phone,
dateOfBirth,
location: user_location,
password1,
password2,
bio,
subscribe,
});
return this.request({ url, method, body }).then(res => res.json());
};
/**
* @method sendEmailConfirmation - verify a user's email by making api call
* to this endpoint with the provided key
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
sendEmailConfirmation = key => {
const url = 'rest-auth/registration/verify-email/';
const method = 'POST';
const body = JSON.stringify({ key });
return this.request({ url, method, body }).then(res =>
Promise.resolve(res.status === 200 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method sendPhoneConfirmation - verify a user's phone number by making api call
* to this endpoint with the provided key
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
sendPhoneConfirmation = key => {
const url = 'creators/verify-phone/';
const method = 'POST';
const body = JSON.stringify({ key });
return this.request({ url, method, body }).then(res =>
Promise.resolve(res.status === 200 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method sendPasswordResetLink
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
sendPasswordResetLink = email => {
const url = 'rest-auth/password/reset/';
const method = 'POST';
const body = JSON.stringify({ email });
return this.request({ url, method, body }).then(res =>
Promise.resolve(res.status === 200 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method passwordResetConfirm
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
passwordResetConfirm = ({ new_password1, new_password2, uid, token }) => {
const url = 'rest-auth/password/reset/confirm/';
const method = 'POST';
const body = JSON.stringify({ new_password1, new_password2, uid, token });
return this.request({ url, method, body }).then(res =>
Promise.resolve(res.status === 200 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method getAuthUser - make api request to this endpoint providing a valid user token to
* get the user profile of the user with the provided token
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getAuthUser = token => {
const url = 'creators/auth-user/';
return this.request({ url, token }).then(res => res.json());
};
/**
* @method getAccountStatus - make api request to this endpoint providing a valid user token to
* get the account status of the creator the token belongs to.
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getAccountStatus = token => {
const url = 'creators/account-status/';
return this.request({ url, token }).then(res => res.json());
};
/**
* @method getUserProfile - get the user profile of the user that the username belongs to
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getUserProfile = ({ username, token }) => {
const url = `creators/${username}/`;
if (token) {
return this.request({ url, token }).then(res => res.json());
} else {
return this.request({ url }).then(res => res.json());
}
};
/**
* @method getUserProjects - get a paginated list of projects
* created by the user with the provided username
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getUserProjects = ({ username, page, limit }) => {
let url;
if (limit && page) {
url = `creators/${username}/projects/?limit=${limit}&&${page}`;
} else if (limit) {
url = `creators/${username}/projects/?limit=${limit}`;
} else if (page) {
url = `creators/${username}/projects/?${page}`;
} else {
url = `creators/${username}/projects/`;
}
return this.request({ url }).then(res => res.json());
};
/**
* @method searchProjects - perform full-text search of projects
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
searchProjects = ({ page, token, query_string, criteria }) => {
const params = { q: query_string, criteria };
if (page) {
params[page] = page;
}
const searchParams = new URLSearchParams(params);
const url = `projects/search/?${searchParams.toString()}`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method searchCreators
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
searchCreators = ({ page, token, query_string }) => {
let url;
if (page) {
url = `creators/search/?q=${query_string}&page=${page}`;
} else {
url = `creators/search/?q=${query_string}`;
}
return this.request({ url, token }).then(res => res.json());
};
searchTags = ({ page, token, query_string }) => {
let url;
if (page) {
url = `projects/tags/search/?q=${query_string}&page=${page}`;
} else {
url = `projects/tags/search/?q=${query_string}`;
}
return this.request({ url, token }).then(res => res.json());
};
/**
* @method getFollowers - get a list of users that a username is following
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getFollowers = ({ page, username }) => {
const url = page
? `creators/${username}/followers/?${page}`
: `creators/${username}/followers/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getFollowing
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getFollowing = ({ page, username }) => {
const url = page
? `creators/${username}/following/?${page}`
: `creators/${username}/following/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getSaved - get a list of projects bookmarked by the user with the given token
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getSaved = ({ page, token }) => {
const url = page ? `projects/saved/?${page}` : `projects/saved/`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method editUserProfile
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
editUserProfile = props => {
const { token, username, email, phone, dateOfBirth, bio, user_location } =
props;
const url = 'creators/edit-creator/';
const method = 'PUT';
const body = JSON.stringify({
username,
email,
phone,
dateOfBirth,
bio,
location: user_location,
});
return this.request({ url, method, token, body }).then(res => res.json());
};
/**
* @method deleteAccount
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
deleteAccount = ({ token }) => {
const url = 'creators/delete/';
const method = 'DELETE';
return this.request({ url, method, token }).then(res =>
Promise.resolve(res.status === 204 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method toggleFollow
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
toggleFollow = ({ id, token }) => {
const url = `creators/${id}/toggle-follow/`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method getMembers
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getMembers = ({ page, username }) => {
const url = page
? `creators/${username}/members/?${page}`
: `creators/${username}/members/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method addMembers
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
addMembers = ({ token, data }) => {
const url = 'creators/add-members/';
const method = 'POST';
const content_type = false;
const body = data;
return this.request({ url, method, token, body, content_type }).then(res =>
res.json(),
);
};
/**
* @method removeMember
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
removeMember = ({ id, token }) => {
const url = `creators/${id}/remove-member/`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method sendGroupInviteConfirmation
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
sendGroupInviteConfirmation = key => {
const url = 'creators/confirm-group-invite/';
const method = 'POST';
const body = JSON.stringify({ key });
return this.request({ url, method, body }).then(res =>
Promise.resolve(res.status === 200 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method getLocations
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getLocations = () => {
const url = 'creators/locations/';
return this.request({ url }).then(res => res.json());
};
/**
* @method createProject
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
createProject = ({
token,
title,
description,
video,
images,
materials_used,
category,
tags,
publish,
}) => {
const url = 'projects/create/';
const method = 'POST';
const body = JSON.stringify({
title,
description,
images,
video,
materials_used,
category,
tags,
publish,
});
return this.request({ url, method, token, body }).then(res => res.json());
};
/**
* @method updateProject
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
updateProject = ({
token,
id,
title,
description,
video,
images,
materials_used,
category,
tags,
publish,
}) => {
const url = `projects/${id}/update/`;
const method = 'PATCH';
const body = JSON.stringify({
id,
title,
description,
images,
video,
materials_used,
category,
tags,
publish,
});
return this.request({ url, method, token, body }).then(res => res.json());
};
/**
* @method deleteProject
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
deleteProject = ({ token, id }) => {
const url = `projects/${id}/delete/`;
const method = 'DELETE';
return this.request({ url, method, token }).then(res =>
Promise.resolve(res.status === 204 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method shouldUploadToLocal
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
shouldUploadToLocal = ({ token }) => {
const url = 'upload-file-to-local/';
return this.request({ url, token }).then(res => res.json());
};
/**
* @method unpublishComment
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
unpublishComment = ({ token, id }) => {
const url = `projects/${id}/unpublish-comment/`;
const method = 'PATCH';
const body = JSON.stringify({});
return this.request({ url, method, token, body }).then(res =>
Promise.resolve(
res.status === 200 ? res.json() : { details: 'unknown error' },
),
);
};
/**
* @method deleteComment
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
deleteComment = ({ token, id }) => {
const url = `projects/${id}/delete-comment/`;
const method = 'DELETE';
return this.request({ url, method, token }).then(res =>
Promise.resolve(res.status === 204 ? { detail: 'ok' } : res.json()),
);
};
/**
* @method getProjects
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getProjects = ({ token, page }) => {
const url = page ? `projects/?${page}` : `projects/`;
return this.request({ token, url }).then(res => res.json());
};
/**
* @method getCategories
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getCategories = () => {
const url = 'projects/categories/';
return this.request({ url }).then(res => res.json());
};
/**
* @method suggestTags
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
suggestTags = value => {
const url = `projects/tags/search/?q=${value}`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getStaffPicks
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getStaffPicks = ({ token }) => {
const url = 'projects/staff-picks/';
return this.request({ token, url }).then(res => res.json());
};
/**
* @method getStaffPick
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getStaffPick = ({ token, page, id }) => {
const url = page
? `projects/staff-picks/${id}/?page=${page}`
: `projects/staff-picks/${id}`;
return this.request({ token, url }).then(res => res.json());
};
/**
* @method getProject
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getProject = ({ id, token }) => {
const url = `projects/${id}`;
if (token) {
return this.request({ url, token }).then(res => res.json());
} else {
return this.request({ url }).then(res => res.json());
}
};
/**
* @method toggleLike
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
toggleLike = ({ id, token }) => {
const url = `projects/${id}/toggle-like/`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method toggleSave
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
toggleSave = ({ id, token }) => {
const url = `projects/${id}/toggle-save/`;
return this.request({ url, token }).then(res => res.json());
};
/**
* @method addComment
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
addComment = ({ id, text, token, parent_id }) => {
const url = `projects/${id}/add-comment/`;
const method = 'POST';
const body = JSON.stringify({ text, parent_id });
return this.request({ url, method, body, token }).then(res => res.json());
};
/**
* @method addProfileComment
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
addProfileComment = ({ id, text, token, parent_id }) => {
const url = `creators/${id}/add-comment/`;
const method = 'POST';
const body = JSON.stringify({ text, parent_id });
return this.request({ url, method, body, token }).then(res => res.json());
};
/**
* @method getHero
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getHero = () => {
const url = `hero/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getHelp
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getHelp = () => {
const url = `help/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getPrivacy
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getPrivacy = () => {
const url = `privacy/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getFaqs
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getFaqs = () => {
const url = `faqs/`;
return this.request({ url }).then(res => res.json());
};
/**
* @method getSignature
* @author Raymond Ndibe <[email protected]>
*
* @todo - describe method's signature
*/
getSignature = args => {
const url = 'signature/';
const method = 'POST';
const token = args.token;
delete args.token;
const body = JSON.stringify({ ...args });
return this.request({ url, method, token, body }).then(res => res.json());
};
} |
JavaScript | class KueWithIORedisFactory {
static options(){
return {
singleton: true,
mode: 'factory'
}
}
/**
* Create a new instance of the Kue interface
* @param config
* @param logger
* @param _kue {Object} used for testing
* @returns {Queue}
*/
static create(config, logger, _kue){
const kue = _kue || Kue;
const result = Joi.validate(config, KueSchema);
if (result.error) throw new Error(result.error);
config = result.value;
const queue = kue.createQueue({
redis: {
createClientFactory: () => {
return new Redis(config.connection.redis);
}
}
});
// Watch stuck jobs if defined
if (config.watchStuckInterval){
queue.watchStuckJobs(config.watchStuckInterval);
}
return queue;
}
} |
JavaScript | class SliceMessengerFactory {
/**
* Messages transports
* @static
*/
static transports = []
/**
* Add transport
* @param {SliceMessageTransport} transport SliceMessageTransport instance.
* @return {void}
* @static
*/
static addTransport(transport) {
if (transport instanceof SliceMessageTransport) {
if (SliceMessengerFactory.transports.indexOf(transport) < 0) {
SliceMessengerFactory.transports.push(transport)
}
}
}
/**
* Get messenger id from URL
* @param {string} searchURL URL to get messenger id from.
* @return {void}
* @static
*/
static getIdFromURL(searchURL) {
let id = null
const prop = 'messengerId'
const queryStart = searchURL.indexOf("?") + 1
const queryEnd = searchURL.indexOf("#") + 1 || searchURL.length + 1
const query = searchURL.slice(queryStart, queryEnd - 1)
if (URLSearchParams) {
const params = new URLSearchParams(`?${query}`)
if (params.has(prop)) {
id = params.get(prop)
}
} else {
const parseQuery = (value) => {
let params = {}
if (value === "") {
return params
}
const pairs = value.replace(/\+/g, " ").split("&")
for (let i = 0; i < pairs.length; i++) {
const nv = pairs[i].split("=", 2)
const n = decodeURIComponent(nv[0])
const v = decodeURIComponent(nv[1])
if (!params.hasOwnProperty(n)) {
params[n] = []
}
params[n].push(nv.length === 2 ? v : null)
}
return params
}
const params = parseQuery(query)
if (params.hasOwnProperty(prop)) {
id = params[prop]
}
}
return id
}
/**
* Get available transport
* @param {string} id SliceMessage id.
* @param {SliceMessageTransport} transport SliceMessageTransport instance.
* @return {SliceMessenger} created SliceMessenger instance
* @public
*/
static getAvailableTransport() {
let transport = null
if (SliceMessengerFactory.transports.length) {
SliceMessengerFactory.transports.some((item) => {
if (item.isAvailable()) {
transport = item
return true
}
return false
})
}
return transport
}
/**
* Create messenger
* @param {string} id SliceMessage id.
* @param {SliceMessageTransport} transport SliceMessageTransport instance.
* @return {SliceMessenger} created SliceMessenger instance
* @public
*/
static createMessenger(id = SliceMessengerFactory.getIdFromURL(location.search), transport = SliceMessengerFactory.getAvailableTransport()) {
return new SliceMessenger(id, transport)
}
} |
JavaScript | class HttpProvider extends BaseProvider {
constructor (options) {
super(options, defaultOptions)
this.http = axios.create({
baseURL: this.options.endpoint
})
}
get name () {
return 'http'
}
async handle (method, params, convert = false) {
const rawResponse = await this.http.post('/', {
jsonrpc: '2.0',
method: method,
params: params,
id: uuidv4()
})
const response = utils.utils.isString(rawResponse.data)
? JSON.parse(rawResponse.data)
: rawResponse.data
if (response.error) {
throw new Error(response.message)
}
if (convert) {
response.result = this._convertBuffers(response.result)
}
return response.result
}
/**
* Converts any buffer items into hex strings.
* Necessary until we stop pumping buffers out of the operator.
* @param {*} response A response object.
* @return {*} Parsed response with converted buffers.
*/
_convertBuffers (response) {
if (Array.isArray(response)) {
return response.map((item) => {
return this._convertBuffers(item)
})
} else if (typeof response !== 'object' || response === null) {
return response
} else if (this._isBuffer(response)) {
return this._convertBuffer(response)
}
for (let field in response) {
if (this._isBuffer(response[field])) {
response[field] = this._convertBuffer(response[field])
}
}
return response
}
/**
* Converts a buffer to a hex string.
* @param {Buffer} value A buffer.
* @return {string} Buffer as a hex string.
*/
_convertBuffer (value) {
return Buffer.from(value).toString('hex')
}
/**
* Checks if value is a buffer.
* @param {*} value Value to check.
* @return {boolean} `true` if the value is a buffer, `false` otherwise.
*/
_isBuffer (value) {
return value && value.type === 'Buffer'
}
} |
JavaScript | class Combat extends Entity {
constructor(...args) {
super(...args);
/**
* Track the sorted turn order of this combat encounter
* @type {Array}
*/
this.turns=null;
/**
* Record the current round, turn, and tokenId to understand changes in the encounter state
* @type {Object}
* @private
*/
this.current = {
round: null,
turn: null,
tokenId: null
};
/**
* Track the previous round, turn, and tokenId to understand changes in the encounter state
* @type {Object}
* @private
*/
this.previous = {
round: null,
turn: null,
tokenId: null
};
/**
* Track whether a sound notification is currently being played to avoid double-dipping
* @type {Boolean}
* @private
*/
this._soundPlaying = false;
}
/* -------------------------------------------- */
/**
* Configure the attributes of the Folder Entity
*
* @returns {Entity} baseEntity The parent class which directly inherits from the Entity interface.
* @returns {EntityCollection} collection The EntityCollection class to which Entities of this type belong.
* @returns {Array} embeddedEntities The names of any Embedded Entities within the Entity data structure.
*/
static get config() {
return {
baseEntity: Combat,
collection: window.game.combats,
embeddedEntities: { "Combatant": "combatants" },
label: "ENTITY.Combat"
};
}
/* -------------------------------------------- */
/**
* Prepare Embedded Entities which exist within the parent Combat.
* For example, in the case of an Actor, this method is responsible for preparing the Owned Items the Actor contains.
*/
prepareEmbeddedEntities() {
this.turns = this.setupTurns();
}
/* -------------------------------------------- */
/* Properties */
/* -------------------------------------------- */
/**
* A convenience reference to the Array of combatant data within the Combat entity
* @type {Array.<Object>}
*/
get combatants() {
return this.data.combatants;
}
/* -------------------------------------------- */
/**
* Get the data object for the Combatant who has the current turn
* @type {Object}
*/
get combatant() {
return this.turns[this.data.turn];
}
/* -------------------------------------------- */
/**
* The numeric round of the Combat encounter
* @type {number}
*/
get round() {
return this.data.round;
}
/* -------------------------------------------- */
/**
* The numeric turn of the combat round in the Combat encounter
* @type {number}
*/
get turn() {
return this.data.turn;
}
/* -------------------------------------------- */
/**
* Get the Scene entity for this Combat encounter
* @return {Scene}
*/
get scene() {
return window.game.scenes.get(this.data.scene);
}
/* -------------------------------------------- */
/**
* Return the object of settings which modify the Combat Tracker behavior
* @return {Object}
*/
get settings() {
return this.collection.settings;
}
/* -------------------------------------------- */
/**
* Has this combat encounter been started?
* @type {Boolean}
*/
get started() {
return ( this.turns.length > 0 ) && ( this.round > 0 );
}
/* -------------------------------------------- */
/* Combat Control Methods */
/* -------------------------------------------- */
/**
* Set the current Combat encounter as active within the Scene.
* Deactivate all other Combat encounters within the viewed Scene and set this one as active
* @return {Promise.<Combat>}
*/
async activate() {
const scene = window.game.scenes.viewed;
const updates = this.collection.entities.reduce((arr, c) => {
if ( (c.data.scene === scene.id) && c.data.active ) arr.push({_id: c.data._id, active: false});
return arr;
}, []);
updates.push({_id: this.id, active: true});
return this.constructor.update(updates);
}
/* -------------------------------------------- */
/**
* Return the Array of combatants sorted into initiative order, breaking ties alphabetically by name
* @return {Array}
*/
setupTurns() {
const scene = window.game.scenes.get(this.data.scene);
const players = window.game.users.players;
// Populate additional data for each combatant
let turns = this.data.combatants.map(c => {
c.token = scene.getEmbeddedEntity("Token", c.tokenId);
if ( !c.token ) return c;
c.actor = Actor.fromToken(c.token);
c.players = c.actor ? players.filter(u => c.actor.hasPerm(u, "OWNER")) : [];
c.owner = window.game.user.isGM || (c.actor ? c.actor.owner : false);
c.visible = c.owner || !c.hidden;
return c;
}).filter(c => c.token);
// Sort turns into initiative order: (1) initiative, (2) name, (3) tokenId
turns = turns.sort((a, b) => {
const ia = Number.isNumeric(a.initiative) ? a.initiative : -9999;
const ib = Number.isNumeric(b.initiative) ? b.initiative : -9999;
let ci = ib - ia;
if ( ci !== 0 ) return ci;
let [an, bn] = [a.token.name || "", b.token.name || ""];
let cn = an.localeCompare(bn);
if ( cn !== 0 ) return cn;
return a.tokenId - b.tokenId;
});
// Ensure the current turn is bounded
this.data.turn = Math.clamped(this.data.turn, 0, turns.length-1);
this.turns = turns;
// When turns change, tracked resources also change
// if ( ui.combat ) ui.combat.updateTrackedResources();
return this.turns;
}
/* -------------------------------------------- */
/**
* Begin the combat encounter, advancing to round 1 and turn 1
* @return {Promise}
*/
async startCombat() {
return this.update({round: 1, turn: 0});
}
/* -------------------------------------------- */
/**
* Advance the combat to the next turn
* @return {Promise}
*/
async nextTurn() {
let turn = this.turn;
let skip = this.settings.skipDefeated;
// Determine the next turn number
let next = null;
if ( skip ) {
for ( let [i, t] of this.turns.entries() ) {
if ( i <= turn ) continue;
if ( !t.defeated ) {
next = i;
break;
}
}
} else next = turn + 1;
// Maybe advance to the next round
let round = this.round;
if ( (this.round === 0) || (next === null) || (next >= this.turns.length) ) {
round = round + 1;
next = 0;
if ( skip ) {
next = this.turns.findIndex(t => !t.defeated);
if (next === -1) {
console.warn("COMBAT.NoneRemaining");
next = 0;
}
}
}
// Update the encounter
return this.update({round: round, turn: next});
}
/* -------------------------------------------- */
/**
* Rewind the combat to the previous turn
* @return {Promise}
*/
async previousTurn() {
if ( this.turn === 0 && this.round === 0 ) return Promise.resolve();
else if ( this.turn === 0 ) return this.previousRound();
return this.update({turn: this.turn - 1});
}
/* -------------------------------------------- */
/**
* Advance the combat to the next round
* @return {Promise}
*/
async nextRound() {
let turn = 0;
if ( this.settings.skipDefeated ) {
turn = this.turns.findIndex(t => !t.defeated);
if (turn === -1) {
console.warn("COMBAT.NoneRemaining");
turn = 0;
}
}
return this.update({round: this.round+1, turn: turn});
}
/* -------------------------------------------- */
/**
* Rewind the combat to the previous round
* @return {Promise}
*/
async previousRound() {
let turn = ( this.round === 0 ) ? 0 : this.turns.length - 1;
return this.update({round: Math.max(this.round - 1, 0), turn: turn});
}
/* -------------------------------------------- */
/**
* Reset all combatant initiative scores, setting the turn back to zero
* @return {Promise}
*/
async resetAll() {
const updates = this.data.combatants.map(c => { return {
_id: c._id,
initiative: null
}});
await this.updateEmbeddedEntity("Combatant", updates);
return this.update({turn: 0});
}
/* -------------------------------------------- */
/**
* Display a dialog querying the GM whether they wish to end the combat encounter and empty the tracker
* @return {Promise}
*/
async endCombat() {
// return Dialog.confirm({
// title: "End Combat Encounter?",
// content: "<p>End this combat encounter and empty the turn tracker?</p>",
// yes: () => this.delete()
// });
}
/* -------------------------------------------- */
/* Combatant Management Methods */
/* -------------------------------------------- */
/** @extends {Entity.getEmbeddedEntity} */
getCombatant(id) {
return this.getEmbeddedEntity("Combatant", id);
}
/* -------------------------------------------- */
/**
* Get a Combatant using its Token id
* {string} tokenId The id of the Token for which to acquire the combatant
*/
getCombatantByToken(tokenId) {
return this.turns.find(c => c.tokenId === tokenId);
}
/* -------------------------------------------- */
/**
* Set initiative for a single Combatant within the Combat encounter.
* Turns will be updated to keep the same combatant as current in the turn order
* @param {string} id The combatant ID for which to set initiative
* @param {Number} value A specific initiative value to set
*/
async setInitiative(id, value) {
const currentId = this.combatant._id;
await this.updateCombatant({_id: id, initiative: value}, {});
await this.update({turn: this.turns.findIndex(c => c._id === currentId)});
}
/* -------------------------------------------- */
/**
* Roll initiative for one or multiple Combatants within the Combat entity
* @param {Array|string} ids A Combatant id or Array of ids for which to roll
* @param {string|null} formula A non-default initiative formula to roll. Otherwise the system default is used.
* @param {Object} messageOptions Additional options with which to customize created Chat Messages
* @return {Promise.<Combat>} A promise which resolves to the updated Combat entity once updates are complete.
*/
async rollInitiative(ids, formula=null, messageOptions={}) {
// Structure input data
ids = typeof ids === "string" ? [ids] : ids;
const currentId = this.combatant._id;
// Iterate over Combatants, performing an initiative roll for each
const [updates, messages] = ids.reduce((results, id, i) => {
let [updates, messages] = results;
// Get Combatant data
const c = this.getCombatant(id);
if ( !c || !c.owner ) return results;
// Roll initiative
const cf = formula || this._getInitiativeFormula(c);
const roll = this._getInitiativeRoll(c, cf);
updates.push({_id: id, initiative: roll.total});
// Determine the roll mode
let rollMode = messageOptions.rollMode || window.game.settings.get("core", "rollMode");
if (( c.token.hidden || c.hidden ) && (rollMode === "roll") ) rollMode = "gmroll";
// Construct chat message data
// let messageData = mergeObject({
// speaker: {
// scene: canvas.scene._id,
// actor: c.actor ? c.actor._id : null,
// token: c.token._id,
// alias: c.token.name
// },
// flavor: `${c.token.name} rolls for Initiative!`
// }, messageOptions);
// const chatData = roll.toMessage(messageData, {rollMode, create:false});
// if ( i > 0 ) chatData.sound = null; // Only play 1 sound for the whole set
// messages.push(chatData);
// Return the Roll and the chat data
return results;
}, [[], []]);
if ( !updates.length ) return this;
// Update multiple combatants
await this.updateEmbeddedEntity("Combatant", updates);
// Ensure the turn order remains with the same combatant
await this.update({turn: this.turns.findIndex(t => t._id === currentId)});
// Create multiple chat messages
await CONFIG.ChatMessage.entityClass.create(messages);
// Return the updated Combat
return this;
}
/* -------------------------------------------- */
/**
* Acquire the default dice formula which should be used to roll initiative for a particular combatant.
* Modules or systems could choose to override or extend this to accommodate special situations.
* @private
*
* @param {Object} combatant Data for the specific combatant for whom to acquire an initiative formula. This
* is not used by default, but provided to give flexibility for modules and systems.
* @return {string} The initiative formula to use for this combatant.
*/
_getInitiativeFormula(combatant) {
return CONFIG.Combat.initiative.formula || window.game.system.data.initiative;
}
/* -------------------------------------------- */
/**
* Get a Roll object which represents the initiative roll for a given combatant.
* @private
* @param {Object} combatant Data for the specific combatant for whom to acquire an initiative formula. This
* is not used by default, but provided to give flexibility for modules and systems.
* @param {string} [formula] An explicit Roll formula to use for the combatant.
* @return {Roll} The Roll instance to use for the combatant.
*/
_getInitiativeRoll(combatant, formula) {
// const rollData = combatant.actor ? combatant.actor.getRollData() : {};
// return new Roll(formula, rollData).roll();
}
/* -------------------------------------------- */
/**
* Roll initiative for all non-player actors who have not already rolled
* @param {...*} args Additional arguments forwarded to the Combat.rollInitiative method
*/
async rollNPC(...args) {
const npcs = this.turns.filter(t => (!t.actor || !t.players.length) && !t.initiative);
return this.rollInitiative(npcs.map(t => t._id), ...args);
}
/* -------------------------------------------- */
/**
* Roll initiative for all combatants which have not already rolled
* @param {...*} args Additional arguments forwarded to the Combat.rollInitiative method
*/
async rollAll(...args) {
const unrolled = this.turns.filter(t => t.owner && !t.initiative);
return this.rollInitiative(unrolled.map(t => t._id), ...args);
}
/* -------------------------------------------- */
/** @extends {Entity.createEmbeddedEntity} */
async createCombatant(data, options) {
return this.createEmbeddedEntity("Combatant", data, options);
}
/* -------------------------------------------- */
/** @extends {Entity.updateEmbeddedEntity} */
async updateCombatant(data, options) {
return this.updateEmbeddedEntity("Combatant", data, options);
}
/* -------------------------------------------- */
/** @extends {Entity.deleteEmbeddedEntity} */
async deleteCombatant(id, options) {
return this.deleteEmbeddedEntity("Combatant", id, options);
}
/* -------------------------------------------- */
/* Socket Events and Handlers
/* -------------------------------------------- */
/** @override */
_onCreate(...args) {
console.log(args)
// if ( !this.collection.viewed ) ui.combat.initialize({combat: this});
}
/* -------------------------------------------- */
/** @override */
_onUpdate(data, ...args) {
super._onUpdate(data, ...args);
this.setupTurns()
console.log('updating combat')
// Update state tracking
this.previous = this.current;
let c = this.combatant;
this.current = {round: this.data.round, turn: this.data.turn, tokenId: c ? c.tokenId : null};
// If the Combat was set as active, initialize the sidebar
if ( (data.active === true) && ( this.data.scene === window.game.scenes.viewed._id ) ) {
// ui.combat.initialize({combat: this});
}
// Render the sidebar
if ( ["combatants", "round", "turn"].some(k => data.hasOwnProperty(k)) ) {
if ( data.combatants ) this.setupTurns();
// ui.combat.scrollToTurn();
}
}
/* -------------------------------------------- */
/** @override */
_onDelete(...args) {
// if ( this.collection.viewed === this ) ui.combat.initialize();
}
/* -------------------------------------------- */
/** @override */
_onDeleteEmbeddedEntity(embeddedName, child, options, userId) {
super._onDeleteEmbeddedEntity(embeddedName, child, options, userId);
const deletedTurn = this.turns.findIndex(t => t._id === child._id);
if ( deletedTurn <= this.turn ) return this.update({turn: this.turn - 1});
}
/* -------------------------------------------- */
/** @override */
_onModifyEmbeddedEntity(...args) {
this.setupTurns();
if ( this === this.collection.viewed ) this.collection.render();
}
} |
JavaScript | class Strategy {
constructor(name) {
this._name = (name)? name : "";
}
get name() {
return this._name;
}
set name(newName) {
this._name = newName;
}
willCooperate(params) {
return true;
}
} |
JavaScript | class Bar extends Document {
constructor() {
super();
this.foo = require('./foo');
this.num = Number;
}
} |
JavaScript | class Microapi extends Koa {
constructor() {
super()
this.use(body())
this.use(cors())
this.router = new Router()
}
define(api = './api') {
let directory = path.resolve(process.cwd(), api)
this.routing = routing(this.router, directory)
this.use(this.router.routes())
this.use(this.router.allowedMethods())
}
} |
JavaScript | class PublicServerResetMessage extends React.Component {
static propTypes = {
deviceType: PropTypes.string.isRequired,
plural: PropTypes.bool.isRequired
}
static defaultProps = {
}
constructor(props) {
super(props);
}
render() {
let messageText = 'This public server is freely avaliable for testing purposes, however its resources may be removed or reset at any time.';
if (this.props.plural){
messageText = 'These public servers are freely avaliable for testing purposes, however their resources may be removed or reset at any time.'
}
return (
<Message size={DeviceConstants.sizeForMessage(this.props.deviceType)}
negative
icon>
<Icon name='warning sign' />
<Message.Content>
<Message.Header>Warning</Message.Header>
{messageText}
</Message.Content>
</Message>
)
}
} |
JavaScript | class Stack {
constructor(capacity) {
this.MAX_SIZE = capacity;
this.arr = new Array(capacity);
this.CURRENT_SIZE = 0;
}
push = (data) => {
if(this.CURRENT_SIZE < this.MAX_SIZE) {
this.arr[this.CURRENT_SIZE] = data;
this.CURRENT_SIZE += 1;
console.log(`${data} added to stack`);
} else {
console.error("stack is full");
}
};
pop = () => {
if(this.CURRENT_SIZE > 0) {
let index = this.CURRENT_SIZE;
this.CURRENT_SIZE -= 1;
return this.arr[index];
} else {
console.error("stack is empty");
}
};
display = () => {
for(let i = this.CURRENT_SIZE-1; i >= 0; i--) {
console.log(this.arr[i]);
}
};
} |
JavaScript | class B2EdgeShape extends b2Shape_1.B2Shape {
constructor() {
super(1 /* e_edgeShape */, b2Settings_1.B2_polygonRadius);
this.m_vertex1 = new b2Math_1.B2Vec2();
this.m_vertex2 = new b2Math_1.B2Vec2();
this.m_vertex0 = new b2Math_1.B2Vec2();
this.m_vertex3 = new b2Math_1.B2Vec2();
this.m_hasVertex0 = false;
this.m_hasVertex3 = false;
}
/// Set this as an isolated edge.
Set(v1, v2) {
this.m_vertex1.Copy(v1);
this.m_vertex2.Copy(v2);
this.m_hasVertex0 = false;
this.m_hasVertex3 = false;
return this;
}
/// Implement B2Shape.
Clone() {
return new B2EdgeShape().Copy(this);
}
Copy(other) {
super.Copy(other);
/// b2Assert(other instanceof B2EdgeShape);
this.m_vertex1.Copy(other.m_vertex1);
this.m_vertex2.Copy(other.m_vertex2);
this.m_vertex0.Copy(other.m_vertex0);
this.m_vertex3.Copy(other.m_vertex3);
this.m_hasVertex0 = other.m_hasVertex0;
this.m_hasVertex3 = other.m_hasVertex3;
return this;
}
/// @see B2Shape::GetChildCount
GetChildCount() {
return 1;
}
/// @see B2Shape::TestPoint
TestPoint(xf, p) {
return false;
}
ComputeDistance(xf, p, normal, childIndex) {
const v1 = b2Math_1.B2Transform.MulXV(xf, this.m_vertex1, B2EdgeShape.ComputeDistance_s_v1);
const v2 = b2Math_1.B2Transform.MulXV(xf, this.m_vertex2, B2EdgeShape.ComputeDistance_s_v2);
const d = b2Math_1.B2Vec2.SubVV(p, v1, B2EdgeShape.ComputeDistance_s_d);
const s = b2Math_1.B2Vec2.SubVV(v2, v1, B2EdgeShape.ComputeDistance_s_s);
const ds = b2Math_1.B2Vec2.DotVV(d, s);
if (ds > 0) {
const s2 = b2Math_1.B2Vec2.DotVV(s, s);
if (ds > s2) {
b2Math_1.B2Vec2.SubVV(p, v2, d);
}
else {
d.SelfMulSub(ds / s2, s);
}
}
normal.Copy(d);
return normal.Normalize();
}
RayCast(output, input, xf, childIndex) {
// Put the ray into the edge's frame of reference.
const p1 = b2Math_1.B2Transform.MulTXV(xf, input.p1, B2EdgeShape.RayCast_s_p1);
const p2 = b2Math_1.B2Transform.MulTXV(xf, input.p2, B2EdgeShape.RayCast_s_p2);
const d = b2Math_1.B2Vec2.SubVV(p2, p1, B2EdgeShape.RayCast_s_d);
const v1 = this.m_vertex1;
const v2 = this.m_vertex2;
const e = b2Math_1.B2Vec2.SubVV(v2, v1, B2EdgeShape.RayCast_s_e);
const normal = output.normal.Set(e.y, -e.x).SelfNormalize();
// q = p1 + t * d
// dot(normal, q - v1) = 0
// dot(normal, p1 - v1) + t * dot(normal, d) = 0
const numerator = b2Math_1.B2Vec2.DotVV(normal, b2Math_1.B2Vec2.SubVV(v1, p1, b2Math_1.B2Vec2.s_t0));
const denominator = b2Math_1.B2Vec2.DotVV(normal, d);
if (denominator === 0) {
return false;
}
const t = numerator / denominator;
if (t < 0 || input.maxFraction < t) {
return false;
}
const q = b2Math_1.B2Vec2.AddVMulSV(p1, t, d, B2EdgeShape.RayCast_s_q);
// q = v1 + s * r
// s = dot(q - v1, r) / dot(r, r)
const r = b2Math_1.B2Vec2.SubVV(v2, v1, B2EdgeShape.RayCast_s_r);
const rr = b2Math_1.B2Vec2.DotVV(r, r);
if (rr === 0) {
return false;
}
const s = b2Math_1.B2Vec2.DotVV(b2Math_1.B2Vec2.SubVV(q, v1, b2Math_1.B2Vec2.s_t0), r) / rr;
if (s < 0 || 1 < s) {
return false;
}
output.fraction = t;
b2Math_1.B2Rot.MulRV(xf.q, output.normal, output.normal);
if (numerator > 0) {
output.normal.SelfNeg();
}
return true;
}
ComputeAABB(aabb, xf, childIndex) {
const v1 = b2Math_1.B2Transform.MulXV(xf, this.m_vertex1, B2EdgeShape.ComputeAABB_s_v1);
const v2 = b2Math_1.B2Transform.MulXV(xf, this.m_vertex2, B2EdgeShape.ComputeAABB_s_v2);
b2Math_1.B2Vec2.MinV(v1, v2, aabb.lowerBound);
b2Math_1.B2Vec2.MaxV(v1, v2, aabb.upperBound);
const r = this.m_radius;
aabb.lowerBound.SelfSubXY(r, r);
aabb.upperBound.SelfAddXY(r, r);
}
/// @see B2Shape::ComputeMass
ComputeMass(massData, density) {
massData.mass = 0;
b2Math_1.B2Vec2.MidVV(this.m_vertex1, this.m_vertex2, massData.center);
massData.I = 0;
}
SetupDistanceProxy(proxy, index) {
proxy.m_vertices = proxy.m_buffer;
proxy.m_vertices[0].Copy(this.m_vertex1);
proxy.m_vertices[1].Copy(this.m_vertex2);
proxy.m_count = 2;
proxy.m_radius = this.m_radius;
}
ComputeSubmergedArea(normal, offset, xf, c) {
c.SetZero();
return 0;
}
Dump(log) {
log(' const shape: B2EdgeShape = new B2EdgeShape();\n');
log(' shape.m_radius = %.15f;\n', this.m_radius);
log(' shape.m_vertex0.Set(%.15f, %.15f);\n', this.m_vertex0.x, this.m_vertex0.y);
log(' shape.m_vertex1.Set(%.15f, %.15f);\n', this.m_vertex1.x, this.m_vertex1.y);
log(' shape.m_vertex2.Set(%.15f, %.15f);\n', this.m_vertex2.x, this.m_vertex2.y);
log(' shape.m_vertex3.Set(%.15f, %.15f);\n', this.m_vertex3.x, this.m_vertex3.y);
log(' shape.m_hasVertex0 = %s;\n', this.m_hasVertex0);
log(' shape.m_hasVertex3 = %s;\n', this.m_hasVertex3);
}
} |
JavaScript | class CreateAccountRequest extends AuthRequest {
/**
* @param [options={}] {Object}
* @param [options.accountManager] {AccountManager}
* @param [options.userAccount] {UserAccount}
* @param [options.session] {Session} e.g. req.session
* @param [options.response] {HttpResponse}
* @param [options.returnToUrl] {string} If present, redirect the agent to
* this url on successful account creation
* @param [options.enforceToc] {boolean} Whether or not to enforce the service provider's T&C
* @param [options.tocUri] {string} URI to the service provider's T&C
* @param [options.acceptToc] {boolean} Whether or not user has accepted T&C
*/
constructor (options) {
super(options)
this.username = options.username
this.userAccount = options.userAccount
this.acceptToc = options.acceptToc
this.disablePasswordChecks = options.disablePasswordChecks
this.certPEM = options.certPEM
this.certPKCS12 = options.certPKCS12
if (this.userAccount &&
this.userAccount.externalWebId &&
this.userAccount.webId !== this.userAccount.externalWebId &&
this.userAccount.externalWebId.length > 1) {
let rc = WebIdTls.getRequestCertificate(this.req)
if (rc.certificate) {
let cert = rc.certificate
let uris = getUris(cert)
if (uris.length > 0) {
this.userAccount.tlsCertificate = cert
this.userAccount.tlsCertificateWebid = uris[0]
this.userAccount.tlsCertificateModulus = cert.modulus
this.userAccount.tlsCertificateExponent = parseInt(cert.exponent)
}
}
}
function getUris (certificate) {
var uris = []
if (certificate && certificate.subjectaltname) {
certificate
.subjectaltname
.replace(/URI:([^, ]+)/g, function (match, uri) {
return uris.push(uri)
})
}
return uris
}
}
/**
* Factory method, creates an appropriate CreateAccountRequest subclass from
* an HTTP request (browser form submit), depending on the authn method.
*
* @param req
* @param res
*
* @throws {Error} If required parameters are missing (via
* `userAccountFrom()`), or it encounters an unsupported authentication
* scheme.
*
* @return {CreateOidcAccountRequest|CreateTlsAccountRequest}
*/
static fromParams (req, res) {
const options = AuthRequest.requestOptions(req, res)
const locals = req.app.locals
const authMethod = locals.authMethod
const accountManager = locals.accountManager
const body = req.body || {}
if (body.username) {
options.username = body.username.toLowerCase()
body.webId = accountManager.accountWebIdFor(body.username)
options.userAccount = accountManager.userAccountFrom(body)
}
options.enforceToc = locals.enforceToc
options.tocUri = locals.tocUri
options.disablePasswordChecks = locals.disablePasswordChecks
switch (authMethod) {
case 'oidc':
options.password = body.password
return new CreateOidcAccountRequest(options)
case 'tls':
options.spkac = body.spkac
return new CreateTlsAccountRequest(options)
default:
throw new TypeError('Unsupported authentication scheme')
}
}
static async post (req, res) {
const request = CreateAccountRequest.fromParams(req, res)
try {
request.validate()
await request.createAccount()
} catch (error) {
request.error(error, req.body)
}
}
/**??*WAS
renegotiate doesn't supported by TLS1.3
static async post (req, res) {
let request = null
const connection = req.connection
try {
await Promise.resolve()
.then(() => {
return new Promise(function (resolve, reject) {
// Typically, certificates for WebID-TLS are not signed or self-signed,
// and would hence be rejected by Node.js for security reasons.
// However, since WebID-TLS instead dereferences the profile URL to validate ownership,
// we can safely skip the security check.
connection.renegotiate({ requestCert: true, rejectUnauthorized: false }, (error) => {
request = CreateAccountRequest.fromParams(req, res)
if (error) {
debug('Error renegotiating TLS:', error)
return reject(error)
}
resolve()
})
})
})
request.validate()
await request.createAccount()
} catch (error) {
request.error(error, req.body)
}
}
***/
static get (req, res) {
const request = CreateAccountRequest.fromParams(req, res)
return Promise.resolve()
.then(() => request.renderForm())
.catch(error => request.error(error))
}
/**
* Renders the Register form
*/
renderForm (error, data = {}) {
const authMethod = this.accountManager.authMethod
const params = Object.assign({}, this.authQueryParams, {
enforceToc: this.enforceToc,
loginUrl: this.loginUrl(),
multiuser: this.accountManager.multiuser,
registerDisabled: authMethod === 'tls',
returnToUrl: this.returnToUrl,
authTls: authMethod === 'tls',
tocUri: this.tocUri,
disablePasswordChecks: this.disablePasswordChecks,
username: data.username,
name: data.name,
email: data.email,
externalWebId: data.externalWebId,
acceptToc: data.acceptToc,
connectExternalWebId: data.connectExternalWebId
})
if (error) {
params.error = error.message
this.response.status(error.statusCode || 401)
}
if (data) { params.webid = data.webid || '' }
if (authMethod === 'tls' && data) {
if (data.name) {
params.name = data.name
} else if (data.certificate && data.certificate.subject) {
params.name = data.certificate.subject.CN
}
}
this.response.render('account/register', params)
}
/**
* Creates an account for a given user (from a POST to `/api/accounts/new`)
*
* @throws {Error} If errors were encountering while validating the username.
*
* @return {Promise<UserAccount>} Resolves with newly created account instance
*/
async createAccount () {
const userAccount = this.userAccount
const accountManager = this.accountManager
if (userAccount.externalWebId) {
const error = new Error('Linked users not currently supported, sorry (external WebID without TLS?)')
error.statusCode = 400
throw error
}
this.cancelIfUsernameInvalid(userAccount)
this.cancelIfBlacklistedUsername(userAccount)
await this.cancelIfAccountExists(userAccount)
await this.createAccountStorage(userAccount)
await this.saveCredentialsFor(userAccount)
this.saveCertificateFor(userAccount)
this.resetUserSession(userAccount)
await this.sendResponse(userAccount)
// 'return' not used deliberately, no need to block and wait for email
if (userAccount && userAccount.email) {
debug('Sending Welcome email')
accountManager.sendWelcomeEmail(userAccount)
}
return userAccount
}
saveCertificateFor (userAccount) {
let certificate = null
if (this.certPEM && this.certPEM.length > 0) {
let cert = pki.certificateFromPem(this.certPEM)
if (cert) {
let webId
let ext = cert.getExtension('subjectAltName')
if (ext !== null && ext.altNames) {
for (var i = 0; i < ext.altNames.length; ++i) {
let altName = ext.altNames[i]
if (altName.type === 6) {
webId = altName.value
break
}
}
}
if (webId && webId === userAccount.webId) {
try {
let profileUri = webId.split('#')[0]
let keyUri = profileUri + '#key-' + cert.validity.notBefore.getTime()
let CN = cert.subject.getField('CN')
let commonName = (CN && CN.value) ? CN.value : this.username
let exponent = cert.publicKey.e.toString(10)
let modulus = cert.publicKey.n.toString(16).toLowerCase()
let YMD = cert.validity.notBefore.toISOString().substring(0, 10).replace(/-/g, '_')
let fname = 'cert_' + YMD + '_' + cert.validity.notBefore.getTime() + '.p12'
let rootUrl = userAccount.accountUri
let ldp = this.req.app.locals.ldp
let rm = new ResourceMapper(
{
rootUrl,
rootPath: ldp.root,
includeHost: ldp.multiuser
})
let path = rm.getFullPath(rootUrl + '/profile/' + fname)
certificate = {
certificate: cert,
date: cert.validity.notBefore,
modulus,
exponent,
commonName,
webId,
keyUri,
pathP12: path
}
} catch (err) {
err.status = 400
err.message = 'Error adding certificate to profile: ' + err.message
throw err
}
this.accountManager.addCertKeyToProfile(certificate, userAccount)
.catch(err => {
debug('Error adding certificate to profile: ' + err.message)
})
.then(() => {
if (certificate && this.certPKCS12 && this.certPKCS12.length > 1) {
let fd = fs.openSync(certificate.pathP12, 'w')
fs.writeSync(fd, new Buffer(this.certPKCS12, 'base64'))
}
})
}
}
}
return userAccount
}
resetUserSession (userAccount) {
this.req.session.userId = null
this.req.session.subject = {}
return userAccount
}
/**
* Rejects with an error if an account already exists, otherwise simply
* resolves with the account.
*
* @param userAccount {UserAccount} Instance of the account to be created
*
* @return {Promise<UserAccount>} Chainable
*/
cancelIfAccountExists (userAccount) {
const accountManager = this.accountManager
return accountManager.accountExists(userAccount.username)
.then(exists => {
if (exists) {
debug(`Canceling account creation, ${userAccount.webId} already exists`)
const error = new Error('Account already exists')
error.status = 400
throw error
}
// Account does not exist, proceed
return userAccount
})
}
/**
* Creates the root storage folder, initializes default containers and
* resources for the new account.
*
* @param userAccount {UserAccount} Instance of the account to be created
*
* @throws {Error} If errors were encountering while creating new account
* resources.
*
* @return {Promise<UserAccount>} Chainable
*/
createAccountStorage (userAccount) {
return this.accountManager.createAccountFor(userAccount)
.catch(error => {
error.message = 'Error creating account storage: ' + error.message
throw error
})
.then(() => {
debug('Account storage resources created')
return userAccount
})
}
/**
* Check if a username is a valid slug.
*
* @param userAccount {UserAccount} Instance of the account to be created
*
* @throws {Error} If errors were encountering while validating the
* username.
*
* @return {UserAccount} Chainable
*/
cancelIfUsernameInvalid (userAccount) {
if (!userAccount.username || !isValidUsername(userAccount.username)) {
debug('Invalid username ' + userAccount.username)
const error = new Error('Invalid username (contains invalid characters)')
error.status = 400
throw error
}
return userAccount
}
/**
* Check if a username is a valid slug.
*
* @param userAccount {UserAccount} Instance of the account to be created
*
* @throws {Error} If username is blacklisted
*
* @return {UserAccount} Chainable
*/
cancelIfBlacklistedUsername (userAccount) {
const validUsername = blacklistService.validate(userAccount.username)
if (!validUsername) {
debug('Invalid username ' + userAccount.username)
const error = new Error('Invalid username (username is blacklisted)')
error.status = 400
throw error
}
return userAccount
}
} |
JavaScript | class CreateOidcAccountRequest extends CreateAccountRequest {
/**
* @constructor
*
* @param [options={}] {Object} See `CreateAccountRequest` constructor docstring
* @param [options.password] {string} Password, as entered by the user at signup
* @param [options.acceptToc] {boolean} Whether or not user has accepted T&C
*/
constructor (options) {
super(options)
this.password = options.password
}
/**
* Validates the Login request (makes sure required parameters are present),
* and throws an error if not.
*
* @throws {Error} If missing required params
*/
validate () {
let error
if (!this.username) {
error = new Error('Username required')
error.statusCode = 400
throw error
}
if (!this.password) {
error = new Error('Password required')
error.statusCode = 400
throw error
}
if (this.enforceToc && !this.acceptToc) {
error = new Error('Accepting Terms & Conditions is required for this service')
error.statusCode = 400
throw error
}
}
/**
* Generate salted password hash, etc.
*
* @param userAccount {UserAccount}
*
* @return {Promise<null|Graph>}
*/
saveCredentialsFor (userAccount) {
return this.userStore.createUser(userAccount, this.password)
.then(() => {
debug('User credentials stored')
return userAccount
})
}
/**
* Generate the response for the account creation
*
* @param userAccount {UserAccount}
*
* @return {UserAccount}
*/
sendResponse (userAccount) {
const redirectUrl = this.returnToUrl || userAccount.podUri
this.response.redirect(redirectUrl)
return userAccount
}
} |
JavaScript | class CreateTlsAccountRequest extends CreateAccountRequest {
/**
* @constructor
*
* @param [options={}] {Object} See `CreateAccountRequest` constructor docstring
* @param [options.spkac] {string}
* @param [options.acceptToc] {boolean} Whether or not user has accepted T&C
*/
constructor (options) {
super(options)
this.spkac = options.spkac
this.certificate = null
}
/**
* Validates the Signup request (makes sure required parameters are present),
* and throws an error if not.
*
* @throws {Error} If missing required params
*/
validate () {
let error
if (!this.username) {
error = new Error('Username required')
error.statusCode = 400
throw error
}
if (this.userAccount && this.userAccount.externalWebId.length === 0) {
error = new Error('External WebId required')
error.statusCode = 400
throw error
}
if (this.enforceToc && !this.acceptToc) {
error = new Error('Accepting Terms & Conditions is required for this service')
error.statusCode = 400
throw error
}
}
/**
* Generates a new X.509v3 RSA certificate (if `spkac` was passed in) and
* adds it to the user account. Used for storage in an agent's WebID
* Profile, for WebID-TLS authentication.
*
* @param userAccount {UserAccount}
* @param userAccount.webId {string} An agent's WebID URI
*
* @throws {Error} HTTP 400 error if errors were encountering during
* certificate generation.
*
* @return {Promise<UserAccount>} Chainable
*/
generateTlsCertificate (userAccount) {
if (!this.spkac) {
debug('Missing spkac param, not generating cert during account creation')
return Promise.resolve(userAccount)
}
return Promise.resolve()
.then(() => {
const host = this.accountManager.host
return WebIdTlsCertificate.fromSpkacPost(this.spkac, userAccount, host)
.generateCertificate()
})
.catch(err => {
err.status = 400
err.message = 'Error generating a certificate: ' + err.message
throw err
})
.then(certificate => {
debug('Generated a WebID-TLS certificate as part of account creation')
this.certificate = certificate
return userAccount
})
}
/**
* Generates a WebID-TLS certificate and saves it to the user's profile
* graph.
*
* @param userAccount {UserAccount}
*
* @return {Promise<UserAccount>} Chainable
*/
saveCredentialsFor (userAccount) {
return this.generateTlsCertificate(userAccount)
.then(userAccount => {
if (this.certificate) {
return this.accountManager
.addCertKeyToProfile(this.certificate, userAccount)
.then(() => {
debug('Saved generated WebID-TLS certificate to profile')
})
} else {
debug('No certificate generated, no need to save to profile')
}
})
.then(() => {
return userAccount
})
}
/**
* Writes the generated TLS certificate to the http Response object.
*
* @param userAccount {UserAccount}
*
* @return {UserAccount} Chainable
*/
sendResponse (userAccount) {
const res = this.response
res.set('User', userAccount.webId)
res.status(200)
if (this.certificate) {
res.set('Content-Type', 'application/x-x509-user-cert')
res.send(this.certificate.toDER())
} else {
res.end()
}
return userAccount
}
} |
JavaScript | class CSVFormatter extends AbstractLogFormatter {
/**
* @private
*/
/**
*
* Constructor for this formatter. Never called directly, but called by AwesomeLog
* when `Log.start()` is called.
*
* @param {Object} options
*/
constructor(options) {
super(options);
}
/**
* @private
*/
/**
*
* Given the log entry object, format it to our output string.
*
* @param {Object} logentry
* @return {*}
*/
format(logentry) {
let s = [];
s.push(this.formatValue(logentry.timestamp||Date.now()));
s.push(this.formatValue(logentry.level||""));
s.push(this.formatValue(logentry.pid||"????"));
s.push(this.formatValue(logentry.system||""));
s.push(this.formatValue(logentry.text||""));
if (logentry.args && logentry.args.length>0) s = s.concat(logentry.args.map((arg)=>{
return this.formatValue(arg);
}));
s.concat(Object.keys(logentry).map((key)=>{
if (key==="timestamp" || key==="level" || key==="pid" || key==="system" || key==="text" || key==="args") return;
return this.formatValue(logentry[key]);
}));
return s.join(",");
}
/**
* @private
*/
formatValue(value) {
if (value===null || value===undefined) return "";
else if (typeof value==="string") return "\""+value+"\"";
else if (typeof value==="number") return ""+value;
else if (typeof value==="boolean") return ""+value;
else if (value instanceof Date) return ""+value.getTime();
else if (value instanceof Array) return "\""+this.formatCSVJSON(value)+"\"";
else if (value instanceof Object) return "\""+this.formatCSVJSON(value)+"\"";
else return "\""+value.toString()+"\"";
}
/**
* @private
*/
formatCSVJSON(obj) {
let json = JSON.stringify(obj);
json = json.replace(/"/g,'\\"');
return json;
}
} |
JavaScript | class TimelineModule extends TimelineBaseModule {
/**
* @memberof Vevet.TimelineModule
* @typedef {object} Properties
* @augments Vevet.TimelineBaseModule.Properties
* @augments Vevet.TimelineModule.Settings
*
* @property {boolean} [destroyOnEnd=false] - Destroy the timeline when it ends.
*/
/**
* @alias Vevet.TimelineModule
* @param {Vevet.TimelineModule.Properties} [data]
*/
constructor(data) {
super(data);
}
// Extra Constructor
_extra() {
super._extra();
/**
* @description If animation is playing.
* @protected
* @member {boolean}
*/
this._playing = false;
/**
* @description If animation is paused.
* @protected
* @member {boolean}
*/
this._paused = false;
/**
* @description If animation is stopped.
* @protected
* @member {boolean}
*/
this._stopped = false;
/**
* @description If animation is reversed.
* @protected
* @member {boolean}
*/
this._reversed = false;
/**
* @description Animation Frame.
* @protected
* @member {number|null}
*/
this._frame = null;
}
/**
* @description Create tickers variables.
* @protected
*/
_tickers() {
super._tickers();
/**
* @protected
* @member {number}
*/
this._ticker = 0;
/**
* @protected
* @member {number}
*/
this._lastFrame = 0;
}
/**
* @memberof Vevet.TimelineModule
* @typedef {object} Settings
* @augments Vevet.TimelineBaseModule.Settings
* @property {number} [duration=750] - Duration of the animation.
* @property {boolean} [autoDuration=false] - Defines if the duration can be changed according to the animation scope.
*/
/**
* @description Get default settings.
* @readonly
* @type {Vevet.TimelineModule.Settings}
*/
get defaultSettings() {
return merge(super.defaultSettings, {
duration: 750,
autoDuration: false
});
}
/**
* @description Check if the timeline is already playing.
* @readonly
* @default false
* @type {boolean}
*/
get playing() {
return this._playing;
}
/**
* @description Check if the timeline is reversed.
* @readonly
* @default false
* @type {boolean}
*/
get reversed() {
return this._reversed;
}
/**
* @memberof Vevet.TimelineModule
* @typedef {object} Data
* @augments Vevet.TimelineBaseModule.Data
* @property {number} duration - Duration of the animation.
*/
/**
* @description Get animation data.
* @readonly
* @type {Vevet.TimelineModule.Data}
*/
get data() {
return merge(super.data, {
duration: this._settings.duration
});
}
/**
* @description Start animation. Launch requestAnimationFrame.
* Common for {@linkcode Vevet.TimelineModule#play} & {@linkcode Vevet.TimelineModule#resume}.
* @protected
*/
_start() {
// change values
this._lastFrame = Date.now();
// change states
this._playing = true;
this._paused = false;
this._stopped = false;
// launch frame
this._frame = window.requestAnimationFrame(this._animate.bind(this));
}
/**
* @description Stop animation and set progress to zero.
* Common for {@linkcode Vevet.TimelineModule#stop} & {@linkcode Vevet.TimelineModule#pause}.
* @protected
*/
_stop() {
this._playing = false;
if (this._frame != null) {
cancelAnimationFrame(this._frame);
this._frame = null;
}
}
/**
* @description Start the timeline.
* @param {Vevet.TimelineModule.Settings} data - Settings of the animation.
* @returns {Vevet.TimelineModule} Returns 'this'.
*/
play(data = this._settings) {
// check if already playing
if (this._playing) {
return this;
}
// check if paused
if (this._paused) {
return this.resume();
}
// reset tickers
if (!this._reversed) {
this._tickers();
}
// get properties
this._settings = merge(this.defaultSettings, data);
let settings = this._settings;
// get scope line
let scope = settings.scope,
scopeLine = Math.abs(scope[0] - scope[1]);
// change duration according to the scope
if (settings.autoDuration) {
settings.duration *= scopeLine;
}
// launch animation
this._start();
// launch callback
this.lbt('play', this.data);
return this;
}
/**
* @description Pause animation.
* @returns {Vevet.TimelineModule} Returns 'this'.
*/
pause() {
// check if not playing
if (!this._playing) {
return this;
}
// pause
this._paused = true;
this._stop();
// launch callback
this.lbt("pause", this.data);
return this;
}
/**
* @description Resume animation after it is paused.
* @returns {Vevet.TimelineModule} Returns 'this'.
*/
resume() {
// check if playing
if (this._playing) {
return this;
}
// check if not paused
if (!this._paused) {
return this;
}
// check if not ended
if (this._absolute === 1) {
return this;
}
// launch animation
this._start();
// launch callback
this.lbt("resume", this.data);
return this;
}
/**
* @description Stop animation and set progress to zero.
* @returns {Vevet.TimelineModule} Returns 'this'.
*/
stop() {
// reset states & stop the animation
this._stopReset();
this._reversed = false;
// reset tickers
this._tickers();
this._stopped = true;
// launch callback
this.lbt("stop", this.data);
return this;
}
/**
* @description Stop animation and set progress to zero.
* @protected
*/
_stopReset() {
this._paused = false;
this._stopped = false;
this._stop();
}
/**
* @description Reverse animation. This method does'nt start the animation line.
* @returns {Vevet.TimelineModule} Returns 'this'.
*/
reverse() {
if (this._reversed) {
this._reversed = false;
}
else {
this._reversed = true;
}
// launch callback
this.lbt('reverse', this.data);
return this;
}
/**
* @description Animation itself.
* @protected
*/
_animate() {
let now = Date.now(),
frameDuration = now - this._lastFrame;
// iterate ticker
if (!this._reversed) {
this._ticker += frameDuration;
}
else {
this._ticker -= frameDuration;
}
// get progress
let progress = this._ticker / this._settings.duration;
if (progress > 1) {
progress = 1;
}
if (progress < 0) {
progress = 0;
}
// calculate values
this.calc(progress);
// if need to stop
let stop = false,
end = false;
if (!this._reversed) {
if (this._progress === 1) {
stop = true;
end = true;
}
}
else {
if (this._progress === 0) {
stop = true;
end = true;
}
}
// stop animation
if (stop) {
this._stopReset();
}
// end callback
if (end) {
this.lbt('end');
}
// destroy & stop
if (stop) {
// destroy the class
if (this._prop.destroyOnEnd) {
this.destroy();
}
return;
}
// frame difference, set last frame time
this._lastFrame = now;
// frame
this._frame = window.requestAnimationFrame(this._animate.bind(this));
}
/**
* @description Destroy the class.
*/
destroy() {
super.destroy();
// destroy animation frame
if (this._frame != null) {
cancelAnimationFrame(this._frame);
this._frame = null;
}
}
} |
JavaScript | class Words {
/**
* Capitalizes the given word, conerting the first charater to upper case and the rest of the characters to lower
* case.
*
* @param {String} word - The word to capitalize.
* @returns {String} The capitalized word.
*/
static capitalized (word) {
if (word == null || word.length === 0) {
return word
}
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
}
} |
JavaScript | class SuggestModel extends BaseModel {
constructor() {
super();
this.store = SuggestStore;
this.service = SuggestService;
this.registerIOC('SuggestModel');
}
wineName(text) {
return this.service.wineName(text);
}
country(prefix) {
return this.service.country(prefix);
}
async pageSection(pageId) {
var results = {}, item;
for( var key in MarksStore.data.byId ) {
item = MarksStore.data.byId[key];
if( item.data && item.data.section && item.pageId === pageId ) {
results[item.data.section] = 1;
}
}
return Object.keys(results);
}
} |
JavaScript | class SendEvent {
constructor({ eventRecordsGateway, testing = false }) {
const processQueue = initQueueProcessor(eventRecordsGateway, testing);
if (testing) {
this.processQueue = processQueue;
}
}
async execute(requestModel) {
let { eventIDs, date } = requestModel;
if (typeof eventIDs === 'string') {
const values = eventIDs.split('.');
eventIDs = values.reduce((accumulator, value, i) => {
accumulator.push(`${values.slice(0, i + 1).join('.')}`);
return accumulator;
}, []);
}
// console.log('sendEvent: ' + JSON.stringify(eventIDs, null, 2));
// Fall back to current date if no date was passed in.
date = date || new Date();
queue.push({ eventIDs, date });
return 'success';
}
} |
JavaScript | class UserHelper {
async userExists(body) {
try {
let where = {
email: body.email,
};
if (body.verification_code) {
where.verification_code = body.verification_code;
}
let user = await db.find("users", where, {});
console.log("user", user);
return user;
} catch (error) {
return promise.reject(error);
}
}
insertUser(body, verification_code, password, file) {
try {
let user = {
first_name: body.first_name,
last_name: body.last_name,
email: body.email,
phone_number: body.phone_number,
profileImage: file.originalname,
verification_code: verification_code,
is_verified: 0,
is_activated: 1,
created_date: common.getCurrentTimeStamp(),
modified_date: common.getCurrentTimeStamp(),
};
if (password) {
user.salt = password.salt;
user.hash = password.hash;
}
return db.insertOne("users", user);
} catch (error) {
return promise.reject(error);
}
}
async verificationEmail(body) {
try {
let where = {
email: body.email,
verification_code: body.verification_code,
};
let update = {
is_verified: 1,
verification_code: "",
};
return db.updateOne("users", where, update, {}, 0, "");
} catch (error) {
return promise.reject(error);
}
}
async getUserProfile(user_id) {
try {
var where = { is_verified: 1, _id: db.getMongoObjectId(user_id) };
var projection = {
_id: 1,
first_name: 1,
last_name: 1,
email: 1,
phone_number: 1,
profileImage: 1,
is_activated:1
};
let result = await db.find("users", where, projection);
return result;
} catch (error) {
console.log("erro in helper", error);
return promise.reject("SOMETHING_WENT_WRONG");
}
}
async updateProfile(body,file, user_id) {
try {
let update = {
first_name: body.first_name,
last_name: body.last_name,
phone_number: body.phone_number,
is_verified: 1,
is_activated:1,
modified_date: common.getCurrentTimeStamp(),
};
if(file){
update.profileImage=file.originalname
}
let where = {
_id: db.getMongoObjectId(user_id),
};
return db.updateOne("users", where, update, {}, 0, "");
} catch (error) {
return promise.reject(error);
}
}
} |
JavaScript | class Newsletters {
/**
* @param {object} req - The newsletter request object
* @param {object} res - The newsletter response object
* @returns {object} Success message
*/
static async createNewsletter(req, res) {
try {
const { error } = newsletterValidation(req.body);
if (error) {
util.setError(400, "Validation Error", error.message);
return util.send(res);
}
const { title, message } = req.body;
const newsletterDetails = { title, message };
const newsletters = await Newsletter.createNewsletter(newsletterDetails);
const getSubscribers = await Subscriber.subscribers();
if (getSubscribers) {
getSubscribers.forEach(async element => {
await sendGrid.sendNewsletter(element.email, element.firstName, title, message);
await Subscriber.receivedMail(element.email, newsletterDetails.title);
await Newsletter.updateNewsletterId(element.id, newsletters.dataValues.id);
});
}
if (newsletters) {
return res.status(201).json({ status: 201, message: "Newsletter created!", data: newsletters });
}
} catch (error) {
return res.status(500).json({ status: 500, error: "Server Error" });
}
}
} |
JavaScript | class GymScene extends Scene {
constructor(pixiRef, controller) {
super(pixiRef, controller);
// The workouts that will be done in this stage
this.workouts; // {task: "", freq: 0}
// The reps for the workout. Used for the workout progress bar
this.currentReps = 0;
// When the gym activity is done, callback will be run, after CALLBACKDELAY.
this.doneCallback;
// Current Workout index
this.workoutIndex;
// Prev rep, to keep track of payload reps.
this.prevRep;
// Whether the player is currently resting.
this.resting = false;
}
startNewWorkout(workouts) {
// TODO: This can be inside transition callback
// Set a new workout routine that will be done in this stage.
// This should reset every value, so that the gym cycle can begin anew.
this.workouts = workouts;
this.workoutIndex = -1;
this.currentReps = 0;
this.prevRep = 0;
// Set resting to be true.
this.resting = true;
// Set the first workout in x seconds.
// Show the countdown too.
this._restCountdown(20);
// Randomize enemy to spawn.
this.fightUI.changeEnemy();
this._updateScores();
this._updatePose();
// this._addOne(); // Testing Purposes
}
_addOneRep() {
// Only adds one rep if there is still workout to do.
if (this.resting || this.workoutIndex >= this.workouts.length) return;
const maxRep = this.workouts[this.workoutIndex].freq;
// Here, we decide whether all the reps have been done.
if (this.currentReps < maxRep) {
// Does rep animation
this.fightMan.repOnce();
// Increase the progress bar
this.currentReps++;
this.fightUI.workoutP = this.currentReps / maxRep;
this.fightUI.workoutCounter.text = maxRep - this.currentReps;
this.fightUI._redrawWorkoutBar();
}
this.repSound.play();
}
_lastRep() {
// Will be called if in the last rep.
// When this is the last rep, enter resting mode and set timeout
// When animation finished to rest.
this.resting = true;
let callback;
// Check whether this is the last workout.
if (this.workoutIndex < this.workouts.length - 1) {
callback = () => {
this._restCountdown(RESTSECONDS);
};
} else {
callback = () => {
this.workoutIndex++;
this._updateScores();
this._updatePose();
};
}
// Wait for the duration of the last workout, and additional 500ms.
setTimeout(
callback,
this.fightMan.fightMan.currentSprite.state.getCurrent(0).animation
.duration *
1000 +
500
);
}
_updateScores() {
// Updates some of the UI elements in the game
// (Health, Workout text, Counter)
// FIX
if (this.workoutIndex < this.workouts.length) {
// Update the texts
this.fightUI.workoutCounter.text = this.workouts[
this.workoutIndex
].freq;
this.fightUI.setWorkoutText(this.workouts[this.workoutIndex].task);
this.fightUI.workoutP = 0;
this.fightUI._redrawWorkoutBar();
this.fightUI.updateInstruction(
this.workouts[this.workoutIndex].task
);
} else {
// Obliterate the enemy
this.fightUI.flyEnemy();
// When all the workouts is done.
this.fightUI.workoutCounter.text = "✅";
this.fightUI.setWorkoutText("VICTORY!");
this.fightUI.workoutP = 1;
this.fightUI._redrawWorkoutBar();
// Do callback if done.
if (this.doneCallback !== undefined)
setTimeout(this.doneCallback, CALLBACKDELAY);
}
// Update enemy health
this.fightUI.enemyHealthP =
(this.workouts.length - this.workoutIndex) / this.workouts.length;
this.fightUI._redrawEnemyHealth();
}
_updatePose() {
// Update pose depending on the current workout index
if (this.workoutIndex < this.workouts.length) {
this.fightMan.fightMan.changePose(
this.workouts[this.workoutIndex].task,
false
);
} else {
this.fightMan.fightMan.changePose("Idle", true);
}
}
_restCountdown(seconds) {
// Create a countdown object that will callback
// The next workout event.
// This will be called after the user have completed an exercise
// and there is still next exercise.
this.prevRep = 0;
this.currentReps = 0;
this.restCountdown.setSeconds(seconds);
this.restCountdown.start();
this.resting = true;
// Damage the enemy here, do animations.
this.fightUI.enemy.state.setAnimation(0, "fly", false);
this.fightUI.enemy.state.addAnimation(0, "idle", true, 0);
// Summon the buttons
this.addObj(this.skipButton);
this.addObj(this.delayButton);
// Add next workout text
const textRef = this.fightUI.workoutText;
textRef.text = "Next up:\n" + textRef.text;
// Update scores
this.workoutIndex++;
this._updateScores();
this.addObj(this.restCountdown);
// Set the person animation to be idle.
this.fightMan.fightMan.changePose("Idle", true);
// Display the instruction screen.
this.fightUI.setDisplayInstruction(true);
// Play sound.
this.nextWorkoutSound.play();
}
_goToNextWorkout() {
// This event will be run after the resting countdown have been completed.
// After the countdown has completed, jump to the next workout.
this.delObj(this.restCountdown);
this.resting = false;
// Delete the buttons
this.delObj(this.skipButton);
this.delObj(this.delayButton);
// If next exists in the text, then delete it.
const textRef = this.fightUI.workoutText;
if (textRef.text.includes("\n")) {
textRef.text = textRef.text.split("\n")[1];
}
peer.connection.sendData({ status: "startnext" });
// Change the pose
this._updatePose();
// Remove the display instruction
this.fightUI.setDisplayInstruction(false);
// Play sound.
this.nextWorkoutSound.play();
}
_addOne() {
// TEST: Testing Purposes only
this._addOneRep();
console.log("Add one.");
setTimeout(this._addOne.bind(this), 2000);
}
dataListener(payload) {
// If a payload data that corresponds to the current workout is received, then increase rep by one.
if (
"exerciseType" in payload &&
this.workoutIndex < this.workouts.length
) {
if (
payload.exerciseType == this.workouts[this.workoutIndex].task &&
(payload.status == "mid" || payload.status == "end") &&
this.prevRep < payload.repAmount
) {
const repAmount = payload.repAmount - this.prevRep;
this.prevRep = payload.repAmount;
for (var i = 0; i < repAmount; i++) this._addOneRep();
if (payload.status == "end") {
this._lastRep();
}
}
}
}
switchCallback() {}
setup(pixiRef) {
this.floatState = false; // The state whether to do the float down animation.
this.lerpFunction = (x) => 1 - Math.pow(1 - x, 3); // Interpolation function to use. (Ease out lerp)
this.initYOffset = pixiRef.app.screen.height; // Offset to place the objects in.
this.floatCounter = 0;
this.floatDuration = 5; // The amount of duration for floatDown.
this.fightFloor = new FightFloor(pixiRef);
this.fightMan = new FightMan(pixiRef);
this.fightUI = new FightUI(pixiRef);
this.restCountdown = new Countdown(
pixiRef,
null,
this._goToNextWorkout.bind(this)
);
// Set the position of the countdown.
this.restCountdown.yPos = () => 100;
this.infoButton = new Button(
pixiRef,
"help_outline",
() => {
this.fightUI.setDisplayInstruction(
!this.fightUI.displayInstruction
);
},
() => 32,
() => 96 + 16,
64,
0x00aaaa
);
// Skip button.
this.skipButton = new Button(
pixiRef,
"skip_next",
() => {
this.restCountdown.counter = 1;
},
() => 32,
() => 160 + 32,
64,
0x00aaaa
);
// Delay 5 second button
this.delayButton = new Button(
pixiRef,
"forward_5",
() => {
this.restCountdown.counter += 5;
},
() => 32,
() => 224 + 48,
64,
0x00aaaa
);
this.addObj(this.fightFloor);
this.addObj(this.fightMan);
this.addObj(this.fightUI);
this.addObj(this.infoButton);
this.nextWorkoutSound = pixiRef.resources.nextsound.sound;
this.repSound = pixiRef.resources.repsound.sound;
}
floatDown() {
// Function to pan down to the game, starting it.
this.floatState = true;
this.setAbove();
}
setAbove() {
// Function to set every object to be at bottom.
this.fightFloor.mainContainer.y += this.initYOffset;
this.fightMan.mainContainer.y += this.initYOffset;
this.fightUI.enemyCont.y += this.initYOffset;
}
loopCode(delta) {
if (this.floatState) {
const deltaS = delta / 1000;
// Calculate offset
const curOffset =
this.initYOffset *
(this.lerpFunction(
(this.floatCounter + deltaS) / this.floatDuration
) -
this.lerpFunction(this.floatCounter / this.floatDuration));
// Increase the position
this.fightFloor.mainContainer.y -= curOffset;
this.fightMan.mainContainer.y -= curOffset;
this.fightUI.enemyCont.y -= curOffset;
this.fightMan.manShadow.uniforms.floorY =
this.fightMan.mainContainer.y +
this.fightMan.fightMan.fightMan.y;
this.fightUI.enemyShadow.uniforms.floorY =
this.fightUI.enemyCont.y +
(this.fightUI.enemy.y + this.fightUI.enemyPosOffset.y);
// Increase the duration.
this.floatCounter += deltaS;
// Stop the animation once it reaches floatDuration.
// and send a trigger that the animation is completed.
if (this.floatCounter > this.floatDuration) {
this.floatState = false;
this.animationDone();
}
}
}
animationDone() {
this.onResize();
}
start() {}
onResizeCode() {}
pauseCallback(isPaused) {
this.restCountdown.paused = isPaused;
}
tapCallback() {}
} |
JavaScript | class AutoScaleModifier extends Modifier {
@service autoScaleImage;
get width() {
return this.args.named.width || 0;
}
get height() {
return this.args.named.height || 0;
}
get imageSrc() {
return this.args.named.imageSrc || '';
}
get fallbackSrc() {
return this.args.named.fallbackSrc || '';
}
didReceiveArguments() {
this.loadImage.perform();
}
didUpdateArguments() {
this.loadImage.perform();
}
@task *loadImage() {
this.loaded = false;
let width = parseInt(this.width);
let height = parseInt(this.height);
const src = this.imageSrc;
const fallbackSrc = this.fallbackSrc;
const result = yield this.autoScaleImage
.get('scaleImage')
.perform(src, width, height, fallbackSrc);
this.element.src = result.imageSrc;
this.element.style.width = `${result.size.width}px`;
this.element.style.height = `${result.size.height}px`;
}
} |
JavaScript | class Term extends Component {
async handleChange(event) {
const term = event.target.value;
const type = this.props.type;
const username = getCookieValue('user');
const updatedTop = await getUserEntry(username, type, term);
this.props.updater(type, updatedTop);
}
render() {
return (
<Select onChange={this.handleChange.bind(this)}>
<option value="short_term">30 days</option>
<option value="medium_term">6 months</option>
<option value="long_term">All Time</option>
</Select>
);
}
} |
JavaScript | class Observer {
/* istanbul ignore next */
constructor ({
seanceOrigin,
created,
destroyed
} = {}) {
this.messageId = generateID();
this.uuid = generateUUID();
this.seanceOrigin = seanceOrigin;
this.proxyEl = null;
this.onCreated = created;
this.beforeDestroy = destroyed;
this.responses = new Map();
this.preflight = null;
this.onAcknowledge = function () {
this.preflight = TIMERS.CONN_FULFILLED;
};
}
/**
* @summary Initialize the observer instance;
* creates a new iframe DOM node as a proxy for communicating with the observable
*/
init () {
this.renderFrame();
this.poll();
window.addEventListener(
'message',
this.recv.bind(this)
);
window.addEventListener(
'load',
this.mount.bind(this)
);
window.addEventListener(
'beforeunload',
this.unMount.bind(this)
);
// from base instance, expose initializer `sequence`
return this;
}
/**
* @summary Open a proxy to the Observable instance by appending its origin as an iframe on the Observer's document
*/
renderFrame () {
const frame = window.document.createElement('iframe');
// map base frame styles to set display to 'none' and other such obfuscators
for (const [key, value] of Object.entries(frameDefaults)) {
frame.style[key] = value;
}
window.document.body.appendChild(frame);
frame.src = this.seanceOrigin;
frame.id = this.uuid;
this.proxyEl = frame;
}
/**
* @summary Callback invoked on-mount; emits a `mount` type event, prompting the Observable to incorporate
* the calling Observer into its known origins mapping
*/
mount () {
this.emit(
EVENT_TYPES.MOUNT,
this.uuid,
/* istanbul ignore next */
x => x
);
this.create();
}
/**
* @summary Callback invoked on-unmount; emits an `unmount` type event, prompting the Observable to eject
* the calling Observer and remove from known origins mapping
*/
unMount () {
this.emit(
EVENT_TYPES.UNMOUNT,
this.uuid,
/* istanbul ignore next */
x => x
);
this.destroy();
}
/**
* @summary Callback invoked once the Observer has been initialized and the load event listener bound;
* further invokes the provided onCreated callback, or a noop if one was not provided
*/
create () {
this.onCreated(
this.uuid
);
}
/**
* @summary Callback invoked right before the Observer has unloaded;
* further invokes the provided beforeDestroy callback, or a noop if one was not provided
*/
destroy () {
this.beforeDestroy(
this.uuid
// TODO return state
);
// cleanup; remove the iframe node
this.proxyEl.parentNode.removeChild(this.proxyEl);
window.removeEventListener(
'message',
this.recv.bind(this)
);
window.removeEventListener(
'load',
this.mount.bind(this)
);
window.removeEventListener(
'beforeunload',
this.unMount.bind(this)
);
}
/**
* @summary Polling executor; polls the Observable at *n* ms interval, propagating ACK callback invocations;
* these invocations result in the toggling of the preflight flag
*/
poll () {
setInterval(() => {
this.emit(
EVENT_TYPES.SYN,
this.uuid,
this.onAcknowledge.bind(this)
);
}, TIMERS.CONN_INTERVAL);
}
/**
* @summary Invoked on-message; processes inbound messages from the Observable and their respective payloads;
* enforces CORS restrictions
* @param {(string|any)} message If valid, a serialized message received via `postMessage`
*/
recv (message) {
if (message.origin !== this.seanceOrigin || not(isString(message.data))) return;
const { id, error, result } = deserialize(message.data);
if (
not(notNullOrUndefined(id)) ||
(not(notNullOrUndefined(result)) && not(notNullOrUndefined(error)))
) return;
/* anticipated messages w/out ids */
// observable `unload` fired
if (id === IDENTIFIERS.DESTROY_ID && result === EVENT_TYPES.CLOSE) {
this.preflight = null;
return;
}
/* anticipated messages with corresponding ids */
if (!this.responses.has(id)) return;
// recv poll response
if (result === EVENT_TYPES.ACK) {
this.preflight = TIMERS.CONN_FULFILLED;
} else {
const cb = this.responses.get(id);
if (isFunction(cb)) (error, result);
}
this.responses.delete(id);
}
/**
* @summary Send a message to the Observable
* @param {string} type
* @param {object} payload
* @param {function} cb A callback to be invoked upon receipt of the message's corresponding response
*/
emit (type, payload, cb) {
// generate an id; the corresponding response from the Observable will utilize this
const id = this.messageId.next().value;
this.proxyEl.contentWindow.postMessage(
serialize({
sender: this.uuid,
id,
type,
payload
}), this.seanceOrigin);
this.responses.set(id, cb);
}
/* Public Interface */
/**
* @summary Resolves on confirmed connections to the Observable (and in kind rejects on unfulfilled connections);
* initialize a sequence of shared state changes
* @returns {Promise} A promise that resolves to the Observer's public interface
*/
sequence () {
const resolver = () => {
/* istanbul ignore else */
if (this.preflight === TIMERS.CONN_FULFILLED) return { ...this.publicApi() };
throw new Error(`Observable storage instance at ${this.seanceOrigin} cannot be reached`);
};
return retry(resolver, TIMERS.MAX_CONN_ATTEMPTS, TIMERS.CONN_INTERVAL);
}
/**
* @summary Retrieve an item or items from the storage adapter
* @param {array} keys An array of keys, each denoting the storage keys for which to retrieve values
* @param {function} cb A callback to be invoked upon receipt of the message's corresponding response
* @returns {object} The Observer's public interface
*/
get (keys, cb) {
// guards
mustBeArray(keys);
if (notNullOrUndefined(cb)) mustBeFunc(cb);
keys.forEach(mustBeStrOrNum);
// iface
this.emit(
QUERY_TYPES.GET,
keys,
cb
);
return this.publicApi();
}
/**
* @summary Set an item or items in the storage adapter
* @param {array} pairs An array of objects, each denoting the storage values and keys to which they will be set
* @param {function} cb A callback to be invoked upon receipt of the message's corresponding response
* @returns {object} The Observer's public interface
*/
set (pairs, cb) {
// guards
mustBeArray(pairs);
if (notNullOrUndefined(cb)) mustBeFunc(cb);
pairs.forEach(hasValidVals);
// iface
this.emit(
QUERY_TYPES.SET,
pairs,
cb
);
return this.publicApi();
}
/**
* @summary Delete an item or items from the storage adapter
* @param {array} keys An array of keys, each denoting the storage keys for which to delete values
* @param {function} cb A callback to be invoked upon receipt of the message's corresponding response
* @returns {object} The Observer's public interface
*/
delete (keys, cb) {
// guards
mustBeArray(keys);
if (notNullOrUndefined(cb)) mustBeFunc(cb);
// iface
this.emit(
QUERY_TYPES.DELETE,
keys,
cb
);
return this.publicApi();
}
publicApi () {
return {
get: this.get.bind(this),
set: this.set.bind(this),
delete: this.delete.bind(this)
};
}
} |
JavaScript | class Service {
/**
* @description Creates an instance of Service.
* @param {String} name service name
* @param {Object} [options] service options
* @memberof Service
*/
constructor(name, options) {
if (is.string(name) && is.not.empty(name)) this.name = name;
else throw new Error(`invalid service name: ${name}`);
this._options = Object.assign({}, options || {});
this._logger = pino(
Object.assign({ level: 'error' }, is.object(this._options.pino) ? this._options.pino : {}),
);
}
/**
* @description returns service name
* @returns String
* @memberof Service
*/
_name() {
return this.name;
}
/**
* @description executes service handler
* @param {String} name method name
* @param {Object} job payload
* @memberof Service
*/
async _run(job) {
if (is.not.object(job) || is.not.object(job.data)) throw new Error('invalid job');
const { _: method } = job.data;
if (is.not.string(method) || method.startsWith('_')) throw new Error('invalid method name');
else if (is.not.function(this[method])) throw new Error('invalid method');
else if (this[method].constructor.name !== 'AsyncFunction')
throw new Error('method must be an async function');
else return await this[method](job);
}
} |
JavaScript | class DtmfCollector {
constructor({logger, patterns, interDigitTimeout}) {
this.logger = logger;
this.patterns = patterns;
this.idt = interDigitTimeout || 3000;
this.buffer = [];
}
keyPress(key) {
const now = Date.now();
// age out previous entries if interdigit timer has elapsed
const lastDtmf = this.buffer.pop();
if (lastDtmf) {
if (now - lastDtmf.time < this.idt) this.buffer.push(lastDtmf);
else {
this.buffer = [];
}
}
// add new entry
this.buffer.push(new DtmfEntry(key, now));
// check for a match
const collectedDigits = this.buffer
.map((entry) => entry.key)
.join('');
return this.patterns.find((pattern) => collectedDigits.endsWith(pattern));
}
} |
JavaScript | class WrittenDataByFD extends AsyncObject {
// params are [, position[, encoding]]
constructor (fd, string, ...params) {
super(fd, string, ...params)
}
asyncCall () {
return fs.write
}
onResult (written, string) {
return string
}
} |
JavaScript | class StorageField {
/**
* Constructs a new field
*
* @param {string} name - name of field in storage
* @param {any} defaultValue - default value
* @param {function} validator - validator function for new field params
*/
constructor(name, defaultValue, validator = undefined) {
this.name = name;
this.default = defaultValue;
this.validator = validator;
}
/**
* Validates a new field value
*
* @param {any} value - value to validate
*/
is_valid(value) {
if (this.validatior) {
return this.validatior(value);
}
else {
return true;
}
}
/**
* Handler for Tampermonkey menu command
*
* This param is tend to update a storage field.
* Field will be update be user from prompt.
*
* @param {string} menuParamName - a readeble description of updating param
*/
update_from_menu_handler(menuParamName) {
const promtText = `Set ${menuParamName} (default: ${this.default}):`;
let newFieldValue = window.prompt(promtText, this.get());
if (this.is_valid(newFieldValue)) {
this.set(newFieldValue);
}
}
/**
* Returns the field value or a default value
*/
get() {
return GM_getValue(this.name, this.default);
}
/**
* Sets a new field value in the storage without a validation
*
* @param {any} newFieldValue - a new field value
*/
set(newFieldValue) {
GM_setValue(this.name, newFieldValue);
}
} |
JavaScript | class Modes {
constructor(root) {
this.root = root;
this.MODES = {
[MODES_DICTIONARY.STANDARD]: StandardMode,
[MODES_DICTIONARY.TIMER]: TimerMode
};
}
/**
* Create mode instance from existing modes dictionary
* @public
* @param name
* @returns Mode instance
*/
initMode(name) {
if(!this.MODES[name]) {
throw new Error(`Mode with name ${name} doesn't exist`)
}
return new this.MODES[name](this.root);
}
} |
JavaScript | class AmplifyButton {
constructor() {
/** Type of the button: 'button', 'submit' or 'reset' */
this.type = 'button';
/** Variant of a button: 'button' | 'anchor | 'icon' */
this.variant = 'button';
/** Disabled state of the button */
this.disabled = false;
this.handleClick = (ev) => {
if (this.handleButtonClick) {
this.handleButtonClick(ev);
}
else if (hasShadowDom(this.el) && this.type == 'submit') {
// this button wants to specifically submit a form
// climb up the dom to see if we're in a <form>
// and if so, then use JS to submit it
let form = this.el.closest('form');
if (!form) {
// Check for form inside of form section's shadow dom
const formSection = this.el.closest('amplify-form-section');
form = formSection && formSection.shadowRoot.querySelector('form');
}
if (form) {
ev.preventDefault();
const fakeButton = document.createElement('button');
fakeButton.type = this.type;
fakeButton.style.display = 'none';
form.appendChild(fakeButton);
fakeButton.click();
fakeButton.remove();
}
}
};
}
render() {
return (h("button", { class: {
[this.variant]: true,
}, type: this.type, disabled: this.disabled, onClick: this.handleClick },
this.variant === 'icon' && h("amplify-icon", { name: this.icon }),
h("slot", null)));
}
static get is() { return "amplify-button"; }
static get encapsulation() { return "shadow"; }
static get originalStyleUrls() { return {
"$": ["amplify-button.scss"]
}; }
static get styleUrls() { return {
"$": ["amplify-button.css"]
}; }
static get properties() { return {
"type": {
"type": "string",
"mutable": false,
"complexType": {
"original": "ButtonTypes",
"resolved": "\"button\" | \"reset\" | \"submit\"",
"references": {
"ButtonTypes": {
"location": "import",
"path": "../../common/types/ui-types"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Type of the button: 'button', 'submit' or 'reset'"
},
"attribute": "type",
"reflect": false,
"defaultValue": "'button'"
},
"variant": {
"type": "string",
"mutable": false,
"complexType": {
"original": "ButtonVariant",
"resolved": "\"anchor\" | \"button\" | \"icon\"",
"references": {
"ButtonVariant": {
"location": "import",
"path": "../../common/types/ui-types"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "Variant of a button: 'button' | 'anchor | 'icon'"
},
"attribute": "variant",
"reflect": false,
"defaultValue": "'button'"
},
"handleButtonClick": {
"type": "unknown",
"mutable": false,
"complexType": {
"original": "(evt: Event) => void",
"resolved": "(evt: Event) => void",
"references": {
"Event": {
"location": "global"
}
}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "(Optional) Callback called when a user clicks on the button"
}
},
"disabled": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": true,
"docs": {
"tags": [],
"text": "Disabled state of the button"
},
"attribute": "disabled",
"reflect": false,
"defaultValue": "false"
},
"icon": {
"type": "string",
"mutable": false,
"complexType": {
"original": "IconNameType",
"resolved": "\"amazon\" | \"auth0\" | \"ban\" | \"enter-vr\" | \"exit-vr\" | \"facebook\" | \"google\" | \"loading\" | \"maximize\" | \"microphone\" | \"minimize\" | \"photoPlaceholder\" | \"send\" | \"sound\" | \"sound-mute\" | \"warning\"",
"references": {
"IconNameType": {
"location": "import",
"path": "../amplify-icon/icons"
}
}
},
"required": false,
"optional": true,
"docs": {
"tags": [],
"text": "Name of icon to be placed inside the button"
},
"attribute": "icon",
"reflect": false
}
}; }
static get elementRef() { return "el"; }
} |
JavaScript | class Customer_Delete extends Retrieve_Update_Delete {
_display_name = "Customer_Delete";
_last_verified_square_api_version = "2021-07-21";
_help = this.display_name + ": " + man;
constructor(id, version) {
super(id);
this._method = "DELETE";
this._delivery;
if (version !== undefined) {
this.version = version;
}
}
// GETTERS
get delivery() {
return this._delivery;
}
// SETTERS
set delivery(parcel) {
this._delivery = parcel;
}
set #endpoint(str) {
this._endpoint = str;
}
set replace_id(id) {
let replacement = endpoint_id_replace(this.endpoint, id);
this._endpoint = replacement;
}
set version(int) {
if (shazam_is_integer(int, this.display_name, "version"))
this.#query_param_replace("version", int + "");
}
// PRIVATE METHODS
#init_query_param_sequence(param, value) {
let modified_endpoint = this.endpoint;
// check if endpoint is already formatted as a query string.
if (!query_param_is_query_string(modified_endpoint)) {
// if not then append ?param=value and return false
modified_endpoint += "?" + param + "=" + value;
this.#endpoint = modified_endpoint;
return false;
} else {
return true;
}
}
#query_param_replace(param, value) {
if (this.#init_query_param_sequence(param, value)) {
this.#endpoint = query_param_replace_value(this.endpoint, param, value);
}
}
/**
* make() method of Customer_Delete
* Make sure to have the Square Docs open in front of you.
* Sub-Method names are exactly the same as the property names listed
* in the Square docs. There may be additional methods and/or shortened aliases of other methods.
*
* You should read the generated docs as:
* method_name(arg) {type} description of arg
*
* @typedef {function} Customer_Delete.make
* @method
* @public
* @memberOf Customer_Delete
* @property id(id) {string<id>} - replaces or set the /{id} portion of the endpoint - can be used any time before calling .request().
* @property version(version) {integer} - Expects an integer. Sets the 'version' query parameter
* @example
* You must use parentheses with every call to make and with every sub-method. If you have to make a lot
* of calls from different lines, it will reduce your tying and improve readability to set make() to a
* variable.
*
* let make = myVar.make();
* make.gizmo()
* make.gremlin()
* //is the same as
* myVar.make().gizmo().gremlin()
* */
make() {
return {
self: this,
id: function (id) {
this.self.replace_id = id;
return this;
},
version: function (version) {
this.self.version = version;
return this;
},
};
}
} |
JavaScript | class PGroup {
constructor(members){
this.members = members;
}
add(e){
if(!this.has(e)) return new PGroup(this.members.concat(e));
else return this;
}
delete(e){
// remove an element from an array: filter function
return new PGroup(this.members.filter(v => v!== e));
}
has(e) {
return this.members.includes(e);
}
} |
JavaScript | class PipelineRunQueryOrderBy {
/**
* Create a PipelineRunQueryOrderBy.
* @member {string} orderBy Parameter name to be used for order by. Possible
* values include: 'RunStart', 'RunEnd'
* @member {string} order Sorting order of the parameter. Possible values
* include: 'ASC', 'DESC'
*/
constructor() {
}
/**
* Defines the metadata of PipelineRunQueryOrderBy
*
* @returns {object} metadata of PipelineRunQueryOrderBy
*
*/
mapper() {
return {
required: false,
serializedName: 'PipelineRunQueryOrderBy',
type: {
name: 'Composite',
className: 'PipelineRunQueryOrderBy',
modelProperties: {
orderBy: {
required: true,
serializedName: 'orderBy',
type: {
name: 'String'
}
},
order: {
required: true,
serializedName: 'order',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class UtilError extends Error {
constructor(message) {
super(message);
this.name = "UtilDoPackageError";
}
} |
JavaScript | class StaffForm extends React.Component {
defaultState = {
username: '',
email: '',
passwordOne: '',
passwordTwo: '',
error: null,
role: '',
uniq_id: ''
};
constructor(props) {
super(props);
this.state = {
...this.defaultState,
...this.props.rowData
};
}
componentDidUpdate(prevProps) {
if (this.props.rowData !== prevProps.rowData) {
this.setState({ ...this.defaultState, ...this.props.rowData });
}
}
//Used to send the data to the databsae and reset the state.
handleOk = showLoadingAnimation => {
this.props.form.validateFieldsAndScroll(err => {
if (!err && !this.state.error) {
showLoadingAnimation();
var newData = JSON.parse(JSON.stringify(this.state));
var row = this.props.rowData;
// currently this chunk is unused
// but will likely be needed in future
const roles = [];
if (this.state.role === 'Admin') {
roles.push(ROLES.ADMIN);
} else {
roles.push(ROLES.STANDARD);
}
newData.password = newData.passwordOne;
delete newData.passwordOne;
delete newData.passwordTwo;
const callback = () => this.props.refreshTable(this.props.closeModal);
if (row && row.uniq_id) {
// if we are editing a user, set in place
db.setUserObj(row.uniq_id, newData, callback);
} else {
// else we are creating a new user
db.createNewUser(newData, callback).catch(error => {
this.setState(byPropKey('error', error));
});
}
}
});
};
onStatusChange = value => {
this.setState({ role: value });
};
handleDelete = showLoadingAnimation => {
showLoadingAnimation();
const callback = () => this.props.refreshTable(this.props.closeModal);
db.deleteUserObj(this.props.rowData.uniq_id, callback).catch(error => {
this.setState(byPropKey('error', error));
});
};
render() {
const { getFieldDecorator, getFieldsError, isFieldsTouched } = this.props.form;
const isInvalid = this.state.passwordOne !== this.state.passwordTwo;
const isCreatingNewUser = !this.props.rowData;
return (
<Modal
title={'Add New Staff Member'}
style={{
top: 20
}}
width={'30vw'}
destroyOnClose={true}
visible={this.props.modalVisible}
onCancel={this.props.closeModal}
afterClose={this.props.closeForm}
footer={[
<Footer
key={'footer'}
rowData={this.props.rowData}
closeModal={this.props.closeModal}
handleOk={this.handleOk}
handleDelete={this.handleDelete}
saveDisabled={!isFieldsTouched() || hasErrors(getFieldsError()) || isInvalid}
/>
]}
>
<Form layout={'vertical'} style={styles.form}>
<Form.Item style={styles.fullWidthFormItem} label={'Username:'}>
{getFieldDecorator('username', {
initialValue: this.state.username,
rules: [{ whitespace: true, required: true, message: 'Please Enter A Username' }]
})(
<Input
placeholder={'Username'}
onChange={event => this.setState(byPropKey('username', event.target.value))}
/>
)}
</Form.Item>
{!isCreatingNewUser ? null : (
<Form.Item style={styles.fullWidthFormItem} label={'Email:'}>
{getFieldDecorator('email', {
initialValue: this.state.email,
rules: [
{
whitespace: true,
required: true,
message: 'Please Enter A Valid Email',
validator: (rule, value, callback) => isEmail(value)
}
]
})(
<Input
placeholder={'Email'}
onChange={event => this.setState(byPropKey('email', event.target.value))}
/>
)}
</Form.Item>
)}
<Form.Item style={styles.fullWidthFormItem} label={'Role:'}>
{getFieldDecorator('role', {
initialValue: this.state.role,
rules: [
{
required: true,
message: 'Please Select A Role'
}
]
})(
<Select placeholder={'Role'} onChange={val => this.setState(byPropKey('role', val))}>
<Option value={'Admin'}>Admin</Option>
<Option value={'Standard'}>Standard</Option>
</Select>
)}
</Form.Item>
<PasswordFields
isCreatingNewUser={isCreatingNewUser}
styles={styles}
error={this.state.error}
isInvalid={isInvalid}
onChange={(prop, event) => this.setState(byPropKey(prop, event.target.value))}
getFieldDecorator={getFieldDecorator}
/>
</Form>
</Modal>
);
}
} |
JavaScript | class GetSessionBase extends ServiceBase {
/**
* Constructor to fetch session details by userId and addresses.
*
* @param {object} params
* @param {string} params.user_id
* @param {integer} params.client_id
* @param {integer} [params.token_id]
*
* @augments ServiceBase
*
* @constructor
*/
constructor(params) {
super(params);
const oThis = this;
oThis.userId = params.user_id;
oThis.tokenId = params.token_id;
oThis.clientId = params.client_id;
oThis.sessionShardNumber = null;
oThis.sessionNonce = {};
oThis.sessionAddresses = [];
oThis.lastKnownChainBlockDetails = {};
oThis.sessionDetails = [];
}
/**
* Async perform.
*
* @returns {Promise<*|result>}
*/
async _asyncPerform() {
const oThis = this;
await oThis._validateAndSanitizeParams();
await oThis._validateTokenStatus();
await oThis._fetchUserSessionShardNumber();
await oThis._setSessionAddresses();
await oThis._setLastKnownChainBlockDetails();
await oThis._fetchSessionsExtendedDetails();
return oThis._formatApiResponse();
}
/**
* Fetch session shard number of user
*
* @sets oThis.sessionShardNumber
*
* @return {Promise<never>}
* @private
*/
async _fetchUserSessionShardNumber() {
const oThis = this;
const TokenUserDetailsCache = oThis.ic().getShadowedClassFor(coreConstants.icNameSpace, 'TokenUserDetailsCache'),
tokenUserDetailsCacheObj = new TokenUserDetailsCache({ tokenId: oThis.tokenId, userIds: [oThis.userId] }),
cacheFetchRsp = await tokenUserDetailsCacheObj.fetch(),
userData = cacheFetchRsp.data[oThis.userId];
if (!CommonValidators.validateObject(userData)) {
return Promise.reject(
responseHelper.paramValidationError({
internal_error_identifier: 'a_s_s_g_b_1',
api_error_identifier: 'resource_not_found',
params_error_identifiers: ['user_not_found'],
debug_options: {}
})
);
}
oThis.sessionShardNumber = userData.sessionShardNumber;
}
/**
* Set last known block details of a specific chain.
*
* @sets oThis.lastKnownChainBlockDetails
*
* @return {Promise<void>}
* @private
*/
async _setLastKnownChainBlockDetails() {
const oThis = this,
chainId = oThis.ic().configStrategy.auxGeth.chainId,
BlockTimeDetailsCache = oThis.ic().getShadowedClassFor(coreConstants.icNameSpace, 'BlockTimeDetailsCache'),
blockTimeDetailsCache = new BlockTimeDetailsCache({ chainId: chainId });
const blockDetails = await blockTimeDetailsCache.fetch();
oThis.lastKnownChainBlockDetails = {
blockGenerationTime: Number(blockDetails.data.blockGenerationTime),
lastKnownBlockTime: Number(blockDetails.data.createdTimestamp),
lastKnownBlockNumber: Number(blockDetails.data.block)
};
}
/**
* Fetch session extended details.
*
* @returns {Promise<*>}
* @private
*/
async _fetchSessionsExtendedDetails() {
const oThis = this;
const sessionsMap = (await oThis._fetchSessionsFromCache()).data;
const noncePromiseArray = [],
currentTimestamp = Math.floor(new Date() / 1000);
for (const index in oThis.sessionAddresses) {
const sessionAddress = oThis.sessionAddresses[index],
session = sessionsMap[sessionAddress];
if (!CommonValidators.validateObject(session)) {
continue;
}
// Add expirationTimestamp to session
// Only send approx expiry when authorized
session.expirationTimestamp = null;
if (session.status === sessionConstants.authorizedStatus) {
session.expirationHeight = Number(session.expirationHeight);
const blockDifference = session.expirationHeight - oThis.lastKnownChainBlockDetails.lastKnownBlockNumber,
timeDifferenceInSecs = blockDifference * oThis.lastKnownChainBlockDetails.blockGenerationTime;
session.expirationTimestamp = oThis.lastKnownChainBlockDetails.lastKnownBlockTime + timeDifferenceInSecs;
}
// Compare approx expiration time with current time and avoid fetching nonce from contract.
// If session is expired then avoid fetching from contract.
const approxExpirationTimestamp = session.expirationTimestamp || 0;
if (Number(approxExpirationTimestamp) > currentTimestamp) {
noncePromiseArray.push(oThis._fetchSessionTokenHolderNonce(session.address));
}
oThis.sessionDetails.push(session);
}
await Promise.all(noncePromiseArray);
for (let index = 0; index < oThis.sessionDetails.length; index++) {
const session = oThis.sessionDetails[index];
session.nonce = oThis.sessionNonce[session.address] || null;
}
}
/**
* Get session details of a user from a multi cache
*
* @returns {Promise<*|result>}
*/
async _fetchSessionsFromCache() {
const oThis = this;
const SessionsByAddressCache = oThis.ic().getShadowedClassFor(coreConstants.icNameSpace, 'SessionsByAddressCache'),
sessionsByAddressCache = new SessionsByAddressCache({
userId: oThis.userId,
tokenId: oThis.tokenId,
addresses: oThis.sessionAddresses,
shardNumber: oThis.sessionShardNumber
}),
response = await sessionsByAddressCache.fetch();
if (response.isFailure()) {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'a_s_s_g_b_3',
api_error_identifier: 'something_went_wrong',
debug_options: {}
})
);
}
return response;
}
/**
* Fetch nonce from contract.
*
* @param {string} sessionAddress
*
* @sets oThis.sessionNonce
*
* @returns {Promise<any>}
* @private
*/
_fetchSessionTokenHolderNonce(sessionAddress) {
const oThis = this;
const TokenHolderNonceKlass = oThis.ic().getShadowedClassFor(coreConstants.icNameSpace, 'TokenHolderNonce'),
auxChainId = oThis.ic().configStrategy.auxGeth.chainId,
params = {
auxChainId: auxChainId,
tokenId: oThis.tokenId,
userId: oThis.userId,
sessionAddress: sessionAddress
};
return new Promise(function(onResolve) {
logger.debug('Fetching nonce session token holder nonce. SessionAddress:', sessionAddress);
new TokenHolderNonceKlass(params)
.perform()
.then(function(resp) {
logger.debug('Fetching nonce Done. SessionAddress:', sessionAddress, 'Data: ', resp);
if (resp.isSuccess()) {
oThis.sessionNonce[sessionAddress] = resp.data.nonce;
}
onResolve();
})
.catch(function(err) {
logger.error(err);
onResolve();
});
});
}
/**
* Validate and sanitize input parameters.
*
* @returns {Promise<void>}
* @private
*/
async _validateAndSanitizeParams() {
throw new Error('Sub-class to implement.');
}
/**
* Set session addresses.
*
* @returns {Promise<void>}
* @private
*/
async _setSessionAddresses() {
throw new Error('Sub-class to implement.');
}
/**
* Format API response.
*
* @returns {Promise<void>}
* @private
*/
async _formatApiResponse() {
throw new Error('Sub-class to implement.');
}
} |
JavaScript | class Login extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
errors: {}
};
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
// Form Change Handler
onChange(e) {
this.setState({ [e.target.id]: e.target.value });
};
// Submit login info, try to log in
onSubmit(e) {
const {toggleLogin} = this.context;
e.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
};
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
}
// Request token for corresponding user account from backend
fetch('/api/users/login', requestOptions)
.then(response => {
const r = response.json()
return r
})
.then(data => {
this.setState({ errors: data })
if(data.success===true){
toggleLogin(data.token)
this.props.history.push("/fridge");
}
})
};
render() {
if(this.context.loggedIn){
this.props.history.push("/fridge");
}
const { errors } = this.state;
return (
<div className="container-fluid poppin" style={{marginTop:"50px",maxWidth:"750px",width:"100%"}}>
<div className="row">
<div className="col-sm-12">
<div>
<h4>
<b>Log In</b>
</h4>
<p>
Don't have an account? <Link to="/register">Sign Up</Link>
</p>
</div>
<form noValidate onSubmit={this.onSubmit}>
<div className="form-group">
<label for="email">Email</label>
<input className="form-control"
onChange={this.onChange}
value={this.state.email}
error={errors.email}
id="email"
type="email"
/>
</div>
<div className="form-group">
<label for="password">Password</label>
<input className="form-control"
onChange={this.onChange}
value={this.state.password}
error={errors.password}
id="password"
type="password"
/>
</div>
<button
style={{
width: "100px",
borderRadius: "3px",
}}
type="submit"
className="btn btn-primary"
>
Log In
</button>
</form>
{/* Errors */}
<small className="form-text text-danger">
{errors.email}
<br/>
{errors.emailnotfound}
<br/>
{errors.password}
<br/>
{errors.passwordincorrect}
</small>
</div>
</div>
</div>
);
}
} |
JavaScript | class GLFramebuffer
{
/**
* @param {WebGLRenderingContext} gl - The current WebGL rendering context
* @param {number} width - the width of the drawing area of the frame buffer
* @param {number} height - the height of the drawing area of the frame buffer
*/
constructor(gl, width = 100, height = 100)
{
/**
* The current WebGL rendering context.
*
* @member {WebGLRenderingContext}
*/
this.gl = gl;
/**
* The frame buffer.
*
* @member {WebGLFramebuffer}
*/
this.framebuffer = gl.createFramebuffer();
/**
* The stencil buffer.
*
* @member {WebGLRenderbuffer}
*/
this.stencil = null;
/**
* The stencil buffer.
*
* @member {GLTexture}
*/
this.texture = null;
/**
* The width of the drawing area of the buffer.
*
* @member {number}
*/
this.width = width;
/**
* The height of the drawing area of the buffer.
*
* @member {number}
*/
this.height = height;
}
/**
* Creates a frame buffer with a texture containing the given data
*
* @static
* @param {WebGLRenderingContext} gl - The current WebGL rendering context
* @param {number} width - the width of the drawing area of the frame buffer
* @param {number} height - the height of the drawing area of the frame buffer
* @return {GLFramebuffer} The new framebuffer.
*/
static createRGBA(gl, width, height)
{
return GLFramebuffer.createFloat32(gl, width, height, null);
}
/**
* Creates a frame buffer with a texture containing the given data
*
* @static
* @param {WebGLRenderingContext} gl - The current WebGL rendering context
* @param {number} width - the width of the drawing area of the frame buffer
* @param {number} height - the height of the drawing area of the frame buffer
* @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} data - an array of data
* @return {GLFramebuffer} The new framebuffer.
*/
static createFloat32(gl, width, height, data)
{
const texture = GLTexture.fromData(gl, data, width, height);
texture.enableNearestScaling();
texture.enableWrapClamp();
// now create the framebuffer object and attach the texture to it.
const fbo = new GLFramebuffer(gl, width, height);
fbo.enableTexture(texture);
fbo.unbind();
return fbo;
}
/**
* Adds a texture to the framebuffer.
*
* @param {GLTexture} texture - the texture to add.
*/
enableTexture(texture)
{
const gl = this.gl;
this.texture = texture || new GLTexture(gl);
this.texture.bind();
this.bind();
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0);
}
/**
* Initialises the stencil buffer
*/
enableStencil()
{
if (this.stencil) return;
const gl = this.gl;
this.stencil = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil);
// TODO.. this is depth AND stencil?
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width, this.height);
}
/**
* Erases the drawing area and fills it with a colour
*
* @param {number} r - the red value of the clearing colour
* @param {number} g - the green value of the clearing colour
* @param {number} b - the blue value of the clearing colour
* @param {number} a - the alpha value of the clearing colour
*/
clear(r = 0, g = 0, b = 0, a = 1)
{
this.bind();
const gl = this.gl;
gl.clearColor(r, g, b, a);
gl.clear(gl.COLOR_BUFFER_BIT);
}
/**
* Binds the frame buffer to the WebGL context
*/
bind()
{
const gl = this.gl;
if (this.texture)
{
this.texture.unbind();
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
}
/**
* Unbinds the frame buffer to the WebGL context
*/
unbind()
{
this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);
}
/**
* Resizes the drawing area of the buffer to the given width and height
*
* @param {number} width - the new width
* @param {number} height - the new height
*/
resize(width, height)
{
const gl = this.gl;
this.width = width;
this.height = height;
if (this.texture)
{
this.texture.uploadData(null, width, height);
}
if (this.stencil)
{
// update the stencil buffer width and height
gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
}
}
/**
* Destroys this buffer
*/
destroy()
{
if (this.texture)
{
this.texture.destroy();
}
this.gl.deleteFramebuffer(this.framebuffer);
this.gl = null;
this.framebuffer = null;
this.stencil = null;
this.texture = null;
}
} |
JavaScript | class StockGraph {
error
id
name
numDays
/**
* Creates a stock graph
* @param name Company name
* @param symbol Stock ticker symbol
*/
constructor(name, symbol, apiKey) {
this.error = false
this.id = symbol
this.name = name
// Make API call
let stocks = this.stockApiCall(symbol, apiKey)
.then(this.json2stocks)
// Scale sentiment data and draw
stocks.then((stock => {
// Warn about API key
if(stock.length === 0) this.error = true
this.sentimentApiCall(name)
.then(this.json2sentiments)
.then(sentiment => {
this.numDays = sentiment.length
this.draw(stock, sentiment, symbol)
})
}).bind(this))
}
/**
* Makes a call to the sentiment API, and returns the json from it
* @param symbol Stock trading symbol
*/
sentimentApiCall(name) {
const api = 'https://sentocks.sandyuraz.com/api/sentiments/market'
const url = `${api}?company=${name}`
return fetch(url).then(res => res.json())
}
/**
* Makes a call to the stocks, and returns the json from it
* @param symbol Stock trading symbol
*/
stockApiCall(symbol, apiKey) {
// const apiKey = 'VF5PZ9DBDNDKYYSN'
const api = 'https://www.alphavantage.co/query?'
const url = `${api}function=TIME_SERIES_INTRADAY&outputsize=full&symbol=${symbol}&interval=1min&apikey=${apiKey}`
return fetch(url).then(res => res.json())
}
/**
* Draws the graphs in their respective context
* @param stock stock data
* @param sentiment sentiment data
* @param symbol The stock trading symbol
*/
draw(stock, sentiment, symbol) {
// console.log(symbol, 'stock', stock.slice(-this.numDays))
// console.log(symbol, 'sentiment', sentiment.slice(-this.numDays))
let chart = this.getChart(
stock.slice(-this.numDays),
sentiment.slice(-this.numDays)
)
//draw on canvas
new Chart(document.getElementById(`${symbol}-preview`), chart)
new Chart(document.getElementById(`${symbol}-full`), chart)
}
getChart(stock, sentiment) {
// Generate colors
const color = {
r: Math.random()*100 + 50,
g: Math.random()*100 + 50,
b: Math.random()*100 + 50
}
// Generate a dataset
const dataset = (title, data, color, side) => ({label: title, data: data, yAxisID: side, fill: false, borderColor: color, lineTension: 0, pointRadius: 0})
return {
type: 'line',
data: {
labels: this.getLabels(this.numDays),
datasets: [
dataset('Stock Price', stock, `rgb(${color.r}, ${color.g}, ${color.b})`, 'left'),
dataset('Sentiment Rating', sentiment, `rgb(${color.r+100}, ${color.g+100}, ${color.b+100})`, 'right')
]
},
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
scales: {
yAxes: [{
type: 'linear',
display: true,
position: 'left',
id: 'left'
}, {
type: 'linear',
display: true,
position: 'right',
id: 'right'
}],
}
}
}
}
/**
* Generates the list of labels for the last n days
* @param n number of days
*/
getLabels(n) {
return new Array(n).fill(' ')
// let date = new Date
// date.setHours(9)
// date.setMinutes(30)
// return [...Array(n).keys()].map(n => {
// date = new Date(date.getTime() + 60000)
// let min = date.getMinutes()
// return `${date.getHours()}:${min<10?'0':''}${min}`
// })
}
/**
* converts the JSON object from the API into a list of sentiment data
* @param json The JSON object to be converted
*/
json2sentiments(json) {
return json.map(e => e[1])
}
/**
* Converts the JSON object from the API into a list of stock data
* @param json The JSON object to be converted
*/
json2stocks(json) {
const minKey = 'Time Series (1min)'
const dataKey = '4. close'
const minutes = json[minKey]
let data = []
for(let min in minutes) data.push(minutes[min][dataKey])
return data
}
} |
JavaScript | class Base {
constructor (json) {
if (!json) throw new ParserError(`Invalid JSON to instantiate the ${this.constructor.name} object.`);
this._json = json;
}
/**
* @returns {Any}
*/
json(key) {
if (key === undefined) return this._json;
if (!this._json) return;
return this._json[key];
}
} |
JavaScript | class DataProvider {
constructor() {
this.resources = {}
this.libraries = {}
this.signatures = {}
this.entities = {}
}
async serialize_resource(res, opts) {
if (opts === undefined) opts = {}
const resource = await this.resolve_resource(res)
const serialized = {}
serialized.id = await resource.id
serialized.meta = await resource.meta
if (opts.validator) serialized['$validator'] = await resource.validator
if (!opts.fetched_data) {
if (opts.signatures === true) {
await this.fetch_signatures_for_libraries(await resource.libraries)
}
if (opts.data === true) {
const signatures = (await PromiseAllSeq((await resource.libraries).map(
(library) =>
async () => await library.signatures
))).reduce(
(all, sigs) => [...all, ...sigs], []
)
await this.fetch_data_for_signatures(signatures)
}
}
if (opts.libraries === true) {
serialized.libraries = await PromiseAllSeq(
(await resource.libraries).map(
(library) =>
async () => await this.serialize_library(library, {
signatures: opts.signatures,
data: opts.data,
validator: opts.validator,
fetched_data: true,
})
)
)
}
return serialized
}
async serialize_library(lib, opts) {
if (opts === undefined) opts = {}
const library = await this.resolve_library(lib)
const serialized = {}
serialized.id = await library.id
serialized.meta = await library.meta
serialized.dataset = await library.dataset
serialized.dataset_type = await library.dataset_type
if (opts.validator) serialized['$validator'] = await library.validator
if (!opts.fetched_data) {
if (opts.signatures === true) {
await this.fetch_signatures_for_libraries([library])
}
if (opts.data === true) {
await this.fetch_data_for_signatures(await library.signatures)
}
}
if (opts.resource === true) {
const resource = await library.resource
if (resource !== undefined) {
serialized.resource = await this.serialize_resource(resource)
}
}
if (opts.signatures === true) {
serialized.signatures = await PromiseAllSeq(
(await library.signatures).map(
(signature) =>
async () => await this.serialize_signature(signature, {
data: opts.data, validator: opts.validator, fetched_data: true,
})
)
)
}
return serialized
}
async serialize_signature(sig, opts) {
if (opts === undefined) opts = {}
const signature = await this.resolve_signature(sig)
const serialized = {}
serialized.id = await signature.id
serialized.meta = await signature.meta
if (opts.validator) serialized['$validator'] = await signature.validator
if (opts.library === true) {
serialized.library = await this.serialize_library(await signature.library, {
resource: opts.resource,
validator: opts.validator,
})
}
if (opts.data === true) {
serialized.data = await PromiseAllSeq(
(await signature.data).map(
(entity) =>
async () => await this.serialize_entity(entity, { validator: opts.validator })
)
)
}
return serialized
}
async serialize_entity(ent, opts) {
// TODO: deal with rank data
if (opts === undefined) opts = {}
const entity = await this.resolve_entity(ent)
const serialized = {}
serialized.id = await entity.id
serialized.meta = await entity.meta
if (opts.validator) serialized['$validator'] = await entity.validator
if (opts.signature === true) {
serialized.signature = await this.serialize_signature(await entity.library, {
library: opts.library, resource: opts.resource, validator: opts.validator,
})
}
return serialized
}
resolve_resource = (resource) => {
if (resource instanceof Resource) {
return resource
}
if (typeof resource === 'string') {
resource = { 'id': resource }
}
if (typeof resource === 'object' && resource.id !== undefined) {
if (this.resources[resource.id] === undefined) {
this.resources[resource.id] = new Resource(resource, this)
}
return this.resources[resource.id]
} else {
return undefined
// throw new Error(`Invalid resource object provided for resolution: ${resource}`)
}
}
resolve_library = (library) => {
if (library instanceof Library) {
return library
}
if (typeof library === 'string') {
library = { 'id': library }
}
if (typeof library === 'object' && library.id !== undefined) {
if (this.libraries[library.id] === undefined) {
this.libraries[library.id] = new Library(library, this)
}
return this.libraries[library.id]
} else {
throw new Error(`Invalid library object provided for resolution ${library}`)
}
}
resolve_signature = (signature) => {
if (signature instanceof Signature) {
return signature
}
if (typeof signature === 'string') {
signature = { 'id': signature }
}
if (typeof signature === 'object' && signature.id !== undefined) {
if (this.signatures[signature.id] === undefined) {
this.signatures[signature.id] = new Signature(signature, this)
}
return this.signatures[signature.id]
} else {
throw new Error(`Invalid signature object provided for resolution: ${signature}`)
}
}
resolve_entity = (entity) => {
if (entity instanceof Entity) {
return entity
}
if (typeof entity === 'string') {
entity = { 'id': entity }
}
if (typeof entity === 'object' && entity.id !== undefined) {
if (this.entities[entity.id] === undefined) {
this.entities[entity.id] = new Entity(entity, this)
}
return this.entities[entity.id]
} else {
throw new Error(`Invalid entity object provided for resolution: ${entity}`)
}
}
resolve_resources = async (resources) => {
return await PromiseAllSeq(
resources.map(
(resource) =>
async () => await this.resolve_resource(resource)
)
)
}
resolve_libraries = async (libraries) => {
return await PromiseAllSeq(
libraries.map(
(library) =>
async () => await this.resolve_library(library)
)
)
}
resolve_signatures = async (signatures) => {
return await PromiseAllSeq(
signatures.map(
(signature) =>
async () => await this.resolve_signature(signature)
)
)
}
resolve_entities = async (entities) => {
return await PromiseAllSeq(
entities.map(
(entity) =>
async () => await this.resolve_entity(entity)
)
)
}
fetch_resources = async () => {
const { libraries, resources, library_resource } = await get_library_resources()
for (const res of Object.values(resources)) {
const resource = await this.resolve_resource(res)
resource._fetched = true
resource._resource = res
resource._libraries = new Set(await this.resolve_libraries(resource._resource.libraries))
}
for (const lib of Object.values(libraries)) {
// update library
const library = await this.resolve_library(lib)
library._fetched = true
library._library = lib
// update resource
if (library_resource[lib.id] !== undefined) {
library._resource = await this.resolve_resource(library_resource[lib.id])
}
// update signatures
if (library._signatures === undefined) {
library._signatures = new Set()
}
for (const signature of Object.values(this.signatures)) {
if (lib.id === await (await signature.library).id) {
library._signatures.add(signature)
}
}
}
}
fetch_libraries = async () => {
await this.fetch_resources()
}
fetch_signatures_for_libraries = async (libraries) => {
// TODO: consider just fetching uuids here so we don't fetch the whole signature if
// we already have it
if (libraries === undefined) libraries = Object.values(this.libraries)
const { response } = await fetch_meta_post({
endpoint: `/signatures/find`,
body: {
filter: {
where: {
library: {
inq: await PromiseAllSeq(
libraries.map(
(library) =>
async () => await library.id
)
),
},
},
},
},
})
for (const sig of response) {
const signature = await this.resolve_signature(sig)
signature._fetched = true
signature._signature = sig
const library = await signature.library
if (library._signatures === undefined) {
library._signatures = new Set()
}
library._signatures.add(signature)
}
}
fetch_signatures = async () => {
const signatures = Object.keys(this.signatures).filter((entity) => !this.signatures[entity]._fetched)
if (signatures.length === 0) {
return
}
const { response } = await fetch_meta_post({
endpoint: `/signatures/find`,
body: {
filter: {
where: {
id: {
inq: signatures,
},
},
},
},
})
for (const sig of response) {
const signature = await this.resolve_signature(sig)
signature._fetched = true
signature._signature = sig
const library = await signature.library
if (library._signatures === undefined) {
library._signatures = new Set()
}
library._signatures.add(signature)
}
}
fetch_data_for_signatures = async (signatures) => {
if (signatures === undefined) signatures = Object.values(this.signatures)
// filter by signatures not yet fetched
signatures = (await this.resolve_signatures(signatures)).filter((signature) => !signature._fetched_data)
// group signatures by (dataset, dataset_type)
const dataset_with_type_signatures = {}
for (const signature of signatures) {
const library = await signature.library
const dataset_with_type = JSON.stringify([await library.dataset, await library.dataset_type])
if (dataset_with_type_signatures[dataset_with_type] === undefined) {
dataset_with_type_signatures[dataset_with_type] = new Set()
}
dataset_with_type_signatures[dataset_with_type].add(signature)
}
// go through groups and grab signatures
for (const dataset_with_type of Object.keys(dataset_with_type_signatures)) {
const [dataset, dataset_type] = JSON.parse(dataset_with_type)
const cur_signatures = [...dataset_with_type_signatures[dataset_with_type]]
// get the relevant endpoint to query
let endpoint
if (dataset_type.startsWith('geneset')) {
endpoint = 'set'
} else if (dataset_type.startsWith('rank')) {
endpoint = 'rank'
} else {
throw new Error(`${dataset_type} not recognized`)
}
// construct request with signatures of interest
const { response } = await fetch_data({
endpoint: `/fetch/${endpoint}`,
body: {
entities: [],
signatures: await PromiseAllSeq(cur_signatures.map((signature) => async () => await signature.id)),
database: dataset,
},
})
// resolve results
// TODO: Deal with rank data differently?
for (const sig of response.signatures) {
const signature = await this.resolve_signature(sig.uid)
signature._fetched_data = true
if (endpoint === 'set') {
const entities = await this.resolve_entities(sig.entities)
signature._data = entities
} else if (endpoint === 'rank') {
const ranks = sig.ranks
const ranked_entities = response.entities.map((ent, ind) => ({ ent, rank: ranks[ind] }))
ranked_entities.sort(({ rank: rank_a }, { rank: rank_b }) => rank_a - rank_b)
const entities = await this.resolve_entities(ranked_entities.reduce((agg, { ent }) => ent !== undefined ? [...agg, ent] : agg, []))
// const rank_index = ranks.map((rank)=>sig.ranks.indexOf(rank))
// const entities = await this.resolve_entities(rank_index.map((rank) => response.entities[rank]).filter((ent) => ent !== undefined))
signature._data = entities
} else {
throw new Error(`endpoint ${endpoint} not recognized`)
}
}
}
}
fetch_entities = async () => {
const entities = Object.keys(this.entities).filter((entity) => !this.entities[entity]._fetched)
if (entities.length === 0) {
return
}
const { response } = await fetch_meta_post({
endpoint: `/entities/find`,
body: {
filter: {
where: {
id: {
inq: entities,
},
},
},
},
})
for (const ent of response) {
const entity = await this.resolve_entity(ent)
entity._fetched = true
entity._entity = ent
}
}
} |
JavaScript | class Flyout extends Core {
constructor(options = {}) {
super(options);
this._render(Template, options);
this.initialOptions = options;
}
_componentDidMount() {
this.setAnchorPoint(this.initialOptions.anchorPoint);
this._setType(this.initialOptions.type);
this.flyoutContainer = this._findDOMEl('.hig__flyout__container', this.el);
this.flyoutContent = this._findDOMEl('.hig__flyout__panel', this.el);
this.containerAnimation = new CSSTransition({
el: this.el,
class: 'hig__flyout',
enteringDuration: 300,
exitingDuration: 300
});
}
open() {
this.containerAnimation.enter();
this._ensureFlyoutLeftEdgeVisibility();
this._ensureFlyoutRightEdgeVisibility();
}
close() {
this.containerAnimation.exit();
}
_setType(type = 'default') {
if (!Flyout.AvailableTypes.includes(type)) {
console.error(
`Flyout cannot have type "${type}". Only these inset types are allowed: `,
Flyout.AvailableTypes
);
return;
}
this.el.classList.remove(
...Flyout.AvailableTypes.map(s => `hig__flyout--${s}`)
);
this.el.classList.add(`hig__flyout--${type}`);
}
onClickOutside(fn) {
return this._attachListener(
'click',
window.document.body,
window.document.body,
this._callbackIfClickOutside.bind(this, fn)
);
}
addSlot(slotElement) {
this.mountPartialToComment('SLOT', slotElement);
}
addTarget(targetElement) {
this.mountPartialToComment('TARGET', targetElement);
}
setAnchorPoint(anchorPoint) {
if (!Flyout.AvailableAnchorPoints.includes(anchorPoint)) {
console.error(
`Flyout cannot have anchorPoint "${anchorPoint}". Only these inset anchorPoints are allowed: `,
Flyout.AvailableAnchorPoints
);
return;
}
const container = this._findDOMEl('.hig__flyout__container', this.el);
container.classList.remove(
...Flyout.AvailableAnchorPoints.map(
s => `hig__flyout__container--anchor-${s}`
)
);
container.classList.add(`hig__flyout__container--anchor-${anchorPoint}`);
const panel = this._findDOMEl('.hig__flyout__panel', this.el);
panel.setAttribute('data-anchor-point', anchorPoint);
this._ensureFlyoutLeftEdgeVisibility();
this._ensureFlyoutRightEdgeVisibility();
}
_ensureFlyoutLeftEdgeVisibility() {
const viewPortWidth = document.documentElement.clientWidth;
const flyoutPanel = this._findDOMEl('.hig__flyout__panel', this.el);
const flyoutViewPortInfo = flyoutPanel.getBoundingClientRect();
const chevron = this._findDOMEl('.hig__flyout__chevron', this.el);
const target = this.el.firstElementChild;
const targetCenter = this._getXCenterCoordinate(target);
const chevronEl = this._findDOMEl('.hig__flyout__chevron--dark', this.el);
const chevronCenter = this._getXCenterCoordinate(chevronEl);
if (viewPortWidth < flyoutViewPortInfo.right) {
const shiftDistance = (flyoutViewPortInfo.right - viewPortWidth) + 5; // 5 is added hear to account for scrollbar
flyoutPanel.style.position = 'absolute';
flyoutPanel.style.left = `-${shiftDistance}px`;
this._updateChevronIndex(chevron);
chevron.style.left = `-${chevronCenter - targetCenter}px`;
}
}
_ensureFlyoutRightEdgeVisibility() {
const flyoutPanel = this._findDOMEl('.hig__flyout__panel', this.el);
const flyoutViewportInfo = flyoutPanel.getBoundingClientRect();
const target = this.el.firstElementChild;
const chevronContainer = this._findDOMEl('.hig__flyout__chevron', this.el);
if (flyoutViewportInfo.x < 0) {
flyoutPanel.style.position = 'absolute';
this._resetTopOrBottomFlyout(flyoutPanel, target, chevronContainer);
this._resetRightFlyout(flyoutPanel);
}
}
_resetTopOrBottomFlyout(flyoutPanel, target, chevronContainer) {
const updatedFlyoutViewportInfo = flyoutPanel.getBoundingClientRect();
const targetInfo = target.getBoundingClientRect();
if (
flyoutPanel.dataset.anchorPoint.includes('bottom-') ||
flyoutPanel.dataset.anchorPoint.includes('top-')
) {
const shiftDistance = updatedFlyoutViewportInfo.left - targetInfo.left;
flyoutPanel.style.left = `-${shiftDistance}px`;
if (flyoutPanel.dataset.anchorPoint.includes('bottom-')) {
flyoutPanel.style.bottom = '0px';
}
this._updateChevronIndex(chevronContainer);
}
}
_getXCenterCoordinate(el) {
const { width, x } = el.getBoundingClientRect();
return x + (width / 2);
}
_resetRightFlyout(flyoutPanel) {
if (flyoutPanel.dataset.anchorPoint.includes('right-')) {
const updatedAnchorPoint = flyoutPanel.dataset.anchorPoint.replace(
/right-/,
'left-'
);
this.setAnchorPoint(updatedAnchorPoint);
flyoutPanel.style.position = 'static';
}
}
_updateChevronIndex(chevron) {
chevron.style.zIndex = '9998';
}
setMaxHeight(maxHeight) {
if (maxHeight) {
this.flyoutContent.style.maxHeight = `${maxHeight}px`;
}
}
_callbackIfClickOutside(callback, event) {
if (
this.flyoutContainer.contains(event.target) ||
this.flyoutContainer === event.target
) {
return;
}
if (
this.containerAnimation.isEntering() ||
this.containerAnimation.isEntered()
) {
callback(event);
}
}
} |
JavaScript | class DocumentComment extends mixinBehaviors([NotifyBehavior, FormatBehavior], Nuxeo.Element) {
static get template() {
return html`
<style include="nuxeo-document-comments-styles nuxeo-button-styles">
:host {
margin-top: 5px;
}
#body:hover paper-icon-button {
opacity: 0.5;
transition: opacity 100ms;
}
.author {
font-weight: bold;
margin-right: 5px;
}
.info {
margin-left: 10px;
@apply --layout-vertical;
@apply --layout-flex;
}
.separator {
margin: 0 5px;
}
.text {
display: inline;
}
.text span {
white-space: pre-wrap;
}
paper-menu-button {
--paper-menu-button: {
padding: 0;
}
}
paper-listbox {
--paper-listbox: {
padding: 0;
}
}
paper-icon-button {
opacity: 0;
--paper-icon-button: {
padding: 0;
}
}
paper-icon-item {
--paper-icon-item: {
padding: 5px 5px;
display: flex;
cursor: pointer;
}
--paper-item-min-height: 24px;
--paper-item-icon: {
width: 1.75em;
margin-right: 10px;
}
--paper-item-selected-weight: normal;
--paper-item-focused-before: {
background-color: transparent;
}
}
</style>
<nuxeo-connection id="nxcon" user="{{currentUser}}"></nuxeo-connection>
<nuxeo-resource id="commentRequest" path="/id/[[comment.parentId]]/@comment/[[comment.id]]"></nuxeo-resource>
<nuxeo-dialog id="dialog" with-backdrop>
<h2>[[i18n('comments.deletion.dialog.heading')]]</h2>
<div>[[_computeConfirmationLabel(comment.numberOfReplies)]]</div>
<div class="buttons">
<paper-button name="dismiss" dialog-dismiss class="secondary"
>[[i18n('comments.deletion.dialog.buttons.cancel')]]</paper-button
>
<paper-button name="confirm" dialog-confirm on-click="_deleteComment" class="primary"
>[[i18n('comments.deletion.dialog.buttons.delete')]]</paper-button
>
</div>
</nuxeo-dialog>
<dom-if if="[[comment]]">
<template>
<div id="content" class="horizontal">
<nuxeo-user-avatar
user="[[comment.author]]"
height="[[_computeAvatarDimensions(level)]]"
width="[[_computeAvatarDimensions(level)]]"
border-radius="50"
font-size="[[_computeAvatarFontSize(level)]]"
>
</nuxeo-user-avatar>
<div class="info">
<div id="body">
<div id="header" class="horizontal">
<span class="author">[[comment.author]]</span>
<span class="smaller opaque"
>[[_computeDateLabel(comment, comment.creationDate, comment.modificationDate, i18n)]]</span
>
<dom-if if="[[_areExtendedOptionsAvailable(comment.author, currentUser)]]">
<template>
<paper-menu-button id="options" no-animations close-on-activate>
<paper-icon-button
class="main-option"
icon="more-vert"
slot="dropdown-trigger"
aria-label$="[[i18n('command.menu')]]"
>
</paper-icon-button>
<paper-listbox slot="dropdown-content">
<paper-icon-item name="edit" class="smaller no-selection" on-tap="_editComment">
<iron-icon icon="nuxeo:edit" slot="item-icon"></iron-icon>
<span>[[i18n('comments.options.edit')]]</span>
</paper-icon-item>
<paper-icon-item
name="delete"
class="smaller no-selection"
on-tap="_toggleDeletionConfirmation"
>
<iron-icon icon="nuxeo:delete" slot="item-icon"></iron-icon>
<span>[[i18n('comments.options.delete')]]</span>
</paper-icon-item>
</paper-listbox>
</paper-menu-button>
</template>
</dom-if>
</div>
<dom-if if="[[!editing]]">
<template>
<div id="view-area" class="text">
<span inner-h-t-m-l="[[_computeTextToDisplay(comment.text, maxChars, truncated)]]"></span>
<dom-if if="[[truncated]]">
<template>
<span class="smaller opaque pointer" on-tap="_showFullComment"
>[[i18n('comments.showAll')]]</span
>
</template>
</dom-if>
<dom-if if="[[!truncated]]">
<template>
<iron-icon
name="reply"
class="main-option opaque"
icon="reply"
on-tap="_reply"
hidden$="[[!_isRootElement(level)]]"
></iron-icon>
</template>
</dom-if>
</div>
</template>
</dom-if>
<dom-if if="[[editing]]">
<template>
<div class="input-area">
<paper-textarea
id="inputContainer"
placeholder="[[_computeTextLabel(level, 'writePlaceholder', null, i18n)]]"
value="{{text}}"
max-rows="[[_computeMaxRows()]]"
no-label-float
on-keydown="_checkForEnter"
>
</paper-textarea>
<dom-if if="[[!_isBlank(text)]]">
<template>
<iron-icon
id="submit"
name="submit"
class="main-option opaque"
icon="check"
on-tap="_submitComment"
></iron-icon>
<nuxeo-tooltip for="submit">[[i18n('comments.submit.tooltip')]]</nuxeo-tooltip>
<iron-icon
name="clear"
class="main-option opaque"
icon="clear"
on-tap="_clearInput"
></iron-icon>
</template>
</dom-if>
</div>
</template>
</dom-if>
<dom-if if="[[_isSummaryVisible(comment.expanded, comment.numberOfReplies)]]">
<template>
<div id="summary" class="horizontal smaller">
<span class="more-content pointer no-selection" on-tap="_expand"
>[[i18n('comments.numberOfReplies', comment.numberOfReplies)]]</span
>
<span class="separator opaque">•</span>
<span class="opaque"
>[[_computeDateLabel(comment, 'lastReplyDate', comment.lastReplyDate, i18n)]]</span
>
</div>
</template>
</dom-if>
</div>
<dom-if if="[[comment.expanded]]">
<template>
<nuxeo-document-comment-thread id="thread" uid="[[comment.id]]" level="[[_computeSubLevel(level)]]">
</nuxeo-document-comment-thread>
</template>
</dom-if>
</div>
</div>
</template>
</dom-if>
`;
}
static get is() {
return 'nuxeo-document-comment';
}
static get properties() {
return {
/**
* Document comment object.
*
* @type {Comment}
*/
comment: {
type: Object,
},
/** Level of depth for the comment. */
level: {
type: Number,
value: 1,
},
/**
* Whether comment's text is not totally displayed, showing only the first 256 characters.
* @see {@link maxChars} for more details.
*/
truncated: {
type: Boolean,
computed: '_computeTruncatedFlag(comment.showFull, comment.text, maxChars)',
},
/**
* Limit of characters for comment's text.
* When exceeded, the comment will be truncated and an option to "show all" content will be displayed.
*/
maxChars: {
type: Number,
readOnly: true,
value: 256,
},
/** Whether comment is being edited. */
editing: {
type: Boolean,
readOnly: true,
reflectToAttribute: true,
value: false,
},
};
}
/**
* Fired when the user confirms the deletion of a comment.
*
* @event delete-comment
* @param {string} commentId Comment's Unique Identifier.
*/
/**
* Fired when the user edits a comment.
*
* @event edit-comment
* @param {string} commentId Comment's Unique Identifier.
* @param {date} modificationDate Date when the comment was modified.
* @param {string} text New comment's text accordingly the edition made.
*/
/**
* Fired when some error occurred and the user needs to be notified.
*
* @event notify
* @param {string} message Informative message to be presented to the user.
*/
connectedCallback() {
super.connectedCallback();
this.addEventListener('number-of-replies', this._handleRepliesChange);
this.text = this.comment && this.comment.text;
}
disconnectedCallback() {
this.removeEventListener('number-of-replies', this._handleRepliesChange);
super.disconnectedCallback();
}
_checkForEnter(e) {
if (e.keyCode === 13 && e.ctrlKey && !this._isBlank(this.comment.text)) {
this._submitComment();
}
}
_clearInput() {
this._setEditing(false);
this.text = this.comment.text;
}
_deleteComment() {
this.$.commentRequest.data = {};
this.$.commentRequest
.remove()
.then(() => {
this.dispatchEvent(
new CustomEvent('delete-comment', {
composed: true,
bubbles: true,
detail: { commentId: this.comment.id },
}),
);
})
.catch((error) => {
if (error.status === 404) {
this.notify({ message: this._computeTextLabel(this.level, 'notFound') });
} else {
this.notify({ message: this._computeTextLabel(this.level, 'deletion.error') });
throw error;
}
});
}
_editComment() {
this._setEditing(true);
afterNextRender(this, function() {
this.$$('#inputContainer').focus();
});
}
_expand() {
this.set('comment.expanded', true);
}
_handleRepliesChange(event) {
const numberOfReplies = event.detail.total;
if (numberOfReplies === 0) {
this.set('comment.expanded', false);
}
this.set('comment.numberOfReplies', numberOfReplies);
event.stopPropagation();
}
_reply() {
if (!this.comment.expanded) {
this._expand();
}
afterNextRender(this, function() {
this.$$('#thread').focusInput();
});
}
_showFullComment() {
this.set('comment.showFull', true);
}
_submitComment(e) {
if (e) {
e.preventDefault();
}
this.$.commentRequest.data = {
'entity-type': 'comment',
parentId: this.comment.parentId,
text: this.$$('#inputContainer').value.trim(),
};
this.$.commentRequest
.put()
.then((response) => {
this.dispatchEvent(
new CustomEvent('edit-comment', {
composed: true,
bubbles: true,
detail: {
commentId: this.comment.id,
modificationDate: response.modificationDate,
text: response.text,
},
}),
);
this.text = response.text;
this.set('comment.modificationDate', response.modificationDate);
this.set('comment.text', response.text);
this._clearInput();
})
.catch((error) => {
if (error.status === 404) {
this.notify({ message: this._computeTextLabel(this.level, 'notFound') });
} else {
this.notify({ message: this._computeTextLabel(this.level, 'edition.error') });
throw error;
}
});
}
_toggleDeletionConfirmation() {
this.$.dialog.toggle();
}
_computeAvatarDimensions(level) {
return this._isRootElement(level) ? 24 : 20;
}
_computeAvatarFontSize(level) {
return this._isRootElement(level) ? 13 : 11;
}
_computeConfirmationLabel(replies) {
return this.i18n(`comments.deletion.dialog.message.${replies > 0 ? 'withReplies' : 'withoutReplies'}`);
}
_computeDateLabel(item, option) {
if (item) {
let date = this.formatDate(item.creationDate, 'relative');
if (option === 'lastReplyDate') {
date = this.formatDate(item.lastReplyDate, 'relative');
return this.i18n('comments.lastReply', date);
}
if (item.modificationDate) {
return this.i18n('comments.edited', date);
}
return date;
}
}
_computeMaxRows() {
const lineHeight = parseFloat(this.getComputedStyleValue('--nuxeo-comment-line-height'));
const maxHeight = parseFloat(this.getComputedStyleValue('--nuxeo-comment-max-height'));
return Math.round((Number.isNaN(maxHeight) ? 80 : maxHeight) / (Number.isNaN(lineHeight) ? 20 : lineHeight));
}
_computeSubLevel(level) {
return level + 1;
}
_computeTextLabel(level, option, placeholder) {
return level === 1
? this.i18n(`comments.${option}.comment`, placeholder)
: this.i18n(`comments.${option}.reply`, placeholder);
}
_computeTextToDisplay(text, maxChars, truncated) {
let parsedText = text;
if (truncated) {
parsedText = `${text.substring(0, maxChars - 1)}…`;
}
return parsedText;
}
_computeTruncatedFlag(showFull, text, limit) {
return !showFull && typeof text === 'string' && text.length > limit;
}
/** Visibility Methods * */
_areExtendedOptionsAvailable(author, currentUser) {
return (
currentUser &&
((currentUser.properties && currentUser.properties.username === author) || currentUser.isAdministrator)
);
}
_isBlank(text) {
return !text || typeof text !== 'string' || text.trim().length === 0;
}
_isRootElement(level) {
return level === 1;
}
_isSummaryVisible(expanded, total) {
return !expanded && total > 0;
}
} |
JavaScript | class ProfileSettingsFormComponent extends Component {
constructor(props) {
super(props);
this.uploadDelayTimeoutId = null;
this.state = { uploadDelay: false };
this.submittedValues = {};
}
componentDidUpdate(prevProps) {
// Upload delay is additional time window where Avatar is added to the DOM,
// but not yet visible (time to load image URL from srcset)
if (prevProps.uploadInProgress && !this.props.uploadInProgress) {
this.setState({ uploadDelay: true });
this.uploadDelayTimeoutId = window.setTimeout(() => {
this.setState({ uploadDelay: false });
}, UPLOAD_CHANGE_DELAY);
}
}
componentWillUnmount() {
window.clearTimeout(this.uploadDelayTimeoutId);
}
render() {
return (
<FinalForm
{...this.props}
render={fieldRenderProps => {
const {
className,
currentUser,
handleSubmit,
intl,
invalid,
onImageUpload,
pristine,
profileImage,
rootClassName,
updateInProgress,
updateProfileError,
uploadImageError,
uploadInProgress,
form,
values,
} = fieldRenderProps;
const user = ensureCurrentUser(currentUser);
const identity = v => v;
// First name
const firstNameLabel = intl.formatMessage({
id: 'ProfileSettingsForm.firstNameLabel',
});
const firstNamePlaceholder = intl.formatMessage({
id: 'ProfileSettingsForm.firstNamePlaceholder',
});
const firstNameRequiredMessage = intl.formatMessage({
id: 'ProfileSettingsForm.firstNameRequired',
});
const firstNameRequired = validators.required(firstNameRequiredMessage);
// Last name
const lastNameLabel = intl.formatMessage({
id: 'ProfileSettingsForm.lastNameLabel',
});
const lastNamePlaceholder = intl.formatMessage({
id: 'ProfileSettingsForm.lastNamePlaceholder',
});
const lastNameRequiredMessage = intl.formatMessage({
id: 'ProfileSettingsForm.lastNameRequired',
});
const lastNameRequired = validators.required(lastNameRequiredMessage);
// Bio
const bioLabel = intl.formatMessage({
id: 'ProfileSettingsForm.bioLabel',
});
const bioPlaceholder = intl.formatMessage({
id: 'ProfileSettingsForm.bioPlaceholder',
});
const titleRequiredMessage = intl.formatMessage({ id: 'EditListingLocationForm.address' });
const addressPlaceholderMessage = intl.formatMessage({
id: 'EditListingLocationForm.addressPlaceholder',
});
const addressRequiredMessage = intl.formatMessage({
id: 'EditListingLocationForm.addressRequired',
});
const addressNotRecognizedMessage = intl.formatMessage({
id: 'EditListingLocationForm.addressNotRecognized',
});
const optionalText = intl.formatMessage({
id: 'EditListingLocationForm.optionalText',
});
const buildingMessage = intl.formatMessage(
{ id: 'EditListingLocationForm.building' },
{ optionalText: optionalText }
);
const buildingPlaceholderMessage = intl.formatMessage({
id: 'EditListingLocationForm.buildingPlaceholder',
});
const uploadingOverlay =
uploadInProgress || this.state.uploadDelay ? (
<div className={css.uploadingImageOverlay}>
<IconSpinner />
</div>
) : null;
const hasUploadError = !!uploadImageError && !uploadInProgress;
const errorClasses = classNames({ [css.avatarUploadError]: hasUploadError });
const transientUserProfileImage = profileImage.uploadedImage || user.profileImage;
const transientUser = { ...user, profileImage: transientUserProfileImage };
// Ensure that file exists if imageFromFile is used
const fileExists = !!profileImage.file;
const fileUploadInProgress = uploadInProgress && fileExists;
const delayAfterUpload = profileImage.imageId && this.state.uploadDelay;
const imageFromFile =
fileExists && (fileUploadInProgress || delayAfterUpload) ? (
<ImageFromFile
id={profileImage.id}
className={errorClasses}
rootClassName={css.uploadingImage}
aspectRatioClassName={css.squareAspectRatio}
file={profileImage.file}
>
{uploadingOverlay}
</ImageFromFile>
) : null;
// Avatar is rendered in hidden during the upload delay
// Upload delay smoothes image change process:
// responsive img has time to load srcset stuff before it is shown to user.
const avatarClasses = classNames(errorClasses, css.avatar, {
[css.avatarInvisible]: this.state.uploadDelay,
});
const avatarComponent =
!fileUploadInProgress && profileImage.imageId ? (
<Avatar
className={avatarClasses}
renderSizes="(max-width: 767px) 96px, 240px"
user={transientUser}
disableProfileLink
/>
) : null;
const chooseAvatarLabel =
profileImage.imageId || fileUploadInProgress ? (
<div className={css.avatarContainer}>
{imageFromFile}
{avatarComponent}
<div className={css.changeAvatar}>
<FormattedMessage id="ProfileSettingsForm.changeAvatar" />
</div>
</div>
) : (
<div className={css.avatarPlaceholder}>
<div className={css.avatarPlaceholderText}>
<FormattedMessage id="ProfileSettingsForm.addYourProfilePicture" />
</div>
<div className={css.avatarPlaceholderTextMobile}>
<FormattedMessage id="ProfileSettingsForm.addYourProfilePictureMobile" />
</div>
</div>
);
const submitError = updateProfileError ? (
<div className={css.error}>
<FormattedMessage id="ProfileSettingsForm.updateProfileFailed" />
</div>
) : null;
const classes = classNames(rootClassName || css.root, className);
const submitInProgress = updateInProgress;
const submittedOnce = Object.keys(this.submittedValues).length > 0;
const pristineSinceLastSubmit = submittedOnce && isEqual(values, this.submittedValues);
const submitDisabled =
invalid || pristine || pristineSinceLastSubmit || uploadInProgress || submitInProgress;
const { LatLng } = sdkTypes;
// const lat = values.location.selectedPlace.origin.lat?values.location.selectedPlace.origin.lat: 51.5074;
// const lng = values.location.selectedPlace.origin.lng? values.location.selectedPlace.origin.lng: -0.1278;
// const orig= new LatLng(lat, lng)
// console.log('createdorigin', orig)
const geolocation = (values.location && values.location.selectedPlace && values.location.selectedPlace.origin)?values.location.selectedPlace.origin: new LatLng(51.5074, -0.1278);
const address =(values.location && values.location.selectedPlace && values.location.selectedPlace.address) ? values.location.selectedPlace.address.trim() : 'London, London';
const mapProps = config.maps.fuzzy.enabled
? { obfuscatedCenter: obfuscatedCoordinates(geolocation) }
: { address, center: obfuscatedCoordinates(geolocation) };
const map = <Map {...mapProps} useStaticMap={true} />;
return (
<Form
className={classes}
onSubmit={e => {
this.submittedValues = values;
handleSubmit(e);
}}
>
<div className={css.sectionContainer}>
<h3 className={css.sectionTitle}>
<FormattedMessage id="ProfileSettingsForm.yourProfilePicture" />
</h3>
<Field
accept={ACCEPT_IMAGES}
id="profileImage"
name="profileImage"
label={chooseAvatarLabel}
type="file"
form={null}
uploadImageError={uploadImageError}
disabled={uploadInProgress}
>
{fieldProps => {
const { accept, id, input, label, disabled, uploadImageError } = fieldProps;
const { name, type } = input;
const onChange = e => {
const file = e.target.files[0];
form.change(`profileImage`, file);
form.blur(`profileImage`);
if (file != null) {
const tempId = `${file.name}_${Date.now()}`;
onImageUpload({ id: tempId, file });
}
};
let error = null;
if (isUploadImageOverLimitError(uploadImageError)) {
error = (
<div className={css.error}>
<FormattedMessage id="ProfileSettingsForm.imageUploadFailedFileTooLarge" />
</div>
);
} else if (uploadImageError) {
error = (
<div className={css.error}>
<FormattedMessage id="ProfileSettingsForm.imageUploadFailed" />
</div>
);
}
return (
<div className={css.uploadAvatarWrapper}>
<label className={css.label} htmlFor={id}>
{label}
</label>
<input
accept={accept}
id={id}
name={name}
className={css.uploadAvatarInput}
disabled={disabled}
onChange={onChange}
type={type}
/>
{error}
</div>
);
}}
</Field>
<div className={css.tip}>
<FormattedMessage id="ProfileSettingsForm.tip" />
</div>
<div className={css.fileInfo}>
<FormattedMessage id="ProfileSettingsForm.fileInfo" />
</div>
</div>
<div className={css.sectionContainer}>
<h3 className={css.sectionTitle}>
<FormattedMessage id="ProfileSettingsForm.yourName" />
</h3>
<div className={css.nameContainer}>
<FieldTextInput
className={css.firstName}
type="text"
id="firstName"
name="firstName"
label={firstNameLabel}
placeholder={firstNamePlaceholder}
validate={firstNameRequired}
/>
<FieldTextInput
className={css.lastName}
type="text"
id="lastName"
name="lastName"
label={lastNameLabel}
placeholder={lastNamePlaceholder}
validate={lastNameRequired}
/>
</div>
</div>
<div className={classNames(css.sectionContainer, css.lastSection)}>
<h3 className={css.sectionTitle}>
<FormattedMessage id="ProfileSettingsForm.bioHeading" />
</h3>
<FieldTextInput
type="textarea"
id="bio"
name="bio"
label={bioLabel}
placeholder={bioPlaceholder}
/>
<p className={css.bioInfo}>
<FormattedMessage id="ProfileSettingsForm.bioInfo" />
</p>
</div>
{submitError}
<LocationAutocompleteInputField
className={css.locationAddress}
inputClassName={css.locationAutocompleteInput}
iconClassName={css.locationAutocompleteInputIcon}
predictionsClassName={css.predictionsRoot}
validClassName={css.validLocation}
autoFocus
name="location"
label={titleRequiredMessage}
placeholder={addressPlaceholderMessage}
useDefaultPredictions={false}
format={identity}
valueFromForm={values.location}
validate={composeValidators(
autocompleteSearchRequired(addressRequiredMessage),
autocompletePlaceSelected(addressNotRecognizedMessage)
)}
/>
<FieldTextInput
className={css.building}
type="text"
name="building"
id="building"
label={buildingMessage}
placeholder={buildingPlaceholderMessage}
/>
{
(values && values.location)?(<div className={css.map}>{map}</div>):(<div>{map}</div>)
}
{submitError}
<Button
className={css.submitButton}
type="submit"
inProgress={submitInProgress}
disabled={submitDisabled}
ready={pristineSinceLastSubmit}
>
<FormattedMessage id="ProfileSettingsForm.saveChanges" />
</Button>
</Form>
);
}}
/>
);
}
} |
JavaScript | class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
} |
JavaScript | class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parse_url(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parse_url(`${input}`);
}
input = {};
} else {
parsedURL = parse_url(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has('Content-Type')) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
} |
JavaScript | class ViewLeaderboardButton extends Component {
handleClick(event) {
event.preventDefault()
}
render () {
return (
<div className="navbar">
<button onClick={(event) => this.handleClick(event)} className="button"><NavLink className="link" to="/leaderboard">View Leaderboard</NavLink></button>
</div>
)
}
} |
JavaScript | class RawImageData {
/**
* Constructs a new image data container.
*
* @param {Number} [width=0] - The width of the image.
* @param {Number} [height=0] - The height of the image.
* @param {Uint8ClampedArray} [data=null] - The image data.
*/
constructor(width = 0, height = 0, data = null) {
/**
* The width of the image.
*
* @type {Number}
*/
this.width = width;
/**
* The height of the image.
*
* @type {Number}
*/
this.height = height;
/**
* The RGBA image data.
*
* @type {Uint8ClampedArray}
*/
this.data = data;
}
/**
* Creates a canvas from this image data.
*
* @return {Canvas} The canvas, or null if it couldn't be created.
*/
toCanvas() {
return (typeof document === "undefined") ? null : createCanvas(this.width, this.height, this.data);
}
/**
* Creates a new image data container.
*
* @param {ImageData|Image} image - An image or plain image data.
* @return {RawImageData} The image data.
*/
static from(image) {
const { width, height } = image;
let data;
if(image instanceof Image) {
const canvas = createCanvas(width, height, image);
if(canvas !== null) {
const context = canvas.getContext("2d");
data = context.getImageData(0, 0, width, height).data;
}
} else {
data = image.data;
}
return new RawImageData(width, height, data);
}
} |
JavaScript | class App2 extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div className = "box">
<div id = 'title'>{this.props.title}</div>
<div id = 'text'>{this.props.children}</div>
</div>
);
}
} |
JavaScript | class Registry {
/**
* Creates a new registry.
*/
constructor() {
/** @type {MutationObserver} */
this.observer = new MutationObserver(() => this.updateComponents());
/** @type {Array.<ComponentHandler>} */
this.handlers = [];
}
/**
* Registers a component in the registry.
* @param {string} cssClassName CSS class of elements to render the
* components into.
* @param {ComponentCtor} componentCtor The component constructor, which
* should be a subclass of `Component`.
* @param {Object=} options Options to pass to every component
* constructor.
* @return {Registry} The registry instance, for chaining.
*/
register(cssClassName, componentCtor, options=null) {
this.handlers.push(
new ComponentHandler(cssClassName, componentCtor, options || {}));
return this;
}
/**
* Starts the registry's DOM listener and renders any registered components.
* The registry then manages the lifecycle of components as elements enter and
* leave the DOM, initializing and destroying the components as necessary.
*/
run() {
this.updateComponents();
this.observer.observe(document.body, {
attributes: true,
attributeFilter: ['class'],
childList: true,
subtree: true,
});
}
/**
* Destroys the registry.
*/
destroy() {
this.handlers.forEach((handler) => handler.destroy());
this.handlers = [];
this.observer.disconnect();
}
/**
* Adds and removes all registered components depending on their state in the
* DOM.
*/
updateComponents() {
this.handlers.forEach((handler) => handler.updateComponents());
}
} |
JavaScript | class ComponentHandler {
/**
* Creates a new registration.
* @param {string} cssClassName
* @param {ComponentCtor} componentCtor
* @param {Object} options
*/
constructor(cssClassName, componentCtor, options) {
/**
* An active NodeList that matches the `cssClassName`.
* @type {NodeList}
*/
this.nodeList = document.getElementsByClassName(cssClassName);
/** @type {ComponentCtor} */
this.componentCtor = componentCtor;
/**
* Options object to pass to every component constructor.
* @type {Object}
*/
this.options = options;
/**
* A map of id => component.
* @type {Object<Component>}
*/
this.components = {};
/**
* The ID to assign to the component once it's created. This is used to keep
* track of components in `this.components` since the element itself is not
* hashable.
* @type {number}
* @private
*/
this.nextId_ = 1;
}
/**
* Adds and removes components depending on their state in the DOM.
*/
updateComponents() {
// Init new components.
const activeElements = new Set();
for (let i = 0, element; element = this.nodeList[i]; i++) {
if (!element.akId) {
const component = new this.componentCtor(element, this.options);
element.akId = this.nextId_++;
element.component = component;
component.init();
this.components[element.akId] = component;
}
activeElements.add(element.akId);
}
// Destroy any component no longer in the DOM.
Object.values(this.components)
.filter((component) => !activeElements.has(component.element.akId))
.forEach((component) => {
this.destroyComponent_(component);
});
}
/**
* Destroys all components managed by the handler.
*/
destroy() {
Object.values(this.components).forEach((component) => {
this.destroyComponent_(component);
});
// Remove the active NodeList object to free up memory.
this.nodeList = null;
this.components = null;
}
/**
* Destroys a component and unregisters the element from the handler.
* @param {Component} component
* @private
*/
destroyComponent_(component) {
delete this.components[component.element.akId];
component.element.akId = null;
component.element.akComponent = null;
component.destroy();
}
} |
JavaScript | class I18n {
constructor(app) {
this.app = app
this.translations = {}
}
/**
* Load translations from a set of plugins. The translations
* are expected to be packaged in `app_i18n_plugins.js`.
* @param {Object} plugins - References plugins to load i18n data for.
*/
loadPluginsI18n(plugins) {
for (const builtinPlugin of plugins.builtin) {
if (builtinPlugin.i18n) {
builtinPlugin.i18n.forEach((i) => {
this.app.__mergeDeep(this.translations, require(`${i}/src/js/i18n`))
})
}
if (builtinPlugin.addons && builtinPlugin.addons.i18n) {
builtinPlugin.addons.i18n.forEach((i) => {
this.app.__mergeDeep(this.translations, require(`${i}/src/js/i18n`))
})
}
}
for (const name of Object.keys(plugins.custom)) {
if (plugins.custom[name].parts.includes('i18n')) {
this.app.__mergeDeep(this.translations, require(`${plugins.custom[name].name}/src/js/i18n`))
}
}
}
} |
JavaScript | class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertLeft(value) {
this.left = new BinaryTreeNode(value);
return this.left;
}
insertRight(value) {
this.right = new BinaryTreeNode(value);
return this.right;
}
} |
JavaScript | class RoleConceptDetail extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.state = {
environment: ConfigLoader.getConfig('role.table.filter.environment', [])
};
}
componentDidMount() {
super.componentDidMount();
// We have to create concept from props here, because same instance this component
// could be used in past (in this case may be this.prosp and nextProps same)
this._initComponent(this.props);
}
getContentKey() {
return 'content.task.IdentityRoleConceptTable';
}
// @Deprecated - since V10 ... replaced by dynamic key in Route
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps && (
JSON.stringify(nextProps.entity) !== JSON.stringify(this.props.entity) ||
nextProps.isEdit !== this.props.isEdit ||
nextProps.multiAdd !== this.props.multiAdd
)) {
this._initComponent(nextProps);
}
}
getEavForm() {
return this.refs.eavForm;
}
getForm() {
return this.refs.form;
}
_initComponent(props) {
const entity = props.entity;
if (!entity) {
return;
}
const entityFormData = _.merge({}, entity, {
role: entity._embedded && entity._embedded.role ? entity._embedded.role : null
});
if (entityFormData.role && entityFormData.role.identityRoleAttributeDefinition) {
selectedRole = entityFormData.role;
selectedIdentityRole = entityFormData;
this.context.store.dispatch(roleManager.fetchAttributeFormDefinition(
entityFormData.role.id,
`${uiKeyRoleAttributeFormDefinition}-${entityFormData.role.id}`,
(json, error) => {
this.handleError(error);
}
));
if (selectedIdentityRole.id && selectedIdentityRole.operation !== 'ADD') {
// Form definition will be loaded from identityRole only if selectedIdentityRole is identity-role not concept
if (selectedIdentityRole.state === undefined) {
this.context.store.dispatch(identityRoleManager.fetchFormInstances(
selectedIdentityRole.id,
`${uiKeyIdentityRoleFormInstance}-${selectedIdentityRole.id}`,
(formInstances, error) => {
if (error) {
this.addErrorMessage({ hidden: true, level: 'info' }, error);
this.setState({ error });
}
}
));
}
} else {
selectedIdentityRole = null;
}
} else {
selectedRole = null;
selectedIdentityRole = null;
}
if (this.refs.role) {
this.refs.role.focus();
}
}
/**
* Pre-fill valid-from by contract validity
*/
_onChangeSelectOfContract(value) {
const entity = this.state && this.state.entity ? this.state.entity : this.props.entity;
let validFrom = value ? value.validFrom : null;
const now = moment().utc().valueOf();
if (validFrom && moment(validFrom).isBefore(now)) {
validFrom = now;
}
const entityFormData = _.merge({}, entity);
entityFormData.validFrom = validFrom;
entityFormData.identityContract = value;
if (this.refs.role) {
entityFormData.role = this.refs.role.getValue();
}
if (this.props.entity) {
this.setState({entity: entityFormData});
}
return true;
}
_onChangeSelectOfRole(value, originalValue) {
if (!_.isArray(originalValue) || originalValue.length === 1) {
selectedRole = _.isArray(originalValue) ? originalValue[0] : originalValue;
if (selectedRole.identityRoleAttributeDefinition) {
this.context.store.dispatch(
roleManager.fetchAttributeFormDefinition(selectedRole.id, `${uiKeyRoleAttributeFormDefinition}-${selectedRole.id}`, (json, error) => {
this.handleError(error);
})
);
}
} else {
selectedRole = null;
}
// TODO: move selectedRole, _identityRoleAttributeDefinition, _identityRoleFormInstance to state and get them directly from callback above
this.setState({ selectedRole });
//
return true;
}
_onEnvironmentChange(value) {
const codes = [];
if (value) {
if (_.isArray(value)) { // codelist is available - list of object
value.forEach(v => {
codes.push(v.value);
});
} else if (value.currentTarget) { // is event (~text field onchange)
codes.push(value.currentTarget.value);
}
}
//
this.setState({
environment: codes
});
}
render() {
const {
showLoading,
identityUsername,
readOnly,
_identityRoleAttributeDefinition,
_identityRoleFormInstance,
style,
isEdit,
multiAdd,
validationErrors,
showEnvironment
} = this.props;
const { environment } = this.state;
const entity = this.state.entity ? this.state.entity : this.props.entity;
if (!entity) {
return null;
}
const added = entity.operation === 'ADD';
let _formInstance = null;
let _showEAV = false;
if (selectedRole && selectedRole.identityRoleAttributeDefinition) {
_showEAV = true;
}
if (selectedRole && _identityRoleAttributeDefinition) {
if (entity
&& entity._eav
&& entity._eav.length === 1) {
_formInstance = new FormInstance(_identityRoleAttributeDefinition, entity._eav[0].values);
} else if (multiAdd) {
_formInstance = new FormInstance(_identityRoleAttributeDefinition, null);
}
}
if (!_formInstance && _identityRoleFormInstance && _identityRoleFormInstance.size === 1) {
_identityRoleFormInstance.forEach(instance => {
_formInstance = instance;
});
}
return (
<Basic.AbstractForm
ref="form"
data={ entity }
style={ style }
showLoading={ showLoading }
readOnly={ !isEdit || readOnly }>
<Advanced.CodeListSelect
code="environment"
hidden={!showEnvironment}
label={ this.i18n('entity.Role.environment.label') }
placeholder={ this.i18n('entity.Role.environment.help') }
multiSelect
onChange={ this._onEnvironmentChange.bind(this) }
rendered={ (!added || readOnly || !Utils.Entity.isNew(entity)) === false }
value={ environment }/>
<Advanced.RoleSelect
required
readOnly={ !added || readOnly || !Utils.Entity.isNew(entity)}
multiSelect={ added && multiAdd }
showActionButtons
header={ this.i18n('selectRoleCatalogue.header') }
onChange={ this._onChangeSelectOfRole.bind(this) }
label={ this.i18n('entity.IdentityRole.role') }
ref="role"
forceSearchParameters={ new SearchParameters('can-be-requested').setFilter('environment', environment) }/>
<Advanced.IdentityContractSelect
ref="identityContract"
manager={ identityContractManager }
forceSearchParameters={
new SearchParameters()
.setFilter('identity', identityUsername)
.setFilter('validNowOrInFuture', true)
.setFilter('_permission', 'CHANGEPERMISSION')
}
defaultSearchParameters={
new SearchParameters().clearSort()
}
pageSize={ 100 }
label={ this.i18n('entity.IdentityRole.identityContract.label') }
placeholder={ this.i18n('entity.IdentityRole.identityContract.placeholder') }
helpBlock={ this.i18n('entity.IdentityRole.identityContract.help') }
returnProperty={false}
readOnly={ !added || readOnly || !Utils.Entity.isNew(entity) }
onChange={ this._onChangeSelectOfContract.bind(this) }
niceLabel={ (contract) => identityContractManager.getNiceLabel(contract, false) }
required
useFirst
clearable={ false }/>
<Basic.LabelWrapper
label={ this.i18n('entity.IdentityRole.automaticRole.label') }
helpBlock={ this.i18n('entity.IdentityRole.automaticRole.help') }
rendered={ entity.automaticRole !== null }
hidden={ added }>
{ entity.automaticRole ? roleTreeNodeManager.getNiceLabel(entity._embedded.automaticRole) : null }
</Basic.LabelWrapper>
<Basic.Row>
<Basic.Col lg={ 6 }>
<Basic.DateTimePicker
mode="date"
className={entity.hasOwnProperty('_validFromChanged') ? 'text-danger' : null}
ref={entity.hasOwnProperty('_validFromChanged') ? '_validFromChanged' : 'validFrom'}
label={this.i18n('label.validFrom')}/>
</Basic.Col>
<Basic.Col lg={ 6 }>
<Basic.DateTimePicker
mode="date"
className={entity.hasOwnProperty('_validTillChanged') ? 'text-danger' : null}
ref={entity.hasOwnProperty('_validTillChanged') ? '_validTillChanged' : 'validTill'}
label={this.i18n('label.validTill')}/>
</Basic.Col>
</Basic.Row>
<Basic.Panel rendered={_showEAV} showLoading={!_formInstance} style={{border: '0px'}}>
<Basic.ContentHeader>
{this.i18n('identityRoleAttributes.header') }
</Basic.ContentHeader>
<Advanced.EavForm
ref="eavForm"
formInstance={ _formInstance }
readOnly={!isEdit || readOnly}
useDefaultValue={Utils.Entity.isNew(entity)}
validationErrors={ validationErrors }/>
</Basic.Panel>
</Basic.AbstractForm>
);
}
} |
JavaScript | class QR33 extends Component {
onSuccess(e) {
// alert(e.data);
this.props.navigation.navigate('TabloPage',{ name: e.data});
}
// async UNSAFE_componentWillMount() {
// try {
// const granted = await PermissionsAndroid.request(
// PermissionsAndroid.PERMISSIONS.CAMERA,
// {
// 'title': 'Cool Photo App Camera Permission',
// 'message': 'Cool Photo App needs access to your camera ' +
// 'so you can take awesome pictures.'
// }
// )
// if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// console.warn("You can use the camera")
// } else {
// console.warn("Camera permission denied")
// }
// } catch (err) {
// console.warn(err)
// }
componentDidMount() {
Orientation.lockToPortrait();
this.forceUpdate();
}
componentWillMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Homeindex');
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => {
this.props.navigation.openDrawer()}}
>
<Icon name="menu" />
</Button>
</Left>
<Body style = {{
justifyContent: "flex-end",
alignItems: "flex-end"}}>
<Title>QR</Title>
</Body>
</Header>
<View style={{flex : 1}}>
<QRCodeScanner
fadeIn={false}
reactivate={true}
reactivateTimeout={2000}
showMarker={true}
onRead={this.onSuccess.bind(this)}
topContent={
<Text style={styles.centerText}>
<Text style={styles.textBold}>اسکن کنید !</Text>
</Text>
}
bottomContent={
<Content>
<Left>
<Icon name="md-qr-scanner" />
</Left>
<Body>
<Text>
به سمت کد بگیرید
</Text>
</Body>
</Content>
}
/>
</View>
</Container>
);
}
} |
JavaScript | class Time {
/**
* A constant to represent "now" in a NPT scheme.
* @static
* @accessor
* @type {Number}
*/
static get NOW() {
return NOW
}
/**
* Creates a `Time` instance from input.
* @static
* @param {Number|String|Object|Time} arg
* @return {Time}
*/
static from(arg) {
if ('number' === typeof arg && !Number.isNaN(arg)) {
return new this(arg)
} else if ('string' === typeof arg) {
if ('now' === arg) {
return new this(NOW)
} else {
const parsed = parse(arg)
if (parsed) {
return new this(parsed/1000)
}
}
} else if (arg && 'number' === typeof arg.value) {
return new this(arg.value)
} else if (arg && ('hours' in arg || 'minutes' in arg || 'seconds' in arg)) {
return new this(getComputedSeconds(arg))
}
return new this(Number.NaN)
}
/**
* Creates a "now" `Time` instance.
* @static
* @return {Time}
*/
static now() {
return this.from(NOW)
}
/**
* `Time` class constructor.
* @private
* @param {Number} value
*/
constructor(value) {
this.value = value
}
/**
* `true` if the time value is the "now" constant.
* @accessor
* @type {Boolean}
*/
get isNow() {
return NOW === this.value
}
/**
* `true` if the time value is valid.
* @accessor
* @type {Boolean}
*/
get isValid() {
return false === Number.isNaN(this.value) && isFinite(+this.value)
}
/**
* Computed time values for this `Time` instance.
* @accessor
* @type {?Object}
*/
get computed() {
if (Number.isNaN(this.value) || null == this.value) {
return null
}
const computed = cache.get(this.value) || getComputedTime(this.value)
cache.set(this.value, computed)
return computed
}
/**
* Computed total number of hours this `Time` instance represents.
* @accessor
* @type {Number}
*/
get totalHours() {
return this.computed.totalHours
}
/**
* Computed total number of minutes this `Time` instance represents.
* @accessor
* @type {Number}
*/
get totalMinutes() {
return this.computed.totalMinutes
}
/**
* Computed total number of seconds this `Time` instance represents.
* @accessor
* @type {Number}
*/
get totalSeconds() {
return this.computed.totalSeconds
}
/**
* Computed total number of milliseconds this `Time` instance represents.
* @accessor
* @type {Number}
*/
get totalMilliseconds() {
return this.computed.totalMilliseconds
}
/**
* Computed number of hours this `Time` instance represents.
* @accessor
* @type {Number}
*/
get hours() {
return this.computed.hours
}
/**
* Computed number of minutes this `Time` instance represents.
* @accessor
* @type {Number}
*/
get minutes() {
return this.computed.minutes
}
/**
* Computed number of seconds this `Time` instance represents.
* @accessor
* @type {Number}
*/
get seconds() {
return this.computed.seconds
}
/**
* Computed number of milliseconds this `Time` instance represents.
* @accessor
* @type {Number}
*/
get milliseconds() {
return this.computed.milliseconds
}
/**
* Computed number of milliseconds this `Time` instance represents.
* @accessor
* @type {Number}
*/
get ms() {
return this.milliseconds
}
/**
* Set the time value for this instance.
* @param {Number|String|Object|Time} arg
*/
set(value) {
if (false === Number.isNaN(value) && null != value) {
const temp = this.constructor.from(value)
this.value = temp.value
}
}
/**
* Resets the value of this `Time` instance to `Number.NaN`.
*/
reset() {
this.value = Number.NaN
}
/**
* The integer value this `Time` instance represents.
* @return {Number}
*/
valueOf() {
return this.value
}
/**
* Converts this `Time` instance to an optionally formatted string.
* @param {?String} format
* @return {String}
* @example
* time.toString('hh:mm::ss') // default format, padded time
* time.toString('hh') // padded hours
* time.toString('mm') // padded minutes
* time.toString('ss') // padded seconds
* time.toString('H') // total hours, not padded
* time.toString('M') // total minutes, not padded
* time.toString('S') // total seconds, not padded
*/
toString(format) {
const { computed, value } = this
format = format || 'hh:mm:ss'
if (-1 === value) {
return 'now'
}
if (Number.isNaN(value)) {
return ''
}
return format
.replace('S', computed.totalSeconds)
.replace('M', computed.totalMinutes)
.replace('H', computed.totalHours)
.replace('hh', pad(2, computed.hours))
.replace('mm', pad(2, computed.minutes))
.replace('ss',
pad(2, computed.seconds) + (computed.ms ? `.${String(computed.ms/1000).slice(2)}` : '')
)
.replace('h', computed.hours)
.replace('m', computed.minutes)
.replace('s',
computed.seconds + (computed.ms ? `.${String(computed.ms/1000).slice(2)}` : '')
)
.replace(/(hh|mm|ss|H|M|S)(\:)?/g, '')
.trim()
function pad(n, s) {
return String(s).padStart(n, 0)
}
}
/**
* Converts this `Time` instance into a plain JSON object.
* @private
* @return {Object}
*/
/* istanbul ignore next */
toJSON() {
const { hours, minutes, seconds, milliseconds } = this
return { hours, minutes, seconds, milliseconds }
}
/**
* Implements `util.inspect.custom` symbol for pretty output.
* @private
* @return {String}
*/
/* istanbul ignore next */
[inspect.custom]() {
const formatted = this.toString('hh:mm:ss') || 'Invalid'
const { value } = this
const { name } = this.constructor
return `${name} (${formatted}) ${inspect({ value }, { colors: true })}`
}
} |
JavaScript | class Range {
/**
* Creates a `Range` instance from input.
* @static
* @param {Array<String>|Range|Object|String} ...args
* @return {Time}
*/
static from(...args) {
if (Array.isArray(args[0])) {
return new this(args[0][0], args[0][1])
} else if (args[0] && 'object' === typeof args[0]) {
return new this(args[0].start, args[0].stop)
} else if (1 === args.length) {
if ('string' === typeof args[0]) {
const [ start, stop ] = args[0].split('-')
return new this(start, stop)
} else {
return new this(args[0], null)
}
} else {
return new this(...args)
}
}
/**
* `Range` class constructor.
* @private
* @param {Time} start
* @param {Time} stop
*/
constructor(start, stop) {
this.start = Time.from()
this.stop = Time.from()
this.set(start, stop)
}
/**
* Set the start and stop time values for this range.
* @param {Number|String|Object|Time} start
* @param {?(Number|String|Object|Time)} stop
*/
set(start, stop) {
this.start.set(start)
if (stop) {
this.stop.set(stop)
if (this.stop < this.start) {
this.stop.set(Number.NaN)
}
} else if (null === stop) {
this.stop.reset()
}
}
/**
* Resets the start and stop `Time` instance.
*/
reset() {
this.start.reset()
this.stop.reset()
}
/**
* Converts this `Range` instance to an optionally formatted string.
* @param {?String} format
* @return {String}
*/
toString(format) {
const start = this.start.toString(format)
const stop = this.stop.toString(format)
if (start && stop && this.stop >= this.start) {
return `${start}-${stop}`
} else if (start) {
return `${start}-`
} else if (stop) {
return `-${stop}`
} else {
return ''
}
}
/**
* Converts this `Range` instance into a plain JSON object.
* @private
* @return {Object}
*/
/* istanbul ignore next */
toJSON() {
const { start, stop } = this
return { start, stop }
}
/**
* Implements `util.inspect.custom` symbol for pretty output.
* @private
* @return {String}
*/
/* istanbul ignore next */
[inspect.custom]() {
const { start, stop } = this
const { value } = this
const { name } = this.constructor
return `${name} (${start}-${stop}) ${inspect({ start, stop }, { colors: true })}`
}
} |
JavaScript | class Timecode extends Range {
/**
* Converts this `Timecode` instance to an integer value. This function will
* compute the difference in seconds between a start and stop timecode range
* if both were give, otherwise the timecode value as seconds is returned.
* @return {Number}
*/
valueOf() {
const { start, stop } = this
if (start.isNow) {
return Time.NOW
}
if (!start.value && stop.isNow) {
return Time.NOW
}
if (start < stop) {
return stop - start
}
return 0 + start
}
} |
JavaScript | class MotorJoint extends Joint {
constructor(bodyA, bodyB, anchor = bodyB.position, maxForce = 1000.0, maxTorque = 1000.0, frequency = 60, dampingRatio = 1.0, jointMass = -1) {
super(bodyA, bodyB, frequency, dampingRatio, jointMass);
this.linearImpulseSum = new Vector2();
this.angularImpulseSum = 0.0;
this.linearOffset = new Vector2();
this.initialAngleOffset = bodyB.rotation - bodyA.rotation;
this.angularOffset = 0.0;
this._maxForce = Util.clamp(maxForce, 0, Number.MAX_VALUE);
this._maxTorque = Util.clamp(maxTorque, 0, Number.MAX_VALUE);
;
this.localAnchorA = this.bodyA.globalToLocal.mulVector2(anchor, 1);
this.localAnchorB = this.bodyB.globalToLocal.mulVector2(anchor, 1);
this.drawConnectionLine = false;
}
prepare() {
// Calculate Jacobian J and effective mass M
// J = [-I, -skew(ra), I, skew(rb)] // Revolute
// [ 0, -1, 0, 1] // Angle
// M = (J · M^-1 · J^t)^-1
this.ra = this.bodyA.localToGlobal.mulVector2(this.localAnchorA, 0);
this.rb = this.bodyB.localToGlobal.mulVector2(this.localAnchorB, 0);
let k0 = new Matrix2();
k0.m00 = this.bodyA.inverseMass + this.bodyB.inverseMass +
this.bodyA.inverseInertia * this.ra.y * this.ra.y + this.bodyB.inverseInertia * this.rb.y * this.rb.y;
k0.m01 = -this.bodyA.inverseInertia * this.ra.y * this.ra.x - this.bodyB.inverseInertia * this.rb.y * this.rb.x;
k0.m10 = -this.bodyA.inverseInertia * this.ra.x * this.ra.y - this.bodyB.inverseInertia * this.rb.x * this.rb.y;
k0.m11 = this.bodyA.inverseMass + this.bodyB.inverseMass
+ this.bodyA.inverseInertia * this.ra.x * this.ra.x + this.bodyB.inverseInertia * this.rb.x * this.rb.x;
k0.m00 += this.gamma;
k0.m11 += this.gamma;
let k1 = (this.bodyA.inverseInertia + this.bodyB.inverseInertia + this.gamma);
this.m0 = k0.inverted();
this.m1 = 1.0 / k1;
let pa = this.bodyA.position.add(this.ra);
let pb = this.bodyB.position.add(this.rb);
let error0 = pb.sub(pa.add(this.linearOffset));
let error1 = this.bodyB.rotation - this.bodyA.rotation - this.initialAngleOffset - this.angularOffset;
if (Settings.positionCorrection) {
this.bias0 = new Vector2(error0.x, error0.y).mul(this.beta * Settings.inv_dt);
this.bias1 = error1 * this.beta * Settings.inv_dt;
}
else {
this.bias0 = new Vector2(0.0, 0.0);
this.bias1 = 0.0;
}
if (Settings.warmStarting)
this.applyImpulse(this.linearImpulseSum, this.angularImpulseSum);
}
solve() {
// Calculate corrective impulse: Pc
// Pc = J^t * λ (λ: lagrangian multiplier)
// λ = (J · M^-1 · J^t)^-1 ⋅ -(J·v+b)
let jv0 = this.bodyB.linearVelocity.add(Util.cross(this.bodyB.angularVelocity, this.rb))
.sub(this.bodyA.linearVelocity.add(Util.cross(this.bodyA.angularVelocity, this.ra)));
let jv1 = this.bodyB.angularVelocity - this.bodyA.angularVelocity;
let lambda0 = this.m0.mulVector(jv0.add(this.bias0).add(this.linearImpulseSum.mul(this.gamma)).inverted());
let lambda1 = this.m1 * -(jv1 + this.bias1 + this.angularImpulseSum * this.gamma);
// Clamp linear impulse
{
let maxLinearImpulse = Settings.dt * this._maxForce;
let oldLinearImpulse = this.linearImpulseSum.copy();
this.linearImpulseSum = this.linearImpulseSum.add(lambda0);
if (this.linearImpulseSum.length > maxLinearImpulse)
this.linearImpulseSum = this.linearImpulseSum.normalized().mul(maxLinearImpulse);
lambda0 = this.linearImpulseSum.sub(oldLinearImpulse);
}
// Clamp angular impulse
{
let maxAngularImpulse = Settings.dt * this._maxTorque;
let oldAngularImpulse = this.angularImpulseSum;
this.angularImpulseSum += lambda1;
this.angularImpulseSum = Util.clamp(this.angularImpulseSum, -maxAngularImpulse, maxAngularImpulse);
lambda1 = this.angularImpulseSum - oldAngularImpulse;
}
this.applyImpulse(lambda0, lambda1);
}
applyImpulse(lambda0, lambda1) {
// V2 = V2' + M^-1 ⋅ Pc
// Pc = J^t ⋅ λ
// Solve for point-to-point constraint
this.bodyA.linearVelocity = this.bodyA.linearVelocity.sub(lambda0.mul(this.bodyA.inverseMass));
this.bodyA.angularVelocity = this.bodyA.angularVelocity - this.bodyA.inverseInertia * this.ra.cross(lambda0);
this.bodyB.linearVelocity = this.bodyB.linearVelocity.add(lambda0.mul(this.bodyB.inverseMass));
this.bodyB.angularVelocity = this.bodyB.angularVelocity + this.bodyB.inverseInertia * this.rb.cross(lambda0);
// Solve for angle constraint
this.bodyA.angularVelocity = this.bodyA.angularVelocity - lambda1 * this.bodyA.inverseInertia;
this.bodyB.angularVelocity = this.bodyB.angularVelocity + lambda1 * this.bodyB.inverseInertia;
}
get maxForce() {
return this._maxForce;
}
set maxForce(maxForce) {
this._maxForce = Util.clamp(maxForce, 0, Number.MAX_VALUE);
}
get maxTorque() {
return this._maxTorque;
}
set maxTorque(maxTorque) {
this._maxTorque = Util.clamp(maxTorque, 0, Number.MAX_VALUE);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.