language
stringclasses 5
values | text
stringlengths 15
988k
|
|---|---|
JavaScript
|
class grupoEnController {
/*------------Guardar GrupoEn-----------------*/
guardarGrupoEn(req, res) {
var nombre = req.body.nombreG;
var descripcion = req.body.descripcion;
var external = req.body.enID;
var fotog = req.body.foto;
Entorno.findOne({ where: { external_id: external } }).then(function (entorno) {
GrupoEn.create({
nombre: nombre,
descripcion: descripcion,
foto: fotog,
id_entorno: entorno.id,
}).then(function (newGrupoEn, created) {
if (GrupoEn) {
GrupoEn_id = newGrupoEn.id;
res.redirect("/verEntornomiau/" + external);
}
});
});
}
/*------------ visualizar Grupos incio entorno-----------------*/
/**
* Este metodo me permite conocer los grupos del entorno
* Al hacer la consulta retorna un json
* @param {type} req
* @param {type} res
* @returns {undefined}
*/
cargarGrupoEn(req, res) {
var identorno = req.query.id;
console.log(identorno);
GrupoEn.findAll({
where: { id_entorno: identorno }
}).then(function (data) {
res.json(data);
});
}
/*------------ Editar Grupo -----------------*/
/**
* Este metodo me permite editar el nombre y descripcion
* a un grupo
*/
editarGrupoEn(req, res) {
var nombre = req.body.nombreG;
var descripcion = req.body.descripcion;
var external1 = req.body.exterEn;
var external = req.body.enID;
GrupoEn.findOne({ where: { external_id: external } }).then(function (data) {
data.nombre = nombre;
data.descripcion = descripcion,
data.save().then(function (ok) {
req.flash('success', 'Se ha modificado el grupo!');
res.redirect("/verEntornomiau/" + external1);
});
}).error(function (error) {
req.flash('error', 'Hubo un problema!');
res.redirect("/verEntornomiau/" + external1);
});
}
/*------------ visualizar Grupo editar-----------------*/
/**
* Este metodo me permite conocer el Grupo
* @param {type} req
* @param {type} res
* @returns {undefined}
*/
cargarGrupoEneditar(req, res) {
var external = req.params.external;
GrupoEn.findOne({ where: { external_id: external } }).then(function (dataEn) {
var id_ento = dataEn.id_entorno;
Entorno.findOne({ where: { id: id_ento } }).then(function (entorno) {
var id_per = entorno.id_persona;
Persona.findOne({ where: { id: id_per } }).then(function (persona) {
res.render('index', {
title: 'Moifica tu entorno',
fragmentos: "entorno/fr_modificar_grupo",
nombre: req.user.nombre,
idp: req.user.id,
foto: persona.foto,
nomEntor: entorno.nombre,
externalID: entorno.external_id,
nombregru: dataEn.nombre,
descrigru: dataEn.descripcion,
eternalGru: dataEn.external_id,
});
});
});
});
}
eliminarGrupoEn(req, res) {
var external = req.params.external;
var external1 = req.params.externalGrupo;
GrupoEn.destroy({ where: { external_id: external } }).then(function (dt) {
res.redirect("/verEntornomiau/" + external1);
})
}
/**
* Metodo permite guardar la imagen en la carpeta perfil
* Guarda el nombre de la imagen en la base de datos
* @param {type} req
* @param {type} res
* @returns {undefined}
*/
foto_GrupoEn(req, res) {
var form = new formidable.IncomingForm();
var external = req.params.externalFoto;
var external1 = req.params.externalGrupo;
form.parse(req, function (err, fields, files) {
if (files.archivo.size <= maxSize) {
console.log(files.archivo);
var extension = files.archivo.name.split(".").pop().toLowerCase();
if (extensiones.includes(extension)) {
var nombreFoto = uuid.v4() + "." + extension;
mv(files.archivo.path, "public/images/personasEn/" + nombreFoto,
function (err) {
if (err) {
console.log("ERROR");
req.flash('error', "Hubo un error " + err);
res.redirect("/verEntornomiau/" + external1);
} else {
GrupoEn.findAll({ where: { external_id: external } }).then(function (resultado) {
if (resultado.length > 0) {
console.log("Se Encontro Persona");
var grupoEn = resultado[0];
grupoEn.foto = nombreFoto;
grupoEn.save().then(function (save) {
console.log("Guardado");
fs.exists(files.archivo.path, function (exists) {
if (exists)
fs.unlinkSync(files.archivo.path);
});
req.flash('success', "Se ha la foto de grupo");
res.redirect("/verEntornomiau/" + external1);
});
}
});
}
});
} else {
console.log("ARCHIVO NO VALIDO");
req.flash('error', "El tipo de archivo no es valido, debe ser png, jpg, o gif");
res.redirect("/verEntornomiau/" + external1);
}
} else {
console.log("TAMAÑO SUPERA 1M");
req.flash('error', "El tamano no puede superar 1 MB");
res.redirect("/verEntornomiau/" + external1);
}
});
}
}
|
JavaScript
|
class MyStromLocalDiscovery extends EventEmitter {
/**
* Constructs a new MyStromLocalDiscovery.
*
* @param {string} listenAddress optional listen address. If undefined or '0.0.0.0', the discovery will be attempted on all addresses.
*/
constructor(listenAddress) {
super();
this.listenAddress = listenAddress;
this.socket = undefined;
}
/**
* Starts the UDP auto discovery process.
* If the discovery is already running the function simply returns.
*
* @event start
* @event discover
* @type {object}
* @property {string} id - MAC address as unique device identifier
* @property {string} ip - IP address
* @property {string} type - device type: see ../myStrom#DEVICE_TYPES
* @property {number} lastActivity - timestamp of last device access, initialized to current time
* @property {boolean} reachable - indicates if device is reachable, initialized to true
* @event error
*/
start() {
if (this.socket && this.socket._receiving === true) {
return;
}
this.socket = dgram.createSocket('udp4');
this.socket.bind(7979, this.listenAddress);
this.socket.on('listening', () => {
const address = this.socket.address();
logger.info(`[LocalDiscovery] Listening for myStrom UDP broadcast on ${address.address}:${address.port}`);
this.emit('start');
});
this.socket.on('close', () => this.emit('stop'));
this.socket.on('error', (err) => this.emit('error', err));
this.socket.on('message', (msg, rinfo) => {
if (rinfo.size !== 8) {
logger.warn('[LocalDiscovery] Ignoring invalid message of size: %d. Message:', rinfo.size, msg.toString('hex'));
return;
}
let mac = msg.slice(0, 6).toString('hex');
let deviceType = myStrom.DEVICE_ID_MAP.get(msg[6]);
//let flags = msg[7]; // to be reverse engineered! Unfortunately it's not the power state :(
this.emit('discover', { id: mac, ip: rinfo.address, type: deviceType, lastActivity: Date.now(), reachable: true });
});
}
/**
* Stops the auto discovery process if it is currently running.
*
* @event stop
*/
stop() {
if (this.socket) {
this.socket.close();
this.socket = undefined;
}
}
}
|
JavaScript
|
class ServiceManager {
/**
* Creates a new instance of {@link ServiceManager}.
*
* @public
*/
constructor() {
this._services = {}
}
/**
* Returns the {@link Service} being managed with the specified <code>name</code>.
*
* @param {String} name - the name of the {@link Service} to be returned
* @return {Service} The {@link Service} is being managed with <code>name</code>.
* @throws {Error} If no {@link Service} is being managed with <code>name</code>.
* @public
*/
getService(name) {
const service = this._services[name]
if (!service) {
throw new Error(`Service is not being managed with name: ${name}`)
}
return service
}
/**
* Sets the {@link Service} implementation to be managed for the specified <code>name</code> to the
* <code>service</code> provided.
*
* @param {String} name - the name of the {@link Service} to be managed with <code>name</code>
* @param {Service} service - the {@link Service} implementation to be managed
* @throws {Error} If a {@link Service} is already being managed with the same <code>name</code>.
* @public
*/
setService(name, service) {
if (this._services[name]) {
throw new Error(`Service is already managed with name: ${name}`)
}
if (service) {
this._services[name] = service
}
}
}
|
JavaScript
|
class IPv4FirewallRule {
/**
* Create a IPv4FirewallRule.
* @member {string} [firewallRuleName] The rule name.
* @member {string} [rangeStart] The start range of IPv4.
* @member {string} [rangeEnd] The end range of IPv4.
*/
constructor() {
}
/**
* Defines the metadata of IPv4FirewallRule
*
* @returns {object} metadata of IPv4FirewallRule
*
*/
mapper() {
return {
required: false,
serializedName: 'IPv4FirewallRule',
type: {
name: 'Composite',
className: 'IPv4FirewallRule',
modelProperties: {
firewallRuleName: {
required: false,
serializedName: 'firewallRuleName',
type: {
name: 'String'
}
},
rangeStart: {
required: false,
serializedName: 'rangeStart',
type: {
name: 'String'
}
},
rangeEnd: {
required: false,
serializedName: 'rangeEnd',
type: {
name: 'String'
}
}
}
}
};
}
}
|
JavaScript
|
class GaussianNoise extends Layer {
/**
* Creates a GaussianNoise layer
*
* @param {Object} [attrs] - layer config attributes
* @param {number} [attrs.stddev] - standard deviation of the noise distribution
*/
constructor(attrs = {}) {
super(attrs)
this.layerClass = 'GaussianNoise'
const { stddev = 0 } = attrs
this.stddev = stddev
}
/**
* Method for layer computational logic
*
* @param {Tensor} x
* @returns {Tensor}
*/
call(x) {
this.output = x
return this.output
}
}
|
JavaScript
|
class IsBetween extends Comparison {
/**
* @param {!string} propertyName Name of the context property to compare.
* @param {!number} lowerBoundary The lower bound of the range.
* @param {!number} upperBoundary The upper bound of the range.
*/
constructor(propertyName, lowerBoundary, upperBoundary) {
super('PropertyIsBetween', propertyName);
/**
* @type {!number}
*/
this.lowerBoundary = lowerBoundary;
/**
* @type {!number}
*/
this.upperBoundary = upperBoundary;
}
}
|
JavaScript
|
class SpaceShipWarping extends SpaceShipState {
/**
* Constructs warping state
*
* @param {SpaceShip} spaceShip Reference to spaceship this state is attached to
*/
constructor(spaceShip) {
super(spaceShip)
this.spaceShip.color = SPACESHIP_WARPING_COLOR
this.timer = SPACESHIP_TIME_TO_WARP
this.cooldownStep = SPACESHIP_WARP_COOLDOWN / SPACESHIP_TIME_TO_WARP
this.radius = WARP_RADIUS_START
this.radiusStep = (WARP_RADIUS_END - WARP_RADIUS_START) / SPACESHIP_TIME_TO_WARP
this.warpDestination = pickRandomLocation()
}
/**
* Procs timer on the state (called each game cycle)
*/
act() {
this.radius += this.radiusStep
this.spaceShip.warpCooldown += this.cooldownStep
if(this.timer > 0) {
this.timer -= 1
} else {
this.spaceShip.location = this.warpDestination
this.spaceShip.state = new SpaceShipInvincible(this.spaceShip)
this.spaceShip.color = SPACESHIP_COLOR
this.spaceShip.warpCooldown = SPACESHIP_WARP_COOLDOWN
}
}
/**
* Defines the behavior when spaceship is commanded to warp
*/
warp() {
// intentionally left blank
}
/**
* Defines the behavior when spaceship collides with @param object
*
* @param {GameObject} object Object which collided with spaceship
*/
handleCollision(object) {
if(this.spaceShip.lives > 1) {
this.spaceShip.lives -= 1
this.spaceShip.state = new SpaceShipInvincible(this.spaceShip)
this.spaceShip.color = SPACESHIP_COLOR
this.spaceShip.warpCooldown = SPACESHIP_WARP_COOLDOWN
} else {
this.spaceShip.state = new SpaceShipDead(this.spaceShip)
}
}
/**
* Renders additional assets associated with the state
*
* @param {CanvasRenderingContext2D} context Context to draw with
*/
render(context) {
context.save()
context.beginPath()
context.fillStyle = WARP_PORTAL_COLOR
context.arc(this.warpDestination.x, this.warpDestination.y,
this.radius, 0, 2 * Math.PI, true)
context.fill()
context.closePath()
context.beginPath()
context.fillStyle = 'black'
context.arc(this.warpDestination.x, this.warpDestination.y,
Math.max(0.0, this.radius - WARP_PORTAL_WIDTH), 0, 2 * Math.PI, true)
context.fill()
context.closePath()
context.restore()
}
}
|
JavaScript
|
class Share {
/**
* Only one object is passing to constructor
* Params:
* url {String} url to share
* title {String} site title
* image {String} image url
* description {String} site description
* metrics {Object} yandex metrics object (?)
* prefix {String} prefix for metrics goal
* @param {Object} params
*/
constructor(params) {
// assign params to context
Object.assign(this, params);
// set default prefix if not passed.
// Prefix for metrics goal prefix+name (ex. share_vk)
this.prefix = params.prefix || 'share_';
// popup params
this.width = 600;
this.height = 600;
// default value for canvas fix
this.isCanvas = params.isCanvas || false;
// default value for window open mode
this.mode = params.mode || '';
// library
this.library = params.library || 'vanilla';
}
/**
* sites data for generating link
* @return {Object}
*/
get sites() {
let list = {
'vk': {
'domain': 'https://vk.com/share.php?',
'params': {
'url': this.url,
'title': this.title,
'description': this.description,
},
},
'fb': {
'domain': 'https://www.facebook.com/sharer.php?',
'params': {
'u' : this.url,
}
},
'tw': {
'domain': 'https://twitter.com/share?',
'params': {
'text': this.description,
'url': this.url,
}
},
'ok': {
'domain': 'https://connect.ok.ru/offer?',
'params': {
'url' : this.url,
'title' : this.title,
'imageUrl' : this.image,
}
},
};
return list;
}
reachGoal(name) {
switch (this.library) {
case 'vanilla':
this.metrics(this.id, 'reachGoal', `${this.prefix}${name}`);
break;
case 'vue':
this.metrics.reachGoal(`${this.prefix}${name}`);
break;
case 'react':
this.metrics('reachGoal', `${this.prefix}${name}`);
break;
}
}
/**
* check if data for this site available
* @param {String} name site short name
* @return {Object} object with site data
*/
check(name) {
let site = this.sites[name];
if (!site || typeof site === 'undefined') {
throw new Error(`Wrong site (${name}). Available: ${Object.keys(this.sites).join(',')}`);
}
if (this.library === 'vanilla' && !this.id) {
throw new Error(`Choosen 'vanilla', please pass 'id'`);
}
const libs = ['vanilla', 'vue', 'react'];
if (!libs.includes(this.library)) {
throw new Error(`Wrong library (${this.library}. Available: ${Object.keys(libs).join(',')})`);
}
return site;
}
/**
* generating final share link
* you can use it like Share.create('vk')
* ⚠️ it only generate link, no metrics call
* @param {String} name site short name
* @return {String} final share link
*/
create(name) {
// check if valid site passed first
let site = this.check(name);
// generate params from object
let params = Object.entries(site.params)
.map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
.join('&');
// join domain and params
let shareLink = `${site.domain}${params}`;
return shareLink;
}
/**
* open share link in popup and call metrics
* @param {String} name site short name
*/
open(name) {
// check if valid site passed first
this.check(name);
// call metrics if ya.metrics object(?) passed
if (this.metrics) {
this.reachGoal(name);
}
// open popup
if (this.isCanvas) {
function OpenURL (url) {
let gameCanvas = document.getElementsByTagName('canvas')[0];
if (gameCanvas !== null) {
let endInteractFunction = function() {
window.open(url, this.mode, this.mode === '' ? `width=${this.width},height=${this.height}` : '');
gameCanvas.onmouseup = null;
gameCanvas.ontouchend = null;
}
gameCanvas.ontouchend = endInteractFunction;
gameCanvas.onmouseup = endInteractFunction;
}
}
OpenURL(this.create(name));
} else {
window.open(this.create(name), this.mode, this.mode === '' ? `width=${this.width},height=${this.height}` : '');
}
}
}
|
JavaScript
|
class BasePlugin {
/**
* Key for options passed to a plugin from the plugin manager
* @property {String}
*/
static options = '';
/**
* @constructor
*/
constructor(options = {}) {
assign(this, {
log: logger,
options
});
}
/**
* The setup hook is invoked after the coordinator initializes all
* of it's pieces. It is called with the client server, proxy
* server, socket API server, and the state store instance.
*
* @param {ClientServer} client - Client server instance
* @param {ProxyServer} proxy - Proxy server instance
* @param {SocketServer} sockets - Socket API server instance
* @param {Store} store - Coordinator state store
*/
setup(client, proxy, sockets, store) {}
/**
* The start hook is invoked before the coordinator starts any other
* pieces or launches browsers.
*
* @returns {Promise} should resolve after the plugin starts
*/
async start() {}
/**
* The stop hook is invoked after the coordinator has closed
* launched browsers and stopped all other pieces.
*
* @returns {Promise} should resolve after the plugin stops
*/
async stop() {}
}
|
JavaScript
|
class NavBar extends Component {
handleItemClick = (e, {id}) => {
this.setState({activeItem: id});
};
render() {
const activeItem = this.props.location.pathname;
return (
<Menu inverted borderless color='blue' id='main-menu'>
<Menu.Item className='nav-bar-desktop-item' id={ROUTER_PATH.CODING} as="span"
onClick={this.handleItemClick}>LEDR Monitor Progress</Menu.Item>
<Menu.Menu position="right">
<a href={ROUTER_PATH.LOGOUT}>
<Menu.Item className='nav-bar-desktop-item' id={ROUTER_PATH.LOGOUT} as="span"
active={activeItem === ROUTER_PATH.LOGOUT} onClick={this.handleItemClick}
link>Log Out</Menu.Item>
</a>
</Menu.Menu>
</Menu>
);
}
}
|
JavaScript
|
class Crashes {
/**
* Create a Crashes.
* @param {AppCenterClient} client Reference to the service client.
*/
constructor(client) {
this.client = client;
this._getAppVersions = _getAppVersions;
this._getHockeyAppCrashForwardingStatus = _getHockeyAppCrashForwardingStatus;
this._updateHockeyAppCrashForwarding = _updateHockeyAppCrashForwarding;
this._getAppCrashesInfo = _getAppCrashesInfo;
this._listSessionLogs = _listSessionLogs;
this._getCrashTextAttachmentContent = _getCrashTextAttachmentContent;
this._getCrashAttachmentLocation = _getCrashAttachmentLocation;
this._listAttachments = _listAttachments;
this._getStacktrace = _getStacktrace;
this._getRawCrashLocation = _getRawCrashLocation;
this._getNativeCrashDownload = _getNativeCrashDownload;
this._getNativeCrash = _getNativeCrash;
this._get = _get;
this._list = _list;
}
/**
* @summary Gets a list of application versions
*
* Gets a list of application versions
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getAppVersionsWithHttpOperationResponse(ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getAppVersions(ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Gets a list of application versions
*
* Gets a list of application versions
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Array} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {array} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getAppVersions(ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getAppVersions(ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getAppVersions(ownerName, appName, options, optionalCallback);
}
}
/**
* @summary Gets the state of HockeyApp Crash forwarding for SxS apps
*
* Gets the state of HockeyApp Crash forwarding for SxS apps
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HockeyAppCrashForwardingInfo>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getHockeyAppCrashForwardingStatusWithHttpOperationResponse(ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getHockeyAppCrashForwardingStatus(ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Gets the state of HockeyApp Crash forwarding for SxS apps
*
* Gets the state of HockeyApp Crash forwarding for SxS apps
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {HockeyAppCrashForwardingInfo} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link HockeyAppCrashForwardingInfo} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getHockeyAppCrashForwardingStatus(ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getHockeyAppCrashForwardingStatus(ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getHockeyAppCrashForwardingStatus(ownerName, appName, options, optionalCallback);
}
}
/**
* @summary Enable HockeyApp crash forwarding for SxS apps
*
* Enable HockeyApp crash forwarding for SxS apps
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.enableForwarding]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<HockeyAppCrashForwardingInfo>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
updateHockeyAppCrashForwardingWithHttpOperationResponse(ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._updateHockeyAppCrashForwarding(ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Enable HockeyApp crash forwarding for SxS apps
*
* Enable HockeyApp crash forwarding for SxS apps
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.enableForwarding]
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {HockeyAppCrashForwardingInfo} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link HockeyAppCrashForwardingInfo} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
updateHockeyAppCrashForwarding(ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._updateHockeyAppCrashForwarding(ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._updateHockeyAppCrashForwarding(ownerName, appName, options, optionalCallback);
}
}
/**
* @summary Gets whether the application has any crashes
*
* Gets whether the application has any crashes
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AppCrashesInfo>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getAppCrashesInfoWithHttpOperationResponse(ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getAppCrashesInfo(ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Gets whether the application has any crashes
*
* Gets whether the application has any crashes
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {AppCrashesInfo} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link AppCrashesInfo} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getAppCrashesInfo(ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getAppCrashesInfo(ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getAppCrashesInfo(ownerName, appName, options, optionalCallback);
}
}
/**
* Get session logs by crash ID
*
* @param {string} crashId The id of the a crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<GenericLogContainer>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listSessionLogsWithHttpOperationResponse(crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._listSessionLogs(crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Get session logs by crash ID
*
* @param {string} crashId The id of the a crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {GenericLogContainer} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link GenericLogContainer} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
listSessionLogs(crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._listSessionLogs(crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._listSessionLogs(crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets content of the text attachment
*
* @param {string} crashId id of a specific crash
*
* @param {string} attachmentId attachment id
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<String>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getCrashTextAttachmentContentWithHttpOperationResponse(crashId, attachmentId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getCrashTextAttachmentContent(crashId, attachmentId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets content of the text attachment
*
* @param {string} crashId id of a specific crash
*
* @param {string} attachmentId attachment id
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {String} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {string} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getCrashTextAttachmentContent(crashId, attachmentId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getCrashTextAttachmentContent(crashId, attachmentId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getCrashTextAttachmentContent(crashId, attachmentId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets the URI location to download crash attachment
*
* @param {string} crashId id of a specific crash
*
* @param {string} attachmentId attachment id
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CrashAttachmentLocation>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getCrashAttachmentLocationWithHttpOperationResponse(crashId, attachmentId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getCrashAttachmentLocation(crashId, attachmentId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets the URI location to download crash attachment
*
* @param {string} crashId id of a specific crash
*
* @param {string} attachmentId attachment id
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CrashAttachmentLocation} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CrashAttachmentLocation} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getCrashAttachmentLocation(crashId, attachmentId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getCrashAttachmentLocation(crashId, attachmentId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getCrashAttachmentLocation(crashId, attachmentId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets all attachments for a specific crash
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listAttachmentsWithHttpOperationResponse(crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._listAttachments(crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets all attachments for a specific crash
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Array} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {array} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
listAttachments(crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._listAttachments(crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._listAttachments(crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets a stacktrace for a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.groupingOnly] true if the stacktrace should be
* only the relevant thread / exception. Default is false
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Stacktrace>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getStacktraceWithHttpOperationResponse(crashGroupId, crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getStacktrace(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets a stacktrace for a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.groupingOnly] true if the stacktrace should be
* only the relevant thread / exception. Default is false
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Stacktrace} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Stacktrace} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getStacktrace(crashGroupId, crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getStacktrace(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getStacktrace(crashGroupId, crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets the URI location to download json of a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CrashRawLocation>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getRawCrashLocationWithHttpOperationResponse(crashGroupId, crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getRawCrashLocation(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets the URI location to download json of a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CrashRawLocation} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CrashRawLocation} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getRawCrashLocation(crashGroupId, crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getRawCrashLocation(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getRawCrashLocation(crashGroupId, crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* @summary Gets the native log of a specific crash as a text attachment
*
* Gets the native log of a specific crash as a text attachment
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<String>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getNativeCrashDownloadWithHttpOperationResponse(crashGroupId, crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getNativeCrashDownload(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Gets the native log of a specific crash as a text attachment
*
* Gets the native log of a specific crash as a text attachment
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {String} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {string} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getNativeCrashDownload(crashGroupId, crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getNativeCrashDownload(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getNativeCrashDownload(crashGroupId, crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* @summary Gets the native log of a specific crash
*
* Gets the native log of a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<String>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getNativeCrashWithHttpOperationResponse(crashGroupId, crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getNativeCrash(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Gets the native log of a specific crash
*
* Gets the native log of a specific crash
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {String} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {string} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getNativeCrash(crashGroupId, crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getNativeCrash(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getNativeCrash(crashGroupId, crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets a specific crash for an app
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.includeReport] true if the crash should include
* the raw crash report. Default is false
*
* @param {boolean} [options.includeLog] true if the crash should include the
* custom log report. Default is false
*
* @param {boolean} [options.includeDetails] true if the crash should include
* in depth crash details
*
* @param {boolean} [options.includeStacktrace] true if the crash should
* include the stacktrace information
*
* @param {boolean} [options.groupingOnly] true if the stacktrace should be
* only the relevant thread / exception. Default is false
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Crash>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getWithHttpOperationResponse(crashGroupId, crashId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._get(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets a specific crash for an app
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} crashId id of a specific crash
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.includeReport] true if the crash should include
* the raw crash report. Default is false
*
* @param {boolean} [options.includeLog] true if the crash should include the
* custom log report. Default is false
*
* @param {boolean} [options.includeDetails] true if the crash should include
* in depth crash details
*
* @param {boolean} [options.includeStacktrace] true if the crash should
* include the stacktrace information
*
* @param {boolean} [options.groupingOnly] true if the stacktrace should be
* only the relevant thread / exception. Default is false
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Crash} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link Crash} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
get(crashGroupId, crashId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._get(crashGroupId, crashId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._get(crashGroupId, crashId, ownerName, appName, options, optionalCallback);
}
}
/**
* Gets all crashes of a group
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.includeReport] true if the crash should include
* the raw crash report. Default is false
*
* @param {boolean} [options.includeLog] true if the crash should include the
* custom log report. Default is false
*
* @param {date} [options.dateFrom]
*
* @param {date} [options.dateTo]
*
* @param {string} [options.appVersion] version
*
* @param {string} [options.errorType] Possible values include:
* 'CrashingErrors', 'HandledErrors'
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listWithHttpOperationResponse(crashGroupId, ownerName, appName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._list(crashGroupId, ownerName, appName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Gets all crashes of a group
*
* @param {string} crashGroupId id of a specific group
*
* @param {string} ownerName The name of the owner
*
* @param {string} appName The name of the application
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.includeReport] true if the crash should include
* the raw crash report. Default is false
*
* @param {boolean} [options.includeLog] true if the crash should include the
* custom log report. Default is false
*
* @param {date} [options.dateFrom]
*
* @param {date} [options.dateTo]
*
* @param {string} [options.appVersion] version
*
* @param {string} [options.errorType] Possible values include:
* 'CrashingErrors', 'HandledErrors'
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {Array} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {array} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
list(crashGroupId, ownerName, appName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._list(crashGroupId, ownerName, appName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._list(crashGroupId, ownerName, appName, options, optionalCallback);
}
}
}
|
JavaScript
|
class Display {
constructor(config, criterias) {
this.dispositionPath = config.defaultPath;
this.defaultProfileUrl = config.defaultProfileUrl;
this.criterias = criterias;
}
new(data, dispositionPath) {
this.dispositionPath = dispositionPath ? dispositionPath : this.dispositionPath;
const displayContent = document.getElementById("display-content");
UI.emptyElementContent(displayContent);
if (data.length > 0) {
const mainWindow = createWindow(data, this.criterias, this.dispositionPath, this.defaultProfileUrl, "home");
mainWindow.htmlElement.querySelector(".overview").id = "home";
document.getElementById("display-content").appendChild(mainWindow.htmlElement);
document.querySelectorAll(".window-title").forEach(
(title) => setFontSizeToHeight(title)
);
// Wait until images are loaded
setTimeout(() => {
document.querySelectorAll(".practitioner-name").forEach(
(practitionerName) => optimizeTextSize(practitionerName)
);
}, 1000);
return mainWindow;
}
else {
const errorMessage = document.createElement("p");
errorMessage.id = "error-message";
errorMessage.innerText = "Aucun praticien ne correspond à votre recherche...";
displayContent.appendChild(errorMessage);
}
}
}
|
JavaScript
|
class Test {
static methods() {
return Object.getOwnPropertyNames(this.prototype).filter(
method => method !== "constructor" && !method.startsWith("_")
);
}
list() {
return {
id: 'l',
name: 'list'
}
}
create() {
return {
id: 'c',
name: 'create'
}
}
}
|
JavaScript
|
class Encryptor {
constructor(encKey, algorithm = 'AES-128-CBC') {
if (!encKey) {
throw new Exceptions_1.RuntimeException('Application key is necessary for encryption.');
}
if (!Encryptor.supported(encKey, algorithm)) {
throw new Exceptions_1.RuntimeException(`The encryption algorithm '${algorithm}' is not supported or the encryption key used doesn't match the required length.`, 'E_UNSUPPORTED_ALGORITHM');
}
this.encKey = encKey;
this.algorithm = algorithm.toLowerCase();
}
static supported(encKey, algorithm) {
return algorithm.toLowerCase() in Encryptor.supportedAlgos && encKey.length === Encryptor.supportedAlgos[algorithm.toLowerCase()];
}
static generateKey(algorithm) {
return randomstring.generate(Encryptor.supportedAlgos[algorithm]);
}
encrypt(value, encoding = 'utf8') {
if (!value) {
throw new Exceptions_1.InvalidArgumentException('Missing argument to encrypt.', 'E_MISSING_PARAMETER');
}
const iv = crypto.randomBytes(Encryptor.supportedAlgos[this.algorithm]);
const cipher = crypto.createCipheriv(this.algorithm, this.encKey, iv);
value = cipher.update(value, encoding, 'base64');
value += cipher.final('base64');
// Once we have the encrypted value we will go ahead base64 encode the input
// vector and create the MAC for the encrypted value so we can verify its
// authenticity. Then, we'll JSON encode the data in a "payload" array.
const ivStr = Encryptor.base64Encode(iv);
const mac = this.hash(ivStr, value);
const json = JSON.stringify({ iv: ivStr, value: value, mac: mac });
return Encryptor.base64Encode(json);
}
decrypt(value, encoding = 'utf8') {
let payload;
try {
payload = JSON.parse(Encryptor.base64Decode(value).toString());
}
catch (error) {
throw new InvalidDecryptionPayloadException('Could not parse payload object.');
}
const ret = ['iv', 'value', 'mac'].every((a) => {
return Object.keys(payload).includes(a);
});
if (!(0, util_1.isObject)(payload) || !ret || Encryptor.base64Decode(payload['iv'], true).length != Encryptor.supportedAlgos[this.algorithm]) {
throw new InvalidDecryptionPayloadException('The payload is not valid.');
}
// check MAC from the payload
const mac_key = Encryptor.generateKey(this.algorithm);
const calculated = crypto.createHmac('sha256', mac_key).update(this.hash(payload.iv, payload.value)).digest();
if (!crypto.timingSafeEqual(crypto.createHmac('sha256', mac_key).update(payload.mac).digest(), calculated)) {
throw new InvalidDecryptionPayloadException('The MAC is invalid.');
}
const iv = Encryptor.base64Decode(payload.iv, true);
const decipher = crypto.createDecipheriv(this.algorithm, this.encKey, iv);
let decrypted = decipher.update(payload.value, 'base64', encoding);
decrypted += decipher.final(encoding);
return decrypted;
}
hash(iv, value) {
return crypto.createHmac('sha256', this.encKey).update(iv + value).digest('hex');
}
static base64Encode(unencoded) {
return Buffer.from(unencoded).toString('base64');
}
static base64Decode(encoded, raw) {
if (raw) {
return Buffer.from(encoded, 'base64');
}
return Buffer.from(encoded, 'base64').toString('utf8');
}
}
|
JavaScript
|
class UsageRecordStatus {
/**
* Create a UsageRecordStatus.
* @property {boolean} [expectedLatestBuildExists] Is the age of the most
* recent Build service usage record within expected limits
* @property {boolean} [expectedLatestTestExists] Is the age of the most
* recent Test service usage record within expected limits
* @property {string} [latestBuildUsageRecordTime] The time of the most
* recent Build service usage record
* @property {string} [latestTestUsageRecordTime] The time of the most recent
* Test service usage record
*/
constructor() {
}
/**
* Defines the metadata of UsageRecordStatus
*
* @returns {object} metadata of UsageRecordStatus
*
*/
mapper() {
return {
required: false,
serializedName: 'UsageRecordStatus',
type: {
name: 'Composite',
className: 'UsageRecordStatus',
modelProperties: {
expectedLatestBuildExists: {
required: false,
serializedName: 'expectedLatestBuildExists',
type: {
name: 'Boolean'
}
},
expectedLatestTestExists: {
required: false,
serializedName: 'expectedLatestTestExists',
type: {
name: 'Boolean'
}
},
latestBuildUsageRecordTime: {
required: false,
serializedName: 'latestBuildUsageRecordTime',
type: {
name: 'String'
}
},
latestTestUsageRecordTime: {
required: false,
serializedName: 'latestTestUsageRecordTime',
type: {
name: 'String'
}
}
}
}
};
}
}
|
JavaScript
|
class InputQueue {
/**
* Constructs the object.
*/
constructor() {
this.size = 0;
this.queue = [];
this.entryPoints = [];
}
at(idx) {
if (idx < 0 || (idx > (this.size - 1))) {
throw Error('Invalid value of `idx` ' + idx);
}
return this.queue[idx];
}
/**
* Determines if a given path is already covered by the items we have in our queue.
* Please note that we take into consideration the scores of the coverages
* !One more thing! The {path} param is of type `Converage`, while the items in this queue are of type QueueObject
*
* @param {Coverage} path The path to check whether it is covered.
* @return {boolean} True iff covered.
*/
isCovered(path) {
for (let qObj of this.queue) {
if (path.isSubset(qObj.path)) {
return true;
}
}
return false;
}
/**
* Adds an item to the queue
*
* @param {QueueObject} new_input The object to add to the queue
*/
enqueue(new_input) {
if (new_input) {
this.queue.push(new_input);
++this.size;
}
}
dequeue() {
throw Error('This method should never be called! Only the shrinking mechanism should delete item from the queue!');
}
/**
* Helper function. Returns the QueueObject with the bigger score.
*
* @param {QueueObject} queueObj1 QueueObject object
* @param {QueueObject} queueObj2 QueueObject object
* @return {QueueObject} The QueueObject with the bigger score.
*/
_maxScoreCallback(queueObj1, queueObj2) {
let accScore = queueObj1.path.getScore() / queueObj1.inputsSequence.size;
let curScore = queueObj2.path.getScore() / queueObj2.inputsSequence.size;
if (accScore === curScore) { // if the scores are the same, we take the path with the better coverage
// return [queueObj1, queueObj2].randomItem();
return (queueObj1.path.getCoveragePercentage() > queueObj2.path.getCoveragePercentage()) ? queueObj1 : queueObj2;
}
return (accScore > curScore) ? queueObj1 : queueObj2;
}
/**
* Retrieves the QueueItem with the best score
*
* @return {QueueItem} Item from the queue with the best score
*/
dequeue_best() {
/// TODO: think of uncommenting this code
// let weightFunc = (qObj) => {
// if (!qObj || !qObj.inputsSequence) {
// return 0;
// }
// let gisWithBody = qObj.inputsSequence
// .filter(genInput => genInput && genInput.bodyVal && genInput.bodyVal.value);
// let res = 0;
// if (gisWithBody && gisWithBody.length > 0) {
// // we prefer gis's with body
// let res = gisWithBody.map(genInput => Object.keys(genInput.bodyVal.value).length ? 1 : 0).sum() / qObj.inputsSequence.size;
// // console.log('res:', res);
// return res;
// } else {
// res = Math.random() / 2;
// }
// return res;
// }
switch (this.size) {
case 0:
return null;
case 1:
return this.queue[0];
}
// let epsList = this.queue.map(qObj => qObj.getEntryPoints()).flatten().getUniqByCmpFunc(ep => ep.entryName);
// if (!epsList) {
// throw Error('Entry points list is not valid');
// }
// let chosenEP = epsList.randomItem();
// if (!chosenEP) {
// throw Error('Invalid chosen entry point');
// }
// let qObjsMatchingEP = this.queue.filter(qObj =>
// qObj.inputsSequence.some(gi => gi.entryPoint.eq(chosenEP)));
// return qObjsMatchingEP.randomItem();
// return this.queue.randomItem();
// return this.queue.weightedRandomItem(weightFunc);
let randomNum = Math.random();
return randomNum > 0.8 ? this.queue.reduce(this._maxScoreCallback) : this.queue.randomItem();
}
/**
* Returns a string representation of the object.
*
* @return {string} String representation of the object.
*/
toString() {
var outStr = '';
for (var obj of this.queue) {
outStr += obj.toString() + '\n';
}
return outStr;
}
/**
* Helper function. Retrieves the QueueObject with the best score for the given tuple index.
*
* @param {int} tupleIdx Index of the entry in the path we would like to be set
* @return {QueueObject} QueueObject with the entry at {tupleIdx} set and the maximal score.
*/
_findBestEntryForTuple(tupleIdx) {
if (tupleIdx < 0) {
throw Error('Tuple index should be a non-negative number');
} else if (tupleIdx > Path.MAX_COVERAGE_SIZE - 1) {
throw Error('Tuple index should be at most ' + (Path.MAX_COVERAGE_SIZE));
}
// A small optimization - if we have only a single item in the queue, it's always the best (and worst) one
if (1 == this.size) {
return this.queue[0];
}
let ret = this.queue
.filter(queueObj => (queueObj.path.coverage[tupleIdx] !== 0) && (!queueObj._isInTmpWorkingSet));
if (ret.length !== 0) {
// return ret.randomItem();
return ret.reduce(this._maxScoreCallback, ret[0]);
} else {
return null;
}
}
/**
* Determines if all items in list are in the working set.
*
* @return {boolean} True iff all items are in the working set.
*/
_isAllInWorkingSet() {
return this.size === this.queue.filter(item => item._isInTmpWorkingSet).length;
}
/**
* Reduces the size of the queue by removing redundant coverages
* The actual algorithm explained in the code below (it's pretty self explanatory),
* and in the AFL whitepaper here: http://lcamtuf.coredump.cx/afl/technical_details.txt
* in section `4) Culling the corpus`
*/
shrinkQueue() {
if (this.size < config.inputQueue.SHRINK_THRSHOLD) {
return;
}
logger.info('Size before: ' + this.size);
this.queue.forEach(item => {
item._isInTmpWorkingSet = false;
});
let workingSetSize = Path.MAX_COVERAGE_SIZE;
// `Working set` as stated here:
// http://lcamtuf.coredump.cx/afl/technical_details.txt
// in section 4) Culling the corpus
//
// from Buffer docs: If {fill} is undefined, the Buffer will be zero-filled.
let workingSet = new Uint8Array(workingSetSize);
let isAnythingInWorkingSet = false;
for (let i = 0;
(i < workingSetSize) && (-1 !== workingSetSize) && !this._isAllInWorkingSet();) {
let bestEntryForTuple = this._findBestEntryForTuple(i);
if (bestEntryForTuple) {
bestEntryForTuple._isInTmpWorkingSet = true;
workingSet.or(bestEntryForTuple.path.coverage);
// find next index where workingSet[i] == 0
let nextI = workingSet.indexOf(0, i /*fromIndex*/ );
// console.log('nextI:', nextI, 'num of items in WS:', this.queue.filter(qObj => qObj._isInTmpWorkingSet).length);
if (-1 === nextI) {
break;
} else {
i = nextI;
isAnythingInWorkingSet = true;
}
} else {
++i;
}
}
// remove all items in queue that are not in the working set
if (!isAnythingInWorkingSet) {
let randomIdx = Math.randomInt(this.size);
this.queue = this.queue.filter((qObj, index) => qObj.inputsSequence.isFromUserInput || index === randomIdx);
} else {
this.queue = this.queue.filter(qObj => qObj._isInTmpWorkingSet || qObj.inputsSequence.isFromUserInput);
}
this.size = this.queue.length;
logger.info('Size after: ' + this.size);
}
}
|
JavaScript
|
class Utils {
/**
* Creates a new utilities class by either using the already initialized
* `window.app.data` [Data]{@link Data} object or by creating a new
* [Data]{@link Data} object.
*/
constructor() {
this.data = window.app ? window.app.data || new Data() : new Data();
}
/**
* Converts a timestring into a `Date` assuming that the day was today. If
* the time was a period (i.e. not actually one of `window.app.data
* .timeStrings`), this method defaults to returning `now`.
* @param {string} timestring - The time string to convert (e.g. '2:45 PM').
* @return {Date} The time string in date format (assuming that it was
* today).
*/
static timestringToDate(timestring) {
const now = new Date();
if (window.app.data.timeStrings.indexOf(timestring) < 0) return now;
const parts = timestring.split(':');
const min = new Number(parts[1].split(' ')[0]);
const ampm = parts[1].split(' ')[1];
const hour = new Number(parts[0]);
now.setHours(ampm === 'PM' ? hour + 12 : hour);
now.setMinutes(min);
now.setSeconds(0);
return now;
}
/**
* Converts a date into a timestring.
* @param {Date} date - The date to convert.
* @return {string} The date converted into a timestring (e.g. '2:45 PM').
*/
static dateToTimestring(date) {
if (!(date instanceof Date)) date = new Date(date);
if (date.toString() === 'Invalid Date')
throw new Error('Invalid date passed to `dateToTimestring`.');
try {
const untrimmed = date.toLocaleTimeString();
const ampm = untrimmed.split(' ')[1];
const time = untrimmed.split(' ')[0];
const splitTime = time.split(':');
return splitTime[0] + ':' + splitTime[1] + ' ' + ampm;
} catch (err) {
console.warn(
'[WARNING] Unsupported locale time string (' + untrimmed + '):',
err
);
return date.toLocaleTimeString();
}
}
/**
* Checks if the given `clockIn` time string is valid. Optionally pass a
* `clockOut` to confirm that the `clockIn` occurs before the `clockOut`.
* @param {string} clockIn - The clock-in time string to check.
* @param {(string|Date)} [clockOut] - The clock-out time to use when
* checking if the clock-in occurs before the clock-out time.
* @return {bool} Whether the given `clockIn` time string is valid.
*/
static validClockInTime(clockIn, clockOut) {
if (!Utils.validTimestring(clockIn)) return false;
if (!clockOut) return true;
if (clockOut instanceof Date) clockOut = Utils.dateToTimestring(clockOut);
const clockInIndex = window.app.data.timeStrings.indexOf(clockIn);
const clockOutIndex = window.app.data.timeStrings.indexOf(clockOut);
return clockInIndex < clockOutIndex;
}
/**
* Checks if the given `clockOut` time string is valid. Optionally pass a
* `clockIn` to confirm that the `clockOut` occurs after the `clockIn`.
* @param {string} clockOut - The clock-in time string to check.
* @param {(string|Date)} [clockIn] - The clock-in time to use when
* checking if the clock-out occurs after the clock-in time.
* @return {bool} Whether the given `clockOut` time string is valid.
*/
static validClockOutTime(clockOut, clockIn) {
if (!Utils.validTimestring(clockOut)) return false;
if (!clockIn) return true;
if (clockIn instanceof Date) clockIn = Utils.dateToTimestring(clockIn);
const clockInIndex = window.app.data.timeStrings.indexOf(clockIn);
const clockOutIndex = window.app.data.timeStrings.indexOf(clockOut);
return clockInIndex < clockOutIndex;
}
/**
* Checks if the given `timestring` is contained in
* `window.app.data.timeStrings`.
* @param {string} The time string to check.
* @return {bool} Whether the given `timestring` is valid.
*/
static validTimestring(timestring) {
if (!window.app.data || !(window.app.data.timeStrings instanceof Array))
return false;
return window.app.data.timeStrings.indexOf(timestring) >= 0;
}
/**
* Joins the array like the typicall `Array.join` function but adds the
* `ending` concatenator between the last two items.
* @example
* const Utils = require('@tutorbook/utils');
* const subjects = ['Chemistry', 'Chemistry H', 'Algebra 1'];
* const str = Utils.join(subjects, 'or');
* assert(str === 'Chemistry, Chemistry H, or Algebra 1');
* @param {string[]} arr - The array of (typically) strings to concatenate.
* @param {string} ending - The concatenator to insert between the last two
* items in the given `arr`.
* @param {bool} [oxfordComma=true] - Whether or not to have the Oxford
* comma before the last item.
* @return {string} The concatenated array in string form (with the given
* `ending` between the last two items in the given `arr`).
*/
static join(arr, ending, oxfordComma = true) {
const lastItem = arr.pop();
const str = arr.join(', ');
return str + (oxfordComma ? ', ' : ' ') + ending + ' ' + lastItem;
}
/**
* Determine if an array contains one or more items from another array.
* @param {array} haystack - The array to search.
* @param {array} arr - The array providing items to check for in the
* haystack.
* @return {boolean} true|false if haystack contains at least one item from
* arr.
*/
static arrayContainsAny(haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
}
static visible(opts = {}) {
if (!opts.el) return false;
const element = typeof opts.el === 'string' ? $(opts.el)[0] : opts.el;
const pageTop = opts.pageTop || $(window).scrollTop();
const pageBottom = opts.pageBottom || pageTop + $(window).height();
const elementTop = $(element).offset().top;
const elementBottom = elementTop + $(element).height();
if (opts.partiallyInView) {
return elementTop <= pageBottom && elementBottom >= pageTop;
} else {
return pageTop < elementTop && pageBottom > elementBottom;
}
}
static sync(obj, root) {
Object.entries(obj).forEach(([k, v]) => (root[k] = Utils.clone(v)));
}
static identicalMaps(mapA, mapB) {
// Thanks to https://bit.ly/2H4Nz1S
if (mapA.size !== mapB.size) return false;
for (var [key, val] of Object.entries(mapA)) {
if (typeof val === 'object' && !Utils.identicalMaps(mapB[key], val))
return false;
if (typeof val !== 'object' && mapB[key] !== val) return false;
}
return true;
}
static shortenString(str, length = 100, ending = '...') {
return str.length > length
? str.substring(0, length - ending.length) + ending
: str;
}
static updateSetupProfileCard(p) {
if (!Object.values(p.availability).length) {
return p.type === 'Tutor'
? (p.cards.setupProfile = true)
: (p.cards.setupAvailability = true);
} else if (p.type !== 'Tutor') {
return (p.cards.setupAvailability = false);
}
for (var key of ['type', 'grade', 'gender', 'phone', 'email']) {
if (!p[key]) return (p.cards.setupProfile = true);
}
if (!p.subjects.length) return (p.cards.setupProfile = true);
p.cards.setupProfile = false;
}
static wrap(str, maxWidth) {
// See https://bit.ly/2GePdNV
const testWhite = (x) => {
const white = new RegExp(/^\s$/);
return white.test(x.charAt(0));
};
const newLineStr = '\n';
var res = '';
while (str.length > maxWidth) {
var found = false;
// Inserts new line at first whitespace of the line
for (var i = maxWidth - 1; i >= 0; i--) {
if (testWhite(str.charAt(i))) {
res = res + [str.slice(0, i), newLineStr].join('');
str = str.slice(i + 1);
found = true;
break;
}
}
// Inserts new line at maxWidth position, the word is too long to
// wrap
if (!found) {
res += [str.slice(0, maxWidth), newLineStr].join('');
str = str.slice(maxWidth);
}
}
return res + str;
}
/**
* Opens up a new tab with the raw JSON data of the given Firestore document
* (and ID).
* @param {external:DocumentSnapshot} doc - The Firestore document to show
* the raw data from.
*/
static viewRaw(doc) {
const json = JSON.stringify(
{
data: doc.data(),
id: doc.id,
},
null,
2
);
const w = window.open();
w.document.open();
w.document.write('<html><body><pre>' + json + '</pre>' + '</body></html>');
w.document.close();
}
static getNextDateWithDay(day) {
const now = new Date();
const date = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,
0,
0,
0
);
var count = 0;
// Added counter just in case we get something that goes on forever
while (Data.days[date.getDay()] !== day && count <= 256) {
date.setDate(date.getDate() + 1);
count++;
}
return date;
}
static color(time, colors) {
if (!colors || typeof colors !== 'object') colors = {};
if (colors[time.day] && colors[time.day][time.from])
return colors[time.day][time.from];
const palette = {
purples: ['#7e57c2', '#5e35b1', '#4527a0', '#311b92'],
pinks: ['#ec407a', '#d81b60', '#ad1457', '#880e4f'],
blues: ['#5c6bc0', '#3949ab', '#283593', '#1a237e'],
oranges: ['#ffa726', '#fb8c00', '#ef6c00', '#e65100'],
greens: ['#26a69a', '#00897b', '#00695c', '#004d40'],
greys: ['#78909c', '#546e7a', '#37474f', '#263238'],
};
if (colors[time.day]) {
var type = 'oranges';
var used = [];
Object.entries(palette).forEach((entry) => {
Object.values(colors[time.day]).forEach((color) => {
if (entry[1].indexOf(color) >= 0) type = entry[0];
used.push(color);
});
});
for (var i = 0; i < palette[type].length; i++) {
if (used.indexOf(palette[type][i]) < 0) {
colors[time.day][time.from] = palette[type][i];
break;
}
}
if (!colors[time.day][time.from]) colors[time.day][time.from] = used[0];
} else {
colors[time.day] = {};
var type = 'oranges';
var used = [];
Object.entries(palette).forEach((entry) => {
Object.values(colors).forEach((times) => {
Object.values(times).forEach((c) => {
if (entry[1].indexOf(c) >= 0) used.push(entry[0]);
});
});
});
for (var i = 0; i < Object.keys(palette).length; i++) {
var key = Object.keys(palette)[i];
if (used.indexOf(key) < 0) type = key;
}
colors[time.day][time.from] = palette[type][0];
}
return colors[time.day][time.from];
}
static showPayments() {
window.app.user.config.showPayments = true;
window.app.nav.initDrawer();
window.app.updateUser();
window.app.payments.view();
}
static viewCard(card, cards) {
if (!card) {
throw new Error('Invalid card passed to viewCard:', card);
}
var id = $(card).attr('id').trim();
var existing = $(cards).find('#' + id);
if ($(existing).length) {
return $(existing).replaceWith(card);
}
var timestamp = new Date($(card).attr('timestamp'));
for (var i = 0; i < cards.children.length; i++) {
var child = cards.children[i];
var time = new Date($(child).attr('timestamp'));
if (time && time < timestamp) {
return $(card).insertBefore(child);
}
}
$(cards).append(card);
}
/**
* Callback the displays new or updates existing views based on a given
* snapshot of Firestore data.
* @callback displayCallback
* @param {external:DocumentSnapshot} doc - The updated Firestore document
* to display.
* @param {string} type - The key of the query that this Firestore document
* came from (e.g. `appts` or `pastAppts`).
* @param {int} [index=0] - The index of the query this Firestore document
* came from (usually just `0` though it can be different if you passed an
* array of queries at the same key when calling
* [`Utils.recycle`]{@link Utils#recycle}).
* @see {@link recycler}
* @see {@link Utils#recycle}
*/
/**
* Callback the removes existing views based on a given snapshot of
* Firestore data.
* @callback removeCallback
* @param {external:DocumentSnapshot} doc - The deleted Firestore document
* to remove.
* @param {string} type - The key of the query that this Firestore document
* came from (e.g. `appts` or `pastAppts`).
* @param {int} [index=0] - The index of the query this Firestore document
* came from (usually just `0` though it can be different if you passed an
* array of queries at the same key when calling
* [`Utils.recycle`]{@link Utils#recycle}).
* @see {@link Recycler}
* @see {@link Utils#recycle}
*/
/**
* Callback the empties new or updates existing views based on a given
* snapshot of Firestore data.
* @callback emptyCallback
* @param {string} type - The key of the query that is now empty (e.g.
* `appts` or `pastAppts`).
* @param {int} [index=0] - The index of the query that is now empty
* (usually just `0` though it can be different if you passed an array of
* queries at the same key when calling
* [`Utils.recycle`]{@link Utils#recycle}).
* @see {@link Recycler}
* @see {@link Utils#recycle}
*/
/**
* An recycler object containing `display`, `remove`, and `empty` callbacks
* to recycle/show updated Firestore data as it changes live.
* @typedef {Object} Recycler
* @global
* @property {displayCallback} display - Callback to display new or update
* existing data.
* @property {removeCallback} remove - Callback to remove data.
* @property {emptyCallback} empty - Callback to empty all data.
*/
/**
* Listens to the given queries and calls the recycler when those queries's
* data changes.
* @param {Object} queries - A map of arrays (or just a map of) Firestore
* [Query]{@link external:Query}s to listen to and subsequently recycle.
* @param {Recycler} recycler - A recycler containing callbacks to display,
* remove, or empty different query data.
* @see {@link https://firebase.google.com/docs/firestore/query-data/queries}
*/
static recycle(queries, recycler) {
Object.entries(queries).forEach(([key, val]) => {
if (!(val instanceof Array)) queries[key] = [val];
});
Object.entries(queries).forEach(([subcollection, queries]) => {
queries.forEach((query) => {
const index = queries.indexOf(query);
window.app.listeners.push(
query.onSnapshot({
error: (err) =>
console.error(
'[ERROR] Could not get ' +
subcollection +
' (' +
index +
') data snapshot b/c ' +
'of ',
err
),
next: (snapshot) => {
if (!snapshot.size) return recycler.empty(subcollection, index);
snapshot.docChanges().forEach((change) => {
if (change.type === 'removed')
return recycler.remove(change.doc, subcollection, index);
recycler.display(change.doc, subcollection, index);
});
},
})
);
});
});
}
static getDurationStringFromDates(start, end, readable) {
const secs = (end.getTime() - start.getTime()) / 1000;
const string = Utils.getDurationStringFromSecs(secs);
if (readable) return string.slice(0, -3);
return string + '.00'; // For clockIn timers
}
static getDurationStringFromSecs(secs) {
// See: https://www.codespeedy.com/convert-seconds-to-hh-mm-ss-format-
// in-javascript/
const time = new Date(null);
time.setSeconds(secs);
return time.toISOString().substr(11, 8);
}
static getEarliestDateWithDay(date) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
0,
0,
0,
0
);
}
static getTimeString(timestamp) {
// NOTE: Although we create timestamp objects here as new Date() objects,
// Firestore converts them to Google's native Timestamp() objects and thus
// we must call toDate() to access any Date() methods.
var timeString = timestamp.toDate().toLocaleTimeString();
var timeStringSplit = timeString.split(':');
var hour = timeStringSplit[0];
var min = timeStringSplit[1];
var ampm = timeStringSplit[2].split(' ')[1];
return hour + ':' + min + ' ' + ampm;
}
/**
* Gets the other attendee given the user to not return.
* @param {Profile} notThisUser - The user that you don't want to return.
* @param {Profile[]} attendees - The array of user's to look through.
* @return {Profile} The other user attendee.
*/
static getOther(notThisUser, attendees) {
if (!notThisUser.email && !!notThisUser.length) {
if (notThisUser[0].email === window.app.user.email) {
return notThisUser[1];
}
return notThisUser[0];
}
if (attendees[0].email === notThisUser.email) {
return attendees[1];
}
return attendees[0];
}
/**
* Capitalizes every word in a string (i.e. the first letter of each set
* of characters separated by a space).
* @param {string} str - The string to capitalize.
* @return {string} The capitalized string.
* @example
* const original = 'the Rabbit ran across The road.';
* const changed = Utils.caps(original);
* assert(changed === 'The Rabbit Ran Across The Road.');
*/
static caps(str) {
var str = str.split(' ');
for (let i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(' ');
}
static getPhone(phoneString) {
const parsed = phone(phoneString);
if (!parsed[0]) return phoneString || '';
return parsed[0];
}
static getName(profile) {
// Capitalizes the name ("nick li" -> "Nick Li")
var name = profile.name || profile.displayName || '';
return Utils.caps(name);
}
/**
* Takes in a parameter key and returns it's value. Note that the value
* cannot contain a `/` because we trim off any slashes for consistency.
* @example
* window.location = '/app/?redirect=home?cards=searchTutors+setupProfile';
* assert(Utils.getURLParam('redirect') === 'home');
* @todo Actually use standard URL parameter syntax here (i.e. instead of
* separating pairs with a `?` use an `&`).
* @param {string} param - The key of the URL parameter to return.
* @return {(string|undefined)} The value at the given `param` key
* (`undefined` if the given `param` key wasn't in the URL).
*/
static getURLParam(param) {
const pairs = location
.toString()
.split('?')
.map((p) => p.split('='));
if (pairs.findIndex((pair) => pair[0] === param) < 0) return;
const raw = pairs[pairs.findIndex((pair) => pair[0] === param)][1];
return raw.replace('/', '');
}
static getType(type = '') {
const urlSpecifiedType = Utils.getURLParam('type');
if (Data.types.indexOf(urlSpecifiedType) >= 0) return urlSpecifiedType;
return type;
}
static getLocation(profile) {
try {
// TODO: Bug here is that data.locationNames only includes name of the
// current app location (unless partition is 'Any').
const valid = window.app.data.locationNames;
if (valid.indexOf(profile.location) >= 0) return profile.location;
// This uses the most recently added availability (i.e. the last key).
if (!profile.availability) return window.app.location.name || '';
for (var loc of Object.keys(profile.availability).reverse()) {
if (valid.indexOf(loc) >= 0) return loc;
}
return window.app.location.name || '';
} catch (err) {
console.error(
'[ERROR] Could not get location for ' +
profile.name +
' (' +
profile.uid +
'), returning empty...'
);
return '';
}
}
static getLocations(profile = {}) {
console.log("[TODO] Update storage of each user's location.");
return [];
/*
*return profile.availability ? Utils.concatArr(Object.keys(profile
* .availability), [window.app.location.name]) : [window.app.location
* .name
*];
*/
}
static getAuth(profile = {}) {
if (profile.authenticated) return profile.authenticated;
if (['Pupil', 'Tutor'].indexOf(profile.type) >= 0) return true;
if (Utils.getURLParam('auth') === 'true') return true;
return false;
}
static getCards(cards = {}) {
const urlSpecifiedCards = Utils.getURLParam('cards');
if (urlSpecifiedCards) {
const cardNames = urlSpecifiedCards.split('+');
cardNames.map((name) => (cards[name] = true));
}
return cards;
}
static getPayments(profile = {}) {
const defaultPayments = {
hourlyChargeString: '$25.00',
hourlyCharge: 25,
totalChargedString: '$0.00',
totalCharged: 0,
currentBalance: 0,
currentBalanceString: '$0.00',
type: 'Free',
policy:
'Hourly rate is $25.00 per hour. Will accept lesson ' +
'cancellations if given notice within 24 hours. No refunds ' +
'will be issued unless covered by a Tutorbook guarantee.',
};
const urlSpecifiedPayments = Utils.getURLParam('payments');
if (urlSpecifiedPayments === 'true') {
if (!profile.config) profile.config = {};
profile.config.showPayments = true;
return Utils.combineMaps(defaultPayments, {
type: 'Paid',
});
}
return profile.payments || defaultPayments;
}
static filterProfile(profile) {
return {
name: Utils.getName(profile),
uid: profile.uid || '',
access: profile.access || [],
photo: profile.photoURL || profile.photo || '',
id: profile.email || '', // Use email as ID
email: profile.email || '',
phone: Utils.getPhone(profile.phone),
type: Utils.getType(profile.type),
gender: profile.gender || '',
grade: profile.grade || '',
bio: profile.bio || '',
avgRating: profile.avgRating || 0,
numRatings: profile.numRatings || 0,
subjects: profile.subjects || [],
cards: Utils.getCards(profile.cards),
settings: profile.settings || {},
availability: profile.availability || {},
payments: Utils.getPayments(profile),
config: profile.config || {
showPayments: false,
showProfile: true,
},
authenticated: Utils.getAuth(profile),
location: Utils.getLocation(profile),
locations: Utils.getLocations(profile),
children: profile.children || [],
secondsTutored: profile.secondsTutored || 0,
secondsPupiled: profile.secondsPupiled || 0,
proxy: profile.proxy || [],
created: profile.created || new Date(),
updated: new Date(),
};
}
static concatArr(arrA = [], arrB = []) {
var result = [];
arrA.forEach((item) => {
if (result.indexOf(item) < 0 && item !== '') {
result.push(item);
}
});
arrB.forEach((item) => {
if (result.indexOf(item) < 0 && item !== '') {
result.push(item);
}
});
return result;
}
/**
* Returns the other user in a request or appointment (i.e. the user that
* does not share a uID with our current app user). Note that this will
* return even if both users are the current user (it will default to the
* first user given).
* @param {Object} userA - The first user to compare with our current user.
* @param {Object} userB - The second user to compare with our current user.
* @return {otherUser} The user that did not match our current user (default
* to `userA`).
*/
static getOtherUser(userA, userB) {
if (userA.email === window.app.user.email) return userB;
return userA; // Default is to return the first user
}
static genID() {
// See: https://gist.github.com/gordonbrander/2230317
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9
// characters after the decimal.
return '_' + Math.random().toString(36).substr(2, 9);
}
/**
* Updates the currently viewed URL without changing the history at all.
* @todo Don't break the user's browser navigation. Clicking back on the
* browser nav should be the same as clicking back on the app nav.
* @param {string} url - The new URL.
*/
static url(url) {
history.pushState({}, null, url);
}
static getCleanPath(dirtyPath) {
dirtyPath = dirtyPath || document.location.pathname;
if (dirtyPath.startsWith('/app/index.html')) {
const newPath = dirtyPath.split('/').slice(2).join('/');
return newPath;
} else {
return dirtyPath;
}
}
static attachMenu(menuEl) {
$(menuEl)
.find('.mdc-list-item')
.each(function () {
MDCRipple.attachTo(this);
});
return new MDCMenu(menuEl);
}
/**
* Attaches an [`MDCTopAppBar`]{@link https://material.io/develop/web/components/top-app-bar/}
* to a given header element, [`MDCRipple`]{@link https://material.io/develop/web/components/ripples/}'s
* to that element's buttons and list items, and returns the managed
* `MDCTopAppBar`.
* @example
* const header = Utils.attachHeader(this.header); // Pass an element
* @example
* const header = Utils.attachHeader('#my-header'); // Pass a query
* @param {(HTMLElement|string)} [headerEl='header .mdc-top-app-bar'] - The
* header element (or string query for the element) to attach to.
* @return {MDCTopAppBar} The attached and managed top app bar instance.
*/
static attachHeader(headerEl = 'header .mdc-top-app-bar') {
if (typeof headerEl === 'string') headerEl = $(headerEl)[0];
$(headerEl)
.find('.mdc-icon-button')
.each(function () {
MDCRipple.attachTo(this).unbounded = true;
});
$(headerEl)
.find('.mdc-list-item')
.each(function () {
MDCRipple.attachTo(this);
});
return MDCTopAppBar.attachTo(headerEl);
}
/**
* Attaches the given select by:
* 1. Populating it's options with the options in the `mdc-list`.
* 2. Listening for `keydown` events that act as shortcuts to select an
* option (like most native `select` elements do).
* @param {HTMLElement} selectEl - The `mdc-select` element to attach.
* @return {external:MDCSelect} The attached `MDCSelect` instance.
*/
static attachSelect(selectEl) {
// Initialize select
if (typeof selectEl === 'string') selectEl = $(selectEl)[0];
const ops = [];
$(selectEl)
.find('.mdc-list-item')
.each(function () {
MDCRipple.attachTo(this);
if (ops.indexOf(this.innerText) < 0) ops.push(this.innerText);
});
const selected = $(selectEl).find('.mdc-select__selected-text').text();
const select = MDCSelect.attachTo(selectEl);
// Helper functions
const lastClicked = []; // Last inputted shortcut keys
const selectOption = (op) => (select.selectedIndex = ops.indexOf(op));
const listen = (event) => {
const justClicked = event.keyCode;
const possible = ops.filter((option) => {
option = option.toUpperCase();
var i = 0;
for (i; i < lastClicked.length; i++)
if (option.charCodeAt(i) !== lastClicked[i]) return false;
return option.charCodeAt(i) === justClicked;
});
if (possible.length === 1) {
lastClicked.length = 0;
selectOption(possible[0]);
} else if (possible.length > 1) {
lastClicked.push(justClicked);
}
};
// Render empty selects even when val is null, undefined, or false
if (selected !== '') selectOption(selected);
// Listen for shortcut keys (when select is in focus)
$(selectEl).on('focusin', () => $(document).keydown(listen));
$(selectEl).on('focusout', () => $(document).off('keydown', listen));
return select;
}
static parseAvailabilityStrings(strings) {
// Then, convert those strings into individual parsed maps
var maps = [];
strings.forEach((string) => {
maps.push(Utils.parseAvailabilityString(string));
});
// Finally, parse those maps into one availability map
var result = {};
maps.forEach((map) => {
result[map.location] = {};
});
maps.forEach((map) => {
result[map.location][map.day] = [];
});
maps.forEach((map) => {
result[map.location][map.day].push({
open: map.fromTime,
close: map.toTime,
booked: false,
});
});
return result;
}
// Helper function to parse a profile availability string into a map of day,
// location, fromTime, and toTime values.
static parseAvailabilityString(string, openingDialog) {
// NOTE: The string is displayed in the textField as such:
// 'Friday at the Gunn Library from 11:00 AM to 12:00 PM'
if (string.indexOf('at the') < 0 && string !== '') {
return Utils.parseAvailabilityString(string.replace('at', 'at the'));
}
// First check if this is a valid string. If it isn't we want to throw
// an error so nothing else happens.
if (
string.indexOf('at the') < 0 ||
string.indexOf('from') < 0 ||
string.indexOf('to') < 0
) {
if (openingDialog) {
return {
day: '',
location: '',
fromTime: '',
toTime: '',
};
}
window.app.snackbar.view(
'Invalid availability. Please click on ' +
'the input to re-select your availability.'
);
throw new Error('Invalid availabilityString:', string);
}
// Helper function to return the string between the two others within an
// array of strings
function getStringBetween(splitString, startString, endString) {
// We know that 'Friday at the' and 'from 11:00 AM' will always be the
// same.
const startIndex = splitString.indexOf(startString);
const endIndex = splitString.indexOf(endString);
var result = '';
for (var i = startIndex + 1; i < endIndex; i++) {
result += splitString[i] + ' ';
}
return result.trim();
}
// Same as above but without an endString (returns from startString
// until the end)
function getStringUntilEnd(splitString, startString) {
const startIndex = splitString.indexOf(startString);
var result = '';
for (var i = startIndex + 1; i < splitString.length; i++) {
result += splitString[i] + ' ';
}
return result.trim();
}
const split = string.split(' ');
const day = split[0].substring(0, split[0].length - 1);
const location = getStringBetween(split, 'the', 'from');
const fromTime = getStringBetween(split, 'from', 'to');
const toTime = getStringUntilEnd(split, 'to').replace('.', '');
return {
day: day,
location: location,
fromTime: fromTime,
toTime: toTime,
time: fromTime !== toTime ? fromTime + ' to ' + toTime : fromTime,
};
}
// Helper function to return an array of timeStrings (e.g. '11:00 AM') for every
// 30 min between the startTime and endTime. (Or for every period in that day's
// schedule if the startTime and endTime are given as periods.)
// TODO: Make sure to sync w/ the Gunn App to be able to have an up to date
// daily period/schedule data.
getTimesBetween(start, end, day) {
var times = [];
// First check if the time is a period
if (this.data.periods[day].indexOf(start) >= 0) {
// Check the day given and return the times between those two
// periods on that given day.
var periods = Data.gunnSchedule[day];
for (var i = periods.indexOf(start); i <= periods.indexOf(end); i++) {
times.push(periods[i]);
}
} else {
var timeStrings = this.data.timeStrings;
// Otherwise, grab every 30 min interval from the start and the end
// time.
for (
var i = timeStrings.indexOf(start);
i <= timeStrings.indexOf(end);
i += 30
) {
times.push(timeStrings[i]);
}
}
return times;
}
// Helper function that returns the duration (in hrs:min:sec) between two
// timeStrings
getDurationFromStrings(startString, endString) {
// TODO: Right now, we just support getting times from actual time strings
// not periods. To implement getting hours from periods, we need to
// know exactly the day that the startString and endString took place
// and the schedule for that day.
var duration = '';
var hours = this.getHoursFromStrings(startString, endString);
duration += hours.split('.')[0];
// NOTE: We multiply by 6 and not 60 b/c we already got rid of that
// decimal when we split it (i.e. 0.5 becomes just 5)
var minutes = Number(hours.split('.')[1]) * 6;
duration += ':' + minutes;
return duration;
}
// Helper function that returns the hours between two timeStrings
getHoursFromStrings(startString, endString) {
var times = this.data.timeStrings;
var minutes = Math.abs(
times.indexOf(endString) - times.indexOf(startString)
);
return minutes / 60 + '';
}
// Helper function to return all of a user's possible days based on their
// availability map.
static getLocationDays(availability) {
// NOTE: Location availability is stored in the Firestore database as:
// availability: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var days = [];
Object.entries(availability).forEach((time) => {
var day = time[0];
days.push(day);
});
return days;
}
getLocationTimeWindowsByDay(day, hours) {
const times = [];
hours[day].forEach((time) => {
times.push(time);
});
return times;
}
// Helper function to return a list of all a location's times for a given
// day.
getLocationTimesByDay(day, hours) {
// NOTE: Location availability is stored in the Firestore database as:
// availability: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var times = [];
hours[day].forEach((time) => {
times.push(time);
});
// Now, we have an array of time maps (i.e. { open: '10:00 AM', close:
// '3:00 PM' })
var result = [];
times.forEach((timeMap) => {
result = result.concat(
this.getTimesBetween(timeMap.open, timeMap.close, day)
);
});
return result;
}
getLocationTimeWindows(availability) {
const result = [];
Object.entries(availability).forEach((time) => {
var timeArray = time[1];
var day = time[0];
timeArray.forEach((time) => {
result.push(
Utils.combineMaps(time, {
day: day,
})
);
});
});
return result;
}
// Helper function to return all of a user's possible times based on their
// availability map.
getLocationTimes(availability) {
// NOTE: Location availability is stored in the Firestore database as:
// availability: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var result = [];
Object.entries(availability).forEach((time) => {
var timeArray = time[1];
var day = time[0];
timeArray.forEach((time) => {
result.push(
Utils.combineMaps(time, {
day: day,
})
);
});
});
// Now, we have an array of time maps (i.e. { open: '10:00 AM', close:
// '3:00 PM' })
var times = [];
result.forEach((timeMap) => {
times = times.concat(
this.getTimesBetween(timeMap.open, timeMap.close, timeMap.day)
);
});
return times;
}
// Helper function to return all of a user's possible locations based on their
// availability map.
static getUserAvailableLocations(availability) {
// NOTE: Availability is stored in the Firestore database as:
// availability: {
// Gunn Library: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var locations = [];
Object.entries(availability).forEach((entry) => {
locations.push(entry[0]);
});
return locations;
}
// Helper function to return a user's available days for a given location
static getUserAvailableDaysForLocation(availability, location) {
// NOTE: Availability is stored in the Firestore database as:
// availability: {
// Gunn Library: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
try {
var days = [];
Object.entries(availability[location]).forEach((entry) => {
var day = entry[0];
var times = entry[1];
days.push(day);
});
return days;
} catch (e) {
// This is most likely b/c the user's profile's location we deleted
// or changed somehow
console.warn(
'[ERROR] While getting userAvailableDaysForLocation ' +
'(' +
location +
'):',
e
);
Utils.viewNoAvailabilityDialog(location);
}
}
getUserAvailableTimeslots(availability) {
var times = [];
for (var locationHours of Object.values(availability)) {
for (var timeslots of Object.values(locationHours)) {
times = times.concat(
timeslots.map((timeslot) =>
timeslot.open === timeslot.close
? timeslot.open
: timeslot.open + ' to ' + timeslot.close
)
);
}
}
return times.filter(Boolean);
}
getUserAvailableTimeslotsForDay(availability, day, location) {
for (var entry of Object.entries(availability[location])) {
var d = entry[0];
var times = entry[1].map((timeslot) =>
timeslot.open === timeslot.close
? timeslot.open
: timeslot.open + ' to ' + timeslot.close
);
if (d === day) return times.filter(Boolean);
}
return this.getUserAvailableTimeslots(availability);
}
// Helper function to return a user's available times for a given day and
// location
getUserAvailableTimesForDay(availability, day, location) {
// NOTE: Availability is stored in the Firestore database as:
// availability: {
// Gunn Library: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
try {
var times = [];
Object.entries(availability[location]).forEach((entry) => {
var d = entry[0];
var t = entry[1];
if (d === day) times = t;
});
var result = [];
times.forEach((time) => {
result = result.concat(
this.getTimesBetween(time.open, time.close, day)
);
});
return result;
} catch (e) {
// This is most likely b/c the user's profile's location we deleted
// or changed somehow
console.warn(
'[ERROR] While getting userAvailableTimesForDay (' +
day +
's at the ' +
location +
'):',
e
);
Utils.viewNoAvailabilityDialog(location);
}
}
static viewNoAvailabilityDialog(location) {
new window.app.NotificationDialog(
'No Availability',
'This user or ' +
'location does not have any availability. The ' +
location +
' may no longer be open at these times or this user may no longer' +
' be available. Ask the user and location to update their ' +
'availability or cancel this request and create a new one.',
() => {}
).view();
}
// Helper function to return all of a user's possible days based on their
// availability map.
static getUserAvailableDays(availability) {
// NOTE: Availability is stored in the Firestore database as:
// availability: {
// Gunn Library: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var days = [];
Object.entries(availability).forEach((entry) => {
var times = entry[1];
Object.entries(times).forEach((time) => {
var day = time[0];
days.push(day);
});
});
return days;
}
// Helper function to return all of a user's possible times based on their
// availability map.
getUserAvailableTimes(availability) {
// NOTE: Availability is stored in the Firestore database as:
// availability: {
// Gunn Library: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// ...
// };
var that = this;
var result = [];
Object.entries(availability).forEach((entry) => {
var location = entry[0];
var times = entry[1];
Object.entries(times).forEach((time) => {
var timeArray = time[1];
var day = time[0];
timeArray.forEach((time) => {
result.push(
Utils.combineMaps(time, {
day: day,
})
);
});
});
});
// Now, we have an array of time maps (i.e. { open: '10:00 AM', close: '3:00 PM' })
var times = [];
result.forEach((timeMap) => {
times = times.concat(
this.getTimesBetween(timeMap.open, timeMap.close, timeMap.day)
);
});
return times;
}
/**
* Combines the two given maps while giving priority to the second map over
* the first. **Note that setting `deep` to `true` will mess up any other
* objects in the map** (e.g. `Array`s will become a `Map`s).
* @param {Map} mapA - The first map.
* @param {Map} mapB - The second map (that gets priority).
* @param {bool} [deep=false] - Whether to use recursive duplication or not.
* @return {Map} The combined maps.
*/
static combineMaps(mapA, mapB, deep = false) {
const combined = {};
for (const i in mapA)
combined[i] =
deep && mapB ? Utils.combineMaps(mapA[i], mapB[i], deep) : mapA[i];
for (const i in mapB)
combined[i] =
deep && mapA ? Utils.combineMaps(mapA[i], mapB[i], deep) : mapB[i];
return combined;
}
static combineAvailability(availA, availB) {
const concatTimeslots = (slotsA, slotsB) => {
slotsA.forEach((slot) => {
if (
slotsB.findIndex(
(t) => t.open === slot.open && t.close === slot.close
) < 0
)
slotsB.push(slot);
});
return slotsB;
};
const combined = {};
for (var l in availA) {
// Location
if (!combined[l]) combined[l] = {};
for (var d in availA[l]) {
// Day
if (!combined[l][d]) combined[l][d] = []; // Timeslots
combined[l][d] = concatTimeslots(combined[l][d], availA[l][d]);
}
}
for (var l in availB) {
// Location
if (!combined[l]) combined[l] = {};
for (var d in availB[l]) {
// Day
if (!combined[l][d]) combined[l][d] = []; // Timeslots
combined[l][d] = concatTimeslots(combined[l][d], availB[l][d]);
}
}
return combined;
}
static getAvailabilityString(data) {
if (Data.locations.indexOf(data.location) >= 0) {
return (
data.day +
's at the ' +
data.location +
' from ' +
data.fromTime +
' to ' +
data.toTime
);
}
return (
data.day +
's at ' +
data.location +
' from ' +
data.fromTime +
' to ' +
data.toTime
);
}
/**
* Parses an array of hour strings and returns an [Hours]{@link Hours}
* object.
* @example
* Utils.parseHourStrings([
* 'Fridays from 10:00 AM to 3:00 PM',
* 'Fridays from 10:00 AM to 3:00 PM',
* 'Tuesdays from 10:00 AM to 3:00 PM',
* ]);
* // The code above will return {
* // Friday: [
* // { open: '10:00 AM', close: '3:00 PM' },
* // { open: '10:00 AM', close: '3:00 PM' },
* // ],
* // Tuesday: [
* // { open: '10:00 AM', close: '3:00 PM' },
* // ],
* // };
* @see {@link Utils#parseHourString}
* @param {string[]} strings - The hour strings to parse.
* @return {Hours} The hour strings as an [Hours]{@link Hours} object.
*/
static parseHourStrings(strings) {
const timeslots = strings.map((str) => Utils.parseHourString(str));
const hours = {};
timeslots.forEach((timeslot) => {
if (!hours[timeslot.day]) hours[timeslot.day] = [];
if (
hours[timeslot.day].findIndex(
(t) => t.open === timeslot.open && t.close === timeslot.close
) < 0
)
hours[timeslot.day].push({
open: timeslot.open,
close: timeslot.close,
});
});
return hours;
}
/**
* A window of time (typically used in availability or open hour data
* storage/processing).
* @typedef {Object} Timeslot
* @global
* @property {string} open - The opening time or period (e.g. '3:00 PM').
* @property {string} close - The closing time or period.
* @property {string} day - The day of the week (e.g. 'Friday').
*/
/**
* Parses a given open hour string into a useful map of data.
* @example
* Utils.parseHourString('Fridays from 10:00 AM to 3:00 PM');
* // The code above returns {
* // day: 'Friday',
* // open: '10:00 AM',
* // close: '3:00 PM',
* // }
* @param {string} string - The open hour string to parse.
* @return {Timeslot} The parsed map of data.
*/
static parseHourString(string) {
try {
const [day, times] = string.split(' from ');
const [from, to] = times.split(' to ');
return {
day: day.endsWith('s') ? day.slice(0, -1) : day,
open: from,
close: to,
};
} catch (e) {
console.warn('[WARNING] Could not parse hour string:', string);
return {
day: '',
open: '',
close: '',
};
}
}
static getHourString(hour) {
return hour.day + 's from ' + hour.open + ' to ' + hour.close;
}
static getHourStrings(hours = {}) {
// @param hours: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// Tuesday: [
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// }
// @return [
// 'Fridays from 10:00 AM to 3:00 PM',
// 'Fridays from 10:00 AM to 3:00 PM',
// 'Tuesdays from 10:00 AM to 3:00 PM',
// ]
const strings = [];
Object.entries(hours).forEach(([day, times]) =>
times.forEach((t) =>
strings.push(day + 's from ' + t.open + ' to ' + t.close)
)
);
return strings;
}
static getAvailabilityStrings(availability = {}) {
// NOTE: User availability is stored in the Firestore database as:
// availability: {
// Gunn Academic Center: {
// Friday: [
// { open: '10:00 AM', close: '3:00 PM' },
// { open: '10:00 AM', close: '3:00 PM' },
// ],
// },
// Paly Tutoring Center: {
// ...
// },
// };
const availableTimes = [];
Object.entries(availability).forEach((entry) => {
var location = entry[0];
var times = entry[1];
Object.entries(times).forEach((time) => {
var day = time[0];
var openAndCloseTimes = time[1];
openAndCloseTimes.forEach((openAndCloseTime) => {
availableTimes.push(
Utils.getAvailabilityString({
day: day,
location: location,
fromTime: openAndCloseTime.open,
toTime: openAndCloseTime.close,
}) + '.'
);
});
});
});
// Next, sort the strings by day
const result = [];
const temp = {};
availableTimes.forEach((time) => {
var day = time.split(' ')[0];
try {
temp[day].push(time);
} catch (e) {
temp[day] = [time];
}
});
[
'Mondays',
'Tuesdays',
'Wednesdays',
'Thursdays',
'Fridays',
'Saturdays',
'Sundays',
].forEach((day) => {
Object.entries(temp).forEach((entry) => {
if (entry[0] === day) {
entry[1].forEach((time) => {
result.push(time);
});
}
});
});
return result;
}
static clone(val) {
return val instanceof Array
? Utils.cloneArr(val)
: val instanceof firebase.firestore.Timestamp
? val.toDate()
: val instanceof Date
? new Date(val)
: val instanceof Object
? Utils.cloneMap(val)
: val;
}
static cloneArr(arr) {
return arr.map((i) => Utils.clone(i));
}
static cloneMap(map) {
const clone = {};
for (var i in map) clone[i] = Utils.clone(map[i]);
return clone;
}
/**
* Gets the user's gender pronoun (e.g. `his`, `her` or `their`).
* @param {string} gender - Gender (either `Male` or `Female`).
* @return {string} The user's gender pronoun.
*/
static getPronoun(gender) {
switch (gender) {
case 'Male':
return 'his';
case 'Female':
return 'her';
case 'Other':
return 'their';
default:
return 'their';
}
}
static replaceElement(parent, content) {
parent.innerHTML = '';
parent.append(content);
}
// Helper function that takes in a map and returns only those values that
// correspond with location data.
static filterLocationData(data) {
const hrsConfig = {
threshold: Data.thresholds[0],
rounding: Data.roundings[0],
timeThreshold: Data.timeThresholds[0],
};
return {
name: data.name,
city: data.city,
hours: Utils.cloneMap(data.hours),
config: {
hrs: data.config
? Utils.cloneMap(data.config.hrs || hrsConfig)
: hrsConfig,
},
description: data.description,
supervisors: data.supervisors,
timestamp: data.timestamp,
};
}
// Helper function that takes in a map and returns only those values that
// correspond with the location data that is editable by request dialogs.
static filterLocationInputData(data) {
return {
name: data.name,
city: data.city,
hours: data.hours,
description: data.description,
supervisors: data.supervisors,
};
}
// Helper function that takes in a map and returns only those values that
// correspond with the request data that is editable by request dialogs.
static filterRequestInputData(data) {
return {
subject: data.subject,
time: data.time,
message: data.message,
location: data.location,
};
}
// Helper function that takes in a map and returns only those valuse that
// correspond with appt data.
static filterPastApptData(data) {
return {
attendees: data.attendees,
for: this.filterRequestData(data.for),
time: {
day: data.time.day,
from: data.time.from,
to: data.time.to,
clocked: data.time.clocked,
},
clockIn: data.clockIn,
clockOut: data.clockOut,
location: data.location,
timestamp: data.timestamp,
id: data.id || '', // NOTE: We use this to be able to access and update the
// Firestore document across different functions within the app all
// using the same `this.currentRequest` map.
};
}
/**
* A time object storing when appointments or lesson requests are supposed
* to happen.
* @typedef {Object} Time
* @global
* @property {string} day - The weekday of the appointment or lesson request
* (e.g. 'Monday').
* @property {string} from - When the appointment or lesson starts (e.g.
* '3:45 PM').
* @property {string} to - When the appointment or lesson ends (e.g.
* '4:45 PM').
*/
/**
* An appointment object storing relevant appointment data.
* @typedef {Object} Appointment
* @global
* @property {Profile[]} attendees - An array of the users attending the
* appointment.
* @property {Time} time - A `Map` storing the time of the appointment.
* @property {Request} for - The appointment's original lesson request.
* @property {Location} location - The location at which the appointment is
* going to occur.
* @property {Date} timestamp - When the appointment was created.
* @property {string} id - The Firestore document ID of the appointment.
*/
/**
* Helper function that takes in a map and returns only those valuse that
* correspond with appt data.
*/
static filterApptData(data) {
return {
attendees: data.attendees,
for: this.filterRequestData(data.for),
time: {
day: data.time.day,
from: data.time.from,
to: data.time.to,
clocked: data.time.clocked || '0:0:0.00',
},
location: data.location,
timestamp: data.timestamp,
id: data.id || '', // NOTE: We use this to be able to access and
// update the Firestore document across different functions within
// the app all using the same `this.currentRequest` map.
};
}
static filterMessageData(data) {
return {
message: data.message,
sentBy: Utils.filterRequestUserData(data.sentBy),
timestamp: data.timestamp,
};
}
static filterChatData(data) {
return {
chatters: data.chatters,
chatterEmails: data.chatterEmails,
chatterUIDs: data.chatterUIDs,
lastMessage: Utils.filterMessageData(data.lastMessage),
createdBy: Utils.filterRequestUserData(data.createdBy),
name: data.name || '', // We use the chatter name as the chat name
photo: data.photo || '', // Use the chatter photo as the chat photo
location: data.location || window.app.location,
};
}
// Helper function that takes in a map and returns only those values that
// correspond with activeAppt data.
static filterActiveApptData(data) {
return {
attendees: data.attendees,
for: this.filterRequestData(data.for),
time: {
day: data.time.day,
from: data.time.from,
to: data.time.to,
clocked: data.time.clocked || '0:0:0.00',
},
location: data.location,
timestamp: data.timestamp,
// activeAppt only data
clockIn: {
sentBy: data.clockIn.sentBy,
sentTimestamp: data.clockIn.sentTimestamp,
approvedBy: data.clockIn.approvedBy,
approvedTimestamp: data.clockIn.approvedTimestamp,
},
supervisor: data.supervisor,
id: data.id || '', // NOTE: We use this to be able to access and update the
// Firestore document across different functions within the app all
// using the same `this.currentRequest` map.
};
}
// Helper function that takes in a map and returns only those values that
// correspond with pastAppt data (this is also how my Firebase Functions will be
// able to process payments, etc).
static filterPastApptData(data) {
return {
attendees: data.attendees,
for: this.filterRequestData(data.for),
time: {
day: data.time.day,
from: data.time.from,
to: data.time.to,
clocked: data.time.clocked || '0:0:0.00',
},
location: data.location,
timestamp: data.timestamp,
// activeAppt only data
clockIn: {
sentBy: data.clockIn.sentBy,
sentTimestamp: data.clockIn.sentTimestamp,
approvedBy: data.clockIn.approvedBy,
approvedTimestamp: data.clockIn.approvedTimestamp,
},
supervisor: {
name: data.supervisor.name,
email: data.supervisor.email,
phone: data.supervisor.phone,
},
// pastAppt only data
clockOut: {
sentBy: data.clockIn.sentBy,
sentTimestamp: data.clockIn.sentTimestamp,
approvedBy: data.clockIn.approvedBy,
approvedTimestamp: data.clockIn.approvedTimestamp,
},
duration: data.duration,
payment: data.payment, // TODO: Implement a payment method system
// that can detect when an appt occurred and select the correct
// payment method(s) b/c of the timestamp(s).
id: data.id || '', // NOTE: We use this to be able to access and update the
// Firestore document across different functions within the app all
// using the same `this.currentRequest` map.
};
}
// Helper function that takes in a map and returns only those values that
// correspond with request data.
static filterRequestData(data) {
return {
subject: data.subject,
time: data.time,
message: data.message,
location: data.location,
fromUser: Utils.filterRequestUserData(data.fromUser),
toUser: Utils.filterRequestUserData(data.toUser),
timestamp: data.timestamp,
payment: data.payment || {
amount: 0,
type: 'Free',
method: 'PayPal',
},
id: data.id || '', // NOTE: We use this to be able to access and update the
// Firestore document across different functions within the app all
// using the same `this.currentRequest` map.
};
}
// Helper function that filters a user profile to only the fields that we care
// about in the context of an appt
static filterApptUserData(user) {
return {
name: user.name,
email: user.email,
phone: user.phone,
uid: user.uid,
id: user.id,
photo: user.photo,
type: user.type,
};
}
// Helper function that filters a user profile to only the fields that we care
// about in the context of a request
static filterRequestUserData(user) {
return {
name: user.name,
email: user.email,
uid: user.uid,
id: user.id,
photo: user.photo,
type: user.type,
grade: user.grade,
gender: user.gender,
hourlyCharge: user.payments ? user.payments.hourlyCharge : 0,
location: user.location,
payments: user.payments,
proxy: user.proxy,
};
}
}
|
JavaScript
|
class BatchError extends Error {
constructor(err, ackIds, rpc) {
super(`Failed to "${rpc}" for ${ackIds.length} message(s). Reason: ${process.env.DEBUG_GRPC ? err.stack : err.message}`);
this.ackIds = ackIds;
this.code = err.code;
this.details = err.details;
this.metadata = err.metadata;
}
}
|
JavaScript
|
class MessageQueue {
constructor(sub, options = {}) {
this.numPendingRequests = 0;
this.numInFlightRequests = 0;
this._requests = [];
this._subscriber = sub;
this.setOptions(options);
}
/**
* Gets the default buffer time in ms.
*
* @returns {number}
* @private
*/
get maxMilliseconds() {
return this._options.maxMilliseconds;
}
/**
* Adds a message to the queue.
*
* @param {Message} message The message to add.
* @param {number} [deadline] The deadline.
* @private
*/
add({ ackId }, deadline) {
const { maxMessages, maxMilliseconds } = this._options;
this._requests.push([ackId, deadline]);
this.numPendingRequests += 1;
this.numInFlightRequests += 1;
if (this._requests.length >= maxMessages) {
this.flush();
}
else if (!this._timer) {
this._timer = setTimeout(() => this.flush(), maxMilliseconds);
}
}
/**
* Sends a batch of messages.
* @private
*/
async flush() {
if (this._timer) {
clearTimeout(this._timer);
delete this._timer;
}
const batch = this._requests;
const batchSize = batch.length;
const deferred = this._onFlush;
this._requests = [];
this.numPendingRequests -= batchSize;
delete this._onFlush;
try {
await this._sendBatch(batch);
}
catch (e) {
this._subscriber.emit('error', e);
}
this.numInFlightRequests -= batchSize;
if (deferred) {
deferred.resolve();
}
if (this.numInFlightRequests <= 0 && this._onDrain) {
this._onDrain.resolve();
delete this._onDrain;
}
}
/**
* Returns a promise that resolves after the next flush occurs.
*
* @returns {Promise}
* @private
*/
onFlush() {
if (!this._onFlush) {
this._onFlush = defer();
}
return this._onFlush.promise;
}
/**
* Returns a promise that resolves when all in-flight messages have settled.
*/
onDrain() {
if (!this._onDrain) {
this._onDrain = defer();
}
return this._onDrain.promise;
}
/**
* Set the batching options.
*
* @param {BatchOptions} options Batching options.
* @private
*/
setOptions(options) {
const defaults = { maxMessages: 3000, maxMilliseconds: 100 };
this._options = Object.assign(defaults, options);
}
}
|
JavaScript
|
class AckQueue extends MessageQueue {
/**
* Sends a batch of ack requests.
*
* @private
*
* @param {Array.<Array.<string|number>>} batch Array of ackIds and deadlines.
* @return {Promise}
*/
async _sendBatch(batch) {
const client = await this._subscriber.getClient();
const ackIds = batch.map(([ackId]) => ackId);
const reqOpts = { subscription: this._subscriber.name, ackIds };
try {
await client.acknowledge(reqOpts, this._options.callOptions);
}
catch (e) {
throw new BatchError(e, ackIds, 'acknowledge');
}
}
}
|
JavaScript
|
class ModAckQueue extends MessageQueue {
/**
* Sends a batch of modAck requests. Each deadline requires its own request,
* so we have to group all the ackIds by deadline and send multiple requests.
*
* @private
*
* @param {Array.<Array.<string|number>>} batch Array of ackIds and deadlines.
* @return {Promise}
*/
async _sendBatch(batch) {
const client = await this._subscriber.getClient();
const subscription = this._subscriber.name;
const modAckTable = batch.reduce((table, [ackId, deadline]) => {
if (!table[deadline]) {
table[deadline] = [];
}
table[deadline].push(ackId);
return table;
}, {});
const modAckRequests = Object.keys(modAckTable).map(async (deadline) => {
const ackIds = modAckTable[deadline];
const ackDeadlineSeconds = Number(deadline);
const reqOpts = { subscription, ackIds, ackDeadlineSeconds };
try {
await client.modifyAckDeadline(reqOpts, this._options.callOptions);
}
catch (e) {
throw new BatchError(e, ackIds, 'modifyAckDeadline');
}
});
await Promise.all(modAckRequests);
}
}
|
JavaScript
|
class InstrumentPicker extends Component {
constructor() {
super(...arguments);
validate(this.props.dependencies, [ 'voxophone', 'instrumentManager' ], this, { addPrefix: '_' });
this.state = {
instrumentOptions: [],
selectedInstrumentImageSource: ''
};
this._instrumentManager.getInstruments()
.then(instruments => {
// The data that will be used to render the selectable `Instrument` components.
let instrumentOptions = instruments.map(instrument => ({
// Pass the child a component a function it can call to set its instrument as the selected one.
handleInstrumentSelected: () => this._setInstrument(instrument),
imageSource: instrument.imageInfo.filePath,
key: instrument.id
}));
this.setState({ instrumentOptions });
this._setInstrument(instruments[0]);
});
}
render() {
return (
<View>
<View style={styles.selectedInstrument}>
<Image style={styles.selectedInstrumentImage} source={{ uri: this.state.selectedInstrumentImageSource }} />
</View>
<ScrollView horizontal={true} style={styles.instrumentsScrollView}>
{this.state.instrumentOptions.map(({ imageSource, handleInstrumentSelected, key }) => (<Instrument imageSource={imageSource} onSelected={handleInstrumentSelected} key={key} />))}
</ScrollView>
</View>
);
}
_setInstrument(instrument) {
this._voxophone.setInstrument({ instrument });
this.setState({ selectedInstrumentImageSource: instrument.imageInfo.filePath });
}
}
|
JavaScript
|
class EasyGrid {
constructor({
selector = 'defaultId',
dimensions = {
width: "150",
height: "100",
margin: "5",
minHeight: "100",
maxHeight: "300"
},
config = {
fetchFromHTML: true,
filter: true
},
animations = {
fadeInSpeed: "100",
addItemSpeed: "100"
},
style = {
background: "rgb(96, 120, 134)",
borderRadius: '5'
},
responsive = [
{
breakpoint: 300,
columns: 1
}
]
})
{
// Define Variables
this.selector = selector.substring(1);
this.animation = animations;
this.style = style;
this.config = config;
this.dimensions = dimensions;
this.responsive = responsive;
this.queueItem = 0;
// Selector
var randomID = Math.floor(Math.random() * (9999 - 0 + 1)) + 0;
var selector = this.selector;
// Dimensions
var width = this.dimensions["width"];
var requestedWidth = this.dimensions["width"];
var height = this.dimensions["height"];
var margin = this.dimensions["margin"];
var minHeight = this.dimensions["minHeight"];
var maxHeight = this.dimensions["maxHeight"];
// Responsive
var responsive = this.responsive;
// Animations
var animations = this.animation;
// Style
var style = this.style;
// Config
var config = this.config;
var ncolumns, additem;
var widthM = 0, widthM2 = 0, countAddblock=0;
var _this = this;
var filtersArray = {};
var allItemsFilter = {};
// Apply style to main grid container
document.getElementById(selector).style.paddingRight = margin+"px";
// Fade in Function
function fadeIn(el, time) {
el.style.opacity = 0;
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
// Main throttle function
function throttle (func, interval) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function () {
timeout = false;
};
if (!timeout) {
func.apply(context, args)
timeout = true;
setTimeout(later, interval)
}
}
}
// Generates a random hex color
function getRandomColor(type) {
switch(type) {
case "random": // In case its Random color
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
break;
case "shadesOfGrey": // In case its Shades of Grey
var v = (Math.random()*(256)|0).toString(16);//bitwise OR. Gives value in the range 0-255 which is then converted to base 16 (hex).
return "#" + v + v + v;
break;
}
}
// Add items to easy grid
var AddItems = this.AddItems = function AddItems(content)
{
// Update variable values in case it was change with method
height = _this.dimensions["height"];
minHeight = _this.dimensions["minHeight"];
maxHeight = _this.dimensions["maxHeight"];
margin = _this.dimensions["margin"];
style = _this.style;
// Get width of div
var rect_main = document.getElementById(selector);
var ChildItems = 0, bvgridLess = "easygrid_column_1_"+randomID;
var maxColumns = document.querySelectorAll("#"+selector + ' .easygrid_column ').length;
document.querySelectorAll("#"+selector + ' .easygrid_column ').forEach((item) => {
if(item.childElementCount > ChildItems)
{
// If it is last element, goes back to 1
if(item.id == "easygrid_column_"+maxColumns+"_"+randomID)
{
bvgridLess = "easygrid_column_1_"+randomID;
ChildItems = item.childElementCount;
} else {
bvgridLess = item.id;
ChildItems = item.childElementCount;
}
}
// Save position when find column with less blocks
if(item.childElementCount < ChildItems)
{
bvgridLess = item.id;
ChildItems = item.childElementCount;
}
});
// Append Style
var newItem = document.getElementById(bvgridLess);
// Add Countblocks
countAddblock++;
// Check Color
if(style.background == 'random' || (style.background == 'shadesOfGrey')) { var bgColor = getRandomColor(style.background); } else { var bgColor = style.background; }
// Check if height is random or not
if(height == "random") { var heightToApply = Math.floor(Math.random() * (Number(maxHeight) - Number(minHeight) + 1)) + Number(minHeight)+"px"; } else { var heightToApply = height+"px"; }
// Insert New Item
newItem.insertAdjacentHTML('beforeend', "<div id='block_"+countAddblock+"_"+randomID+"' style='opacity:0; background-color:"+bgColor+"; margin-bottom:"+margin+"px; border-radius:"+style.borderRadius+"px; height:"+heightToApply+"' class='easygrid_block'>"+content+"</div>");
var block = document.getElementById("block_"+countAddblock+"_"+randomID);
// Fade In Item
fadeIn(block, animations.fadeInSpeed);
}
// Setup Columns
var SetupColumns = this.SetupColumns = async function SetupColumns()
{
// Empty grid
document.getElementById(_this.selector).innerHTML = "";
// Update variable values in case it was change with method
width = _this.dimensions["width"];
requestedWidth = _this.dimensions["width"];
margin = _this.dimensions["margin"];
ncolumns = undefined;
// Get width of div
var rect_main = document.getElementById(selector);
// Save div Width
widthM = rect_main.offsetWidth;
// Get number of columns possible to fit
ncolumns = rect_main.offsetWidth / Number(width);
ncolumns = Math.floor(ncolumns);
// Check if width of container is less than request item width
if(widthM <= requestedWidth){
ncolumns = 1;
}
// Loop responsive object to get current viewport
for (var loop = 0; loop < responsive.length; loop++) {
if(widthM < responsive[loop].breakpoint)
{
if(responsive[loop].columns != undefined)
{
ncolumns = responsive[loop].columns;
}
}
}
// Set main columns
for (var i = 1; i <= Math.floor(ncolumns); i++) {
document.getElementById(selector).insertAdjacentHTML('beforeend', "<div id='easygrid_column_"+i+"_"+randomID+"' style='padding-left:"+margin+"px; width:100%;' class='easygrid_column'></div>");
}
}
// Change items according to filters
var SetFilters = this.SetFilters = function SetFilters(parameter)
{
// Setup Columns
this.SetupColumns();
// Check if parameter is all
if(parameter == "egfilter_all")
{
Object.keys(allItemsFilter["egfilter_all"]).forEach(function(key) {
_this.AddItems(allItemsFilter["egfilter_all"][key].innerHTML);
});
} else {
var size = Object.keys(allItemsFilter[parameter]).length;
for (var i = 0; i < size; i++) {
this.AddItems(allItemsFilter[parameter][i].innerHTML);
}
}
}
// Startup filter, set all different buttons based
var StartFilter = this.StartFilter = function StartFilter()
{
// Get diferent types of classes
document.querySelectorAll("#"+selector + ' .easygrid_fetch').forEach((item_fetch_clist) => {
// Get all diferent types of classes
var classLength = item_fetch_clist["classList"].length;
for (var i = 0; i < classLength; i++) {
var itemClass = item_fetch_clist["classList"][i];
if(itemClass != "easygrid_fetch")
{
if(itemClass.startsWith("egfilter"))
{
filtersArray[itemClass] = {};
allItemsFilter[itemClass] = {};
}
}
}
});
// Loop those classes and get all elements containing that class
for (var key in allItemsFilter) {
var pos = 0;
if (allItemsFilter.hasOwnProperty(key)) {
document.querySelectorAll("#"+selector + " ."+key).forEach((item_fetch_separate) => {
allItemsFilter[key][pos] = item_fetch_separate;
pos++;
});
}
}
// Add all category, where it stores all items
allItemsFilter["egfilter_all"] = {};
var posall = 0;
document.querySelectorAll("#"+selector + ' .easygrid_fetch').forEach((item_fetch_all) => {
allItemsFilter["egfilter_all"][posall] = item_fetch_all;
posall++;
});
// Set filter
this.SetFilters("egfilter_all");
}
// Startup EasyGrid
this.SetupGrid = function(number) {
// Check if filter config is active
if(_this.config['filter'] == true)
{
this.StartFilter();
} else {
// Save all items inside main selector, when SetupColumns all items inside selector are removed.
if(_this.config['fetchFromHTML'] == true)
{
var fetchedItems = [];
document.querySelectorAll("#"+selector + ' .easygrid_fetch').forEach((item_fetch) => {
fetchedItems.push(item_fetch.innerHTML);
});
}
// Setup Columns
this.SetupColumns();
// Fetch from all items
if(_this.config['fetchFromHTML'] == true)
{
var arrayLength = fetchedItems.length;
for (var array_block = 0; array_block < arrayLength; array_block++) {
AddItems(fetchedItems[array_block]);
}
fetchedItems = [];
}
}
};
// My function that will run repeatedly at each fixed interval of time.
var ResizeWindow = throttle(function() {
var rect_main_new = document.getElementById(selector);
var rect_check_width = rect_main_new.offsetWidth;
if(rect_check_width != widthM2)
{
// Get get all elements from current columns
var countBlocks = 0;
countAddblock = 0;
var itemsArray = [];
document.querySelectorAll("#"+selector + ' .easygrid_column ').forEach((item) => {
var idColumn = item.id;
document.querySelectorAll("#"+idColumn + ' .easygrid_block').forEach((itemBlock) => {
// Increase block count
var str2 = itemBlock.id;
var parts = str2.split('_');
var blockid = parts[parts.length - 2];
itemsArray.push(({'element': itemBlock.innerHTML, 'sort': blockid}));
});
});
// Sort array
itemsArray.sort(function(a, b) { return a.sort - b.sort; });
// Setup Columns
SetupColumns();
// Loop trough array and append items
var arrayLength = itemsArray.length;
for (var array_block = 0; array_block < arrayLength; array_block++) {
AddItems(itemsArray[array_block]["element"]);
}
} else { return; }
widthM2 = rect_check_width;
}, 100); // Adjust interval of time
// Add EventListener
window.addEventListener('resize', ResizeWindow);
// ** SETUP GRID **
this.SetupGrid();
}
// ** METHODS **
// Refresh Grid
Refresh(content) {
// Refresh grid positioning
this.RefreshGrid();
}
// Add New Item
async AddItem(content) {
if(this.queueItem == 0)
{
// Function to Sleep
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// OnComplete Callback
function onComplete(callback) {
if (typeof callback == "function") { callback();}
}
// Check if content is object
if(content.items && typeof(content.items) === 'object')
{
// Loop object and add invidual items
var prop = Object.keys(content.items).length;
// Loop object and add invidual items
var prop = Object.keys(content.items).length;
for (var i = 0; i < prop; i++) {
// Set qeue line
this.queueItem = 1; // There are items in line
// Check if object is empty
if(content["items"][i] != "")
{
// Add Item to grid
this.AddItems(content["items"][i]);
await sleep(this.animation.addItemSpeed); // Wait
}
}
// Set qeue line
this.queueItem = 0; // There no are items in line
// if is "onComplete" is a function, call it back.
if (typeof content.onComplete == "function") { onComplete(content.onComplete); }
} else {
// Add Item to grid
this.AddItems(content.items);
// if is "onComplete" is a function, call it back.
if (typeof content.onComplete == "function") { onComplete(content.onComplete); }
}
} else {
return "There are items in qeue";
}
}
// Start up Easygrid from scrath
SetupEasyGrid() {
// Setup Columns
if(this.queueItem == 0)
{
this.SetupColumns();
} else { return "There are items in qeue"; }
}
// Clear Grid
Change(content) {
// Check items in qeue
if(this.queueItem == 0)
{
// Check if content is object
if(content && typeof(content) === 'object')
{
// Clear grid in case someone want to change while is adding items
document.getElementById(this.selector).innerHTML = "";
// Check if contains Style
if ("style" in content) {
this.style = content.style;
}
// Check if contains Dimensions
if ("dimensions" in content) {
this.dimensions = content.dimensions;
}
// Setup Columns with new width
this.SetupColumns();
} else {
console.log("Properties must be Object, Check documentation.")
}
} else { return "There are items in qeue"; }
}
// Clear Grid
Filter(filter_name) {
// Check filter if it is empty
if(filter_name)
{
this.SetFilters(filter_name);
}
}
// Clear Grid
Clear() {
// Clear current grid and apend items again in the same order
if(this.queueItem == 0)
{
document.getElementById(this.selector).innerHTML = "";
} else { return "There are items in qeue"; }
}
}
|
JavaScript
|
class StoreManager {
constructor (args) {
this.args = args
this.instance = ''
this.executing = false
}
_getType (any) {
return Object.prototype.toString.call(any).slice(8, -1)
}
start (...args) {
if (!this.instance) {
this.instance = new StoreManager(args)
let url = window.location.href
let [rules = [], $store, ...rest] = args
window.addEventListener('hashchange', () => {
this.instance && this.instance.updateStore()
})
window.addEventListener('popstate', () => {
this.instance && this.instance.updateStore()
})
$store.registerModule('_storeManage_', {
namespaced: true,
state: {
version: '0.0.1',
'MOUNTED': ''
},
mutations: {
'MOUNTED' (state, payload) {
state['MOUNTED'] = payload
}
}
})
}
return this.instance
}
updateStore (url) {
if (this.executing) return
try {
url = url || window.location.href
if (!url) throw ''
} catch (e) {
throw new Error('非浏览器环境时,需要提供参数: 匹配对象<String>, 如url等')
}
this.executing = true
let [rules, $store, ...rest] = this.args
let matched = []
let notMatched = []
let mounted = []
rules.forEach(item => {
let isMatched
if (this._getType(item.rule) === 'RegExp') {
isMatched = item.rule.test(url)
} else if (this._getType(item.rule) === 'Function') {
isMatched = item.rule(url, ...this.args)
} else {
throw new Error('Expected the `rule` to be a function or regExp.')
}
if (isMatched) {
matched.push(item)
} else {
notMatched.push(item)
}
})
matched.forEach(item => {
let {name, module} = item
if (!name || !module) {
throw new Error('Missing `name` or `module` for rules')
}
// if (module.namespaced !== false) {
// module.namespaced = true
// }
if ($store.state[name] === undefined) {
$store.registerModule(name, module)
}
mounted.push(name)
})
setTimeout(() => {
notMatched.forEach(item => {
let moduleName = item.name
$store.state[moduleName] && $store.unregisterModule(moduleName)
})
$store.commit('_storeManage_/MOUNTED', `_${mounted.join('_')}_`)
this.executing = false
}, 100)
}
}
|
JavaScript
|
class TileMask extends BaseObject {
/**
* @param {TileMaskOptions} options Tile mask options
*/
constructor(options) {
super();
/**
* @type {ol/Map}
*/
this.map = options.map;
/**
* Layers for scanning
* @type {Array<ol/layer/Layer>}
*/
this.layers = null;
/**
* Binary mask
* @type {Mask}
*/
this.mask = null;
/**
* Array of indices of a boundary points in the mask
* @private
* @type {Array<number>}
*/
this.border_ = null;
/**
* @private
* @type {number}
*/
this.hatchInterval_ = null;
/**
* @private
* @type {number}
*/
this.hatchOffset_ = 0;
/**
* @type {number}
*/
this.hatchLength = options.hatchLength;
/**
* @type {number}
*/
this.hatchTimeout = options.hatchTimeout;
/**
* @type {Size}
*/
this.size = null;
/**
* Context for mask
* @type {CanvasRenderingContext2D}
*/
this.context = null;
/**
* Image data without mask
* @type {Uint8ClampedArray}
*/
this.snapshot = null;
/**
* @protected
* @type {CanvasRenderingContext2D}
*/
this.contextWithoutMask = document.createElement("canvas").getContext("2d");
/**
* Amount of bytes per pixel in the snapshot
* @type {number}
*/
this.bytes = 4;
/**
* @private
* @type {boolean}
*/
this.loading_ = false;
/**
* @private
* @type {boolean}
*/
this.lock_ = false;
/**
* @private
* @type {ol/events/Array<EventsKey>}
*/
this.mapKeys_ = null;
/**
* @private
* @type {ol/events/Array<EventsKey>}
*/
this.layersKeys_ = null;
/**
* @private
* @type {ol/events/EventsKey}
*/
this.mapKeyOnceComplete = null;
/**
* @private
* @type {ol/events/EventsKey}
*/
this.mapKeyOnceRender = null;
this.createCanvas();
this.connectToMap();
this.setLayers(options.layers);
if (this.hatchTimeout && this.hatchTimeout > 0) {
this.hatchInterval = setInterval(() => this.hatchTick_(), this.hatchTimeout);
}
}
/**
* Creates a tile canvas.
* @protected
*/
createCanvas() {
this.context = document.createElement("canvas").getContext("2d");
this.setCanvasSize();
this.clearMask();
}
/**
* @protected
*/
setCanvasSize() {
let size = this.map.getSize();
this.context.canvas.width = size[0];
this.context.canvas.height = size[1];
this.contextWithoutMask.canvas.width = size[0];
this.contextWithoutMask.canvas.height = size[1];
this.size = { w: size[0], h: size[1] };
}
/**
* @inheritDoc
*/
disposeInternal() {
this.disconnectFromMap();
this.disconnectFromLayers();
this.clearMask();
// stop hatching animation
if (this.hatchInterval) clearInterval(this.hatchInterval);
this.layers = null;
this.contextWithoutMask = null;
this.context = null;
this.snapshot = null;
this.map = null;
super.disposeInternal();
}
//#region Map
/**
* @protected
*/
connectToMap() {
this.mapKeys_ = [
this.map.getView().on('change:resolution', this.onViewResChanged_.bind(this)),
this.map.on('change:size', this.onMapSizeChanged_.bind(this)),
this.map.on('moveend', this.onMapMoved_.bind(this)),
this.map.on('postrender', this.onPostRender_.bind(this))
];
}
/**
* @protected
*/
disconnectFromMap() {
if (this.mapKeys_) {
unByKey(this.mapKeys_);
this.mapKeys_ = null;
}
if (this.mapKeyOnceComplete) {
unByKey(this.mapKeyOnceComplete);
this.mapKeyOnceComplete = null;
}
if (this.mapKeyOnceRender) {
unByKey(this.mapKeyOnceRender);
this.mapKeyOnceRender = null;
}
}
/**
* @private
*/
onViewResChanged_() {
this.createCanvas();
this.setCanvasSize();
}
/**
* @private
*/
onMapSizeChanged_() {
this.setCanvasSize();
setTimeout(() => this.scan(), 50);
}
/**
* @private
*/
onMapMoved_() {
this.scan();
}
//#endregion
//#region Layers
/**
* @param {ol/layer/Layer | Array<ol/layer/Layer>} layers Layer(s) for scanning
* @return {boolean}
*/
setLayers(layers) {
if (!layers) return false;
this.disconnectFromLayers();
this.layers = Array.isArray(layers) ? layers : [layers];
this.connectToLayers();
this.scan();
return true;
}
/**
* @protected
*/
connectToLayers() {
this.layersKeys_ = [];
this.layers.forEach((layer) => {
this.layersKeys_.push(
layer.on('change', (e) => this.scan()),
layer.on('propertychange', (e) => this.scan())
//layer.getSource().on('change', (e) => this.scan()),
//layer.getSource().on('propertychange', (e) => this.scan())
);
});
}
/**
* @protected
*/
disconnectFromLayers() {
if (this.layersKeys_) {
unByKey(this.layersKeys_);
this.layersKeys_ = null;
}
}
//#endregion
//#region Snapshot
/**
* Indicates whether or not the snapshot is fully loaded
*/
isReady() {
return !this.loading_ && this.snapshot != null;
}
/**
* Force to recreate the snapshot
*/
scan() {
if (this.loading_ || !this.map) return;
this.snapshot = null;
if (!this.hasVisibleLayers_()) return;
this.dispatchEvent("scanStarted");
let sz = this.map.getSize();
this.size = { w: sz[0], h: sz[1] };
this.loading_ = true;
this.mapKeyOnceComplete = this.map.once('rendercomplete', () => {
if (!this.lock_) {
this.mapKeyOnceRender = this.map.once('postrender', () => {
if (this.getRenderLayers_().length > 0) {
this.snapshot = this.contextWithoutMask.getImageData(0, 0, this.size.w, this.size.h).data;
}
this.loading_ = false;
this.lock_ = false;
this.dispatchEvent("scanFinished");
});
}
this.lock_ = true;
this.map.render(); // force to call postrender
});
this.map.render(); // force to call rendercomplete
}
hasVisibleLayers_() {
return this.layers != null && this.layers.filter(l => {
return l.getVisible() && l.getOpacity() > 0;
}).length > 0;
}
/**
* @private
* @param {RenderEvent} e
*/
onPostRender_() {
if (this.lock_) {
this.contextWithoutMask.clearRect(0, 0, this.size.w, this.size.h);
this.getRenderLayers_().forEach((layer) => {
let cnv = layer.getRenderer().context.canvas;
this.contextWithoutMask.drawImage(cnv, 0, 0, cnv.width, cnv.height, 0, 0, this.size.w, this.size.h);
});
}
this.drawBorder();
}
//#endregion
//#region Mask
/**
* Render the current context to the top visible layer
* @param {boolean} [clear=false] Render the snapshot before
*/
render(clear = false) {
let layers = this.getRenderLayers_();
if (layers.length == 0) return;
let layerCtx = layers[layers.length - 1].getRenderer().context; // top layer
// render snapshot context without mask
if (clear) {
let snap = this.contextWithoutMask;
layerCtx.drawImage(snap.canvas, 0, 0, snap.canvas.width, snap.canvas.height, 0, 0, layerCtx.canvas.width, layerCtx.canvas.height);
}
let ctx = this.context;
layerCtx.drawImage(ctx.canvas, 0, 0, ctx.canvas.width, ctx.canvas.height, 0, 0, layerCtx.canvas.width, layerCtx.canvas.height);
}
/**
* @private
* @return {Array<ol/layer/Layer>} renderable layers
*/
getRenderLayers_() {
return this.layers == null ? [] : this.layers.filter(l => {
let ctx = l.getRenderer().context;
return ctx && l.getVisible() && l.getOpacity() > 0 && ctx.canvas.width > 0 && ctx.canvas.height > 0;
}).sort((a, b) => a.getZIndex() - b.getZIndex());
}
/**
* @private
*/
hatchTick_() {
this.hatchOffset_ = (this.hatchOffset_ + 1) % (this.hatchLength * 2);
return this.drawBorder(false);
}
/**
* Clear the current mask and remove it from the map
*/
clearMask() {
this.mask = null;
this.border_ = null;
if (this.context)
this.context.clearRect(0, 0, this.size.w, this.size.h);
this.map.render();
}
/**
* Set a binary mask and render it
* @param {Mask} mask
*/
setMask(mask) {
this.mask = mask;
this.map.render();
}
/**
* Draw a hatch border of the binary mask
* @param {boolean} [needBorder = true] If true, needs to recreate a border
*/
drawBorder(needBorder = true) {
if (!this.mask) return false;
var i, j, k, q, len,
w = this.size.w, // viewport size
h = this.size.h,
ix = this.size.w - 1, // right bottom of viewport (left top = [0,0])
iy = this.size.h - 1,
sw = this.size.w + 2, // extend viewport size (+1 px on each side)
sh = this.size.h + 2;
if (needBorder) { // create border
var offset = MagicWand.getMainWorldOffset(this.map); // viewport offset in the main world basis
var dx, dy, x0, y0, x1, y1, k1, k2,
rx0, rx1, ry0, ry1, // result of the intersection mask with the viewport (+1 px on each side)
img = this.mask.data,
w1 = this.mask.width,
b = this.mask.bounds,
gf = this.mask.globalOffset, // mask offset in the main world basis,
data = new Uint8Array(sw * sh), // viewport data (+1 px on each side) for correct detection border
off,
maskOffsets = [{ // all posible mask world offsets (considering 'multiWorld')
x: gf.x,
y: gf.y
}, { // add the mask in the left world
x: (gf.x - offset.width) + 1, // 1px for overlap
y: gf.y
}, { // add the mask in the right world
x: (gf.x + offset.width) - 1, // 1px for overlap
y: gf.y
}];
// walk through all worlds
var offsetsLen = maskOffsets.length;
for (j = 0; j < offsetsLen; j++) {
off = maskOffsets[j]; // viewport offset in the world basis
dx = off.x - offset.x; // delta for the transformation to the viewport basis (mask offset in the viewport basis)
dy = off.y - offset.y;
x0 = dx + b.minX; // left top of binary image (in viewport basis)
y0 = dy + b.minY;
x1 = dx + b.maxX; // right bottom of binary image (in viewport basis)
y1 = dy + b.maxY;
// intersection of the mask with viewport
if (!(x1 < 0 || x0 > ix || y1 < 0 || y0 > iy)) {
rx0 = x0 > -1 ? x0 : -1; // intersection +1 px on each side (for search border)
ry0 = y0 > -1 ? y0 : -1;
rx1 = x1 < ix + 1 ? x1 : ix + 1;
ry1 = y1 < iy + 1 ? y1 : iy + 1;
} else {
continue;
}
// copy result of the intersection(+1 px on each side) to image data for detection border
len = rx1 - rx0 + 1;
i = (ry0 + 1) * sw + (rx0 + 1);
k1 = (ry0 - dy) * w1 + (rx0 - dx);
k2 = (ry1 - dy) * w1 + (rx0 - dx) + 1;
// walk through rows (Y)
for (k = k1; k < k2; k += w1) {
// walk through cols (X)
for (q = 0; q < len; q++) {
if (img[k + q] === 1) data[i + q] = 1; // copy only "black" points
}
i += sw;
}
}
// save result of border detection for animation
this.border_ = MagicWandLib.getBorderIndices({ data: data, width: sw, height: sh });
}
this.context.clearRect(0, 0, w, h);
var ind = this.border_; // array of indices of the boundary points
if (!ind) return false;
var x, y,
imgData = this.context.createImageData(w, h), // result image
res = imgData.data,
hatchLength = this.hatchLength,
hatchLength2 = hatchLength * 2,
hatchOffset = this.hatchOffset_;
len = ind.length;
for (j = 0; j < len; j++) {
i = ind[j];
x = i % sw; // calc x by index
y = (i - x) / sw; // calc y by index
x -= 1; // viewport coordinates transformed from extend (+1 px) viewport
y -= 1;
if (x < 0 || x > ix || y < 0 || y > iy) continue;
k = (y * w + x) * 4; // result image index by viewport coordinates
if ((x + y + hatchOffset) % hatchLength2 < hatchLength) { // detect hatch color
res[k + 3] = 255; // black, set only alpha
} else {
res[k] = 255; // white
res[k + 1] = 255;
res[k + 2] = 255;
res[k + 3] = 255;
}
}
this.context.putImageData(imgData, 0, 0);
this.render();
return true;
}
//#endregion
/**
* Get color of the snapshot by screen coordinates
* @param {number} x
* @param {number} y
* @return {Array<number>} RGBA color
*/
getPixelColor(x, y) {
var i = (y * this.size.w + x) * this.bytes;
var res = [this.snapshot[i], this.snapshot[i + 1], this.snapshot[i + 2], this.snapshot[i + 3]];
return res;
}
/**
* Create data URL from the snapshot
* @param {string} [format="image/png"] Image type
* @return {string} Image binary content URL
*/
toImageUrl(format = "image/png") {
if (!this.isReady() || !this.size) return null;
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
context.canvas.width = this.size.w;
context.canvas.height = this.size.h;
var imgData = context.createImageData(this.size.w, this.size.h);
for (var i = 0; i < this.snapshot.length; i++) {
imgData.data[i] = this.snapshot[i];
}
context.putImageData(imgData, 0, 0);
return canvas.toDataURL(format);
}
}
|
JavaScript
|
class MagicWand extends PointerInteraction {
/**
* @param {MagicWandOptions} options MagicWand options
*/
constructor(options) {
super();
/**
* Layer(s) for scanning
* @protected
* @type {ol/layer/Layer|Array<ol/layer/Layer>}
*/
this.layers = options.layers;
/**
* @type {number}
*/
this.hatchLength = options.hatchLength == null ? 4 : options.hatchLength;
/**
* @type {number}
*/
this.hatchTimeout = options.hatchTimeout == null ? 300 : options.hatchTimeout;
/**
* @type {number}
*/
this.colorThreshold = options.colorThreshold == null ? 15 : options.colorThreshold;
/**
* @type {number}
*/
this.blurRadius = options.blurRadius == null ? 5 : options.blurRadius;
/**
* @type {boolean}
*/
this.includeBorders = options.includeBorders == null ? true : options.includeBorders;
/**
* @private
* @type {number}
*/
this.currentThreshold_ = 0;
/**
* History of binary masks
* @type {MaskHistory}
*/
this.history = options.history == false ? null : new MaskHistory();
/**
* Tile for displaying mask
* @private
* @type {TileMask}
*/
this.tileMask_ = null;
/**
* @private
* @type {boolean}
*/
this.isMapConnect_ = false;
/**
* @private
* @type {boolean}
*/
this.allowDraw_ = false;
/**
* @private
* @type {boolean}
*/
this.addMode_ = false;
/**
* @private
* @type {Mask}
*/
this.oldMask_ = null;
/**
* @private
* @type {Point}
*/
this.downPoint_ = null;
/**
* @private
* @type {ol/events/Array<EventsKey>}
*/
this.mapKeys_ = null;
/**
* @private
* @type {boolean}
*/
this.allowAdd_ = options.addMode == null ? true : options.addMode;
/**
* @private
* @type {boolean}
*/
this.isDebug_ = options.debugMode == null ? false : options.debugMode;
if (options.waitClass) this.waitClass = options.waitClass;
if (options.drawClass) this.drawClass = options.drawClass;
if (options.addClass) this.addClass = options.addClass;
}
//#region Handlers
/**
* @inheritDoc
* @param {ol/MapBrowserPointerEvent} evt
*/
handleDragEvent(evt) {
let e = evt.originalEvent;
// log current pixel color (debug mode)
//var pixel = this.getMap().getEventPixel(e);
//if (this.tileMask_ && this.tileMask_.isReady()) {
// var r = this.tileMask_.getPixelColor(Math.round(pixel.x), Math.round(pixel.y));
// console.log(r[0] + " " + r[1] + " " + r[2] + " " + r[3]);
//}
//return;
if (this.allowDraw_) {
var pixel = this.getMap().getEventPixel(e);
var x = Math.round(pixel[0]);
var y = Math.round(pixel[1]);
var px = this.downPoint_.x;
var py = this.downPoint_.y;
if (x != px || y != py) {
// color threshold calculation
var dx = x - px;
var dy = y - py;
var len = Math.sqrt(dx * dx + dy * dy);
var adx = Math.abs(dx);
var ady = Math.abs(dy);
var sign = adx > ady ? dx / adx : dy / ady;
sign = sign < 0 ? sign / 5 : sign / 3;
var thres = Math.min(Math.max(this.colorThreshold + Math.round(sign * len), 1), 255); // 1st method
//var thres = Math.min(Math.max(this.colorThreshold + dx / 2, 1), 255); // 2nd method
//var thres = Math.min(this.colorThreshold + Math.round(len / 3), 255); // 3rd method
if (thres != this.currentThreshold_) {
this.currentThreshold_ = thres;
this.drawMask_(px, py);
}
}
}
return !this.allowDraw_;
}
/**
* @inheritDoc
* @param {ol/MapBrowserPointerEvent} evt
*/
handleDownEvent(evt) {
let e = evt.originalEvent;
if (e.button == 2) { // right button - draw mask
if (!this.tileMask_ || !this.tileMask_.isReady() || this.getMap().getView().getAnimating()) return;
let px = this.getMap().getEventPixel(e);
this.downPoint_ = { x: Math.round(px[0]), y: Math.round(px[1]) }; // mouse down point (base point)
this.allowDraw_ = true;
this.addMode_ = e.ctrlKey; // || e.shiftKey;
this.drawMask_(this.downPoint_.x, this.downPoint_.y);
} else { // reset all
this.allowDraw_ = false;
this.oldMask_ = null;
this.addMode_ = false;
return false;
}
return true;
}
/**
* @inheritDoc
* @param {ol/MapBrowserPointerEvent} evt
*/
handleUpEvent(evt) {
let e = evt.originalEvent;
// add current mask to history
if (this.allowDraw_ && this.tileMask_ && this.history) {
this.history.addMask(this.tileMask_.mask);
}
// reset all
this.currentThreshold_ = this.colorThreshold;
this.allowDraw_ = false;
this.oldMask_ = null;
this.addMode_ = false;
return false;
}
/**
* @private
*/
onMapKeyDown_(evt) {
let map = this.getMap();
if (map) {
let div = map.getTargetElement();
if (evt.keyCode == 17 && this.addClass != null && this.allowAdd_) // ctrl press (add mode on)
div.classList.add(this.addClass);
}
}
/**
* @private
*/
onMapKeyUp_(evt) {
let map = this.getMap();
if (map) {
let div = map.getTargetElement();
let view = map.getView();
if (evt.keyCode == 17 && this.allowAdd_) div.classList.remove(this.addClass); // ctrl unpress (add mode off)
if (evt.keyCode == 83 && this.isDebug_) { // 's' key - show current snapshot (debug mode)
if (!this.tileMask_ || !this.tileMask_.isReady() || view.getInteracting() || view.getAnimating()) return;
this.tileMask_.context.clearRect(0, 0, this.tileMask_.size.w, this.tileMask_.size.h);
this.tileMask_.render(true);
}
if (evt.keyCode == 67 && this.isDebug_) { // 'c' key - show contours (debug mode)
if (!this.tileMask_ || !this.tileMask_.isReady() || view.getInteracting() || view.getAnimating()) return;
var cs = this.getContours();
if (cs == null) return;
var outer = cs.filter((c) => !c.inner);
var inner = cs.filter((c) => c.inner);
console.log(`Contours: ${outer.length}[${inner.length}]`);
var ctx = this.tileMask_.context;
ctx.clearRect(0, 0, this.tileMask_.size.w, this.tileMask_.size.h);
var i, j, ps;
// outer
ctx.beginPath();
for (i = 0; i < outer.length; i++) {
ps = outer[i].points;
ctx.moveTo(ps[0].x, ps[0].y);
//ctx.arc(ps[0].x, ps[0].y, 2, 0, 2 * Math.PI);
for (j = 1; j < ps.length; j++) {
ctx.lineTo(ps[j].x, ps[j].y);
//ctx.arc(ps[j].x, ps[j].y, 1, 0, 2 * Math.PI);
}
}
ctx.strokeStyle = "green";
ctx.stroke();
// inner
ctx.beginPath();
for (i = 0; i < inner.length; i++) {
ps = inner[i].points;
ctx.moveTo(ps[0].x, ps[0].y);
//ctx.arc(ps[0].x, ps[0].y, 2, 0, 2 * Math.PI);
for (j = 1; j < ps.length; j++) {
ctx.lineTo(ps[j].x, ps[j].y);
//ctx.arc(ps[j].x, ps[j].y, 1, 0, 2 * Math.PI);
}
}
ctx.strokeStyle = "red";
ctx.stroke();
this.tileMask_.render(true);
}
if (evt.ctrlKey && this.history) { // history manipulations
var img = null;
if (evt.keyCode == 89) img = this.history.redo(); // ctrl + y
if (evt.keyCode == 90) img = this.history.undo(); // ctrl + z
if (img && this.tileMask_) this.tileMask_.setMask(img); // apply mask from history
}
}
}
//#endregion
/**
* @inheritDoc
*/
setActive(active) {
if (!this.getActive() && active) {
this.onActivate_();
}
if (this.getActive() && !active) {
this.onDeactivate_();
}
super.setActive(active);
}
/**
* @private
*/
onActivate_() {
let map = this.getMap();
if (map) {
this.connectToMap(map);
this.createMask(map);
}
}
/**
* @private
*/
onDeactivate_() {
this.allowDraw_ = false;
this.downPoint_ = null;
this.oldMask_ = null;
this.addMode_ = false;
this.disconnectFromMap();
if (this.tileMask_) this.tileMask_.dispose();
this.tileMask_ = null;
this.clearHistory_();
}
/**
* @inheritDoc
*/
disposeInternal() {
this.onDeactivate_();
if (this.history) this.history.dispose();
this.history = null;
this.layers = null;
super.disposeInternal();
}
//#region Map
/**
* @inheritDoc
*/
setMap(map) {
this.onDeactivate_();
super.setMap(map);
if (this.getActive()) {
this.onActivate_();
}
}
/**
* @protected
* @param {ol/Map} map
*/
connectToMap(map) {
this.mapKeys_ = [
map.getView().on('change:resolution', this.onViewResChanged_.bind(this))
];
this.keyDownListener = this.onMapKeyDown_.bind(this);
this.keyUpListener = this.onMapKeyUp_.bind(this);
document.addEventListener("keydown", this.keyDownListener);
document.addEventListener("keyup", this.keyUpListener);
let div = map.getTargetElement();
if (this.drawClass) div.classList.add(this.drawClass);
this.onMapContextMenuListener_ = (e) => {
if (this.getActive()) e.preventDefault();
};
div.addEventListener("contextmenu", this.onMapContextMenuListener_);
}
/**
* @protected
*/
disconnectFromMap() {
if (this.mapKeys_) {
unByKey(this.mapKeys_);
this.mapKeys_ = null;
}
document.removeEventListener("keydown", this.keyDownListener);
document.removeEventListener("keyup", this.keyUpListener);
let map = this.getMap();
if (map) {
let div = map.getTargetElement();
div.classList.remove(this.drawClass);
div.classList.remove(this.waitClass);
div.classList.remove(this.addClass);
div.removeEventListener("contextmenu", this.onMapContextMenuListener_);
}
}
/**
* @private
*/
onViewResChanged_() {
this.clearHistory_();
}
/**
* @private
*/
clearHistory_() {
if (this.history) this.history.clear();
}
/**
* Get pixel offset in the main world
* @param {ol/Map} map
* @return {PixelOffset}
*/
static getMainWorldOffset(map) {
let extent = map.getView().getProjection().getExtent();
let topLeft = map.getPixelFromCoordinate([extent[0], extent[3]]);
topLeft = { x: Math.round(-topLeft[0]), y: Math.round(-topLeft[1]) };
let bottomRight = map.getPixelFromCoordinate([extent[2], extent[1]]);
bottomRight = { x: Math.round(-bottomRight[0]), y: Math.round(-bottomRight[1]) };
let w = topLeft.x - bottomRight.x;
let x = topLeft.x % w;
return { x: x < 0 ? x + w : x, y: topLeft.y, width: w };
}
//#endregion
//#region Mask
/**
* @protected
* @param {ol/Map} map
*/
createMask(map) {
let div = map.getTargetElement();
this.tileMask_ = new TileMask({ map: map, layers: this.layers, hatchTimeout: this.hatchTimeout, hatchLength: this.hatchLength });
if (this.waitClass) {
this.tileMask_.on("scanStarted", () => div.classList.add(this.waitClass));
this.tileMask_.on("scanFinished", () => div.classList.remove(this.waitClass));
}
}
/**
* Concatenate mask and old mask
* @private
* @param {Mask} mask
* @param {Mask} old
* @return {Mask} concatenated mask
*/
concatMask_(mask, old) {
var data1 = old.data,
data2 = mask.data,
w1 = old.width,
w2 = mask.width,
px1 = old.globalOffset.x,
py1 = old.globalOffset.y,
px2 = mask.globalOffset.x,
py2 = mask.globalOffset.y,
b1 = old.bounds,
b2 = mask.bounds,
px = Math.min(b1.minX + px1, b2.minX + px2), // global offset for new mask (by min in bounds)
py = Math.min(b1.minY + py1, b2.minY + py2),
b = { // bounds for new mask include all of the pixels [0,0,width,height] (reduce to bounds)
minX: 0,
minY: 0,
maxX: Math.max(b1.maxX + px1, b2.maxX + px2) - px,
maxY: Math.max(b1.maxY + py1, b2.maxY + py2) - py
},
w = b.maxX + 1, // size for new mask
h = b.maxY + 1,
i, j, k, k1, k2, len;
var result = new Uint8Array(w * h);
// copy all old mask
len = b1.maxX - b1.minX + 1;
i = (py1 - py + b1.minY) * w + (px1 - px + b1.minX);
k1 = b1.minY * w1 + b1.minX;
k2 = b1.maxY * w1 + b1.minX + 1;
// walk through rows (Y)
for (k = k1; k < k2; k += w1) {
result.set(data1.subarray(k, k + len), i); // copy row
i += w;
}
// copy new mask (only "black" pixels)
len = b2.maxX - b2.minX + 1;
i = (py2 - py + b2.minY) * w + (px2 - px + b2.minX);
k1 = b2.minY * w2 + b2.minX;
k2 = b2.maxY * w2 + b2.minX + 1;
// walk through rows (Y)
for (k = k1; k < k2; k += w2) {
// walk through cols (X)
for (j = 0; j < len; j++) {
if (data2[k + j] === 1) result[i + j] = 1;
}
i += w;
}
return {
data: result,
width: w,
height: h,
bounds: b,
globalOffset: {
x: px,
y: py
}
};
}
/**
* Create mask for the specified pixel position
* @private
* @param {number} x
* @param {number} y
* @return {boolean}
*/
drawMask_(x, y) {
if (!this.tileMask_ || !this.tileMask_.isReady()) return false;
var size = this.tileMask_.size;
var map = this.getMap();
var ms = map.getSize();
var mapSize = { w: ms[0], h: ms[1] };
if (size.w != mapSize.w || size.h != mapSize.h) { // if map size is not equal to snapshot size then recreate snapshot
this.tileMask_.scan();
return false;
//if (!this.tileMask_.isReady()) return false;
//size = this.tileMask_.size;
}
var tile = this.tileMask_;
var offset = MagicWand.getMainWorldOffset(map); // snapshot (viewport) offset in the main world
var image = {
data: this.tileMask_.snapshot,
width: size.w,
height: size.h,
bytes: this.tileMask_.bytes
};
var mask = null;
if (this.allowAdd_ && this.addMode_ && tile.mask) {
if (!this.oldMask_) {
var img = tile.mask;
var bounds = img.bounds;
// clone mask
this.oldMask_ = {
data: new Uint8Array(img.data),
width: img.width,
height: img.height,
bounds: {
minX: bounds.minX,
maxX: bounds.maxX,
minY: bounds.minY,
maxY: bounds.maxY
},
globalOffset: {
x: img.globalOffset.x,
y: img.globalOffset.y
}
};
var oldOffset = this.oldMask_.globalOffset,
offsets = [{ x: oldOffset.x, y: oldOffset.y }]; // add old mask offset (current world)
let i, j, k, k1, k2, len, off,
x0, y0, x1, y1, dx, dy,
rx0, rx1, ry0, ry1,
w = image.width,
h = image.height,
data = new Uint8Array(w * h),
old = this.oldMask_.data,
w1 = this.oldMask_.width,
b = this.oldMask_.bounds,
ix = image.width - 1, // right bottom of image (left top = [0,0])
iy = image.height - 1,
offsetsLen = offsets.length;
// copy visible data from old mask for floodfill (considering 'multiWorld' and neighboring worlds)
for (j = 0; j < offsetsLen; j++) {
off = offsets[j]; // old mask offset in the global basis
dx = off.x - offset.x; // delta for the transformation to image basis
dy = off.y - offset.y;
x0 = dx + b.minX; // left top of old mask (in image basis)
y0 = dy + b.minY;
x1 = dx + b.maxX; // right bottom of old mask (in image basis)
y1 = dy + b.maxY;
// intersection of the old mask with the image (viewport)
if (!(x1 < 0 || x0 > ix || y1 < 0 || y0 > iy)) {
rx0 = x0 > 0 ? x0 : 0; // result of the intersection
ry0 = y0 > 0 ? y0 : 0;
rx1 = x1 < ix ? x1 : ix;
ry1 = y1 < iy ? y1 : iy;
} else {
continue;
}
// copy result of the intersection to mask data for floodfill
len = rx1 - rx0 + 1;
i = ry0 * w + rx0;
k1 = (ry0 - dy) * w1 + (rx0 - dx);
k2 = (ry1 - dy) * w1 + (rx0 - dx) + 1;
// walk through rows (Y)
for (k = k1; k < k2; k += w1) {
data.set(old.subarray(k, k + len), i); // copy row
i += w;
}
}
this.oldMask_.visibleData = data;
}
// create a new mask considering the current visible data
mask = MagicWandLib.floodFill(image, x, y, this.currentThreshold_, this.oldMask_.visibleData, this.includeBorders);
if (!mask) return false;
// blur a new mask considering the current visible data
if (this.blurRadius > 0) mask = MagicWandLib.gaussBlurOnlyBorder(mask, this.blurRadius, this.oldMask_.visibleData);
mask.globalOffset = offset;
// check a shortest path for concatenation
let distance = (offset.x + mask.width / 2) - (this.oldMask_.globalOffset.x + this.oldMask_.width / 2);
if (Math.abs(distance) > offset.width / 2) {
mask.globalOffset.x = distance > 0 ? offset.x - offset.width : offset.x + offset.width;
}
mask = this.concatMask_(mask, this.oldMask_); // old mask + new mask
} else {
mask = MagicWandLib.floodFill(image, x, y, this.currentThreshold_, null, this.includeBorders);
if (this.blurRadius > 0) mask = MagicWandLib.gaussBlurOnlyBorder(mask, this.blurRadius);
mask.globalOffset = offset;
}
tile.setMask(mask);
return true;
}
//#endregion
//#region Public
/**
* Set map layers to create snapshot and to draw a mask
* @param {ol/layer/Layer|Array<ol/layer/Layer>} layers Layer(s) for scanning
* @return {boolean}
*/
setLayers(layers) {
if (!layers) return false;
this.layers = layers;
return !this.tileMask_ ? false : this.tileMask_.setLayers(layers);
}
/**
* Return contours of binary mask
* @param {number} [simplifyTolerant=1] Tool parameter: Simplify tolerant (see method 'simplifyContours' in 'magic-wand-tool')
* @param {number} [simplifyCount=30] Tool parameter: Simplify count (see method 'simplifyContours' in 'magic-wand-tool')
* @return {Array<Contour>} Contours in the viewport basis
*/
getContours(simplifyTolerant = 1, simplifyCount = 30) {
if (!this.tileMask_.mask) return null;
var offset = MagicWand.getMainWorldOffset(this.getMap()); // viewport offset in the main world
var i, j, points, len, plen, c,
mask = this.tileMask_.mask,
dx = mask.globalOffset.x - Math.round(offset.x),
dy = mask.globalOffset.y - Math.round(offset.y),
contours = MagicWandLib.traceContours(mask),
result = [];
if (simplifyTolerant > 0) contours = MagicWandLib.simplifyContours(contours, simplifyTolerant, simplifyCount);
return contours.map(c => {
c.initialCount = c.initialCount || c.points.length;
c.points.forEach(p => {
p.x += dx;
p.y += dy;
});
return c;
});
}
/**
* Get a data of the current mask
* @return {OffsetMask} Mask data in the viewport basis
*/
getMask() {
if (this.tileMask_) {
let mask = this.tileMask_.mask;
let offset = MagicWand.getMainWorldOffset(this.getMap()); // viewport offset in the main world
let x, y, k = 0,
data = mask.data,
bounds = mask.bounds,
maskW = mask.width,
sw = bounds.maxX - bounds.minX + 1,
sh = bounds.maxY - bounds.minY + 1,
res = new Uint8Array(sw * sh);
for (y = bounds.minY; y <= bounds.maxY; y++) {
for (x = bounds.minX; x <= bounds.maxX; x++) {
res[k++] = data[y * maskW + x];
}
}
return {
data: res,
size: {
w: sw,
h: sh
},
offset: {
x: mask.globalOffset.x + bounds.minX - Math.round(offset.x),
y: mask.globalOffset.y + bounds.minY - Math.round(offset.y)
}
};
}
return null;
}
/**
* Clear the current mask and remove it from the map view
*/
clearMask() {
if (this.tileMask_) {
this.tileMask_.clearMask();
}
}
//#endregion
}
|
JavaScript
|
class MaskHistory extends BaseObject {
constructor() {
super();
/**
* Array of masks
* @type {Array<Mask>}
*/
this.masks = [];
/**
* Current index of history array
* @type {number}
*/
this.current = -1;
}
/**
* @inheritDoc
*/
disposeInternal() {
this.masks = null;
super.disposeInternal();
}
clear() {
this.masks.length = 0;
this.current = -1;
}
/**
* @param {Mask}
* @return {boolean}
*/
addMask(mask) {
if (!mask) return false;
this.current++;
this.masks.length = this.current;
this.masks.push(mask);
return true;
}
/**
* @return {Mask}
*/
getCurrent() {
return this.current > -1 ? this.masks[this.current] : null;
}
/**
* @return {boolean}
*/
allowUndo() {
return this.current > 0;
}
/**
* @return {boolean}
*/
allowRedo() {
return this.current < this.masks.length - 1;
}
/**
* @return {Mask}
*/
undo() {
if (!this.allowUndo()) return null;
this.current--;
return this.getCurrent();
}
/**
* @return {Mask}
*/
redo() {
if (!this.allowRedo()) return null;
this.current++;
return this.getCurrent();
}
}
|
JavaScript
|
class Investment extends Resource {
constructor(inv) {
if (typeof(inv.principle) !== 'number') {
throw new BankError('You must provide a valid amount to invest with!');
}
if (inv.principle < Investment.MINIMUM) {
return new BankError(`Investment amount must be at least ${Investment.MINIMUM}.`);
}
super(Constants.TEMPLATE, inv);
}
get current() {
return Date.now();
}
get elapsed() {
return this.current - this.started;
}
get interest() {
if (this.compounding && !isNaN(this.compounding) && isFinite(this.compounding)) {
return this.compoundInterest;
} else {
return this.continuousInterest;
}
}
get compoundInterest() {
return Investment.compoundInterest(this.principle, this.elapsed / Investment.TIME_SCALE, this.rate, this.compounding);
}
get continuousInterest() {
return Investment.continuousInterest(this.principle, this.elapsed / Investment.TIME_SCALE, this.rate);
}
summary(Bank, Account) {
return {
title: 'Investment Transcript',
timestamp: new Date(this.started),
fields: [
{
name: 'Account',
value: Account ? md.mention(Account) : '<anonymous>',
inline: true
},
{
name: 'Principle',
value: Bank.formatCredits(this.principle),
inline: true
},
{
name: 'Interest Earned',
value: Bank.formatCredits(this.interest),
inline: true
},
{
name: 'Time Elapsed',
value: fmt.timestamp(this.elapsed),
inline: true
},
{
name: 'Interest Rate',
value: fmt.percent(this.rate) + ' (daily)',
inline: true
},
{
name: 'Interest Compounding',
value: isFinite(this.compounding) ? this.compounding + 'x/day' : 'continuous',
inline: true
}
]
};
}
shortSummary(Bank) {
return {
name: Bank.formatCredits(this.principle) + ' @ ' + fmt.percent(this.rate) + ' | ' + fmt.timestamp(this.elapsed),
value: Bank.formatCredits(this.interest)
};
}
static get MINIMUM() {
return Constants.MINIMUM;
}
static get RATE() {
return Constants.RATE;
}
static get COMPOUNDING() {
return Constants.COMPOUNDING;
}
static get TIME_SCALE() {
return Constants.TIME_SCALE;
}
static interest(principle, time, rate = this.RATE, compounding = this.COMPOUNDING) {
if (compounding && isFinite(compounding)) {
return this.compoundInterest(principle, time, rate, compounding);
} else {
return this.continuousInterest(principle, time, rate);
}
}
static compoundInterest(principle, time, rate = this.RATE, compounding = this.COMPOUNDING) {
return principle * (Math.pow((1 + rate / compounding), compounding * time) - 1);
}
static continuousInterest(principle, time, rate = this.RATE) {
return principle * (Math.exp(rate * time) - 1);
}
}
|
JavaScript
|
class KeyboardEvent extends UIEvent {
constructor(ev) {
// [Constructor(DOMString typeArg, optional KeyboardEventInit keyboardEventInitDict)]
// interface KeyboardEvent : UIEvent {
// // KeyLocationCode
// const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
// const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
// const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
// const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;
// readonly attribute DOMString key;
// readonly attribute DOMString code;
// readonly attribute unsigned long location;
// readonly attribute boolean ctrlKey;
// readonly attribute boolean shiftKey;
// readonly attribute boolean altKey;
// readonly attribute boolean metaKey;
// readonly attribute boolean repeat;
// readonly attribute boolean isComposing;
// boolean getModifierState (DOMString keyArg);
// };
super(ev);
/**
* @name KeyboardEvent#DOM_KEY_LOCATION_STANDARD
* @type Number
*/
this.DOM_KEY_LOCATION_STANDARD = 0x00;
/**
* @name KeyboardEvent#DOM_KEY_LOCATION_LEFT
* @type Number
*/
this.DOM_KEY_LOCATION_LEFT = 0x01;
/**
* @name KeyboardEvent#DOM_KEY_LOCATION_RIGHT
* @type Number
*/
this.DOM_KEY_LOCATION_RIGHT = 0x02;
/**
* @name KeyboardEvent#DOM_KEY_LOCATION_NUMPAD
* @type Number
*/
this.DOM_KEY_LOCATION_NUMPAD = 0x03;
/**
* @name KeyboardEvent#key
* @type String
*/
this.key = ev.key;
/**
* @name KeyboardEvent#code
* @type String
*/
this.code = ev.code;
/**
* @name KeyboardEvent#location
* @type Number
*/
this.location = ev.location;
/**
* @name KeyboardEvent#ctrlKey
* @type Boolean
*/
this.ctrlKey = ev.ctrlKey;
/**
* @name KeyboardEvent#shiftKey
* @type Boolean
*/
this.shiftKey = ev.shiftKey;
/**
* @name KeyboardEvent#altKey
* @type Boolean
*/
this.altKey = ev.altKey;
/**
* @name KeyboardEvent#metaKey
* @type Boolean
*/
this.metaKey = ev.metaKey;
/**
* @name KeyboardEvent#repeat
* @type Boolean
*/
this.repeat = ev.repeat;
/**
* @name KeyboardEvent#isComposing
* @type Boolean
*/
this.isComposing = ev.isComposing;
/**
* @name KeyboardEvent#keyCode
* @type String
* @deprecated
*/
this.keyCode = ev.keyCode;
}
/**
* Return the name of the event type
*
* @method
*
* @return {String} Name of the event type
*/
toString() {
return 'KeyboardEvent';
};
}
|
JavaScript
|
class EntitiesPrototype extends Array {
constructor() {
super();
// TODO: garbage collect the map
this._map = {};
}
get(mesh) {
// clicking accessories should select main object
// while (!jqueryObject.parent().is("body")) {
// jqueryObject = jqueryObject.parent();
// }
// console.log(mesh);
for (var i = 0; i < this.length; i ++) {
if (mesh == this[i].view) {
return this[i];
}
}
return null;
}
push(entity) {
super.push(entity);
this._map[entity._id] = entity;
if (entity.team == My.TEAM) {
socket.emit('create', serialize(entity));
}
}
remove(entity) {
for (var i = 0; i < this.length; i ++) {
if (this[i] == entity) {
this.splice(i, 1);
}
}
}
lookup(id) {
return this._map[id];
}
isEntity(x) {
return x instanceof Entity;
}
isEnemy(x, y) {
// true for opposite team and aliens, false for mines
return x instanceof Attackable && y instanceof Attackable && x.team != y.team;
}
is(x, type) {
return x instanceof Entity && x.type == type;
}
myRobot(x) {
return x instanceof Robot && x.team == My.TEAM;
}
distance(entity1, entity2) {
var ent1X = entity1.view.position['x'];
var ent1Z = entity1.view.position['z'];
var ent2X = entity2.view.position['x'];
var ent2Z = entity2.view.position['z'];
var playerX
// //var robotRadius = player.view.geometry.boundingSphere.radius;
// var playerX = (player.view.position.x + robotRadius);
// var playerZ = (player.view.position.z + robotRadius);
// var entityX = (entity.view.position.x + 0 / 2);
// var entityZ = (entity.view.position.z + 0 / 2);// entity.view.height()
return Util.distance(ent1X - ent2X, ent1Z - ent2Z);
}
}
|
JavaScript
|
class _Either {
constructor(data) {
definer.public.readonly(this,
'data', data
);
}
}
|
JavaScript
|
class _Left extends _Either {
constructor(data) {
super(data);
definer.public.readonly(this,
'type', _EitherType.LEFT
);
}
}
|
JavaScript
|
class _Right extends _Either {
constructor(data) {
super(data);
definer.public.readonly(this,
'type', _EitherType.RIGHT
);
}
}
|
JavaScript
|
class AppConfig {
@Config("relayerProvider")
setupResources(relayerProvider) {
relayerProvider.createApi("resources", Resources, "http://www.example.com/resources")
}
}
|
JavaScript
|
class Monitor {
constructor(ctx) {
setInterval(() => (async () => {
let status = (await RecordingService.status(ctx)).status;
if (status === SessionStatus.RUNNING && desktopIdle.getIdleTime() > STOP_SESSION_THRESHOLD) {
await RecordingService.stop(ctx);
notifier.notify({
'title': 'Stopped Focus Session',
'message': 'Stopped due to inactivity. Start another?',
closeLabel: 'Close',
timeout: 10,
sound: true,
actions: "Start"
}, (error, response, metadata) => (async () => {
if (response === 'activate') {
await RecordingService.start(ctx);
}
})().catch(e => console.log(e)));
}
})().catch(e => console.log(e)), 30000);
}
}
|
JavaScript
|
class MapKmlLayer {
constructor(_map, _ngZone) {
this._map = _map;
this._ngZone = _ngZone;
this._eventManager = new MapEventManager(this._ngZone);
this._options = new BehaviorSubject({});
this._url = new BehaviorSubject('');
this._destroyed = new Subject();
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.click
*/
this.kmlClick = this._eventManager.getLazyEmitter('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/kml
* #KmlLayer.defaultviewport_changed
*/
this.defaultviewportChanged = this._eventManager.getLazyEmitter('defaultviewport_changed');
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.status_changed
*/
this.statusChanged = this._eventManager.getLazyEmitter('status_changed');
}
set options(options) {
this._options.next(options || {});
}
set url(url) {
this._url.next(url);
}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions().pipe(take(1)).subscribe(options => {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => this.kmlLayer = new google.maps.KmlLayer(options));
this._assertInitialized();
this.kmlLayer.setMap(this._map.googleMap);
this._eventManager.setTarget(this.kmlLayer);
});
this._watchForOptionsChanges();
this._watchForUrlChanges();
}
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
if (this.kmlLayer) {
this.kmlLayer.setMap(null);
}
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getDefaultViewport
*/
getDefaultViewport() {
this._assertInitialized();
return this.kmlLayer.getDefaultViewport();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getMetadata
*/
getMetadata() {
this._assertInitialized();
return this.kmlLayer.getMetadata();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getStatus
*/
getStatus() {
this._assertInitialized();
return this.kmlLayer.getStatus();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getUrl
*/
getUrl() {
this._assertInitialized();
return this.kmlLayer.getUrl();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getZIndex
*/
getZIndex() {
this._assertInitialized();
return this.kmlLayer.getZIndex();
}
_combineOptions() {
return combineLatest([this._options, this._url]).pipe(map(([options, url]) => {
const combinedOptions = Object.assign(Object.assign({}, options), { url: url || options.url });
return combinedOptions;
}));
}
_watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
if (this.kmlLayer) {
this._assertInitialized();
this.kmlLayer.setOptions(options);
}
});
}
_watchForUrlChanges() {
this._url.pipe(takeUntil(this._destroyed)).subscribe(url => {
if (url && this.kmlLayer) {
this._assertInitialized();
this.kmlLayer.setUrl(url);
}
});
}
_assertInitialized() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._map.googleMap) {
throw Error('Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.');
}
if (!this.kmlLayer) {
throw Error('Cannot interact with a Google Map KmlLayer before it has been ' +
'initialized. Please wait for the KmlLayer to load before trying to interact with it.');
}
}
}
}
|
JavaScript
|
class Neo4jError extends Error {
/**
* @constructor
* @param {string} message - The error message.
* @param {string} code - Optional error code. Will be populated when error originates in the database.
*/
constructor(message, code = 'N/A') {
super( message );
this.message = message;
this.code = code;
this.name = "Neo4jError"
}
}
|
JavaScript
|
class Writer {
constructor(tracks) {
this.data = [];
var trackType = tracks.length > 1 ? Constants.HEADER_CHUNK_FORMAT1 : Constants.HEADER_CHUNK_FORMAT0;
var numberOfTracks = Utils.numberToBytes(tracks.length, 2); // two bytes long
// Header chunk
this.data.push(new Chunk({
type: Constants.HEADER_CHUNK_TYPE,
data: trackType.concat(numberOfTracks, Constants.HEADER_CHUNK_DIVISION)}));
// Track chunks
tracks.forEach(function(track, i) {
track.addEvent(new MetaEvent({data: Constants.META_END_OF_TRACK_ID}));
this.data.push(track);
}, this);
}
/**
* Builds the file into a Uint8Array
* @return {Uint8Array}
*/
buildFile() {
var build = [];
// Data consists of chunks which consists of data
this.data.forEach((d) => build = build.concat(d.type, d.size, d.data));
return new Uint8Array(build);
}
/**
* Convert file buffer to a base64 string. Different methods depending on if browser or node.
* @return {string}
*/
base64() {
if (typeof btoa === 'function') return btoa(String.fromCharCode.apply(null, this.buildFile()));
return new Buffer(this.buildFile()).toString('base64');
}
/**
* Get the data URI.
* @return {string}
*/
dataUri() {
return 'data:audio/midi;base64,' + this.base64();
}
/**
* Output to stdout
* @return {string}
*/
stdout() {
return process.stdout.write(new Buffer(this.buildFile()));
}
/**
* Save to MIDI file
* @param {string} filename
*/
saveMIDI(filename) {
var buffer = new Buffer(this.buildFile());
fs.writeFile(filename + '.mid', buffer, function (err) {
if(err) return console.log(err);
});
}
}
|
JavaScript
|
class PublicKey extends CompositeType {
/**
* Constructor.
*
* @param {String} id
* @param {Boolean} omitXYLenghts
*/
constructor(id = null, omitXYLenghts = false) {
super(id || 'public_key');
this.addSubType(new Curve('curve'));
// oh come on..
if (omitXYLenghts) {
this.addSubType(
new BytesWithoutLength('x')
.description('The X value of the public key.')
);
this.addSubType(new BytesWithoutLength('y'));
} else {
this.addSubType(
new BytesWithLength('x', 2, 'x_length', 'Length of X value')
.description('The X value of the public key.')
);
this.addSubType(
new BytesWithLength('y', 2, 'y_length', 'Length of Y value')
.description('The X value of the public key.')
);
}
}
/**
* Reads a value and returns a new PascalCoin PublicKey instance.
*
* @param {BC|Buffer|Uint8Array|String} bc
* @param {Object} options
* @param {*} all
* @returns {PublicKeyType}
*/
decodeFromBytes(bc, options = {}, all = null) {
const decoded = super.decodeFromBytes(bc);
return new PublicKeyType(decoded.x, decoded.y, decoded.curve);
}
/**
* Gets the base58 representation of a public key.
*
* @returns {String}
*/
encodeToBase58(publicKey) {
const prefix = BC.fromHex('01');
const encoded = this.encodeToBytes(publicKey);
const aux = Sha.sha256(encoded);
const suffix = aux.slice(0, 4);
const raw = BC.concat(prefix, encoded, suffix);
return Base58.encode(raw);
}
/**
* Gets a public key instance from the given base58 string.
*
* @param {String} base58
* @returns {PublicKey}
*/
decodeFromBase58(base58) {
const decoded = Base58.decode(base58);
return this.decodeFromBytes(decoded.slice(1, -4));
}
}
|
JavaScript
|
class Header extends Component {
constructor(props) {
super(props);
this.state = { openDropdown: '' };
}
componentDidMount() {
window.addEventListener('mousedown', this.handleWindowMousedown);
}
componentWillUnmount() {
window.removeEventListener('mousedown', this.handleWindowMousedown);
}
handleWindowMousedown = ({ target }) => {
const isMenuTrigger = parentHasClass(target, 'menu-item', 'menu-trigger');
if (!isMenuTrigger && this.state.openDropdown) {
this.setState({ openDropdown: '' });
}
}
toggleDropdown = (openDropdown) => () => this.setState({ openDropdown });
render() {
return (
<header className="app-header" role="banner">
<div className="breadcrumbs">
<Breadcrumbs t={this.props.t} crumbsConfig={this.props.crumbsConfig} />
</div>
<div className="label">{ this.props.t('header.appName') }</div>
<div className="items-container">
<div className="menu-container">
<button className="menu-trigger" onClick={this.toggleDropdown(docsDropdown)}>
<Svg path={svgs.questionMark} className="item-icon" />
</button>
{
this.state.openDropdown === docsDropdown &&
<div className="menu">
{
docLinks.map(({ url, translationId }) =>
<Link key={translationId}
className="menu-item"
target="_blank"
to={url}>
{ this.props.t(translationId) }
</Link>
)
}
</div>
}
</div>
{
isFunc(this.props.openSystemSettings) &&
<button onClick={this.props.openSystemSettings}>
<Svg path={svgs.settings} className="item-icon" />
</button>
}
{
isFunc(this.props.openUserProfile) &&
<button className="item-icon profile" onClick={this.props.openUserProfile}>
<img src={ProfileImagePath} alt={ this.props.t('header.profile') } />
</button>
}
</div>
</header>
);
}
}
|
JavaScript
|
class CookieKonnector extends BaseKonnector {
/**
* Constructor
*
* @param {function} requestFactoryOptions - Option object passed to requestFactory to
* initialize this.request. It is still possible to change this.request doing :
*
* ```javascript
* this.request = this.requestFactory(...)
* ```
*
* Please not you have to run the connector yourself doing :
*
* ```javascript
* connector.run()
* ```
*/
constructor(requestFactoryOptions) {
super()
if (!this.testSession) {
throw new Error(
'Could not find a testSession method. CookieKonnector needs it to test if a session is valid. Please implement it'
)
}
this._jar = requestFactory().jar()
this.request = this.requestFactory(requestFactoryOptions)
}
/**
* Initializes the current connector with data coming from the associated account
* and also the session
*
* @return {Promise} with the fields as an object
*/
async init(cozyFields, account) {
const fields = await super.init(cozyFields, account)
await this.initSession()
return fields
}
/**
* Hook called when the connector is ended
*/
async end() {
await this.saveSession()
return super.end()
}
/**
* Calls cozy-konnector-libs requestFactory forcing this._jar as the cookie
*
* @param {object} options - requestFactory option
* @return {object} - The resulting request object
*/
requestFactory(options) {
this._jar = this._jar || requestFactory().jar()
return requestFactory({
...options,
jar: this._jar
})
}
/**
* Reset cookie session with a new empty session and save it to the associated account
*
* @return {Promise}
*/
async resetSession() {
log('info', 'Reset cookie session...')
this._jar = requestFactory().jar()
return this.saveSession()
}
/**
* Get the cookie session from the account if any
*
* @return {Promise} true or false if the session in the account exists or not
*/
async initSession() {
const accountData = this.getAccountData()
try {
if (this._account.state === 'RESET_SESSION') {
log('info', 'RESET_SESSION state found')
await this.resetSession()
await this.updateAccountAttributes({ state: null })
}
} catch (err) {
log('warn', 'Could not reset the session')
log('warn', err.message)
}
try {
let jar = null
if (accountData && accountData.auth) {
jar = JSON.parse(accountData.auth[JAR_ACCOUNT_KEY])
}
if (jar) {
log('info', 'found saved session, using it...')
this._jar._jar = CookieJar.fromJSON(jar, this._jar._jar.store)
return true
}
} catch (err) {
log('info', 'Could not parse session')
}
log('info', 'Found no session')
return false
}
/**
* Saves the current cookie session to the account
*
* @return {Promise}
*/
async saveSession() {
const accountData = { ...this._account.data, auth: {} }
accountData.auth[JAR_ACCOUNT_KEY] = JSON.stringify(this._jar._jar.toJSON())
await this.saveAccountData(accountData)
log('info', 'saved the session')
}
/**
* This is signin function from cozy-konnector-libs which is forced to use the current cookies
* and current request from CookieKonnector. It also automatically saves the session after
* signin if it is a success.
*
* @return {Promise}
*/
async signin(options) {
const result = await signin({
...options,
requestInstance: this.request
})
await this.saveSession()
return result
}
/**
* This is saveFiles function from cozy-konnector-libs which is forced to use the current cookies
* and current request from CookieKonnector.
*
* @return {Promise}
*/
saveFiles(entries, fields, options) {
return super.saveFiles(entries, fields, {
...options,
requestInstance: this.request
})
}
/**
* This is saveBills function from cozy-konnector-libs which is forced to use the current cookies
* and current request from CookieKonnector.
*
* @return {Promise}
*/
saveBills(entries, fields, options) {
return super.saveBills(entries, fields, {
...options,
requestInstance: this.request
})
}
}
|
JavaScript
|
class UrlsBox {
_box = document.querySelector("#urls");
/**
* @param {function} RenameModal - The class of the rename modal to be opened
* when a rename button is clicked.
* @param {function} DeleteModal - The class of the delete modal to be
* opened when a delete button is clicked.
*/
constructor(RenameModal, DeleteModal) {
this._renameModal = new RenameModal();
this._deleteModal = new DeleteModal();
this._box.addEventListener("click", this._copyHandler);
this._box.addEventListener("click", this._renameHandler.bind(this));
this._box.addEventListener("click", this._deleteHandler.bind(this));
}
/**
* Copy the the url associated with the clicked copy button to the clipboard.
* @param {MouseEvent} event - The click event.
* @private
*/
async _copyHandler(event) {
if (!event.target.classList.contains("copy-button")) {
return;
}
const urlRow = UrlRow.fromChild(event.target);
try {
await navigator.clipboard.writeText(urlRow.dataset.url);
} catch (error) {
console.log(error);
}
displayNotice("URL has been copied.", "is-success");
}
/**
* Open the rename modal.
* @param {MouseEvent} event - The click event.
* @private
*/
_renameHandler(event) {
if (event.target.classList.contains("rename-button")) {
const urlRow = UrlRow.fromChild(event.target);
this._renameModal.open(urlRow);
}
}
/**
* Open the delete modal.
* @param {MouseEvent} event - The click event.
* @private
*/
_deleteHandler(event) {
if (event.target.classList.contains("delete-button")) {
const urlRow = UrlRow.fromChild(event.target);
this._deleteModal.open(urlRow);
}
}
}
|
JavaScript
|
class UrlRow {
/**
* @param {HTMLElement} div - The url-row div.
*/
constructor(div) {
this._url = div.querySelector(".url");
this.dataset = div.dataset;
}
/**
* Instantiate a url row from one of its child elements.
* @param {HTMLElement} child - A child element of the url row.
* @returns {UrlRow} A UrlRow object.
*/
static fromChild(child) {
let current = child;
while (!current.classList.contains("url-row")) {
current = current.parentNode;
}
return new UrlRow(current);
}
/**
* Set the url associated with this row.
* @param {string} value
*/
set url(value) {
this._url.textContent = value;
this._url.href = value;
this.dataset.url = value;
}
}
|
JavaScript
|
class Modal {
/**
* @param {string} id - The ID of the modal div element.
*/
constructor(id) {
this._div = document.getElementById(id);
this._background = this._div.querySelector(".modal-background");
this._closeButton = this._div.querySelector(".modal-close");
this._background.addEventListener("click", this.close.bind(this));
this._closeButton.addEventListener("click", this.close.bind(this));
document.addEventListener("keydown", this._escapeHandler.bind(this));
}
/**
* Close the modal when the escape key is pressed.
* @param {KeyboardEvent} event - Keydown event.
* @private
*/
_escapeHandler(event) {
if (event.code === "Escape") {
this.close();
}
}
/**
* Whether the modal is open or not.
* @returns {boolean} true or false.
*/
get isOpen() {
return this._div.classList.contains("is-active");
}
/**
* Open the modal.
*/
open() {
this._div.classList.add("is-active");
}
/**
* Close the modal.
*/
close() {
this._div.classList.remove("is-active");
}
}
|
JavaScript
|
class RenameModal extends Modal {
_input = document.querySelector("#rename-input");
_help = document.querySelector("#rename-help");
_confirmButton = document.querySelector("#rename-confirm-button");
constructor() {
super("rename-modal");
this._urlRow = null;
this._helpText = this._help.textContent;
this._confirmButton.addEventListener("click", this._confirmHandler.bind(this));
document.addEventListener("keydown", this._enterHandler.bind(this));
}
/**
* Open the modal and associate it with the url row who's rename button was
* clicked.
* @param {UrlRow} urlRow - Row which contains the clicked rename button.
*/
open(urlRow) {
this._urlRow = urlRow;
this._input.value = "";
this._input.placeholder = urlRow.dataset.name;
this._resetHelpText();
super.open();
this._input.focus();
}
/**
* Send a PATCH request to the modify endpoint. If the request is successful,
* close the modal and change the url in the associated row. If not, set the
* error message to the one received in the response.
*/
async _confirmHandler() {
let response;
try {
response = await fetch(this._urlRow.dataset.endpoint, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrfToken(),
},
body: JSON.stringify({
name: this._input.value,
}),
});
} catch (error) {
console.log(error);
return;
}
const json = await response.json();
if (json.error) {
this._error = json.error;
} else {
this._urlRow.url = json.url;
this._urlRow.dataset.name = json.name;
this.close();
displayNotice("URL has been renamed.", "is-success");
}
}
/**
* Submit the new url name if enter is pressed.
* @param {KeyboardEvent} event - Keydown event.
* @private
*/
_enterHandler(event) {
if (event.key === "Enter" && this.isOpen) {
this._confirmHandler();
}
}
/**
* Set the error message.
* @param {string} value
* @private
*/
set _error(value) {
this._help.textContent = value;
this._help.classList.add("is-danger");
}
/**
* Reset the help text to its original state.
* @private
*/
_resetHelpText() {
this._help.textContent = this._helpText;
this._help.classList.remove("is-danger");
}
}
|
JavaScript
|
class DeleteModal extends Modal {
_confirmButton = document.querySelector("#delete-confirm-button");
_cancelButton = document.querySelector("#delete-cancel-button");
_url = document.querySelector("#delete-url");
constructor() {
super("delete-modal");
this._urlRow = null;
this._confirmButton.addEventListener("click", this._confirmHandler.bind(this));
this._cancelButton.addEventListener("click", this.close.bind(this));
document.addEventListener("keydown", this._enterHandler.bind(this));
}
/**
* Open the modal and associate it with the url row who's delete button was
* clicked.
* @param {UrlRow} urlRow - Row which contains the clicked delete button.
*/
open(urlRow) {
this._urlRow = urlRow;
this._url.textContent = urlRow.dataset.url;
this._url.href = urlRow.dataset.url;
super.open();
}
/**
* Send a DELETE request to the modify endpoint. If the request is successful,
* close the modal and delete the url box from the page. If not, display the
* error message in a notice.
*/
async _confirmHandler() {
let response;
try {
response = await fetch(this._urlRow.dataset.endpoint, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrfToken(),
},
});
} catch (error) {
console.log(error);
return;
}
const json = await response.json();
if (json.error) {
displayNotice(json.error, "is-danger");
} else {
location.reload();
}
this.close();
}
/**
* Delete the url if enter is pressed.
* @param {KeyboardEvent} event - Keydown event.
* @private
*/
_enterHandler(event) {
if (event.key === "Enter" && this.isOpen) {
this._confirmHandler();
}
}
}
|
JavaScript
|
class Camera2D extends Camera{
// The 2D camera has panning instead of changing the camera angle.
// The z coordinate is not important here because it gets defined in the shaders as 0 in any case.
constructor(){
super();
let obj = this;
obj.zoomPointClip = [0,0];
obj.k = 1;
} // constructor
move(x,y, vpp){
// Instead of changing the camera pitch/yaw/roll pan the view.
let obj = this;
vpp = vpp == undefined ? 1 : vpp;
if(obj.mouseDown){
let diffX = (x - obj.mouseStart[0])*vpp;
let diffY = (y - obj.mouseStart[1])*vpp;
// Limit the panning?
obj.x = obj.xStart - diffX;
obj.y = obj.yStart + diffY;
} // if
} // move
incrementZoomValue(d){
this.k += d;
} // incrementZoomValue
} // Camera2D
|
JavaScript
|
class PlayButton{
// The y is given as the centerline about which to position the button. Half above, and half below. The initial y is therefore half the height, and should draw the button completely on hte svg.
y = 20*2*Math.sqrt(3)/3 / 2;
width = 20;
constructor(){
let obj = this;
obj.node = svg2element$2( template$f );
} // constructor
update(playing){
let obj = this;
let d = playing ? pause(obj.width, obj.y) : play(obj.width, obj.y);
obj.node.querySelector("path").setAttribute("d", d);
} // update
} // PlayButton
|
JavaScript
|
class GeneralComment extends Comment{
replies = [];
constructor(config){
super(config);
let obj = this;
// The general comment can have replies associated with it. Handle these here. Furthermore an additional control for expanding, reducing hte comments is required.
obj.replynode = html2element$1(template$9);
obj.node.appendChild( obj.replynode );
// Add the functionality to the caret.
obj.repliesExpanded = false;
obj.replynode.querySelector("div.expand-controls").onclick = function(){
obj.repliesExpanded = !obj.repliesExpanded;
obj.update();
}; // onclick
// Replies on the config need to be initialised. But actually, they should be stored as separate entries for ease of updating...
obj.update();
} // constructor
reply(replyconfig){
// Replies can also need to be updated if the server pushes an updated version. In that case handle the replacement here.
let obj = this;
// Make a comment node, and append it to this comment.
replyconfig.parentid = obj.id;
let r = new ReplyComment(replyconfig);
let existing = findArrayItemById$1(obj.replies, r.id);
if(existing){
obj.replaceReply(existing, r);
} else {
// Add this one at the end.
obj.replynode.querySelector("div.replies").appendChild(r.node);
obj.replies.push(r);
} // if
// Update the view.
obj.update();
} // reply
replaceReply(existing, replacement){
// For simplicity handle the replacing of hte comment here.
let obj = this;
// Update the internal comments store.
obj.replies.splice(obj.replies.indexOf(existing), 1, replacement);
// Update teh DOM.
let container = obj.node.querySelector("div.replies");
container.insertBefore(replacement.node, existing.node);
} // replaceReply
update(){
// Only the time is allowed to be updated (if it will be calculated back), and the up and down votes.
let obj = this;
// From superclass
obj.updateTimestamp();
obj.updateVoteCounter("upvote");
obj.updateVoteCounter("downvote");
// GeneralComment specific.
obj.updateReplies();
} // update
updateReplies(){
let obj = this;
// First update is called when the superclass constructor is called.
if(obj.replies){
let n = obj.replies.length;
obj.replynode.style.display = n > 0 ? "" : "none";
// View replies or hide replies
let s = n == 1 ? "y" : `ies (${n})`;
obj.replynode
.querySelector("div.expand-controls")
.querySelector("i.control-text")
.innerText = obj.repliesExpanded ? `Hide repl${s}` : `View repl${s}`;
obj.replynode
.querySelector("div.expand-controls")
.querySelector("i.fa")
.classList.value = obj.repliesExpanded ? "fa fa-caret-up" : "fa fa-caret-down";
obj.replynode.querySelector("div.replies").style.display = obj.repliesExpanded ? "" : "none";
} // if
} // updateReplies
} // GeneralComment
|
JavaScript
|
class DiscussionSelector{
tags = []
selected = []
constructor(){
let obj = this;
obj.node = html2element$1(template$8);
} // constructor
update(newtags){
let obj = this;
if(newtags){
// Replace the tags if necessary. The same tags should be grouped together, but different authors may have differing views on what constitutes features.
obj.tags = newtags;
obj.selected = obj.selected.filter(d=>newtags.includes(d));
obj.externalAction();
} // if
let buttons = joinDataToElements(obj.tags, obj.node.querySelectorAll("button"), d=>d);
buttons.enter.forEach(d=>{
let el = html2element$1(tagtemplate);
obj.node.appendChild( el );
el.querySelector("i").innerText = d;
el.__data__ = d;
el.onclick = function(){
obj.toggle(el);
}; // onclick
}); // forEach
buttons.exit.forEach(button=>button.remove());
} // update
toggle(el){
let obj = this;
if(obj.selected.includes(el.__data__)){
obj.selected.splice(obj.selected.indexOf(el.__data__),1);
el.style.fontWeight = "";
} else {
obj.selected.push(el.__data__);
el.style.fontWeight = "bold";
} // if
obj.externalAction();
} // toggle
// Placeholder that will allow the actual comments to be hidden. Maybe just name it that?
externalAction(){} // externalAction
} // DiscussionSelector
|
JavaScript
|
class UnsteadyPlayer2D extends ViewFrame2D {
constructor(gl, unsteadyMetadataFilename){
super(gl);
let obj = this;
// Actual geometry to be drawn.
obj.geometry = new Mesh2D(gl, unsteadyMetadataFilename);
// The FPS at which to swap out data.
obj.fps = 24;
obj.dt = 1000 / obj.fps;
obj.timelastdraw = 0;
// Add in precofigured UI. The metadata filename identifies this small multiple.
obj.ui = new interactivePlayerUI(unsteadyMetadataFilename);
obj.node.appendChild( obj.ui.node );
} // constructor
update(now){
let obj = this;
// Compute the view matrices
obj.computeModelMatrix();
obj.computeViewMatrix();
obj.computeOrthographicMatrix();
// Will the rendering loop have to be redone in order to allow promises to be returned to ensure that the player is ready for the next step?
if(now > obj.timelastdraw + obj.dt){
if( obj.ui.playing ){
obj.timelastdraw = now;
obj.incrementTimeStep();
} else if ( obj.ui.skipped ){
obj.timelastdraw = now;
obj.incrementTimeStep(0);
obj.ui.skipped = false;
} // if
} // if
// The time domain can only be known AFTER the metadata is loaded. But, after the timesteps are updated the playcontrols need to be updated too. Specifically, the chapters need to be rebuild because they are independent of the actual annotations. But they currently don't need to be! Yes, they do - e.g. padding etc.
obj.ui.t_domain = obj.geometry.domain.t;
} // update
incrementTimeStep(dt){
/*
The small multiple should be able to play on its own. In that case it should just update the data 24 times per second.
It should of course support playing several small multiples at once. If the 'dt' for all the simulations are the same then playing several at once just requires an input that will toggle several small multiples on at the same time. If the 'dt' are not the same, then it becomes more difficult because the data can't be loaded by incrementing, and instead a desired time must be passed to the player. Furthermore, the player should support several small multiples to be played at once, but starting from different times. In those cases the player must keep track of the time increment total to ensure all small multiples move by the same amount.
For now the playbar can just play forward correctly, and the t_play can be used to keep track of the actual playing time. The dt is just added on to that time them.
*/
let obj = this;
if(dt >= 0){
let t_new = obj.ui.t_play + dt;
obj.geometry.timestepCurrentFrame(t_new);
obj.ui.t_play = t_new;
} else {
obj.geometry.incrementCurrentFrame();
obj.ui.t_play = obj.geometry.currentTime;
} // if
obj.geometry.updateCurrentFrameBuffer();
} // incrementTimeStep
} // UnsteadyPlayer2D
|
JavaScript
|
class DrawLink{
// Indices when exiting parent node, entering child node, and the index of position of the bend.
pi = 0
ci = 0
bendi = 0
// Actual dimensions. The label width is the minimum horizontal line length. Bundle width is the space reserved for the vertical line width. Line width is the actual width of the white outline. The default radius is the basis for the actual bend radii.
node_label_width = 70
bundle_width = 4
line_width = 4
r = 16
constructor(parentnode, childnode, author){
let obj = this;
// So that hte locations can be changed on hte go.
obj.parentnode = parentnode;
obj.childnode = childnode;
obj.author = author;
// Exit radius is determined node level difference.
obj.r1 = (childnode.level - parentnode.level)*obj.r;
obj.r2 = obj.r;
} // constructor
get path(){
// Doesn't take into account the offsets yet!!
// Allow this to return a straight path, or a curved one. The straight path is exclusively for bundles that have only one parent. Furthermore, that one should only be allowed when connecting nodes on the same height. So maybe just base the decision off of that?
// Straight path is just M0 0 L40 0 or so.
let obj = this;
let dyc = obj.ci*obj.line_width + obj.childnode.markerEmptyIn;
let dyp = obj.pi*obj.line_width + obj.parentnode.markerEmptyOut;
// The target x should be > `xHorizontal + r1 + r2'
let xHorizontal = obj.parentnode.x + obj.node_label_width + obj.bendi*obj.bundle_width;
// Origin and target MUST be at least `[node_label_width + 2*r, 2*r]' apart otherwise the graphic logic doesn't follow.
let origin = {
x: obj.parentnode.x,
y: obj.parentnode.yMarkerStart + dyp
};
let target = {
x: obj.childnode.x,
y: obj.childnode.yMarkerStart + dyc
};
let arc1start = {
x: xHorizontal - obj.r1,
y: origin.y
};
let arc1end = {
x: xHorizontal,
y: origin.y + obj.r1
};
let arc2start = {
x: xHorizontal,
y: target.y - obj.r2
};
let arc2end = {
x: xHorizontal + obj.r2,
y: target.y
};
/*
How the path is made up.
start point : M0 0
horizontal line : L40 0
first bend to vertical : A16 16 90 0 1 46 16
vertical line : L46 34
second bend to horizontal : A16 16 90 0 0 62 50
horizontal connection to node : L62 50
*/
let p = `M${ origin.x } ${ origin.y } L${ arc1start.x } ${ arc1start.y } A${ obj.r1 } ${ obj.r1 } 90 0 1 ${ arc1end.x } ${ arc1end.y } L${ arc2start.x } ${ arc2start.y } A${ obj.r2 } ${ obj.r2 } 90 0 0 ${ arc2end.x } ${ arc2end.y } L${ target.x } ${ target.y }`;
return p
} // path
} // DrawLink
|
JavaScript
|
class treebundle{
// Index is the ranked position of this bundle within hte level. It determines the position of hte vertical line segment, and the corner radius.
links = []
_bendi = 0;
constructor(seednode, author){
// A seed node is passed in to define the bundle parents and thus instantiate a bundle. After instantialisation only the children of the bundle can change.
// NOTE: seednode is a `treenode' instance, but parents and children are `taskgroup' instances. The level is only defined for the node because it can change when the user interacts with the tree.
let obj = this;
obj.node = svg2element$1( template$4 );
obj.author = author,
obj.level = seednode.level;
obj.parents = seednode.connections.parents;
obj.children = [seednode.connections.group];
obj.nodeChildren = [seednode];
obj.nodeParents = [];
} // constructor
set bendi(i){
// When a bunldes bend index is set it should propagate it to all the children.
let obj = this;
obj.links.forEach(link=>{
link.bendi = i;
}); // forEach
obj._bendi = i;
} // bendi
get bendi(){return this._bendi} // get bendi
update(color){
let obj = this;
let paths = obj.node.querySelectorAll("path");
for(let i=0; i<paths.length; i++){
paths[i].setAttribute("d", obj.path);
} // for
if(color){
paths[paths.length-1].setAttribute("stroke", color);
} // if
} // update
addparent(node){
// Only nodes can be pushed. And only the ones declared upon initialisation!
let obj = this;
let isNodeAllowed = obj.parents.includes(node.connections.group);
let isNodeUnknown = !obj.nodeParents.includes(node);
if( isNodeAllowed && isNodeUnknown ){
obj.nodeParents.push(node);
obj.updateNodeMinPositions();
} // if
} // addparent
addchild(node){
let obj = this;
if(!obj.children.includes(node.connections.group)){
obj.children.push(node.connections.group);
} // if
if(!obj.nodeChildren.includes(node)){
obj.nodeChildren.push(node);
obj.updateNodeMinPositions();
} // if
} // addchild
makelinks(){
let obj = this;
// Links must be made for every child-parent combination. Strictly speaking at least one link must be made for all the children, and at least one link must connect to every parent.
let links = [];
obj.nodeParents.forEach(p=>{
obj.nodeChildren.forEach(c=>{
links.push( new DrawLink(p,c) );
}); // forEach
}); // forEach
obj.links = links;
} // links
// Make the full path here??
get path(){
let obj = this;
return obj.links.map(link=>link.path).join("")
} // path
get width(){
// The width of the bundle is the fixed horizontal distance plus the number of bundles multiplied by the width reserved for the vertical line segment. The nodes, and therefore the lines are not yet positioned properly, therefore their width cannot be used to calculate the bunlde width. But they can be just summed together though!
// Note that this is the minimum width of spanning one level, and not the entire width of the bundle, which may include lines spanning multiple levels!
return node_label_width$1 + obj.bundles.length*bundle_width$1 + r$1;
} // get width
updateNodeMinPositions(){
// This should just be run whenever teh parents or the children are changed.
// Because the links make two 90 degree turns when connecting the parent to the child the radii of these turns constitute the minimum y offset of this bundle relative to the previous one. Furthermore, this is offset relative to the lowest parent! This is important when positioning the child nodes.
let obj = this;
let y_lowest_parent = obj.nodeParents.reduce((acc, p)=>{
return acc > p.y ? acc : p.y
}, 0);
obj.nodeChildren.forEach(child=>{
child.miny = y_lowest_parent + 2*r$1;
}); // forEach
} // y_min
} // treebundle
|
JavaScript
|
class TreeLevel{
constructor(nodes, bundles, nlevel){
let obj = this;
obj.n = nlevel;
obj.bundles = bundles.filter(b=>b.level==nlevel);
obj.nodes = nodes.filter(n=>n.level==nlevel);
} // constructor
get width(){
// The width of the entire level. It's the width of the label plus the width of all the vertical line segments (including padding), plus the length of the finishing horizontal segment (this is zero for the right-most bundle).
let obj = this;
// The width of the level is determined by the bundles that end in it. If there aren't any bundles, there is no width. Maybe do a reduce and move the width calculation to the bundle? That would eliminate the dimensions here.
if(obj.bundles.length > 0){
return node_label_width + obj.bundles.length*bundle_width + r;
} else {
return 0
} // if
} // width
} // TreeLevel
|
JavaScript
|
class TreeNode{
x = undefined
_y = 0
miny = 0
// Line width is the width of the incoming line. The pitch is the vertical spacing to the next node.
line_width = 4
pitch = 32
nbundlesin = 0
nbundlesout = 0
hidden = false;
constructor(treegroup){
let obj = this;
obj.node = svg2element$1( template$3 );
// The treegroup holds all the connections of a particular group.
obj.connections = treegroup;
let label = obj.node.querySelector("g.label");
label.onmouseenter = function(){ obj.highlighttext(true); };
label.onmouseleave = function(){ obj.highlighttext(false); };
let marker = obj.node.querySelector("g.marker");
marker.onmouseenter = function(){ obj.highlightmarker(true); };
marker.onmouseleave = function(){ obj.highlightmarker(false); };
} // constructor
update(){
let obj = this;
let marker = obj.node.querySelector("g.marker");
let paths = marker.querySelectorAll("path");
let label = obj.node.querySelector("g.label");
let texts = label.querySelectorAll("text");
for(let i=0; i<paths.length; i++){
paths[i].setAttribute("d", `M${ obj.x } ${ obj.yMarkerStart } L${ obj.x } ${ obj.yMarkerStart + obj.markersize }`);
} // for
label.setAttribute("transform", `translate(${obj.labelx}, ${obj.labely})`);
for(let i=0; i<texts.length; i++){
texts[i].innerHTML = obj.label;
} // for
} // update
highlighttext(v){
let obj = this;
let size = v ? "12px" : "10px";
let texts = obj.node.querySelector("g.label").querySelectorAll("text");
for(let i=0; i<texts.length; i++){
texts[i].setAttribute("font-size", size);
} // for
} // highlighttext
highlightmarker(v){
let obj = this;
let size = v ? 10 : 8;
let outline = obj.node.querySelector("g.marker").querySelector("path.outline");
outline.setAttribute("stroke-width", size);
} // highlighttext
clear(){
let obj = this;
obj.x = undefined;
obj._y = 0;
obj.miny = 0;
obj.nbundlesin = 0;
obj.nbundlesout = 0;
} // clear
set y(val){
let obj = this;
obj._y = val;
} // set y
get y(){
let obj = this;
return Math.max(obj._y, obj.miny)
} // get y
get yMarkerStart(){
let obj = this;
let yoffset = obj.markersize > 0 ? obj.line_width/2 : 0;
return obj.y - obj.markersize/2 + yoffset;
} // markery
get markersize(){
return Math.max(this.nbundlesin-1, this.nbundlesout-1, 0)*this.line_width;
} // markersize
get markerEmptyIn(){
// If the marker is larger than the width of the lines coming in, then the lines should be centered in hte middle of the marker. Calculate the empty space from hte marker start to where the lines should begin.
let obj = this;
return (obj.markersize - (obj.nbundlesin-1)*obj.line_width) / 2;
} // markerEmptyIn
get markerEmptyOut(){
let obj = this;
return (obj.markersize - (obj.nbundlesout-1)*obj.line_width) / 2;
} // markerEmptyIn
// Label to be displayed next to it. Shouldn't be larger than the node_label_width.
get label(){
let obj = this;
let name = obj.connections.group.tags.length > 0 ? obj.connections.group.tags[0].label : "Root";
// Temporarily changed to show n tasks for troubleshooting.
// let n = obj.connections.descendants.length;
let n = obj.connections.group.members.length;
return `${name} ${n > 0 ? `(${ n })`: ""}`
} // label
get labelx(){
return this.x + 4;
} // labelx
get labely(){
return this.yMarkerStart - 4;
} // labely
} // TreeNode
|
JavaScript
|
class treegroup{
constructor(taskgroup){
let obj = this;
obj.group = taskgroup;
// Groups CAN have more than 1 parent. While it's true that during a single dive through the tasks each group can only have one parent, it's possible that additional dives (by the same, or other users) will produce the same groups, but tracing different steps. The merging already combines all identical groups, so the merged groups can have multiple parents.
// Select the parents as all those candidate groups that have not been referenced by other candidate groups already.
obj.ancestors = []; // All upstream groups
obj.parents = []; // Only groups directly above this one.
obj.descendants = []; // All downstream groups
obj.children = undefined; // Only groups directly below. Is this needed??
} // constructor
} // treegroup
|
JavaScript
|
class Group{
members = []
constructor(drawingorder, members, tags){
let obj = this;
obj.node = html2element(template$1);
obj.wrappednode = obj.node.querySelector("div.item-proxy");
obj.wrappedview = obj.node.querySelector("div.view-proxy");
obj.bookmarks = obj.node.querySelector("div.bookmarks");
obj.node.querySelector("div.label").innerText = tags[0].label;
obj.tags = tags;
// Drawing order allows the group to changethe order in which the GPU renders the items.
obj.drawingorder = drawingorder;
// Calculate where the node should be added. Store the original positions on the items, as long as they are in the group.
let n = members.length;
let pos = members.reduce((acc, item)=>{
acc[0] += parseInt( item.node.style.left )/n;
acc[1] += parseInt( item.node.style.top )/n;
return acc
}, [0,0]);
obj.node.style.left = pos[0] + "px";
obj.node.style.top = pos[1] + "px";
// All the members should also be moved to this position. Turn off their uis, wih the exception of the playbar. Also remember their relative positions?
members.forEach(item=>{
obj.add(item);
}); // foEach
obj.current = obj.members[0];
// pos needs to be made before calling .add, but .add creates initialposition which is needed for calculating pos.
// Removal of the group.
obj.node.querySelector("button.ungroup").onclick = function(){
obj.remove();
}; // onclick
// Dissolving the annotations.
obj.node.querySelector("button.dissolve").onclick = function(){
obj.dissolve();
}; // onclick
// The view events should be passed down to the current item.
obj.wrappedview.onmousedown = function(e){ obj.current.cameraMoveStart(e); };
obj.wrappedview.onmousemove = function(e){ obj.current.cameraMove(e); };
obj.wrappedview.onmouseup = function(e){ obj.current.cameraMoveEnd(); };
obj.wrappedview.onmouseleave = function(e){ obj.current.cameraMoveEnd(); };
obj.wrappedview.addEventListener("wheel", (e)=>{
e.preventDefault();
obj.current.cameraZoom(e);
}, {passive: false});
// Add ina commenting module. Which id should it use? Maybe the one of the current object?
obj.commenting = new CommentingManager( obj.current.ui.commenting.viewid );
obj.node.querySelector("div.commenting").appendChild( obj.commenting.node );
obj.updateWrapperSize();
obj.update();
// A flag that allows checking whether the group has been edited by the user.
obj.edited = false;
} // constructor
// Setting hte user is important to for interactions with the annotations.
set user(name){
let obj = this;
// The commenting needs to know who is looking at it.
obj.commenting.user = name;
// Store the name
obj._user = name;
// Toggle the dissolve button if the user has any annotations.
let currentUserAnnotations = obj.tags.filter(tag=>tag.author==name);
if(currentUserAnnotations.length > 0){
obj.node.querySelector("button.dissolve").style.display = "";
} // if
} // set user
get user(){
return this._user;
} // get user
// set and get current node ui?? This also ensures that the group div fully covers the actual item, and therefore the group gets dragged as opposed to the individual item.
set current(item){
let obj = this;
// First return the ui controls if needed.
obj.returnUiElements();
// Now append the new current ui controls.
obj.borrowUiElements(item);
// If the commenting has already been established, update the user.
if( obj.commenting ){ obj.commenting.user = item.ui.commenting.user; } // if
if(obj._current){ obj._current.node.style.display = "none"; } // if
item.node.style.display = "inline-block";
obj._current = item;
} // set current
get current(){
return this._current;
} // get current
updateWrapperSize(){
let obj = this;
// Interactions with the commening are not possible if the item is covered by an empty div.
obj.wrappedview.style.width = obj.current.node.querySelector("div.view").style.width;
obj.wrappedview.style.height = obj.current.node.querySelector("div.view").style.height;
} // updateWrapperSize
borrowUiElements(item){
let obj = this;
obj.wrappednode.querySelector("div.playcontrols-proxy").appendChild( item.ui.playcontrols.node );
obj.wrappednode.querySelector("div.chapterform-proxy").appendChild( item.ui.chapterform.node );
} // borrowUiElements
returnUiElements(){
let obj = this;
let pc = obj.wrappednode.querySelector("div.playcontrols-proxy").children[0];
if(pc){ obj.current.ui.playControlsWrapperNode.appendChild( pc ); } // if
let cf = obj.wrappednode.querySelector("div.chapterform-proxy").children[0];
if(pc){ obj.current.ui.chapterFormWrapperNode.appendChild( cf ); } // if
} // returnUiElements
update(){
let obj = this;
// Make a bookmark tab for each of the members. When the tab is moused over, the view should change. First remove allthe bookmarks before updating.
let bookmarksToRemove = obj.bookmarks.querySelectorAll("div.mark");
for(let i=0; i<bookmarksToRemove.length; i++){
bookmarksToRemove[i].remove();
} // for
// Items should also be moved in order to update the view. And they should be triggered to draw.
obj.members.forEach((item, i)=>{
let bookmark = html2element( bookmarktemplate );
obj.bookmarks.appendChild(bookmark);
bookmark.onmouseenter = function(){
obj.highlightBookmark(bookmark);
// Place the item at the end of the draing line.
obj.drawingorder.splice(obj.drawingorder.indexOf(item), 1);
obj.drawingorder.push(item);
obj.current = item;
obj.updateWrapperSize();
}; // onmouseover
var pressTimer;
bookmark.onmouseup = function(){
clearTimeout(pressTimer);
return false;
}; // onmouseup
bookmark.onmousedown = function(){
pressTimer = window.setTimeout(function(){
obj.release(item, obj.getReleaseScales());
obj.members.splice(obj.members.indexOf(item), 1);
obj.current = obj.members[0];
obj.update();
},2000);
return false;
}; // onmousedown
if(obj.current == item){ obj.highlightBookmark(bookmark); } // if
}); // forEach
// Collect all hte member comments, and put them into a combined commenting item.
obj.commenting.clear();
let allComments = obj.members.reduce((acc, member)=>{
return acc.concat(member.ui.commenting.comments);
}, []).map(commentobj=>commentobj.config).sort(function(a,b){
return Date.parse(a.time)-Date.parse(b.time);
}); // reduce().sort()
allComments.forEach(comment=>{
obj.commenting.add(comment);
}); // forEach
} // update
highlightBookmark(b){
let obj = this;
let allBookmarks = obj.bookmarks.querySelectorAll("div.mark");
for(let i=0; i<allBookmarks.length; i++){
allBookmarks[i].style.backgroundColor = b == allBookmarks[i] ? "gray" : "gainsboro";
} // for
} // highlightBookmarks
remove(){
// All the members should be made visible again, and their comment sections should be turned back on, and they should be staggered to their relative psitions.
let obj = this;
// First return the ui elements so that the items are again complete.
obj.returnUiElements();
// When ungrouping the items should be positioned close to where the group used to be (within 1 width of the item). Position the exiting items within 1 width of the top left corner.
// What I really want is to get the maximum relative distances, scale them down, and then calculate where to position hte items.
let scales = obj.getReleaseScales();
// Redistribute the items according to their original positions.`
obj.members.forEach((item, i)=>{
obj.release(item, scales);
}); // forEach
obj.members = [];
// Remove the actual DOM.
obj.node.remove();
} // remove
release(item, scales){
let obj = this;
// Need to calculate the position to release to...
item.node.querySelector("div.label").style.color = "#888";
item.node.style.display = "inline-block";
item.ui.node.style.display = "";
item.node.style.boxShadow = "1px 2px 4px 0px rgba(0,0,0,0.25)";
let x = parseInt(item.node.style.left) + scales.x.dom2range(item.initialposition[0]);
let y = parseInt(item.node.style.top) + scales.y.dom2range(item.initialposition[1]);
item.node.style.left = x + "px";
item.node.style.top = y + "px";
delete item.initialposition;
obj.edited = true;
} // release
add(item){
// Add an item to the group by dragging it over the group.
let obj = this;
obj.members.push(item);
// Make a temporary attribute to store the position at which the noe was collected.
item.initialposition = [parseInt( item.node.style.left ), parseInt( item.node.style.top )];
item.node.style.left = obj.node.style.left;
item.node.style.top = obj.node.style.top;
item.node.querySelector("div.label").style.color = "transparent";
item.node.style.boxShadow = "none";
item.node.style.display = obj.current == item ? "inline-block" : "none";
item.ui.node.style.display = "none";
// A flag highlighting that the group has changed.
obj.edited = true;
} // add
dissolve(){
let obj = this;
// Soo, find all hte annotations that can be dissolved, and then dissolve them. This will require a call to the knowledge manager. How should this be messaged upstream?
let currentUserAnnotations = obj.tags.filter(tag=>tag.author==obj.user);
obj.dissolveexternal( currentUserAnnotations );
obj.remove();
} // dissolve
actualise(){
let obj = this;
// Similarto before, first dissolve all the annotations by this user, and then add new annotations for all members.
let currentUserAnnotations = obj.tags.filter(tag=>tag.author==obj.user);
obj.dissolveexternal( currentUserAnnotations );
let t = Date();
let newAnnotations = obj.members.map((item,i)=>{
return {
id: `${obj.user} ${t} ${i}`,
taskId: item.ui.metadata.taskId,
label: obj.node.querySelector("div.label").innerText,
author: obj.user
}
});
obj.createexternal(newAnnotations);
} // actualise
dissolveexternal(a){
console.log("Remove annotations: ", a);
} // dissolveexternal
createexternal(a){
console.log("Make annotations: ", a);
}
getReleaseScales(){
let obj = this;
let domain = obj.members.reduce((acc,member)=>{
acc.x[0] = acc.x[0] > member.initialposition[0] ? member.initialposition[0] : acc.x[0];
acc.x[1] = acc.x[1] < member.initialposition[0] ? member.initialposition[0] : acc.x[1];
acc.y[0] = acc.y[0] > member.initialposition[0] ? member.initialposition[0] : acc.y[0];
acc.y[1] = acc.y[1] < member.initialposition[0] ? member.initialposition[0] : acc.y[1];
return acc
}, {x: [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY], y: [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]});
let xscale = new scaleLinear();
xscale.domain = domain.x;
xscale.range = [-150, 150];
let yscale = new scaleLinear();
yscale.domain = domain.y;
yscale.range = [-150, 150];
return {x: xscale, y: yscale}
} // releaseScales
} // Group
|
JavaScript
|
class GroupingCoordinator {
constructor(items, container, svg){
// Container is only needed if groups need to be appended.
let obj = this;
obj.container = container;
obj.items = items;
obj.tasks = items.map(item=>item.ui.metadata.taskId);
obj.groups = [];
// First the items need to be draggable to allow for grouping.
obj.addDraggingToSiblingItems(80);
// The hierarchy is essentially a function of the grouping. The navigation tree can therefore be used to create teh grouping interface.
obj.navigation = new TreeRender([]);
// navigationsvg.appendChild(obj.navigation.node)
// obj.navigation.update();
obj.navigation.moveto = function(nodeobj){
// Now remove all existing group items, hide all unnecessary items, calculate the direct descendant groups, and create items for them.
let current = nodeobj.connections.group.members;
obj.clear();
obj.showCurrentTasks( current );
obj.makeDirectDescendantGroups(nodeobj);
}; // moveto
// Add the treenavigation graphic.
svg.querySelector("g.tree")
.appendChild(obj.navigation.node);
obj.navigation.update();
// On lasso mouseup the GroupingCoordinator should create an additional group based on the lasso selection. So maybe this should all be moved into the knowledge manager?
new lasso(svg);
} // constructor
clear(){
let obj = this;
obj.groups.forEach(group=>{
group.remove();
});
obj.groups = [];
} // clear
// When the parent group is specified the items should be adjusted immediately.
showCurrentTasks(tasks){
let obj = this;
// First find if any of the specified tsks are valid.
let validtasks = tasks.filter(task=>obj.tasks.includes(task));
if(validtasks.length > 0){
obj.items.forEach(item=>{
if(validtasks.includes(item.ui.metadata.taskId)){
item.node.style.display = "";
} else {
item.node.style.display = "none";
} // if
}); // forEach
} // if
} // showCurrentTasks
makeDirectDescendantGroups(nodeobj){
let obj = this;
// First remove all existing groups.
obj.groups.forEach(group=>{
group.remove();
}); // forEach
// Find all groups that should appear.
let descendants = nodeobj.connections.descendants;
let directDescendants = descendants.filter(group=>{
return !descendants.some(d=>{
if(d != group){
return arrayIncludesAll(d.members, group.members)
} // if
return false
}) // some
}); // filter
// Make all groups that should appear.
directDescendants.forEach(d=>{
// Pass the actual item objects to the group.
let members = obj.items.filter(item=>{
return d.members.includes(item.ui.metadata.taskId);
}); // filter
// 'obj.items' needs to always be passed in so that when the bookmarks are moused over the drawing order can change. Tags are passed in to allow changes to be made.
let groupitem = new Group(obj.items, members, d.tags);
obj.groups.push( groupitem );
obj.container.appendChild( groupitem.node );
let ondrag = function(){
groupitem.members.forEach(item=>{
item.node.style.left = groupitem.node.style.left;
item.node.style.top = groupitem.node.style.top;
});
};
addDraggingToItem( groupitem, undefined, ondrag );
groupitem.dissolveexternal = function(a){
obj.dissolveexternal(a);
}; // function
groupitem.createexternal = function(a){
obj.createexternal(a);
}; // function
}); // forEach
} // makeDirectDescendantGroups
// Proxies.
dissolveexternal(a){ console.log("Remove annotations", a); } // dissolveexternal
createexternal(a){ console.log("Make annotations", a); } // createexternal
getCurrentPositions(items, variable){
// Current positions are needed for calculating correlations, or for adding additional metadata variables based on the users actions. How should the positions and the metadata be combined actually? Should there be a specific method for it? If a variable is specified, then return it with the positions.
return items.map(item=>{
let pos = [
ParseInt(item.node.style.left),
ParseInt(item.node.style.top)
];
if(variables != undefined){
pos.push(item.metadata[variable]);
} // if
return pos
}) // map
} // getCurrentPositions
addDraggingToSiblingItems(headeroffset){
// To add the dragging an additional "dragging" attribute is introduced to the items. The items are ViewFrame objects that all have their nodes inside the same parent node. The parent node must be the same as the initial positions of the frames are calculated based on their current positions within hte parent div.
let obj = this;
let positions = obj.items.reduce((acc,item)=>{
acc.push([item.node.offsetLeft, item.node.offsetTop + headeroffset]);
return acc
},[]);
obj.items.forEach((item,i)=>{
item.node.style.position = "absolute";
item.node.style.left = positions[i][0] + "px";
item.node.style.top = positions[i][1] + "px";
let onstart = function(){
// Move this item to the end of the drawing queue to ensure it's drawn on top.
obj.items.splice(obj.items.indexOf(item), 1);
obj.items.push(item);
}; // function
let onend = function(){
console.log("Check if item should be added to group");
// It should be either if hte item is fully within hte group, or very close to the top left corner?
obj.groups.every(group=>{
// Item should jut be added to a single group.
let addToThisGroup = sufficientlyOverlaid(item, group);
if( addToThisGroup ){
group.add(item);
group.update();
} // if
return !addToThisGroup
}); // every
};// function
addDraggingToItem(item, onstart, undefined, onend);
}); // forEach
} // addDraggingToSiblingItems
setPositionsByMetadata(items, variable){
// Reposition hte items on screen given their metadata values. Reposition to within the current client viewport, or the whole document? Whole document to spread the small multiples out a bit.
} // setPositionsByMetadata
makeGroupFromArrayOfItems(items){
// Calculate the position of the group and create the html elements required for it. How should the renderer be convinced to draw the appropriate contours? It gets the viewport directly from the ViewFrame, which in this case will be disabled. Allow the group object to pass it's own viewport to the correct item, and use them if the div is set to display none?
} // makeGroupFromArrayOfItems
} // GroupingCoordinator
|
JavaScript
|
class ProxyServerStore{
constructor(filename){
let obj = this;
obj.data = [];
fetch(filename)
.then(response => response.json())
.then(data=>{
obj.data=data;
obj.update();
return data;
});
} // constructor
add(item){
// Check if the item is already present. Replace it, or just update the delta? Bank on the idea that no two queries will be simultaneous?
let obj = this;
let i = obj.data.findIndex(d=>d.id==item.id);
obj.data.splice(i>-1 ? i : 0, i>-1, item);
obj.update();
} // add
remove(item){
let obj = this;
let i = obj.data.findIndex(d=>d.id==item.id);
obj.data.splice(i, i>-1);
obj.update();
} // remove
update(){
// Implement the push of all the comments etc to the actual modules for display.
console.log("server pushes changes");
} // update
// Maybe no query is required anyway? Each project would have its own annotations, which are always loaded anyway? Unless you go into a list of users and remove them?
} // ProxyServerStore
|
JavaScript
|
class Table {
constructor (table) {
this.init(table);
}
init (table) {
this.table = table;
this.tableElem = this.table.querySelector('table');
this.tableContent = this.tableElem.querySelector('tbody');
this.isScrollable = this.tableContent.offsetWidth > this.tableElem.offsetWidth;
this.caption = this.tableElem.querySelector('caption');
this.captionHeight = 0;
this.wrap();
const scrolling = this.change.bind(this);
this.tableElem.addEventListener('scroll', scrolling);
this.change();
}
change () {
const newScroll = this.tableContent.offsetWidth > this.tableElem.offsetWidth;
let firstTimeScrollable = this.tableElem.offsetWidth > this.table.offsetWidth;
if (newScroll || firstTimeScrollable) {
this.scroll();
this.handleCaption();
} else {
if (newScroll !== this.isScrollable) this.delete();
}
this.isScrollable = newScroll;
firstTimeScrollable = false;
}
delete () {
api.core.removeClass(this.table, SHADOW_RIGHT_CLASS);
api.core.removeClass(this.table, SHADOW_LEFT_CLASS);
api.core.removeClass(this.table, SHADOW_CLASS);
if (this.caption) {
this.tableElem.style.marginTop = '';
this.caption.style.top = '';
this.tableElem.style.marginBottom = '';
this.caption.style.bottom = '';
}
}
scroll () {
api.core.addClass(this.table, SHADOW_CLASS);
this.setShadowPosition();
}
/* ajoute un wrapper autour du tableau */
wrap () {
const wrapperHtml = document.createElement('div');
wrapperHtml.className = WRAPPER_CLASS;
this.table.insertBefore(wrapperHtml, this.tableElem);
wrapperHtml.appendChild(this.tableElem);
this.tableInnerWrapper = wrapperHtml;
}
/* affiche les blocs shadow en fonction de la position du scroll, en ajoutant la classe visible */
setShadowPosition () {
const tableScrollLeft = this.getScrollPosition(LEFT);
const tableScrollRight = this.getScrollPosition(RIGHT);
// on inverse en cas de lecture droite - gauche
if (document.documentElement.getAttribute('dir') === 'rtl') {
this.setShadowVisibility(RIGHT, tableScrollLeft);
this.setShadowVisibility(LEFT, tableScrollRight);
} else {
this.setShadowVisibility(LEFT, tableScrollLeft);
this.setShadowVisibility(RIGHT, tableScrollRight);
}
}
/* Donne le nombre de pixels scrollés honrizontalement dans un element scrollable */
getScrollPosition (side) {
let inverter = 1;
// on inverse en cas de lecture droite - gauche pour que la valeur de scroll soit toujours positive
if (document.documentElement.getAttribute('dir') === 'rtl') {
inverter = -1;
}
switch (side) {
case LEFT:
return this.tableElem.scrollLeft * inverter;
case RIGHT:
return this.tableContent.offsetWidth - this.tableElem.offsetWidth - this.tableElem.scrollLeft * inverter;
default:
return false;
}
}
/* positionne la caption en top négatif et ajoute un margin-top au wrapper */
handleCaption () {
if (this.caption) {
const style = getComputedStyle(this.caption);
const newHeight = this.caption.offsetHeight + parseInt(style.marginTop) + parseInt(style.marginBottom);
this.captionHeight = newHeight;
if (this.table.classList.contains(CAPTION_BOTTOM_CLASS)) {
this.tableElem.style.marginBottom = this.captionHeight + 'px';
this.caption.style.bottom = -this.captionHeight + 'px';
} else {
this.tableElem.style.marginTop = this.captionHeight + 'px';
this.caption.style.top = -this.captionHeight + 'px';
}
}
}
/* ajoute la classe fr-table--shadow-right ou fr-table--shadow-right sur fr-table
en fonction d'une valeur de scroll et du sens (right, left) */
setShadowVisibility (side, scrollPosition) {
// si on a pas scroll, ou qu'on scroll jusqu'au bout
if (scrollPosition <= SCROLL_OFFSET) {
if (side === LEFT) api.core.removeClass(this.table, SHADOW_LEFT_CLASS);
else if (side === RIGHT) api.core.removeClass(this.table, SHADOW_RIGHT_CLASS);
} else {
if (side === LEFT) api.core.addClass(this.table, SHADOW_LEFT_CLASS);
else if (side === RIGHT) api.core.addClass(this.table, SHADOW_RIGHT_CLASS);
}
}
}
|
JavaScript
|
class SchemaValidator {
static _assertSchemaDefined(schema) {
if (schema === undefined) {
throw new Error(`Cannot add undefined schema`);
}
}
/**
* Instantiates a SchemaValidator instance
*/
constructor() {
this._validator = new jsonschema_1.Validator();
for (const schema of values(schemas_1.schemas)) {
SchemaValidator._assertSchemaDefined(schema);
this._validator.addSchema(schema, schema.id);
}
}
/**
* Add a schema to the validator. All schemas and sub-schemas must be added to
* the validator before the `validate` and `isValid` methods can be called with
* instances of that schema.
* @param schema The schema to add
*/
addSchema(schema) {
SchemaValidator._assertSchemaDefined(schema);
this._validator.addSchema(schema, schema.id);
}
// In order to validate a complex JS object using jsonschema, we must replace any complex
// sub-types (e.g BigNumber) with a simpler string representation. Since BigNumber and other
// complex types implement the `toString` method, we can stringify the object and
// then parse it. The resultant object can then be checked using jsonschema.
/**
* Validate the JS object conforms to a specific JSON schema
* @param instance JS object in question
* @param schema Schema to check against
* @returns The results of the validation
*/
validate(instance, schema) {
SchemaValidator._assertSchemaDefined(schema);
const jsonSchemaCompatibleObject = JSON.parse(JSON.stringify(instance));
return this._validator.validate(jsonSchemaCompatibleObject, schema);
}
/**
* Check whether an instance properly adheres to a JSON schema
* @param instance JS object in question
* @param schema Schema to check against
* @returns Whether or not the instance adheres to the schema
*/
isValid(instance, schema) {
const isValid = this.validate(instance, schema).errors.length === 0;
return isValid;
}
}
|
JavaScript
|
class ContainerStubIterTest {
prev(n) {
return n - 1;
}
next(n) {
return n + 1;
}
}
|
JavaScript
|
class VirtualMachineConfiguration {
/**
* Create a VirtualMachineConfiguration.
* @member {object} [imageReference] Reference to OS image.
* @member {string} [imageReference.publisher]
* @member {string} [imageReference.offer]
* @member {string} [imageReference.sku]
* @member {string} [imageReference.version]
*/
constructor() {
}
/**
* Defines the metadata of VirtualMachineConfiguration
*
* @returns {object} metadata of VirtualMachineConfiguration
*
*/
mapper() {
return {
required: false,
serializedName: 'VirtualMachineConfiguration',
type: {
name: 'Composite',
className: 'VirtualMachineConfiguration',
modelProperties: {
imageReference: {
required: false,
serializedName: 'imageReference',
type: {
name: 'Composite',
className: 'ImageReference'
}
}
}
}
};
}
}
|
JavaScript
|
class CompilerInterface {
/**
* Compiles the application.
* Returns the path of the module to be required.
*
* @returns {Promise<string>}
*/
compile() { }
/**
* Sets the progress handler.
*
* @param {Function} handler
*/
set progressHandler(handler) { }
}
|
JavaScript
|
class LinkList extends Component {
/** Dispatch redux action to update page status and fetch latest posts */
componentDidMount() {
this.props.updateAdminPage("Links");
this.props.fetchLinks();
}
render() {
let items = [(
<div key="new" className="admin-item">
<Link to={"/admin/links/new"}>
<div className="new-item">
Create New Link
</div>
</Link>
</div>
)]
// If a list of links exists in the redux store, append them to items
if (this.props.links) {
let links = _.map(this.props.links, (value, key) => value)
links = links.map(link => (
<div key={link._id} className="admin-item">
<Link to={`/admin/links/edit/${link._id}`}>
<img src={link.imgSrc} />
<div className="content">
<div className="title">
{link.title}
</div>
</div>
</Link>
</div>
))
items = [...items, ...links]
}
return (
<div className="admin-list">
{items}
</div>
)
}
}
|
JavaScript
|
class CustomAnchor extends HTMLAnchorElement {
constructor() {
super();
this.clicks = 0;
}
connectedCallback() {
this.addEventListener('click', e => {
e.preventDefault();
if (confirm('Are you sure?')) {
window.location.href = e.target.href;
} else {
this.clicks += 1;
if ( this.clicks >= 3) {
this.style.fontSize = '32px';
this.style.color = 'red';
}
}
});
}
}
|
JavaScript
|
class ComputerVisionError {
/**
* Create a ComputerVisionError.
* @member {string} code The error code. Possible values include:
* 'InvalidImageUrl', 'InvalidImageFormat', 'InvalidImageSize',
* 'NotSupportedVisualFeature', 'NotSupportedImage', 'InvalidDetails',
* 'NotSupportedLanguage', 'BadArgument', 'FailedToProcess', 'Timeout',
* 'InternalServerError', 'Unspecified', 'StorageException'
* @member {string} message A message explaining the error reported by the
* service.
* @member {string} [requestId] A unique request identifier.
*/
constructor() {
}
/**
* Defines the metadata of ComputerVisionError
*
* @returns {object} metadata of ComputerVisionError
*
*/
mapper() {
return {
required: false,
serializedName: 'ComputerVisionError',
type: {
name: 'Composite',
className: 'ComputerVisionError',
modelProperties: {
code: {
required: true,
serializedName: 'code',
type: {
name: 'Enum',
allowedValues: [ 'InvalidImageUrl', 'InvalidImageFormat', 'InvalidImageSize', 'NotSupportedVisualFeature', 'NotSupportedImage', 'InvalidDetails', 'NotSupportedLanguage', 'BadArgument', 'FailedToProcess', 'Timeout', 'InternalServerError', 'Unspecified', 'StorageException' ]
}
},
message: {
required: true,
serializedName: 'message',
type: {
name: 'String'
}
},
requestId: {
required: false,
serializedName: 'requestId',
type: {
name: 'String'
}
}
}
}
};
}
}
|
JavaScript
|
class Circle {
constructor(size, color) {
this.radius = size;
this.color = color || {
r: 21,
g: 21,
b: 21,
a: 1,
toColor: function() { return makeColor(this.r, this.g, this.b, this.a); }
};
}
set red(value) {
this.color.r = value || 0;
this.color.r = clamp(this.color.r, 0, 255);
}
set green(value) {
this.color.g = value || 0;
this.color.g = clamp(this.color.g, 0, 255);
}
set blue(value) {
this.color.b = value || 0;
this.color.b = clamp(this.color.b, 0, 255);
}
set opacity(value) {
this.color.a = value || 0;
this.color.a = clamp(this.color.a, 0, 1);
}
getColor() {
if(this.color.toColor != null){
return this.color.toColor();
}
return this.color;
}
setColor(r, g, b, a) {
this.red = r;
this.green = g;
this.blue = b;
this.opacity = a;
}
// draw to the canvas.
draw(context, options){
let o = options || {};
o.x = o.x || 0;
o.y = o.y || 0;
o.modifier = o.modifier || 1;
context.save();
let size = this.radius * o.modifier;
this.opacity = this.color.a;
context.beginPath();
context.globalAlpha = this.color.a;
context.fillStyle = this.getColor();
context.arc(o.x, o.y, clamp(size, o.bounds.min, o.bounds.max), 0, Math.PI * 2, false);
context.fill();
if(options.name) { console.log("Drawing circle: " + options.name); }
context.restore();
}
}
|
JavaScript
|
class FlatLayer {
/**
* Construct a flat layer.
*
* @param activation {ActivationFunction}
* The activation function.
* @param count {Number}
* The neuron count.
* @param biasActivation {Number}
* The bias activation.
* @param dropoutRate {Number}
* The dropout rate for this layer
*/
constructor(activation, count, biasActivation = 0, dropoutRate = 0) {
this.activation = activation;
this.count = count;
this.biasActivation = biasActivation;
this.contextFedBy = null;
this.dropoutRate = dropoutRate;
}
/**
* @return {boolean} the bias
*/
hasBias() {
return Math.abs(this.biasActivation) > PATHS.CONSTANTS.DEFAULT_DOUBLE_EQUAL;
}
/**
* @return {number} the count
*/
getCount() {
return this.count;
}
getNeuronCount() {
return this.getCount();
}
/**
* @return {number} The total number of neurons on this layer, includes context, bias and regular.
*/
getTotalCount() {
if (this.contextFedBy === null) {
return this.getCount() + (this.hasBias() ? 1 : 0);
} else {
return this.getCount() + (this.hasBias() ? 1 : 0) + this.contextFedBy.getCount();
}
}
/**
* @return {number} The number of neurons our context is fed by.
*/
getContextCount() {
if (this.contextFedBy == null) {
return 0;
} else {
return this.contextFedBy.getCount();
}
}
/**
* @return {Number} Get the bias activation.
*/
getBiasActivation() {
if (this.hasBias()) {
return this.biasActivation;
} else {
return 0;
}
}
/**
* @return {String}
*/
// toString() {
// let result = "[";
// result += this.constructor.name;
// result += ": count=" + this.count;
// result += ",bias=";
//
// if (hasBias()) {
// result += this.biasActivation;
// } else {
// result += "false";
// }
// if (this.contextFedBy != null) {
// result += ",contextFed=";
// if (this.contextFedBy == this) {
// result += "itself";
// } else {
// result += this.contextFedBy;
// }
// }
// result += "]";
// return result;
// }
toJSON() {
let jsonObj = {};
Object.keys(this).map((key) => {
jsonObj[key] = this[key];
});
jsonObj.activation = this.activation.name;
return jsonObj;
}
}
|
JavaScript
|
class TimeOfWeek {
/**
* Note `utc_offset` is in minutes and is used to convert UTC time to local
* time. That is, UTC time + utc_offset = local time.
*
* Given local time and utc_offset, UTC time = local time - utc_offset.
*
* From the docs:
* The offset from UTC of the Place’s current timezone, in minutes. For
* example, Sydney, Australia in daylight savings is 11 hours ahead of
* UTC, so the <code>utc_offset</code> will be <code>660</code>. For
* timezones behind UTC, the offset is negative. For example, the </code>
* is <code>-60</code> for Cape Verde.
*
* @param {Object} openingHoursTime Open or close openingHoursTime contains
* day (number) and time (string) properties.
* @param {number} utcOffset
* @return {TimeOfWeek}
*/
static createFromOpeningHoursTime(openingHoursTime, utcOffset) {
/** @type {number} */
const day = openingHoursTime.day;
/** @type {string} */
const timeString = openingHoursTime.time;
const hours = parseInt(timeString.substring(0, 2), 10);
const minutes = parseInt(timeString.substring(2, 4), 10);
let utcTimeInMinutes = (day * 24 * 60) + (hours * 60) + minutes - utcOffset;
if (utcTimeInMinutes < this.getMinTime()) {
utcTimeInMinutes = this.getMaxTime() - Math.abs(utcTimeInMinutes);
} else if (utcTimeInMinutes > this.getMaxTime()) {
utcTimeInMinutes = (utcTimeInMinutes - this.getMaxTime());
}
return new TimeOfWeek(utcTimeInMinutes);
}
/**
* @return {number}
*/
static getMaxTime() {
return 10080;
}
/**
* @return {number}
*/
static getMinTime() {
return 0;
}
/**
* @param {Date} date
* @return {TimeOfWeek}
*/
static createFromRequestedTime(date = new Date()) {
const utcDay = date.getUTCDay();
const utcHours = date.getUTCHours();
const utcMinutes = date.getUTCMinutes();
return new TimeOfWeek((utcDay * 24 * 60) + (utcHours * 60) + utcMinutes);
}
/**
* @param {number} timeInMinutes
*/
constructor(timeInMinutes) {
/**
* @type {number}
*/
this.timeInMinutes = timeInMinutes;
}
/**
* Compares the given time in to the `this.timeInMinutes` and returns:
* 1) 0 if equal,
* 2) -1 if it's less,
* 3) +1 if it's greater.
*
* @param {TimeOfWeek} time
* @return {number}
*/
compare(time) {
const timeInMinutes = time.timeInMinutes;
if (this.timeInMinutes === timeInMinutes) {
return 0;
} else if (this.timeInMinutes < timeInMinutes) {
return -1;
} else {
return +1;
}
}
}
|
JavaScript
|
class RyuutamaItem extends Item {
/**
* Augment the basic Item data model with additional dynamic data.
*/
prepareData() {
super.prepareData();
// Get the Item's data
const itemData = this.data;
const actorData = this.actor ? this.actor.data : {};
this._prepareItemData(itemData, actorData);
}
/**
* Prepare Character type specific data
*/
_prepareItemData(itemData, actorData) {
const data = itemData.data;
if (RYUU.STORAGE.includes(itemData.type)) {
if (actorData._id === undefined) {
data.holding = [];
return;
}
const holding = data.holding;
let holdingAmount = 0;
holding.forEach(item => {
const heldItem = actorData.items.find(i => i._id === item.id);
if (heldItem) {
holdingAmount += Number(heldItem.data.size);
}
});
itemData.data.holdingSize = holdingAmount;
}
}
}
|
JavaScript
|
class Mentors extends Component {
constructor() {
super();
this.state = {
persons: [],
all: [],
search: '',
};
this.updateField = this.updateField.bind(this);
this.searchCard = this.searchCard.bind(this);
}
// get all users' info
componentDidMount() {
axios.get('http://localhost:8000/api/v2/persons')
.then((response) => {
console.log(response);
this.setState({
persons: response.data,
all: response.data,
});
});
}
updateField(e) {
const target = e.target;
const name = target.name;
let value = target.value;
this.setState({
[name]: value
});
this.searchCard();
}
// search user based on keyword
searchCard() {
let keyword = this.state.search.toLowerCase();
let all = this.state.all;
const persons = all.filter(person => {
let result = false;
if (person.name) {
result = result || person.name.toLowerCase().includes(keyword);
}
if (person.location) {
result = result || person.location.toLowerCase().includes(keyword);
}
if (person.desc) {
result = result || person.desc.toLowerCase().includes(keyword);
}
return result;
});
this.setState({
persons: persons
});
}
render() {
return (
<div>
<Typography variant="h4" component="h4">
Find Mentors
</Typography>
<br/>
<Paper component="form" style={{border: '1px', padding: '1px 10px', width: '300px'}}>
<InputBase style={{width: '230px'}}
placeholder="Search mentors"
name="search"
value={this.state.search}
onKeyUp={this.updateField}
onChange={this.updateField}
tabIndex="0"
/>
<IconButton onClick={this.searchCard}>
<SearchIcon/>
</IconButton>
</Paper>
<Grid container spacing={3}>
{this.state.persons.map((person) =>
<Grid item xs={12} sm={6} md={4} lg={3} key={person.id} style={{marginTop: '1rem'}}>
<MentorCard
title={person.name}
description={person.desc}
type={person.type}
location={person.location}
/>
</Grid>
)}
</Grid>
</div>
)
}
}
|
JavaScript
|
class FilterExpression {
field;
value;
operand;
filterExpressionType;
expressions;
options;
static types = {
LOGICAL: 'LOGICAL',
AND: 'AND',
OR: 'OR'
};
constructor (field, value, type, operand, leftExpression, rightExpression, options) {
this.field = field;
this.value = value;
this.filterExpressionType = type;
this.options = options;
this.operand = operand;
if (leftExpression) {
this.expressions = [leftExpression];
if (rightExpression) {
this.expressions.push(rightExpression);
}
}
}
toStringExpression () {
return '';
}
findElementAtPosition (position) {
if (this.expressions) {
for (let i = 0; i < this.expressions.length; i++) {
const result = this.expressions[i].findElementAtPosition(position);
if (result) {
return result;
}
}
}
if (this.options) {
const check = (field, includeLast = false) => {
return this.options[field] && this.options[field].first_column !== undefined &&
this.options[field].last_column !== undefined &&
this.options[field].first_column <= position &&
((this.options[field].last_column > position && !includeLast) ||
(this.options[field].last_column >= position && includeLast));
};
if (check('property')) {
return {
text: this.field,
isProperty: true,
expression: this,
starts: this.options.property.first_column,
ends: this.options.property.last_column
};
} else if (check('operand')) {
return {
text: this.operand,
isOperand: true,
expression: this,
starts: this.options.operand.first_column,
ends: this.options.operand.last_column
};
} else if (check('value')) {
return {
text: this.value,
isValue: true,
expression: this,
starts: this.options.value.first_column,
ends: this.options.value.last_column
};
} else if (check('total', true) && this.options.operand) {
return {
text: this.value || '',
isValue: true,
expression: this,
starts: this.options.operand.last_column + 1,
ends: this.options.total.last_column
};
}
}
return null;
}
}
|
JavaScript
|
class Config {
/*
* constructor(cwd)
* Config class constructor.
*/
constructor() {
// Electron Store
this.store = new Store();
// Class Variables
this.config = {};
this.currentMapping = {};
// Make new config if one doesn't exist.
this.init();
// If config version 0, migrate.
this.migrateConfigZero();
// If config version 1, migrate.
this.migrateConfigOne();
// If config version 2, migrate.
this.migrateConfigTwo();
// If config version 3, migrate.
this.migrateConfigThree();
}
/*
* init()
* @param bool reset - Overloaded method for reseting regardless of current state.
* @return bool
* Makes a new configuration if this is the first time it's being used.
*/
init(reset=false) {
if (typeof this.store.get('config') !== 'undefined') {
if (!reset) {
this.config = this.store.get('config');
return false;
}
}
const config = require(OJD.appendCwdPath('app/js/data/config.json'));
const profile = require(OJD.appendCwdPath('app/js/data/profile.json'));
const mappings = require(OJD.appendCwdPath('app/js/data/mappings.json'));
// Center on Screen
const screenSize = electron.screen.getPrimaryDisplay().size;
config.bounds.x = parseInt((screenSize.width - config.bounds.width)/2, 10);
config.bounds.y = parseInt((screenSize.height - config.bounds.height)/2, 10);
this.store.set('mappings', mappings);
this.store.set('profiles', [profile]);
this.store.set('config', config);
this.config = this.store.get('config');
return true;
}
migrateConfigThree() {
if (this.config.version !== 3) {
return false;
}
const newMappings = require(OJD.appendCwdPath('app/js/data/mappings-v4.json'));
const mappings = this.store.get('mappings');
for (const map of newMappings) {
mappings.push(map);
}
for (const map of mappings) {
map.triggerFixed = [];
}
this.store.set('mappings', mappings);
// Set Config to Version 4
this.config.version = 4;
this.store.set('config', this.config);
// Reload
this.config = this.store.get('config');
}
migrateConfigTwo() {
if (this.config.version !== 2) {
return false;
}
const newMappings = require(OJD.appendCwdPath('app/js/data/mappings-v3.json'));
const mappings = this.store.get('mappings');
for (const map of newMappings) {
mappings.push(map);
}
for (const map of mappings) {
map.triggerFixed = [];
}
this.store.set('mappings', mappings);
// Set Config to Version 2
this.config.version = 3;
this.store.set('config', this.config);
// Reload
this.config = this.store.get('config');
}
/*
* migrateConfigOne()
* @return bool
* Migrates config version 1 to version 2. Adds new default mappings for RetroSpy.
*/
migrateConfigOne() {
if (this.config.version !== 1) {
return false;
}
// Push new mappings for this release.
const newMappings = require(OJD.appendCwdPath('app/js/data/mappings-v2.json'));
const mappings = this.store.get('mappings');
for (const map of newMappings) {
mappings.push(map);
}
this.store.set('mappings', mappings);
// Set Config to Version 2
this.config.version = 2;
this.store.set('config', this.config);
// Reload
this.config = this.store.get('config');
}
/*
* migrateConfigZero()
* @return bool
* Migrates config version 0 to version 1. Separates mappings and profile from core config for easy backups.
*/
migrateConfigZero() {
if (this.config.version !== 0) {
return false;
}
// Migrate to new profile system, will be removed in future releases.
const profile = require(OJD.appendCwdPath('app/js/data/profile.json'));
const mappings = Clone(this.config.mappings);
profile.theme = this.config.theme;
profile.map = this.config.map;
profile.chroma = this.config.chroma;
profile.chromaColor = this.config.chromaColor;
profile.alwaysOnTop = this.config.alwaysOnTop;
profile.zoom = this.config.zoom*100;
// Remove, no longer in config store.
delete this.config.theme;
delete this.config.map;
delete this.config.chroma;
delete this.config.chromaColor;
delete this.config.alwaysOnTop;
delete this.config.zoom;
delete this.config.mappings;
this.config.profile = 0;
this.config.version = 1;
this.store.set('mappings', mappings);
this.store.set('profiles', [profile]);
this.store.set('config', this.config);
// Reload
this.config = this.store.get('config');
return true;
}
/*
* setBounds(bounds)
* @param object bounds
* @return object
* Sets the current bounds of the window in non-broadcast mode. {x:, y:, height:, width:}.
*/
setBounds(bounds) {
this.config.bounds = Clone(bounds);
this.save();
return bounds;
}
/*
* getBounds()
* @return object
* Returns the current bounds of the window when in interface mode. {x:, y:, height:, width:}. Typically used during launch.
*/
getBounds() {
return this.config.bounds;
}
/*
* toggleBroadcast()
* @return bool
* Toggles between interface and broadcast mode.
*/
toggleBroadcast() {
this.config.broadcast = !this.config.broadcast;
this.save();
return this.config.broadcast;
}
/*
* getBroadcast()
* @return bool
* Determines if we're in interface or broadcast mode.
*/
getBroadcast() {
return this.config.broadcast;
}
/*
* toggleInterface()
* @return bool
* Toggles between having dev tools on or off.
*/
toggleDevtools() {
this.config.devTools = !this.config.devTools;
this.save();
return this.config.devTools;
}
/*
* getInterface()
* @return bool
* Determines if dev tools are opened.
*/
getDevTools() {
return this.config.devTools;
}
/*
* setProfile(id)
* @param integer id
* @return integer
* Sets the profile currently being used in OJD
*/
setProfile(id) {
this.config.profile = parseInt(id, 10);
this.save();
return this.config.profile;
}
/*
* getProfile()
* @return integer
* Returns the profile id set.
*/
getProfile() {
return this.config.profile;
}
/*
* setUserThemeDirectory(id)
* @param string directory
* @return string
* Sets the custom theme directory.
*/
setUserThemeDirectory(directory) {
this.config.themeUserDirectory = directory;
this.save();
return this.config.themeUserDirectory;
}
/*
* getUserThemeDirectory()
* @return string
* Returns the current custom theme directory.
*/
getUserThemeDirectory() {
return this.config.themeUserDirectory;
}
/*
* save()
* @return NULL
* Saves config object
*/
save() {
this.store.set('config', this.config);
}
/*
* reset()
* @return bool
* Alias of init.
*/
reset() {
return this.init(true);
}
}
|
JavaScript
|
class Force {
constructor(body, layers) {
/**
* [description]
*
* @name
* @type
* @since 0.1.0
*/
this.body = body;
/**
* [description]
*
* @name
* @type
* @since 0.1.0
*/
this.layers = layers;
}
/**
* [description]
*
* @method
* @since 0.1.0
*/
execute() {
if (this.body.isOnTile) {
const tile = { tx: this.body.tile.x, ty: this.body.tile.y };
let forceX = 0;
let forceY = 0;
this.layers.forEach((layer) => {
const props = layer.propertiesOf(tile.tx, tile.ty);
if (props) {
forceX += (props.forceX) ? props.forceX : 0;
forceY += (props.forceY) ? props.forceY : 0;
}
});
this.body.acceleration.x = forceX;
this.body.acceleration.y = forceY;
}
}
}
|
JavaScript
|
class Listr {
constructor(task, options) {
var _a, _b, _c;
this.task = task;
this.options = options;
this.tasks = [];
this.err = [];
this.renderHook$ = new rxjs_1.Subject();
// assign over default options
this.options = Object.assign({
concurrent: false,
renderer: 'default',
nonTTYRenderer: 'verbose',
exitOnError: true,
registerSignalListeners: true
}, options);
// define parallel options
this.concurrency = 1;
if (this.options.concurrent === true) {
this.concurrency = Infinity;
}
else if (typeof this.options.concurrent === 'number') {
this.concurrency = this.options.concurrent;
}
// get renderer class
const renderer = renderer_1.getRenderer(this.options.renderer, this.options.nonTTYRenderer, (_a = this.options) === null || _a === void 0 ? void 0 : _a.rendererFallback, (_b = this.options) === null || _b === void 0 ? void 0 : _b.rendererSilent);
this.rendererClass = renderer.renderer;
// depending on the result pass the given options in
if (!renderer.nonTTY) {
this.rendererClassOptions = this.options.rendererOptions;
}
else {
this.rendererClassOptions = this.options.nonTTYRendererOptions;
}
// parse and add tasks
/* istanbul ignore next */
this.add(task || []);
// Graceful interrupt for render cleanup
/* istanbul ignore if */
if (this.options.registerSignalListeners) {
process
.once('SIGINT', async () => {
await Promise.all(this.tasks.map(async (task) => {
if (task.isPending()) {
task.state$ = state_constants_1.StateConstants.FAILED;
}
}));
this.renderer.end(new Error('Interrupted.'));
process.exit(127);
})
.setMaxListeners(0);
}
// disable color programatically for CI purposes
/* istanbul ignore if */
if ((_c = this.options) === null || _c === void 0 ? void 0 : _c.disableColor) {
process.env.LISTR_DISABLE_COLOR = '1';
}
}
add(task) {
const tasks = Array.isArray(task) ? task : [task];
tasks.forEach((task) => {
this.tasks.push(new task_1.Task(this, task, this.options, { ...this.rendererClassOptions, ...task.options }));
});
}
async run(context) {
var _a;
// start the renderer
if (!this.renderer) {
this.renderer = new this.rendererClass(this.tasks, this.rendererClassOptions, this.renderHook$);
}
this.renderer.render();
// create a new context
context = context || ((_a = this.options) === null || _a === void 0 ? void 0 : _a.ctx) || Object.create({});
// create new error queue
const errors = [];
// check if the items are enabled
await this.checkAll(context);
// run tasks
try {
await p_map_1.default(this.tasks, async (task) => {
await this.checkAll(context);
return this.runTask(task, context, errors);
}, { concurrency: this.concurrency });
// catch errors do which do not crash through exitOnError: false
if (errors.length > 0) {
this.err.push(new listr_interface_1.ListrError('Task failed without crashing.', errors, context));
}
this.renderer.end();
}
catch (error) {
this.err.push(new listr_interface_1.ListrError(error, [error], context));
if (this.options.exitOnError !== false) {
this.renderer.end(error);
// Do not exit when explicitely set to `false`
throw error;
}
}
return context;
}
checkAll(context) {
return Promise.all(this.tasks.map((task) => {
task.check(context);
}));
}
runTask(task, context, errors) {
if (!task.isEnabled()) {
return Promise.resolve();
}
return new task_wrapper_1.TaskWrapper(task, errors, this.options).run(context);
}
}
|
JavaScript
|
class Base {
/**
* Constructor for setup tasks that are common across origin & aux chains
*
* @param {Object} params
* @param {Number} params.chainId: chain id on which this is to be performed
* @param {String} params.signerAddress: address who signs Tx
* @param {String} params.chainEndpoint: url to connect to chain
* @param {String} params.gasPrice: gas price to use
* @param {Number} params.gas: required gas for tx
*
* @constructor
*/
constructor(params) {
const oThis = this;
oThis.chainId = params['chainId'];
oThis.chainEndpoint = params['chainEndpoint'];
oThis.signerAddress = params['signerAddress'];
oThis.gasPrice = params['gasPrice'];
oThis.gas = params['gas'];
oThis.web3InstanceObj = null;
}
/**
* Performer
*
* @return {Promise<result>}
*/
perform() {
const oThis = this;
return oThis._asyncPerform().catch(function(error) {
if (responseHelper.isCustomResult(error)) {
return error;
} else {
logger.error('tools/chainSetup/mosaicInteracts/Base::perform::catch');
logger.error(error);
return responseHelper.error({
internal_error_identifier: 't_cs_mi_b_1',
api_error_identifier: 'unhandled_catch_response',
debug_options: {}
});
}
});
}
/**
* Get web3instance to interact with chain
*
* @return {Object}
*/
get _web3Instance() {
const oThis = this;
if (oThis.web3InstanceObj) return oThis.web3InstanceObj;
oThis.web3InstanceObj = web3Provider.getInstance(oThis.chainEndpoint).web3WsProvider;
return oThis.web3InstanceObj;
}
/**
* Get private key of signer from cache
*
* @return {String}
*/
async _fetchSignerKey() {
const oThis = this,
addressPrivateKeyCache = new AddressPrivateKeyCache({ address: oThis.signerAddress }),
cacheFetchRsp = await addressPrivateKeyCache.fetchDecryptedData();
return cacheFetchRsp.data['private_key_d'];
}
/**
* Add key to web3 wallet
*
* @param {String} signerKey
*
* @private
*/
// TODO :: clean up using signer web3
_addKeyToWallet(signerKey) {
const oThis = this;
oThis._web3Instance.eth.accounts.wallet.add(signerKey);
}
/**
* Remove key from web3 wallet
*
* @param {String} signerKey
*
* @private
*/
_removeKeyFromWallet(signerKey) {
const oThis = this;
oThis._web3Instance.eth.accounts.wallet.remove(signerKey);
}
/**
* Fetch nonce (calling this method means incrementing nonce in cache, use judiciously)
*
* @ignore
*
* @return {Promise}
*/
async _fetchNonce() {
const oThis = this;
return new NonceGetForTransaction({
address: oThis.signerAddress,
chainId: oThis.chainId
}).getNonce();
}
}
|
JavaScript
|
class PredicitonDistribution extends PolymerElement {
constructor() {
super();
}
static get is() {
return 'tfma-prediction-distribution';
}
/** @return {!HTMLTemplateElement} */
static get template() {
return template;
}
/** @return {!PolymerElementProperties} */
static get properties() {
return {
/** @type {!Array<!Object>} */
data: {type: Array},
/** @type {number} */
numberOfBuckets: {type: Number, value: 16},
/**
* Chart rendering options.
* @type {!Object}
* @private
*/
options_: {
type: Object,
value: {
'hAxis': {'title': 'Prediction'},
'vAxes': {0: {'title': 'Positive'}, 1: {'title': 'Negative'}},
'series': {
0: {'visibleInLegend': false, 'type': 'bars'},
1: {
'visibleInLegend': true,
'targetAxisIndex': 1,
'type': 'scatter'
},
2: {
'visibleInLegend': true,
'targetAxisIndex': 0,
'type': 'scatter',
'pointShape': 'diamond'
},
},
'explorer': {actions: ['dragToZoom', 'rightClickToReset']},
}
},
/**
* The data to be plotted in the line chart.
* @private {!Array<!Array<string|number>>}
*/
plotData_: {
type: Array,
computed: 'computePlotData_(data, numberOfBuckets)',
},
};
}
/**
* @param {!Array<!Object>|undefined} data
* @param {number} numberOfBuckets
* @return {(!Array<!Array<string|number>>|undefined)} A 2d array representing
* the data that will be visualized in the prediciton distribution.
* @private
*/
computePlotData_(data, numberOfBuckets) {
if (!data) {
return undefined;
}
const minValue = data && data[0] && data[0]['upperThresholdExclusive'] || 0;
const maxValue = data && data[data.length - 1] &&
data[data.length - 1]['lowerThresholdInclusive'] ||
0;
const bucketSize = (maxValue - minValue) / numberOfBuckets || 1;
const plotData = [[
'Prediction',
'Count',
{'type': 'string', 'role': 'tooltip'},
'Positive',
{'type': 'string', 'role': 'tooltip'},
'Negative',
{'type': 'string', 'role': 'tooltip'},
]];
let currentBucketCenter = minValue + bucketSize / 2;
do {
// Initialize histogram with center x and zero count.
plotData.push([currentBucketCenter, 0, '', 0, '', 0, '']);
currentBucketCenter += bucketSize;
} while (currentBucketCenter < maxValue);
const maxIndex = plotData.length - 1;
// For each entry, find the corresponding prediction and update weighted
// example count. Note that index is 1-based since the 0-th entry is the
// header.
data.forEach((entry) => {
const weightedExamples = entry['numWeightedExamples'];
if (weightedExamples) {
const totalLabel = entry['totalWeightedLabel'] || 0;
const prediction =
entry['totalWeightedRefinedPrediction'] / weightedExamples;
const bucketIndex = Math.min(
Math.trunc((prediction - minValue) / bucketSize) + 1, maxIndex);
plotData[bucketIndex][1] = plotData[bucketIndex][1] + weightedExamples;
plotData[bucketIndex][3] = plotData[bucketIndex][3] + totalLabel;
plotData[bucketIndex][5] =
plotData[bucketIndex][5] + weightedExamples - totalLabel;
}
});
// Fill tooltip
let lowerBound = minValue;
let upperBound = minValue + bucketSize;
for (let i = 1; i < plotData.length; i++) {
const boundText = ' example(s) between ' + lowerBound.toFixed(4) +
' and ' + upperBound.toFixed(4);
plotData[i][2] = plotData[i][1] + ' weighted' + boundText;
plotData[i][4] = plotData[i][3] + ' positive' + boundText;
plotData[i][6] = plotData[i][5] + ' negative' + boundText;
lowerBound = upperBound;
upperBound += bucketSize;
}
return plotData;
}
}
|
JavaScript
|
class ErrorObject {
constructor(title, message, status) {
this.title = title;
this.message = message;
// Status is optional. If not given assume 400 or 500
if (status != null) {
this.status = status;
} else {
this.status = 400;
}
}
/**
* Distinguish between server errors and invalud requests or file not foound
* errors.
*/
is404() {
return this.status === 404;
}
}
|
JavaScript
|
class QElement {
constructor(element, priority)
{
this.element = element;
this.priority = priority;
}
}
|
JavaScript
|
class UITextNode3DFacade extends Text3DFacade {
constructor (props) {
super(props)
// Override the sync method so we can have control over when it's called
let mesh = this.threeObject
mesh._actuallySync = mesh.sync
mesh.sync = noop
}
afterUpdate() {
// Read computed layout
const {
offsetLeft,
offsetTop,
offsetWidth
} = this
// Update position and size if flex layout has been completed
const hasLayout = offsetWidth !== null
if (hasLayout) {
let parent = this.parentFlexNode
this.x = offsetLeft - parent.scrollLeft
this.y = -(offsetTop - parent.scrollTop)
// Update clip rect based on parent
const clipRect = this.clipRect || (this.clipRect = [0, 0, 0, 0])
clipRect[0] = this.clipLeft
clipRect[1] = -this.clipBottom
clipRect[2] = this.clipRight
clipRect[3] = -this.clipTop
// If fully hidden by parent clipping rect, cull this object out of the scene
this.threeObject.visible = !this.isFullyClipped
}
// Check text props that could affect flex layout
// TODO seems odd that this happens here rather than FlexLayoutNode
const flexStyles = this._flexStyles
for (let i = 0, len = flexLayoutTextProps.length; i < len; i++) {
const prop = flexLayoutTextProps[i]
const val = prop === 'text' ? this.text : getInheritable(this, prop)
if (val !== flexStyles[prop]) {
flexStyles[prop] = this[prop]
this.needsFlexLayout = true
}
}
super.afterUpdate()
}
onAfterFlexLayoutApplied() {
this.threeObject.maxWidth = this.offsetWidth
this.threeObject._actuallySync(this._afterSync)
}
getBoundingSphere() {
return null //parent UIBlock3DFacade will handle bounding sphere and raycasting
}
}
|
JavaScript
|
class ErrorHandler {
/**
* Constructs a new instance, and also creates a logger
* for use by subclasses.
*/
constructor() {
this.logger = new Logger();
}
/**
* Creates the controller, which may be used by subclasses.
*/
async retrieveController() {
this.contr = await Controller.createController();
};
}
|
JavaScript
|
class Command {
constructor(ctx) {
this.commandResolver = ctx.commandResolver;
}
/**
* Executes command and produces one or more events
* @param command - Command object
* @param [transaction] - Optional database transaction
*/
async execute(command, transaction) {
return Command.empty();
}
/**
* Recover system from failure
* @param command
* @param err
*/
async recover(command, err) {
return Command.empty();
}
/**
* Execute strategy when event is too late
* @param command
*/
async expired(command) {
return Command.empty();
}
/**
* Pack data for DB
* @param data
*/
pack(data) {
return data;
}
/**
* Unpack data from DB
* @param data
*/
unpack(data) {
return data;
}
/**
* Makes command from sequence and continues it
* @param data - Command data
* @param [sequence] - Optional command sequence
* @param [opts] - Optional command options
*/
continueSequence(data, sequence, opts) {
if (!sequence || sequence.length === 0) {
return Command.empty();
}
const [name] = sequence;
sequence = sequence.slice(1);
const handler = this.commandResolver.resolve(name);
const command = handler.default();
const commandData = command.data ? command.data : {};
Object.assign(command, {
data: Object.assign(commandData, data),
sequence,
});
if (opts) {
Object.assign(command, opts);
}
return {
commands: [command],
};
}
/**
* Builds command
* @param name - Command name
* @param data - Command data
* @param [sequence] - Optional command sequence
* @param [opts] - Optional command options
* @returns {*}
*/
build(name, data, sequence, opts) {
const command = this.commandResolver.resolve(name).default();
const commandData = command.data ? command.data : {};
Object.assign(command, {
data: Object.assign(commandData, data),
sequence,
});
if (opts) {
Object.assign(command, opts);
}
return command;
}
/**
* Builds default command
* @param map
* @returns {{add, data: *, delay: *, deadline: *}}
*/
default(map) {
return {
};
}
/**
* Halt execution
* @returns {{repeat: boolean, commands: Array}}
*/
static empty() {
return {
commands: [],
};
}
/**
* Returns repeat info
* @returns {{repeat: boolean, commands: Array}}
*/
static repeat() {
return {
repeat: true,
};
}
/**
* Returns retry info
* @returns {{retry: boolean, commands: Array}}
*/
static retry() {
return {
retry: true,
};
}
}
|
JavaScript
|
class GetShareAccountsClientIdProductIdResponse {
/**
* Constructs a new <code>GetShareAccountsClientIdProductIdResponse</code>.
* GetShareAccountsClientIdProductIdResponse
* @alias module:model/GetShareAccountsClientIdProductIdResponse
*/
constructor() {
GetShareAccountsClientIdProductIdResponse.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>GetShareAccountsClientIdProductIdResponse</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetShareAccountsClientIdProductIdResponse} obj Optional instance to populate.
* @return {module:model/GetShareAccountsClientIdProductIdResponse} The populated <code>GetShareAccountsClientIdProductIdResponse</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GetShareAccountsClientIdProductIdResponse();
if (data.hasOwnProperty('productOptions')) {
obj['productOptions'] = ApiClient.convertToType(data['productOptions'], [GetClientIdProductIdProductOptions]);
}
if (data.hasOwnProperty('chargeOptions')) {
obj['chargeOptions'] = ApiClient.convertToType(data['chargeOptions'], [GetClientIdProductIdChargeOptions]);
}
}
return obj;
}
}
|
JavaScript
|
class Intern extends Employee {
constructor(name, id, email, school) {
// used to access and call from the Employee constructor
super(name, id, email);
// gets school name
this.school = school;
}
getSchool() {
return this.school;
}
getRole() {
return 'Intern';
}
}
|
JavaScript
|
class MemoryCardElement extends PolymerElement {
static get is() {
return 'memory-card';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
//========================================================================
// Public properties
//========================================================================
/**
* The Memory displayed by this element.
* @type {!Memory}
*/
memory: Object,
//========================================================================
// Private properties
//========================================================================
/**
* Whether the Memory has related tab groups or bookmarks.
* @private {boolean}
*/
hasRelatedTabGroupsOrBookmarks_: {
type: Boolean,
computed: 'computeHasRelatedTabGroupsOrBookmarks_(memory)'
},
};
}
constructor() {
super();
/** @private {!PageCallbackRouter} */
this.callbackRouter_ = BrowserProxy.getInstance().callbackRouter;
/** @private {?number} */
this.onVisitsRemovedListenerId_ = null;
}
/** @override */
connectedCallback() {
super.connectedCallback();
this.onVisitsRemovedListenerId_ =
this.callbackRouter_.onVisitsRemoved.addListener(
this.onVisitsRemoved_.bind(this));
}
/** @override */
disconnectedCallback() {
super.disconnectedCallback();
this.callbackRouter_.removeListener(
assert(this.onVisitsRemovedListenerId_));
this.onVisitsRemovedListenerId_ = null;
}
//============================================================================
// Helper methods
//============================================================================
/**
* @param {!Array} array
* @param {number} num
* @return {!Array} Shallow copy of the first `num` items of the input array.
* @private
*/
arrayItems_(array, num) {
return array.slice(0, num);
}
/** @private */
computeHasRelatedTabGroupsOrBookmarks_() {
return this.memory.relatedTabGroups.length > 0 ||
this.memory.bookmarks.length > 0;
}
/**
* @param {!Url} url
* @return {string} The domain name of the URL without the leading 'www.'.
* @private
*/
getHostnameFromUrl_(url) {
return getHostnameFromUrl(url);
}
/**
* Called with the original remove params when the last accepted request to
* browser to remove visits succeeds. Since the same visit may appear in
* multiple Memories, all memories receive this callback in order to get a
* chance to remove their matching visits.
* @param {!Array<!Visit>} removedVisits
* @private
*/
onVisitsRemoved_(removedVisits) {
// A matching visit is a visit to the removed visit's URL whose timespan
// falls within that of the removed visit.
const matchingVisit = (visit) => {
return removedVisits.findIndex((removedVisit) => {
return visit.url.url === removedVisit.url.url &&
visit.time.internalValue <= removedVisit.time.internalValue &&
visit.firstVisitTime.internalValue >=
removedVisit.firstVisitTime.internalValue;
}) !== -1;
};
this.memory.topVisits.forEach((topVisit, topVisitIndex) => {
if (matchingVisit(topVisit)) {
this.splice('memory.topVisits', topVisitIndex, 1);
return;
}
topVisit.relatedVisits.forEach((relatedVisit, relatedVisitIndex) => {
if (matchingVisit(relatedVisit)) {
this.splice(
`memory.topVisits.${topVisitIndex}.relatedVisits`,
relatedVisitIndex, 1);
return;
}
});
});
// If no more visits are left in the Memory, notify the enclosing
// <memories-app> to remove this Memory element from the page.
if (this.memory.topVisits.length === 0) {
this.dispatchEvent(new CustomEvent('remove-empty-memory-element', {
bubbles: true,
composed: true,
detail: this.memory.id,
}));
}
}
}
|
JavaScript
|
class AstEnumValue extends AstItem_1.default {
constructor(options) {
super(options);
this.kind = AstItem_1.AstItemKind.EnumValue;
}
/**
* Returns a text string such as "MyValue = 123,"
*/
getDeclarationLine() {
return PrettyPrinter_1.default.getDeclarationSummary(this.declaration);
}
}
|
JavaScript
|
class Pool {
/**
* Object pool constructor
* @param {Function} allocator returns new empty elements
* @param {Function} resetor resetor(obj) is called on all new elements when they are (re)allocated from pool.
*/
constructor(allocator, resetor) {
if (typeof allocator !== 'function') {
throw new PoolError('allocator is not a function')
}
if (typeof resetor !== 'function') {
throw new PoolError('resetor is not a function')
}
let self = internal(this)
self.allocator = allocator
self.resetor = resetor
self.items = new Map()
return this
}
allocate() {
let
self = internal(this),
items = self.items,
item = getFreeItem(items),
args = Array.prototype.slice.call(arguments)
if (item === false) {
item = self.allocator.apply(null, args)
let isBusy = true
items.set(item, isBusy)
} else {
item = self.resetor(item)
}
return item
}
reset(item) {
let self = internal(this), items = self.items
if (!items.has(item)) {
throw new PoolError('No such item in the pool! Item was not created by the pool')
}
item = self.resetor(item)
items.set(item, false)
return this
}
destroy() {
let self = internal(this)
self.allocator = null
self.resetor = null
self.items.clear()
self.items = null
}
get count() {
return internal(this).items.size
}
}
|
JavaScript
|
class Drag extends State {
/**
* @inheritDoc
*/
constructor(config) {
super(config);
/**
* The drag placeholder that is active at the moment.
* @type {Element}
* @protected
*/
this.activeDragPlaceholder_ = null;
/**
* The drag source that is active at the moment.
* @type {Element}
* @protected
*/
this.activeDragSource_ = null;
/**
* The distance that has been dragged.
* @type {number}
* @protected
*/
this.distanceDragged_ = 0;
/**
* Flag indicating if one of the sources are being dragged.
* @type {boolean}
* @protected
*/
this.dragging_ = false;
/**
* The `EventHandler` instance that holds events that keep track of the drag action.
* @type {!EventHandler}
* @protected
*/
this.dragHandler_ = new EventHandler();
/**
* `DragScrollDelta` instance.
* @type {!DragScrollDelta}
* @protected
*/
this.dragScrollDelta_ = new DragScrollDelta();
/**
* The current x and y positions of the mouse (or null if not dragging).
* @type {{x: number, y: number}}
* @protected
*/
this.mousePos_ = null;
/**
* The distance between the mouse position and the dragged source position
* (or null if not dragging).
* @type {{x: number, y: number}}
* @protected
*/
this.mouseSourceDelta_ = null;
/**
* The `EventHandler` instance that holds events for the source (or sources).
* @type {!EventHandler}
* @protected
*/
this.sourceHandler_ = new EventHandler();
/**
* The current region values of the element being dragged, relative to
* the document (or null if not dragging).
* @type {Object}
* @protected
*/
this.sourceRegion_ = null;
/**
* The current x and y positions of the element being dragged relative to its
* `offsetParent`, or to the viewport if there's no `offsetParent`
* (or null if not dragging).
* @type {{x: number, y: number}}
* @protected
*/
this.sourceRelativePos_ = null;
this.attachSourceEvents_();
this.on(Drag.Events.DRAG, this.defaultDragFn_, true);
this.on(Drag.Events.END, this.defaultEndFn_, true);
this.on('sourcesChanged', this.handleSourcesChanged_.bind(this));
this.on('containerChanged', this.handleContainerChanged_.bind(this));
this.dragScrollDelta_.on(
'scrollDelta',
this.handleScrollDelta_.bind(this)
);
dom.on(document, 'keydown', this.handleKeyDown_.bind(this));
}
/**
* Attaches the necessary events to the source (or sources).
* @protected
*/
attachSourceEvents_() {
let toAttach = {
keydown: this.handleSourceKeyDown_.bind(this),
mousedown: this.handleDragStartEvent_.bind(this),
touchstart: this.handleDragStartEvent_.bind(this),
};
let eventTypes = Object.keys(toAttach);
for (let i = 0; i < eventTypes.length; i++) {
let listenerFn = toAttach[eventTypes[i]];
if (core.isString(this.sources)) {
this.sourceHandler_.add(
// eslint-disable-next-line
dom.delegate(
this.container,
eventTypes[i],
this.sources,
listenerFn
)
);
} else {
this.sourceHandler_.add(
dom.on(this.sources, eventTypes[i], listenerFn)
);
}
}
}
/**
* Builds the object with data to be passed to a drag event.
* @return {!Object}
* @protected
*/
buildEventObject_() {
return {
placeholder: this.activeDragPlaceholder_,
source: this.activeDragSource_,
relativeX: this.sourceRelativePos_.x,
relativeY: this.sourceRelativePos_.y,
x: this.sourceRegion_.left,
y: this.sourceRegion_.top,
};
}
/**
* Calculates the end positions for the drag action when
* `cloneContainer` is set.
* @return {!Object}
* @protected
*/
calculateEndPosition_() {
let endPos = this.sourceRelativePos_;
const {parentNode} = this.activeDragSource_;
if (parentNode !== this.cloneContainer) {
endPos.x = endPos.x - parentNode.offsetLeft;
endPos.y = endPos.y - parentNode.offsetTop;
}
return endPos;
}
/**
* Calculates the initial positions for the drag action.
* @param {!Event} event
* @protected
*/
calculateInitialPosition_(event) {
this.sourceRegion_ = object.mixin(
{},
Position.getRegion(this.activeDragSource_, true)
);
this.sourceRelativePos_ = this.calculateRelativePosition_();
if (core.isDef(event.clientX)) {
this.mousePos_ = {
x: event.clientX,
y: event.clientY,
};
this.mouseSourceDelta_ = {
x: this.sourceRegion_.left - this.mousePos_.x,
y: this.sourceRegion_.top - this.mousePos_.y,
};
}
}
/**
* Calculates the relative position of the active drag
* source.
* @return {!Object}
* @protected
*/
calculateRelativePosition_() {
let relativePos = {
x: this.activeDragSource_.offsetLeft,
y: this.activeDragSource_.offsetTop,
};
if (this.isPlaceholderClone_() && this.cloneContainer) {
relativePos = {
x: this.sourceRegion_.left,
y: this.sourceRegion_.top,
};
}
return relativePos;
}
/**
* Checks if the given event can start a drag operation.
* @param {!Event} event
* @return {boolean}
* @protected
*/
canStartDrag_(event) {
return (
!this.disabled &&
(!core.isDef(event.button) || event.button === 0) &&
!this.isDragging() &&
this.isWithinHandle_(event.target)
);
}
/**
* Resets all variables to their initial values and detaches drag listeners.
* @protected
*/
cleanUpAfterDragging_() {
if (this.activeDragPlaceholder_) {
this.activeDragPlaceholder_.setAttribute('aria-grabbed', 'false');
dom.removeClasses(this.activeDragPlaceholder_, this.draggingClass);
if (this.isPlaceholderClone_()) {
dom.exitDocument(this.activeDragPlaceholder_);
}
}
this.activeDragPlaceholder_ = null;
this.activeDragSource_ = null;
this.sourceRegion_ = null;
this.sourceRelativePos_ = null;
this.mousePos_ = null;
this.mouseSourceDelta_ = null;
this.dragging_ = false;
this.dragHandler_.removeAllListeners();
}
/**
* Clones the active drag source and adds the clone to the document.
* @return {!Element}
* @protected
*/
cloneActiveDrag_() {
let placeholder = this.activeDragSource_.cloneNode(true);
placeholder.style.position = 'absolute';
placeholder.style.left = this.sourceRelativePos_.x + 'px';
placeholder.style.top = this.sourceRelativePos_.y + 'px';
dom.append(
this.cloneContainer || this.activeDragSource_.parentNode,
placeholder
);
return placeholder;
}
/**
* Constrains the given region according to the current state configuration.
* @param {!Object} region
* @protected
*/
constrain_(region) {
this.constrainToSteps_(region);
this.constrainToRegion_(region);
this.constrainToAxis_(region);
}
/**
* Constrains the given region according to the chosen drag axis, if any.
* @param {!Object} region
* @protected
*/
constrainToAxis_(region) {
if (this.axis === 'x') {
region.top = this.sourceRegion_.top;
region.bottom = this.sourceRegion_.bottom;
} else if (this.axis === 'y') {
region.left = this.sourceRegion_.left;
region.right = this.sourceRegion_.right;
}
}
/**
* Constrains the given region within the region defined by the `constrain` state.
* @param {!Object} region
* @protected
*/
constrainToRegion_(region) {
let constrain = this.constrain;
if (!constrain) {
return;
}
if (core.isFunction(constrain)) {
object.mixin(region, constrain(region));
} else {
if (core.isElement(constrain)) {
constrain = Position.getRegion(constrain, true);
}
if (region.left < constrain.left) {
region.left = constrain.left;
} else if (region.right > constrain.right) {
region.left -= region.right - constrain.right;
}
if (region.top < constrain.top) {
region.top = constrain.top;
} else if (region.bottom > constrain.bottom) {
region.top -= region.bottom - constrain.bottom;
}
region.right = region.left + region.width;
region.bottom = region.top + region.height;
}
}
/**
* Constrains the given region to change according to the `steps` state.
* @param {!Object} region
* @protected
*/
constrainToSteps_(region) {
let deltaX = region.left - this.sourceRegion_.left;
let deltaY = region.top - this.sourceRegion_.top;
region.left -= deltaX % this.steps.x;
region.right = region.left + region.width;
region.top -= deltaY % this.steps.y;
region.bottom = region.top + region.height;
}
/**
* Creates the active drag placeholder, unless it already exists.
* @protected
*/
createActiveDragPlaceholder_() {
let dragPlaceholder = this.dragPlaceholder;
if (this.isPlaceholderClone_()) {
this.activeDragPlaceholder_ = this.cloneActiveDrag_();
} else if (core.isElement(dragPlaceholder)) {
this.activeDragPlaceholder_ = dragPlaceholder;
} else {
this.activeDragPlaceholder_ = this.activeDragSource_;
}
}
/**
* The default behavior for the `Drag.Events.DRAG` event. Can be prevented
* by calling the `preventDefault` function on the event's facade. Moves
* the placeholder to the new calculated source position.
* @protected
*/
defaultDragFn_() {
this.moveToPosition_(this.activeDragPlaceholder_);
}
/**
* The default behavior for the `Drag.Events.END` event. Can be prevented
* by calling the `preventDefault` function on the event's facade. Moves
* the source element to the final calculated position.
* @protected
*/
defaultEndFn_() {
if (this.isPlaceholderClone_() && this.cloneContainer) {
this.sourceRelativePos_ = this.calculateEndPosition_();
}
this.moveToPosition_(this.activeDragSource_);
}
/**
* @inheritDoc
*/
disposeInternal() {
this.cleanUpAfterDragging_();
this.dragHandler_ = null;
this.dragScrollDelta_.dispose();
this.dragScrollDelta_ = null;
this.sourceHandler_.removeAllListeners();
this.sourceHandler_ = null;
super.disposeInternal();
}
/**
* Gets the active drag source.
* @return {Element}
*/
getActiveDrag() {
return this.activeDragSource_;
}
/**
* Handles events that can end a drag action, like "mouseup" and "touchend".
* Triggered when the mouse drag action ends.
* @protected
*/
handleDragEndEvent_() {
if (this.autoScroll) {
this.autoScroll.stop();
}
this.dragScrollDelta_.stop();
DragShim.hideDocShim();
this.emit(Drag.Events.END, this.buildEventObject_());
this.cleanUpAfterDragging_();
}
/**
* Handles events that can move a draggable element, like "mousemove" and "touchmove".
* Tracks the movement on the screen to update the drag action.
* @param {!Event} event
* @protected
*/
handleDragMoveEvent_(event) {
let position = event.targetTouches ? event.targetTouches[0] : event;
let distanceX = position.clientX - this.mousePos_.x;
let distanceY = position.clientY - this.mousePos_.y;
this.mousePos_.x = position.clientX;
this.mousePos_.y = position.clientY;
if (
!this.isDragging() &&
!this.hasReachedMinimumDistance_(distanceX, distanceY)
) {
return;
}
if (!this.isDragging()) {
this.startDragging_(event);
this.dragScrollDelta_.start(
this.activeDragPlaceholder_,
this.scrollContainers
);
}
if (this.autoScroll) {
this.autoScroll.scroll(
this.scrollContainers,
this.mousePos_.x,
this.mousePos_.y
);
}
this.updatePositionFromMouse();
}
/**
* Handles events that can start a drag action, like "mousedown" and "touchstart".
* When this is triggered and the sources were not already being dragged, more
* listeners will be attached to keep track of the drag action.
* @param {!Event} event
* @protected
*/
handleDragStartEvent_(event) {
if (this.canStartDrag_(event)) {
event.preventDefault();
event.stopPropagation();
this.activeDragSource_ =
event.delegateTarget || event.currentTarget;
this.calculateInitialPosition_(
event.targetTouches ? event.targetTouches[0] : event
);
if (event.type === 'keydown') {
this.startDragging_(event);
} else {
// eslint-disable-next-line
this.dragHandler_.add.apply(
this.dragHandler_,
DragShim.attachDocListeners(this.useShim, {
mousemove: this.handleDragMoveEvent_.bind(this),
touchmove: this.handleDragMoveEvent_.bind(this),
mouseup: this.handleDragEndEvent_.bind(this),
touchend: this.handleDragEndEvent_.bind(this),
})
);
this.distanceDragged_ = 0;
}
}
}
/**
* Handles a `keydown` event on the document. Ends the drag if ESC was the pressed key.
* @param {!Event} event
* @protected
*/
handleKeyDown_(event) {
if (event.keyCode === 27 && this.isDragging()) {
this.handleDragEndEvent_();
}
}
/**
* Handles a "scrollDelta" event. Updates the position data for the source,
* as well as the placeholder's position on the screen when "move" is set to true.
* @param {!Object} event
* @protected
*/
handleScrollDelta_(event) {
this.mouseSourceDelta_.x += event.deltaX;
this.mouseSourceDelta_.y += event.deltaY;
this.updatePositionFromMouse();
}
/**
* Handles a `keydown` event from `KeyboardDrag`. Does the appropriate drag action
* for the pressed key.
* @param {!Object} event
* @protected
*/
handleSourceKeyDown_(event) {
if (this.isDragging()) {
let currentTarget = event.delegateTarget || event.currentTarget;
if (currentTarget !== this.activeDragSource_) {
return;
}
if (event.keyCode >= 37 && event.keyCode <= 40) {
// Arrow keys during drag move the source.
let deltaX = 0;
let deltaY = 0;
let speedX =
this.keyboardSpeed >= this.steps.x
? this.keyboardSpeed
: this.steps.x;
let speedY =
this.keyboardSpeed >= this.steps.y
? this.keyboardSpeed
: this.steps.y;
if (event.keyCode === 37) {
deltaX -= speedX;
} else if (event.keyCode === 38) {
deltaY -= speedY;
} else if (event.keyCode === 39) {
deltaX += speedX;
} else {
deltaY += speedY;
}
this.updatePositionFromDelta(deltaX, deltaY);
event.preventDefault();
} else if (
event.keyCode === 13 ||
event.keyCode === 32 ||
event.keyCode === 27
) {
// Enter, space or esc during drag will end it.
this.handleDragEndEvent_();
}
} else if (event.keyCode === 13 || event.keyCode === 32) {
// Enter or space will start the drag action.
this.handleDragStartEvent_(event);
}
}
/**
* Triggers when the `container` state changes. Detaches events attached to the
* previous container and attaches them to the new value instead.
* @protected
*/
handleContainerChanged_() {
if (core.isString(this.sources)) {
this.sourceHandler_.removeAllListeners();
this.attachSourceEvents_();
}
if (this.prevScrollContainersSelector_) {
this.scrollContainers = this.prevScrollContainersSelector_;
}
}
/**
* Triggers when the `sources` state changes. Detaches events attached to the
* previous sources and attaches them to the new value instead.
* @protected
*/
handleSourcesChanged_() {
this.sourceHandler_.removeAllListeners();
this.attachSourceEvents_();
}
/**
* Checks if the minimum distance for dragging has been reached after
* adding the given values.
* @param {number} distanceX
* @param {number} distanceY
* @return {boolean}
* @protected
*/
hasReachedMinimumDistance_(distanceX, distanceY) {
this.distanceDragged_ += Math.abs(distanceX) + Math.abs(distanceY);
return this.distanceDragged_ >= this.minimumDragDistance;
}
/**
* Checks if one of the sources are being dragged.
* @return {boolean}
*/
isDragging() {
return this.dragging_;
}
/**
* Returns true if current drag placeholder is a clone of the original drag
* source.
* @return {boolean}
* @protected
*/
isPlaceholderClone_() {
return (
// eslint-disable-next-line
this.dragPlaceholder &&
this.dragPlaceholder === Drag.Placeholder.CLONE
);
}
/**
* Checks if the given element is within a valid handle.
* @param {!Element} element
* @protected
* @return {boolean}
*/
isWithinHandle_(element) {
let handles = this.handles;
if (!handles) {
return true;
} else if (core.isString(handles)) {
return dom.match(element, handles + ', ' + handles + ' *');
} else {
return dom.contains(handles, element);
}
}
/**
* Moves the given element to the current source coordinates.
* @param {!Element} element
* @protected
*/
moveToPosition_(element) {
element.style.left = this.sourceRelativePos_.x + 'px';
element.style.top = this.sourceRelativePos_.y + 'px';
}
/**
* Setter for the `autoScroll` state key.
* @param {*} val
* @return {!DragAutoScroll}
*/
setterAutoScrollFn_(val) {
if (val !== false) {
return new DragAutoScroll(val);
}
}
/**
* Setter for the `constrain` state key.
* @param {!Element|Object|string} val
* @return {!Element|Object}
* @protected
*/
setterConstrainFn(val) {
if (core.isString(val)) {
val = dom.toElement(val);
}
return val;
}
/**
* Sets the `scrollContainers` state key.
* @param {Element|string} val
* @return {!Array<!Element>}
* @protected
*/
setterScrollContainersFn_(val) {
this.prevScrollContainersSelector_ = core.isString(val) ? val : null;
let elements = this.toElements_(val);
elements.push(document);
return elements;
}
/**
* Starts dragging the selected source.
* @param {!Event} event
* @protected
*/
startDragging_(event) {
this.dragging_ = true;
this.createActiveDragPlaceholder_();
dom.addClasses(this.activeDragPlaceholder_, this.draggingClass);
this.activeDragPlaceholder_.setAttribute('aria-grabbed', 'true');
this.emit(Drag.Events.START, {
originalEvent: event,
});
}
/**
* Converts the given element or selector into an array of elements.
* @param {Element|string} elementOrSelector
* @return {!Array<!Element>}
* @protected
*/
toElements_(elementOrSelector) {
if (core.isString(elementOrSelector)) {
let matched = this.container.querySelectorAll(elementOrSelector);
return Array.prototype.slice.call(matched, 0);
} else if (elementOrSelector) {
return [elementOrSelector];
} else {
return [];
}
}
/**
* Updates the dragged element's position using the given calculated region.
* @param {!Object} newRegion
*/
updatePosition(newRegion) {
this.constrain_(newRegion);
let deltaX = newRegion.left - this.sourceRegion_.left;
let deltaY = newRegion.top - this.sourceRegion_.top;
if (deltaX !== 0 || deltaY !== 0) {
this.sourceRegion_ = newRegion;
this.sourceRelativePos_.x += deltaX;
this.sourceRelativePos_.y += deltaY;
this.emit(Drag.Events.DRAG, this.buildEventObject_());
}
}
/**
* Updates the dragged element's position, moving its placeholder if `move`
* is set to true.
* @param {number} deltaX
* @param {number} deltaY
*/
updatePositionFromDelta(deltaX, deltaY) {
let newRegion = object.mixin({}, this.sourceRegion_);
newRegion.left += deltaX;
newRegion.right += deltaX;
newRegion.top += deltaY;
newRegion.bottom += deltaY;
this.updatePosition(newRegion);
}
/**
* Updates the dragged element's position, according to the current mouse position.
*/
updatePositionFromMouse() {
let newRegion = {
height: this.sourceRegion_.height,
left: this.mousePos_.x + this.mouseSourceDelta_.x,
top: this.mousePos_.y + this.mouseSourceDelta_.y,
width: this.sourceRegion_.width,
};
newRegion.right = newRegion.left + newRegion.width;
newRegion.bottom = newRegion.top + newRegion.height;
this.updatePosition(newRegion);
}
/**
* Validates the given value, making sure that it's either an element or a string.
* @param {*} val
* @return {boolean}
* @protected
*/
validateElementOrString_(val) {
return core.isString(val) || core.isElement(val);
}
/**
* Validates the given value, making sure that it's either an element,
* string, or null.
* @param {*} val
* @return {boolean}
* @protected
*/
validateCloneContainer_(val) {
return val === null || this.validateElementOrString_(val);
}
/**
* Validates the value of the `constrain` state.
* @param {*} val
* @return {boolean}
* @protected
*/
validatorConstrainFn(val) {
return core.isString(val) || core.isObject(val);
}
}
|
JavaScript
|
class VideoLayer extends models['Layer'] {
/**
* Create a VideoLayer.
* @member {number} [bitrate] Describes the average bitrate (in bits per
* second) at which to encode the input video when generating this layer.
* This is a required field.
* @member {number} [maxBitrate] Describes the maximum bitrate (in bits per
* second), at which the VBV buffer should be assumed to refill. If not
* specified, defaults to the same value as bitrate.
* @member {number} [bFrames] Describes the number of B-frames to be used
* when encoding this layer. If not specified, the encoder chooses an
* appropriate number based on the video Profile and Level.
* @member {string} [frameRate] Describes the frame rate (in frames per
* second) at which to encode this layer. The value can be in the form of M/N
* where M and N are integers (e.g. 30000/1001), or in the form of a number
* (e.g. 30, or 29.97). The encoder enforces constraints on allowed frame
* rates based on the Profile and Level. If it is not specified, the encoder
* will use the same frame rate as the input video.
* @member {number} [slices] Describes the number of slices to be used when
* encoding this layer. If not specified, default is zero, which means that
* encoder will use a single slice for each frame.
* @member {boolean} [adaptiveBFrame] Determines whether or not adaptive
* B-frames are to be used when encoding this layer. If not specified, the
* encoder will turn it on whenever the video Profile permits its use.
*/
constructor() {
super();
}
/**
* Defines the metadata of VideoLayer
*
* @returns {object} metadata of VideoLayer
*
*/
mapper() {
return {
required: false,
serializedName: '#Microsoft.Media.VideoLayer',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '@odata.type',
clientName: 'odatatype'
},
uberParent: 'Layer',
className: 'VideoLayer',
modelProperties: {
width: {
required: false,
serializedName: 'width',
type: {
name: 'String'
}
},
height: {
required: false,
serializedName: 'height',
type: {
name: 'String'
}
},
label: {
required: false,
serializedName: 'label',
type: {
name: 'String'
}
},
odatatype: {
required: true,
serializedName: '@odata\\.type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
bitrate: {
required: false,
serializedName: 'bitrate',
type: {
name: 'Number'
}
},
maxBitrate: {
required: false,
serializedName: 'maxBitrate',
type: {
name: 'Number'
}
},
bFrames: {
required: false,
serializedName: 'bFrames',
type: {
name: 'Number'
}
},
frameRate: {
required: false,
serializedName: 'frameRate',
type: {
name: 'String'
}
},
slices: {
required: false,
serializedName: 'slices',
type: {
name: 'Number'
}
},
adaptiveBFrame: {
required: false,
serializedName: 'adaptiveBFrame',
type: {
name: 'Boolean'
}
}
}
}
};
}
}
|
JavaScript
|
class ReferenceData {
constructor(client) {
this.client = client;
this.urls = new Urls(client);
this.locations = new Locations(client);
this.airlines = new Airlines(client);
}
/**
* The namespace for the Location APIs - accessing a specific location
*
* @param {string} [locationId] The ID of the location to search for
* @return {Location}
**/
location(locationId) {
return new Location(this.client, locationId);
}
}
|
JavaScript
|
class Server {
// initialize Routes and Server
constructor(options) {
var _this = this;
// setup server
const server = new __WEBPACK_IMPORTED_MODULE_0_koa___default.a();
this.server = server;
// passed in -- option from config.js
this.port = options.port;
// keep track of active requests
this.activeRequests = 0;
// log requests & track active -- middleware
server.use((() => {
var _ref = _asyncToGenerator(function* (ctx, next) {
const start = new Date();
_this.activeRequests++;
yield next();
const ms = new Date() - start;
_this.activeRequests--;
console.log(`${ctx.method} '${ctx.url}' -- ${ms} ms`);
if (!options.test) {
process.send({ 'cmd': 'notifyRequest' });
}
});
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
})());
// set up body parser for easy-access to json
server.use(__WEBPACK_IMPORTED_MODULE_5_koa_bodyparser___default()({ formLimit: '4mb' }));
// make static folder static
server.use(__WEBPACK_IMPORTED_MODULE_4_koa_mount___default()('/assets', (() => {
var _ref2 = _asyncToGenerator(function* (ctx) {
yield __WEBPACK_IMPORTED_MODULE_1_koa_send___default()(ctx, ctx.path, {
root: `${__dirname}/../src/assets`
});
});
return function (_x3) {
return _ref2.apply(this, arguments);
};
})()));
// handle front page view -- proxy for /random/ until we (I) get some metric for rating -- switches on page 1
server.use(__WEBPACK_IMPORTED_MODULE_2_koa_route___default.a.get('/(.*)', __WEBPACK_IMPORTED_MODULE_3__routes_routes_js__["a" /* default */].handleFP));
}
// log number of active requests
logRequests() {
console.log(`Active Requests: ${this.activeRequests}`);
}
// start server
start() {
this.server.listen(this.port);
}
}
|
JavaScript
|
class OrderItem {
/**
* Constructs a new <code>OrderItem</code>.
* @alias module:model/OrderItem
* @class
* @param count {Number}
* @param parameters {Array.<module:model/ParameterValue>}
*/
constructor(count, parameters) {
this['count'] = count;this['parameters'] = parameters;
}
/**
* Constructs a <code>OrderItem</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/OrderItem} obj Optional instance to populate.
* @return {module:model/OrderItem} The populated <code>OrderItem</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new OrderItem();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'String');
}
if (data.hasOwnProperty('count')) {
obj['count'] = ApiClient.convertToType(data['count'], 'Number');
}
if (data.hasOwnProperty('parameters')) {
obj['parameters'] = ApiClient.convertToType(data['parameters'], [ParameterValue]);
}
if (data.hasOwnProperty('plan_id')) {
obj['plan_id'] = ApiClient.convertToType(data['plan_id'], 'String');
}
if (data.hasOwnProperty('catalog_id')) {
obj['catalog_id'] = ApiClient.convertToType(data['catalog_id'], 'String');
}
if (data.hasOwnProperty('provider_id')) {
obj['provider_id'] = ApiClient.convertToType(data['provider_id'], 'String');
}
if (data.hasOwnProperty('order_id')) {
obj['order_id'] = ApiClient.convertToType(data['order_id'], 'String');
}
if (data.hasOwnProperty('state')) {
obj['state'] = ApiClient.convertToType(data['state'], 'String');
}
if (data.hasOwnProperty('created_at')) {
obj['created_at'] = ApiClient.convertToType(data['created_at'], 'Date');
}
if (data.hasOwnProperty('ordered_at')) {
obj['ordered_at'] = ApiClient.convertToType(data['ordered_at'], 'Date');
}
if (data.hasOwnProperty('completed_at')) {
obj['completed_at'] = ApiClient.convertToType(data['completed_at'], 'Date');
}
if (data.hasOwnProperty('updated_at')) {
obj['updated_at'] = ApiClient.convertToType(data['updated_at'], 'Date');
}
if (data.hasOwnProperty('external_ref')) {
obj['external_ref'] = ApiClient.convertToType(data['external_ref'], 'String');
}
}
return obj;
}
/**
* @member {String} id
*/
id = undefined;
/**
* @member {Number} count
*/
count = undefined;
/**
* @member {Array.<module:model/ParameterValue>} parameters
*/
parameters = undefined;
/**
* Stores the Plan ID from the catalog
* @member {String} plan_id
*/
plan_id = undefined;
/**
* Stores the Catalog ID from the provider
* @member {String} catalog_id
*/
catalog_id = undefined;
/**
* ID of the provider object
* @member {String} provider_id
*/
provider_id = undefined;
/**
* ID of the order object
* @member {String} order_id
*/
order_id = undefined;
/**
* Current State of this order item
* @member {module:model/OrderItem.StateEnum} state
*/
state = undefined;
/**
* @member {Date} created_at
*/
created_at = undefined;
/**
* @member {Date} ordered_at
*/
ordered_at = undefined;
/**
* @member {Date} completed_at
*/
completed_at = undefined;
/**
* @member {Date} updated_at
*/
updated_at = undefined;
/**
* An external reference from the provider that can be used to track the progress of the order item
* @member {String} external_ref
*/
external_ref = undefined;
/**
* Allowed values for the <code>state</code> property.
* @enum {String}
* @readonly
*/
static StateEnum = {
/**
* value: "Created"
* @const
*/
"Created": "Created",
/**
* value: "Ordered"
* @const
*/
"Ordered": "Ordered",
/**
* value: "Failed"
* @const
*/
"Failed": "Failed",
/**
* value: "Completed"
* @const
*/
"Completed": "Completed"
};
}
|
JavaScript
|
class BusinessClassAndTypeSelect extends Component {
constructor(props){
super(props);
this.state = {
businessClasses: [],
businessTypes: [],
businessClass: null,
businessType: null
}
this.onBusinessSubtypeChange = this.onBusinessSubtypeChange.bind(this)
}
onBusinessSubtypeChange(value){
if(this.props.updateFunction) {
this.props.updateFunction(this.state.businessClass, this.state.businessType)
}
}
onBusinessClassChange(event) {
var value = event.target.value;
if(this.props.updateFunction) this.props.updateFunction(value, null)
businessRulesService
.getAllBusinessTypes(value, this.props.containerId)
.then(json => {
this.setState({
businessTypes: json.metaData.businessTypes
})
})
}
/**
* Generates a select box with list of business classes.
*/
businessClassesSelect(){
var defaultSelection = this.props.defaultBusinessClass,
businessClassOptions = [];
this.state.businessClasses.map(item => {
businessClassOptions.push(<option value={item}>{item}</option>);
});
var selectBusinessClass = (
<Input value={defaultSelection} type="select" name="business-class"
id="business-class"
onChange={this.onBusinessClassChange.bind(this)}>
<option value="">Select a business class ...</option>
{businessClassOptions}
</Input>
)
return selectBusinessClass;
}
/**
* When user selects a business class, fetch subtypes of that class and
* display it into a select box.
*/
businessTypesSelect(){
var subtypesOptions = [];
subtypesOptions.push(<option value=''>Select a type ...</option>);
if(this.state.selectBusinessTypes){
this.state.selectBusinessTypes.map(item => {
subtypesOptions.push(<option value={item.attributes.id}>{item.attributes.displayName}</option>);
});
}
var selectBusinessType = (
<Input value={this.props.defaultBusinessType} type="select" name="business-type" id="business-type"
onChange={(e) => this.onBusinessSubtypeChange(e.target.value)}>
{subtypesOptions}
</Input>
)
return selectBusinessType;
}
componentDidMount(){
businessRulesService
.getAllBusinessClass(this.props.containerId)
.then(json => {
this.setState({
businessClasses: json.metaData.businessClass
})
})
}
render() {
const businessTypesSelect= this.businessTypesSelect();
var businessClassesSelect = this.businessClassesSelect();
const display = this.props.displayFunction(businessClassesSelect, businessTypesSelect);
return (
<React.Fragment>{display}</React.Fragment>
)
}
}
|
JavaScript
|
class Comment extends Model {
/**
* Constructs comment model with the name and defined schema.
* @constructor
*/
constructor() {
super('Comments', {
caption: {
type: String,
required: true,
},
post: {
type: Schema.Types.ObjectId,
ref: 'Posts',
required: true,
},
commenter: {
type: Schema.Types.ObjectId,
ref: 'Users',
required: true,
},
});
}
}
|
JavaScript
|
class CountStream extends stream.Transform {
/**
* @see {@link Transform}
* @param {object} [options]
* @property {number|number[]} markers Add one or more markers that will fire a "marker" event once the number of
* bytes have been processed.
*/
constructor(options) {
super(options);
this.clear();
if (options) {
this.addMarker(options.markers);
}
this._bytes = 0;
}
/**
* Add one or more markers that you would like to have an event be fired on.
* @param {...number|number[]} marker
* @return {CountStream}
*/
addMarker(marker) {
if (marker) {
for (let entry of arguments) {
this._markers = this._markers.concat(entry);
}
this._markers.sort();
}
return this;
}
/**
* Remove one or more markers that have been set previously.
* @param {...number|number[]} marker
* @return {CountStream}
*/
removeMarker(marker) {
if (marker) {
this._markers = this._markers.filter(val => {
for (let entry of arguments) {
if (entry instanceof Array) {
if (entry.indexOf(val) !== -1) {
return false;
}
} else if (entry == val) {
return false;
}
}
return true;
});
}
return this;
}
/**
* Removes all registered markers.
*/
clear() {
this._markers = [];
return this;
}
_transform(chunk, encoding, cb) {
var buf = chunk instanceof Buffer ? chunk : new Buffer(chunk, encoding);
this._bytes += buf.length;
while (this._markers.length && this._markers[0] <= this._bytes) {
this.emit('marker', this._markers.shift(), this);
}
if (this.push(buf)) {
setImmediate(cb);
}
}
/**
* Returns the number of bytes that have been read so far.
* @returns {number}
*/
get count() {
return this._bytes;
}
}
|
JavaScript
|
class User extends OkitArtifact {
/*
** Create
*/
constructor (data={}, okitjson={}) {
super(okitjson);
// Configure default values
// const array_pos = okitjson.users ? okitjson.users.length + 1 : 0;
// this.display_name = this.generateDefaultName(okitjson.users.length + 1);
this.compartment_id = null;
this.description = ''
this.email = ''
// Update with any passed data
this.merge(data);
this.convert();
}
/*
** Clone Functionality
*/
clone() {
return new User(JSON.clone(this), this.getOkitJson());
}
/*
** Name Generation
*/
getNamePrefix() {
return super.getNamePrefix() + 'usr';
}
/*
** Static Functionality
*/
static getArtifactReference() {
return 'User';
}
}
|
JavaScript
|
class ButtonShuffle extends Component {
static propTypes = {
shuffle: React.PropTypes.bool
}
constructor(props) {
super(props);
}
render() {
const svg = require('../../../images/icons/player-shuffle.svg');
const buttonClasses = classnames('button', {
active: this.props.shuffle
});
return (
<button type='button' className={ buttonClasses } onClick={ AppActions.player.shuffle }>
<InlineSVG src={ svg } className='icon shuffle' />
</button>
);
}
}
|
JavaScript
|
class Boid {
constructor(x, y, word, category) {
this.acceleration = createVector(0, 0);
this.velocity = p5.Vector.random2D();
this.position = createVector(x, y);
this.r = 5.0;
this.maxspeed = 0.9; // Maximum speed
this.maxforce = 0.05; // Maximum steering force
this.word = word;
this.category = category;
this.colour = '#000000';
// Niall using this in draw() to centre the text at the boid's position
this.width = textWidth(word);
// here is where we set different properties for different categories of boid!
// i'm matching the 'category' name based on the column heading we've taken from the CSV file.
switch (category) {
case 'mass':
this.maxspeed = 7.0;
this.maxforce = 0.9;
this.colour = '#FA8072';
break;
case 'spreading':
this.maxspeed = 0.9;
this.maxforce = 0.05;
this.colour = '#CD853F';
break;
case 'edge':
this.maxspeed = 2.0;
this.maxforce = 0.8;
this.colour = '#9ACD32';
break;
case 'vibration':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#7f827d';
break;
case 'movement':
this.maxspeed = 3.0;
this.maxforce = 0.5;
this.colour = '#ff0000';
case 'structures':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#4a6355';
break;
case 'living':
this.maxspeed = 1.2;
this.maxforce = 0.75;
this.colour = '#155432';
break;
case 'gesture':
this.maxspeed = 0.6;
this.maxforce = 0.8;
this.colour = '#69945f';
break;
case 'structures':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = 'grey';
break;
case 'placeholder':
this.maxspeed = 0.02;
this.maxforce = 0.15;
this.colour = '#6f7a74';
break;
case 'form/quality':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#d4a8a1';
break;
case 'mass_phrases':
this.maxspeed = 0.42;
this.maxforce = 0.5;
this.colour = '#808000';
break;
case 'spreading_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#EAC50A';
break;
case 'edge_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#9ac777';
break;
case 'movement_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#c77d77';
break;
case 'vibration_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#c2b082';
break;
case 'living_phrases':
this.maxspeed = 0.52;
this.maxforce = 0.5;
this.colour = '#556952';
break;
case 'gesture_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#ba9272';
break;
case 'structures_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#ba9272';
break;
case 'placeholder_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#c77d77';
break;
case 'form_phrases':
this.maxspeed = 0.2;
this.maxforce = 0.5;
this.colour = '#ba9272';
break;
default:
print("we need to create some properties for this category: " + category);
break;
}
this.draw = function() {
this.velocity.limit(1);
fill(this.colour);
// if you wanna debug the boids actual position, uncomment this
// ellipse(this.position.x, this.position.y, 5, 5);
// i've offset the text by half its width, so the text is displayed centred at the boid
text(this.word, this.position.x - this.width / 2, this.position.y);
textSize(20);
}
}
run(boids) {
this.flock(boids);
this.update();
this.borders();
this.draw();
}
// Forces go into acceleration
applyForce(force) {
this.acceleration.add(force);
}
// We accumulate a new acceleration each time based on three rules
flock(boids) {
let sep = this.separate(boids); // Separation
let ali = this.align(boids); // Alignment
let coh = this.cohesion(boids); // Cohesion
// Arbitrarily weight these forces
sep.mult(2.5);
ali.mult(1.0);
coh.mult(1.0);
// Add the force vectors to acceleration
this.applyForce(sep);
this.applyForce(ali);
this.applyForce(coh);
}
// Method to update location
update() {
// Update velocity
this.velocity.add(this.acceleration);
// Limit speed
this.velocity.limit(this.maxspeed);
this.position.add(this.velocity);
// Reset acceleration to 0 each cycle
this.acceleration.mult(0);
}
// A method that calculates and applies a steering force towards a target
// STEER = DESIRED MINUS VELOCITY
seek(target) {
let desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
// Normalize desired and scale to maximum speed
desired.normalize();
desired.mult(this.maxspeed);
// Steering = Desired minus Velocity
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxforce); // Limit to maximum steering force
return steer;
}
// Wraparound
borders() {
// preventing boids from just disappearing off screen by making their bounds way bigger
let size_exaggeration = this.r * 10;
if (this.position.x < -size_exaggeration) this.position.x = width + size_exaggeration;
if (this.position.y < -size_exaggeration) this.position.y = height + size_exaggeration;
if (this.position.x > width + size_exaggeration) this.position.x = -size_exaggeration;
if (this.position.y > height + size_exaggeration) this.position.y = -size_exaggeration;
}
// Separation
// Method checks for nearby boids and steers away
separate(boids) {
let desiredseparation = 25.0;
let steer = createVector(0, 0);
let count = 0;
// For every boid in the system, check if it's too close
for (let i = 0; i < boids.length; i++) {
let d = p5.Vector.dist(this.position, boids[i].position);
// If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
if ((d > 0) && (d < desiredseparation)) {
// Calculate vector pointing away from neighbor
let diff = p5.Vector.sub(this.position, boids[i].position);
diff.normalize();
diff.div(d); // Weight by distance
steer.add(diff);
count++; // Keep track of how many
}
}
// Average -- divide by how many
if (count > 0) {
steer.div(count);
}
// As long as the vector is greater than 0
if (steer.mag() > 0) {
// Implement Reynolds: Steering = Desired - Velocity
steer.normalize();
steer.mult(this.maxspeed);
steer.sub(this.velocity);
steer.limit(this.maxforce);
}
return steer;
}
// Alignment
// For every nearby boid in the system, calculate the average velocity
align(boids) {
let neighbordist = 50;
let sum = createVector(0, 0);
let count = 0;
for (let i = 0; i < boids.length; i++) {
let d = p5.Vector.dist(this.position, boids[i].position);
if ((d > 0) && (d < neighbordist)) {
sum.add(boids[i].velocity);
count++;
}
}
if (count > 0) {
sum.div(count);
sum.normalize();
sum.mult(this.maxspeed);
let steer = p5.Vector.sub(sum, this.velocity);
steer.limit(this.maxforce);
return steer;
} else {
return createVector(0, 0);
}
}
// Cohesion
// For the average location (i.e. center) of all nearby boids, calculate steering vector towards that location
cohesion(boids) {
let neighbordist = 50;
let sum = createVector(0, 0); // Start with empty vector to accumulate all locations
let count = 0;
for (let i = 0; i < boids.length; i++) {
let d = p5.Vector.dist(this.position, boids[i].position);
if ((d > 0) && (d < neighbordist)) {
sum.add(boids[i].position); // Add location
count++;
}
}
if (count > 0) {
sum.div(count);
return this.seek(sum); // Steer towards the location
} else {
return createVector(0, 0);
}
}
}
|
JavaScript
|
class LrndesignStepper extends PolymerElement {
constructor() {
super();
import("@lrnwebcomponents/lrndesign-stepper/lib/lrndesign-stepper-button.js");
}
static get template() {
return html`
<style>
:host {
display: block;
}
</style>
<div class="buttons"><slot></slot></div>
`;
}
static get tag() {
return "lrndesign-stepper";
}
ready() {
super.ready();
var children = this.shadowRoot
.querySelector("slot")
.assignedNodes({ flatten: true })
.filter(n => n.nodeType === Node.ELEMENT_NODE);
if (children.length > 1) {
children.forEach(function(child, index) {
if (index === 0) {
child.setAttribute("location", "start");
} else if (index === children.length - 1) {
child.setAttribute("location", "end");
} else {
child.setAttribute("location", "middle");
}
console.log(child, index);
});
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.