language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class ConnectionHandler {
constructor(connection) {
this.connection = connection;
}
handle(data) {}
enter() {}
leave() {}
hungup() {}
} |
JavaScript | class SubTableComponent extends Component {
render() {
const styles = {
title: {
textAlign: 'center',
}
}
const chartData = dataToPieChart(this.props.row.original);
const { row } = this.props;
return (
<div>
<h4 style={styles.title}>{getFullProviderName(row.original.provider)} in {row.original.region}</h4>
<div className="row" style={{ padding: '0px 40px'}}>
<div className="col-md-6">
<SubBlock details={row.original.details.frequent} title="Frequent Access"/>
<SubBlock details={row.original.details.infrequent} title="Infrequent Access"/>
<SubBlock details={row.original.details.archive} title="Archive"/>
</div>
<div className="col-md-6">
<PieChartComponent data={chartData} elementId={`chartId-${hashString(row.original.region)}`}/>
</div>
</div>
<br/>
<div className="clearfix"/>
</div>
);
}
} |
JavaScript | class FormCheckbox extends React.Component {
constructor(props) {
super(props);
this.getRef = this.getRef.bind(this);
}
getRef(ref) {
if (this.props.innerRef) {
this.props.innerRef(ref);
}
this.ref = ref;
}
render() {
const {
className,
children,
inline,
valid,
invalid,
innerRef,
toggle,
small,
id: _id,
...attrs
} = this.props;
const labelClasses = classNames(
className,
"custom-control",
!toggle ? "custom-checkbox" : "custom-toggle",
toggle && small && "custom-toggle-sm",
inline && "custom-control-inline",
valid && "is-valid",
invalid && "is-invalid"
);
const inputClasses = classNames(
"custom-control-input",
valid && "is-valid",
invalid && "is-invalid"
);
const id = _id || `dr-checkbox-${shortid.generate()}`;
return (
<label className={labelClasses}>
<input
{...attrs}
ref={innerRef}
id={id}
type="checkbox"
className={inputClasses}
/>
<label id={id} className="custom-control-label" aria-hidden="true" onClick={this.props.onChange} />
<span className="custom-control-description">{children}</span>
</label>
);
}
} |
JavaScript | class UiYoutube extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.classList.add("youtube");
this.videoid = this.getAttribute("videoid") || null;
this.videoparams = this.getAttribute("videoparams") || null;
// Based on the YouTube ID, we can easily find the thumbnail image
this.style.backgroundImage = 'url(http://i.ytimg.com/vi/' + this.videoid + '/sddefault.jpg)';
// Overlay the Play icon to make it look like a video player
var play = document.createElement("div");
play.setAttribute("class", "play");
play = this.appendChild(play);
this.onclick = function () {
// Create an iFrame with autoplay set to true
var iframe = document.createElement("iframe");
var iframe_url = "https://www.youtube.com/embed/" + this.videoid + "?autoplay=1&autohide=1";
if (this.videoparams) iframe_url += '&' + this.videoparams;
iframe.setAttribute("src", iframe_url);
iframe.setAttribute("frameborder", '0');
iframe.setAttribute("allowfullscreen", 'true');
iframe.setAttribute("allow", 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
// The height and width of the iFrame should be the same as parent
iframe.style.width = this.style.width;
iframe.style.height = this.style.height;
// Replace the YouTube thumbnail with YouTube Player
play.remove();
this.appendChild(iframe);
}
}
} |
JavaScript | class BundleResolver {
// private final Trace trace;
constructor(pool) {
this.pool = pool;
}
// NODE-TODO private final Map<ModuleName, AbstractModuleDefinition> moduleDefinitions;
/**
* @param {ModuleDefinition} bundle Bundle definition to resolve
* @param {object} [options] Options
* @param {string[]} [options.defaultFileTypes]
List of default file types to which a prefix pattern shall be expanded.
* @returns {Promise<ResolvedBundleDefinition>}
*/
resolve(bundle, options) {
const fileTypes = (options && options.defaultFileTypes) || undefined;
let visitedResources = Object.create(null);
let selectedResources = Object.create(null);
let selectedResourcesSequence = [];
const pool = this.pool;
/**
* @param {JSModuleSectionDefinition} section
* @returns {Collection<ModuleName>}
*/
function collectModulesForSection(section) {
let prevLength;
let newKeys;
// NODE-TODO resolvePlaceholders(section.getFilters());
const filters = new ResourceFilterList( section.filters, fileTypes );
function isAccepted(resourceName, required) {
let match = required;
// evaluate module filters only when global filters match
match = filters.matches(resourceName, required); // NODE-TODO filter.matches(name, match, required);
return match;
}
function checkForDecomposableBundle(resource) {
if ( resource == null ||
resource.info == null ||
resource.info.subModules.length === 0 ||
/(?:^|\/)library.js$/.test(resource.info.name) ) {
return {resource, decomposable: false};
}
return Promise.all(
resource.info.subModules.map((sub) => pool.findResource(sub).catch(() => false))
).then((modules) => {
// it might look more natural to expect 'all' embedded modules to exist in the pool,
// but expecting only 'some' module to exist is a more conservative approach
return ({resource, decomposable: modules.some(($) => ($))});
});
}
function checkAndAddResource(resourceName, depth, msg) {
// console.log(" checking " + resourceName + " at depth " + depth);
let maybeAccepted = true;
let done;
if ( !(resourceName in visitedResources) && (maybeAccepted = isAccepted(resourceName, depth > 0)) ) {
// console.log(" accepted: " + resourceName );
if ( dependencyTracker != null ) {
dependencyTracker.visitDependency(resourceName);
}
// remember that we have seen this module already
visitedResources[resourceName] = resourceName;
done = pool.findResourceWithInfo(resourceName)
.catch( (err) => {
// if the caller provided an error message, log it
if ( msg ) {
log.error(msg);
}
// return undefined
})
.then( (resource) => checkForDecomposableBundle(resource) )
.then( ({resource, decomposable}) => {
const dependencyInfo = resource && resource.info;
let promises = [];
if ( decomposable ) {
// bundles are not added, only their embedded modules
promises = dependencyInfo.subModules.map( (included) => {
return checkAndAddResource(included, depth + 1,
"**** error: missing submodule " + included + ", included by " + resourceName);
});
} else if ( resource != null ) {
// trace.trace(" checking dependencies of " + resource.name );
selectedResources[resourceName] = resourceName;
selectedResourcesSequence.push(resourceName);
// trace.info(" collecting %s", resource.name);
// add dependencies, if 'resolve' is configured
if ( section.resolve && dependencyInfo ) {
promises = dependencyInfo.dependencies.map( function(required) {
// ignore conditional dependencies if not configured
if ( !section.resolveConditional &&
dependencyInfo.isConditionalDependency(required) ) {
return;
}
return checkAndAddResource( required, depth + 1,
"**** error: missing module " + required + ", required by " + resourceName);
});
}
// add renderer, if 'renderer' is configured and if it exists
if ( section.renderer ) {
const rendererModuleName = UI5ClientConstants.getRendererName( resourceName );
promises.push( checkAndAddResource( rendererModuleName, depth + 1) );
}
}
return Promise.all( promises.filter( ($) => $ ) );
});
if ( dependencyTracker != null ) {
dependencyTracker.endVisitDependency(resourceName);
}
} else if ( dependencyTracker != null && maybeAccepted && isAccepted(resourceName, depth>0) ) {
// Note: the additional 'maybeAccepted' condition avoids calling the expensive 'isAccepted'
// twice if it already returned false in the 'if' condition
dependencyTracker.visitDependencyAgain(resourceName);
done = Promise.resolve(true);
}
return done;
}
let oldSelectedResources;
let oldIgnoredResources;
let oldSelectedResourcesSequence;
if ( section.mode == SectionType.Require ) {
oldSelectedResources = selectedResources;
oldIgnoredResources = visitedResources;
oldSelectedResourcesSequence = selectedResourcesSequence;
selectedResources = Object.create(null);
selectedResourcesSequence = [];
visitedResources = Object.create(null);
} else {
// remember current state of module collection - needed to determine difference set later
prevLength = selectedResourcesSequence.length;
}
/*
* In the Maven version of the bundle tooling, it was possible to define the content
* of a section of type 'provided' by listing a set of other bundle definition files.
* The whole content of those bundles then was determined and excluded from the current bundle.
*
* In the NodeJS version of the tooling, this is not supported. Instead, the resulting JS file for
* a bundle can be specified and the dependency analysis will determine the content of the bundle
* and exclude it from the current bundle.
*
if ( section.mode == SectionType.Provided && section.modules ) {
throw new Error("unsupported");
for(ModuleName providedModuleDefinitionName : section.getProvidedModules()) {
AbstractModuleDefinition providedModuleDefinition =
moduleDefinitions.get(providedModuleDefinitionName);
if ( providedModuleDefinition instanceof JSModuleDefinition ) {
trace.verbose(" resolving provided module %s", providedModuleDefinitionName);
ModuleResolver resolver = new ModuleResolver(trace, pool, moduleDefinitions, null);
ResolvedBundleDefinition resolved = resolver.run((JSModuleDefinition) providedModuleDefinition,
placeholderValues);
for(ResolvedBundleDefinitionSection resolvedSection : resolved.getSections()) {
if ( resolvedSection.getMode() != SectionType.Require ) {
for(ModuleName providedModuleName : resolvedSection.getModules()) {
ModuleInfo providedModuleInfo = pool.getModuleInfo(providedModuleName);
if ( providedModuleInfo != null &&
!visitedModules.containsKey(providedModuleName) ) {
visitedModules.put(providedModuleName, providedModuleInfo);
}
}
}
}
} else {
trace.error("provided module could not be found or is not a JS module : %s",
providedModuleDefinitionName);
}
}
}
*/
// scan all known resources
const promises = pool.resources.map( function(resource) {
return checkAndAddResource(resource.name, 0);
});
return Promise.all(promises).then( function() {
if ( section.mode == SectionType.Require ) {
newKeys = selectedResourcesSequence;
selectedResources = oldSelectedResources;
visitedResources = oldIgnoredResources;
selectedResourcesSequence = oldSelectedResourcesSequence;
} else {
newKeys = selectedResourcesSequence.slice( prevLength ); // preserve order (for raw sections)
}
// console.log(" resolved module set: %s", newKeys);
return newKeys;
});
}
/*
* In the Maven version of the bundle tooling, a bundle definition could be
* parameterized by locale, ltr/rtl mode and theme. The LBT doesn't support this yet.
*
* As theming files are build with less now, only the parameterization by locale
* might be needed. It's lack can be compensated by programmatically building the
* necessary bundle definitions and e.g. injecting the locale into the Id or the
* filters defining the content of the bundle.
* .
private Collection<ModuleFilter> resolvePlaceholders(Collection<ModuleFilter> list) {
if ( !placeholderValues.isEmpty() ) {
List<ModuleFilter> modifiedList = new ArrayList<ModuleFilter>(list);
for(int i=0; i<modifiedList.size(); i++) {
ModuleNameMatcher matcher = modifiedList.get(i).getMatcher();
ModuleNameMatcher resolved = ModuleNamePattern.resolvePlaceholders(matcher, placeholderValues);
if ( resolved != matcher ) {
modifiedList.set(i, new ModuleFilter(resolved, modifiedList.get(i).getMode()));
}
}
list = modifiedList;
}
return list;
} */
// NODE-TODO if ( PerfMeasurement.ACTIVE ) PerfMeasurement.start(PerfKeys.RESOLVE_MODULE);
if ( dependencyTracker != null ) {
dependencyTracker.startResolution(bundle);
}
// NODE-TODO placeholderValues = vars;
log.verbose(" resolving bundle definition %s", bundle.name);
const resolved = new ResolvedBundleDefinition(bundle /* , vars*/);
let previous = Promise.resolve(true);
bundle.sections.forEach(function(section, index) {
previous = previous.then( function() {
log.verbose(" resolving section%s of type %s",
section.name ? " '" + section.name + "'" : "", section.mode);
// NODE-TODO long t0=System.nanoTime();
const resolvedSection = resolved.sections[index];
return collectModulesForSection(section).
then( (modules) => {
if ( section.mode == SectionType.Raw && section.sort ) {
// sort the modules in topological order
return topologicalSort(pool, modules).then( (modules) => {
log.verbose(" resolved modules (sorted): %s", modules);
return modules;
});
}
log.verbose(" resolved modules: %s", modules);
return modules;
}).then( function(modules) {
resolvedSection.modules = modules;
});
// NODE-TODO long t1=System.nanoTime();
// NODE-TODO if ( PerfMeasurement.ACTIVE ) trace.info("[Measurement] %12d nsec - %s", t1-t0,
// "Module collection and filtering");
});
});
if ( dependencyTracker != null ) {
dependencyTracker.endResolution(bundle, /* NODE-TODO, vars*/);
}
// NODE-TODO if ( PerfMeasurement.ACTIVE ) PerfMeasurement.stop(PerfKeys.RESOLVE_MODULE);
return previous.then( function() {
log.verbose(" resolving bundle done");
return resolved;
});
}
} |
JavaScript | class StripeController {
/**
* @description -This method charges on stripe
* @param {object} req - The request payload sent from the router
* @param {object} res - The response payload sent back from the controller
* @returns {object} - charge and message
*/
static async payWithStripe(req, res) {
const {
order_id: orderId, description, amount, currency, stripeToken
} = req.body;
const { email } = req.user;
try {
const order = await Order.findOne({ where: { order_id: orderId, customer_id: req.user.id } });
if (order && order.dataValues.status === 0) {
const customer = await Stripe.customers.create({
email,
source: stripeToken
});
const charge = await Stripe.charges.create({
amount,
description,
currency,
customer: customer.id,
metadata: { order_id: orderId },
});
await order.update({ status: 1 });
sendMail({
from: process.env.MAIL_SENDER,
to: email,
subject: 'Confirmation On Your Order',
text: confirmationTemplateText(req.user.name, process.env.BASE_URL),
html: confirmationTemplateHtml(req.user.name, process.env.BASE_URL)
});
res.status(200).json({ charge, message: 'Payment processed' });
} else if (order && order.dataValues.status === 1) {
return res.status(422).json({
error: {
status: 422,
message: 'Order has already been completed',
field: 'order id'
}
});
} else {
return res.status(404).json({
error: {
status: 404,
message: 'Order id does not exist',
field: 'order id'
}
});
}
} catch (error) {
if (error.message.includes('Invalid API Key')) {
return res.status(401).json({
code: 'AUT_02',
message: 'The apikey is invalid.',
field: 'API-KEY'
});
}
if (error.message.includes('You cannot use a Stripe token more than once')) {
return res.status(500).json({
code: 'resource_missing',
message: `No such token: ${stripeToken}`,
field: 'source'
});
}
return res.status(500).json(errorResponse(req, res, 500, 'STR_500', error.message, ''));
}
}
/**
* @description -This method returns webhook from Stripe
* @param {object} req - The request payload sent from the router
* @param {object} res - The response payload sent back from the controller
* @returns {object} - webhook details
*/
static async webhook(req, res) {
return res.status(200).json({ received: true });
}
/**
* @description -This method returns a Stripe token
* @param {object} req - The request payload sent from the router
* @param {object} res - The response payload sent back from the controller
* @returns {object} - get token
*/
static async getToken(req, res) {
try {
const token = await Stripe.tokens.create({
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2020,
cvc: '123'
}
});
res.status(200).send({ stripeToken: token.id });
} catch (error) {
res.status(404).send({ error });
}
}
} |
JavaScript | class LifecycleBucketProcessor {
/**
* Constructor of LifecycleBucketProcessor
*
* @constructor
* @param {Object} zkConfig - zookeeper config
* @param {Object} kafkaConfig - kafka configuration object
* @param {string} kafkaConfig.hosts - list of kafka brokers
* as "host:port[,host:port...]"
* @param {Object} lcConfig - lifecycle config
* @param {Object} lcConfig.auth - authentication info
* @param {String} lcConfig.bucketTasksTopic - lifecycle bucket topic name
* @param {Object} lcConfig.bucketProcessor - kafka consumer object
* @param {String} lcConfig.bucketProcessor.groupId - kafka
* consumer group id
* @param {Number} [lcConfig.bucketProcessor.concurrency] - number
* of max allowed concurrent operations
* @param {Object} [lcConfig.backlogMetrics] - param object to
* publish backlog metrics to zookeeper (see {@link
* BackbeatConsumer} constructor)
* @param {Object} s3Config - s3 config
* @param {String} s3Config.host - host ip
* @param {String} s3Config.port - port
* @param {String} transport - http or https
*/
constructor(zkConfig, kafkaConfig, lcConfig, s3Config, transport) {
this._log = new Logger('Backbeat:Lifecycle:BucketProcessor');
this._zkConfig = zkConfig;
this._kafkaConfig = kafkaConfig;
this._lcConfig = lcConfig;
this._s3Endpoint = `${transport}://${s3Config.host}:${s3Config.port}`;
this._transport = transport;
this._bucketProducer = null;
this._objectProducer = null;
this.accountCredsCache = {};
// The task scheduler for processing lifecycle tasks concurrently.
this._internalTaskScheduler = async.queue((ctx, cb) => {
const { task, rules, value, s3target } = ctx;
return task.processBucketEntry(rules, value, s3target, cb);
}, this._lcConfig.bucketProcessor.concurrency);
// Listen for errors from any task being processed.
this._internalTaskScheduler.drain(err => {
if (err) {
this._log.error('error occurred during task processing', {
error: err,
});
}
});
}
/**
* Send entry to the object task topic
* @param {Object} entry - The Kafka entry to send to the topic
* @param {Function} cb - The callback to call
* @return {undefined}
*/
sendObjectEntry(entry, cb) {
const entries = [{ message: JSON.stringify(entry) }];
this._objectProducer.send(entries, cb);
}
/**
* Send entry back to bucket task topic
* @param {Object} entry - The Kafka entry to send to the topic
* @param {Function} cb - The callback to call
* @return {undefined}
*/
sendBucketEntry(entry, cb) {
const entries = [{ message: JSON.stringify(entry) }];
this._bucketProducer.send(entries, cb);
}
/**
* Get the state variables of the current instance.
* @return {Object} Object containing the state variables
*/
getStateVars() {
return {
sendBucketEntry: this.sendBucketEntry.bind(this),
sendObjectEntry: this.sendObjectEntry.bind(this),
enabledRules: this._lcConfig.rules,
log: this._log,
};
}
/**
* Return an S3 client instance using the given account credentials.
* @param {Object} accountCreds - Object containing account credentials
* @param {String} accountCreds.accessKeyId - The account access key
* @param {String} accountCreds.secretAccessKey - The account secret key
* @return {AWS.S3} The S3 client instance to make requests with
*/
_getS3Client(accountCreds) {
return new AWS.S3({
endpoint: this._s3Endpoint,
credentials: {
accessKeyId: accountCreds.accessKeyId,
secretAccessKey: accountCreds.secretAccessKey,
},
sslEnabled: this._transport === 'https',
s3ForcePathStyle: true,
signatureVersion: 'v4',
httpOptions: {
agent: new http.Agent({ keepAlive: true }),
timeout: 0,
},
maxRetries: 0,
});
}
/**
* Determine whether the given config should be processed.
* @param {Object} config - The bucket lifecycle configuration
* @return {Boolean} Whether the config should be processed
*/
_shouldProcessConfig(config) {
if (config.Rules.length === 0) {
this._log.debug('bucket lifecycle config has no rules to process', {
config,
});
return false;
}
const { rules } = this._lcConfig;
// Check if backbeat config has a lifecycle rule enabled for processing.
const enabled = Object.keys(rules).some(rule => rules[rule].enabled);
if (!enabled) {
this._log.debug('no lifecycle rules enabled in backbeat config');
}
return enabled;
}
/**
* Process the given bucket entry, get the bucket's lifecycle configuration,
* and schedule a task with the lifecycle configuration rules, if
* applicable.
* @param {Object} entry - The kafka entry containing the information for
* performing a listing of the bucket's objects
* @param {Object} entry.value - The value of the entry object
* (see format of messages in lifecycle topic for bucket tasks)
* @param {Function} cb - The callback to call
* @return {undefined}
*/
_processBucketEntry(entry, cb) {
const { error, result } = safeJsonParse(entry.value);
if (error) {
this._log.error('could not parse bucket entry',
{ value: entry.value, error });
return process.nextTick(() => cb(error));
}
if (result.action !== PROCESS_OBJECTS_ACTION) {
return process.nextTick(cb);
}
if (typeof result.target !== 'object') {
this._log.error('malformed kafka bucket entry', {
method: 'LifecycleBucketProcessor._processBucketEntry',
entry: result,
});
return process.nextTick(() => cb(errors.InternalError));
}
const { bucket, owner } = result.target;
if (!bucket || !owner) {
this._log.error('kafka bucket entry missing required fields', {
method: 'LifecycleBucketProcessor._processBucketEntry',
bucket,
owner,
});
return process.nextTick(() => cb(errors.InternalError));
}
this._log.debug('processing bucket entry', {
method: 'LifecycleBucketProcessor._processBucketEntry',
bucket,
owner,
});
return async.waterfall([
next => this._getAccountCredentials(owner, next),
(accountCreds, next) => {
const s3 = this._getS3Client(accountCreds);
const params = { Bucket: bucket };
return s3.getBucketLifecycleConfiguration(params,
(err, data) => {
next(err, data, s3);
});
},
], (err, config, s3) => {
if (err) {
this._log.error('error getting bucket lifecycle config', {
method: 'LifecycleBucketProcessor._processBucketEntry',
bucket,
owner,
error: err,
});
return cb(err);
}
if (!this._shouldProcessConfig(config)) {
return cb();
}
this._log.info('scheduling new task for bucket lifecycle', {
method: 'LifecycleBucketProcessor._processBucketEntry',
bucket,
owner,
details: result.details,
});
return this._internalTaskScheduler.push({
task: new LifecycleTask(this),
rules: config.Rules,
value: result,
s3target: s3,
}, cb);
});
}
/**
* Set up the backbeat producer with the given topic.
* @param {String} topic - - Kafka topic to write to
* @param {Function} cb - The callback to call
* @return {undefined}
*/
_setupProducer(topic, cb) {
const producer = new BackbeatProducer({
kafka: { hosts: this._kafkaConfig.hosts },
topic,
});
producer.once('error', cb);
producer.once('ready', () => {
producer.removeAllListeners('error');
producer.on('error', err => {
this._log.error('error from backbeat producer', {
topic,
error: err,
});
});
return cb(null, producer);
});
}
/**
* Set up the lifecycle consumer.
* @return {undefined}
*/
_setupConsumer() {
let consumerReady = false;
this._consumer = new BackbeatConsumer({
zookeeper: {
connectionString: this._zkConfig.connectionString,
},
kafka: { hosts: this._kafkaConfig.hosts },
topic: this._lcConfig.bucketTasksTopic,
groupId: this._lcConfig.bucketProcessor.groupId,
concurrency: this._lcConfig.bucketProcessor.concurrency,
queueProcessor: this._processBucketEntry.bind(this),
autoCommit: true,
backlogMetrics: this._lcConfig.backlogMetrics,
});
this._consumer.on('error', err => {
if (!consumerReady) {
this._log.fatal('unable to start lifecycle consumer', {
error: err,
method: 'LifecycleBucketProcessor._setupConsumer',
});
process.exit(1);
}
});
this._consumer.on('ready', () => {
consumerReady = true;
this._consumer.subscribe();
});
}
/**
* Set up the credentials (service account credentials or provided
* by vault depending on config)
* @return {undefined}
*/
_setupCredentials() {
const { type } = this._lcConfig.auth;
if (type === 'vault') {
return this._setupVaultClientCache();
}
return undefined;
}
/**
* Set up the vault client cache for making requests to vault.
* @return {undefined}
*/
_setupVaultClientCache() {
const { vault } = this._lcConfig.auth;
const { host, port, adminPort, adminCredentialsFile } = vault;
const adminCredsJSON = fs.readFileSync(adminCredentialsFile);
const adminCredsObj = JSON.parse(adminCredsJSON);
const accessKey = Object.keys(adminCredsObj)[0];
const secretKey = adminCredsObj[accessKey];
this._vaultClientCache = new VaultClientCache();
if (accessKey && secretKey) {
this._vaultClientCache
.setHost('lifecycle:admin', host)
.setPort('lifecycle:admin', adminPort)
.loadAdminCredentials('lifecycle:admin', accessKey, secretKey);
} else {
throw new Error('Lifecycle bucket processor not properly ' +
'configured: missing credentials for Vault admin client');
}
this._vaultClientCache
.setHost('lifecycle:s3', host)
.setPort('lifecycle:s3', port);
}
/**
* Get the account's credentials for making a request with S3.
* @param {String} canonicalId - The canonical ID of the bucket owner.
* @param {Function} cb - The callback to call with the account credentials.
* @return {undefined}
*/
_getAccountCredentials(canonicalId, cb) {
const cachedAccountCreds = this.accountCredsCache[canonicalId];
if (cachedAccountCreds) {
return process.nextTick(() => cb(null, cachedAccountCreds));
}
const credentials = getAccountCredentials(this._lcConfig.auth,
this._log);
if (credentials) {
this.accountCredsCache[canonicalId] = credentials;
return process.nextTick(() => cb(null, credentials));
}
const { type } = this._lcConfig.auth;
if (type === 'vault') {
return this._generateVaultAdminCredentials(canonicalId, cb);
}
return cb(errors.InternalError.customizeDescription(
`invalid auth type ${type}`));
}
_generateVaultAdminCredentials(canonicalId, cb) {
const vaultClient = this._vaultClientCache.getClient('lifecycle:s3');
const vaultAdmin = this._vaultClientCache.getClient('lifecycle:admin');
return async.waterfall([
// Get the account's display name for generating a new access key.
next =>
vaultClient.getAccounts(undefined, undefined, [canonicalId], {},
(err, data) => {
if (err) {
return next(err);
}
if (data.length !== 1) {
return next(errors.InternalError);
}
return next(null, data[0].name);
}),
// Generate a new account access key beacuse it has not been cached.
(name, next) =>
vaultAdmin.generateAccountAccessKey(name, (err, data) => {
if (err) {
return next(err);
}
const accountCreds = {
accessKeyId: data.id,
secretAccessKey: data.value,
};
this.accountCredsCache[canonicalId] = accountCreds;
return next(null, accountCreds);
}),
], (err, accountCreds) => {
if (err) {
this._log.error('error generating new access key', {
error: err.message,
method: 'LifecycleBucketProcessor._getAccountCredentials',
});
return cb(err);
}
return cb(null, accountCreds);
});
}
/**
* Set up the producers and consumers needed for lifecycle.
* @return {undefined}
*/
start() {
this._setupCredentials();
return async.parallel([
// Set up producer to populate the lifecycle bucket task topic.
next => this._setupProducer(this._lcConfig.bucketTasksTopic,
(err, producer) => {
if (err) {
this._log.error('error setting up kafka producer for ' +
'bucket task', {
error: err.message,
method: 'LifecycleBucketProcessor.start',
});
return next(err);
}
this._bucketProducer = producer;
return next();
}),
// Set up producer to populate the lifecycle object task topic.
next => this._setupProducer(this._lcConfig.objectTasksTopic,
(err, producer) => {
if (err) {
this._log.error('error setting up kafka producer for ' +
'object task', {
error: err.message,
method: 'LifecycleBucketProcessor.start',
});
return next(err);
}
this._objectProducer = producer;
return next();
}),
], err => {
if (err) {
this._log.error('error setting up kafka clients', {
error: err,
method: 'LifecycleBucketProcessor.start',
});
process.exit(1);
}
this._setupConsumer();
this._log.info('lifecycle bucket processor successfully started');
return undefined;
});
}
/**
* Close the lifecycle bucket processor
* @param {function} cb - callback function
* @return {undefined}
*/
close(cb) {
async.parallel([
done => {
this._log.debug('closing bucket tasks consumer');
this._consumer.close(done);
},
done => {
this._log.debug('closing bucket tasks producer');
this._bucketProducer.close(done);
},
done => {
this._log.debug('closing object tasks producer');
this._objectProducer.close(done);
},
], () => cb());
}
isReady() {
return this._bucketProducer && this._bucketProducer.isReady() &&
this._objectProducer && this._objectProducer.isReady() &&
this._consumer && this._consumer.isReady();
}
} |
JavaScript | class ChainSetup extends GenerateAddressBase {
/**
* Generate address constructor
*
* @param params {object}
* @param {string} params.chainId - chain kind
* @param {string} params.chainKind - chain kind
* @param {string} params.addressKind - type of address
*
*/
constructor(params) {
super(params);
const oThis = this;
oThis.chainId = params.chainId;
oThis.chainKind = params['chainKind'];
oThis.addressKind = params['addressKind'];
oThis.associatedAuxChainId = oThis.chainKind === coreConstants.auxChainKind ? oThis.chainId : 0;
}
/**
* Insert into chain addresses table.
*
* @param {Number} knownAddressId
*
* @return Promise<void>
*/
async insertIntoTable(knownAddressId) {
const oThis = this;
const insertedRec = await new ChainAddressModel().insertAddress({
associatedAuxChainId: oThis.associatedAuxChainId,
addressKind: oThis.addressKind,
address: oThis.ethAddress,
knownAddressId: knownAddressId,
status: chainAddressConstants.activeStatus
});
if (insertedRec.affectedRows == 0) {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 'l_gka_cs_1',
api_error_identifier: 'something_went_wrong',
debug_options: {}
})
);
}
// Clear chain address cache.
await new ChainAddressCache({ associatedAuxChainId: oThis.associatedAuxChainId }).clear();
return responseHelper.successWithData({ chainAddressId: insertedRec.id });
}
/**
* prepare response data.
*/
prepareResponseData() {
const oThis = this;
oThis.responseData = {
[oThis.addressKind]: oThis.ethAddress
};
}
} |
JavaScript | class PackagePicker extends LitElement {
/**
* Convention we use
*/
static get tag() {
return "package-picker";
}
/**
* HTMLElement
*/
constructor() {
super();
this.searchTerm = "";
this.responseList = [];
this.list = [];
import("@lrnwebcomponents/simple-fields/lib/simple-fields-field.js");
}
/**
* LitElement render
*/
render() {
return html`
<simple-fields-field
id="urltosend"
disabled
aria-controls="urltosend"
label="URL to request"
type="url"
required
auto-validate=""
></simple-fields-field>
<simple-fields-field
id="add"
aria-controls="add"
label="Add via URL"
type="url"
auto-validate=""
@keypress="${this.keyPressed}"
></simple-fields-field>
<simple-fields-field
id="searchterm"
aria-controls="searchterm"
label="Search NPM"
type="text"
auto-validate=""
@value-changed="${this.searchTermChanged}"
></simple-fields-field>
<div class="response-list">
${this.responseList.map(
item => html`
<button
class="response-item"
@click="${this.clickPackage}"
data-name="${item.package.name}"
data-version="${item.package.version}"
>
${item.package.name} (${item.package.version})
<div>${item.package.description}</div>
<div>author: ${item.package.publisher.username}</div>
</button>
`
)}
</div>
<div class="item-list">
${this.list.map(
(item, index) => html`
<simple-fields-field
id="item-${index}"
@value-changed="${this.checkChanged}"
label="${item.name} (${item.version})"
.value="${item.value}"
type="checkbox"
></simple-fields-field>
`
)}
</div>
`;
}
keyPressed(e) {
if (e.key === "Enter") {
let list = this.list;
list.push({
name: this.shadowRoot.querySelector("#add").value,
version: "*",
value: true
});
this.list = [...list];
this.shadowRoot.querySelector("#add").field.value = "";
this.shadowRoot.querySelector("#add").value = "";
}
}
checkChanged(e) {
// remove if unchecked
if (!e.detail.value) {
let list = this.list;
let index = parseInt(e.target.id.replace("item-", ""));
if (list[index].target) {
list[index].target.removeAttribute("disabled");
}
list.splice(index, 1);
this.list = [...list];
}
}
clickPackage(e) {
var index = 0;
while (e.path[index].tagName != "BUTTON") {
index++;
}
let target = e.path[index];
target.setAttribute("disabled", "disabled");
let list = this.list;
list.push({
name: target.getAttribute("data-name"),
version: target.getAttribute("data-version"),
value: true,
target: target
});
this.list = [...list];
}
searchTermChanged(e) {
// only process if longer then 3 in the search term
if (e.detail.value && e.detail.value.length > 3) {
this.searchTerm = e.detail.value;
}
}
/**
* LitElement render styles
*/
static get styles() {
return css`
:host {
display: block;
}
:host([hidden]) {
display: none;
}
.response-item {
width: 400px;
background-color: #eeeeee;
font-size: 16px;
height: 100px;
border: 1px solid black;
color: #000000;
overflow: hidden;
}
.response-item:active,
.response-item:focus,
.response-item:hover {
background-color: #dddddd;
}
`;
}
// properties available to the custom element for data binding
static get properties() {
return {
responseList: {
type: Array
},
list: {
type: Array
},
searchTerm: {
type: String
}
};
}
updateURLToSend(list) {
var response = {};
// transform from array to object key pair
list.forEach(el => {
response[el.name] = el.version;
});
this.shadowRoot.querySelector("#urltosend").value =
__SERVICEAPI + JSON.stringify(response);
}
/**
* LitElement life cycle - property changed
*/
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName == "searchTerm") {
fetch(`${__NPMAPI}${this[propName]}`)
.then(response => {
return response.json();
})
.then(data => {
this.responseList = [...data.objects];
})
.catch(err => {
console.warn(err);
});
}
if (propName == "list") {
this.updateURLToSend(this[propName]);
}
});
}
} |
JavaScript | class MlcTranslateLocalStorageCache
{
constructor() {
}
buildKey(project, locale, group) {
return `mlc-translate[${project}][${locale}][${group}]`;
}
getGroup(project, locale, group) {
let g = localStorage.getItem(this.buildKey(project, locale, group));
if(g) {
return JSON.parse(g);
}
// not in cache
return null;
}
setGroup(project, locale, group, content) {
localStorage.setItem(this.buildKey(project, locale, group), JSON.stringify(content));
}
} |
JavaScript | class FileReader {
/**
* Creates a new file reader instance, using the given filename.
* @param {*} filename
*/
constructor(filename) {
this._filename = filename;
}
/**
* Opens the file descriptor for a file, and returns a promise that resolves
* when the file is open. After this, {@link FileReader#read} can be called
* to read file content into a buffer.
* @returns a promise
*/
open() {
return new Promise((resolve, reject) => {
fs.open(this._filename, 'r', 0o666, (err, fd) => {
if(err) {
return reject(err);
}
this._fd = fd;
resolve();
});
});
}
/**
* Closes the file descriptor associated with an open document, if there
* is one, and returns a promise that resolves when the file handle is closed.
* @returns a promise
*/
close() {
return new Promise((resolve, reject) => {
if (this._fd) {
fs.close(this._fd, (err) => {
if (err) {
return reject(err);
}
delete this._fd;
resolve();
});
} else {
resolve();
}
});
}
/**
* Reads a buffer of `length` bytes into the `buffer`. The new data will
* be added to the buffer at offset `offset`, and will be read from the
* file starting at position `position`
* @param {*} buffer
* @param {*} offset
* @param {*} length
* @param {*} position
* @returns a promise that resolves to the buffer when the data is present
*/
read(buffer, offset, length, position) {
return new Promise((resolve, reject) => {
if ( !this._fd) {
return reject(new Error("file not open"));
}
fs.read(this._fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) {
return reject(err);
}
resolve(buffer);
});
});
}
/**
* Returns the open file descriptor
* @returns the file descriptor
*/
fd() {
return this._fd;
}
/**
* Returns true if the passed instance is an instance of this class.
* @param {*} instance
* @returns true if `instance` is an instance of {@link FileReader}.
*/
static isFileReader(instance) {
return instance instanceof FileReader;
}
} |
JavaScript | class DisableModal extends React.PureComponent {
render() {
const {
type,
item,
hidden,
onClose,
onSubmit,
} = this.props;
const dialogProps = {
hidden,
onDismiss: onClose,
dialogContentProps: {
type: DialogType.normal,
title: item[ACK.TITLE],
},
};
const primaryButtonProps = {
onClick: onSubmit,
text: 'Confirm',
};
const cancelButtonProps = {
onClick: onClose,
text: 'Cancel',
};
const warningText = `WARNING: There is no going back! Are you sure you want to ${type} ${item[ACK.TITLE]}?`;
return (
<Dialog {...dialogProps}>
<Warning>{warningText}</Warning>
<DialogFooter>
<PrimaryButton {...primaryButtonProps} />
<DefaultButton {...cancelButtonProps} />
</DialogFooter>
</Dialog>
);
}
} |
JavaScript | class Select extends Component {
/*
* Initialize the component based on the provided properties.
*
* By default the Select is closed & the focused option in case the user opens
* it will be the selected option.
*/
constructor(properties) {
super(properties);
let selectedValue;
let focusedOptionValue;
if (properties.children) {
this.children = flattenReactChildren(properties.children);
this.options = filter(this.children, isOption);
}
if (has(properties, 'valueLink')) {
selectedValue = properties.valueLink.value;
focusedOptionValue = selectedValue;
} else if (has(properties, 'value')) {
selectedValue = properties.value;
focusedOptionValue = selectedValue;
} else if (has(properties, 'defaultValue')) {
selectedValue = properties.defaultValue;
focusedOptionValue = selectedValue;
} else if (!isEmpty(this.children) && !some(this.children, isPlaceholder)) {
const firstOption = first(this.options);
selectedValue = firstOption ? firstOption.props.value : void 0;
focusedOptionValue = selectedValue;
} else if (!isEmpty(this.children)) {
const firstOption = first(this.options);
focusedOptionValue = firstOption ? firstOption.props.value : void 0;
}
this.state = {
isOpen: false,
isFocused: false,
selectedValue,
focusedOptionValue,
selectedOptionWrapperProps: sanitizeSelectedOptionWrapperProps(properties),
wrapperProps: sanitizeWrapperProps(properties.wrapperProps),
menuProps: sanitizeMenuProps(properties.menuProps),
caretProps: sanitizeCaretProps(properties.caretProps),
isTouchedToToggle: false,
};
}
static displayName = 'Select';
static propTypes = {
children: validateChildrenAreOptionsAndMaximumOnePlaceholder,
value: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Date),
]),
defaultValue: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
PropTypes.number,
]),
onUpdate: PropTypes.func,
valueLink: PropTypes.shape({
value: PropTypes.string.isRequired,
requestChange: PropTypes.func.isRequired,
}),
className: PropTypes.string,
shouldPositionOptions: PropTypes.bool,
positionOptions: PropTypes.func,
style: PropTypes.object,
focusStyle: PropTypes.object,
hoverStyle: PropTypes.object,
activeStyle: PropTypes.object,
wrapperStyle: PropTypes.object,
menuStyle: PropTypes.object,
caretToOpenStyle: PropTypes.object,
caretToCloseStyle: PropTypes.object,
wrapperProps: PropTypes.object,
menuProps: PropTypes.object,
caretProps: PropTypes.object,
disabled: PropTypes.bool,
disabledStyle: PropTypes.object,
disabledHoverStyle: PropTypes.object,
disabledCaretToOpenStyle: PropTypes.object,
id: PropTypes.string,
onClick: PropTypes.func,
onTouchCancel: PropTypes.func,
onMouseDown: PropTypes.func,
onMouseUp: PropTypes.func,
onTouchEnd: PropTypes.func,
onTouchStart: PropTypes.func,
};
static childContextTypes = {
isDisabled: PropTypes.bool.isRequired,
isHoveredValue: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
PropTypes.number,
]),
};
static defaultProps = {
disabled: false,
};
getChildContext() {
return {
isDisabled: this.props.disabled,
isHoveredValue: this.state.focusedOptionValue,
};
}
/**
* Generates the style-id & inject the focus & hover style.
*/
componentWillMount() {
const id = uniqueId();
// Note: To ensure server side rendering creates the same results React's internal
// id for this element is leveraged.
this.selectedOptionWrapperId = this.props.id ? this.props.id : `belle-select-id-${id}`;
this._styleId = `style-id${id}`;
updatePseudoClassStyle(this._styleId, this.props);
if (canUseDOM) {
this.mouseUpOnDocumentCallback = this._onMouseUpOnDocument;
document.addEventListener('mouseup', this.mouseUpOnDocumentCallback);
}
}
componentWillReceiveProps(properties) {
if (properties.children) {
this.children = flattenReactChildren(properties.children);
this.options = filter(this.children, isOption);
}
const newState = {
selectedOptionWrapperProps: sanitizeSelectedOptionWrapperProps(properties),
wrapperProps: sanitizeWrapperProps(properties.wrapperProps),
menuProps: sanitizeMenuProps(properties.menuProps),
caretProps: sanitizeCaretProps(properties.caretProps),
};
if (has(properties, 'valueLink')) {
newState.selectedValue = properties.valueLink.value;
newState.focusedOptionValue = properties.valueLink.value;
} else if (has(properties, 'value')) {
newState.selectedValue = properties.value;
newState.focusedOptionValue = properties.value;
}
this.setState(newState);
removeStyle(this._styleId);
updatePseudoClassStyle(this._styleId, properties);
}
/**
* In case shouldPositionOptions is active the scrollTop position is stored
* to be applied later on. The menu is hidden to make sure it is
* not displayed beofre repositioned.
*/
componentWillUpdate(nextProperties, nextState) {
const shouldPositionOptions = has(nextProperties, 'shouldPositionOptions') ? nextProperties.shouldPositionOptions : config.shouldPositionOptions;
if (shouldPositionOptions) {
const menuNode = ReactDOM.findDOMNode(this.refs.menu);
this.cachedMenuScrollTop = menuNode.scrollTop;
if (!this.state.isOpen && nextState.isOpen) {
menuNode.style.display = 'none';
}
}
}
/**
* In case shouldPositionOptions is active when opening the menu it is
* repositioned & switched to be visible.
*/
componentDidUpdate(previousProperties, previousState) {
const shouldPositionOptions = has(this.props, 'shouldPositionOptions') ? this.props.shouldPositionOptions : config.shouldPositionOptions;
if (shouldPositionOptions && !this.props.disabled) {
const menuNode = ReactDOM.findDOMNode(this.refs.menu);
// the menu was just opened
if (!previousState.isOpen && this.state.isOpen && this.children && this.children.length > 0) {
const positionOptions = has(this.props, 'positionOptions') ? this.props.positionOptions : config.positionOptions;
positionOptions(this);
// restore the old scrollTop position
} else {
menuNode.scrollTop = this.cachedMenuScrollTop;
}
const separators = filter(this.children, isSeparator);
const childrenPresent = !isEmpty(this.options) || !isEmpty(separators);
if (!previousState.isOpen && this.state.isOpen && childrenPresent) {
const menuStyle = {
...style.menuStyle,
...this.props.menuStyle,
};
menuNode.style.display = menuStyle.display;
}
}
}
/**
* Remove a component's associated styles whenever it gets removed from the DOM.
*/
componentWillUnmount() {
removeStyle(this._styleId);
if (canUseDOM) {
document.removeEventListener('mouseup', this.mouseUpOnDocumentCallback);
}
}
/**
* Update the focusedOption based on Option the user is touching.
*
* Unfortunately updating the focusedOption only works in case the menu
* is not scrollable.
* If a setState would be triggered during a touch with the intention to
* scroll the setState would trigger a re-render & prevent the scrolling.
*/
_onTouchStartAtOption = (event, index) => {
if (event.touches.length === 1) {
this._touchStartedAt = this._getValueForIndex(index);
// save the scroll position
const menuNode = ReactDOM.findDOMNode(this.refs.menu);
if (menuNode.scrollHeight > menuNode.offsetHeight) {
this._scrollTopPosition = menuNode.scrollTop;
// Note: don't use setState in here as it would prevent the scrolling
} else {
this._scrollTopPosition = 0;
this.setState({ focusedOptionValue: this._touchStartedAt });
}
// reset interaction
this._scrollActive = false;
}
};
/**
* Identifies if the menu is scrollable.
*/
_onTouchMoveAtOption = () => {
const menuNode = ReactDOM.findDOMNode(this.refs.menu);
if (menuNode.scrollTop !== this._scrollTopPosition) {
this._scrollActive = true;
}
};
/**
* Triggers a change event after the user touched on an Option.
*/
_onTouchEndAtOption = (event, index) => {
if (this._touchStartedAt && !this._scrollActive) {
const value = this._getValueForIndex(index);
if (this._touchStartedAt === value) {
event.preventDefault();
this._triggerChange(value);
}
}
this._touchStartedAt = undefined;
};
/**
* Triggers a change event after the user touched on an Option.
*/
_onTouchCancelAtOption = () => {
this._touchStartedAt = undefined;
};
/**
* Triggers a change event after the user clicked on an Option.
*/
_onClickAtOption = (index) => {
this._triggerChange(this._getValueForIndex(index));
};
/**
* In order to inform the user which element in the document is active the
* component keeps track of when it's de-selected and depending on that
* close the menu.
*/
_onBlur = (event) => {
this.setState({
isOpen: false,
isFocused: false,
});
if (this.props.wrapperProps && this.props.wrapperProps.onBlur) {
this.props.wrapperProps.onBlur(event);
}
};
/**
* In order to inform the user which element in the document is active the
* component keeps track of when it's de-selected and depending on that
* close the menu.
*/
_onFocus = (event) => {
this.setState({
isFocused: true,
});
if (this.props.wrapperProps && this.props.wrapperProps.onFocus) {
this.props.wrapperProps.onFocus(event);
}
};
/**
* In order to inform the user which Option is active the component keeps
* track of when an option is in focus by the user and depending on that
* provide a visual indicator.
*/
_onMouseEnterAtOption = (index) => {
this.setState({
focusedOptionValue: this._getValueForIndex(index),
});
};
/**
* Initiate the toggle for the menu.
*/
_onTouchStartToggleMenu = (event) => {
if (event.touches.length === 1) {
this.setState({ isTouchedToToggle: true, isActive: true });
} else {
this.setState({ isTouchedToToggle: false });
}
if (this.props.onTouchStart) {
this.props.onTouchStart(event);
}
};
/**
* Toggle the menu after a user touched it & resets the pressed state
* for to toggle.
*/
_onTouchEndToggleMenu = (event) => {
// In case touch events are used preventDefault is applied to avoid
// triggering the click event which would cause trouble for toggling.
// In any case calling setState triggers a render. This leads to the fact
// that the click event won't be triggered anyways. Nik assumes it's due the
// element won't be in the DOM anymore.
// This also means the Select's onClick won't be triggered for touchDevices.
event.preventDefault();
/* To avoid weird behaviour we check before focusing again - no specific use-case found */
const wrapperNode = ReactDOM.findDOMNode(this.refs.wrapper);
if (document.activeElement !== wrapperNode) {
wrapperNode.focus();
}
if (this.state.isTouchedToToggle) {
if (this.state.isOpen) {
this.setState({ isOpen: false });
} else {
this.setState({ isOpen: true });
}
}
this.setState({ isTouchedToToggle: false, isActive: false });
if (this.props.onTouchEnd) {
this.props.onTouchEnd(event);
}
};
/**
* Reset the precondition to initialize a toggle of the menu.
*/
_onTouchCancelToggleMenu = (event) => {
this.setState({ isTouchedToToggle: false, isActive: false });
if (this.props.onTouchCancel) {
this.props.onTouchCancel(event);
}
};
/**
* Set isActive to true on mouse-down.
*/
_onMouseDown = (event) => {
this.setState({ isActive: true });
if (this.props.onMouseDown) {
this.props.onMouseDown(event);
}
};
/**
* Set isActive to false on mouse-up.
*/
_onMouseUp = (event) => {
this.setState({ isActive: false });
if (this.props.onMouseUp) {
this.props.onMouseUp(event);
}
};
/**
* Set isActive to false on mouse-up.
*/
_onMouseUpOnDocument = () => {
this.setState({ isActive: false });
};
/**
* Set isActive to false on is context menu opens on select's div.
*/
_onContextMenu = () => {
this.setState({ isActive: false });
};
/**
* Update focus for the options for an already open menu.
*
* The user experience of HTML's native select is good and the goal here is to
* achieve the same behaviour.
*
* - Focus on the first entry in case no options is focused on.
* - Switch focus to the next option in case one option already has focus.
*/
_onArrowDownKeyDown = () => {
if (this.state.focusedOptionValue !== void 0) {
const indexOfFocusedOption = this._getIndexOfFocusedOption();
if (hasNext(this.options, indexOfFocusedOption)) {
this.setState({
focusedOptionValue: this.options[indexOfFocusedOption + 1].props.value,
});
}
} else {
this.setState({
focusedOptionValue: first(this.options).props.value,
});
}
};
/**
* Update focus for the options for an already open menu.
*
* The user experience of HTML's native select is good and the goal here is to
* achieve the same behaviour.
*
* - Focus on the last entry in case no options is focused on.
* - Switch focus to the previous option in case one option already has focus.
*/
_onArrowUpKeyDown = () => {
if (this.state.focusedOptionValue !== void 0) {
const indexOfFocusedOption = this._getIndexOfFocusedOption();
if (hasPrevious(this.options, indexOfFocusedOption)) {
this.setState({
focusedOptionValue: this.options[indexOfFocusedOption - 1].props.value,
});
}
} else {
this.setState({
focusedOptionValue: last(this.options).props.value,
});
}
};
/**
* After the user pressed the `Enter` or `Space` key for an already open
* menu the focused option is selected.
*
* Same as _onClickAtOption this update the state & dispatches a change event.
*/
_onEnterOrSpaceKeyDown = () => {
this._triggerChange(this.state.focusedOptionValue);
};
/**
* Manages the keyboard events.
*
* In case the Select is in focus, but closed ArrowDown, ArrowUp, Enter and
* Space will result in opening the menu.
*
* In case the menu is already open each key press will have
* different effects already documented in the related methods.
*
* Pressing Escape will close the menu.
*/
_onKeyDown = (event) => {
if (!this.props.disabled) {
if (!isEmpty(this.options)) {
if (!this.state.isOpen) {
if (event.key === 'ArrowDown' ||
event.key === 'ArrowUp' ||
event.key === ' ') {
event.preventDefault();
this.setState({ isOpen: true });
}
} else {
// Updates the state to set focus on the next option
// In case no option is active it should jump to the first.
// In case it is the last it should stop there.
if (event.key === 'ArrowDown') {
event.preventDefault();
this._onArrowDownKeyDown();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
this._onArrowUpKeyDown();
} else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this._onEnterOrSpaceKeyDown();
}
}
if (event.key === 'Escape') {
event.preventDefault();
this.setState({ isOpen: false });
}
}
}
if (this.props.wrapperProps && this.props.wrapperProps.onKeyDown) {
this.props.wrapperProps.onKeyDown(event);
}
};
/**
* Toggle the menu after a user clicked on it.
*/
_onClickToggleMenu = (event) => {
if (!this.props.disabled) {
if (this.state.isOpen) {
this.setState({ isOpen: false });
} else {
this.setState({ isOpen: true });
}
}
if (this.props.onClick) {
this.props.onClick(event);
}
};
/**
* Returns the index of the entry with a certain value from the component's
* children.
*
* The index search includes only option components.
*/
_getIndexOfFocusedOption() {
return findIndex(this.options, (element) => (
element.props.value === this.state.focusedOptionValue
));
}
/**
* Returns the value of the child with a certain index.
*/
_getValueForIndex(index) {
return this.options[index].props.value;
}
/**
* After an option has been selected the menu gets closed and the
* selection processed.
*
* Depending on the component's properties the value gets updated and the
* provided change callback for onUpdate or valueLink is called.
*/
_triggerChange(value) {
if (has(this.props, 'valueLink')) {
this.props.valueLink.requestChange(value);
this.setState({
isOpen: false,
});
} else if (has(this.props, 'value')) {
this.setState({
isOpen: false,
});
} else {
this.setState({
focusedOptionValue: value,
selectedValue: value,
isOpen: false,
});
}
if (this.props.onUpdate) {
this.props.onUpdate({ value });
}
}
_renderChildren() {
let optionsIndex = 0;
return (
React.Children.map(this.children, (entry, index) => {
if (isOption(entry)) { // filter out all non-Option Components
const localOptionIndex = optionsIndex;
const isHovered = entry.props.value === this.state.focusedOptionValue;
const element = (
<SelectItem
onItemClick={ this._onClickAtOption }
onItemTouchStart={ this._onTouchStartAtOption }
onItemTouchMove={ this._onTouchMoveAtOption }
onItemTouchEnd={ this._onTouchEndAtOption }
onItemTouchCancel={ this._onTouchCancelAtOption }
onItemMouseEnter={ this._onMouseEnterAtOption }
isHovered={ isHovered }
index={localOptionIndex}
key={ index }
>
{ entry }
</SelectItem>
);
optionsIndex++;
return element;
} else if (isSeparator(entry)) {
return (
<li
key={ index }
role="presentation"
>
{ entry }
</li>
);
}
return null;
})
);
}
render() {
const defaultStyle = {
...style.style,
...this.props.style,
};
const hoverStyle = {
...defaultStyle,
...style.hoverStyle,
...this.props.hoverStyle,
};
const focusStyle = {
...defaultStyle,
...style.focusStyle,
...this.props.focusStyle,
};
const activeStyle = {
...defaultStyle,
...style.activeStyle,
...this.props.activeStyle,
};
const disabledStyle = {
...defaultStyle,
...style.disabledStyle,
...this.props.disabledStyle,
};
const disabledHoverStyle = {
...disabledStyle,
...style.disabledHoverStyle,
...this.props.disabledHoverStyle,
};
const menuStyle = {
...style.menuStyle,
...this.props.menuStyle,
};
const caretToCloseStyle = {
...style.caretToCloseStyle,
...this.props.caretToCloseStyle,
};
const caretToOpenStyle = {
...style.caretToOpenStyle,
...this.props.caretToOpenStyle,
};
const disabledCaretToOpenStyle = {
...caretToOpenStyle,
...style.disabledCaretToOpenStyle,
...this.props.disabledCaretToOpenStyle,
};
const wrapperStyle = {
...style.wrapperStyle,
...this.props.wrapperStyle,
};
let selectedOptionOrPlaceholder;
if (this.state.selectedValue !== void 0) {
const selectedEntry = find(this.children, (entry) => (
entry.props.value === this.state.selectedValue
));
if (selectedEntry) {
selectedOptionOrPlaceholder = React.cloneElement(selectedEntry, {
_isDisplayedAsSelected: true,
});
}
} else {
selectedOptionOrPlaceholder = find(this.children, isPlaceholder);
}
const separators = filter(this.children, isSeparator);
const childrenNotPresent = isEmpty(this.options) && isEmpty(separators);
const computedMenuStyle = this.props.disabled || !this.state.isOpen || childrenNotPresent ? { display: 'none' } : menuStyle;
const hasCustomTabIndex = this.props.wrapperProps && this.props.wrapperProps.tabIndex;
let tabIndex = hasCustomTabIndex ? this.props.wrapperProps.tabIndex : '0';
let selectedOptionWrapperStyle;
if (this.props.disabled) {
if (this.state.isTouchedToToggle) {
selectedOptionWrapperStyle = disabledHoverStyle;
} else {
selectedOptionWrapperStyle = disabledStyle;
}
tabIndex = -1;
} else {
if (this.state.isActive) {
selectedOptionWrapperStyle = activeStyle;
} else if (this.state.isFocused) {
selectedOptionWrapperStyle = focusStyle;
} else if (this.state.isTouchedToToggle) {
selectedOptionWrapperStyle = hoverStyle;
} else {
selectedOptionWrapperStyle = defaultStyle;
}
}
let caretStyle;
if (this.props.disabled) {
caretStyle = disabledCaretToOpenStyle;
} else if (this.state.isOpen) {
caretStyle = caretToCloseStyle;
} else {
caretStyle = caretToOpenStyle;
}
return (
<div
style={ wrapperStyle }
tabIndex={ tabIndex }
onKeyDown={ this._onKeyDown }
onBlur={ this._onBlur }
onFocus={ this._onFocus }
ref="wrapper"
{...this.state.wrapperProps}
>
<div
onClick={ this._onClickToggleMenu }
onTouchStart={ this._onTouchStartToggleMenu }
onTouchEnd={ this._onTouchEndToggleMenu }
onTouchCancel={ this._onTouchCancelToggleMenu }
onContextMenu={ this._onContextMenu }
onMouseDown = { this._onMouseDown }
onMouseUp = { this._onMouseUp }
style={ selectedOptionWrapperStyle }
className={ unionClassNames(this.props.className, this._styleId) }
ref="selectedOptionWrapper"
role="button"
aria-expanded={ this.state.isOpen }
id={ this.selectedOptionWrapperId }
{...this.state.selectedOptionWrapperProps}
>
{ selectedOptionOrPlaceholder }
<span
style={ caretStyle }
{...this.state.caretProps}
/>
</div>
<ul
style={ computedMenuStyle }
role="listbox"
aria-labelledby={ this.selectedOptionWrapperId }
ref="menu"
{...this.state.menuProps}
>
{ this._renderChildren() }
</ul>
</div>
);
}
} |
JavaScript | class Client {
constructor(sender) {
this.sender = sender;
}
/**
* Sends up to 100 lookups for validation.
* @param data may be a Lookup object, or a Batch which must contain between 1 and 100 Lookup objects
* @throws SmartyException
*/
send(data) {
const dataIsBatch = data instanceof Batch;
const dataIsLookup = data instanceof Lookup;
if (!dataIsLookup && !dataIsBatch) throw new UndefinedLookupError;
let batch;
if (dataIsLookup) {
if (data.maxCandidates == null && data.match == "enhanced")
data.maxCandidates = 5;
batch = new Batch();
batch.add(data);
} else {
batch = data;
}
return sendBatch(batch, this.sender, Candidate, keyTranslationFormat);
}
} |
JavaScript | class Client extends EventEmitter {
constructor (options) {
super()
// override default options
this.options = Object.assign({}, DEFAULTS, options)
this.ID = this.options.id || common.generateUUID()
this.channels = {}
this.RSAExchangeEncKey = null
this.commonECDHDerivedKey = null
this.EC = null
this.RSA = null
this.masqStore = this.options.masqStore
this.socket = undefined
this.myChannel = undefined
}
/**
* Init a new socketClient connection.
*
* @return {Promise} Promise resolves/rejects upon connection or errors
*/
init () {
return new Promise((resolve, reject) => {
this.socket = socketClient.create(this.options)
this.socket.on('error', (err) => {
return reject(err)
})
this.socket.on('close', (err) => {
return reject(err)
})
this.socket.on('connect', async () => {
// Also subscribe this client to its own channel by default
await this.subscribeSelf()
return resolve()
})
})
}
/**
* Send a message to the channel
* @param {string} channel - The channel name
* @param {Object} msg - The message
*/
sendMessage (channel, msg) {
// checkParameter(msg)
if (!this.channels[channel]) {
throw common.generateError(ERRORS.CHANNELNOTSUBSCRIBED)
}
this.channels[channel].socket.publish(msg)
}
/**
* This function stores the RSAExchangeEncKey in the current masq-sync
* instance to en/decrypt the exchanged of the RSA public keys during
* pairing operation/communications.
*
* @param {string} RSAExchangeEncKey - The hexadecimal string of the symmetric key (128bits)
*/
saveRSAExchangeEncKey (RSAExchangeEncKey) {
this.RSAExchangeEncKey = MasqCrypto.utils.hexStringToBuffer(RSAExchangeEncKey)
}
/**
* Send the long term public key, encrypted with an ephemeral
* symmetric key (exchanged through another channel)
* The symmetric key is given as parameter on the device which
* asks the pairing.
* The paired device must generate the symmetric key and call
* saveRSAExchangeEncKey method before sending the QRCOde or pairing link
* @param {Object} params - The public key exchange parameters
* @param {string} [params.from] - The sender channel
* @param {string} [params.publicKey] - The public key object
* @param {string} [params.symmetricKey] - The hexadecimal string of the symmetric key (128bits)
* @param {boolean} params.ack - Indicate if this is a response to a previous event
*/
async sendRSAPublicKey (params) {
if (params.symmetricKey) {
this.RSAExchangeEncKey = MasqCrypto.utils.hexStringToBuffer(params.symmetricKey)
}
if (!params.symmetricKey && !this.RSAExchangeEncKey) {
throw common.generateError(ERRORS.RSAEXCHANGEENCKEY)
}
const cipherAES = new MasqCrypto.AES({
mode: MasqCrypto.aesModes.GCM,
key: params.symmetricKey ? MasqCrypto.utils.hexStringToBuffer(params.symmetricKey) : this.RSAExchangeEncKey,
keySize: 128
})
const currentDevice = await this.masqStore.getCurrentDevice()
const encPublicKey = await cipherAES.encrypt(JSON.stringify(currentDevice.publicKeyRaw))
let msg = {
from: this.ID,
event: 'publicKey',
data: { key: encPublicKey },
to: params.to,
ack: params.ack
}
this.sendMessage(msg.to, msg)
}
/**
* Send the EC public key along with associated signature
* The EC key pair is generated and stored in this.EC
* @param {Object} params - The EC public key exchange parameters
* @param {string} params.to - The channel name
* @param {boolean} ack - Indicate if this is a response to a previous event
*/
async sendECPublicKey (params) {
if (!this.EC) {
this.EC = new MasqCrypto.EC({})
await this.EC.genECKeyPair()
}
const ECPublicKey = await this.EC.exportKeyRaw()
const currentDevice = await this.masqStore.getCurrentDevice()
if (!this.RSA) {
this.RSA = new MasqCrypto.RSA({})
this.RSA.publicKey = currentDevice.publicKey
this.RSA.privateKey = currentDevice.privateKey
}
const signature = await this.RSA.signRSA(ECPublicKey)
let msg = {
from: this.ID,
event: 'ECPublicKey',
to: params.to,
ack: params.ack,
data: {
key: MasqCrypto.utils.bufferToHexString(ECPublicKey),
signature: MasqCrypto.utils.bufferToHexString(signature)
}
}
this.sendMessage(msg.to, msg)
}
/**
* Send the group channel key, encrypted with common derived secret key (ECDH)
* @param {Object} params - The group key exchange parameters
* @param {string} params.to - The channel name
* @param {string} params.groupkey - The group key (hex string of a 128 bit AES key)
*/
async sendChannelKey (params) {
if (!this.commonECDHDerivedKey) {
throw common.generateError(ERRORS.NOCOMMONKEY)
}
const cipherAES = new MasqCrypto.AES({
mode: MasqCrypto.aesModes.GCM,
key: this.commonECDHDerivedKey,
keySize: 128
})
const encGroupKey = await cipherAES.encrypt(params.groupkey)
let msg = {
to: params.to,
event: 'channelKey',
from: this.ID,
data: { key: encGroupKey }
}
this.sendMessage(msg.to, msg)
}
readyToTransfer (channel) {
let msg = {
event: 'readyToTransfer',
from: this.ID
}
this.sendMessage(channel, msg)
}
/**
* Decryption of the received RSA public key with this.RSAExchangeEncKey.
* this.RSAExchangeEncKey is, stored by the device which generates it, i.e. the
* device which is asked to be paired, and, retrieved by another channel for the
* paired device.
* @param {Object} key - The stringified and encrypted RSA public key
* @return {Object} - The decrypted but still stringified RSA public key
*/
async decryptRSAPublicKey (key) {
const cipherAES = new MasqCrypto.AES({
mode: MasqCrypto.aesModes.GCM,
key: this.RSAExchangeEncKey,
keySize: 128
})
const decPublicKey = await cipherAES.decrypt(key)
return decPublicKey
}
async decryptGroupKey (msg) {
if (!this.commonECDHDerivedKey) {
throw common.generateError(ERRORS.NOCOMMONKEY)
}
const cipherAES = new MasqCrypto.AES({
mode: MasqCrypto.aesModes.GCM,
key: this.commonECDHDerivedKey,
keySize: 128
})
const decGroupKey = await cipherAES.decrypt(msg.data.key)
return decGroupKey
}
/**
*
* @param {string} from - The sender of the RSA public key
* @param {Object} key - The stringified RSA public key
*/
async storeRSAPublicKey (from, key) {
let device = {
name: from,
RSAPublicKey: key,
isSynched: true
}
log(device)
await this.masqStore.addPairedDevice(device)
}
storeECPublicKey (msg) {
}
/**
* Derive the common secret key - ECDH
* this.EC.privateKey must exist
* @param {string} senderECPublicKey - The hexadecimal string of of the sender EC public key
*/
async deriveSecretKey (senderECPublicKey) {
if (!this.EC.privateKey) {
throw common.generateError(ERRORS.NOECPRIVATEKEY)
}
const ECPublicKey = MasqCrypto.utils.hexStringToBuffer(senderECPublicKey)
const ECCryptoKey = await this.EC.importKeyRaw(ECPublicKey)
this.commonECDHDerivedKey = await this.EC.deriveKeyECDH(ECCryptoKey, 'aes-gcm', 128)
}
/**
*
* @param {Object} data - The message data
* @param {string} data.key - The hexadecimal string of of the sender EC public key
* @param {string} data.signature - The hexadecimal string of the signature
* @param {CryptoKey} senderRSAPublicKey - The RSA public key (jwt object)
*/
async verifyReceivedECPublicKey (data, senderRSAPublicKey) {
const ECPublicKey = MasqCrypto.utils.hexStringToBuffer(data.key)
const signature = MasqCrypto.utils.hexStringToBuffer(data.signature)
return MasqCrypto.RSA.verifRSA(senderRSAPublicKey, signature, ECPublicKey)
}
async handleGroupKey (msg) {
const groupKey = await this.decryptGroupKey(msg)
this.emit('channelKey', { key: groupKey, from: msg.from })
}
/**
* Handle the received RSA public key
* @param {ECPublicKeyMsgFormat} msg
*/
async handleRSAPublicKey (msg) {
const RSAPublicKey = await this.decryptRSAPublicKey(msg.data.key)
this.storeRSAPublicKey(msg.from, RSAPublicKey)
this.emit('RSAPublicKey', { key: RSAPublicKey, from: msg.from })
if (msg.ack) { return }
// If initial request, send the RSA public key
let params = {
to: msg.from,
ack: true
}
this.sendRSAPublicKey(params)
}
/**
* Handle the received EC public key
* @param {ECPublicKeyMsgFormat} msg
*/
async handleECPublicKey (msg) {
const devices = await this.masqStore.listDevices()
if (!devices[msg.from].RSAPublicKey) {
throw common.generateError(ERRORS.NORSAPUBLICKEYSTORED)
}
// The RSAPublicKey is stringified, we must parse the key in order to import it.
const senderRSAPublicKey = await MasqCrypto.RSA.importRSAPubKey(JSON.parse(devices[msg.from].RSAPublicKey))
if (!this.verifyReceivedECPublicKey(msg.data, senderRSAPublicKey)) {
throw common.generateError(ERRORS.VERIFICATIONFAILED)
}
if (msg.ack) {
await this.deriveSecretKey(msg.data.key)
this.emit('initECDH', { key: this.commonECDHDerivedKey, from: msg.from })
this.readyToTransfer(msg.from)
} else {
// If initial request, send EC public key
this.EC = new MasqCrypto.EC({})
await this.EC.genECKeyPair()
await this.deriveSecretKey(msg.data.key)
let params = {
to: msg.from,
ack: true
}
this.sendECPublicKey(params)
}
}
/**
* Subscribe this client to its own channel.
*
* @return {object} The WebSocket client
*/
subscribeSelf () {
this.myChannel = this.socket.subscribe(this.ID)
this.myChannel.watch(msg => {
log('****** RECEIVE ******')
log(`From ${msg.from} : ${msg}`)
log('****** RECEIVE ******')
if (msg.from === this.ID) return
if (msg.from) {
log(`New msg in my channel:`, msg.event)
if (msg.event === 'ping') {
var data = {
event: 'pong',
from: this.ID
}
if (!this.channels[msg.from]) {
// Subscribe to that user
this.channels[msg.from] = {
socket: this.socket.subscribe(msg.from)
}
}
this.channels[msg.from].socket.publish(data)
// log('Channel up with ' + msg.from)
}
if (msg.event === 'ECPublicKey') {
this.handleECPublicKey(msg)
}
if (msg.event === 'readyToTransfer') {
this.emit('initECDH', { key: this.commonECDHDerivedKey, from: msg.from })
}
if (msg.event === 'channelKey') {
this.handleGroupKey(msg)
}
if (msg.event === 'publicKey') {
this.handleRSAPublicKey(msg)
}
}
})
}
/**
* Subscribe peer to a given channel.
*
* @param {string} peer A peer (device)
* @param {boolean} batch Whether to batch requests for increased perfomance
* @return {Promise} Promise resolves/rejects upon subscription or errors
*/
subscribePeer (peer, batch = false) {
return new Promise((resolve, reject) => {
if (!peer || peer.length === 0) {
return reject(new Error('Invalid peer value'))
}
this.channels[peer] = {
socket: this.socket.subscribe(peer, {
batch: batch
})
}
this.channels[peer].socket.on('subscribe', () => {
this.channels[peer].socket.publish({
event: 'ping',
from: this.ID
})
return resolve()
})
this.channels[peer].socket.on('subscribeFail', () => {
return reject(new Error('Subscribe failed'))
})
})
}
/**
* Subscribe a list of peers to a given channel.
*
* @param {array} peers List of peers (devices)
* @return {Promise} Promise resolves/rejects upon subscription or errors
*/
subscribePeers (peers = []) {
if (!Array.isArray(peers)) {
return Promise.reject(new Error('Invalid peer list'))
}
let pending = []
peers.forEach((peer) => {
const sub = this.subscribePeer(peer, true)
sub.catch(() => {
// do something with err
})
pending.push(sub)
})
return Promise.all(pending)
}
/**
* Unsubscribe peer from a given channel.
*
* @param {string} peer A peer (device)
* @return {Promise} Promise resolves/rejects upon unsubscription or errors
*/
unsubscribePeer (peer) {
return new Promise((resolve, reject) => {
if (!peer || peer.length === 0 || this.channels[peer] === undefined) {
return reject(new Error('Invalid peer value'))
}
this.channels[peer].socket.unsubscribe()
delete this.channels[peer]
return resolve()
})
}
/**
* Deterministically elect a master device, by using the first element of a
* alphabetically ordered list of peers.
*
* @param {array} peers List of peers (devices)
* @return {string} The peer ID of the master
*/
electMaster (peers = []) {
peers.push(this.ID)
peers.sort()
return peers[0]
}
} |
JavaScript | class JSTF extends SimpleTable {
constructor(dict, dataview) {
const { p } = super(dict, dataview);
}
} |
JavaScript | class DependancyLinkedList extends LinkedList {
constructor() {
super()
}
async installDependancy(command, appBaseDirectory) {
if(!this.head) {
console.log('No dependancies added to this linked list')
} else {
let curr = this.head
while(curr) {
if(curr.value) {
let dependancy = curr.value
console.log(`..........Starting to install ${dependancy}`)
// install dependancies in order
await execPromisified(
`cd ${appBaseDirectory} && ${command} ${dependancy}`
);
chooseConsoleColorText(
colorSet.normal,
`\n Installed ${colorString(
colorSet.log,
`${dependancy}`
)} in the application.`
);
}
// move current to the next node
curr = curr.next
}
}
}
// run any operations/commands such as git init
runFinalCommands(appBaseDirectory) {
if(!this.head) {
console.log('No commands to run')
} else {
let curr = this.head
while(curr) {
if(curr.value) {
let command = curr.value
console.log(`.......Running command: ${command}`)
execPromisified(`cd ${appBaseDirectory} && ${command}`);
}
// move current to the next node
curr = curr.next
}
}
}
} |
JavaScript | class PlaybackBar extends Component {
constructor(props) {
super(props);
this.state = {
time: getPlaybackTime(),
playing: isPlaying(),
intervalID: setInterval(this.updatePropValuesFromMusic, 1000/UPDATE_FREQUENCY)
};
}
updatePropValuesFromMusic = () => {
this.setState({
time: getPlaybackTime(),
playing: isPlaying()
});
}
componentWillUnmount() {
// Cleanup on component unmount
clearInterval(this.state.intervalID);
}
render() {
return (
<Container fluid>
<Row>
<Col>
<ProgressBar min={0} now={ this.state.time } max={ this.props.duration } style={{ width: '100%', height: '100%' }} />
</Col>
<div>
{ toTimeNotation(this.state.time) } / { toTimeNotation(this.props.duration) }
</div>
</Row>
</Container>
);
}
} |
JavaScript | class CardStack extends PureComponent {
static propTypes = {
...RNCardStack.propTypes,
renderNavBar: PropTypes.func,
// Controls whether native animation driver will be used
// for screen transitions or not.
useNativeAnimations: PropTypes.bool,
// Controls whether the navigation bar should be rendered,
// together with the screen, or should it be global for the
// entire app.
inlineNavigationBar: PropTypes.bool,
style: PropTypes.shape({
cardStack: RNCardStack.propTypes.style,
card: PropTypes.any,
}),
};
static defaultProps = {
useNativeAnimations: true,
inlineNavigationBar: true,
};
static contextTypes = {
getNavBarProps: PropTypes.func,
getScene: PropTypes.func,
};
static childContextTypes = {
setNavBarProps: PropTypes.func,
getNavBarProps: PropTypes.func,
clearNavBarProps: PropTypes.func,
};
constructor(props, context) {
super(props, context);
this.renderNavBar = this.renderNavBar.bind(this);
this.renderScene = this.renderScene.bind(this);
this.getNavBarProps = this.getNavBarProps.bind(this);
this.setNavBarProps = this.setNavBarProps.bind(this);
this.clearNavBarProps = this.clearNavBarProps.bind(this);
this.refreshNavBar = this.refreshNavBar.bind(this);
/**
* A map where the key is the route key, and the value is
* the navigation bar props object for that route.
*/
this.navBarProps = {};
}
getChildContext() {
return {
getNavBarProps: this.getNavBarProps,
setNavBarProps: this.setNavBarProps,
clearNavBarProps: this.clearNavBarProps,
};
}
setNavBarProps(route = {}, props) {
const currentProps = this.getNavBarProps(route);
// Merge the props, so that we may set them partially
// in cases when there are multiple screens in the hierarchy.
this.navBarProps[route.key] = {
...currentProps,
...props,
};
this.refreshNavBar();
}
getNavBarProps(route = {}) {
const { getNavBarProps, getScene } = this.context;
const { useNativeAnimations, inlineNavigationBar } = this.props;
let props = this.navBarProps[route.key] || {};
if (getNavBarProps && getScene) {
const scene = getScene();
const parentProps = getNavBarProps(scene.route);
if (parentProps.child) {
delete parentProps.child;
delete parentProps.driver;
props = _.merge({}, props, parentProps);
delete props.child;
}
}
return {
...props,
useNativeAnimations,
inline: inlineNavigationBar,
};
}
clearNavBarProps(route = {}) {
delete this.navBarProps[route.key];
}
refreshNavBar() {
if (this.props.useNativeAnimations) {
requestAnimationFrame(() => this.forceUpdate());
} else {
InteractionManager.runAfterInteractions(() => this.forceUpdate());
}
}
renderNavBar(props) {
const { scene } = props;
const nextProps = this.getNavBarProps(scene.route);
const navBarProps = {
...props,
...nextProps,
};
// Expose the animation driver to child components of the
// navigation bar, so that we can animate them without
// explicitly passing the driver to each component.
return (
<ScrollView.DriverProvider driver={navBarProps.driver}>
{this.props.renderNavBar(navBarProps)}
</ScrollView.DriverProvider>
);
}
renderScene(props) {
const { inlineNavigationBar, style = {} } = this.props;
// DriverProvider provides the animation driver from the
// primary scroll component of the screen to all other
// screen children. The scene provider provides the current
// navigation scene to child components through the context.
const scene = (
<ScrollView.DriverProvider>
<SceneProvider scene={props.scene}>
{this.props.renderScene(props)}
</SceneProvider>
</ScrollView.DriverProvider>
);
return inlineNavigationBar ? (
<View style={style.sceneContainer}>
{scene}
{this.renderNavBar(props)}
</View>
) : scene;
}
render() {
const {
useNativeAnimations,
inlineNavigationBar,
style = {},
} = this.props;
// NOTE: explicitly providing enableGestures in props may
// override the value of the useNativeAnimations prop, because
// the native animations are currently controlled through the
// enableGestures prop in RN CardStack.
return (
<RNCardStack
enableGestures={!useNativeAnimations}
{...this.props}
style={style.cardStack}
cardStyle={style.card}
renderHeader={inlineNavigationBar ? null : this.renderNavBar}
renderScene={this.renderScene}
interpolateCardStyle={style.interpolateCardStyle}
/>
);
}
} |
JavaScript | class Camera extends DisplayObject {
constructor() {
super();
Black.camera = this;
}
get worldTransformation() {
let wt = super.worldTransformation.clone();
wt.prepend(this.stage.worldTransformationInverted);
return wt;
}
} |
JavaScript | class Listicle extends Component {
/*
shouldComponentUpdate(nextProps, nextState) {
return this.props.things != nextProps.things ||
this.props.selected != nextProps.selected ||
this.props.highlighted != nextProps.highlighted;
}
*/
render() {
const {passthrough, width, height,
isHighlighted, hover, endHover, click,
valFunc=d=>d,
labelFunc=d=>d.toString(),
sortBy, controls=[],
itemClass=()=>''} = this.props;
const things = this.props.things.sort((a,b)=>(sortBy||valFunc)(b)-(sortBy||valFunc)(a));
// not sure what's going wrong with sorting... going without for now
//const things = _.sortBy(this.props.things, sortBy||valFunc);
var ext = d3.extent(things.map((thing,i)=>valFunc(thing,i)));
var dumbExt = [0, ext[1]];
var xScale = d3.scale.linear()
.domain(dumbExt)
.range([0, width]);
var bars = things.map((thing, i) =>
<Item
passthrough={passthrough}
thing={thing}
valFunc={valFunc}
labelFunc={labelFunc}
controls={controls}
itemClass={itemClass}
isHighlighted={isHighlighted}
click={click}
hover={hover}
endHover={endHover}
chartWidth={width}
xScale={xScale}
i={i}
key={i}
/>
);
return <div className="listicle">
{bars}
</div>;
}
} |
JavaScript | class Pt extends exports.PtBaseArray {
/**
* Create a Pt. If no parameter is provided, this will instantiate a Pt with 2 dimensions [0, 0].
*
* Note that `new Pt(3)` will only instantiate Pt with length of 3 (ie, same as `new Float32Array(3)` ). If you need a Pt with 1 dimension of value 3, use `new Pt([3])`.
* @example `new Pt()`, `new Pt(1,2,3,4,5)`, `new Pt([1,2])`, `new Pt({x:0, y:1})`, `new Pt(pt)`
* @param args a list of numeric parameters, an array of numbers, or an object with {x,y,z,w} properties
*/
constructor(...args) {
if (args.length === 1 && typeof args[0] == "number") {
super(args[0]); // init with the TypedArray's length. Needed this in order to make ".map", ".slice" etc work.
}
else {
super((args.length > 0) ? Util_1.Util.getArgs(args) : [0, 0]);
}
}
static make(dimensions, defaultValue = 0, randomize = false) {
let p = new exports.PtBaseArray(dimensions);
if (defaultValue)
p.fill(defaultValue);
if (randomize) {
for (let i = 0, len = p.length; i < len; i++) {
p[i] = p[i] * Math.random();
}
}
return new Pt(p);
}
get id() { return this._id; }
set id(s) { this._id = s; }
get x() { return this[0]; }
get y() { return this[1]; }
get z() { return this[2]; }
get w() { return this[3]; }
set x(n) { this[0] = n; }
set y(n) { this[1] = n; }
set z(n) { this[2] = n; }
set w(n) { this[3] = n; }
/**
* Clone this Pt
*/
clone() {
return new Pt(this);
}
/**
* Check if another Pt is equal to this Pt, within a threshold
* @param p another Pt to compare with
* @param threshold a threshold value within which the two Pts are considered equal. Default is 0.000001.
*/
equals(p, threshold = 0.000001) {
for (let i = 0, len = this.length; i < len; i++) {
if (Math.abs(this[i] - p[i]) > threshold)
return false;
}
return true;
}
/**
* Update the values of this Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
to(...args) {
let p = Util_1.Util.getArgs(args);
for (let i = 0, len = Math.min(this.length, p.length); i < len; i++) {
this[i] = p[i];
}
return this;
}
/**
* Like `to()` but returns a new Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$to(...args) {
return this.clone().to(...args);
}
/**
* Update the values of this Pt to point at a specific angle
* @param radian target angle in radian
* @param magnitude Optional magnitude if known. If not provided, it'll calculate and use this Pt's magnitude.
* @param anchorFromPt If `true`, translate to new position from current position. Default is `false` which update the position from origin (0,0);
*/
toAngle(radian, magnitude, anchorFromPt = false) {
let m = (magnitude != undefined) ? magnitude : this.magnitude();
let change = [Math.cos(radian) * m, Math.sin(radian) * m];
return (anchorFromPt) ? this.add(change) : this.to(change);
}
/**
* Create an operation using this Pt, passing this Pt into a custom function's first parameter. See the [Op guide](../../guide/Op-0400.html) for details.
* For example: `let myOp = pt.op( fn ); let result = myOp( [1,2,3] );`
* @param fn any function that takes a Pt as its first parameter
* @returns a resulting function that takes other parameters required in `fn`
*/
op(fn) {
let self = this;
return (...params) => {
return fn(self, ...params);
};
}
/**
* This combines a series of operations into an array. See `op()` for details.
* For example: `let myOps = pt.ops([fn1, fn2, fn3]); let results = myOps.map( (op) => op([1,2,3]) );`
* @param fns an array of functions for `op`
* @returns an array of resulting functions
*/
ops(fns) {
let _ops = [];
for (let i = 0, len = fns.length; i < len; i++) {
_ops.push(this.op(fns[i]));
}
return _ops;
}
/**
* Take specific dimensional values from this Pt and create a new Pt
* @param axis a string such as "xy" (use Const.xy) or an array to specify index for two dimensions
*/
$take(axis) {
let p = [];
for (let i = 0, len = axis.length; i < len; i++) {
p.push(this[axis[i]] || 0);
}
return new Pt(p);
}
/**
* Concatenate this Pt with addition dimensional values and return as a new Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$concat(...args) {
return new Pt(this.toArray().concat(Util_1.Util.getArgs(args)));
}
/**
* Add scalar or vector values to this Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
add(...args) {
(args.length === 1 && typeof args[0] == "number") ? LinearAlgebra_1.Vec.add(this, args[0]) : LinearAlgebra_1.Vec.add(this, Util_1.Util.getArgs(args));
return this;
}
/**
* Like `add`, but returns result as a new Pt
*/
$add(...args) { return this.clone().add(...args); }
/**
* Subtract scalar or vector values from this Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
subtract(...args) {
(args.length === 1 && typeof args[0] == "number") ? LinearAlgebra_1.Vec.subtract(this, args[0]) : LinearAlgebra_1.Vec.subtract(this, Util_1.Util.getArgs(args));
return this;
}
/**
* Like `subtract`, but returns result as a new Pt
*/
$subtract(...args) { return this.clone().subtract(...args); }
/**
* Multiply scalar or vector values (as element-wise) with this Pt.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
multiply(...args) {
(args.length === 1 && typeof args[0] == "number") ? LinearAlgebra_1.Vec.multiply(this, args[0]) : LinearAlgebra_1.Vec.multiply(this, Util_1.Util.getArgs(args));
return this;
}
/**
* Like `multiply`, but returns result as a new Pt
*/
$multiply(...args) { return this.clone().multiply(...args); }
/**
* Divide this Pt over scalar or vector values (as element-wise)
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
divide(...args) {
(args.length === 1 && typeof args[0] == "number") ? LinearAlgebra_1.Vec.divide(this, args[0]) : LinearAlgebra_1.Vec.divide(this, Util_1.Util.getArgs(args));
return this;
}
/**
* Like `divide`, but returns result as a new Pt
*/
$divide(...args) { return this.clone().divide(...args); }
/**
* Get the sqaured distance (magnitude) of this Pt from origin
*/
magnitudeSq() { return LinearAlgebra_1.Vec.dot(this, this); }
/**
* Get the distance (magnitude) of this Pt from origin
*/
magnitude() { return LinearAlgebra_1.Vec.magnitude(this); }
/**
* Convert to a unit vector, which is a normalized vector whose magnitude equals 1.
* @param magnitude Optional: if the magnitude is known, pass it as a parameter to avoid duplicate calculation.
*/
unit(magnitude = undefined) {
LinearAlgebra_1.Vec.unit(this, magnitude);
return this;
}
/**
* Get a unit vector from this Pt
*/
$unit(magnitude = undefined) { return this.clone().unit(magnitude); }
/**
* Dot product of this Pt and another Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
dot(...args) { return LinearAlgebra_1.Vec.dot(this, Util_1.Util.getArgs(args)); }
/**
* 2D Cross product of this Pt and another Pt. Return results as a new Pt.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
cross2D(...args) { return LinearAlgebra_1.Vec.cross2D(this, Util_1.Util.getArgs(args)); }
/**
* 3D Cross product of this Pt and another Pt. Return results as a new Pt.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$cross(...args) { return LinearAlgebra_1.Vec.cross(this, Util_1.Util.getArgs(args)); }
/**
* Calculate vector projection of this Pt on another Pt. Returns result as a new Pt.
* @param p a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$project(p) {
let m = p.magnitude();
let a = this.$unit();
let b = p.$divide(m);
let dot = a.dot(b);
return a.multiply(m * dot);
}
/**
* Absolute values for all values in this pt
*/
abs() {
LinearAlgebra_1.Vec.abs(this);
return this;
}
/**
* Get a new Pt with absolute values of this Pt
*/
$abs() {
return this.clone().abs();
}
/**
* Floor values for all values in this pt
*/
floor() {
LinearAlgebra_1.Vec.floor(this);
return this;
}
/**
* Get a new Pt with floor values of this Pt
*/
$floor() {
return this.clone().floor();
}
/**
* Ceil values for all values in this pt
*/
ceil() {
LinearAlgebra_1.Vec.ceil(this);
return this;
}
/**
* Get a new Pt with ceil values of this Pt
*/
$ceil() {
return this.clone().ceil();
}
/**
* Round values for all values in this pt
*/
round() {
LinearAlgebra_1.Vec.round(this);
return this;
}
/**
* Get a new Pt with round values of this Pt
*/
$round() {
return this.clone().round();
}
/**
* Find the minimum value across all dimensions in this Pt
* @returns an object with `value` and `index` which returns the minimum value and its dimensional index
*/
minValue() {
return LinearAlgebra_1.Vec.min(this);
}
/**
* Find the maximum value across all dimensions in this Pt
* @returns an object with `value` and `index` which returns the maximum value and its dimensional index
*/
maxValue() {
return LinearAlgebra_1.Vec.max(this);
}
/**
* Get a new Pt that has the minimum dimensional values of this Pt and another Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$min(...args) {
let p = Util_1.Util.getArgs(args);
let m = this.clone();
for (let i = 0, len = Math.min(this.length, p.length); i < len; i++) {
m[i] = Math.min(this[i], p[i]);
}
return m;
}
/**
* Get a new Pt that has the maximum dimensional values of this Pt and another Pt
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
$max(...args) {
let p = Util_1.Util.getArgs(args);
let m = this.clone();
for (let i = 0, len = Math.min(this.length, p.length); i < len; i++) {
m[i] = Math.max(this[i], p[i]);
}
return m;
}
/**
* Get angle of this vector from origin
* @param axis a string such as "xy" (use Const.xy) or an array to specify index for two dimensions
*/
angle(axis = Util_1.Const.xy) {
return Math.atan2(this[axis[1]], this[axis[0]]);
}
/**
* Get the angle between this and another Pt
* @param p the other Pt
* @param axis a string such as "xy" (use Const.xy) or an array to specify index for two dimensions
*/
angleBetween(p, axis = Util_1.Const.xy) {
return Num_1.Geom.boundRadian(this.angle(axis)) - Num_1.Geom.boundRadian(p.angle(axis));
}
/**
* Scale this Pt from origin or from an anchor point
* @param scale scale ratio
* @param anchor optional anchor point to scale from
*/
scale(scale, anchor) {
Num_1.Geom.scale(this, scale, anchor || Pt.make(this.length, 0));
return this;
}
/**
* Rotate this Pt from origin or from an anchor point in 2D
* @param angle rotate angle
* @param anchor optional anchor point to scale from
* @param axis optional string such as "yz" to specify a 2D plane
*/
rotate2D(angle, anchor, axis) {
Num_1.Geom.rotate2D(this, angle, anchor || Pt.make(this.length, 0), axis);
return this;
}
/**
* Shear this Pt from origin or from an anchor point in 2D
* @param shear shearing value which can be a number or an array of 2 numbers
* @param anchor optional anchor point to scale from
* @param axis optional string such as "yz" to specify a 2D plane
*/
shear2D(scale, anchor, axis) {
Num_1.Geom.shear2D(this, scale, anchor || Pt.make(this.length, 0), axis);
return this;
}
/**
* Reflect this Pt along a 2D line
* @param line a Group of 2 Pts that defines a line for reflection
* @param axis optional axis such as "yz" to define a 2D plane of reflection
*/
reflect2D(line, axis) {
Num_1.Geom.reflect2D(this, line, axis);
return this;
}
/**
* A string representation of this Pt: "Pt(1, 2, 3)"
*/
toString() {
return `Pt(${this.join(", ")})`;
}
/**
* Convert this Pt to a javascript Array
*/
toArray() {
return [].slice.call(this);
}
} |
JavaScript | class Group extends Array {
constructor(...args) {
super(...args);
}
get id() { return this._id; }
set id(s) { this._id = s; }
/** The first Pt in this group */
get p1() { return this[0]; }
/** The second Pt in this group */
get p2() { return this[1]; }
/** The third Pt in this group */
get p3() { return this[2]; }
/** The forth Pt in this group */
get p4() { return this[3]; }
/** The last Pt in this group */
get q1() { return this[this.length - 1]; }
/** The second-last Pt in this group */
get q2() { return this[this.length - 2]; }
/** The third-last Pt in this group */
get q3() { return this[this.length - 3]; }
/** The forth-last Pt in this group */
get q4() { return this[this.length - 4]; }
/**
* Depp clone this group and its Pts
*/
clone() {
let group = new Group();
for (let i = 0, len = this.length; i < len; i++) {
group.push(this[i].clone());
}
return group;
}
/**
* Convert an array of numeric arrays into a Group of Pts
* @param list an array of numeric arrays
* @example `Group.fromArray( [[1,2], [3,4], [5,6]] )`
*/
static fromArray(list) {
let g = new Group();
for (let i = 0, len = list.length; i < len; i++) {
let p = (list[i] instanceof Pt) ? list[i] : new Pt(list[i]);
g.push(p);
}
return g;
}
/**
* Convert an array of Pts into a Group.
* @param list an array of Pts
*/
static fromPtArray(list) {
return Group.from(list);
}
/**
* Split this Group into an array of sub-groups
* @param chunkSize number of items per sub-group
* @param stride forward-steps after each sub-group
* @param loopBack if `true`, always go through the array till the end and loop back to the beginning to complete the segments if needed
*/
split(chunkSize, stride, loopBack = false) {
let sp = Util_1.Util.split(this, chunkSize, stride, loopBack);
return sp;
}
/**
* Insert a Pt into this group
* @param pts Another group of Pts
* @param index the index position to insert into
*/
insert(pts, index = 0) {
Group.prototype.splice.apply(this, [index, 0, ...pts]);
return this;
}
/**
* Like Array's splice function, with support for negative index and a friendlier name.
* @param index start index, which can be negative (where -1 is at index 0, -2 at index 1, etc)
* @param count number of items to remove
* @returns The items that are removed.
*/
remove(index = 0, count = 1) {
let param = (index < 0) ? [index * -1 - 1, count] : [index, count];
return Group.prototype.splice.apply(this, param);
}
/**
* Split this group into an array of sub-group segments
* @param pts_per_segment number of Pts in each segment
* @param stride forward-step to take
* @param loopBack if `true`, always go through the array till the end and loop back to the beginning to complete the segments if needed
*/
segments(pts_per_segment = 2, stride = 1, loopBack = false) {
return this.split(pts_per_segment, stride, loopBack);
}
/**
* Get all the line segments (ie, edges in a graph) of this group
*/
lines() { return this.segments(2, 1); }
/**
* Find the centroid of this group's Pts, which is the average middle point.
*/
centroid() {
return Num_1.Geom.centroid(this);
}
/**
* Find the rectangular bounding box of this group's Pts.
* @returns a Group of 2 Pts representing the top-left and bottom-right of the rectangle
*/
boundingBox() {
return Num_1.Geom.boundingBox(this);
}
/**
* Anchor all the Pts in this Group using a target Pt as origin. (ie, subtract all Pt with the target anchor to get a relative position). All the Pts' values will be updated.
* @param ptOrIndex a Pt, or a numeric index to target a specific Pt in this Group
*/
anchorTo(ptOrIndex = 0) { Num_1.Geom.anchor(this, ptOrIndex, "to"); }
/**
* Anchor all the Pts in this Group by its absolute position from a target Pt. (ie, add all Pt with the target anchor to get an absolute position). All the Pts' values will be updated.
* @param ptOrIndex a Pt, or a numeric index to target a specific Pt in this Group
*/
anchorFrom(ptOrIndex = 0) { Num_1.Geom.anchor(this, ptOrIndex, "from"); }
/**
* Create an operation using this Group, passing this Group into a custom function's first parameter. See the [Op guide](../../guide/Op-0400.html) for details.
* For example: `let myOp = group.op( fn ); let result = myOp( [1,2,3] );`
* @param fn any function that takes a Group as its first parameter
* @returns a resulting function that takes other parameters required in `fn`
*/
op(fn) {
let self = this;
return (...params) => {
return fn(self, ...params);
};
}
/**
* This combines a series of operations into an array. See `op()` for details.
* For example: `let myOps = pt.ops([fn1, fn2, fn3]); let results = myOps.map( (op) => op([1,2,3]) );`
* @param fns an array of functions for `op`
* @returns an array of resulting functions
*/
ops(fns) {
let _ops = [];
for (let i = 0, len = fns.length; i < len; i++) {
_ops.push(this.op(fns[i]));
}
return _ops;
}
/**
* Get an interpolated point on the line segments defined by this Group
* @param t a value between 0 to 1 usually
*/
interpolate(t) {
t = Num_1.Num.clamp(t, 0, 1);
let chunk = this.length - 1;
let tc = 1 / (this.length - 1);
let idx = Math.floor(t / tc);
return Num_1.Geom.interpolate(this[idx], this[Math.min(this.length - 1, idx + 1)], (t - idx * tc) * chunk);
}
/**
* Move every Pt's position by a specific amount. Same as `add`.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
moveBy(...args) {
return this.add(...args);
}
/**
* Move the first Pt in this group to a specific position, and move all the other Pts correspondingly
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
moveTo(...args) {
let d = new Pt(Util_1.Util.getArgs(args)).subtract(this[0]);
this.moveBy(d);
return this;
}
/**
* Scale this group's Pts from an anchor point. Default anchor point is the first Pt in this group.
* @param scale scale ratio
* @param anchor optional anchor point to scale from
*/
scale(scale, anchor) {
for (let i = 0, len = this.length; i < len; i++) {
Num_1.Geom.scale(this[i], scale, anchor || this[0]);
}
return this;
}
/**
* Rotate this group's Pt from an anchor point in 2D. Default anchor point is the first Pt in this group.
* @param angle rotate angle
* @param anchor optional anchor point to scale from
* @param axis optional string such as "yz" to specify a 2D plane
*/
rotate2D(angle, anchor, axis) {
for (let i = 0, len = this.length; i < len; i++) {
Num_1.Geom.rotate2D(this[i], angle, anchor || this[0], axis);
}
return this;
}
/**
* Shear this group's Pt from an anchor point in 2D. Default anchor point is the first Pt in this group.
* @param shear shearing value which can be a number or an array of 2 numbers
* @param anchor optional anchor point to scale from
* @param axis optional string such as "yz" to specify a 2D plane
*/
shear2D(scale, anchor, axis) {
for (let i = 0, len = this.length; i < len; i++) {
Num_1.Geom.shear2D(this[i], scale, anchor || this[0], axis);
}
return this;
}
/**
* Reflect this group's Pts along a 2D line. Default anchor point is the first Pt in this group.
* @param line a Group of 2 Pts that defines a line for reflection
* @param axis optional axis such as "yz" to define a 2D plane of reflection
*/
reflect2D(line, axis) {
for (let i = 0, len = this.length; i < len; i++) {
Num_1.Geom.reflect2D(this[i], line, axis);
}
return this;
}
/**
* Sort this group's Pts by values in a specific dimension
* @param dim dimensional index
* @param desc if true, sort descending. Default is false (ascending)
*/
sortByDimension(dim, desc = false) {
return this.sort((a, b) => (desc) ? b[dim] - a[dim] : a[dim] - b[dim]);
}
/**
* Update each Pt in this Group with a Pt function
* @param ptFn string name of an existing Pt function. Note that the function must return Pt.
* @param args arguments for the function specified in ptFn
*/
forEachPt(ptFn, ...args) {
if (!this[0][ptFn]) {
Util_1.Util.warn(`${ptFn} is not a function of Pt`);
return this;
}
for (let i = 0, len = this.length; i < len; i++) {
this[i] = this[i][ptFn](...args);
}
return this;
}
/**
* Add scalar or vector values to this group's Pts.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
add(...args) {
return this.forEachPt("add", ...args);
}
/**
* Subtract scalar or vector values from this group's Pts.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
subtract(...args) {
return this.forEachPt("subtract", ...args);
}
/**
* Multiply scalar or vector values (as element-wise) with this group's Pts.
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
multiply(...args) {
return this.forEachPt("multiply", ...args);
}
/**
* Divide this group's Pts over scalar or vector values (as element-wise)
* @param args a list of numbers, an array of number, or an object with {x,y,z,w} properties
*/
divide(...args) {
return this.forEachPt("divide", ...args);
}
/**
* Apply this group as a matrix and calculate matrix addition
* @param g a scalar number, an array of numeric arrays, or a group of Pt
* @returns a new Group
*/
$matrixAdd(g) {
return LinearAlgebra_1.Mat.add(this, g);
}
/**
* Apply this group as a matrix and calculate matrix multiplication
* @param g a scalar number, an array of numeric arrays, or a Group of K Pts, each with N dimensions (K-rows, N-columns) -- or if transposed is true, then N Pts with K dimensions
* @param transposed (Only applicable if it's not elementwise multiplication) If true, then a and b's columns should match (ie, each Pt should have the same dimensions). Default is `false`.
* @param elementwise if true, then the multiplication is done element-wise. Default is `false`.
* @returns If not elementwise, this will return a new Group with M Pt, each with N dimensions (M-rows, N-columns).
*/
$matrixMultiply(g, transposed = false, elementwise = false) {
return LinearAlgebra_1.Mat.multiply(this, g, transposed, elementwise);
}
/**
* Zip one slice of an array of Pt. Imagine the Pts are organized in rows, then this function will take the values in a specific column.
* @param idx index to zip at
* @param defaultValue a default value to fill if index out of bound. If not provided, it will throw an error instead.
*/
zipSlice(index, defaultValue = false) {
return LinearAlgebra_1.Mat.zipSlice(this, index, defaultValue);
}
/**
* Zip a group of Pt. eg, [[1,2],[3,4],[5,6]] => [[1,3,5],[2,4,6]]
* @param defaultValue a default value to fill if index out of bound. If not provided, it will throw an error instead.
* @param useLongest If true, find the longest list of values in a Pt and use its length for zipping. Default is false, which uses the first item's length for zipping.
*/
$zip(defaultValue = undefined, useLongest = false) {
return LinearAlgebra_1.Mat.zip(this, defaultValue, useLongest);
}
/**
* Get a string representation of this group
*/
toString() {
return "Group[ " + this.reduce((p, c) => p + c.toString() + " ", "") + " ]";
}
} |
JavaScript | class FundNotationScreenerSearchDataFund {
/**
* Constructs a new <code>FundNotationScreenerSearchDataFund</code>.
* Parameters related to funds.
* @alias module:model/FundNotationScreenerSearchDataFund
*/
constructor() {
FundNotationScreenerSearchDataFund.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>FundNotationScreenerSearchDataFund</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/FundNotationScreenerSearchDataFund} obj Optional instance to populate.
* @return {module:model/FundNotationScreenerSearchDataFund} The populated <code>FundNotationScreenerSearchDataFund</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new FundNotationScreenerSearchDataFund();
if (data.hasOwnProperty('etf')) {
obj['etf'] = ApiClient.convertToType(data['etf'], 'String');
}
if (data.hasOwnProperty('currency')) {
obj['currency'] = FundNotationScreenerSearchDataFundCurrency.constructFromObject(data['currency']);
}
if (data.hasOwnProperty('domicile')) {
obj['domicile'] = FundNotationScreenerSearchDataFundDomicile.constructFromObject(data['domicile']);
}
if (data.hasOwnProperty('holdingType')) {
obj['holdingType'] = FundNotationScreenerSearchDataFundHoldingType.constructFromObject(data['holdingType']);
}
if (data.hasOwnProperty('countryDevelopment')) {
obj['countryDevelopment'] = FundNotationScreenerSearchDataFundCountryDevelopment.constructFromObject(data['countryDevelopment']);
}
if (data.hasOwnProperty('regionalExposure')) {
obj['regionalExposure'] = FundNotationScreenerSearchDataFundRegionalExposure.constructFromObject(data['regionalExposure']);
}
if (data.hasOwnProperty('strategy')) {
obj['strategy'] = FundNotationScreenerSearchDataFundStrategy.constructFromObject(data['strategy']);
}
if (data.hasOwnProperty('industry')) {
obj['industry'] = FundNotationScreenerSearchDataFundIndustry.constructFromObject(data['industry']);
}
if (data.hasOwnProperty('minimumSrri')) {
obj['minimumSrri'] = FundNotationScreenerSearchDataFundMinimumSrri.constructFromObject(data['minimumSrri']);
}
if (data.hasOwnProperty('issuer')) {
obj['issuer'] = FundNotationScreenerSearchDataFundIssuer.constructFromObject(data['issuer']);
}
if (data.hasOwnProperty('assetsUnderManagement')) {
obj['assetsUnderManagement'] = FundNotationScreenerSearchDataFundAssetsUnderManagement.constructFromObject(data['assetsUnderManagement']);
}
if (data.hasOwnProperty('compliance')) {
obj['compliance'] = FundNotationScreenerSearchDataFundCompliance.constructFromObject(data['compliance']);
}
}
return obj;
}
} |
JavaScript | class StringField extends Field {
getWidget() {
return Mutt.config.getWidget('text')
}
} |
JavaScript | class DataNode {
constructor(value) {
this.value = value;
this.pending = NOTPENDING;
this.log = null;
}
current() {
if (Listener !== null) {
if (this.log === null) this.log = createLog();
logRead(this.log);
}
return this.value;
}
next(value) {
if (RunningClock !== null) {
if (this.pending !== NOTPENDING) {
// value has already been set once, check for conflicts
if (value !== this.pending) {
throw new Error("conflicting changes: " + value + " !== " + this.pending);
}
} else {
// add to list of changes
this.pending = value;
RootClock.changes.add(this);
}
} else {
// not batching, respond to change now
if (this.log !== null) {
this.pending = value;
RootClock.changes.add(this);
event();
} else {
this.value = value;
}
}
return value;
}
} |
JavaScript | class OrganizationResponseManagement extends models['OrganizationResponseInternal'] {
/**
* Create a OrganizationResponseManagement.
* @member {string} [email] The organization email, if the app was synced
* from HockeyApp
*/
constructor() {
super();
}
/**
* Defines the metadata of OrganizationResponseManagement
*
* @returns {object} metadata of OrganizationResponseManagement
*
*/
mapper() {
return {
required: false,
serializedName: 'OrganizationResponseManagement',
type: {
name: 'Composite',
className: 'OrganizationResponseManagement',
modelProperties: {
id: {
required: true,
serializedName: 'id',
type: {
name: 'String'
}
},
displayName: {
required: true,
serializedName: 'display_name',
type: {
name: 'String'
}
},
name: {
required: true,
serializedName: 'name',
type: {
name: 'String'
}
},
avatarUrl: {
required: false,
serializedName: 'avatar_url',
type: {
name: 'String'
}
},
origin: {
required: true,
serializedName: 'origin',
type: {
name: 'String'
}
},
createdAt: {
required: true,
serializedName: 'created_at',
type: {
name: 'String'
}
},
updatedAt: {
required: true,
serializedName: 'updated_at',
type: {
name: 'String'
}
},
featureFlags: {
required: false,
serializedName: 'feature_flags',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
email: {
required: false,
serializedName: 'email',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class CanvasListManager {
constructor() {
this.list = new DataList();
}
create(gameParent, width, height) {
let canvasContainer = this.firstFree();
let canvas;
// no parent found
if (canvasContainer === null) {
canvasContainer = {
parent: gameParent,
canvas: document.createElement('canvas')
};
this.list.push(canvasContainer);
canvas = canvasContainer.canvas;
} else {
canvasContainer.parent = gameParent;
canvas = canvasContainer.canvas;
}
canvas.width = width;
canvas.height = height;
return canvas;
}
filter(gameParent) { // functional programming
var list = scintilla.CanvasList.list;
return list.parent === gameParent;
}
firstFree() {
this.list.each((canvas) => {
if (!canvas.parent) {
return canvas;
}
});
return null;
}
remove(parent) {
var list = this.list;
for (var i = 0; i < list.length; i++)
{
if (list[i].parent === parent)
{
list[i].parent = null;
}
}
}
clear() {
/// TODO
}
} |
JavaScript | class MuteToggleButton extends Component {
static propTypes = {
onMuteChange: PropTypes.func.isRequired,
isMuted: PropTypes.bool,
isEnabled: PropTypes.bool,
className: PropTypes.string,
extraClasses: PropTypes.string,
style: PropTypes.object,
}
static defaultProps = {
isMuted: false,
isEnabled: true,
className: 'MuteToggleButton',
extraClasses: '',
style: {},
}
@autobind
handleMuteChange (isMuted) {
if (this.props.isEnabled) {
this.props.onMuteChange(isMuted)
}
}
render () {
const {
isMuted, isEnabled,
className, extraClasses, childClasses,
style, childrenStyles,
} = this.props
return (
<div
className={classNames(className, extraClasses, { isMuted, isEnabled })}
style={style}
>
{isMuted
? (
<SoundOffButton
className={childClasses.SoundOffButton}
style={childrenStyles.SoundOffButton}
isEnabled={isEnabled}
onClick={() => this.handleMuteChange(false)}
/>
)
: (
<SoundOnButton
className={childClasses.SoundOnButton}
style={childrenStyles.SoundOnButton}
isEnabled={isEnabled}
onClick={() => this.handleMuteChange(true)}
/>
)
}
</div>
)
}
} |
JavaScript | class StringLength extends String {
constructor(s) {
super(s);
}
concat() {
return new StringLength(super.concat.apply(this, arguments));
}
valueOf() {
return this.length;
}
} |
JavaScript | class CalculatorWorker {
constructor() {
/**@type{Worker|null} */
this.worker = null;
}
compute(
/** @type{string} */
input,
/** @type{function} */
callback
) {
if (this.worker === null) {
this.worker = new Worker("/calculator_html/web_assembly/calculator_web_assembly_all_in_one.js");
}
this.worker.postMessage(["compute", input]);
this.worker.onmessage = (message) => {
this.receiveResult(message.data, callback);
}
}
receiveResult(
/**@type {string} */
data,
/** @type{function} */
callback,
) {
callback(data);
}
} |
JavaScript | class App extends React.Component {
/**
* Initiates the web socket communicator and an empty alarm list.
*
* @param {object} props
*/
constructor(props) {
super(props);
this.state = {
'alarm_entries': []
};
this.webSocketCommunicator = new WebSocketCommunicator('ws://' + this.getWebSocketDomain() +
':12614');
this.addAlarm = this.addAlarm.bind(this);
this.addAlarmRelative = this.addAlarmRelative.bind(this);
this.listResponse = this.listResponse.bind(this);
this.loadAlarmEntries = this.loadAlarmEntries.bind(this);
this.playAlarm = this.playAlarm.bind(this);
this.sendWebSocketCommand = this.sendWebSocketCommand.bind(this);
this.shutdownServer = this.shutdownServer.bind(this);
this.stopAlarm = this.stopAlarm.bind(this);
this.stopAlarmEntry = this.stopAlarmEntry.bind(this);
}
/**
* Adds a fixed alarm on the server.
*
* Reloads the alarm list after 300ms.
*
* @param {string} time
* @param {bool} repeat
*/
addAlarm(time, repeat) {
this.sendWebSocketCommand('timer' + (repeat ? '_repeat' : '') + ' ' + time);
setTimeout(this.loadAlarmEntries, 300);
}
/**
* Adds a relative alarm on the server.
*
* @param {number} amount
* @param {string} unit
* @param {bool} repeat
*/
addAlarmRelative(amount, unit, repeat) {
this.sendWebSocketCommand('timer' + (repeat ? '_repeat' : '') + ' ' + amount + unit);
setTimeout(this.loadAlarmEntries, 300);
}
/**
* Loads the alarm entries when the component was mounted.
*/
componentDidMount() {
this.loadAlarmEntries();
}
/**
* Extracts the domain/ip from the browser location.
*
* @returns {string}
*/
getWebSocketDomain() {
let wsDomain = '127.0.0.1';
// noinspection HttpUrlsUsage
let locationMatch = window.location.href.match(/http:\/\/([^:/]+)/);
if (locationMatch) {
wsDomain = locationMatch[1];
}
return wsDomain;
}
/**
* Callback when the server sent the alarm entries.
*
* @param {MessageEvent} message
*/
listResponse(message) {
let lines = message.data.split("\n");
let entries = [];
for (let l = 0; l < lines.length; l++) {
if (!lines[l].trim()) {
continue;
}
let data = lines[l].split(';');
let timer = data[0].split(' ');
entries.push({
'repeat': 'timer_repeat' === timer[0],
'data': timer[1],
'next_date': 2 === data.length ? data[1] : null
});
}
this.setState({'alarm_entries': entries});
}
/**
* Loads the alarm entries from the web socket.
*/
loadAlarmEntries() {
this.webSocketCommunicator.sendMessageWithResponse('list', this.listResponse, 2000);
}
/**
* Tells the server to play the alarm sound.
*/
playAlarm() {
this.sendWebSocketCommand('play');
}
/**
* Renders the app.
*
* @returns {JSX.Element}
*/
render() {
return (
<CRow>
<CCol sm={7}>
<CCard>
<CCardHeader>Current alarms</CCardHeader>
<CCardBody>
<div className="mb-3">
<CButtonGroup>
<CButton color={'danger'} onClick={this.playAlarm}>Alarm</CButton>
<CButton color={'primary'} onClick={this.stopAlarm}>Stop</CButton>
</CButtonGroup>
</div>
<AlarmList entries={this.state.alarm_entries} loadAlarmEntries={this.loadAlarmEntries}
stopAlarmEntry={this.stopAlarmEntry} />
</CCardBody>
</CCard>
</CCol>
<CCol sm={5}>
<CCard>
<CCardHeader>Add relative alarm</CCardHeader>
<CCardBody>
<RelativeAlarmForm amount={10} unit="m" addAlarm={this.addAlarmRelative} />
</CCardBody>
</CCard>
<CCard>
<CCardHeader>Add alarm</CCardHeader>
<CCardBody>
<AlarmForm time="15:00" addAlarm={this.addAlarm} />
</CCardBody>
</CCard>
<CCard>
<CCardHeader>System</CCardHeader>
<CCardBody>
<CButton className="with-icon" color="danger" onClick={this.shutdownServer}>
<CIcon content={cilPowerStandby} />
Shutdown
</CButton>
</CCardBody>
</CCard>
</CCol>
</CRow>
);
}
/**
* Send a command to the server via the web socket.
*
* @param {string} command
*/
sendWebSocketCommand(command) {
this.webSocketCommunicator.sendMessage(command);
}
/**
* Sends the shutdown command to the server.
*/
shutdownServer() {
this.sendWebSocketCommand('shutdown');
}
/**
* Tells the server to stop the alarm sound.
*/
stopAlarm() {
this.sendWebSocketCommand('stop');
}
/**
* Stops an alarm entry and reloads the alarm entries.
*
* @param {string} command
*/
stopAlarmEntry(command) {
this.sendWebSocketCommand(command);
setTimeout(this.loadAlarmEntries, 300);
}
} |
JavaScript | class QAClient {
constructor(settings, clientFactory, handler) {
this.handler = handler;
/**
* Raw RPC implementation for each service client method.
* The raw methods provide more control on the incoming data and events. E.g. they can be useful to read status `OK` metadata.
* Attention: these methods do not throw errors when non-zero status codes are received.
*/
this.$raw = {
/**
* Unary RPC for /ondewo.qa.QA/GetAnswer
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.GetAnswerResponse>>
*/
getAnswer: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/GetAnswer',
requestData,
requestMetadata,
requestClass: thisProto.GetAnswerRequest,
responseClass: thisProto.GetAnswerResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/RunScraper
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.RunScraperResponse>>
*/
runScraper: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/RunScraper',
requestData,
requestMetadata,
requestClass: thisProto.RunScraperRequest,
responseClass: thisProto.RunScraperResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/UpdateDatabase
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.UpdateDatabaseResponse>>
*/
updateDatabase: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/UpdateDatabase',
requestData,
requestMetadata,
requestClass: thisProto.UpdateDatabaseRequest,
responseClass: thisProto.UpdateDatabaseResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/RunTraining
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.RunTrainingResponse>>
*/
runTraining: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/RunTraining',
requestData,
requestMetadata,
requestClass: googleProtobuf003.Empty,
responseClass: thisProto.RunTrainingResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/GetServerState
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.GetServerStateResponse>>
*/
getServerState: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/GetServerState',
requestData,
requestMetadata,
requestClass: googleProtobuf003.Empty,
responseClass: thisProto.GetServerStateResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/ListProjectIds
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.ListProjectIdsResponse>>
*/
listProjectIds: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/ListProjectIds',
requestData,
requestMetadata,
requestClass: googleProtobuf003.Empty,
responseClass: thisProto.ListProjectIdsResponse
});
},
/**
* Unary RPC for /ondewo.qa.QA/GetProjectConfig
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<GrpcEvent<thisProto.GetProjectConfigResponse>>
*/
getProjectConfig: (requestData, requestMetadata = new GrpcMetadata()) => {
return this.handler.handle({
type: GrpcCallType.unary,
client: this.client,
path: '/ondewo.qa.QA/GetProjectConfig',
requestData,
requestMetadata,
requestClass: thisProto.GetProjectConfigRequest,
responseClass: thisProto.GetProjectConfigResponse
});
}
};
this.client = clientFactory.createClient('ondewo.qa.QA', settings);
}
/**
* Unary RPC for /ondewo.qa.QA/GetAnswer
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.GetAnswerResponse>
*/
getAnswer(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.getAnswer(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/RunScraper
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.RunScraperResponse>
*/
runScraper(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.runScraper(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/UpdateDatabase
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.UpdateDatabaseResponse>
*/
updateDatabase(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.updateDatabase(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/RunTraining
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.RunTrainingResponse>
*/
runTraining(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.runTraining(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/GetServerState
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.GetServerStateResponse>
*/
getServerState(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.getServerState(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/ListProjectIds
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.ListProjectIdsResponse>
*/
listProjectIds(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.listProjectIds(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
/**
* Unary RPC for /ondewo.qa.QA/GetProjectConfig
*
* @param requestMessage Request message
* @param requestMetadata Request metadata
* @returns Observable<thisProto.GetProjectConfigResponse>
*/
getProjectConfig(requestData, requestMetadata = new GrpcMetadata()) {
return this.$raw
.getProjectConfig(requestData, requestMetadata)
.pipe(throwStatusErrors(), takeMessages());
}
} |
JavaScript | class TopicManager {
constructor() {
this.topics = []; // Array of topics listed by ID
this.rank = []; // Linked list of topics sorted by score, descending
this.insertion_point = 0; // Index where to insert the next new topic
}
// If the id is valid, return the topic
get(id) {
if (id < 0 || id > this.topics.length - 1) throw Error('Invalid ID');
return this.topics[id];
}
// Insert the new topic into the insertion_point
// Possible performance improvement: splice might be slower than creating a new
// Array and discarding the old Array depending on JavaScript engine.
add(title) {
const topic = new Topic(title, this.topics.length);
this.topics.push(topic);
this.rank.splice(this.insertion_point, 0, topic);
this.insertion_point += 1;
}
// Upvote a given topic id
upvote(id) {
if (this.get(id).score === -1) this.insertion_point += 1;
this.adjust(id, 1);
}
// Downvote a given topic id
downvote(id) {
if (this.get(id).score === 0) this.insertion_point -= 1;
this.adjust(id, -1);
}
// Re-sort this.rank in descending order using the built-in Array.prototype.sort function
adjust(id, amount) {
const topic = this.get(id);
topic.score += amount;
this.rank.sort((t1, t2) => t2.score - t1.score);
}
} |
JavaScript | class DemoFuroUi5MessageStripDisplay extends FBP(LitElement) {
/**
* Themable Styles
* @private
* @return {CSSResult}
*/
static get styles() {
// language=CSS
return (
Theme.getThemeForComponent('DemoFuroUi5MessageStripDisplay') ||
css`
:host {
display: block;
height: 100%;
padding-right: var(--spacing);
}
:host([hidden]) {
display: none;
}
`
);
}
/**
*@private
*/
static get properties() {
return {};
}
/**
* @private
* @returns {TemplateResult}
*/
render() {
// eslint-disable-next-line lit/no-invalid-html
return html`
<furo-vertical-flex>
<div>
<h2>Demo furo-ui5-message-strip-display</h2>
</div>
<furo-demo-snippet flex>
<template>
<furo-ui5-message-strip-display autofocus></furo-ui5-message-strip-display>
<furo-vertical-scroller>
<h2>Parse grpc status message</h2>
<furo-ui5-message-strip
ƒ-parse-grpc-status="--notification-grpc-status"
@-message-strip-closed="--closed"
></furo-ui5-message-strip>
<produce-banner-data
@-response-error="--notification-grpc-status"
@-notification-closed="--notificationAction"
label="Generate GRPC ERROR"
></produce-banner-data>
<h2>trigger the wire to show message strip </h2>
<furo-ui5-message-strip
ƒ-show="--show"
size="200px"
message="MessageStrip with size"
@-message-strip-closed="--closed"
></furo-ui5-message-strip>
<furo-button label="show" @-click="--show"></furo-button>
<h2>Display the payload by notification custom action </h2>
<furo-pretty-json ƒ-inject-data="--closed"></furo-pretty-json>
<furo-data-object
type="task.Task"
@-object-ready="--entity"
ƒ-inject-raw="--response(*.data)"
></furo-data-object>
<furo-deep-link
service="TaskService"
@-hts-out="--hts"
ƒ-qp-in="--qp"
></furo-deep-link>
<furo-entity-agent
service="TaskService"
ƒ-hts-in="--hts"
ƒ-load="--hts"
ƒ-bind-request-data="--entity"
@-response="--response"
>
<hr />
</furo-vertical-scroller>
</template>
</furo-demo-snippet>
</furo-vertical-flex>
`;
}
} |
JavaScript | class ContractForm extends Component {
state = {
fieldValues: {},
}
componentDidMount () {
// dapp field values are stored in Redux state
if (
Object.values(graphTypes.dapp).includes(this.props.graph.type) &&
Object.keys(this.props.fieldValues).length > 0
) {
this.setState({ fieldValues: this.props.fieldValues })
}
}
componentWillUnmount () {
// dapp field values are stored in Redux state
if (
Object.values(graphTypes.dapp).includes(this.props.graph.type) &&
Object.keys(this.state.fieldValues).length > 0
) {
this.props.storeFieldValues(this.state.fieldValues)
}
}
render () {
const { classes } = this.props
return (
<Fragment>
<Typography
className={classes.nested}
variant="title"
id="modal-title"
>
{this.props.heading}
</Typography>
{this.getSubheading()}
{this.getFunctionForm()}
</Fragment>
)
}
/**
* Determines and returns ContractForm subheading. If there is a
* contractAddress prop, wraps Typography component in CopyToClipboard
* component.
*
* @returns {jsx} the ContractForm's subheading
*/
getSubheading = () => {
let type
if (this.props.selectedContractFunction) {
type =
this.props.graph.elements
.nodes[this.props.selectedContractFunction].type
} else {
type = this.props.graph.type
}
const typography = (
<Typography
className={this.props.classes.nested}
id="simple-modal-description"
variant="subheading"
>
{
this.props.contractAddress
? getDisplayAddress(this.props.contractAddress)
: type === graphTypes.contract._constructor
? 'Constructor'
: 'Deployed'
}
</Typography>
)
return (
this.props.contractAddress
? <CopyToClipboard
text={this.props.contractAddress}
onCopy={this.handleCopy}
style={{ cursor: 'pointer', flexShrink: 1 }}
>
{typography}
</CopyToClipboard>
: typography
)
}
/**
* Creates notification when contract address is copied to clipboard.
*/
handleCopy = () => {
this.props.addSnackbarNotification(
'Contract address copied to clipboard!',
2000
)
}
/**
* Stores input in component state.
* TODO: Does not handle checkboxes or radio buttons.
*
* @param {string} id input field id
*/
handleInputChange = id => event => {
const target = event.target
// const value = target.type === 'checkbox' ? target.checked : target.value
// TODO: handle checkboxes and radio buttons
this.setState({
fieldValues: {
...this.state.fieldValues,
[id]: target.value,
},
})
}
/**
* Form submit handler.
* Initiates web3 call to deployed contract when a contract function form is
* submitted. Clears form fields and closes containing modal.
*
* @param {object} web3Data web3 data from form
*/
handleFunctionSubmit = web3Data => event => {
event.preventDefault()
this.props.callInstance(
this.props.contractAddress,
web3Data.abiName,
web3Data.paramOrder.length > 0 // if there are any function params
? web3Data.paramOrder.map(id => {
return this.state.fieldValues[id]
})
: null
)
this.setState({ fieldValues: {} })
this.props.closeContractForm()
}
/**
* Form submit handler.
* Initiates web3 call to deploy a contract when a contract constructor form
* is submitted. Closes the containing modal without clearing form.
*
* @param {object} web3Data web3 data from form
*/
handleConstructorSubmit = web3Data => event => {
event.preventDefault()
this.props.deployContract(
this.props.graph.name,
web3Data.paramOrder.map(id => {
return this.state.fieldValues[id]
})
)
this.props.closeContractForm()
}
/**
* Uses form data to update the wipDappDeployment state object, which
* defines the web3 calls made when a dapp is deployed.
*
* @param {object} web3Data web3 data from form
*/
handleDappFunctionSubmit = web3Data => event => {
event.preventDefault()
const wipDeployment = {
...(
this.props.wipDappDeployment
? this.props.wipDappDeployment
: {}
),
}
// TODO: application logic, move to thunk
wipDeployment[web3Data.id] = {
nodeId: web3Data.id,
contractName: web3Data.abiName,
deploymentOrder:
this.props.dappTemplate.contractNodes[web3Data.id].deploymentOrder,
params: {
...web3Data.params,
},
outputs: {
...web3Data.outputs,
},
}
// store field values in component state
Object.values(wipDeployment[web3Data.id].params).forEach(param => {
if (param.source) { // if this parameter is an edge target
if (param.sourceParent === 'account') {
param.value = this.props.account
} else console.log('ignoring param source', param.source)
} else {
param.value = this.state.fieldValues[param.id]
}
})
// store outputs of form's corresponding contract deployment in
// wipDeployment
Object.values(wipDeployment[web3Data.id].outputs).forEach(output => {
// TODO? if other output types are added, this must handle them
if (output.target) { // if this parameter is an edge source
if (!wipDeployment[web3Data.id].childParams) {
wipDeployment[web3Data.id].childParams = []
}
wipDeployment[web3Data.id].childParams.push({
type: 'address',
paramId: output.target,
contractId: output.targetParent,
deploymentOrder:
this.props.dappTemplate.contractNodes[output.targetParent].deploymentOrder,
})
}
})
this.props.updateWipDappDeployment(wipDeployment)
this.props.closeContractForm()
}
/**
* Primary render workhorse. Gets form components and sets up handlers per
* Redux state.
*/
getFunctionForm = () => {
const { classes } = this.props
const nodes = this.props.graph.elements.nodes
const graphType = this.props.graph.type
// const selectedNode = nodes[this.props.selectedContractFunction]
const formData = this.getFunctionFormData()
let submitHandler; let functionCall = false
switch (graphType) {
case graphTypes.contract._constructor:
submitHandler = this.handleConstructorSubmit
break
case graphTypes.contract.functions:
functionCall = true
submitHandler = this.handleFunctionSubmit
break
case graphTypes.dapp.template:
// in the case of a dapp, a function id is selected in Grapher by an
// event handler in the Joint paper and passed to
// this.props.selectedContractFunction
submitHandler = this.handleDappFunctionSubmit
break
default:
throw new Error('unhandled graph type: ' + graphType)
}
return (
<Fragment>
{
functionCall
? <DropdownMenu
classes={{ root: classes.root }}
menuItemData={getFunctionAndConstructorIds(nodes)}
menuTitle="Functions"
selectAction={this.props.selectContractFunction} />
: null
}
{
formData
?
(
<form
className={classes.container}
onSubmit={submitHandler(formData.web3Data)}
>
<div className={classes.nested}>
{formData.fields}
</div>
<div
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-end',
}}
>
{
!(
functionCall &&
!this.props.selectedContractFunction
)
? <Button
className={classes.button}
variant="contained"
type="submit"
>
{
graphType === graphTypes.dapp.template
? 'Save Inputs'
: functionCall
? 'Call Function'
: 'Deploy'
}
</Button>
: null
}
</div>
</form>
)
: null
}
</Fragment>
)
}
/**
* Gets form fields and generates web3 data object for completing web3 calls.
*
* @returns {object} form metadata and corresponding web3 (contract) data
*/
getFunctionFormData = () => {
const nodes = this.props.graph.elements.nodes
const edges = this.props.graph.elements.edges
const functionId = this.props.selectedContractFunction
const functionNodes = []
Object.values(nodes).forEach(node => {
if (node.id === functionId || node.parent === functionId) {
functionNodes.push(node)
}
})
const web3Data = {
params: {},
outputs: {},
paramOrder: [],
}
const fields = []
functionNodes.forEach(node => {
if (
Object.values(graphTypes.contract).includes(node.type) ||
node.type === 'function'
) {
web3Data.title = node.displayName
web3Data.abiName = node.abiName
web3Data.id = node.id
} else if (node.type === 'parameter') {
const fieldType = parseSolidityType(node.abiType)
const paramData = {
id: node.id,
abiName: node.abiName,
abiType: node.abiType,
paramOrder: node.paramOrder,
parentForm: node.parent,
}
Object.values(edges).forEach(edge => {
if (edge.target === node.id) {
paramData.edge = edge.id
paramData.source = edge.source
paramData.sourceParent = edge.sourceParent
}
})
web3Data.params[node.id] = paramData
web3Data.paramOrder.push(node.id)
switch (fieldType) {
// TODO: handle different parameter types
// case 'string':
default:
fields.push(
<TextField
key={node.id}
id={node.id}
label={node.displayName}
className={this.props.classes.textField}
value={
paramData.source
? this.getSourcedFieldValue(edges[paramData.edge])
: this.state.fieldValues[node.id]
? this.state.fieldValues[node.id]
: ''
}
disabled={Boolean(paramData.source)}
onChange={this.handleInputChange(node.id)}
margin="normal"
/>
)
break
}
} else if (node.type === 'output') {
Object.values(edges).forEach(edge => {
if (edge.source === node.id) {
web3Data.outputs[edge.id] = {
edge: edge.id,
target: edge.target,
targetParent: edge.targetParent,
}
}
})
} else {
console.warn('ContractForm: ignoring unknown node type: ' + node.type)
}
})
fields.sort((a, b) => {
return (
web3Data.params[a.props.id].paramOrder -
web3Data.params[b.props.id].paramOrder
)
})
web3Data.paramOrder.sort((a, b) => {
return web3Data.params[a].paramOrder - web3Data.params[b].paramOrder
})
return {web3Data, fields}
}
/**
* Gets value for field defined by edge in dapp graph.
*
* @param {object} edge edge defining value of field
* @returns {string} field value
*/
getSourcedFieldValue = edge => {
// TODO: handle remaining possible value sources
if (edge.sourceParent === 'account') {
return 'Current Account Address'
}
if (edge.sourceAbiType === 'address') {
return 'Deployed Contract Address'
} else throw new Error('unknown field value')
}
} |
JavaScript | class PolygonOverlayRenderer extends WebGLOverlayRenderer {
/**
* Instantiates a new PolygonOverlayRenderer object.
*
* @param {Object} options - The overlay options.
* @param {Array} options.polygonColor - The color of the line.
*/
constructor(options = {}) {
super(options);
this.polygonColor = defaultTo(options.polygonColor, [ 1.0, 0.4, 0.1, 0.8 ]);
this.shader = null;
this.polygons = null;
}
/**
* Executed when the overlay is attached to a plot.
*
* @param {Plot} plot - The plot to attach the overlay to.
*
* @returns {PolygonOverlayRenderer} The overlay object, for chaining.
*/
onAdd(plot) {
super.onAdd(plot);
this.shader = this.createShader(SHADER_GLSL);
return this;
}
/**
* Executed when the overlay is removed from a plot.
*
* @param {Plot} plot - The plot to remove the overlay from.
*
* @returns {PolygonOverlayRenderer} The overlay object, for chaining.
*/
onRemove(plot) {
super.onRemove(plot);
this.shader = null;
return this;
}
/**
* Generate any underlying buffers.
*
* @returns {PolygonOverlayRenderer} The overlay object, for chaining.
*/
refreshBuffers() {
const clipped = this.overlay.getClippedGeometry();
if (clipped) {
this.polygons = clipped.map(points => {
// generate the buffer
return createBuffers(this, points);
});
} else {
this.polygons = null;
}
}
/**
* The draw function that is executed per frame.
*
* @returns {PolygonOverlayRenderer} The overlay object, for chaining.
*/
draw() {
if (!this.polygons) {
return this;
}
const gl = this.gl;
const shader = this.shader;
const polygons = this.polygons;
const plot = this.overlay.plot;
const cell = plot.cell;
const proj = this.getOrthoMatrix();
const scale = Math.pow(2, plot.zoom - cell.zoom);
const opacity = this.overlay.opacity;
// get view offset in cell space
const offset = cell.project(plot.viewport, plot.zoom);
// set blending func
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// bind shader
shader.use();
// set global uniforms
shader.setUniform('uProjectionMatrix', proj);
shader.setUniform('uViewOffset', [ offset.x, offset.y ]);
shader.setUniform('uScale', scale);
shader.setUniform('uPolygonColor', this.polygonColor);
shader.setUniform('uOpacity', opacity);
// for each polyline buffer
polygons.forEach(buffer => {
// draw the points
buffer.vertex.bind();
buffer.index.draw();
});
return this;
}
} |
JavaScript | class Layout {
/**
* Create a Layout object. This constructor will throw if any duplicate
* attributes are given.
* @param {Array} ...attributes - An ordered list of attributes that
* describe the desired memory layout for each vertex attribute.
* <p>
*
* @see {@link Mesh}
*/
constructor(...attributes) {
this.attributes = attributes;
let offset = 0;
let maxStrideMultiple = 0;
for (const attribute of attributes) {
if (this[attribute.key]) {
throw new DuplicateAttributeException(attribute);
}
// Add padding to satisfy WebGL's requirement that all
// vertexAttribPointer calls have an offset that is a multiple of
// the type size.
if (offset % attribute.sizeOfType !== 0) {
offset += attribute.sizeOfType - offset % attribute.sizeOfType;
console.warn('Layout requires padding before ' + attribute.key + ' attribute');
}
this[attribute.key] = {
'attribute': attribute,
'size': attribute.size,
'type': attribute.type,
'normalized': attribute.normalized,
'offset': offset,
};
offset += attribute.sizeInBytes;
maxStrideMultiple = Math.max(
maxStrideMultiple,
attribute.sizeOfType);
}
// Add padding to the end to satisfy WebGL's requirement that all
// vertexAttribPointer calls have a stride that is a multiple of the
// type size. Because we're putting differently sized attributes into
// the same buffer, it must be padded to a multiple of the largest
// type size.
if (offset % maxStrideMultiple !== 0) {
offset += maxStrideMultiple - offset % maxStrideMultiple;
console.warn('Layout requires padding at the back');
}
this.stride = offset;
for (const attribute of attributes) {
this[attribute.key].stride = this.stride;
}
}
} |
JavaScript | class DuplicateAttributeException {
/**
* Create a DuplicateAttributeException
* @param {Attribute} attribute - The attribute that was found more than
* once in the {@link Layout}
*/
constructor(attribute) {
this.message = 'found duplicate attribute: ' + attribute.key;
}
} |
JavaScript | class Attribute {
/**
* Create an attribute. Do not call this directly, use the predefined
* constants.
* @param {string} key - The name of this attribute as if it were a key in
* an Object. Use the camel case version of the upper snake case
* const name.
* @param {number} size - The number of components per vertex attribute.
* Must be 1, 2, 3, or 4.
* @param {string} type - The data type of each component for this
* attribute. Possible values:<br/>
* "BYTE": signed 8-bit integer, with values in [-128, 127]<br/>
* "SHORT": signed 16-bit integer, with values in
* [-32768, 32767]<br/>
* "UNSIGNED_BYTE": unsigned 8-bit integer, with values in
* [0, 255]<br/>
* "UNSIGNED_SHORT": unsigned 16-bit integer, with values in
* [0, 65535]<br/>
* "FLOAT": 32-bit floating point number
* @param {boolean} normalized - Whether integer data values should be
* normalized when being casted to a float.<br/>
* If true, signed integers are normalized to [-1, 1].<br/>
* If true, unsigned integers are normalized to [0, 1].<br/>
* For type "FLOAT", this parameter has no effect.
*/
constructor(key, size, type, normalized=false) {
this.key = key;
this.size = size;
this.type = type;
this.normalized = false;
this.sizeOfType = sizeInBytesOfType(type);
this.sizeInBytes = this.sizeOfType * size;
}
} |
JavaScript | class Geofences {
/**
* @param {Object} utils - General utilities passed from main HERETracking
* @param {function(varArgs: ...string): string} utils.url - Generate the URL for HERE Tracking
* @param {function(options: Object, required: Array): Promise} utils.validate - Check the supplied parameters
* @param {function(url: string, options: Object): Object} utils.fetch - Wrap the standard Fetch API
* (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to provide error handling
*/
constructor(utils) {
/**
* Generate the URL for HERE Tracking
* @type {function(varArgs: ...string): string} generate URL for HERE Tracking
*/
this.url = utils.url;
/**
* Check the supplied parameters
* @type {function(options: Object, required: Array): Promise}
*/
this.validate = utils.validate;
/**
* Wrap the standard Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
* to provide error handling
* @type {function(url: string, options: Object): Object}
*/
this.fetch = utils.fetch;
}
/**
* List the geofences available to the user.
*
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @param {number} [options.count] - Number of geofences returned per page (default 100)
* @param {string} [options.pageToken] - Page token used for retrieving next page
* @returns {Object} Body of the geofence response
* @throws {Error} When an HTTP error has occurred
*/
list({ count, pageToken, token }) {
return this.validate({ token }, ['token'])
.then(() => {
const queryParameters = {};
if (count) {
queryParameters.count = count;
}
if (pageToken) {
queryParameters.pageToken = pageToken;
}
const url = this.url('geofences', 'v2', queryParameters);
return this.fetch(url, {
credentials: 'include',
headers: new Headers({
'Authorization': `Bearer ${token}`
})
});
});
}
/**
* Retrieve details about a geofence.
*
* @param {string} geofenceId - ID of geofence to retrieve
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Body of the geofence response
* @throws {Error} When an HTTP error has occurred
*/
get(geofenceId, { token }) {
return this.validate({ token, geofenceId }, ['token', 'geofenceId'])
.then(() => {
const url = this.url('geofences', 'v2', geofenceId);
return this.fetch(url, {
credentials: 'include',
headers: new Headers({
'Authorization': `Bearer ${token}`
})
});
});
}
/**
* Create a new geofence associated with a user
*
* @param {Object} geofence - definition of the geofence
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Body of the geofence response
* @throws {Error} When an HTTP error has occurred
*/
create(geofence, { token }) {
return this.validate({ token }, ['token'])
.then(() => {
const url = this.url('geofences', 'v2');
const fields = Object.keys(geofence);
if (fields.indexOf('type') < 0) {
return Promise.reject(new Error('No geofence type specified'));
}
if (fields.indexOf('definition') < 0) {
return Promise.reject(new Error('No geofence shape definition specified'));
}
return this.fetch(url, {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}),
body: JSON.stringify(geofence)
});
});
}
/**
* Update a geofence
*
* @param {Object} geofence - Definition of the geofence
* @param {Object} geofence.id - ID of the geofence
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Body of the geofence response
* @throws {Error} When an HTTP error has occurred
*/
update(geofence, { token }) {
return this.validate({ token }, ['token'])
.then(() => this.validate(geofence, ['id']))
.then(() => {
const url = this.url('geofences', 'v2', geofence.id);
delete geofence.id;
const fields = Object.keys(geofence);
const missing = atLeastOneOf.filter(x => fields.indexOf(x) < 0);
if (missing.length === atLeastOneOf.length) {
return Promise.reject(new Error(`Geofence update requires at least one of: ${missing.join(', ')}`));
}
return this.fetch(url, {
method: 'put',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}),
body: JSON.stringify(geofence)
});
});
}
/**
* Remove geofence
*
* @param {Object} geofenceId - ID of the geofence
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object}
* @throws {Error} When an HTTP error has occurred
*/
remove(geofenceId, { token }) {
return this.validate({ geofenceId, token }, ['token', 'geofenceId'])
.then(() => this.fetch(this.url('geofences', 'v2', geofenceId), {
method: 'delete',
headers: new Headers({
'Authorization': `Bearer ${token}`
})
}));
}
/**
* Remove all geofences.
* This is a separate method so that it can't be called by accidentally
* forgetting to pass geofenceId
*
* @param {boolean} really - Confirmation to delete all
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object}
* @throws {Error} When an HTTP error has occurred
*/
removeAll(really, { token }) {
return this.validate({ token }, ['token'])
.then(() => {
if (really !== true) {
return Promise.reject(new Error('Confirmation required to delete all geofences.'));
}
const url = this.url('geofences', 'v2');
return this.fetch(url, {
method: 'delete',
headers: new Headers({
'Authorization': `Bearer ${token}`,
'x-confirm': really
})
});
});
}
/**
* Get the devices associated with a geofence.
*
* @param {string} geofenceId - ID of the geofence
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @param {string} [options.pageToken] - Page token used for retrieving next page
* @param {number} [options.count] - Number of devices returned per page
* @returns {Object} Body of the device response
* @throws {Error} When an HTTP error has occurred
*/
getDevices(geofenceId, { token, count, pageToken }) {
return this.validate({ geofenceId, token }, ['geofenceId', 'token'])
.then(() => {
const queryParameters = {};
if (count) {
queryParameters.count = count;
}
if (pageToken) {
queryParameters.pageToken = pageToken;
}
const url = this.url('geofence-associations', 'v2', geofenceId, 'devices', queryParameters);
return this.fetch(url, {
credentials: 'include',
headers: new Headers({
'Authorization': `Bearer ${token}`
})
});
});
}
/**
* Add a device to a geofence
*
* @param {string} geofenceId - ID of geofence
* @param {string} trackingId - ID of device to add
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Body of the transition response
* @throws {Error} When an HTTP error has occurred
*/
addDevice(geofenceId, trackingId, { token }) {
return this.validate({ geofenceId, trackingId, token }, ['geofenceId', 'trackingId', 'token'])
.then(() => this.fetch(this.url('geofence-associations', 'v2', geofenceId, trackingId), {
method: 'put',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
})
}));
}
/**
* Remove a device from a geofence
*
* @param {string} geofenceId - ID of geofence
* @param {string} trackingId - ID of device to remove
* @param {Object} options - Object containing request options
* @param {string} options.token - Valid user access token
* @returns {Object} Body of the transition response
* @throws {Error} When an HTTP error has occurred
*/
removeDevice(geofenceId, trackingId, { token }) {
return this.validate({ geofenceId, trackingId, token }, ['geofenceId', 'trackingId', 'token'])
.then(() => this.fetch(this.url('geofence-associations', 'v2', geofenceId, trackingId), {
method: 'delete',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
})
}));
}
} |
JavaScript | class TestTables {
constructor() {
this.matchedConditions = {};
this.matched = {};
}
/**
* Registers a matching subfilters in the test tables
*
* @param {Set} subfilters - matching subfilters
*/
addMatch(subfilters) {
for (const subfilter of subfilters) {
const matched = this.matchedConditions[subfilter.id] || subfilter.conditions.size;
if (matched > 1) {
this.matchedConditions[subfilter.id] = matched - 1;
}
else {
for (const filter of subfilter.filters) {
this.matched[filter.id] = 1;
}
}
}
}
} |
JavaScript | class FirebaseUploadfile extends LitElement {
static get is() {
return 'firebase-uploadfile';
}
static get properties() {
return {
path: {
type: String
},
waitingMsg: {
type: String,
attribute: 'waiting-msg'
},
uploadErrorMsg: {
type: String,
attribute: 'upload-errmsg'
},
uploadOkMsg: {
type: String,
attribute: 'upload-okmsg'
},
name: {
type: String
},
storageName: {
type: String,
attribute: 'storage-name'
},
saveFileDatabase: {
type: Boolean,
attribute: 'save-file-database'
},
deleteBtn: {
type: Boolean,
attribute: 'delete-btn'
},
dataUser: {
type: Object
},
value: {
type: String
},
fileIsImage: {
type: Boolean
}
};
}
static get styles() {
return css`
/* CSS CUSTOM VARS
--progress-bg-color, #eee;
--progress-color1: #09c;
--progress-color2: #f44;
--progress-width: 500px
--bgcolor-button: #106BA0;
--color-button: #FFF;
--progress-width: 500px
*/
:host {
display: flex;
padding: 0;
margin: 30px 0;
align-items: start;
justify-content: center;
flex-direction: column;
}
#uploader {
-webkit-appearance: none;
appearance: none;
width: 100%;
margin-bottom: 10px;
}
#msg {
border: 3px outset gray;
border-radius: 15px;
width: 300px;
height: 100px;
position: absolute;
background: gray;
display:none;
color: #FFF;
font-weight: bold;
justify-content: center;
align-items: center;
font-size: 1.2rem;
}
label {
font-weight: bold;
margin: 5px 0;
}
.wrapper {
display:flex;
}
.bloque1 {
width: var(--progress-width, 500px);
}
.bloque2 {
margin-left:20px;
}
.bloque2 a {
display: block;
}
.fakefile {
width:80px;
height: 80px;
border:2px solid black;
}
.fakefile > div::before {
transform: rotate(-45deg);
content: "FILE";
}
.invisible {
visibility: hidden;
}
progress[value]::-webkit-progress-bar {
background-color: var(--progress-bg-color, #eee);
border-radius: 2px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.25) inset;
}
progress[value]::-webkit-progress-value {
background-image:
-webkit-linear-gradient(-45deg, transparent 33%, rgba(0, 0, 0, .1) 33%, rgba(0,0, 0, .1) 66%, transparent 66%),
-webkit-linear-gradient(top, rgba(255, 255, 255, .25), rgba(0, 0, 0, .25)),
-webkit-linear-gradient(left, var(--progress-color1, #09c), var(--progress-color2, #f44));
border-radius: 2px;
background-size: 35px 20px, 100% 100%, 100% 100%;
-webkit-animation: animate-stripes 5s linear infinite;
animation: animate-stripes 5s linear infinite;
}
progress[value]::-moz-progress-bar {
background-image:
-moz-linear-gradient(135deg, transparent 33%, rgba(0, 0, 0, 0.1) 33%, rgba(0, 0, 0, 0.1) 66%, transparent 66%),
-moz-linear-gradient(top, rgba(255, 255, 255, 0.25), rgba(0, 0, 0, 0.25)),
-moz-linear-gradient(left, var(--progress-color1, #09c), var(--progress-color2, #f44));
border-radius: 2px;
background-size: 35px 20px, 100% 100%, 100% 100%;
animation: animate-stripes 5s linear infinite;
}
input[type="file"] {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
label[for="fileButton"] {
padding: 0.5rem;
}
label[for="fileButton"], button {
font-size: 14px;
font-weight: 600;
color: var(--color-button, #FFF);
background-color: var(--bgcolor-button, #106BA0);
display: inline-block;
transition: all .5s;
cursor: pointer;
text-transform: uppercase;
width: fit-content;
text-align: center;
border: 2px outset var(--bgcolor-button, #106BA0);
border-radius: 10px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.bloque1 button {
margin:0.3rem;
padding: 0.5rem;
}
.lds-dual-ring {
display: inline-block;
width: 80px;
height: 80px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 64px;
height: 64px;
margin: 8px;
border-radius: 50%;
border: 6px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@-webkit-keyframes animate-stripes {
100% { background-position: -100px 0px; }
}
@keyframes animate-stripes {
100% { background-position: -100px 0px; }
}
`;
}
constructor() {
super();
this.path = '/';
this.name = 'name';
this.storageName = 'sname';
this.waitingMsg = 'Waiting Login...';
this.uploadErrorMsg = 'Upload Error';
this.uploadOkMsg = 'File Uploaded';
this.bLog = false;
this.loggedUser = '';
this.dataUser = null;
this.saveFileDatabase = false;
this.deleteBtn = false;
this.value = '';
this.fileIsImage = false;
this._fileValueChange = this._fileValueChange.bind(this);
this._deleteValue = this._deleteValue.bind(this);
}
connectedCallback() {
super.connectedCallback();
document.addEventListener('firebase-signin', (ev) => {
this._userLogged(ev);
});
document.addEventListener('firebase-signout', (ev) => {
this._userLogout(ev);
});
const firebaseAreYouLoggedEvent = new Event('are-it-logged-into-firebase');
document.dispatchEvent(firebaseAreYouLoggedEvent);
const firebaseAreYouLoggedEvent2 = new Event('firebase-are-you-logged');
document.dispatchEvent(firebaseAreYouLoggedEvent2);
console.log(this.path);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener('firebase-signin', (ev) => {
this._userLogged(ev);
});
document.removeEventListener('firebase-signout', (ev) => {
this._userLogout(ev);
});
}
firstUpdated() {
this.sdomMsgLayer = this.shadowRoot.querySelector('#msg');
}
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName === 'dataUser' && this.dataUser !== null) {
this.main();
}
if (propName === 'value') {
this.fileIsImage = (this.value.search(/jpg|png|gif|tif|svg/) !== -1);
}
});
}
log(msg) {
if (this.bLog) {
console.log(msg);
}
}
_userLogged(obj) {
if (!this.user && obj.detail.user) {
this.user = obj.detail.user.displayName;
this.dataUser = obj.detail.user;
this.app = obj.detail.firebaseApp;
const slash = ( this.path.substr(-1) !== '/' ) ? '/' :'';
this.path = `${this.path}${slash}${this.user.replace(/\s+/g, '_')}`;
}
}
_userLogout() {
this.dataUser = null;
this.data = null;
}
getFileName(file) {
const hoy = new Date();
const hora = `${hoy.getHours()}_${hoy.getMinutes()}_${hoy.getSeconds()}`;
const fecha = `${hoy.getDate()}_${hoy.getMonth()}_${hoy.getFullYear()}`;
const fileNameData = { 'FILENAME': file.name, 'USER': this.user.replace(/\s/g, '_'), 'DATE': fecha, 'HOUR': hora, 'NAME': this.name };
const nameParts = this.storageName.split(',');
let fileNameParts = [];
nameParts.forEach((part) => {
let name = fileNameData[part] ? fileNameData[part] : part;
fileNameParts.push(name);
});
return fileNameParts.join('-');
}
_cleanString(str) {
const cleanedStr= str.toLowerCase()
.replace(/\s/g, '_')
.replace(/[àáä]/g, 'a')
.replace(/[èéë]/g, 'e')
.replace(/[ìíï]/g, 'i')
.replace(/òóö/g, 'o')
.replace(/[ùúü]/g, 'u')
.replace(/[ñÑ]/g, 'n')
.replace(/[\[\]\.]/g, '');
return cleanedStr;
}
closeMsg(layer) {
setTimeout(
() => {
layer.style.display = 'none';
layer.innerText = '';
this.shadowRoot.querySelector('#uploader').value = 0;
}, 1500);
}
saveDownloadURL() {
const hoy = new Date();
const cleanuser = this._cleanString(this.user);
const path = `${this.path}/${cleanuser}/${this.name}`;
const rootRef = firebase.database().ref();
const storesRef = rootRef.child(path);
const newStoreRef = storesRef.push();
newStoreRef.set(this.value);
}
_deleteValue() {
this.value = '';
this.shadowRoot.querySelector('.bloque1 button').classList.add('invisible');
this.shadowRoot.querySelector('#fileButton').value = '';
}
// Firebase 8: para ver el progreso de la carga de archivos
_progressBar(task) {
this.shadowRoot.querySelector('progress').classList.remove('invisible');
task.on('state_changed',
(snapshot) => {
let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
(err) => {
msgLayer.style.display = 'flex';
msgLayer.innerText = this.uploadErrorMsg;
this.closeMsg(msgLayer);
},
() => {
task.snapshot.ref.getDownloadURL().then((downloadURL) => {
this.value = downloadURL;
this.fileIsImage = (file && file.type.split('/')[0] === 'image');
if (this.saveFileDatabase) {
this.saveDownloadURL();
}
const id = this.id || 'id-not-defined';
this.shadowRoot.querySelector('progress').classList.add('invisible');
if (this.deleteBtn) {
this.shadowRoot.querySelector('.bloque1 button').classList.remove('invisible');
}
document.dispatchEvent(new CustomEvent('firebase-file-storage-uploaded', { 'detail': { downloadURL: downloadURL, name: this.name, id: id } }));
});
this._showMessage(this.uploadOkMsg)
}
);
}
_showLoading() {
this.sdomMsgLayer.style.display = 'flex';
this.sdomMsgLayer.innerHTML = '<div class="lds-dual-ring"></div>';
}
_showMessage(message) {
const msgLayer = this.shadowRoot.querySelector('#msg');
msgLayer.style.display = 'flex';
msgLayer.innerText = message;
this.closeMsg(msgLayer);
}
async _fileValueChange(e) {
const uploader = this.shadowRoot.querySelector('#uploader');
const msgLayer = this.shadowRoot.querySelector('#msg');
const file = e.target.files[0];
const fileName = this.getFileName(file);
try {
this._showLoading();
const storage = await getStorage(this.app);
const storageRef = ref(storage, this.path + '/' + fileName);
const uploadResult = await uploadBytes(storageRef, file);
//TODO: Investigar como obtener el progreso con firebase 9: const uploadTask = uploadBytesResumable(storageRef, file);
// this._progressBar(uploadTask);
this._showMessage('File uploaded sucessusfully');
} catch(err) {
console.error(err);
}
}
main() {
const fileButton = this.shadowRoot.querySelector('#fileButton');
if (this.deleteBtn) {
this.shadowRoot.querySelector('.bloque1 button').addEventListener('click', this._deleteValue);
}
fileButton.addEventListener('change', this._fileValueChange);
}
render() {
const name = this.name.split('/').pop();
return html`
${this.dataUser !== null ? html`
<section class="wrapper">
<div class="bloque1">
<label>${name}</label>
<progress value="0" max="100" id="uploader" class="invisible">0%</progress>
<div style="display:flex">
<label for="fileButton">Selecciona un fichero
<input type="file" value="upload" id="fileButton">
</label>
${(this.deleteBtn) ? (this.value !== '') ? html`<button>Delete</button>`: html`<button class="invisible">Delete</button>` : html``}
</div>
</div>
<div class="bloque2">
${(this.value !== '') ? (this.fileIsImage) ? html`<img src="${this.value}" alt="${name}" width="150">` : html`<div class='fakefile'><div></div></div>` : html``}
${(this.value !== '') ? html`<a href='${this.value}' target="_blank">${this.value.split('/').pop().split('?')[0].split('-').pop()}</a>` : html``}
</div>
</section>
<div id="filelink"></div>
<div id="msg"></div>
` : html`<div class="waiting">Waiting for login...</div>`}
`;
}
} |
JavaScript | class DataBindingDirective {
constructor(scheduler, changeDetector, localDataChangesService) {
this.scheduler = scheduler;
this.changeDetector = changeDetector;
this.localDataChangesService = localDataChangesService;
this.originalData = [];
if (localDataChangesService) {
this.dataChangedSubscription = this.localDataChangesService.changes.subscribe(this.rebind.bind(this));
}
}
/**
* The array of data which will populate the Scheduler.
*/
set data(value) {
this.originalData = value || [];
if (this.localDataChangesService) {
this.localDataChangesService.data = value;
}
this.scheduler.events = this.process();
}
/**
* @hidden
*/
ngOnInit() {
this.subscription = this.scheduler
.dateChange
.subscribe(e => this.onDateChange(e));
}
/**
* @hidden
*/
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
if (this.dataChangedSubscription) {
this.dataChangedSubscription.unsubscribe();
}
}
/**
* @hidden
*/
rebind() {
this.data = this.originalData;
this.changeDetector.markForCheck();
}
process() {
if (!this.dateRange) {
// No processing until a date range is set
return [];
}
const data = [];
const fields = this.scheduler.modelFields;
this.originalData
.forEach(item => {
if (getField(item, fields.recurrenceRule)) {
const series = occurrences(item, fields, this.dateRange, this.scheduler.timezone);
data.push(...series);
}
else {
data.push(item);
}
});
return data;
}
onDateChange(e) {
this.dateRange = e.dateRange;
this.rebind();
}
} |
JavaScript | class InitiateReply extends ServiceBase {
/**
* Constructor to initiate reply.
*
* @param {object} params
* @param {object} params.current_user
* @param {number} params.parent_kind: parent post kind
* @param {number} params.parent_id: parent video id
* @param {number} params.reply_detail_id: if reply is editing
* @param {string} params.video_url: s3 video url
* @param {string} params.poster_image_url: s3 poster image url
* @param {number} params.video_width: video width
* @param {number} params.video_height {number}: video height
* @param {number} params.video_size: video size
* @param {number} params.video_duration: video duration
* @param {number} params.video_duration_preference: video duration Preference
* @param {number} params.image_width: image width
* @param {number} params.image_height: image height
* @param {number} params.image_size: image size
* @param {string} [params.video_description]: Video description
* @param {string} [params.link]: Link
*
* @augments ServiceBase
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.replyDetailId = params.reply_detail_id || null;
oThis.currentUser = params.current_user;
oThis.parentKind = params.parent_kind;
oThis.parentId = params.parent_id;
oThis.videoUrl = params.video_url;
oThis.posterImageUrl = params.poster_image_url;
oThis.videoWidth = params.video_width;
oThis.videoHeight = params.video_height;
oThis.videoSize = params.video_size;
oThis.imageWidth = params.image_width;
oThis.imageHeight = params.image_height;
oThis.imageSize = params.image_size;
oThis.videoDescription = params.video_description;
oThis.link = params.link;
oThis.videoDuration = params.video_duration;
oThis.videoDurationPref = params.video_duration_preference;
oThis.videoId = null;
}
/**
* Async perform.
*
* @sets oThis.videoId, oThis.replyDetailId
*
* @returns {Promise<void>}
* @private
*/
async _asyncPerform() {
const oThis = this;
await oThis._validateAndSanitize();
if (oThis.replyDetailId) {
await oThis._getReplyDetails();
if (oThis.replyDetail.creatorUserId !== oThis.currentUser.id) {
return Promise.reject(
responseHelper.error({
internal_error_identifier: 's_r_i_1',
api_error_identifier: 'unauthorized_api_request',
debug_options: { replyDetail: oThis.replyDetail, currentUserId: oThis.currentUser.id }
})
);
}
await oThis._editReplyDescription();
await new EditReplyLink({
replyDetailId: oThis.replyDetail.id,
link: oThis.link
}).perform();
} else {
await oThis._addLink();
const resp = await oThis._validateAndSaveReply();
oThis.videoId = resp.videoId;
oThis.replyDetailId = resp.replyDetailId;
await oThis._addReplyDescription();
await oThis._onVideoPostCompletion();
}
if (UserModelKlass.isUserApprovedCreator(oThis.currentUser)) {
const messagePayload = {
userId: oThis.currentUser.id,
parentVideoId: oThis.parentId,
replyDetailId: oThis.replyDetailId
};
await bgJob.enqueue(bgJobConstants.slackContentReplyMonitoringJobTopic, messagePayload);
} else {
const messagePayload = {
userId: oThis.currentUser.id
};
await bgJob.enqueue(bgJobConstants.approveNewCreatorJobTopic, messagePayload);
}
return responseHelper.successWithData({
[entityTypeConstants.videoReplyList]: [
{
id: oThis.replyDetailId,
creatorUserId: oThis.currentUser.id,
replyDetailId: oThis.replyDetailId,
updatedAt: Math.round(new Date() / 1000)
}
]
});
}
/**
* Validate and sanitize.
*
* @sets oThis.parentKind, oThis.link
*
* @returns {Promise<never>}
* @private
*/
async _validateAndSanitize() {
const oThis = this;
oThis.parentKind = oThis.parentKind.toUpperCase();
const validateReplyResp = await new ValidateReplyService({
current_user: oThis.currentUser,
video_description: oThis.videoDescription,
link: oThis.link,
parent_kind: oThis.parentKind,
parent_id: oThis.parentId
}).perform();
if (validateReplyResp.isFailure()) {
return Promise.reject(validateReplyResp);
}
if (!CommonValidators.validateGenericUrl(oThis.link)) {
oThis.link = null;
}
}
/**
* Get reply details.
*
* @sets oThis.replyDetail
*
* @returns {Promise<never>}
* @private
*/
async _getReplyDetails() {
const oThis = this;
const replyDetailsCacheResp = await new ReplyDetailsByIdsCache({ ids: [oThis.replyDetailId] }).fetch();
if (replyDetailsCacheResp.isFailure()) {
logger.error('Error while fetching reply detail data for reply_detail_id:', oThis.replyDetailId);
return Promise.reject(replyDetailsCacheResp);
}
oThis.replyDetail = replyDetailsCacheResp.data[oThis.replyDetailId];
}
/**
* Edit reply description.
*
* @returns {Promise<void>}
* @private
*/
async _editReplyDescription() {
const oThis = this;
const editDescriptionResp = await new EditDescriptionLib({
videoId: oThis.replyDetail.entityId,
videoDescription: oThis.videoDescription,
replyDetailId: oThis.replyDetailId
}).perform();
if (editDescriptionResp.isFailure()) {
return Promise.reject(editDescriptionResp);
}
}
/**
* Add link in urls table.
*
* @sets oThis.linkIds
*
* @returns {Promise<void>}
* @private
*/
async _addLink() {
const oThis = this;
if (oThis.link) {
// If new url is added then insert in 2 tables.
const insertRsp = await new UrlModel({}).insertUrl({
url: oThis.link,
kind: urlConstants.socialUrlKind
});
oThis.linkIds = [insertRsp.insertId];
}
}
/**
* Validate and save reply in reply details and related tables.
*
* @returns {Promise<result>}
* @private
*/
async _validateAndSaveReply() {
const oThis = this;
const addVideoParams = {
userId: oThis.currentUser.id,
videoUrl: oThis.videoUrl,
size: oThis.videoSize,
width: oThis.videoWidth,
height: oThis.videoHeight,
duration: oThis.videoDuration,
durationPref: oThis.videoDurationPref,
posterImageUrl: oThis.posterImageUrl,
posterImageSize: oThis.imageSize,
posterImageWidth: oThis.imageWidth,
posterImageHeight: oThis.imageHeight,
isExternalUrl: false,
videoKind: videoConstants.replyVideoKind,
linkIds: oThis.linkIds,
entityKind: replyDetailConstants.videoEntityKind,
parentKind: oThis.parentKind,
parentId: oThis.parentId
};
const resp = await videoLib.validateAndSave(addVideoParams);
if (resp.isFailure()) {
return Promise.reject(resp);
}
return resp.data;
}
/**
* Add reply description in text table and update text id in reply details.
*
*
* @returns {Promise<void>}
* @private
*/
async _addReplyDescription() {
const oThis = this;
const replyDescriptionResp = await new AddReplyDescription({
videoDescription: oThis.videoDescription,
videoId: oThis.videoId,
replyDetailId: oThis.replyDetailId
}).perform();
if (replyDescriptionResp.isFailure()) {
return Promise.reject(replyDescriptionResp);
}
}
/**
* On video post completion.
*
* @returns {Promise<void>}
* @private
*/
async _onVideoPostCompletion() {
const oThis = this;
let parentVideoDetails = {};
if (oThis.parentKind === replyDetailConstants.videoParentKind) {
const videoDetailsByVideoIdsCacheResp = await new VideoDetailsByVideoIdsCache({
videoIds: [oThis.parentId]
}).fetch();
if (videoDetailsByVideoIdsCacheResp.isFailure()) {
return Promise.reject(videoDetailsByVideoIdsCacheResp);
}
parentVideoDetails = videoDetailsByVideoIdsCacheResp.data[oThis.parentId];
}
let isReplyFree = 0;
if (
CommonValidators.validateZeroWeiValue(parentVideoDetails.perReplyAmountInWei) ||
parentVideoDetails.creatorUserId === oThis.currentUser.id
) {
isReplyFree = 1;
} else {
// Look if creator has already replied on this post
const cacheResp = await new VideoDistinctReplyCreatorsCache({ videoIds: [parentVideoDetails.videoId] }).fetch();
if (cacheResp.isFailure()) {
return Promise.reject(cacheResp);
}
const videoCreatorsMap = cacheResp.data;
// If map is not empty then look for reply creator in that list
const replyCreators = videoCreatorsMap[parentVideoDetails.videoId];
if (CommonValidators.validateNonEmptyObject(replyCreators)) {
// If reply creators is present and creator is already in it, then user can reply free
isReplyFree = replyCreators[oThis.currentUser.id] || 0;
}
}
if (isReplyFree) {
await new ReplyVideoPostTransaction({
currentUserId: oThis.currentUser.id,
replyCreatorUserId: oThis.currentUser.id,
replyDetailId: oThis.replyDetailId,
videoId: oThis.parentId,
pepoAmountInWei: 0
}).perform();
}
}
} |
JavaScript | class Service {
/**
* Service constructor.
*
* @param name Service name.
* @param definition Method a resolve service.
* @param shared Resolve service once (singleton).
*/
constructor(name, definition, shared = false) {
/**
* Service name.
*/
this.name = null;
/**
* Method a resolve service.
*/
this.definition = null;
/**
* Resolve service once (singleton).
*/
this.shared = false;
this.name = name;
this.definition = definition;
this.shared = shared;
}
} |
JavaScript | class IframeView extends View {
/**
* Creates a new instance of the iframe view.
*
* @param {module:utils/locale~Locale} [locale] The locale instance.
*/
constructor( locale ) {
super( locale );
const bind = this.bindTemplate;
this.setTemplate( {
tag: 'iframe',
attributes: {
class: [
'ck',
'ck-reset_all'
],
// It seems that we need to allow scripts in order to be able to listen to events.
// TODO: Research that. Perhaps the src must be set?
sandbox: 'allow-same-origin allow-scripts'
},
on: {
load: bind.to( 'loaded' )
}
} );
}
/**
* Renders the iframe's {@link #element} and returns a `Promise` for asynchronous
* child `contentDocument` loading process.
*
* @returns {Promise} A promise which resolves once the iframe `contentDocument` has
* been {@link #event:loaded}.
*/
render() {
return new Promise( resolve => {
this.on( 'loaded', resolve );
super.render();
} );
}
} |
JavaScript | class Show {
/**
* @param {RouteController} routeController The route controlles of this class
* @param {?Object} data The data to patch into this object
*/
constructor(routeController, data) {
this.routeController = routeController;
Object.defineProperty(this, 'routeController', { enumerable: false });
if (data) this._patch(data);
}
/**
* Patch data into this class
* @param {Object} data The data to patch
* @return {Show} The show with all fetched details
* @private
*/
_patch(data) {
/**
* The ID of the show
* @type {string}
*/
this.id = data._id;
/**
* The IMDB ID of the show
* @type {string}
*/
this.imdbID = data.imdb_id;
/**
* The TVDB ID of the show
* @type {string}
*/
this.tvdbID = data.tvdb_id;
/**
* The title of the show
* @type {string}
*/
this.title = data.title;
/**
* The year the show was released
* @type {string}
*/
this.year = data.year;
/**
* The name of the show for URLs
* @type {string}
*/
this.slug = data.slug;
/**
* The images of the show
* @type {Object}
* @prop {?string} poster The poster image
* @prop {?string} fanart The fanart image
* @prop {?string} banner The banner image
*/
this.images = data.images;
/**
* The ratings of the show
* @type {Object}
* @prop {?number} percentage The total percentage of rates
* @prop {?number} watching The total of watching rates
* @prop {?number} votes The total of votes
* @prop {?number} loved The total of love rates
* @prop {?number} hated The total of hate rates
*/
this.rating = data.rating;
/**
* The number of seasons the movie has
* @type {number}
*/
this.numSeasons = data.num_seasons;
/**
* The episodes of the show
* @type {Episode[]}
*/
this.episodes = [];
/**
* The seasons of the show
* @type {Season[]}
*/
this.seasons = [];
if (data.details) {
/**
* The current status of the show
* @type {string}
*/
this.status = data.status;
/**
* The synopsis of the show
* @type {string}
*/
this.synopsis = data.synopsis;
/**
* The duration of each episode in minutes
* @type {string}
*/
this.runtime = data.runtime;
/**
* The country of the show
* @type {string}
*/
this.country = data.country;
/**
* The network the movie is released on
* @type {string}
*/
this.network = data.network;
/**
* The day each episode is released
* @type {string}
*/
this.airDay = data.air_day;
/**
* The hour each episode is released
* @type {string}
*/
this.airTime = data.air_time;
/**
* The last time the show was updated
* @type {string}
*/
this.lastUpdatedTimestamp = data.last_updated;
/**
* The genres of the show
* @type {string[]}
*/
this.genres = data.genres;
/**
* The images of the show
* @type {Images}
*/
this.images = data.images;
/**
* The rating of the show
* @type {Rating}
*/
this.rating = data.rating;
this.episodes = data.episodes.map(e => new Episode(e));
for (let number = 1; number <= this.numSeasons; number++)
this.seasons.push(new Season({
number,
episodes: this.episodes.filter(e => e.season == number)
}));
}
return this
}
/**
* Fetch the details of this show
* @returns {Promise<Show>} The show with all fetched details
*/
async fetch() {
const data = await this.routeController._rawDetails(this);
return this._patch(data);
}
/**
* The date of the last time this show was updated
* @type {?Date}
* @readonly
*/
get lastUpdatedAt() {
return this.lastUpdatedTimestamp ? new Date(this.lastUpdatedTimestamp) : null
}
} |
JavaScript | class NetworkQualityStats {
/**
* Construct a {@link NetworkQualityStats}.
* @param {NetworkQualityLevels} networkQualityLevels
*/
constructor({ level, audio, video }) {
Object.defineProperties(this, {
level: {
value: level,
enumerable: true
},
audio: {
value: audio ? new NetworkQualityAudioStats(audio) : null,
enumerable: true
},
video: {
value: video ? new NetworkQualityVideoStats(video) : null,
enumerable: true
}
});
}
} |
JavaScript | class CreateControlActionButton extends Component {
state = {
open: false,
};
handleClick = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const { classes } = this.props;
return (
<React.Fragment>
<Fab
className={classes.root}
color="primary"
onClick={this.handleClick}
>
<AddIcon />
</Fab>
<CreateControlActionForm
open={this.state.open}
onClose={this.handleClose}
/>
</React.Fragment>
);
}
} |
JavaScript | class LoaderBuilder {
/**
* @param {!AmpElement} element
* @param {number} elementWidth
* @param {number} elementHeight
*/
constructor(element, elementWidth, elementHeight) {
/** @private @const {!AmpElement} */
this.element_ = element;
/** @private @const {number} */
this.layoutWidth_ = elementWidth;
/** @private @const {number} */
this.layoutHeight_ = elementHeight;
/** @private {?Element} */
this.domRoot_;
/** @private {?Element} */
this.svgRoot_;
}
/**
* Builds the loader's DOM and returns the element.
* @return {!Element} new loader root element
*/
build() {
this.buildContainers_();
this.maybeAddDefaultPlaceholder_();
this.maybeAddLoaderAnimation_();
return dev().assertElement(this.domRoot_);
}
/**
* Builds the wrappers for the loader.
* @private
*/
buildContainers_() {
const html = htmlFor(this.element_);
this.domRoot_ = html`
<div class="i-amphtml-new-loader">
<div>
<svg
ref="svgRoot"
xmlns="http://www.w3.org/2000/svg"
viewBox="24 24 72 72"
></svg>
</div>
</div>
`;
/**
* There is an extra inner div here for backward compatibility with
* customizing loaders. The common and documented CSS for customizing
* loaders includes a style to hide the old three dots via:
* .my-custom-loader .amp-active > div {
* display: none;
* }
* The extra div mimic a similar DOM.
*/
this.svgRoot_ = dev().assertElement(htmlRefs(this.domRoot_)['svgRoot']);
}
/**
* Adds a combination of spinner/logo if element is eligible based on
* certain heuristics.
*/
maybeAddLoaderAnimation_() {
// If very small or already has image placeholder, no loader animation.
if (this.isTiny_() || this.hasBlurryImagePlaceholder_()) {
return;
}
this.setSize_();
this.maybeAddBackgroundShim_();
this.addSpinnerAndLogo_();
}
/**
* Sets the size of the loader based element's size and a few special cases.
* @private
*/
setSize_() {
const sizeClassDefault = 'i-amphtml-new-loader-size-default';
const sizeClassSmall = 'i-amphtml-new-loader-size-small';
const sizeClassLarge = 'i-amphtml-new-loader-size-large';
// Ads always get the default spinner regardless of the element size
if (this.isAd_()) {
return this.domRoot_.classList.add(sizeClassDefault);
}
// Other than Ads, small spinner is always used if element is small.
if (this.isSmall_()) {
return this.domRoot_.classList.add(sizeClassSmall);
}
// If host is not small, default size spinner is normally used
// unless due to branding guidelines (e.g. Instagram) a larger spinner is
// required.
if (this.requiresLargeSpinner_()) {
return this.domRoot_.classList.add(sizeClassLarge);
}
return this.domRoot_.classList.add(sizeClassDefault);
}
/**
* Adds the background shim under the loader for cases where loader is on
* top of an image.
* @private
*/
maybeAddBackgroundShim_() {
if (!this.requiresBackgroundShim_()) {
return;
}
const svg = svgFor(this.element_);
const shimNode = svg`
<circle
class="i-amphtml-new-loader-shim"
cx="60"
cy="60"
>
</circle>
`;
// Note that logo colors gets overwritten when logo is on top of the
// background shim (when there is image placeholder).
// This is done in CSS. See `i-amphtml-new-loader-has-shim` CSS for details.
this.domRoot_.classList.add('i-amphtml-new-loader-has-shim');
this.svgRoot_.appendChild(shimNode);
}
/**
* Adds the spinner.
* @private
*/
addSpinnerAndLogo_() {
const logo = this.getLogo_();
const color = logo ? logo.color : DEFAULT_LOGO_SPINNER_COLOR;
const spinner = this.getSpinner_(color);
if (logo) {
const svg = svgFor(this.element_);
const logoWrapper = svg`<g class="i-amphtml-new-loader-logo"></g>`;
if (logo.isDefault) {
// default logo is special because it fades away.
logoWrapper.classList.add('i-amphtml-new-loader-logo-default');
}
logoWrapper.appendChild(logo.svg);
this.svgRoot_.appendChild(logoWrapper);
}
this.svgRoot_.appendChild(spinner);
}
/**
* @param {string} color
*/
getSpinner_(color) {
const svg = svgFor(this.element_);
const spinnerWrapper = svg`
<g class="i-amphtml-new-loader-spinner">
`;
for (let i = 0; i < 4; i++) {
const spinnerSegment = svg`
<circle class="i-amphtml-new-loader-spinner-segment" cx="60" cy="60">
</circle>
`;
spinnerSegment.setAttribute('stroke', color);
spinnerWrapper.appendChild(spinnerSegment);
}
return spinnerWrapper;
}
/**
* Adds the default or branded logo.
* @private
*/
getLogo_() {
const customLogo = this.getCustomLogo_();
const useDefaultLogo = !customLogo;
const logo = customLogo || this.getDefaultLogo_();
// Ads always get the logo regardless of size
if (this.isAd_()) {
return logo;
}
// Small hosts do not get a logo
if (this.isSmall_()) {
return;
}
// If element requires a background shim but logo is the default logo,
// we don't show the logo.
if (this.requiresBackgroundShim_() && useDefaultLogo) {
return;
}
return {
svg: logo,
color: logo.getAttribute('fill') || DEFAULT_LOGO_SPINNER_COLOR,
isDefault: useDefaultLogo,
};
}
/**
* Add a gray default placeholder if there isn't a placeholder already and
* other special cases.
* @private
*/
maybeAddDefaultPlaceholder_() {
const hasPlaceholder = !!this.element_.getPlaceholder();
const hasPoster = this.element_.hasAttribute('poster');
if (hasPlaceholder || hasPoster) {
return;
}
// Is it whitelisted for default placeholder?
const tagName = this.element_.tagName.toUpperCase();
if (
DEFAULT_PLACEHOLDER_WHITELIST_NONE_VIDEO[tagName] || // static white list
isIframeVideoPlayerComponent(tagName) // regex for various video players
) {
const html = htmlFor(this.element_);
const defaultPlaceholder = html`
<div placeholder class="i-amphtml-default-placeholder"></div>
`;
this.element_.appendChild(defaultPlaceholder);
}
}
/**
* Returns the custom logo for the element if there is one.
* @private
* @return {?Element}
*/
getCustomLogo_() {
// Keeping the video logo here short term.
// This is because there is no single CSS for all players, there is
// video-interface but not all players implement it. Also the SVG is not
// that big.
// We need to move most of loaders code out of v0 anyway, see
// https://github.com/ampproject/amphtml/issues/23108.
if (isIframeVideoPlayerComponent(this.element_.tagName)) {
const svg = svgFor(this.element_);
const color = DEFAULT_LOGO_SPINNER_COLOR;
const svgNode = svg`
<path
class="i-amphtml-new-loader-white-on-shim"
d="M65,58.5V55c0-0.5-0.4-1-1-1H51c-0.5,0-1,0.5-1,1v10c0,0.6,0.5,1,1,1h13c0.6,0,1-0.4,1-1v-3.5l5,4v-11L65,58.5z"
></path>
`;
svgNode.setAttribute('fill', color);
return svgNode;
}
const customLogo = this.element_.createLoaderLogo();
return customLogo || null;
}
/**
* Returns the default logo.
* @private
* @return {!Element}
*/
getDefaultLogo_() {
const svg = svgFor(this.element_);
const svgNode = svg`
<circle
cx="60"
cy="60"
r="12"
>
</circle>
`;
svgNode.setAttribute('fill', DEFAULT_LOGO_SPINNER_COLOR);
return svgNode;
}
/**
* Whether the element is an Ad.
* @private
* @return {boolean}
*/
isAd_() {
// Not Implemented
return false;
}
/**
* Whether the element is small.
* Small elements get a different loader with does not have a logo and is
* just a spinner.
* @private
* @return {boolean}
*/
isSmall_() {
return (
!this.isTiny_() && (this.layoutWidth_ <= 100 || this.layoutHeight_ <= 100)
);
}
/**
* Very small layout are not eligible for new loaders.
* @return {boolean}
*/
isTiny_() {
return this.layoutWidth_ < 50 || this.layoutHeight_ < 50;
}
/**
* Whether element has an image blurry placeholder
* @return {boolean}
*/
hasBlurryImagePlaceholder_() {
const placeholder = this.element_.getPlaceholder();
return (
placeholder &&
placeholder.classList.contains('i-amphtml-blurry-placeholder')
);
}
/**
* Whether loaders needs the translucent background shim, this is normally
* needed when the loader is on top of an image placeholder:
* - placeholder is `amp-img` or `img` (`img` handles component
* placeholders like `amp-youtube`)
* - Element has implicit placeholder like a `poster` on video
* @private
* @return {boolean}
*/
requiresBackgroundShim_() {
if (this.element_.hasAttribute('poster')) {
return true;
}
const placeholder = this.element_.getPlaceholder();
if (!placeholder) {
return false;
}
if (placeholder.tagName == 'AMP-IMG' || placeholder.tagName == 'IMG') {
return true;
}
return false;
}
/**
* Some components such as Instagram require larger spinner due to
* branding guidelines.
* @private
* @return {boolean}
*/
requiresLargeSpinner_() {
// Not Implemented
return false;
}
} |
JavaScript | class MonacoGoFilesHistory {
constructor() {
this.back = [];
this.forward = [];
}
} |
JavaScript | class Bucket
{
/**
* Class constructor
* @param {number} bucketSize It should be a power of two
* @param {number} windowSize An odd positive number for filtering
*/
constructor(bucketSize = 32, windowSize = 5)
{
// validate parameters
this._bucketSize = 1 << Math.ceil(Math.log2(bucketSize));
this._windowSize = windowSize + (1 - windowSize % 2);
// bucketSize should be a power of 2
if(bucketSize < this._windowSize)
throw new IllegalArgumentError(`Invalid bucketSize of ${bucketSize}`);
// Bucket is implemented as a circular vector
this._head = this._bucketSize - 1;
this._rawData = new Float32Array(this._bucketSize).fill(0);
this._smoothedData = new Float32Array(this._bucketSize).fill(0);
this._average = 0;
this._isSmooth = true;
}
/**
* Put a value in the bucket
* @param {number} value
*/
put(value)
{
this._head = (this._head + 1) & (this._bucketSize - 1);
this._rawData[this._head] = value;
this._isSmooth = false;
}
/**
* Bucket size
* @returns {number}
*/
get size()
{
return this._bucketSize;
}
/**
* Get smoothed average
* @returns {number}
*/
get average()
{
// need to smooth the signal?
if(!this._isSmooth)
this._smooth();
// the median filter does not introduce new data to the signal
// this._average approaches the mean of the distribution as bucketSize -> inf
return this._average;
}
/**
* Fill the bucket with a value
* @param {number} value
*/
fill(value)
{
this._rawData.fill(value);
this._smoothedData.fill(value);
this._average = value;
this._isSmooth = true;
this._head = this._bucketSize - 1;
return this;
}
/**
* Apply the smoothing filter & compute the average
*/
_smooth()
{
// smooth the signal & compute the average
this._average = 0;
for(let i = 0; i < this._bucketSize; i++) {
this._smoothedData[i] = this._median(this._window(i));
this._average += this._smoothedData[i];
}
this._average /= this._bucketSize;
//this._average = this._median(this._rawData);
// the signal has been smoothed
this._isSmooth = true;
}
/**
* Give me a window of size this._windowSize around this._rawData[i]
* @param {number} i central index
* @returns {Float32Array} will reuse the same buffer on each call
*/
_window(i)
{
const arr = this._rawData;
const win = this._win || (this._win = new Float32Array(this._windowSize));
const n = arr.length;
const w = win.length;
const wOver2 = w >> 1;
const head = this._head;
const tail = (head + 1) & (n - 1);
for(let j = 0, k = -wOver2; k <= wOver2; k++) {
let pos = i + k;
// boundary conditions:
// reflect values
if(i <= head){
if(pos > head)
pos = head + (head - pos);
}
else {
if(pos < tail)
pos = tail + (tail - pos);
}
if(pos < 0)
pos += n;
else if(pos >= n)
pos -= n;
win[j++] = arr[pos];
}
return win;
}
/**
* Return the median of a sequence. Do it fast.
* Note: the input is rearranged
* @param {number[]} v sequence
* @returns {number}
*/
_median(v)
{
// fast median search for fixed length vectors
switch(v.length) {
case 1:
return v[0];
case 3:
// v0 v1 v2 [ v0 v1 v2 ]
// \ / \ /
// node node [ min(v0,v1) min(max(v0,v1),v2) max(max(v0,v1),v2) ]
// \ /
// node [ min(min(v0,v1),min(max(v0,v1),v2)) max(min(...),min(...)) max(v0,v1,v2) ]
// |
// median [ min(v0,v1,v2) median max(v0,v1,v2) ]
if(v[0] > v[1]) [v[0], v[1]] = [v[1], v[0]];
if(v[1] > v[2]) [v[1], v[2]] = [v[2], v[1]];
if(v[0] > v[1]) [v[0], v[1]] = [v[1], v[0]];
return v[1];
case 5:
if(v[0] > v[1]) [v[0], v[1]] = [v[1], v[0]];
if(v[3] > v[4]) [v[3], v[4]] = [v[4], v[3]];
if(v[0] > v[3]) [v[0], v[3]] = [v[3], v[0]];
if(v[1] > v[4]) [v[1], v[4]] = [v[4], v[1]];
if(v[1] > v[2]) [v[1], v[2]] = [v[2], v[1]];
if(v[2] > v[3]) [v[2], v[3]] = [v[3], v[2]];
if(v[1] > v[2]) [v[1], v[2]] = [v[2], v[1]];
return v[2];
case 7:
if(v[0] > v[5]) [v[0], v[5]] = [v[5], v[0]];
if(v[0] > v[3]) [v[0], v[3]] = [v[3], v[0]];
if(v[1] > v[6]) [v[1], v[6]] = [v[6], v[1]];
if(v[2] > v[4]) [v[2], v[4]] = [v[4], v[2]];
if(v[0] > v[1]) [v[0], v[1]] = [v[1], v[0]];
if(v[3] > v[5]) [v[3], v[5]] = [v[5], v[3]];
if(v[2] > v[6]) [v[2], v[6]] = [v[6], v[2]];
if(v[2] > v[3]) [v[2], v[3]] = [v[3], v[2]];
if(v[3] > v[6]) [v[3], v[6]] = [v[6], v[3]];
if(v[4] > v[5]) [v[4], v[5]] = [v[5], v[4]];
if(v[1] > v[4]) [v[1], v[4]] = [v[4], v[1]];
if(v[1] > v[3]) [v[1], v[3]] = [v[3], v[1]];
if(v[3] > v[4]) [v[3], v[4]] = [v[4], v[3]];
return v[3];
default:
v.sort((a, b) => a - b);
return (v[(v.length - 1) >> 1] + v[v.length >> 1]) / 2;
}
}
} |
JavaScript | class BModel{
//lines= [startline,endline,totallines]
constructor(ln){ this._lines=ln }
lines(){ return this._lines }
} |
JavaScript | class ElModel extends BModel{
constructor(){
super([0,1,2]);
/*
[[0,0,1],
[1,1,1],
[0,0,0]]
*/
}
clone(){
let n,c=_.randItem(COLORS);
if(_.randSign()>0){_.swap(c,0,1)}
n=null;
return [[n, n, _sp(c[1])],
[_sp(c[0]),_sp(c[1]),_sp(c[0])],
[n,n,n]]
}
} |
JavaScript | class UiSpacer extends LitElement {
constructor() {
super()
this.height = '1em'
}
static get properties() {
return { height: { type: String } }
}
/*
* Change CSS properties based on properties of the component that can be
* changed during runtime
*/
computeVars(height) {
const vars = { '--height': height }
return Object.keys(vars).map(key => [key, vars[key]].join(':')).join(';')
}
render() {
const { height } = this
return html`
<style>
div {
width: 100%;
height: var(--height);
}
</style>
<div style="${this.computeVars(height)}"></div>
`
}
} |
JavaScript | class PrependManifestPlugin extends BasePlugin {
/**
* Create a new instance of `PrependManifestPlugin`.
*
* @param {Object} [config] All the options as passed to
* [workbox-build:getFileManifestEntries]{@link
* module:workbox-build.injectManifest}. See
* [workbox-build:getFileManifestEntries]{@link
* module:workbox-build.injectManifest} for all possible options.
* @param {String} [config.swSrc] When invalid, compilation throws an error.
* @param {String} [config.swDest] Defaults to `%{outputPath}/sw.js`.
*/
constructor(config) {
super(config);
}
/**
* @private
* @param {Object} compilation The [compilation](https://github.com/webpack/docs/wiki/how-to-write-a-plugin#accessing-the-compilation),
* passed from Webpack to this plugin.
* @throws Throws an error if `swSrc` option is invalid.
* @return {Object} The configuration for a given compilation.
*/
getConfig(compilation) {
const config = super.getConfig(compilation);
if (!config.swSrc) {
throw new Error(errors["invalid-sw-src"]);
}
if (!config.swDest) {
config.swDest = path.join(compilation.options.output.path, "sw.js");
}
return config;
}
/**
* This method uses [workbox-build:injectManifest]{
* @link module:workbox-build.injectManifest} to generate a manifest file.
*
* @private
* @param {Object} compilation The [compilation](https://github.com/webpack/docs/wiki/how-to-write-a-plugin#accessing-the-compilation),
* @param {Function} [callback] function that must be invoked when handler
* finishes running.
*/
handleAfterEmit(compilation, callback) {
try {
const config = this.getConfig(compilation);
swBuild
.prependManifest(config)
.then(() => callback())
.catch(e => callback(e));
} catch (e) {
callback(e);
}
}
} |
JavaScript | class QuestionPanel {
constructor(scene, x, y, gamePhase, questionNo, mainTxt) {
this.scene = scene;
var buttonTxt = 'enter answer';
var mainPanel = createMainPanel(scene, gamePhase, questionNo, mainTxt, buttonTxt)
.setPosition(x,y)
.layout()
//.drawBounds(scene.add.graphics(), 0xff0000) //for debugging only
//.setScrollFactor(0); //fix on screen [problematic with scrolling world]
.popUp(500);
}
} |
JavaScript | class StropheLogger extends ConnectionPlugin {
/**
*
*/
constructor() {
super();
this.log = [];
}
/**
*
* @param connection
*/
init(connection) {
super.init(connection);
this.connection.rawInput = this.logIncoming.bind(this);
this.connection.rawOutput = this.logOutgoing.bind(this);
}
/**
*
* @param stanza
*/
logIncoming(stanza) {
this.log.push([ new Date().getTime(), 'incoming', stanza ]);
}
/**
*
* @param stanza
*/
logOutgoing(stanza) {
this.log.push([ new Date().getTime(), 'outgoing', stanza ]);
}
} |
JavaScript | class Generator {
static generate (el, binding, vnode, options = {}) {
const model = Generator.resolveModel(binding, vnode);
return {
name: Generator.resolveName(el, vnode),
el: el,
listen: !binding.modifiers.disable,
scope: Generator.resolveScope(el, binding),
vm: vnode.context,
expression: binding.value,
component: vnode.child,
classes: options.classes,
classNames: options.classNames,
getter: Generator.resolveGetter(el, vnode, model),
events: Generator.resolveEvents(el, vnode) || options.events,
model,
delay: Generator.resolveDelay(el, vnode, options),
rules: getRules(binding, el),
initial: !!binding.modifiers.initial,
invalidateFalse: !!(el && el.type === 'checkbox'),
alias: Generator.resolveAlias(el, vnode),
};
}
/**
* Resolves the delay value.
* @param {*} el
* @param {*} vnode
* @param {Object} options
*/
static resolveDelay (el, vnode, options = {}) {
return getDataAttribute(el, 'delay') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-delay']) || options.delay;
}
/**
* Resolves the alias for the field.
* @param {*} el
* @param {*} vnode
*/
static resolveAlias (el, vnode) {
return getDataAttribute(el, 'as') || (vnode.child && vnode.child.$attrs && vnode.child.$attrs['data-vv-as']) || el.title || null;
}
/**
* Resolves the events to validate in response to.
* @param {*} el
* @param {*} vnode
*/
static resolveEvents (el, vnode) {
if (vnode.child) {
return getDataAttribute(el, 'validate-on') || (vnode.child.$attrs && vnode.child.$attrs['data-vv-validate-on']);
}
return getDataAttribute(el, 'validate-on');
}
/**
* Resolves the scope for the field.
* @param {*} el
* @param {*} binding
*/
static resolveScope (el, binding) {
return (isObject(binding.value) ? binding.value.scope : getScope(el));
}
/**
* Checks if the node directives contains a v-model or a specified arg.
* Args take priority over models.
*
* @return {Object}
*/
static resolveModel (binding, vnode) {
if (binding.arg) {
return binding.arg;
}
if (isObject(binding.value) && binding.value.arg) {
return binding.value.arg;
}
const model = vnode.data.model || find(vnode.data.directives, d => d.name === 'model');
if (!model) {
return null;
}
const watchable = /^[a-z_]+[0-9]*(\w*\.[a-z_]\w*)*$/i.test(model.expression) && hasPath(model.expression, vnode.context);
if (!watchable) {
return null;
}
return model.expression;
}
/**
* Resolves the field name to trigger validations.
* @return {String} The field name.
*/
static resolveName (el, vnode) {
if (vnode.child) {
return getDataAttribute(el, 'name') || (vnode.child.$attrs && (vnode.child.$attrs['data-vv-name'] || vnode.child.$attrs['name'])) || vnode.child.name;
}
return getDataAttribute(el, 'name') || el.name;
}
/**
* Returns a value getter input type.
*/
static resolveGetter (el, vnode, model) {
if (model) {
return () => {
return getPath(model, vnode.context);
};
}
if (vnode.child) {
return () => {
const path = getDataAttribute(el, 'value-path') || (vnode.child.$attrs && vnode.child.$attrs['data-vv-value-path']);
if (path) {
return getPath(path, vnode.child);
}
return vnode.child.value;
};
}
switch (el.type) {
case 'checkbox': return () => {
let els = document.querySelectorAll(`input[name="${el.name}"]`);
els = toArray(els).filter(el => el.checked);
if (!els.length) return undefined;
return els.map(checkbox => checkbox.value);
};
case 'radio': return () => {
const els = document.querySelectorAll(`input[name="${el.name}"]`);
const elm = find(els, el => el.checked);
return elm && elm.value;
};
case 'file': return (context) => {
return toArray(el.files);
};
case 'select-multiple': return () => {
return toArray(el.options).filter(opt => opt.selected).map(opt => opt.value);
};
default: return () => {
return el && el.value;
};
}
}
} |
JavaScript | class Node {
constructor (data) {
this.data = data
this.next = null
}
} |
JavaScript | class DOMObserver {
constructor() {
throw new Error("Static class");
}
/**
* This function abstracts out mutation observer usage inside shadow DOM.
* For native shadow DOM the native mutation observer is used.
* When the polyfill is used, the observeChildren ShadyDOM method is used instead.
*
* @throws Exception
* Note: does not allow several mutation observers per node. If there is a valid use-case, this behavior can be changed.
*
* @param node
* @param callback
* @param options - Only used for the native mutation observer
*/
static observeDOMNode(node, callback, options) {
let observerObject = observers.get(node);
if (observerObject) {
throw new Error("A mutation/ShadyDOM observer is already assigned to this node.");
}
if (w.ShadyDOM) {
observerObject = w.ShadyDOM.observeChildren(node, callback);
} else {
observerObject = new MutationObserver(callback);
observerObject.observe(node, options);
}
observers.set(node, observerObject);
}
/**
* De-registers the mutation observer, depending on its type
* @param node
*/
static unobserveDOMNode(node) {
const observerObject = observers.get(node);
if (!observerObject) {
return;
}
if (observerObject instanceof MutationObserver) {
observerObject.disconnect();
} else {
w.ShadyDOM.unobserveChildren(observerObject);
}
observers.delete(node);
}
} |
JavaScript | class userActionLogRecStoreType {
constructor(_timeStr, _ip_addr, _action_done, _rollDiam, _diamXdir, _cavityDepth, _calcXval, _calcYmin, _calcYmax, _calcScaleMin, _calcScaleMax){
this.timeStr = _timeStr;
this.ip_addr = _ip_addr;
this.action_done = _action_done;
this.rollDiam = _rollDiam;
this.dimXdir = _diamXdir;
this.cavityDepth = _cavityDepth,
this.calcXval = _calcXval;
this.calcYmin = _calcYmin;
this.calcYmax = _calcYmax;
this.calcScaleMin = _calcScaleMin;
this.calcScaleMax = _calcScaleMax
}
} |
JavaScript | class CoverFormalsTransformerError extends Error {
constructor(location, message) {
this.location = location;
this.message = message;
}
} |
JavaScript | class MyElem extends HTMLElement {
constructor(element) {
// Always call super first in constructor
super();
console.log('created my-elem:', arguments)
// we can't do much in the constructor, really:
// - Don’t add, remove, mutate, or access any attribute inside a constructor
// - Don’t insert, remove, mutate, or access a child
// source: https://webkit.org/blog/7027/introducing-custom-elements/
}
connectedCallback() {
// Called when the custom element is inserted into a document
// this is a safe place to do instance-specific things like
// setting component-level variables or event handlers
this._logMessage('ConnectedCallback called.');
// example of setting an inner style via JS
// will be visible in DOM as inline style
// in a way, this is "scoped styles", a term used in
// several frameworks
this.style.cursor = 'pointer';
}
disconnectedCallback() {
// Called when the custom element is removed from the document
// clean up any event handlers added in connectedCallback here...
this._logMessage('DisconnectedCallback called.');
}
adoptedCallback(oldDocument, newDocument) {
// Called when the custom element is adopted from an old document to a new document.
// I have no idea what this means
this._logMessage('AdoptedCallback called.');
}
static get observedAttributes() {
// The million dollar feature of the custom elements V1 API
// in this API method, you declare the attributes to watch
// in case any change happens to that attribute,
// attributeChangedCallback will be called.
// effectively, this allows for super easy synchronization
// between the DOM and the API
// let's watch our name attribute
// this means that when it changed in markup or via the API,
// the change will be detected
return ['name'];
}
attributeChangedCallback(attr, oldValue, newValue) {
// Called anytime any of our watched attributes changes
// We'll call our own custom method Render in case this happens
this._logMessage('AttributeChangedCallback called.');
}
get name() {
// a getter for an attribute, [name] in this case
// accessing this via element.name will always return the
// most up-to-date value
this._logMessage('Name getter called');
return this.getAttribute('name');
}
set name(val) {
// a setter for an attribute, [name] in this case
// setting this via element.name will trigger
// attributeChangedCallback, which will update
// both the internal value and the DOM
if (val) {
this.setAttribute('name', val);
}
this._logMessage('Name setter called: ' + val);
}
_logMessage(message) {
// Not part of API. Just a custom internal helper method to log component-instance specific
// messages for the sake of diagnostics. the _methodname suggests
// that this is a private method, but this is only a convention
// private methods do not exist in JS classes.
logScreen('my-elem:' + message)
}
} |
JavaScript | class Line extends THREE.Line {
/**
* 光点纹理样式,返回一个纹理 {@link https://threejs.org/docs/#api/textures/Texture|THREE.Texture}
* @returns {THREE.Texture}
* @example
* Line.texture()
*/
static get texture() {
if (!Mark._texture) {
let canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
let context = canvas.getContext("2d");
Mark.draw(context);
let texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
Mark._texture = texture;
}
return Mark._texture;
}
/**
* 光点纹理样式,如果你对canvas熟悉可以重写.否则使用默认样式
* @static
* @param {context} context - Canvas上下文对象
* {@link https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/getContext|Canvas.context}
* @example
*
*/
static draw(context) {
context.clearRect(0, 0, 128, 128);
context.fillStyle = "#ffffff";
context.arc(64, 64, 20, 0, Math.PI * 2, false);
context.fill();
context.fillStyle = "rgba(255,255,255,.5)";
context.arc(64, 64, 60, 0, Math.PI * 2, false);
context.fill();
context.fillStyle = "rgba(0,0,0,1)";
context.arc(64, 64, 80, 0, Math.PI * 2, false);
context.fill();
}
/**
* 创建一条线
* @param {Object} pros - The Line options | 线的配置
* @param {string} pros.color - Line base color | 基线颜色
* @param {string} pros.hoverColor - Line base hoverColor | 线的鼠标移入基线颜色
* @param {number} pros.spaceHeight - Line space height | 曲线空间高度
* @param {boolean} pros.hasHalo - Has light emitting line| 是否有发光线
* @param {boolean} pros.hasHaloAnimate - Has light emitting line Animate| 是否有发光线动画效果
* @param {number} pros.haloDensity - Spot density becomes more dense, more consumption performance | 光点密度 值越大
* 越浓密,越消耗性能
* @param {number} pros.haloRunRate - Light point motion frequency | 光点运动频率
* @param {color} pros.haloColor - Halo line color, default inheritance of color | 发光线颜色,默认继承color
* @param {number} pros.haloSize - Halo line color width | 发光线粗细
*/
constructor(pros) {
let fromCoord = pros.coords[0];
let toCoord = pros.coords[1];
let x1 = fromCoord[0];
let y1 = fromCoord[1];
let x2 = toCoord[0];
let y2 = toCoord[1];
let xdiff = x2 - x1;
let ydiff = y2 - y1;
let dif = Math.pow(xdiff * xdiff + ydiff * ydiff, 0.5); //二点间距离
let v3s = [
new THREE.Vector3(x1, y1, pros.extrudeHeight),
new THREE.Vector3(
(x1 + x2) / 2,
(y1 + y2) / 2,
pros.extrudeHeight + pros.spaceHeight
),
new THREE.Vector3(x2, y2, pros.extrudeHeight)
];
//画弧线
let curve = new THREE.QuadraticBezierCurve3(...v3s);
var geometry = new THREE.Geometry();
var amount = (dif + 0.1) * pros.haloDensity;
if (amount < 30) amount = 30;
geometry.vertices = curve.getPoints(amount).reverse();
geometry.vertices.forEach(() => {
geometry.colors.push(new THREE.Color(0xffffff));
});
let material = new THREE.LineBasicMaterial({
color: pros.color,
opacity: 1.0,
blending: THREE.AdditiveBlending,
transparent: true,
depthWrite: false,
vertexColors: true,
linewidth: 1
});
super(geometry, material);
Object.assign(this.userData, pros);
//线条光晕效果
if (pros.hasHalo) {
this.initHalo(geometry);
}
//当前线条索引
this.index = Line.count++;
Line.array.push(this);
}
/**
* 初始化发光线
* @param {THREE.Geometry} geometry - 通过线条几何体初始化发光线 {@link https://threejs.org/docs/#api/core/Geometry|THREE.Geometry}
* @protected
*/
initHalo(geometry) {
let line = this;
let amount = geometry.vertices.length;
let positions = new Float32Array(amount * 3);
let colors = new Float32Array(amount * 3);
let sizes = new Float32Array(amount);
let vertex = new THREE.Vector3();
let color = new THREE.Color(colorToHex(this.userData.color));
for (let i = 0; i < amount; i++) {
vertex.x = geometry.vertices[i].x;
vertex.y = geometry.vertices[i].y;
vertex.z = geometry.vertices[i].z;
vertex.toArray(positions, i * 3);
color.toArray(colors, i * 3);
sizes[i] = line.userData.haloSize;
}
let psBufferGeometry = new THREE.BufferGeometry();
psBufferGeometry.addAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
psBufferGeometry.addAttribute(
"customColor",
new THREE.BufferAttribute(colors, 3)
);
psBufferGeometry.addAttribute("size", new THREE.BufferAttribute(sizes, 1));
let uniforms = {
amplitude: { value: 1.0 },
color: { value: new THREE.Color(colorToHex(this.userData.haloColor)) },
texture: { value: Line.texture }
};
let shaderMaterial = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader,
blending: THREE.AdditiveBlending,
depthTest: true,
depthWrite: false,
transparent: true
// sizeAttenuation: true,
});
//线条光晕
let halo = new THREE.Points(psBufferGeometry, shaderMaterial);
halo.dynamic = true;
this.add(halo);
this.halo = halo;
halo.update = function() {
if (!line.userData.hasHalo || !line.userData.hasHaloAnimate) return;
let time = Date.now() * 0.005 + line.index * 3;
let geometry = this.geometry;
let attributes = geometry.attributes;
for (let i = 0; i < attributes.size.array.length; i++) {
attributes.size.array[i] =
line.userData.haloSize +
line.userData.haloSize *
Math.sin(line.userData.haloRunRate * i + time);
}
attributes.size.needsUpdate = true;
};
}
/**
* 发光线的动画更新方法
* @private
*/
update() {
this.halo.update();
}
/**
* 修改线颜色
* @param {color} color - 线条颜色
* @example
*
*/
setColor(color, haloColor) {
//基线
if (typeof color !== "undefined")
this.material.color = new THREE.Color(colorToHex(color));
}
/**
* 设置发光线宽度,基线永远是1
* @param {number} size - 发光线粗细大小
*/
setLineWidth(size) {
if (!this.userData.hasHalo) {
console.warn("Setting the LineWidth must be hasHalo:true");
}
//粗细
this.userData.haloSize = size;
}
/**
* 线条鼠标移出事件
*
* @param dispatcher
* @param event
* @protected
* @example
*/
onmouseout(dispatcher, event) {
if (this.userData.hoverExclusive) {
//所有线条回复初始
Line.array.map(line => {
if (line.halo) {
line.halo.visible = true;
}
line.setColor(line.userData.color);
});
}
//选中线条
if (this.userData.hasHalo) {
//粗细
let size = this.userData.haloSize / 1.5;
this.userData.haloSize = size;
}
//颜色
this.setColor(this.userData.color);
dispatcher.dispatchEvent({
type: "mouseout",
target: this,
orgEvent: event
});
}
/**
* 线条鼠标移入事件
* @param dispatcher
* @param event
* @protected
* @example
*/
onmouseover(dispatcher, event) {
if (this.userData.hoverExclusive) {
Line.array.map(line => {
if (line.halo) {
line.halo.visible = false;
}
line.setColor(this.userData.decayColor);
});
}
//选中线条
if (this.userData.hasHalo) {
//修改光点线 大小
let size = this.userData.haloSize * 1.5;
this.userData.haloSize = size;
this.halo.visible = true;
}
//颜色
this.setColor(
this.userData.hoverColor ? this.userData.hoverColor : this.userData.color
);
dispatcher.dispatchEvent({
type: "mouseover",
target: this,
orgEvent: event
});
}
/**
* 线条鼠标单击事件
* @param dispatcher
* @param event
* @protected
* @example
*/
onmousedown(dispatcher, event) {
dispatcher.dispatchEvent({
type: "mousedown",
target: this,
orgEvent: event
});
}
} |
JavaScript | class UsuarioDetalhes extends Component {
state = {
usuario: []
};
async componentDidMount() {
const { id } = this.props.match.params;
const response = await api.get(`/usuarios/${id}`);
this.setState({ usuario: response.data });
}
render() {
return (
<div>
<div className="componentes">
<Header />
<Accordion />
</div>
{/* <div className="navegar"></div> */}
{/* <Breadcrumb tag="nav" listTag="div">
<BreadcrumbItem tag="a" href="/main">
Página Inicial
</BreadcrumbItem>
<BreadcrumbItem active tag="span">
Usuários
</BreadcrumbItem>
</Breadcrumb> */}
<section className="content table-responsive col-sm-12 col-md-12 col-lg-12">
<table className="table table-bordered">
<tbody>
{this.state.usuario.map(usuario => (
<tr key={usuario.usuarioId}>
<tr>
<th>ID</th>
<td>{usuario.usuarioId}</td>
</tr>
<tr>
<th>Nome</th>
<td>{usuario.usuarioNome}</td>
</tr>
<tr>
<th>CPF</th>
<td>{usuario.usuarioCPF}</td>
</tr>
<tr>
<th>Login</th>
<td>{usuario.usuarioLogin}</td>
</tr>
<tr>
<th>Contato</th>
<td>{usuario.usuarioContato}</td>
</tr>
<tr>
<th>Tipo</th>
<td>{usuario.usuarioTipo}</td>
</tr>
</tr>
))}
</tbody>
</table>
</section>
</div>
);
}
} |
JavaScript | class Botmaster extends EventEmitter {
/**
* sets up a botmaster object attached to the correct server if one is set
* as a parameter. If not, it creates its own http server
*
* @param {object} settings
*
* @example
* // attach the botmaster generated server to port 5000 rather than the default 3000
* const botmaster = new Botmaster({
* port: 5000,
* });
*
* @example
* const http = require('http');
*
* const myServer = http.createServer()
* // use my own server rather than letting botmaster creat its own.
* const botmaster = new Botmaster({
* server: myServer,
* });
*/
constructor(settings) {
super();
this.settings = settings || {};
this.__throwPotentialUnsupportedSettingsErrors();
this.__setupServer();
this.middleware = new Middleware(this);
// this is used for mounting routes onto bot classes "mini-apps""
this.__serverRequestListeners = {};
// default useDefaultMountPathPrepend to true
if (this.settings.useDefaultMountPathPrepend === undefined) {
this.settings.useDefaultMountPathPrepend = true;
}
this.bots = [];
}
__throwPotentialUnsupportedSettingsErrors() {
const unsupportedSettings = ['botsSettings', 'app'];
for (const settingName of unsupportedSettings) {
if (this.settings[settingName]) {
throw new TwoDotXError(
`Starting botmaster with ${settingName} ` +
'is no longer supported.');
}
}
}
__setupServer() {
if (this.settings.server && this.settings.port) {
throw new Error(
'IncompatibleArgumentsError: Please specify only ' +
'one of port and server');
}
if (this.settings.server) {
this.server = this.settings.server;
} else {
const port = has(this, 'settings.port')
? this.settings.port
: 3000;
this.server = this.__listen(port);
}
this.__setupServersRequestListeners();
}
__setupServersRequestListeners() {
const nonBotmasterListeners = this.server.listeners('request').slice(0);
this.server.removeAllListeners('request');
this.server.on('request', (req, res) => {
// run botmaster requestListeners first
for (const path in this.__serverRequestListeners) {
if (req.url.indexOf(path) === 0) {
const requestListener = this.__serverRequestListeners[path];
return requestListener.call(this.server, req, res);
}
}
// then run the non-botmaster ones
if (nonBotmasterListeners.length > 0) {
for (const requestListener of nonBotmasterListeners) {
requestListener.call(this.server, req, res);
}
} else {
// just return a 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: `Couldn't ${req.method} ${req.url}` }));
}
});
}
__listen(port) {
const server = http.createServer();
server.listen(port, '0.0.0.0', () => { // running it for the public
const serverMsg = `server parameter not specified. Running new server on port: ${port}`;
debug(serverMsg);
this.emit('listening', serverMsg);
});
return server;
}
/**
* Add an existing bot to this instance of Botmaster
*
* @param {BaseBot} bot the bot object to add to botmaster. Must be from
* a subclass of BaseBot
*
* @return {Botmaster} returns the botmaster object for chaining
*/
addBot(bot) {
if (bot.requiresWebhook) {
const path = this.__getBotWebhookPath(bot);
this.__serverRequestListeners[path] = bot.requestListener;
}
bot.master = this;
this.bots.push(bot);
bot.on('error', (err, update) => {
debug(err.message);
this.emit('error', bot, err, update);
});
debug(`added bot of type: ${bot.type} with id: ${bot.id}`);
return this;
}
__getBotWebhookPath(bot) {
const webhookEndpoint = bot.webhookEndpoint.replace(/^\/|\/$/g, '');
const path = this.settings.useDefaultMountPathPrepend
? `/${bot.type}/${webhookEndpoint}`
: `/${webhookEndpoint}`;
return path;
}
/**
* Extract First bot of given type or provided id.
*
* @param {object} options must be { type: 'someBotType} or { id: someBotId }.
*
* @return {BaseBot} The bot found of a class that inherits of BaseBot
*/
getBot(options) {
if (!options ||
(!options.type && !options.id) ||
(options.type && options.id)) {
throw new Error('\'getBot\' needs exactly one of type or id');
}
if (options.id) {
return find(this.bots, { id: options.id });
}
return find(this.bots, { type: options.type });
}
/**
* Extract all bots of given type.
*
* @param {string} botType (there can be multiple bots of a same type)
*
* @return {Array} Array of bots found
*/
getBots(botType) {
if (typeof botType !== 'string' && !(botType instanceof String)) {
throw new Error('\'getBots\' takes in a string as only parameter');
}
const foundBots = [];
for (const bot of this.bots) {
if (bot.type === botType) {
foundBots.push(bot);
}
}
return foundBots;
}
/**
* Remove an existing bot from this instance of Botmaster
*
* @param {Object} bot
*
* @return {Botmaster} returns the botmaster object for chaining
*/
removeBot(bot) {
if (bot.requiresWebhook) {
const path = this.__getBotWebhookPath(bot);
delete this.__serverRequestListeners[path];
}
remove(this.bots, bot);
bot.removeAllListeners();
debug(`removed bot of type: ${bot.type} with id: ${bot.id}`);
return this;
}
/**
* Add middleware to this botmaster object
* This function is just sugar for `middleware.__use` in them
*
* @param {object} middleware
*
* @example
*
* // The middleware param object is something that looks like this for incoming:
* {
* type: 'incoming',
* name: 'my-incoming-middleware',
* controller: (bot, update, next) => {
* // do stuff with update,
* // call next (or return a promise)
* },
* // includeEcho: true (defaults to false), opt-in to get echo updates
* // includeDelivery: true (defaults to false), opt-in to get delivery updates
* // includeRead: true (defaults to false), opt-in to get user read updates
* }
*
* // and like this for outgoing middleware
*
* {
* type: 'outgoing',
* name: 'my-outgoing-middleware',
* controller: (bot, update, message, next) => {
* // do stuff with message,
* // call next (or return a promise)
* }
* }
*
* @return {Botmaster} returns the botmaster object so you can chain middleware
*
*/
use(middleware) {
this.middleware.__use(middleware);
return this;
}
/**
* Add wrapped middleware to this botmaster instance. Wrapped middleware
* places the incoming middleware at beginning of incoming stack and
* the outgoing middleware at end of outgoing stack.
* This function is just sugar `middleware.useWrapped`.
*
* @param {object} incomingMiddleware
* @param {object} outgoingMiddleware
*
* The middleware objects are as you'd expect them to be (see use)
*
* @return {Botmaster} returns the botmaster object so you can chain middleware
*/
useWrapped(incomingMiddleware, outgoingMiddleware) {
this.middleware.__useWrapped(incomingMiddleware, outgoingMiddleware);
return this;
}
} |
JavaScript | class StandardStatsExtractor {
/**
* Extract round trip time.
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
* @returns {Number|undefined} - Extracted rtt, or undefined if the report isn't of the necessary type.
*/
extractRtt(statsEntry, report) {
return getRTTStandard(statsEntry, report);
}
/**
* Determines whether a TURN server is used.
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
* @returns {Boolean|undefined} - true/false if a TURN server is used/not used in the selected candidate pair, or
* undefined if the report isn't of the necessary type.
*/
isUsingRelay(statsEntry, report) {
return isUsingRelayStandard(statsEntry, report);
}
/**
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
*/
// extractJitter(statsEntry, report) {
// // TODO
// }
/**
* Extract outbound packet data.
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
* @returns {PacketsSummary|undefined} - Packet summary or undefined if the report isn't of the necessary type.
*/
extractOutboundPacketLoss(statsEntry, report) {
return getTotalSentPacketsStandard(statsEntry, report);
}
/**
* Extract inbound packet data.
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
* @returns {PacketsSummary|undefined} - Packet summary or undefined if the report isn't of the necessary type.
*/
extractInboundPacketLoss(statsEntry, report) {
return getTotalReceivedPacketsStandard(statsEntry, report);
}
/**
* Extract the inbound video summary.
*
* @param {Object} statsEntry - Complete rtcstats entry
* @param {Object} report - Individual stat report.
* @returns {VideoSummary|undefined} - Video summary or undefined if the report isn't of the necessary type.
*/
extractInboundVideoSummary(statsEntry, report) {
return getInboundVideoSummaryStandard(statsEntry, report);
}
} |
JavaScript | class MethodScope extends monitor_scope_1.MonitorScope {
/**
* Creates a new method scope
* @param reference the function handle
*/
constructor(reference) {
if (!reference || typeof reference !== 'function') {
throw new Error('MethodScope requires a valid function reference');
}
let name = reference.name;
super(name, {
type: 'method',
reference
});
}
/**
* Creates a new child function scope within a method
* @param reference the function reference
*/
function(reference) {
return this.derive(new function_scope_1.FunctionScope(reference));
}
} |
JavaScript | class SideBar extends Component {
// let user = this.props.user.username ? this.props.user.username : null;
render() {
return (
<div className="Dashboard">
{/* <Row className="row"> */}
<div style={{padding: 0}}>
<Nav vertical className="Menu">
<NavItem style={{ listStyleType: "none" }}>
<IoAndroidContact size={45}/> Welcome {localStorage.getItem('User')}
<hr />
</NavItem >
<NavItem style={{ listStyleType: "none" }}>
<Link to="/createrace"><IoAndroidAddCircle size={30}/> Race</Link>
</NavItem >
{/* <NavItem style={{ listStyleType: "none" }}>
<Link to="/showrace">SHOW</Link>
</NavItem> */}
<NavItem style={{ listStyleType: "none" }}>
<Link to="/scoreboard"><IoClipboard size={30} /> Scoreboard</Link>
</NavItem>
<NavItem style={{ listStyleType: "none" }}>
<Link to="/settings"><IoAndroidSettings size={30} /> Settings</Link>
</NavItem>
<NavItem style={{ listStyleType: "none" }}>
<Link to="/" onClick={() => this.props.signOut()} ><IoLogOut size={30} /> Log Out</Link>
</NavItem>
</Nav>
</div>
{/* <div style={{width: "100%"}}>
{routes.map((route, index) => (
<Route key={index} path={route.path} exact={route.exact} component={route.main} />
))}
</div> */}
{/* </Row> */}
</div>
);
}
} |
JavaScript | class FooterController {
/**
* Show a list of all footers.
* GET footers
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index ({ request, response, auth }) {
try {
const footer = await Footer.findBy('user_id',auth.user.id)
return response.send({footer})
} catch (error) {
return response.status(500).send(error.messaage)
}
}
/**
* Create/save a new footer.
* POST footers
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store ({ request, response }) {
try {
const {data} = request.all()
let footer = await Footer.findBy('user_id',auth.user.id)
if(!footer){
footer = await Footer.create({...data, user_id:auth.user.id})
return response.status(201).send({footer})
}
footer.merge({...data})
await footer.save()
return response.send({footer})
} catch (error) {
console.log(error)
return response.status(500).send(error.messaage)
}
}
/**
* Display a single footer.
* GET footers/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show ({ params, request, response, view }) {
}
/**
* Update footer details.
* PUT or PATCH footers/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update ({ params, request, response }) {
}
/**
* Delete a footer with id.
* DELETE footers/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy ({ params, request, response }) {
try {
const footer = await Footer.findBy('id', params.id)
footer.delete()
return response.status(204).send()
} catch (error) {
return response.status(500).send(error.message)
}
}
} |
JavaScript | class HintBox {
constructor(game, x, y, hint) {
this.game = game;
this.x = x;
this.y = y;
this.hint = hint
this.buildHintBox();
}
buildHintBox() {
var style = {
font: 'bold 14pt Arial',
fill: 'black',
align: 'left',
wordWrap: true,
wordWrapWidth: 800
};
this.hintLabel = this.game.add.text(
this.x,
this.y,
"Hint:",
style
);
style = {
font: 'normal 14pt Arial',
fill: 'black',
align: 'left',
wordWrap: true,
wordWrapWidth: 800
};
this.hintText = this.game.add.text(
this.x + 50,
this.y,
this.hint,
style
);
}
setHint(hint) {
this.hintText.setText(hint);
}
} |
JavaScript | class DataService {
static get serviceFactory() { return () => new this(); }
ngbConstants = ngbConstants;
constructor() {
this._serverUrl = this.ngbConstants.urlPrefix;
if (this._serverUrl[this._serverUrl.length - 1] !== '/'){
this._serverUrl += '/';
}
}
/**
*
* @param url
* @param config
* @returns {promise}
*/
get(url, config) { return this.callMethod('get', url, config); }
/**
*
* @param url
* @param data
* @param config
* @returns {promise}
*/
put(url, data, config = {}) { return this.callMethod('put', url, data, config); }
/**
*
* @param url
* @param data
* @param config
* @returns {promise}
*/
post(url, data, config = {}) { return this.callMethod('post', url, data, config); }
/**
*
* @param url
* @param data
* @param config
* @returns {promise}
*/
delete(url, data, config = {}) { return this.callMethod('delete', url, data, config); }
callMethod(method, url, ...rest) {
return $http(method, this._serverUrl + url, ...rest)
.then((xhr) =>
(xhr.response && xhr.response.status === 'OK')
? xhr.response.payload
: Promise.reject(xhr.response));
}
} |
JavaScript | class SplitterPanel {
constructor(childContainers, stackedVertical) {
this.childContainers = childContainers;
this.stackedVertical = stackedVertical;
this.panelElement = document.createElement('div');
this.spiltterBars = [];
this._buildSplitterDOMAndAddElements();
}
_buildSplitterDOMAndAddElements() {
if (this.childContainers.length <= 1)
throw new Error('Splitter panel should contain atleast 2 panels');
this.spiltterBars = [];
let afterElement = null;
for (let i = 0; i < this.childContainers.length - 1; i++) {
let previousContainer = this.childContainers[i];
let nextContainer = this.childContainers[i + 1];
let splitterBar = new SplitterBar(previousContainer, nextContainer, this.stackedVertical);
this.spiltterBars.push(splitterBar);
// Add the container and split bar to the panel's base div element
if (!Array.from(this.panelElement.children).includes(previousContainer.containerElement))
this._insertContainerIntoPanel(previousContainer, afterElement);
this.panelElement.insertBefore(splitterBar.barElement, previousContainer.containerElement.nextSibling);
afterElement = splitterBar.barElement;
}
let last = this.childContainers.slice(-1)[0];
if (!Array.from(this.panelElement.children).includes(last.containerElement))
this._insertContainerIntoPanel(last, afterElement);
}
performLayout(children, relayoutEvenIfEqual) {
let containersEqual = Utils.arrayEqual(this.childContainers, children);
if (!containersEqual || relayoutEvenIfEqual) {
this.childContainers.forEach((container) => {
if (!children.some((item) => item == container)) {
if (container.containerElement) {
container.containerElement.classList.remove('splitter-container-vertical');
container.containerElement.classList.remove('splitter-container-horizontal');
Utils.removeNode(container.containerElement);
}
}
});
this.spiltterBars.forEach((bar) => { Utils.removeNode(bar.barElement); });
// rebuild
this.childContainers = children;
this._buildSplitterDOMAndAddElements();
}
}
removeFromDOM() {
this.childContainers.forEach((container) => {
if (container.containerElement) {
container.containerElement.classList.remove('splitter-container-vertical');
container.containerElement.classList.remove('splitter-container-horizontal');
Utils.removeNode(container.containerElement);
}
});
this.spiltterBars.forEach((bar) => { Utils.removeNode(bar.barElement); });
}
destroy() {
this.removeFromDOM();
this.panelElement.parentNode.removeChild(this.panelElement);
}
_insertContainerIntoPanel(container, afterElement) {
if (!container) {
console.error('container is undefined');
return;
}
if (container.containerElement.parentNode != this.panelElement) {
Utils.removeNode(container.containerElement);
if (afterElement)
this.panelElement.insertBefore(container.containerElement, afterElement.nextSibling);
else {
if (this.panelElement.children.length > 0)
this.panelElement.insertBefore(container.containerElement, this.panelElement.children[0]);
else
this.panelElement.appendChild(container.containerElement);
}
}
container.containerElement.classList.add(this.stackedVertical ? 'splitter-container-vertical' : 'splitter-container-horizontal');
}
/**
* Sets the percentage of space the specified [container] takes in the split panel
* The percentage is specified in [ratio] and is between 0..1
*/
setContainerRatio(container, ratio) {
let splitPanelSize = this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth;
let newContainerSize = splitPanelSize * ratio;
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let otherPanelSizeQuota = splitPanelSize - newContainerSize - barSize * this.spiltterBars.length;
let otherPanelScaleMultipler = otherPanelSizeQuota / splitPanelSize;
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let size;
if (child !== container) {
size = this.stackedVertical ? child.containerElement.parentElement.clientHeight : child.containerElement.parentElement.clientWidth;
size *= otherPanelScaleMultipler;
}
else
size = newContainerSize;
if (this.stackedVertical)
child.resize(child.width, Math.floor(size));
else
child.resize(Math.floor(size), child.height);
}
}
getRatios() {
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let splitPanelSize = (this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth) - barSize * this.spiltterBars.length;
let result = [];
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let sizeOld = this.stackedVertical ? child.containerElement.clientHeight : child.containerElement.clientWidth;
result.push(sizeOld / splitPanelSize);
}
return result;
}
setRatios(ratios) {
let barSize = this.stackedVertical ? this.spiltterBars[0].barElement.clientHeight : this.spiltterBars[0].barElement.clientWidth;
let splitPanelSize = (this.stackedVertical ? this.panelElement.clientHeight : this.panelElement.clientWidth) - barSize * this.spiltterBars.length;
for (let i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
let size = splitPanelSize * ratios[i];
if (this.stackedVertical)
child.resize(child.width, Math.floor(size));
else
child.resize(Math.floor(size), child.height);
}
}
resize(width, height) {
if (this.childContainers.length <= 1)
return;
let i;
// Adjust the fixed dimension that is common to all (i.e. width, if stacked vertical; height, if stacked horizontally)
for (i = 0; i < this.childContainers.length; i++) {
let childContainer = this.childContainers[i];
if (this.stackedVertical)
childContainer.resize(width, !childContainer.height ? height : childContainer.height);
else
childContainer.resize(!childContainer.width ? width : childContainer.width, height);
if (i < this.spiltterBars.length) {
let splitBar = this.spiltterBars[i];
if (this.stackedVertical)
splitBar.barElement.style.width = width + 'px';
else
splitBar.barElement.style.height = height + 'px';
}
}
// Adjust the varying dimension
let totalChildPanelSize = 0;
// Find out how much space existing child containers take up (excluding the splitter bars)
this.childContainers.forEach((container) => {
let size = this.stackedVertical ?
container.height :
container.width;
totalChildPanelSize += size;
});
const barRect = this.spiltterBars[0].barElement.getBoundingClientRect();
// Get the thickness of the bar
let barSize = this.stackedVertical ? barRect.height : barRect.width;
// Find out how much space existing child containers will take after being resized (excluding the splitter bars)
let targetTotalChildPanelSize = this.stackedVertical ? height : width;
targetTotalChildPanelSize -= barSize * this.spiltterBars.length;
// Get the scale multiplier
totalChildPanelSize = Math.max(totalChildPanelSize, 1);
let scaleMultiplier = targetTotalChildPanelSize / totalChildPanelSize;
// Update the size with this multiplier
let updatedTotalChildPanelSize = 0;
for (i = 0; i < this.childContainers.length; i++) {
let child = this.childContainers[i];
if (child.containerElement.style.display == 'none')
child.containerElement.style.display = 'block';
let original = this.stackedVertical ? child.containerElement.clientHeight : child.containerElement.clientWidth;
let newSize = scaleMultiplier > 1 ? Math.floor(original * scaleMultiplier) : Math.ceil(original * scaleMultiplier);
updatedTotalChildPanelSize += newSize;
// If this is the last node, add any extra pixels to fix the rounding off errors and match the requested size
if (i === this.childContainers.length - 1)
newSize += targetTotalChildPanelSize - updatedTotalChildPanelSize;
// Set the size of the panel
if (this.stackedVertical)
child.resize(child.width, newSize);
else
child.resize(newSize, child.height);
}
this.panelElement.style.width = width + 'px';
this.panelElement.style.height = height + 'px';
}
} |
JavaScript | class DisclaimerHandler {
constructor(terria, viewState) {
this.terria = terria;
this.viewState = viewState;
this._pending = {};
this.terria.disclaimerListener = this._handleInitialMessage.bind(this);
}
dispose() {
this.terria.disclaimerListener = undefined;
}
/**
* Handles the {@Terria#disclaimerEvent} being raised. Only one disclaimer will be shown for each catalogItem with the
* same {@link CatalogItem#initialMessage#key}, but all calls will have their successCallback executed when it's
* accepted.
*
* @param catalogItem The catalog item to display a disclaimer for.
* @param successCallback A callback to execute once the disclaimer is accepted.
* @private
*/
_handleInitialMessage(catalogItem, successCallback) {
var keySpecified = defined(catalogItem.initialMessage.key);
if (
keySpecified &&
this.terria.getLocalProperty(catalogItem.initialMessage.key)
) {
successCallback();
return;
}
if (catalogItem.initialMessage.confirmation) {
if (keySpecified) {
var key = catalogItem.initialMessage.key;
if (defined(this._pending[key])) {
this._pending[key].push(successCallback);
} else {
this._pending[key] = [successCallback];
this._openConfirmationModal(
catalogItem,
this._executeCallbacksForKey.bind(this, key)
);
}
} else {
this._openConfirmationModal(catalogItem, successCallback);
}
} else {
if (keySpecified) {
this.terria.setLocalProperty(catalogItem.initialMessage.key, true);
}
this._openNotificationModel(catalogItem);
successCallback();
}
}
/**
* Opens a confirmation modal for the specified {@link CatalogItem}.
*
* @param catalogItem The catalog item to get disclaimer details from.
* @param callback The callback to execute when the modal is dismissed.
* @private
*/
_openConfirmationModal(catalogItem, callback) {
this.viewState.terria.notificationState.addNotificationToQueue(
combine(
{
confirmAction: callback
},
DisclaimerHandler._generateOptions(catalogItem)
)
);
}
_openNotificationModel(catalogItem) {
this.viewState.terria.notificationState.addNotificationToQueue(
DisclaimerHandler._generateOptions(catalogItem)
);
}
/**
* Executes all the callbacks stored in {@link DisclaimerHandler#pending} for the specified key, and clears that key
* in pending.
*
* @param key The key to get callbacks from.
* @private
*/
_executeCallbacksForKey(key) {
(this._pending[key] || []).forEach(function(cb) {
cb();
});
this._pending[key] = undefined;
this.terria.setLocalProperty(key, true);
}
/**
* Generates options for {@link PopupMessageConfirmationViewModel} and {@link PopupMessageViewModel} for a
* {@link CatalogItem}
* @returns {{title: string, message: string, width: number, height: number, confirmText: string}}
* @private
*/
static _generateOptions(catalogItem) {
return {
title: catalogItem.initialMessage.title,
message: catalogItem.initialMessage.content,
confirmText: catalogItem.initialMessage.confirmText,
width: catalogItem.initialMessage.width,
height: catalogItem.initialMessage.height
};
}
} |
JavaScript | class Validator {
/**
* Validate input
* @static
* @returns {object} error description OR return next middleware
*/
static validateInput = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorMessage = errors.errors.map((err) => err.msg);
return Response.errorMessage(res, errorMessage, HttpStatus.BAD_REQUEST);
}
return next();
};
/**
* Validate consumer new account input
* @static
* @returns {object} errors
*/
static signupRules() {
return [
check("username", "username name should be valid").trim().isString(),
check("email", "email should be valid").trim().isEmail(),
check(
"password",
"A valid password should have a character, number, UPPER CASE letter and a lower case letter and should be longer than 8"
)
.matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, "i"),
];
}
/**
* Validate input
* @static
* @returns {object} errors
*/
static loginRules() {
return [
check("email", "email should be valid").trim().isEmail(),
check("password", "Password should be valid").isString(),
];
}
/**
* Validate input
* @static
* @returns {object} errors
*/
static dmRules() {
return [
check("receiverId", "Receiver Id should be provided").trim().isString(),
check("message", "Message should be valid").isString(),
];
}
} |
JavaScript | class Error {
/**
* SCIM Error Message Schema ID
* @type {String}
* @private
*/
static #id = "urn:ietf:params:scim:api:messages:2.0:Error";
/**
* Instantiate a new SCIM Error Message with relevant details
* @param {Object} [ex={}] - the initiating exception to parse into a SCIM error message
* @param {SCIMMY.Messages.Error~ValidStatusTypes} ex.status=500 - HTTP status code to be sent with the error
* @param {SCIMMY.Messages.Error~ValidScimTypes} [ex.scimType] - the SCIM detail error keyword as per [RFC7644§3.12]{@link https://datatracker.ietf.org/doc/html/rfc7644#section-3.12}
* @param {String} [ex.detail] - a human-readable description of what caused the error to occur
* @property {String} status - stringified HTTP status code to be sent with the error
* @property {String} [scimType] - the SCIM detail error keyword as per [RFC7644§3.12]{@link https://datatracker.ietf.org/doc/html/rfc7644#section-3.12}
* @property {String} [detail] - a human-readable description of what caused the error to occur
*/
constructor(ex = {}) {
// Dereference parts of the exception
let {schemas = [], status = 500, scimType, message, detail = message} = ex,
errorSuffix = "SCIM Error Message constructor";
// Rethrow SCIM Error messages when error message schema ID is present
if (schemas.includes(Error.#id))
throw new Types.Error(status, scimType, detail);
// Validate the supplied parameters
if (!validStatusCodes.includes(Number(status)))
throw new TypeError(`Incompatible HTTP status code '${status}' supplied to ${errorSuffix}`);
if (!!scimType && !validScimTypes.includes(scimType))
throw new TypeError(`Unknown detail error keyword '${scimType}' supplied to ${errorSuffix}`);
if (!!scimType && !validCodeTypes[Number(status)]?.includes(scimType))
throw new TypeError(`HTTP status code '${Number(status)}' not valid for detail error keyword '${scimType}' in ${errorSuffix}`);
// No exceptions thrown, assign the parameters to the instance
this.schemas = [Error.#id];
this.status = String(status);
if (!!scimType) this.scimType = String(scimType);
if (!!detail) this.detail = detail;
}
} |
JavaScript | class BrowserFavorites extends PureComponent {
static propTypes = {
/**
* Array containing all the bookmark items
*/
bookmarks: PropTypes.array,
/**
* Function to be called when tapping on a bookmark item
*/
goTo: PropTypes.any,
/**
* function that removes a bookmark
*/
removeBookmark: PropTypes.func
};
actionSheet = null;
self = React.createRef();
keyExtractor = item => item.url;
bookmarkUrlToRemove = null;
showRemoveMenu = url => {
this.bookmarkUrlToRemove = url;
this.actionSheet.show();
};
removeBookmark = () => {
const bookmark = this.props.bookmarks.find(bookmark => bookmark.url === this.bookmarkUrlToRemove);
this.props.removeBookmark(bookmark);
};
createActionSheetRef = ref => {
this.actionSheet = ref;
};
renderItem = item => {
const { url, name } = item;
return (
<View key={item.url} style={styles.bookmarkItem}>
<TouchableOpacity
style={styles.bookmarkTouchable}
onPress={() => this.props.goTo(url)} // eslint-disable-line react/jsx-no-bind
// eslint-disable-next-line react/jsx-no-bind
onLongPress={() => this.showRemoveMenu(url)}
>
<WebsiteIcon
style={styles.bookmarkIco}
url={url}
title={name}
textStyle={styles.fallbackTextStyle}
/>
<Text numberOfLines={1} style={styles.bookmarkUrl}>
{name}
</Text>
</TouchableOpacity>
</View>
);
};
measureMyself(cb) {
this.self && this.self.current && this.self.current.measure(cb);
}
renderBookmarks() {
const { bookmarks } = this.props;
let content = null;
if (bookmarks && bookmarks.length) {
content = bookmarks.map(item => this.renderItem(item));
} else {
content = (
<View style={styles.noBookmarksWrapper}>
<Text style={styles.noBookmarks}>{strings('home_page.no_bookmarks')}</Text>
</View>
);
}
return (
<View style={styles.bookmarksWrapper}>
<View style={styles.bookmarksItemsWrapper}>{content}</View>
<ActionSheet
ref={this.createActionSheetRef}
title={strings('home_page.remove_bookmark_title')}
options={[strings('browser.remove'), strings('browser.cancel')]}
cancelButtonIndex={1}
destructiveButtonIndex={0}
// eslint-disable-next-line react/jsx-no-bind
onPress={index => (index === 0 ? this.removeBookmark() : null)}
/>
</View>
);
}
render() {
const allItemsHeight = (this.props.bookmarks && this.props.bookmarks.length * 40) || MIN_HEIGHT;
return (
<View ref={this.self} style={[styles.wrapper, { height: Math.max(MIN_HEIGHT, allItemsHeight) }]}>
{this.renderBookmarks()}
</View>
);
}
} |
JavaScript | class Info extends DressElement {
/**
* Create callback
*/
onCreated() {
this.classList.add('info-bar');
this._curSelectedElementInfo = {
tag : null,
id : null,
class : null
};
// bind event
this._bindEvent();
this._displayNoSelectedElementInfo();
}
/**
* Destroy callback
*/
onDestroy() {
this.options = null;
this._curSelectedElementInfo = null;
}
/**
* Prepare date for given element
* @param {jQuery} $element
* @return {Info}
* @private
*/
_setElementInfo($element) {
var element = $element[0],
// prepare data about current element
id = element.getAttribute('id'),
classes = join.call(element.classList, '.'),
// init parent variables
parentDetectedElement = null,
parentDetectedElementInfo = null;
// reset information
this._curSelectedElementInfo = {};
// fill information about current element
this._curSelectedElementInfo.tag = element.tagName.toLowerCase();
this._curSelectedElementInfo.id = id ? '#' + id : null;
this._curSelectedElementInfo.class = (classes !== '') ? '.' + classes : null;
// find component in parent chain
parentDetectedElementInfo = ElementDetector.getInstance().detect(element.parentElement);
if (parentDetectedElementInfo) {
// fill information about parent
parentDetectedElement = parentDetectedElementInfo.element;
this._curSelectedElementInfo.parentInternalId = parentDetectedElement.dataset.id;
this._curSelectedElementInfo.parentTag = parentDetectedElement.tagName.toLowerCase();
this._curSelectedElementInfo.parentId = parentDetectedElement.getAttribute('id') ? '#' + parentDetectedElement.getAttribute('id') : null;
this._curSelectedElementInfo.parentClass = parentDetectedElement.classList.length ? '.' + join.call(parentDetectedElement.classList, '.') : null;
}
return this;
}
/**
* Prepare HTML for given data
* @param {Object} elementInfo
* @returns {string}
* @private
*/
static _getRenderedHTMLString(elementInfo) {
var fullStr = '';
if (elementInfo.parentTag) {
fullStr += Mustache.render(textFormatParent, elementInfo);
}
fullStr += Mustache.render(textFormatChild, elementInfo);
return fullStr;
}
/**
* Change HTML in next animation frame
* @private
*/
_render() {
requestAnimationFrame(() => {
this.$el.html(Info._getRenderedHTMLString(this._curSelectedElementInfo));
});
return this;
}
/**
* Bind events to interact with info element
* @private
*/
_bindEvent() {
// on change selected element update information in bar
eventEmitter.on(EVENTS.ElementSelected, (elementId) => {
var design = appManager.getActiveDesignEditor(),
$element = design && design._getElementById(elementId);
if ($element && $element.length) {
this._setElementInfo($element)
._render()
}
});
// on deselect element hide bar
eventEmitter.on(
EVENTS.ElementDeselected,
this._onElementDeselect.bind(this)
);
// on click in element with referer to nother change selected element
this.$el.on('click', '[data-id]', (event) => {
console.log('info-element.click');
const id = event.currentTarget.dataset.id;
if (id) {
elementSelector.select(id);
}
});
}
/**
* Handles element deselect event.
*/
_onElementDeselect() {
this._displayNoSelectedElementInfo.apply(this);
}
/**
* Display static message in element.
*/
_displayNoSelectedElementInfo() {
this.$el.html("No element selected");
}
} |
JavaScript | class MSPDefinitionModal extends Component {
componentDidMount() {
let disableSubmit = _.get(this.props.msp, 'fabric_node_ous.enable', false) && this.props.enableOU;
// Updating the msp in the console it was created
const sameConsoleUpdate = this.props.msp && _.get(this.props.msp, 'host_url') === this.props.setting_host_url;
this.props.updateState(SCOPE, {
data: [],
disableSubmit,
disableRemove: true,
enableOU: sameConsoleUpdate ? !_.get(this.props.msp, 'fabric_node_ous.enable', false) : false,
loading: false,
submitting: false,
error: null,
isUpdate: this.props.msp ? true : false,
remove: this.props.mspModalType === 'delete' ? true : false,
upgrade: this.props.mspModalType === 'upgrade' ? true : false,
duplicateMspError: false,
});
if (this.props.msp && !_.get(this.props.msp, 'fabric_node_ous.enable', false)) {
this.props.updateState(SCOPE, {
msp_id: this.props.msp.msp_id,
msp_name: this.props.msp.name || this.props.msp.display_name,
rootCerts: this.props.msp.root_certs ? this.props.msp.root_certs.map(x => {
return { cert: x };
}) : [] /* prettier-ignore */,
intermediate_certs: this.props.msp.intermediate_certs,
admins: this.props.msp.admins ? this.props.msp.admins.map(x => {
return { cert: x };
}): [] /* prettier-ignore */,
tls_root_certs: this.props.msp.tls_root_certs,
tls_intermediate_certs: this.props.msp.tls_intermediate_certs,
revocation_list: this.props.msp.revocation_list,
organizational_unit_identifiers: this.props.msp.organizational_unit_identifiers,
fabric_node_ous: this.props.msp.fabric_node_ous,
host_url: this.props.msp.host_url,
});
}
}
componentWillUnmount() {
this.props.updateState(SCOPE, {
data: [],
isUpdate: false,
host_url: '',
enableOU: false,
});
}
onComplete() {
if (typeof this.props.onComplete === 'function') return this.props.onComplete(...arguments);
Log.warn(`${SCOPE} ${this.props.mspModalType}: onComplete() is not set`);
}
validateMspid = mspid => {
if (mspid) {
let invalidCharacters = false;
let isEmpty = false;
Log.debug('Validating mspid: ', mspid);
if (mspid.trim() !== '') {
// Restrictions on MSPID
//1. Contain only ASCII alphanumerics, dots '.', dashes '-'
if (/[^a-zA-Z\d-.]/g.test(mspid)) {
//check for invalid characters
invalidCharacters = true;
}
//2. Are shorter than 250 characters.
if (mspid.length > 250) {
invalidCharacters = true;
}
//3. Are not the strings "." or "..".
if (mspid === '.' || mspid === '..') {
invalidCharacters = true;
}
Log.debug('Mspid has invalid characters: ', invalidCharacters);
} else {
isEmpty = true;
Log.debug('Mspid is empty');
}
if (invalidCharacters || isEmpty) {
return false;
}
}
return true;
};
onUpload = async(data, valid) => {
Log.debug('Uploaded json: ', data, valid);
let json = data && data.length ? data[0] : null;
let isMspIdValid = true;
let isSameMsp = true;
if (json && json.msp_id && this.props.isUpdate) {
// if updating msp definition, verify if msp id matches
if (this.props.msp.msp_id !== json.msp_id) {
this.props.updateState(SCOPE, {
error: {
title: 'edit_msp_mspid_error',
},
});
isSameMsp = false;
} else {
this.props.updateState(SCOPE, { error: null });
}
} else if (json && json.msp_id) {
isMspIdValid = this.validateMspid(json.msp_id);
if (!isMspIdValid) {
this.props.updateState(SCOPE, {
error: {
title: 'validation_mspid_invalid',
},
});
} else {
this.props.updateState(SCOPE, { error: null });
}
}
valid = valid && isSameMsp && isMspIdValid;
if (json) {
let duplicateMSPExists = false;
if (!this.props.isUpdate) {
duplicateMSPExists = await MspRestApi.checkIfMSPExists(json.msp_id, json.root_certs, json.intermediate_certs);
}
let admin_certs = json.admins
? json.admins.map(x => {
let parsedCert = StitchApi.parseCertificate(x);
if (!parsedCert) {
valid = false;
this.props.updateState(SCOPE, {
error: {
title: 'invalid_admin_certificate',
},
});
}
return { cert: parsedCert && parsedCert.base_64_pem ? parsedCert.base_64_pem : '' };
})
: [];
this.props.updateState(SCOPE, {
msp_id: json.msp_id,
msp_name: json.name || json.display_name,
rootCerts: json.root_certs ? json.root_certs.map(x => {
return { cert: x };
}) : [] /* prettier-ignore */,
intermediate_certs: json.intermediate_certs,
admins: admin_certs,
tls_root_certs: json.tls_root_certs,
tls_intermediate_certs: json.tls_intermediate_certs,
revocation_list: json.revocation_list,
organizational_unit_identifiers: json.organizational_unit_identifiers,
fabric_node_ous: json.fabric_node_ous,
host_url: json.host_url,
disableSubmit: !valid,
duplicateMspError: duplicateMSPExists ? true : false,
});
}
// Importing the msp in the console it was created
const sameConsoleImport = !this.props.isUpdate && _.get(json, 'host_url') === this.props.setting_host_url;
if (sameConsoleImport) {
this.props.updateState(SCOPE, {
enableOU: !_.get(json, 'fabric_node_ous.enable', false),
});
}
};
onError = error => {
this.props.updateState(SCOPE, {
error: {
title: error,
},
});
};
async onSubmit() {
this.props.updateState(SCOPE, {
submitting: true,
disableSubmit: true,
error: null,
});
if (!this.props.msp_id || !this.props.msp_name || this.props.rootCerts.length === 0 || this.props.admins.length === 0) {
// required fields
this.props.updateState(SCOPE, {
error: {
title: 'error_required_fields',
},
submitting: false,
});
} else {
let intermediate_certs = this.props.intermediate_certs;
let tls_root_certs = this.props.tls_root_certs;
let tls_intermediate_certs = this.props.tls_intermediate_certs;
let revocation_list = this.props.revocation_list;
let organizational_unit_identifiers = this.props.organizational_unit_identifiers;
let fabric_node_ous = this.props.fabric_node_ous;
let root_certs = this.props.rootCerts.filter(x => x.cert !== '').map(x => x.cert);
if (!_.get(this.props, 'fabric_node_ous.enable', false) && this.props.enableOU) {
fabric_node_ous = ChannelApi.getNodeOUIdentifier(root_certs[0]);
}
if (this.props.isUpdate) {
if (_.isEmpty(intermediate_certs) && !_.isEmpty(this.props.msp.intermediate_certs)) {
// Removed completely during update
intermediate_certs = [];
}
if (_.isEmpty(tls_root_certs) && !_.isEmpty(this.props.msp.tls_root_certs)) {
tls_root_certs = [];
}
if (_.isEmpty(tls_intermediate_certs) && !_.isEmpty(this.props.msp.tls_intermediate_certs)) {
tls_intermediate_certs = [];
}
if (_.isEmpty(revocation_list) && !_.isEmpty(this.props.msp.revocation_list)) {
revocation_list = [];
}
if (_.isEmpty(organizational_unit_identifiers) && !_.isEmpty(this.props.msp.organizational_unit_identifiers)) {
organizational_unit_identifiers = [];
}
if (_.isEmpty(fabric_node_ous) && !_.isEmpty(this.props.msp.fabric_node_ous)) {
fabric_node_ous = {};
}
}
const opts = {
type: MSP_TYPE,
msp_id: this.props.msp_id,
display_name: this.props.msp_name,
root_certs,
admins: this.props.admins.filter(x => x.cert !== '').map(x => x.cert),
intermediate_certs,
certificate: this.props.certificate,
tls_root_certs,
tls_intermediate_certs,
revocation_list,
organizational_unit_identifiers,
fabric_node_ous,
host_url: this.props.host_url,
};
if (this.props.isUpdate) {
Log.info('Request for editing msp definition: ', this.props.msp.id, JSON.stringify(opts, null, 4));
let resp;
try {
opts.id = this.props.msp.id;
resp = await MspRestApi.editMsp(opts);
} catch (error) {
Log.error(`Error occurred while editing msp ${error}`);
this.props.updateState(SCOPE, {
submitting: false,
error: {
title: 'error_occurred_during_msp_edit',
details: error,
},
});
return;
}
Log.info('Edit msp response: ', resp);
if (resp && resp.id) {
let nodes = [...(this.props.associatedPeers || []), ...(this.props.associatedOrderers || [])];
if (nodes && nodes.length > 0) {
let updatedAdminCerts = this.props.admins.map(x => x.cert);
Log.info('Now syncing certs to all peers:', updatedAdminCerts);
try {
await NodeRestApi.syncAdminCerts(nodes, updatedAdminCerts, !_.get(this.props, 'fabric_node_ous.enable', false) && this.props.enableOU);
} catch (syncCertError) {
this.props.updateState(SCOPE, {
error: {
title: 'error_occurred_during_sync_certs',
details: syncCertError,
},
submitting: false,
});
return;
}
Log.info('Updated admin certs on all peers successfully');
this.onComplete(this.props.msp_name, true);
this.sidePanel.closeSidePanel();
} else {
this.onComplete(this.props.msp_name, true);
this.sidePanel.closeSidePanel();
}
} else {
this.props.updateState(SCOPE, {
error: {
title: 'error_occurred_during_msp_edit',
details: resp,
},
submitting: false,
});
}
} else {
Log.info('Request for importing new msp definition in database: ', JSON.stringify(opts, null, 4));
let resp;
try {
resp = await MspRestApi.importMSP(opts);
} catch (error) {
Log.error(`Error occurred while importing msp ${error}`);
this.props.updateState(SCOPE, {
submitting: false,
error,
});
return;
}
Log.info('Import msp response: ', resp);
if (resp && resp.id) {
this.onComplete(this.props.msp_name);
this.sidePanel.closeSidePanel();
} else {
this.props.updateState(SCOPE, {
submitting: false,
error: {
title: 'error_occurred_during_msp_import',
details: resp,
},
});
}
}
}
}
renderRemove = translate => {
const mspName = this.props.selectedMsp ? this.props.selectedMsp.display_name : null;
if (this.props.mspModalType === 'settings') {
return;
}
if (this.props.mspModalType === 'delete') {
return (
<div>
<div className="ibp-modal-title">
<h1 className="ibm-light">{translate('remove_org')}</h1>
</div>
<p className="ibp-remove-msp-desc">
{translate('remove_msp_desc', {
name: (
<CodeSnippet
type="inline"
ariaLabel={translate('copy_text', { copyText: mspName })}
light={false}
onClick={() => Clipboard.copyToClipboard(mspName)}
>
{mspName}
</CodeSnippet>
),
})}
</p>
<div>
<p className="ibp-remove-msp-confirm">{translate('remove_msp_confirm')}</p>
<Form
scope={SCOPE}
id={SCOPE + '-remove'}
fields={[
{
name: 'confirm_msp_name',
tooltip: 'remove_msp_name_tooltip',
required: true,
},
]}
onChange={data => {
this.props.updateState(SCOPE, {
disableRemove: data.confirm_msp_name !== this.props.selectedMsp.display_name,
});
}}
/>
</div>
</div>
);
}
};
async deleteMsp() {
const prefix = 'removing MSP:';
this.props.updateState(SCOPE, { submitting: true });
try {
await NodeRestApi.removeComponent(this.props.selectedMsp.id);
} catch (error) {
Log.error(`${prefix} failed: ${error}`);
this.props.updateState(SCOPE, {
error,
submitting: false,
});
return;
}
this.props.updateState(SCOPE, { submitting: false });
this.onComplete(this.props.selectedMsp.name);
this.sidePanel.closeSidePanel();
}
enableOU(translate) {
let sameConsole = this.props.isUpdate
? _.get(this.props, 'msp.host_url') === this.props.setting_host_url
: _.get(this.props, 'host_url') === this.props.setting_host_url;
if (!sameConsole) {
return;
}
return (
<Checkbox
id={'enable_node_ou'}
labelText={translate('node_ou')}
checked={this.props.enableOU}
onClick={event => {
this.props.updateState(SCOPE, {
enableOU: event.target.checked,
});
}}
/>
);
}
renderMSPSettings = translate => {
let nodes = [...(this.props.associatedPeers || []), ...(this.props.associatedOrderers || [])];
if (this.props.mspModalType === 'delete') {
return;
}
if (this.props.mspModalType === 'settings') {
return (
<div>
<div className="ibp-modal-title">
<h1 className="ibm-light">{this.props.isUpdate ? translate('update_msp_definition') : translate('import_msp_definition')}</h1>
</div>
<div>
<div>
<p className="ibp-modal-desc">
{this.props.isUpdate ? translate('update_msp_definition_desc') : translate('import_msp_definition_desc')}
<a
className="ibp-msp-modal-learn-more"
href={translate(this.props.isUpdate ? 'console_update_msp_docs' : 'import_msp_admin_identity_link', { DOC_PREFIX: this.props.docPrefix })}
target="_blank"
rel="noopener noreferrer"
>
{translate('find_more_here')}
</a>
</p>
</div>
{!_.get(this.props.msp, 'fabric_node_ous.enable', false) && this.enableOU(translate)}
<div className="ibp-import-msp">
<JsonInput
id="msp_definition_upload"
definition={Helper.getMSPFields()}
onChange={this.onUpload}
onError={this.onError}
uniqueNames={true}
onlyFileUpload={true}
singleInput={true}
/>
</div>
{this.props.isUpdate && nodes && nodes.length > 0 && (
<>
<ImportantBox text="sync_msp_def_warning" />
<ul>
{nodes.map(node => {
return (
<li className="ibp-note-bullet"
key={node.id}
>
<div className="ibp-note-bullet-point">-</div>
<div className="ibp-note-bullet-text">
<strong>{node.display_name} </strong>
</div>
</li>
);
})}
</ul>
</>
)}
{!this.props.isUpdate && this.props.duplicateMspError && (
<div className="ibp-dup-msp-error">
<SidePanelWarning title="duplicate_mspid_error_title"
subtitle={translate('duplicate_mspid_import_error_desc')}
/>
</div>
)}
</div>
</div>
);
}
};
getButtons = translate => {
let buttons = [];
if (this.props.mspModalType === 'settings') {
buttons.push(
{
id: 'cancel',
text: translate('cancel'),
},
{
id: 'import_msp_definition',
text: translate(this.props.isUpdate ? 'update_msp_definition' : 'import_msp_definition'),
onClick: () => this.onSubmit(),
disabled: this.props.disableSubmit || (!this.props.isUpdate && this.props.duplicateMspError),
type: 'submit',
}
);
} else if (this.props.mspModalType === 'delete') {
buttons.push(
{
id: 'cancel',
text: translate('cancel'),
},
{
id: 'confirm_remove',
text: translate('remove_org'),
onClick: () => this.deleteMsp(),
disabled: this.props.disableRemove || this.props.submitting,
type: 'submit',
}
);
}
return buttons;
};
render() {
const translate = this.props.translate;
return (
<SidePanel
id="import-msp-definition"
closed={this.props.onClose}
ref={sidePanel => (this.sidePanel = sidePanel)}
buttons={this.getButtons(translate)}
error={this.props.error}
submitting={this.props.submitting}
>
{this.renderMSPSettings(translate)}
{this.renderRemove(translate)}
</SidePanel>
);
}
} |
JavaScript | class App extends Component {
render() {
return (
<div>
<div className='music'>
<audio autoPlay controls loop >
<source
type="audio/mpeg"
src="./Far-Away-Places-Call.mp3">
</source>
</audio>
</div>
<World />
</div>
)
}
} |
JavaScript | class Category {
/**
* Create a Category
*
* @param {object} [data] - The record object from the database
*/
constructor(data) {
const myData = angular.extend({
name: 'New category',
masterCategory: null,
sort: 0,
_id: Category.prefix + uuid()
}, data);
this.id = myData._id.slice(myData._id.lastIndexOf('_') + 1);
this._data = myData;
}
/**
* The category name. Will trigger subscriber upon set.
*
* @example
* const cat = new Category();
* cat.name = '⛽ Fuel/Gas';
* cat.name; // === '⛽ Fuel/Gas'
*
* @type {string}
*/
get name() {
return this._data.name;
}
set name(n) {
this._data.name = n;
this.emitChange();
}
/**
* The parent category id. Will trigger subscriber upon set.
*
* @example
* const cat = new Category();
* cat.masterCategory = 'b_8435609a-161c-4eb6-9ed8-a86414a696cf_master-category_ab735ea6-bd56-449c-8f03-6afcc91e2248';
* cat.masterCategory; // === 'b_8435609a-161c-4eb6-9ed8-a86414a696cf_master-category_ab735ea6-bd56-449c-8f03-6afcc91e2248'
*
* @type {string}
*/
get masterCategory() {
return this._data.masterCategory;
}
set masterCategory(n) {
if (this._data.masterCategory !== n) {
this._data.masterCategory = n;
this.emitChange();
}
}
setMasterAndSort(masterCategory, i) {
const saveFn = this.fn;
this.fn = null;
const oldSort = this.sort,
master = this.masterCategory;
this.masterCategory = masterCategory;
this.sort = i;
this.fn = saveFn;
if (i !== oldSort || masterCategory !== master) {
this.emitChange();
}
}
/**
* The category sort order. Will trigger subscriber upon set.
*
* @example
* const cat = new Category();
* cat.sort = 1;
* cat.sort; // === 1
*
* @type {number}
*/
get sort() {
return this._data.sort;
}
set sort(i) {
// only put() new record if
// there has been a change
if (this._data.sort !== i) {
this._data.sort = i;
this.emitChange();
}
}
/**
* The category note (description, any user data).
* Will trigger subscriber upon set.
*
* @example
* const cat = new Category();
* cat.note = 'Commute 30 miles per day.';
* cat.note; // === 'Commute 30 miles per day.'
*
* @type {string}
*/
get note() {
return this._data.note;
}
set note(n) {
this._data.note = n;
this.emitChange();
}
/**
* Get the complete `_id`, with namespace as set in the database.
*
* @example
* const cat = new Category();
* cat._id; // === 'b_8435609a-161c-4eb6-9ed8-a86414a696cf_category_ab735ea6-bd56-449c-8f03-6afcc91e2248'
*
* @type {string}
*/
get _id() {
return this._data._id;
}
/**
*
*/
remove() {
this._data._deleted = true;
return this.emitChange();
}
/**
* Used to set the function to invoke upon record changes.
*
* @param {function} fn - This function will be invoked upon record
* changes with the Category object as the first parameter.
*/
subscribe(fn) {
this.fn = fn;
}
/**
* Will call the subscribed function, if it exists, with self.
*
* @private
*/
emitChange() {
return this.fn && this.fn(this);
}
/**
* Used to set the function to invoke upon record changes
*
* @param {function} fn - This function will be invoked upon record
* changes with the Category object as the first parameter.
*/
subscribeSortChange(fn) {
this.sortFn = fn;
}
/**
* Used to set the function to invoke upon master category changes
*
* @param {function} fn - This function will be invoked upon record
* changes with the Category object as the first parameter.
*/
subscribeMasterCategoryChange(before, after) {
this.masterCategoryBeforeFn = before;
this.masterCategoryAfterFn = after;
}
/**
* Will call the subscribed function, if it exists, with self.
*
* @private
*/
emitSortChange() {
return this.sortFn && this.sortFn(this);
}
/**
* Will call the subscribed function, if it exists, with self.
*
* @private
*/
emitMasterCategoryChange(fn) {
this.masterCategoryBeforeFn(this);
fn();
this.masterCategoryAfterFn(this);
}
/**
* Will serialize the Category object to
* a JSON object for sending to the database.
*
* @returns {object}
*/
toJSON() {
return this._data;
}
get data() {
return this._data;
}
set data(d) {
this._data.name = d.name;
this._data.note = d.note;
const oldSort = this._data.sort;
this._data.sort = d.sort;
const oldMasterCategory = this._data.masterCategory;
if (oldMasterCategory !== d.masterCategory) {
this.emitMasterCategoryChange(() => {
this._data.masterCategory = d.masterCategory;
});
}
if (oldSort !== d.sort) {
this.emitSortChange();
}
this._data._rev = d._rev;
}
/**
* The upper bound of alphabetically sorted Categories by ID. Used by PouchDB.
*
* @type {string}
*/
static get startKey() {
return `b_${budgetId}_category_`;
}
/**
* The lower bound of alphabetically sorted Categories by ID. Used by PouchDB.
*
* @type {string}
*/
static get endKey() {
return this.startKey + '\uffff';
}
/**
* The prefix for namespacing the Category UID
*
* @type {string}
*/
static get prefix() {
return this.startKey;
}
/**
* Used for detecting if a document's _id is a Category
* in this budget.
*
* @param {string} _id - The document's _id
* @returns {boolean} True if document _id is in the budget
* as an category.
*/
static contains(_id) {
return _id > this.startKey && _id < this.endKey;
}
} |
JavaScript | class LoopInputOrder extends InputOrder { // eslint-disable-line no-unused-vars
/**
* Loop input order constructor
* @constructor
* @param {number} loopNumber Number of loop
*/
constructor(loopNumber) {
super();
/**
* Number of loop
* @protected
* @type {number}
*/
this.loopNumber = loopNumber;
/**
* Loop list of input order
* @protected
* @type {Array<InputOrder>}
*/
this.orders = [];
/**
* Index of currently running order
* @protected
* @type {number}
*/
this.orderIndex = 0;
}
/**
* Add input order to loop list
* @param {InputOrder} order Added order
*/
addOrder(order) {
this.orders.push(order);
}
/**
* Initialize input order
* @abstract
*/
init() {
this.orderIndex = 0;
if (this.orders.length > 0) {
this.orders[this.orderIndex].init();
}
}
/**
* Update input order
* @override
* @param {number} dt Delta time
* @return {boolean} Whether order is ended or not
*/
udpate(dt) {
if (this.orders.length === 0) {
return true;
}
// update order
const order = this.orders[this.orderIndex];
if (!order.udpate(dt)) {
return false;
}
// next
order.destruct();
this.orderIndex += 1;
// judge loop
if (this.orderIndex < this.orders.length) {
// init
this.orders[this.orderIndex].init();
return false;
}
// count loop
this.orderIndex = 0;
this.orders[this.orderIndex].init();
this.loopNumber -= 1;
if (this.loopNumber <= 0) {
return true;
}
return false;
}
} |
JavaScript | class Utility {
static urlAppender(prepend, url) {
console.log(`url: `, url);
const parsed_url = regexParser(url);
console.log(`parsed url: `, parsed_url);
const encoded_url = encodeURI(parsed_url);
console.log(`encoded url: `, encodeURI(encoded_url));
const final_url = `${prepend}${encoded_url}`;
console.log(`final url: `, final_url);
return final_url;
}
// https://docs.google.com/a/umd.edu/viewer?url=https://isotropic.org/papers/chicken.pdf&embedded=true
// https://docs.google.com/viewer?url=https://isotropic.org/papers/chicken.pdf&embedded=true
//
static getBinaryData(url, callback) {
// body...
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.responseType = "arraybuffer";
xhr.onload = function (e) {
//binary form of ajax response,
callback(e.currentTarget.response);
};
xhr.onerror = function (e) {
// body...
alert("xhr error" + JSON.stringify(e));
};
xhr.send();
}
static instaScanner(domElementID, urlFoundCallback) {
console.log(domElementID);
let scanner = new Instascan.Scanner({
video: domElementID.ref,
});
scanner.addListener("scan", function (content) {
console.log(content);
if(urlFoundCallback){
urlFoundCallback(content);
}
});
Instascan.Camera.getCameras()
.then(function (cameras) {
if (cameras.length > 0) {
let backCamIndex = cameras.findIndex((camera)=>{ return camera.name?.includes('back')});
//use the back cam if we actually found one
scanner.start(cameras[backCamIndex >=0 ?backCamIndex : 0]);
} else {
console.error("No cameras found.");
alert("No cameras found.");
}
})
.catch(function (e) {
console.error(e);
});
}
} |
JavaScript | class MediaImageTextAlternativeEditing extends Plugin {
/**
* @inheritdoc
*/
static get requires() {
return [DrupalMediaMetadataRepository];
}
/**
* @inheritdoc
*/
static get pluginName() {
return 'MediaImageTextAlternativeEditing';
}
/**
* @inheritdoc
*/
init() {
const {
editor,
editor: { model, conversion },
} = this;
model.schema.extend('drupalMedia', {
allowAttributes: ['drupalMediaIsImage'],
});
// Display error in the editor if fetching Drupal Media metadata failed.
conversion.for('editingDowncast').add((dispatcher) => {
dispatcher.on(
'attribute:drupalMediaIsImage',
(event, data, conversionApi) => {
const { writer, mapper } = conversionApi;
const container = mapper.toViewElement(data.item);
if (data.attributeNewValue !== METADATA_ERROR) {
const existingError = Array.from(container.getChildren()).find(
(child) => child.getCustomProperty('drupalMediaMetadataError'),
);
// If the view contains an existing error, it should be removed
// since retrieving metadata was successful.
if (existingError) {
writer.setCustomProperty(
'widgetLabel',
existingError.getCustomProperty(
'drupalMediaOriginalWidgetLabel',
),
existingError,
);
writer.removeElement(existingError);
}
return;
}
const message = Drupal.t(
'Not all functionality may be available because some information could not be retrieved.',
);
const tooltip = new TooltipView();
tooltip.text = message;
tooltip.position = 'sw';
const html = new Template({
tag: 'span',
children: [
{
tag: 'span',
attributes: {
class: 'drupal-media__metadata-error-icon',
},
},
tooltip,
],
}).render();
const error = writer.createRawElement(
'div',
{
class: 'drupal-media__metadata-error',
},
(domElement, domConverter) => {
domConverter.setContentOf(domElement, html.outerHTML);
},
);
writer.setCustomProperty('drupalMediaMetadataError', true, error);
// Edit widget label to ensure the current status of media embed is
// available for screen reader users.
const originalWidgetLabel =
container.getCustomProperty('widgetLabel');
writer.setCustomProperty(
'drupalMediaOriginalWidgetLabel',
originalWidgetLabel,
error,
);
writer.setCustomProperty(
'widgetLabel',
`${originalWidgetLabel} (${message})`,
container,
);
writer.insert(writer.createPositionAt(container, 0), error);
},
{ priority: 'low' },
);
});
editor.commands.add(
'mediaImageTextAlternative',
new MediaImageTextAlternativeCommand(this.editor),
);
}
} |
JavaScript | class ErpBankAccount extends InfCommon.BankAccount
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpBankAccount;
if (null == bucket)
cim_data.ErpBankAccount = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpBankAccount[obj.id];
}
parse (context, sub)
{
let obj = InfCommon.BankAccount.prototype.parse.call (this, context, sub);
obj.cls = "ErpBankAccount";
base.parse_element (/<cim:ErpBankAccount.bankABA>([\s\S]*?)<\/cim:ErpBankAccount.bankABA>/g, obj, "bankABA", base.to_string, sub, context);
let bucket = context.parsed.ErpBankAccount;
if (null == bucket)
context.parsed.ErpBankAccount = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = InfCommon.BankAccount.prototype.export.call (this, obj, false);
base.export_element (obj, "ErpBankAccount", "bankABA", "bankABA", base.from_string, fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpBankAccount_collapse" aria-expanded="true" aria-controls="ErpBankAccount_collapse" style="margin-left: 10px;">ErpBankAccount</a></legend>
<div id="ErpBankAccount_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ InfCommon.BankAccount.prototype.template.call (this) +
`
{{#bankABA}}<div><b>bankABA</b>: {{bankABA}}</div>{{/bankABA}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpBankAccount_collapse" aria-expanded="true" aria-controls="{{id}}_ErpBankAccount_collapse" style="margin-left: 10px;">ErpBankAccount</a></legend>
<div id="{{id}}_ErpBankAccount_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ InfCommon.BankAccount.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_bankABA'>bankABA: </label><div class='col-sm-8'><input id='{{id}}_bankABA' class='form-control' type='text'{{#bankABA}} value='{{bankABA}}'{{/bankABA}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "ErpBankAccount" };
super.submit (id, obj);
temp = document.getElementById (id + "_bankABA").value; if ("" !== temp) obj["bankABA"] = temp;
return (obj);
}
} |
JavaScript | class ErpDocument extends Common.Document
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpDocument;
if (null == bucket)
cim_data.ErpDocument = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpDocument[obj.id];
}
parse (context, sub)
{
let obj = Common.Document.prototype.parse.call (this, context, sub);
obj.cls = "ErpDocument";
let bucket = context.parsed.ErpDocument;
if (null == bucket)
context.parsed.ErpDocument = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Common.Document.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpDocument_collapse" aria-expanded="true" aria-controls="ErpDocument_collapse" style="margin-left: 10px;">ErpDocument</a></legend>
<div id="ErpDocument_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpDocument_collapse" aria-expanded="true" aria-controls="{{id}}_ErpDocument_collapse" style="margin-left: 10px;">ErpDocument</a></legend>
<div id="{{id}}_ErpDocument_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Common.Document.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpDocument" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class ErpIdentifiedObject extends Core.IdentifiedObject
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpIdentifiedObject;
if (null == bucket)
cim_data.ErpIdentifiedObject = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpIdentifiedObject[obj.id];
}
parse (context, sub)
{
let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub);
obj.cls = "ErpIdentifiedObject";
let bucket = context.parsed.ErpIdentifiedObject;
if (null == bucket)
context.parsed.ErpIdentifiedObject = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpIdentifiedObject_collapse" aria-expanded="true" aria-controls="ErpIdentifiedObject_collapse" style="margin-left: 10px;">ErpIdentifiedObject</a></legend>
<div id="ErpIdentifiedObject_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpIdentifiedObject_collapse" aria-expanded="true" aria-controls="{{id}}_ErpIdentifiedObject_collapse" style="margin-left: 10px;">ErpIdentifiedObject</a></legend>
<div id="{{id}}_ErpIdentifiedObject_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ Core.IdentifiedObject.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpIdentifiedObject" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class ErpReceiveDelivery extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpReceiveDelivery;
if (null == bucket)
cim_data.ErpReceiveDelivery = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpReceiveDelivery[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpReceiveDelivery";
base.parse_attributes (/<cim:ErpReceiveDelivery.ErpRecDelvLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecDelvLineItems", sub, context);
let bucket = context.parsed.ErpReceiveDelivery;
if (null == bucket)
context.parsed.ErpReceiveDelivery = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpReceiveDelivery", "ErpRecDelvLineItems", "ErpRecDelvLineItems", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpReceiveDelivery_collapse" aria-expanded="true" aria-controls="ErpReceiveDelivery_collapse" style="margin-left: 10px;">ErpReceiveDelivery</a></legend>
<div id="ErpReceiveDelivery_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpRecDelvLineItems}}<div><b>ErpRecDelvLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpRecDelvLineItems}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpRecDelvLineItems"]) obj["ErpRecDelvLineItems_string"] = obj["ErpRecDelvLineItems"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpRecDelvLineItems_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpReceiveDelivery_collapse" aria-expanded="true" aria-controls="{{id}}_ErpReceiveDelivery_collapse" style="margin-left: 10px;">ErpReceiveDelivery</a></legend>
<div id="{{id}}_ErpReceiveDelivery_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpReceiveDelivery" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpRecDelvLineItems", "0..*", "1", "ErpRecDelvLineItem", "ErpReceiveDelivery"]
]
)
);
}
} |
JavaScript | class ErpInvoiceLineItem extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpInvoiceLineItem;
if (null == bucket)
cim_data.ErpInvoiceLineItem = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpInvoiceLineItem[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpInvoiceLineItem";
base.parse_attribute (/<cim:ErpInvoiceLineItem.billPeriod\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "billPeriod", sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.glAccount>([\s\S]*?)<\/cim:ErpInvoiceLineItem.glAccount>/g, obj, "glAccount", base.to_string, sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.glDateTime>([\s\S]*?)<\/cim:ErpInvoiceLineItem.glDateTime>/g, obj, "glDateTime", base.to_datetime, sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.lineAmount>([\s\S]*?)<\/cim:ErpInvoiceLineItem.lineAmount>/g, obj, "lineAmount", base.to_float, sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.lineNumber>([\s\S]*?)<\/cim:ErpInvoiceLineItem.lineNumber>/g, obj, "lineNumber", base.to_string, sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.lineVersion>([\s\S]*?)<\/cim:ErpInvoiceLineItem.lineVersion>/g, obj, "lineVersion", base.to_string, sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.netAmount>([\s\S]*?)<\/cim:ErpInvoiceLineItem.netAmount>/g, obj, "netAmount", base.to_float, sub, context);
base.parse_element (/<cim:ErpInvoiceLineItem.previousAmount>([\s\S]*?)<\/cim:ErpInvoiceLineItem.previousAmount>/g, obj, "previousAmount", base.to_float, sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.UserAttributes\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "UserAttributes", sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.ErpPayments\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayments", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ErpRecLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecLineItem", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ErpInvoice\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoice", sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.CustomerBillingInfos\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CustomerBillingInfos", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ErpQuoteLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpQuoteLineItem", sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.WorkBillingInfos\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WorkBillingInfos", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ContainerErpInvoiceLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ContainerErpInvoiceLineItem", sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.ComponentErpInvoiceLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ComponentErpInvoiceLineItems", sub, context);
base.parse_attributes (/<cim:ErpInvoiceLineItem.ErpJournalEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJournalEntries", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ErpRecDelvLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecDelvLineItem", sub, context);
base.parse_attribute (/<cim:ErpInvoiceLineItem.ErpPayableLineItem\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayableLineItem", sub, context);
let bucket = context.parsed.ErpInvoiceLineItem;
if (null == bucket)
context.parsed.ErpInvoiceLineItem = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attribute (obj, "ErpInvoiceLineItem", "billPeriod", "billPeriod", fields);
base.export_element (obj, "ErpInvoiceLineItem", "glAccount", "glAccount", base.from_string, fields);
base.export_element (obj, "ErpInvoiceLineItem", "glDateTime", "glDateTime", base.from_datetime, fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "kind", "kind", fields);
base.export_element (obj, "ErpInvoiceLineItem", "lineAmount", "lineAmount", base.from_float, fields);
base.export_element (obj, "ErpInvoiceLineItem", "lineNumber", "lineNumber", base.from_string, fields);
base.export_element (obj, "ErpInvoiceLineItem", "lineVersion", "lineVersion", base.from_string, fields);
base.export_element (obj, "ErpInvoiceLineItem", "netAmount", "netAmount", base.from_float, fields);
base.export_element (obj, "ErpInvoiceLineItem", "previousAmount", "previousAmount", base.from_float, fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "UserAttributes", "UserAttributes", fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "ErpPayments", "ErpPayments", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ErpRecLineItem", "ErpRecLineItem", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ErpInvoice", "ErpInvoice", fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "CustomerBillingInfos", "CustomerBillingInfos", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ErpQuoteLineItem", "ErpQuoteLineItem", fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "WorkBillingInfos", "WorkBillingInfos", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ContainerErpInvoiceLineItem", "ContainerErpInvoiceLineItem", fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "ComponentErpInvoiceLineItems", "ComponentErpInvoiceLineItems", fields);
base.export_attributes (obj, "ErpInvoiceLineItem", "ErpJournalEntries", "ErpJournalEntries", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ErpRecDelvLineItem", "ErpRecDelvLineItem", fields);
base.export_attribute (obj, "ErpInvoiceLineItem", "ErpPayableLineItem", "ErpPayableLineItem", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpInvoiceLineItem_collapse" aria-expanded="true" aria-controls="ErpInvoiceLineItem_collapse" style="margin-left: 10px;">ErpInvoiceLineItem</a></legend>
<div id="ErpInvoiceLineItem_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#billPeriod}}<div><b>billPeriod</b>: {{billPeriod}}</div>{{/billPeriod}}
{{#glAccount}}<div><b>glAccount</b>: {{glAccount}}</div>{{/glAccount}}
{{#glDateTime}}<div><b>glDateTime</b>: {{glDateTime}}</div>{{/glDateTime}}
{{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}}
{{#lineAmount}}<div><b>lineAmount</b>: {{lineAmount}}</div>{{/lineAmount}}
{{#lineNumber}}<div><b>lineNumber</b>: {{lineNumber}}</div>{{/lineNumber}}
{{#lineVersion}}<div><b>lineVersion</b>: {{lineVersion}}</div>{{/lineVersion}}
{{#netAmount}}<div><b>netAmount</b>: {{netAmount}}</div>{{/netAmount}}
{{#previousAmount}}<div><b>previousAmount</b>: {{previousAmount}}</div>{{/previousAmount}}
{{#UserAttributes}}<div><b>UserAttributes</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/UserAttributes}}
{{#ErpPayments}}<div><b>ErpPayments</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayments}}
{{#ErpRecLineItem}}<div><b>ErpRecLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpRecLineItem}}");}); return false;'>{{ErpRecLineItem}}</a></div>{{/ErpRecLineItem}}
{{#ErpInvoice}}<div><b>ErpInvoice</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInvoice}}");}); return false;'>{{ErpInvoice}}</a></div>{{/ErpInvoice}}
{{#CustomerBillingInfos}}<div><b>CustomerBillingInfos</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/CustomerBillingInfos}}
{{#ErpQuoteLineItem}}<div><b>ErpQuoteLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpQuoteLineItem}}");}); return false;'>{{ErpQuoteLineItem}}</a></div>{{/ErpQuoteLineItem}}
{{#WorkBillingInfos}}<div><b>WorkBillingInfos</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WorkBillingInfos}}
{{#ContainerErpInvoiceLineItem}}<div><b>ContainerErpInvoiceLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ContainerErpInvoiceLineItem}}");}); return false;'>{{ContainerErpInvoiceLineItem}}</a></div>{{/ContainerErpInvoiceLineItem}}
{{#ComponentErpInvoiceLineItems}}<div><b>ComponentErpInvoiceLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ComponentErpInvoiceLineItems}}
{{#ErpJournalEntries}}<div><b>ErpJournalEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpJournalEntries}}
{{#ErpRecDelvLineItem}}<div><b>ErpRecDelvLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpRecDelvLineItem}}");}); return false;'>{{ErpRecDelvLineItem}}</a></div>{{/ErpRecDelvLineItem}}
{{#ErpPayableLineItem}}<div><b>ErpPayableLineItem</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpPayableLineItem}}");}); return false;'>{{ErpPayableLineItem}}</a></div>{{/ErpPayableLineItem}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
obj["kindErpInvoiceLineItemKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in ErpInvoiceLineItemKind) obj["kindErpInvoiceLineItemKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)});
if (obj["UserAttributes"]) obj["UserAttributes_string"] = obj["UserAttributes"].join ();
if (obj["ErpPayments"]) obj["ErpPayments_string"] = obj["ErpPayments"].join ();
if (obj["CustomerBillingInfos"]) obj["CustomerBillingInfos_string"] = obj["CustomerBillingInfos"].join ();
if (obj["WorkBillingInfos"]) obj["WorkBillingInfos_string"] = obj["WorkBillingInfos"].join ();
if (obj["ComponentErpInvoiceLineItems"]) obj["ComponentErpInvoiceLineItems_string"] = obj["ComponentErpInvoiceLineItems"].join ();
if (obj["ErpJournalEntries"]) obj["ErpJournalEntries_string"] = obj["ErpJournalEntries"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["kindErpInvoiceLineItemKind"];
delete obj["UserAttributes_string"];
delete obj["ErpPayments_string"];
delete obj["CustomerBillingInfos_string"];
delete obj["WorkBillingInfos_string"];
delete obj["ComponentErpInvoiceLineItems_string"];
delete obj["ErpJournalEntries_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpInvoiceLineItem_collapse" aria-expanded="true" aria-controls="{{id}}_ErpInvoiceLineItem_collapse" style="margin-left: 10px;">ErpInvoiceLineItem</a></legend>
<div id="{{id}}_ErpInvoiceLineItem_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_billPeriod'>billPeriod: </label><div class='col-sm-8'><input id='{{id}}_billPeriod' class='form-control' type='text'{{#billPeriod}} value='{{billPeriod}}'{{/billPeriod}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_glAccount'>glAccount: </label><div class='col-sm-8'><input id='{{id}}_glAccount' class='form-control' type='text'{{#glAccount}} value='{{glAccount}}'{{/glAccount}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_glDateTime'>glDateTime: </label><div class='col-sm-8'><input id='{{id}}_glDateTime' class='form-control' type='text'{{#glDateTime}} value='{{glDateTime}}'{{/glDateTime}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindErpInvoiceLineItemKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindErpInvoiceLineItemKind}}</select></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lineAmount'>lineAmount: </label><div class='col-sm-8'><input id='{{id}}_lineAmount' class='form-control' type='text'{{#lineAmount}} value='{{lineAmount}}'{{/lineAmount}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lineNumber'>lineNumber: </label><div class='col-sm-8'><input id='{{id}}_lineNumber' class='form-control' type='text'{{#lineNumber}} value='{{lineNumber}}'{{/lineNumber}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lineVersion'>lineVersion: </label><div class='col-sm-8'><input id='{{id}}_lineVersion' class='form-control' type='text'{{#lineVersion}} value='{{lineVersion}}'{{/lineVersion}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_netAmount'>netAmount: </label><div class='col-sm-8'><input id='{{id}}_netAmount' class='form-control' type='text'{{#netAmount}} value='{{netAmount}}'{{/netAmount}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_previousAmount'>previousAmount: </label><div class='col-sm-8'><input id='{{id}}_previousAmount' class='form-control' type='text'{{#previousAmount}} value='{{previousAmount}}'{{/previousAmount}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_UserAttributes'>UserAttributes: </label><div class='col-sm-8'><input id='{{id}}_UserAttributes' class='form-control' type='text'{{#UserAttributes}} value='{{UserAttributes_string}}'{{/UserAttributes}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayments'>ErpPayments: </label><div class='col-sm-8'><input id='{{id}}_ErpPayments' class='form-control' type='text'{{#ErpPayments}} value='{{ErpPayments_string}}'{{/ErpPayments}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecLineItem'>ErpRecLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpRecLineItem' class='form-control' type='text'{{#ErpRecLineItem}} value='{{ErpRecLineItem}}'{{/ErpRecLineItem}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoice'>ErpInvoice: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoice' class='form-control' type='text'{{#ErpInvoice}} value='{{ErpInvoice}}'{{/ErpInvoice}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CustomerBillingInfos'>CustomerBillingInfos: </label><div class='col-sm-8'><input id='{{id}}_CustomerBillingInfos' class='form-control' type='text'{{#CustomerBillingInfos}} value='{{CustomerBillingInfos_string}}'{{/CustomerBillingInfos}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpQuoteLineItem'>ErpQuoteLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpQuoteLineItem' class='form-control' type='text'{{#ErpQuoteLineItem}} value='{{ErpQuoteLineItem}}'{{/ErpQuoteLineItem}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WorkBillingInfos'>WorkBillingInfos: </label><div class='col-sm-8'><input id='{{id}}_WorkBillingInfos' class='form-control' type='text'{{#WorkBillingInfos}} value='{{WorkBillingInfos_string}}'{{/WorkBillingInfos}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ContainerErpInvoiceLineItem'>ContainerErpInvoiceLineItem: </label><div class='col-sm-8'><input id='{{id}}_ContainerErpInvoiceLineItem' class='form-control' type='text'{{#ContainerErpInvoiceLineItem}} value='{{ContainerErpInvoiceLineItem}}'{{/ContainerErpInvoiceLineItem}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecDelvLineItem'>ErpRecDelvLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpRecDelvLineItem' class='form-control' type='text'{{#ErpRecDelvLineItem}} value='{{ErpRecDelvLineItem}}'{{/ErpRecDelvLineItem}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayableLineItem'>ErpPayableLineItem: </label><div class='col-sm-8'><input id='{{id}}_ErpPayableLineItem' class='form-control' type='text'{{#ErpPayableLineItem}} value='{{ErpPayableLineItem}}'{{/ErpPayableLineItem}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "ErpInvoiceLineItem" };
super.submit (id, obj);
temp = document.getElementById (id + "_billPeriod").value; if ("" !== temp) obj["billPeriod"] = temp;
temp = document.getElementById (id + "_glAccount").value; if ("" !== temp) obj["glAccount"] = temp;
temp = document.getElementById (id + "_glDateTime").value; if ("" !== temp) obj["glDateTime"] = temp;
temp = ErpInvoiceLineItemKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ErpInvoiceLineItemKind." + temp; else delete obj["kind"];
temp = document.getElementById (id + "_lineAmount").value; if ("" !== temp) obj["lineAmount"] = temp;
temp = document.getElementById (id + "_lineNumber").value; if ("" !== temp) obj["lineNumber"] = temp;
temp = document.getElementById (id + "_lineVersion").value; if ("" !== temp) obj["lineVersion"] = temp;
temp = document.getElementById (id + "_netAmount").value; if ("" !== temp) obj["netAmount"] = temp;
temp = document.getElementById (id + "_previousAmount").value; if ("" !== temp) obj["previousAmount"] = temp;
temp = document.getElementById (id + "_UserAttributes").value; if ("" !== temp) obj["UserAttributes"] = temp.split (",");
temp = document.getElementById (id + "_ErpPayments").value; if ("" !== temp) obj["ErpPayments"] = temp.split (",");
temp = document.getElementById (id + "_ErpRecLineItem").value; if ("" !== temp) obj["ErpRecLineItem"] = temp;
temp = document.getElementById (id + "_ErpInvoice").value; if ("" !== temp) obj["ErpInvoice"] = temp;
temp = document.getElementById (id + "_CustomerBillingInfos").value; if ("" !== temp) obj["CustomerBillingInfos"] = temp.split (",");
temp = document.getElementById (id + "_ErpQuoteLineItem").value; if ("" !== temp) obj["ErpQuoteLineItem"] = temp;
temp = document.getElementById (id + "_WorkBillingInfos").value; if ("" !== temp) obj["WorkBillingInfos"] = temp.split (",");
temp = document.getElementById (id + "_ContainerErpInvoiceLineItem").value; if ("" !== temp) obj["ContainerErpInvoiceLineItem"] = temp;
temp = document.getElementById (id + "_ErpRecDelvLineItem").value; if ("" !== temp) obj["ErpRecDelvLineItem"] = temp;
temp = document.getElementById (id + "_ErpPayableLineItem").value; if ("" !== temp) obj["ErpPayableLineItem"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["UserAttributes", "0..*", "0..*", "UserAttribute", "ErpInvoiceLineItems"],
["ErpPayments", "0..*", "0..*", "ErpPayment", "ErpInvoiceLineItems"],
["ErpRecLineItem", "0..1", "0..1", "ErpRecLineItem", "ErpInvoiceLineItem"],
["ErpInvoice", "1", "0..*", "ErpInvoice", "ErpInvoiceLineItems"],
["CustomerBillingInfos", "0..*", "0..*", "CustomerBillingInfo", "ErpInvoiceLineItems"],
["ErpQuoteLineItem", "0..1", "0..1", "ErpQuoteLineItem", "ErpInvoiceLineItem"],
["WorkBillingInfos", "0..*", "0..*", "WorkBillingInfo", "ErpLineItems"],
["ContainerErpInvoiceLineItem", "0..1", "0..*", "ErpInvoiceLineItem", "ComponentErpInvoiceLineItems"],
["ComponentErpInvoiceLineItems", "0..*", "0..1", "ErpInvoiceLineItem", "ContainerErpInvoiceLineItem"],
["ErpJournalEntries", "0..*", "0..1", "ErpJournalEntry", "ErpInvoiceLineItem"],
["ErpRecDelvLineItem", "0..1", "0..1", "ErpRecDelvLineItem", "ErpInvoiceLineItem"],
["ErpPayableLineItem", "0..1", "0..1", "ErpPayableLineItem", "ErpInvoiceLineItem"]
]
)
);
}
} |
JavaScript | class ErpQuote extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpQuote;
if (null == bucket)
cim_data.ErpQuote = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpQuote[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpQuote";
base.parse_attributes (/<cim:ErpQuote.ErpQuoteLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpQuoteLineItems", sub, context);
let bucket = context.parsed.ErpQuote;
if (null == bucket)
context.parsed.ErpQuote = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpQuote", "ErpQuoteLineItems", "ErpQuoteLineItems", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpQuote_collapse" aria-expanded="true" aria-controls="ErpQuote_collapse" style="margin-left: 10px;">ErpQuote</a></legend>
<div id="ErpQuote_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpQuoteLineItems}}<div><b>ErpQuoteLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpQuoteLineItems}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpQuoteLineItems"]) obj["ErpQuoteLineItems_string"] = obj["ErpQuoteLineItems"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpQuoteLineItems_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpQuote_collapse" aria-expanded="true" aria-controls="{{id}}_ErpQuote_collapse" style="margin-left: 10px;">ErpQuote</a></legend>
<div id="{{id}}_ErpQuote_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpQuote" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpQuoteLineItems", "0..*", "1", "ErpQuoteLineItem", "ErpQuote"]
]
)
);
}
} |
JavaScript | class ErpLedger extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpLedger;
if (null == bucket)
cim_data.ErpLedger = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpLedger[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpLedger";
base.parse_attributes (/<cim:ErpLedger.ErpLedgerEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedgerEntries", sub, context);
let bucket = context.parsed.ErpLedger;
if (null == bucket)
context.parsed.ErpLedger = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpLedger", "ErpLedgerEntries", "ErpLedgerEntries", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpLedger_collapse" aria-expanded="true" aria-controls="ErpLedger_collapse" style="margin-left: 10px;">ErpLedger</a></legend>
<div id="ErpLedger_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpLedgerEntries}}<div><b>ErpLedgerEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpLedgerEntries}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpLedgerEntries"]) obj["ErpLedgerEntries_string"] = obj["ErpLedgerEntries"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpLedgerEntries_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpLedger_collapse" aria-expanded="true" aria-controls="{{id}}_ErpLedger_collapse" style="margin-left: 10px;">ErpLedger</a></legend>
<div id="{{id}}_ErpLedger_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpLedger" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpLedgerEntries", "0..*", "1", "ErpLedgerEntry", "ErpLedger"]
]
)
);
}
} |
JavaScript | class ErpEngChangeOrder extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpEngChangeOrder;
if (null == bucket)
cim_data.ErpEngChangeOrder = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpEngChangeOrder[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpEngChangeOrder";
let bucket = context.parsed.ErpEngChangeOrder;
if (null == bucket)
context.parsed.ErpEngChangeOrder = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpEngChangeOrder_collapse" aria-expanded="true" aria-controls="ErpEngChangeOrder_collapse" style="margin-left: 10px;">ErpEngChangeOrder</a></legend>
<div id="ErpEngChangeOrder_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpEngChangeOrder_collapse" aria-expanded="true" aria-controls="{{id}}_ErpEngChangeOrder_collapse" style="margin-left: 10px;">ErpEngChangeOrder</a></legend>
<div id="{{id}}_ErpEngChangeOrder_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpEngChangeOrder" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class ErpPayment extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpPayment;
if (null == bucket)
cim_data.ErpPayment = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpPayment[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpPayment";
base.parse_element (/<cim:ErpPayment.termsPayment>([\s\S]*?)<\/cim:ErpPayment.termsPayment>/g, obj, "termsPayment", base.to_string, sub, context);
base.parse_attributes (/<cim:ErpPayment.ErpPayableLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPayableLineItems", sub, context);
base.parse_attributes (/<cim:ErpPayment.ErpInvoiceLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInvoiceLineItems", sub, context);
base.parse_attributes (/<cim:ErpPayment.ErpRecLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecLineItems", sub, context);
let bucket = context.parsed.ErpPayment;
if (null == bucket)
context.parsed.ErpPayment = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_element (obj, "ErpPayment", "termsPayment", "termsPayment", base.from_string, fields);
base.export_attributes (obj, "ErpPayment", "ErpPayableLineItems", "ErpPayableLineItems", fields);
base.export_attributes (obj, "ErpPayment", "ErpInvoiceLineItems", "ErpInvoiceLineItems", fields);
base.export_attributes (obj, "ErpPayment", "ErpRecLineItems", "ErpRecLineItems", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPayment_collapse" aria-expanded="true" aria-controls="ErpPayment_collapse" style="margin-left: 10px;">ErpPayment</a></legend>
<div id="ErpPayment_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#termsPayment}}<div><b>termsPayment</b>: {{termsPayment}}</div>{{/termsPayment}}
{{#ErpPayableLineItems}}<div><b>ErpPayableLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPayableLineItems}}
{{#ErpInvoiceLineItems}}<div><b>ErpInvoiceLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpInvoiceLineItems}}
{{#ErpRecLineItems}}<div><b>ErpRecLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpRecLineItems}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpPayableLineItems"]) obj["ErpPayableLineItems_string"] = obj["ErpPayableLineItems"].join ();
if (obj["ErpInvoiceLineItems"]) obj["ErpInvoiceLineItems_string"] = obj["ErpInvoiceLineItems"].join ();
if (obj["ErpRecLineItems"]) obj["ErpRecLineItems_string"] = obj["ErpRecLineItems"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpPayableLineItems_string"];
delete obj["ErpInvoiceLineItems_string"];
delete obj["ErpRecLineItems_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPayment_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPayment_collapse" style="margin-left: 10px;">ErpPayment</a></legend>
<div id="{{id}}_ErpPayment_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_termsPayment'>termsPayment: </label><div class='col-sm-8'><input id='{{id}}_termsPayment' class='form-control' type='text'{{#termsPayment}} value='{{termsPayment}}'{{/termsPayment}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpPayableLineItems'>ErpPayableLineItems: </label><div class='col-sm-8'><input id='{{id}}_ErpPayableLineItems' class='form-control' type='text'{{#ErpPayableLineItems}} value='{{ErpPayableLineItems_string}}'{{/ErpPayableLineItems}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInvoiceLineItems'>ErpInvoiceLineItems: </label><div class='col-sm-8'><input id='{{id}}_ErpInvoiceLineItems' class='form-control' type='text'{{#ErpInvoiceLineItems}} value='{{ErpInvoiceLineItems_string}}'{{/ErpInvoiceLineItems}}></div></div>
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecLineItems'>ErpRecLineItems: </label><div class='col-sm-8'><input id='{{id}}_ErpRecLineItems' class='form-control' type='text'{{#ErpRecLineItems}} value='{{ErpRecLineItems_string}}'{{/ErpRecLineItems}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "ErpPayment" };
super.submit (id, obj);
temp = document.getElementById (id + "_termsPayment").value; if ("" !== temp) obj["termsPayment"] = temp;
temp = document.getElementById (id + "_ErpPayableLineItems").value; if ("" !== temp) obj["ErpPayableLineItems"] = temp.split (",");
temp = document.getElementById (id + "_ErpInvoiceLineItems").value; if ("" !== temp) obj["ErpInvoiceLineItems"] = temp.split (",");
temp = document.getElementById (id + "_ErpRecLineItems").value; if ("" !== temp) obj["ErpRecLineItems"] = temp.split (",");
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpPayableLineItems", "0..*", "0..*", "ErpPayableLineItem", "ErpPayments"],
["ErpInvoiceLineItems", "0..*", "0..*", "ErpInvoiceLineItem", "ErpPayments"],
["ErpRecLineItems", "0..*", "0..*", "ErpRecLineItem", "ErpPayments"]
]
)
);
}
} |
JavaScript | class ErpPurchaseOrder extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpPurchaseOrder;
if (null == bucket)
cim_data.ErpPurchaseOrder = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpPurchaseOrder[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpPurchaseOrder";
base.parse_attributes (/<cim:ErpPurchaseOrder.ErpPOLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpPOLineItems", sub, context);
let bucket = context.parsed.ErpPurchaseOrder;
if (null == bucket)
context.parsed.ErpPurchaseOrder = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpPurchaseOrder", "ErpPOLineItems", "ErpPOLineItems", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpPurchaseOrder_collapse" aria-expanded="true" aria-controls="ErpPurchaseOrder_collapse" style="margin-left: 10px;">ErpPurchaseOrder</a></legend>
<div id="ErpPurchaseOrder_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpPOLineItems}}<div><b>ErpPOLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpPOLineItems}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpPOLineItems"]) obj["ErpPOLineItems_string"] = obj["ErpPOLineItems"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpPOLineItems_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpPurchaseOrder_collapse" aria-expanded="true" aria-controls="{{id}}_ErpPurchaseOrder_collapse" style="margin-left: 10px;">ErpPurchaseOrder</a></legend>
<div id="{{id}}_ErpPurchaseOrder_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpPurchaseOrder" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpPOLineItems", "0..*", "1", "ErpPOLineItem", "ErpPurchaseOrder"]
]
)
);
}
} |
JavaScript | class ErpChartOfAccounts extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpChartOfAccounts;
if (null == bucket)
cim_data.ErpChartOfAccounts = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpChartOfAccounts[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpChartOfAccounts";
let bucket = context.parsed.ErpChartOfAccounts;
if (null == bucket)
context.parsed.ErpChartOfAccounts = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpChartOfAccounts_collapse" aria-expanded="true" aria-controls="ErpChartOfAccounts_collapse" style="margin-left: 10px;">ErpChartOfAccounts</a></legend>
<div id="ErpChartOfAccounts_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
}
uncondition (obj)
{
super.uncondition (obj);
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpChartOfAccounts_collapse" aria-expanded="true" aria-controls="{{id}}_ErpChartOfAccounts_collapse" style="margin-left: 10px;">ErpChartOfAccounts</a></legend>
<div id="{{id}}_ErpChartOfAccounts_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpChartOfAccounts" };
super.submit (id, obj);
return (obj);
}
} |
JavaScript | class ErpJournal extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpJournal;
if (null == bucket)
cim_data.ErpJournal = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpJournal[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpJournal";
base.parse_attributes (/<cim:ErpJournal.ErpJournalEntries\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpJournalEntries", sub, context);
let bucket = context.parsed.ErpJournal;
if (null == bucket)
context.parsed.ErpJournal = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpJournal", "ErpJournalEntries", "ErpJournalEntries", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpJournal_collapse" aria-expanded="true" aria-controls="ErpJournal_collapse" style="margin-left: 10px;">ErpJournal</a></legend>
<div id="ErpJournal_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpJournalEntries}}<div><b>ErpJournalEntries</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpJournalEntries}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpJournalEntries"]) obj["ErpJournalEntries_string"] = obj["ErpJournalEntries"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpJournalEntries_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpJournal_collapse" aria-expanded="true" aria-controls="{{id}}_ErpJournal_collapse" style="margin-left: 10px;">ErpJournal</a></legend>
<div id="{{id}}_ErpJournal_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpJournal" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpJournalEntries", "0..*", "1", "ErpJournalEntry", "ErpJournal"]
]
)
);
}
} |
JavaScript | class ErpLedgerBudget extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpLedgerBudget;
if (null == bucket)
cim_data.ErpLedgerBudget = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpLedgerBudget[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpLedgerBudget";
base.parse_attributes (/<cim:ErpLedgerBudget.ErpLedBudLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpLedBudLineItems", sub, context);
let bucket = context.parsed.ErpLedgerBudget;
if (null == bucket)
context.parsed.ErpLedgerBudget = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attributes (obj, "ErpLedgerBudget", "ErpLedBudLineItems", "ErpLedBudLineItems", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpLedgerBudget_collapse" aria-expanded="true" aria-controls="ErpLedgerBudget_collapse" style="margin-left: 10px;">ErpLedgerBudget</a></legend>
<div id="ErpLedgerBudget_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#ErpLedBudLineItems}}<div><b>ErpLedBudLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpLedBudLineItems}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpLedBudLineItems"]) obj["ErpLedBudLineItems_string"] = obj["ErpLedBudLineItems"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpLedBudLineItems_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpLedgerBudget_collapse" aria-expanded="true" aria-controls="{{id}}_ErpLedgerBudget_collapse" style="margin-left: 10px;">ErpLedgerBudget</a></legend>
<div id="{{id}}_ErpLedgerBudget_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
</div>
</fieldset>
`
);
}
submit (id, obj)
{
obj = obj || { id: id, cls: "ErpLedgerBudget" };
super.submit (id, obj);
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["ErpLedBudLineItems", "0..*", "1", "ErpLedBudLineItem", "ErpLedgerBudget"]
]
)
);
}
} |
JavaScript | class ErpBOM extends ErpDocument
{
constructor (template, cim_data)
{
super (template, cim_data);
let bucket = cim_data.ErpBOM;
if (null == bucket)
cim_data.ErpBOM = bucket = {};
bucket[template.id] = template;
}
remove (obj, cim_data)
{
super.remove (obj, cim_data);
delete cim_data.ErpBOM[obj.id];
}
parse (context, sub)
{
let obj = ErpDocument.prototype.parse.call (this, context, sub);
obj.cls = "ErpBOM";
base.parse_attribute (/<cim:ErpBOM.Design\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Design", sub, context);
base.parse_attributes (/<cim:ErpBOM.ErpBomItemDatas\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpBomItemDatas", sub, context);
let bucket = context.parsed.ErpBOM;
if (null == bucket)
context.parsed.ErpBOM = bucket = {};
bucket[obj.id] = obj;
return (obj);
}
export (obj, full)
{
let fields = ErpDocument.prototype.export.call (this, obj, false);
base.export_attribute (obj, "ErpBOM", "Design", "Design", fields);
base.export_attributes (obj, "ErpBOM", "ErpBomItemDatas", "ErpBomItemDatas", fields);
if (full)
base.Element.prototype.export.call (this, obj, fields);
return (fields);
}
template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ErpBOM_collapse" aria-expanded="true" aria-controls="ErpBOM_collapse" style="margin-left: 10px;">ErpBOM</a></legend>
<div id="ErpBOM_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.template.call (this) +
`
{{#Design}}<div><b>Design</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Design}}");}); return false;'>{{Design}}</a></div>{{/Design}}
{{#ErpBomItemDatas}}<div><b>ErpBomItemDatas</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpBomItemDatas}}
</div>
</fieldset>
`
);
}
condition (obj)
{
super.condition (obj);
if (obj["ErpBomItemDatas"]) obj["ErpBomItemDatas_string"] = obj["ErpBomItemDatas"].join ();
}
uncondition (obj)
{
super.uncondition (obj);
delete obj["ErpBomItemDatas_string"];
}
edit_template ()
{
return (
`
<fieldset>
<legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ErpBOM_collapse" aria-expanded="true" aria-controls="{{id}}_ErpBOM_collapse" style="margin-left: 10px;">ErpBOM</a></legend>
<div id="{{id}}_ErpBOM_collapse" class="collapse in show" style="margin-left: 10px;">
`
+ ErpDocument.prototype.edit_template.call (this) +
`
<div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Design'>Design: </label><div class='col-sm-8'><input id='{{id}}_Design' class='form-control' type='text'{{#Design}} value='{{Design}}'{{/Design}}></div></div>
</div>
</fieldset>
`
);
}
submit (id, obj)
{
let temp;
obj = obj || { id: id, cls: "ErpBOM" };
super.submit (id, obj);
temp = document.getElementById (id + "_Design").value; if ("" !== temp) obj["Design"] = temp;
return (obj);
}
relations ()
{
return (
super.relations ().concat (
[
["Design", "0..1", "0..*", "Design", "ErpBOMs"],
["ErpBomItemDatas", "0..*", "1", "ErpBomItemData", "ErpBOM"]
]
)
);
}
} |
Subsets and Splits