language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Publish extends command_1.Command { // octokit = new Octokit() async run() { this.warn('TODO: finish this'); // if (!process.env.GH_TOKEN) throw new Error('GH_TOKEN must be set') // const {flags} = this.parse(Publish) // if (process.platform === 'win32') throw new Error('pack does not function on windows') // const {'node-version': nodeVersion, prerelease, draft} = flags // const channel = flags.prerelease ? 'prerelease' : 'stable' // const root = path.resolve(flags.root) // const config = await Tarballs.config(root) // const version = config.version // const baseWorkspace = qq.join([config.root, 'tmp', 'base']) // const updateConfig = config.pjson.oclif.update || {} // const targets = updateConfig.node && updateConfig.node.targets || [] // if (!targets) throw new Error('specify oclif.targets in package.json') // // first create the generic base workspace that will be copied later // await Tarballs.build({config, channel, output: baseWorkspace, version}) // const tarballs: {target: string, tarball: string}[] = [] // for (let [platform, arch] of targets.map(t => t.split('-'))) { // const t = await Tarballs.target({config, platform, arch, channel, version, baseWorkspace, nodeVersion, xz: flags.xz}) // tarballs.push(t) // } // this.octokit.authenticate({ // type: 'token', // token: process.env.GH_TOKEN, // }) // const tag = `v${version}` // const [owner, repo] = config.pjson.repository.split('/') // const commitish = await Tarballs.gitSha(config.root) // const release = await this.findOrCreateRelease({owner, repo, tag, prerelease, draft, commitish}) // for (let {tarball} of tarballs) { // await this.addFileToRelease(release, `${tarball}.tar.gz`) // if (flags.xz) await this.addFileToRelease(release, `${tarball}.tar.xz`) // } // } // async findOrCreateRelease({owner, repo, tag, prerelease, draft, commitish}: {owner: string, repo: string, tag: string, prerelease: boolean, draft: boolean, commitish: string}) { // const findRelease = async () => { // const {data} = await this.octokit.repos.getReleaseByTag({owner, repo, tag}) // action(`found existing release ${tag}`) // return data // } // const createRelease = async () => { // action(`creating ${tag} release`) // const {data} = await this.octokit.repos.createRelease({ // owner, // repo, // target_commitish: commitish, // tag_name: tag, // prerelease, // draft, // }) // return data // } // try { // return await findRelease() // } catch (err) { // this.debug(err) // } // return createRelease() // } // async addFileToRelease(release: {upload_url: string}, file: string) { // action(`uploading ${file}`) // await this.octokit.repos.uploadAsset({ // url: release.upload_url, // file: fs.createReadStream(file), // contentType: 'application/gzip', // contentLength: fs.statSync(file).size, // name: qq.path.basename(file), // label: qq.path.basename(file), // }) } }
JavaScript
class ApplicationRoute extends Route.extend( ApplicationRouteMixin, EnsureStatefulLogin, ) { @service session; @service confirm; @service flashMessages; @service raven; @alias('session.currentUser') currentUser; @service launchDarkly; @service redirects; @service intercom; beforeModel(transition) { super.beforeModel(...arguments); this._storeTargetTransition(transition); if (!this.get('session.isAuthenticated')) { // When running our development environment with a production API, we need to shortcut the // auth flow otherwise you'll get CSRF detected errors from Auth0. This is somewhat of a hack // and means you won't be able to log out or test login functionality in this mode. if (isDevWithProductionAPI()) { this.set('session.isAuthenticated', true); } } return this._loadLaunchDarkly().then(() => { return this._loadCurrentUser(); }); } // Special case: turn off ember-simple-auth-auth0's application-route-mixin expiration timer. // This fixes a specific "mixed auth state" bug where the frontend session can be expired // while the backend API session still exists. This bug can only happen when both 1) the user has // third-party cookies disabled which breaks Silent Auth, and 2) they have a long-lived tab open // which triggers this session expiration. // // Preventing the frontend session from being cleared in the current tab ensures that, // on refresh or next page load, the user will go through a full invalidateAndLogout flow so both // frontend/backend sessions will be in sync. See authenticators/auth0-url-hash.js for more info. beforeSessionExpired() { return reject(); } async _loadLaunchDarkly() { const anonUser = {key: 'anon', anonymous: true}; try { return this.launchDarkly.initialize(anonUser); } catch (e) { // If anything goes wrong with the launch darkly identification, don't crash the app, // just return a resolved promise so the app can keep loading. return resolve(); } } sessionAuthenticated() { // This method is called after the session is authenticated by ember-simple-auth. // By default, it executes some pre-set redirects but we want our own redirect logic, // so we're not calling super here. this._loadCurrentUser().then(() => { this.closeLock(); this._decideRedirect(); }); } _loadCurrentUser() { return this.session.loadCurrentUser().catch(() => { return this._showLoginFailedFlashMessage(); }); } @action showSupport() { // This is necessary for some controller templates and the error template, but otherwise, // please import use the service locally. this.intercom.showIntercom(); } @action showLoginModal() { this.showLoginModalEnsuringState(); } @action logout() { this.session.invalidateAndLogout(); } @action navigateToProject(project) { let organizationSlug = project.get('organization.slug'); let projectSlug = project.get('slug'); this.transitionTo('organization.project.index', organizationSlug, projectSlug); } @action navigateToOrganizationBilling(organization) { let organizationSlug = organization.get('slug'); this.transitionTo('organizations.organization.billing', organizationSlug); } @action navigateToProjectSettings(project) { let organizationSlug = project.get('organization.slug'); let projectSlug = project.get('slug'); this.transitionTo('organization.project.settings', organizationSlug, projectSlug); } // See: https://github.com/damiencaselli/ember-cli-sentry/issues/105 @action error(error) { if (this.get('raven.isRavenUsable')) { this.raven.captureException(error); } return true; // Let the route above this handle the error. } _storeTargetTransition(transition) { const attemptedRoute = transition.targetName; if (!DO_NOT_FORWARD_REDIRECT_ROUTES.includes(attemptedRoute)) { const attemptedTransitionUrl = transition.intent.url; localStorageProxy.set(AUTH_REDIRECT_LOCALSTORAGE_KEY, attemptedTransitionUrl, { useSessionStorage: true, }); } } _decideRedirect() { const redirectAddress = localStorageProxy.get(AUTH_REDIRECT_LOCALSTORAGE_KEY, '/', { useSessionStorage: true, }); if (redirectAddress) { if (redirectAddress === '/') { this.redirects.redirectToDefaultOrganization(); } else { localStorageProxy.removeItem(AUTH_REDIRECT_LOCALSTORAGE_KEY, {useSessionStorage: true}); this.transitionTo(redirectAddress); } } else { this.redirects.redirectToDefaultOrganization(); } } activate() { this.flashMessages.displayLocalStorageMessages(); } _showLoginFailedFlashMessage() { this.flashMessages.createPersistentFlashMessage( { type: 'danger', message: 'There was a problem with logging in. \ Please try again or contact us if the issue does not resolve.', sticky: true, }, {persistentReloads: 1}, ); } }
JavaScript
class OmniboxElement extends HTMLElement { /** @param {string} templateId */ constructor(templateId) { super(); this.attachShadow({mode: 'open'}); const template = OmniboxElement.getTemplate(templateId); this.shadowRoot.appendChild(template); /** @type {!ShadowRoot} */ this.shadowRoot; } /** * Finds the 1st element matching the query within the local shadow root. At * least 1 matching element should exist. * @param {string} query * @return {!Element} */ $(query) { return OmniboxElement.getByQuery_(query, this.shadowRoot); } /** * Finds all elements matching the query within the local shadow root. * @param {string} query * @return {!NodeList<!Element>} */ $$(query) { return (this.shadowRoot || document).querySelectorAll(query); } /** * Get a template that's known to exist within the DOM document. * @param {string} templateId * @return {!Element} */ static getTemplate(templateId) { return OmniboxElement.getByQuery_('#' + templateId).content.cloneNode(true); } /** * Get an element that's known to exist by query. Unlike querySelector, this * satisfies the JSCompiler type system. * @private * @param {string} query * @param {!Node=} context * @return {!Element} */ static getByQuery_(query, context) { return assertInstanceof( (context || document).querySelector(query), Element, `Missing required element: ${query}`); } }
JavaScript
class BenutzerListenEintrag extends Component { constructor(props) { super(props); // Init state this.state = { benutzer: props.benutzer, showBenutzerForm: false, showBenutzerDeleteDialog: false, }; } /** Behandelt das onClose Ereignis vom BenutzerForm */ benutzerFormClosed = (benutzer) => { // Einzelhaendler ist nicht null und deshalb geändert. if (benutzer) { this.setState({ benutzer: benutzer, showBenutzerForm: false }); } else { this.setState({ showBenutzerForm: false }); } } /** Behandelt das onClick Ereignis von der Einzelhaendler löschen Taste. */ deleteBenutzerButtonClicked = (event) => { event.stopPropagation(); this.setState({ showBenutzerDeleteDialog: true }); } /** Behandelt das onClose Ereignis vom EinzelhaendlerLoeschenDialog */ deleteBenutzerDialogClosed = (benutzer) => { // Wenn der Einzelhaendler nicht gleich null ist, lösche ihn if (benutzer) { this.props.onBenutzerDeleted(benutzer); }; // Zeige nicht den Dialog this.setState({ showBenutzerDeleteDialog: false }); } /** Rendert den Komponent */ render() { const { classes, anwenderverbund, userMail } = this.props; const { benutzer, showBenutzerDeleteDialog } = this.state; return ( <div> <Grid container spacing={3} justify='flex-start' alignItems='center'> <Grid item> <Typography variant='body1' className={classes.heading}>{benutzer.getName()} </Typography> </Grid> <Grid item> <ButtonGroup variant='text' size='small'> {benutzer.getEMail() === userMail? <Button color='secondary' startIcon={<DeleteIcon/>} onClick={this.deleteBenutzerButtonClicked}> verlassen </Button> : null } </ButtonGroup> </Grid> <Grid item xs /> </Grid> <BenutzerListeneintragLoeschen anwenderverbund={anwenderverbund} show={showBenutzerDeleteDialog} benutzer={benutzer} onClose={this.deleteBenutzerDialogClosed} /> </div> ); } }
JavaScript
class Color { constructor() { /** * Initiate basic Color picker */ $('.color-picker').colorpicker({ format: 'hex' }); } }
JavaScript
class InvalidAssociativeArrayError extends Error { constructor(...args) { super(...args) this.code = 'E_INVALID_ASSOCIATIVE_ARRAY' } }
JavaScript
class SCountdownComponent extends SWebComponent { /** * Default props * @definition SWebComponent.defaultProps * @protected */ static get defaultProps() { return { /** * Specify the end timestamp of the countdown * @prop * @type {Integer} */ endTimestamp: null, /** * Specify the start timestamp of the countdown. * @prop * @type {Integer} */ startTimestamp: null, /** * Specify some step classes that will be applied on the component itself depending on remaining seconds * For example. A step class named `hour1` with a timing of `3600` will be applied during the last `3600` seconds of the countdown * @prop * @type {Object<Integer>} */ stepClasses: { week1: 3600 * 24 * 7, day1: 3600 * 24, hour1: 3600, minutes30: 60 * 30, minutes10: 60 * 10, minutes5: 60 * 5, minute1: 60 }, /** * Specify a callback to call on countdown complete * @prop * @type {Function} */ onComplete: null, /** * Specify a callback to call on each tick * @prop * @type {Function} */ onTick: null } } /** * Required props * @definition SWebComponent.requiredProps * @protected */ static get requiredProps() { return ["endTimestamp"] } /** * Css * @protected */ static defaultCss(componentName, componentNameDash) { return ` ${componentNameDash} { display : inline-block; } .${componentNameDash}-digit { display : inline-block; } ` } /** * Mount component * @definition SWebComponent.componentMount * @protected */ componentMount() { super.componentMount() // add the global class on the element itself this.classList.add(this.componentNameDash) // add the active class on the element itself this.classList.add("active") // update html refs to elements like the $years, $months, $days, $hours, $minutes and $seconds this._update$Refs() // create a new timer this._timer = new STimer(1000, { loop: true }) this._timer.onComplete(this._tick.bind(this)) this._timer.start() // first tick this._tick() } /** * Unmount component * @definition SWebComponent.componentUnmount * @protected */ componentUnmount() { // destroy the timer this._timer.destroy() } /** * Update the reefa to HTMLElements */ _update$Refs() { this._$years = this.querySelector(`[${this.componentNameDash}-years]`) if (this._$years) this._$years.classList.add(`${this.componentNameDash}-digit-container`) this._$months = this.querySelector(`[${this.componentNameDash}-months]`) if (this._$months) this._$months.classList.add(`${this.componentNameDash}-digit-container`) this._$days = this.querySelector(`[${this.componentNameDash}-days]`) if (this._$days) this._$days.classList.add(`${this.componentNameDash}-digit-container`) this._$hours = this.querySelector(`[${this.componentNameDash}-hours]`) if (this._$hours) this._$hours.classList.add(`${this.componentNameDash}-digit-container`) this._$minutes = this.querySelector(`[${this.componentNameDash}-minutes]`) if (this._$minutes) this._$minutes.classList.add(`${this.componentNameDash}-digit-container`) this._$seconds = this.querySelector(`[${this.componentNameDash}-seconds]`) if (this._$seconds) this._$seconds.classList.add(`${this.componentNameDash}-digit-container`) } /** * Tick function */ _tick() { // start date let start = Date.now() if (this.props.startTimestamp) { start = new Date(this.props.startTimestamp * 1000) } // check if it's the end of the countdown if (this.props.endTimestamp < start / 1000) { // stop the timer this._timer.stop() // remove the active class on the element itself this.classList.remove("active") // wait 1 second to compense the countdown display setTimeout(() => { // onComplete callback if (this.props.onComplete) this.props.onComplete(this) }, 1000) } // get the timespan object from now to the end of the countdown this._timespan = countdown( start, new Date( this.props.endTimestamp < start / 1000 ? Date.now() : this.props.endTimestamp * 1000 ) ) // calculate the number of seconds left const secondsLeft = (this._timespan.end.getTime() - this._timespan.start.getTime()) / 1000 console.log(secondsLeft) // loop on each stepClasses to apply them if needed for (const key in this.props.stepClasses) { const value = this.props.stepClasses[key] if (secondsLeft <= value) { this.classList.add(key) } } // update html using the timespan this._updateHtmlWithTimespan(this._timespan) // on tick callback if (this.props.onTick) this.props.onTick(this) } /** * Update the html with the timespan * @param {Object} timespan The timespan object containing the years, months, days, hours, minutes and seconds remaining */ _updateHtmlWithTimespan(timespan) { if (this._$years && timespan.years !== undefined) { this._updateDigit(this._$years, timespan.years) } if (this._$months && timespan.months !== undefined) { this._updateDigit(this._$months, timespan.months) } if (this._$days && timespan.days !== undefined) { this._updateDigit(this._$days, timespan.days) } if (this._$hours && timespan.hours !== undefined) { this._updateDigit(this._$hours, timespan.hours) } if (this._$minutes && timespan.minutes !== undefined) { this._updateDigit(this._$minutes, timespan.minutes) } if (this._$seconds && timespan.seconds !== undefined) { this._updateDigit(this._$seconds, timespan.seconds) } } /** * Update a digit * @param {HTMLElement} $elm The HTMLElement to update * @param {String} value The new HTMLElement value */ _updateDigit($elm, value) { // query the actual item in the html element const $actualElm = $elm.children[0] let duration = 0 if ($actualElm && $actualElm.tagName) { if ($actualElm.innerHTML === value.toString()) return // add the `out` class $actualElm.classList.add(`${this.componentNameDash}-digit--out`) duration = getTransmationDuration($actualElm) } // append the new child const $newElm = document.createElement("span") $newElm.classList.add(`${this.componentNameDash}-digit`) $newElm.innerHTML = value // remove the old and add the new element // after than the old element has been animated/transitionned out setTimeout(() => { if ($actualElm && $actualElm.tagName) $elm.removeChild($actualElm) $elm.appendChild($newElm) }, duration) } /** * Get the remaining years * @return {Integer} The years remaining */ getYears() { return this._timespan.years || 0 } /** * Get the remaining months * @return {Integer} The months remaining */ getMonths() { return this._timespan.months || 0 } /** * Get the remaining days * @return {Integer} The days remaining */ getDays() { return this._timespan.days || 0 } /** * Get the remaining hours * @return {Integer} The hours remaining */ getHours() { return this._timespan.hours || 0 } /** * Get the remaining minutes * @return {Integer} The minutes remaining */ getMinutes() { return this._timespan.minutes || 0 } /** * Get the remaining seconds * @return {Integer} The seconds remaining */ getSeconds() { return this._timespan.seconds || 0 } }
JavaScript
class URLCrawlerReportUI { static get_open_section() { return $('.sui-accordion-item--open'); } static get_open_section_type() { return URLCrawlerReportUI.get_open_section().data('type'); } static is_ignored_tab_open() { return URLCrawlerReportUI.get_open_section().find('[data-tabs] .active').is('.ignored'); } static replace_report_markup(new_markup) { $('.wds-crawl-results-report').replaceWith(new_markup); } static replace_summary_markup(new_markup) { $('#wds-crawl-summary-container').html(new_markup); } static get_issue_id($context) { return $context.closest('[data-issue-id]').data('issueId'); } static get_path($context) { return $context.closest('[data-path]').data('path'); } static get_redirect_path($context) { return $context.closest('[data-redirect-path]').data('redirectPath'); } static get_issue_ids($context) { let $group_container = $context.closest('.wds-crawl-issues-table'), $issue_container = $group_container.length ? $group_container : $context.closest('.tab_url_crawler'), $issues = $issue_container.find('[data-issue-id]'), issue_ids = []; $issues.each(function (index, issue) { issue_ids.push($(issue).data('issueId')); }); return issue_ids; } static block_ui($target_el) { if ($target_el.closest('.wds-links-dropdown').length) { $target_el = $target_el.closest('.wds-links-dropdown').find('.sui-dropdown-anchor'); } if ($target_el.is('.sui-button-onload')) { // Already blocked return; } $target_el.addClass('sui-button-onload'); $('.wds-disabled-during-request').prop('disabled', true); } static unblock_ui() { $('.wds-disabled-during-request').prop('disabled', false); $('.sui-button-onload').removeClass('sui-button-onload'); } static show_sitemap_message($message, $context) { let $tabs = $context.closest('.sui-tabs'); if (!$tabs.length) { return; } $tabs.prev('.wds-notice').remove(); $message.insertBefore($tabs); } static get_sitemap_path($context) { return $context.closest('[data-issue-id]').data('path'); } static get_sitemap_paths($context) { let $container = $context.closest('.wds-crawl-issues-table'), $issues = $container.find('[data-issue-id]'), paths = []; $issues.each(function (index, issue) { paths.push($(issue).data('path')); }); return paths; } static get_dialog($context) { return $context.closest('.sui-dialog'); } static get_redirect_data($context) { let $modal = URLCrawlerReportUI.get_dialog($context), $fields = $modal.find("input"), data = {}; $fields.each(function () { let $me = $(this); data[$me.attr("name")] = $me.val(); }); return data; } static open_dialog(dialog_id) { let dialog_el = $('#' + dialog_id), dialog = dialog_el.length ? new A11yDialog(dialog_el[0]) : false; if (dialog) { dialog.show(); } } static close_dialog($context) { URLCrawlerReportUI.get_dialog($context).find(".sui-dialog-close").click(); } static replace_dialog_markup(dialog, markup) { $('#' + dialog).replaceWith(markup); } static validate_dialog(dialog_id) { let is_valid = true; $('.sui-form-field', $('#' + dialog_id)).each(function () { let $form_field = $(this), $input = $('input', $form_field); if (!$input.val()) { is_valid = false; $form_field.addClass('sui-form-field-error'); $input.on('focus keydown', function () { $(this).closest('.sui-form-field-error').removeClass('sui-form-field-error'); }); } }); return is_valid; } }
JavaScript
class URLCrawlerReport { init() { $(document) .on('click', '[href="#ignore"]', (e) => this.handle_ignore_single_action(e)) .on('click', '.wds-crawl-issues-table .wds-ignore-all', (e) => this.handle_ignore_group_action(e)) .on('click', '.sui-box-header .wds-ignore-all', (e) => this.handle_ignore_all_action(e)) .on('click', '.wds-ignored-items-table .wds-unignore', (e) => this.handle_restore_single_action(e)) .on('click', '[href="#add-to-sitemap"]', (e) => this.handle_add_single_to_sitemap_action(e)) .on('click', '.wds-crawl-issues-table .wds-add-all-to-sitemap', (e) => this.handle_add_all_to_sitemap_action(e)) .on('click', '[href="#occurrences"]', (e) => this.handle_open_occurrences_dialog_action(e)) .on('click', '[href="#redirect"]', (e) => this.handle_open_redirect_dialog_action(e)) .on('click', '.wds-submit-redirect', (e) => this.handle_save_redirect_action(e)) ; this.templates = { redirect_dialog: Wds.tpl_compile(Wds.template('url_crawler', 'redirect_dialog')), occurrences_dialog: Wds.tpl_compile(Wds.template('url_crawler', 'occurrences_dialog')), issue_occurrences: Wds.tpl_compile(Wds.template('url_crawler', 'issue_occurrences')) }; this.occurrences_request = new $.Deferred(); } post(action, data) { data = $.extend({ action: action, _wds_nonce: _wds_sitemaps.nonce }, data); return $.post(ajaxurl, data); } reload_report() { return this.post('wds-get-sitemap-report', { open_type: URLCrawlerReportUI.get_open_section_type(), ignored_tab_open: URLCrawlerReportUI.is_ignored_tab_open() ? 1 : 0 }).done( /** * @param {{summary_markup:string, markup:string}} data */ (data) => { data = (data || {}); if (data.success && data.markup) { URLCrawlerReportUI.replace_report_markup(data.markup); URLCrawlerReportUI.replace_summary_markup(data.summary_markup); URLCrawlerReportUI.unblock_ui(); $(this).trigger('wds_url_crawler_report:reloaded'); } }); } change_issue_status(issue_id, action) { return this.post(action, {issue_id: issue_id}) .done((data) => { let status = parseInt( (data || {}).status || '0', 10 ); if (status > 0) { this.reload_report(); } }); } ignore_issue(issue_id) { return this.change_issue_status(issue_id, 'wds-service-ignore'); } restore_issue(issue_id) { return this.change_issue_status(issue_id, 'wds-service-unignore'); } handle_ignore_single_action(e) { e.preventDefault(); let $target = $(e.target), issue_id = URLCrawlerReportUI.get_issue_id($target); URLCrawlerReportUI.block_ui($target); return this.ignore_issue(issue_id); } handle_restore_single_action(e) { e.preventDefault(); let $target = $(e.target), issue_id = URLCrawlerReportUI.get_issue_id($target); URLCrawlerReportUI.block_ui($target); return this.restore_issue(issue_id); } handle_ignore_group_action(e) { e.preventDefault(); let $target = $(e.target), issue_ids = URLCrawlerReportUI.get_issue_ids($target); URLCrawlerReportUI.block_ui($target); return this.ignore_issue(issue_ids); } handle_ignore_all_action(e) { e.preventDefault(); let $target = $(e.target), issue_ids = URLCrawlerReportUI.get_issue_ids($target); URLCrawlerReportUI.block_ui($target); return this.ignore_issue(issue_ids); } add_to_sitemap(path, $context) { return this.post('wds-sitemap-add_extra', {path: path}) .done( /** * @param {{status:string, add_all_message:string}} data */ (data) => { data = (data || {}); let status = parseInt( data.status || '0', 10 ); if (status > 0) { let $message = $(data.add_all_message || ''); URLCrawlerReportUI.show_sitemap_message($message, $context); URLCrawlerReportUI.unblock_ui(); } }); } handle_add_single_to_sitemap_action(e) { e.preventDefault(); let $target = $(e.target), path = URLCrawlerReportUI.get_sitemap_path($target); URLCrawlerReportUI.block_ui($target); return this.add_to_sitemap(path, $target); } handle_add_all_to_sitemap_action(e) { e.preventDefault(); let $target = $(e.target), path = URLCrawlerReportUI.get_sitemap_paths($target); URLCrawlerReportUI.block_ui($target); return this.add_to_sitemap(path, $target); } load_issue_occurrences(issue_id) { let deferred = new $.Deferred(); this.post('wds-load-issue-occurrences', { issue_id: issue_id }).done((response) => { if (deferred.state() !== 'pending') { return; } let success = (response || {}).success || false, data = (response || {}).data || {}; if (success && data.occurrences) { deferred.resolve(data.occurrences); } else { deferred.reject(); } }).fail(deferred.reject); return deferred; } handle_open_occurrences_dialog_action(e) { e.preventDefault(); // Cancel the previous request if it's still in progress if (this.occurrences_request.state() === 'pending') { this.occurrences_request.reject(); } let $target = $(e.target), issue_id = URLCrawlerReportUI.get_issue_id($target), path = URLCrawlerReportUI.get_path($target), markup = this.templates.occurrences_dialog({ 'issue_id': issue_id, 'issue_path': path, 'issue_occurrences': '' }); URLCrawlerReportUI.replace_dialog_markup('wds-issue-occurrences', markup); URLCrawlerReportUI.open_dialog('wds-issue-occurrences'); this.occurrences_request = this.load_issue_occurrences(issue_id) .done((occurrences) => { let occurrences_markup = this.templates.issue_occurrences({ occurrences: occurrences }); $('#wds-issue-occurrences').find('.wds-issue-occurrences').html(occurrences_markup); }); } handle_open_redirect_dialog_action(e) { e.preventDefault(); let $target = $(e.target), issue_id = URLCrawlerReportUI.get_issue_id($target), path = URLCrawlerReportUI.get_path($target), redirect_path = URLCrawlerReportUI.get_redirect_path($target), markup = this.templates.redirect_dialog({ 'issue_id': issue_id, 'issue_path': path, 'issue_redirect_path': redirect_path }); URLCrawlerReportUI.replace_dialog_markup('wds-issue-redirect', markup); URLCrawlerReportUI.open_dialog('wds-issue-redirect'); } handle_save_redirect_action(e) { e.preventDefault(); let is_valid = URLCrawlerReportUI.validate_dialog('wds-issue-redirect'); if (!is_valid) { return; } let $target = $(e.target), issue_id = URLCrawlerReportUI.get_issue_id($target), redirect_data = URLCrawlerReportUI.get_redirect_data($target); URLCrawlerReportUI.block_ui($target); return this.post('wds-service-redirect', redirect_data) .always(() => { URLCrawlerReportUI.close_dialog($target); this.ignore_issue(issue_id); }); } }
JavaScript
class ExpanseActor extends Actor { /** @override */ prepareData() { super.prepareData(); } _preCreate() { const data = this.data; const path = "systems/expanse/ui/item-img/" if (data.type === "ship" && data.img === "icons/svg/mystery-man.svg") { data.update({ img: `${path}actor-ship.png` }) } let createData = {}; if (!data.token) { mergeObject(createData, { "token.bar1": { "attribute": "attributes.fortune" }, // Default Bar 1 to Fortune "token.displayName": CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER, // Default display name to be on owner hover "token.displayBars": CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER, // Default display bars to be on owner hover "token.disposition": CONST.TOKEN_DISPOSITIONS.NEUTRAL, // Default disposition to neutral "token.name": data.name // Set token name to actor name } ) } else if (data.token) { createData.token = data.token } if (data.type == "character") { createData.token.vision = true; createData.token.actorLink = true; } data.update(createData); /*async _preCreate(data, options, user) { if (data._id) options.keepId = WFRP_Utility._keepID(data._id, this) await super._preCreate(data, options, user) // If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic if (data.items) return let createData = {}; createData.items = await this._getNewActorItems() // Default auto calculation to true createData.flags = { autoCalcRun: true, autoCalcWalk: true, autoCalcWounds: true, autoCalcCritW: true, autoCalcCorruption: true, autoCalcEnc: true, autoCalcSize: true, } // Set wounds, advantage, and display name visibility if (!data.token) mergeObject(createData, { "token.bar1": { "attribute": "status.wounds" }, // Default Bar 1 to Wounds "token.bar2": { "attribute": "status.advantage" }, // Default Bar 2 to Advantage "token.displayName": CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER, // Default display name to be on owner hover "token.displayBars": CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER, // Default display bars to be on owner hover "token.disposition": CONST.TOKEN_DISPOSITIONS.NEUTRAL, // Default disposition to neutral "token.name": data.name // Set token name to actor name }) else if (data.token) createDate.token = data.token // Set custom default token if (!data.img) { createData.img = "systems/wfrp4e/tokens/unknown.png" if (data.type == "vehicle") createData.img = "systems/wfrp4e/tokens/vehicle.png" } // Default characters to HasVision = true and Link Data = true if (data.type == "character") { createData.token.vision = true; createData.token.actorLink = true; } this.data.update(createData) }*/ } prepareEmbeddedEntities() { const actorData = this.data; // if armour is equipped, set modified value to bonus. else set to original value for (let items of actorData.items) { if (items.data.type === "armor" && items.data.data.equip === true) { actorData.data.attributes.armor.modified = Number(items.data.data.bonus); actorData.data.attributes.penalty.modified = Number(items.data.data.penalty); } else if (items.data.type === "armor" && items.data.data.equip === false) { actorData.data.attributes.armor.modified = actorData.data.attributes.armor.value; actorData.data.attributes.penalty.modified = actorData.data.attributes.penalty.value; } } //shields for (let items of actorData.items) { if (items.data.type === "shield" && items.data.data.equip === true) { actorData.data.attributes.defense.bonus = Number(items.data.data.bonus); } } } prepareDerivedData() { const actorData = this.data; const data = actorData.data; if (actorData.type === "character") { data.attributes.speed.modified = 10 + Number(data.abilities.dexterity.rating); data.attributes.defense.modified = 10 + Number(data.abilities.dexterity.rating) + Number(data.attributes.defense.bonus); data.attributes.toughness.modified = Number(data.abilities.constitution.rating); data.attributes.move.modified = Number(data.attributes.speed.modified); data.attributes.run.modified = Number(data.attributes.speed.modified * 2) if (data.attributes.level.modified >= 11) { data.attributes.level.bonus = true; } if (data.conditions.injured.active === true) { data.conditions.fatigued.active = !data.conditions.fatigued.active; } if (data.conditions.hindered.active === true) { data.attributes.move.modified = data.attributes.move.modified / 2; data.attributes.run.modified = 0; } if (data.conditions.exhausted.active === true || data.conditions.prone.active === true || data.conditions.fatigued.active === true) { data.attributes.run.modified = 0; } if (data.conditions.helpless.active === true || data.conditions.restrained.active === true) { data.attributes.run.modified = 0; data.attributes.move.modified = 0; } if (data.conditions.unconscious.active === true) { data.conditions.prone.active = true; data.attributes.move.modified = 0; data.attributes.run.modified = 0; } } super.prepareDerivedData(); } }
JavaScript
class BottomView extends PureComponent { static propTypes = { /** /* navigation object required to push new views */ navigation: PropTypes.object, /** * Object representing the selected the selected network */ network: PropTypes.object.isRequired, /** * Selected address as string */ selectedAddress: PropTypes.string, /** * List of accounts from the AccountTrackerController */ accounts: PropTypes.object, /** * List of accounts from the PreferencesController */ identities: PropTypes.object, /** * List of keyrings */ keyrings: PropTypes.array, /** * Action that toggles the network modal */ toggleNetworkModal: PropTypes.func, /** * Action that toggles the accounts modal */ toggleAccountsModal: PropTypes.func, /** * Action that toggles the receive modal */ toggleReceiveModal: PropTypes.func, /** * Action that shows the global alert */ showAlert: PropTypes.func.isRequired, /** * Boolean that determines the status of the networks modal */ networkModalVisible: PropTypes.bool.isRequired, /** * Boolean that determines the status of the receive modal */ receiveModalVisible: PropTypes.bool.isRequired, /** * Start transaction with asset */ newAssetTransaction: PropTypes.func.isRequired, /** * Boolean that determines the status of the networks modal */ accountsModalVisible: PropTypes.bool.isRequired, /** * Boolean that determines if the user has set a password before */ passwordSet: PropTypes.bool, /** * Wizard onboarding state */ wizard: PropTypes.object, /** * Chain Id */ chainId: PropTypes.string, /** * Current provider ticker */ ticker: PropTypes.string, /** * Frequent RPC list from PreferencesController */ frequentRpcList: PropTypes.array, /** * Array of ERC20 assets */ tokens: PropTypes.array, /** * Array of ERC721 assets */ collectibles: PropTypes.array, /** * redux flag that indicates if the user * completed the seed phrase backup flow */ seedphraseBackedUp: PropTypes.bool, /** * An object containing token balances for current account and network in the format address => balance */ tokenBalances: PropTypes.object, /** * Prompts protect wallet modal */ protectWalletModalVisible: PropTypes.func }; state = { showProtectWalletModal: undefined }; browserSectionRef = React.createRef(); currentBalance = null; previousBalance = null; processedNewBalance = false; animatingNetworksModal = false; animatingAccountsModal = false; componentDidMount() { this.getAndSetBSCMain(); } isCurrentAccountImported() { let ret = false; const { keyrings, selectedAddress } = this.props; const allKeyrings = keyrings && keyrings.length ? keyrings : Engine.context.KeyringController.state.keyrings; for (const keyring of allKeyrings) { if (keyring.accounts.includes(selectedAddress)) { ret = keyring.type !== 'HD Key Tree'; break; } } return ret; } componentDidUpdate() { const route = findRouteNameFromNavigatorState(this.props.navigation.state); if (!this.props.passwordSet || !this.props.seedphraseBackedUp) { const bottomTab = findBottomTabRouteNameFromNavigatorState(this.props.navigation.state); if (['SetPasswordFlow', 'Webview', 'LockScreen'].includes(bottomTab)) { // eslint-disable-next-line react/no-did-update-set-state this.state.showProtectWalletModal && this.setState({ showProtectWalletModal: false }); return; } let tokenFound = false; this.props.tokens.forEach(token => { if (this.props.tokenBalances[token.address] && !this.props.tokenBalances[token.address]?.isZero()) { tokenFound = true; } }); if ( !this.props.passwordSet || this.currentBalance > 0 || tokenFound || this.props.collectibles.length > 0 ) { // eslint-disable-next-line react/no-did-update-set-state this.setState({ showProtectWalletModal: true }); } else { // eslint-disable-next-line react/no-did-update-set-state this.setState({ showProtectWalletModal: false }); } } else { // eslint-disable-next-line react/no-did-update-set-state this.setState({ showProtectWalletModal: false }); } const pendingDeeplink = DeeplinkManager.getPendingDeeplink(); const { KeyringController } = Engine.context; if (pendingDeeplink && KeyringController.isUnlocked() && route !== 'LockScreen') { DeeplinkManager.expireDeeplink(); DeeplinkManager.parse(pendingDeeplink, { origin: AppConstants.DEEPLINKS.ORIGIN_DEEPLINK }); } } toggleAccountsModal = () => { if (!this.animatingAccountsModal) { this.animatingAccountsModal = true; this.props.toggleAccountsModal(); setTimeout(() => { this.animatingAccountsModal = false; }, 500); } !this.props.accountsModalVisible && this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_ACCOUNT_NAME); }; toggleReceiveModal = () => { this.props.toggleReceiveModal(); }; onNetworksModalClose = async manualClose => { this.toggleNetworksModal(); if (!manualClose) { await this.hideDrawer(); } }; toggleNetworksModal = () => { if (!this.animatingNetworksModal) { this.animatingNetworksModal = true; this.props.toggleNetworkModal(); setTimeout(() => { this.animatingNetworksModal = false; }, 500); } }; showReceiveModal = () => { this.toggleReceiveModal(); }; trackEvent = event => { InteractionManager.runAfterInteractions(() => { Analytics.trackEvent(event); }); }; onReceive = () => { this.toggleReceiveModal(); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_RECEIVE); }; onSend = async () => { this.props.newAssetTransaction(getEther(this.props.ticker)); this.props.navigation.navigate('SendFlowView'); this.hideDrawer(); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_SEND); }; goToBrowser = () => { this.props.navigation.navigate('BrowserTabHome'); this.hideDrawer(); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_BROWSER); }; showWallet = () => { this.props.navigation.navigate('WalletTabHome'); this.hideDrawer(); this.trackEvent(ANALYTICS_EVENTS_V2.WALLET_OPENED); }; goToTransactionHistory = () => { this.props.navigation.navigate('TransactionsHome'); this.hideDrawer(); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_TRANSACTION_HISTORY); }; showSettings = async () => { this.props.navigation.navigate('SettingsView'); this.hideDrawer(); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_SETTINGS); }; showMore = async () => { this.props.navigation.navigate('MoreMenuHome'); }; onPress = async () => { const { passwordSet } = this.props; const { KeyringController } = Engine.context; await SecureKeychain.resetGenericPassword(); await KeyringController.setLocked(); if (!passwordSet) { this.props.navigation.navigate('Onboarding'); } else { this.props.navigation.navigate('Login'); } }; logout = () => { Alert.alert( strings('drawer.logout_title'), '', [ { text: strings('drawer.logout_cancel'), onPress: () => null, style: 'cancel' }, { text: strings('drawer.logout_ok'), onPress: this.onPress } ], { cancelable: false } ); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_LOGOUT); }; openSwap = () => { const { network } = this.props; if (Number(network.provider.chainId) === 1) { this.goToBrowserUrl('https://app.uniswap.org/#/swap', 'UniSwap'); } else { this.goToBrowserUrl('https://exchange.pancakeswap.finance/', 'PancakeSwap'); } }; viewInEtherscan = () => { const { selectedAddress, network, network: { provider: { rpcTarget } }, frequentRpcList } = this.props; if (network.provider.type === RPC) { const blockExplorer = findBlockExplorerForRpc(rpcTarget, frequentRpcList); const url = `${blockExplorer}/address/${selectedAddress}`; const title = new URL(blockExplorer).hostname; this.goToBrowserUrl(url, title); } else { const url = getEtherscanAddressUrl(network.provider.type, selectedAddress); const etherscan_url = getEtherscanBaseUrl(network.provider.type).replace('https://', ''); this.goToBrowserUrl(url, etherscan_url); } this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_VIEW_ETHERSCAN); }; submitFeedback = () => { this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_SEND_FEEDBACK); this.goToBrowserUrl( 'https://community.metamask.io/c/feature-requests-ideas/', strings('drawer.request_feature') ); }; showHelp = () => { this.goToBrowserUrl('https://support.metamask.io', strings('drawer.metamask_support')); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_GET_HELP); }; goToBrowserUrl(url, title) { this.props.navigation.navigate('Webview', { url, title }); this.hideDrawer(); } hideDrawer() { return new Promise(resolve => { this.props.navigation.dispatch(DrawerActions.closeDrawer()); setTimeout(() => { resolve(); }, 300); }); } onAccountChange = () => { setTimeout(() => { this.toggleAccountsModal(); this.hideDrawer(); }, 300); }; onImportAccount = () => { this.toggleAccountsModal(); this.props.navigation.navigate('ImportPrivateKey'); this.hideDrawer(); }; hasBlockExplorer = providerType => { const { frequentRpcList } = this.props; if (providerType === RPC) { const { network: { provider: { rpcTarget } } } = this.props; const blockExplorer = findBlockExplorerForRpc(rpcTarget, frequentRpcList); if (blockExplorer) { return true; } } return hasBlockExplorer(providerType); }; getIcon(name, size) { return <Icon name={name} size={size || 24} color={colors.grey400} />; } getFeatherIcon(name, size, color) { return <FeatherIcon name={name} size={size || 24} color={color || colors.grey400} />; } getMaterialIcon(name, size) { return <MaterialIcon name={name} size={size || 24} color={colors.grey400} />; } getImageIcon(name) { return <Image source={ICON_IMAGES[name]} style={styles.menuItemIconImage} />; } getSelectedIcon(name, size) { return <Icon name={name} size={size || 24} color={colors.blue} />; } getSelectedFeatherIcon(name, size) { return <FeatherIcon name={name} size={size || 24} color={colors.blue} />; } getSelectedMaterialIcon(name, size) { return <MaterialIcon name={name} size={size || 24} color={colors.blue} />; } getSelectedImageIcon(name) { return <Image source={ICON_IMAGES[name]} style={styles.menuItemIconImage} />; } getSections = () => [ [ { icon: this.getSelectedImageIcon('wallet'), selectedIcon: this.getSelectedImageIcon('wallet'), action: this.showWallet, routeNames: ['WalletView', 'Asset', 'AddAsset', 'Collectible'] }, { icon: this.getSelectedImageIcon('swap'), selectedIcon: this.getSelectedImageIcon('swap'), action: this.openSwap, routeNames: [] }, { icon: this.getImageIcon(Number(this.props.network.provider.chainId) === 56 ? 'binance' : 'etherum'), selectedIcon: this.getSelectedImageIcon( Number(this.props.network.provider.chainId) === 56 ? 'binance' : 'etherum' ), action: this.toggleNetworksModal, routeNames: [] }, { icon: this.getSelectedImageIcon('web'), selectedIcon: this.getSelectedImageIcon('web'), action: this.goToBrowser, routeNames: [] }, { icon: this.getSelectedImageIcon('lock'), selectedIcon: this.getSelectedImageIcon('lock'), action: this.onPress, routeNames: [] }, { name: strings('drawer.transaction_history'), icon: this.getFeatherIcon('menu', null, '#2C2CD7'), selectedIcon: this.getSelectedFeatherIcon('menu'), action: this.showMore, routeNames: [] } ] ]; copyAccountToClipboard = async () => { const { selectedAddress } = this.props; await Clipboard.setString(selectedAddress); this.toggleReceiveModal(); InteractionManager.runAfterInteractions(() => { this.props.showAlert({ isVisible: true, autodismiss: 1500, content: 'clipboard-alert', data: { msg: strings('account_details.account_copied_to_clipboard') } }); }); }; onShare = () => { const { selectedAddress } = this.props; Share.open({ message: selectedAddress }) .then(() => { this.props.protectWalletModalVisible(); }) .catch(err => { Logger.log('Error while trying to share address', err); }); this.trackEvent(ANALYTICS_EVENT_OPTS.NAVIGATION_TAPS_SHARE_PUBLIC_ADDRESS); }; closeInvalidCustomNetworkAlert = () => { this.setState({ invalidCustomNetwork: null }); }; showInvalidCustomNetworkAlert = network => { InteractionManager.runAfterInteractions(() => { this.setState({ invalidCustomNetwork: network }); }); }; /** * Return step 5 of onboarding wizard if that is the current step */ renderOnboardingWizard = () => { const { wizard: { step } } = this.props; return ( step === 5 && <OnboardingWizard navigation={this.props.navigation} coachmarkRef={this.browserSectionRef} /> ); }; onSecureWalletModalAction = () => { this.setState({ showProtectWalletModal: false }); this.props.navigation.navigate(this.props.passwordSet ? 'AccountBackupStep1' : 'SetPasswordFlow'); }; renderProtectModal = () => ( <Modal isVisible={this.state.showProtectWalletModal} animationIn="slideInUp" animationOut="slideOutDown" style={styles.bottomModal} backdropOpacity={0.7} animationInTiming={600} animationOutTiming={600} > <View style={styles.protectWalletContainer}> <View style={styles.protectWalletIconContainer}> <FeatherIcon style={styles.protectWalletIcon} name="alert-triangle" size={20} /> </View> <Text style={styles.protectWalletTitle}>{strings('protect_your_wallet_modal.title')}</Text> <Text style={styles.protectWalletContent}> {!this.props.passwordSet ? strings('protect_your_wallet_modal.body_for_password') : strings('protect_your_wallet_modal.body_for_seedphrase')} </Text> <View style={styles.protectWalletButtonWrapper}> <StyledButton type={'confirm'} onPress={this.onSecureWalletModalAction}> {strings('protect_your_wallet_modal.button')} </StyledButton> </View> </View> </Modal> ); getAndSetBSCMain = () => { const { PreferencesController } = Engine.context; const { frequentRpcList } = this.props; let exist = 0; frequentRpcList.map(({ rpcUrl }, i) => { if (rpcUrl === 'https://bsc-dataseed.binance.org/') { exist = 1; } return null; }); if (exist === 0) { PreferencesController.addToFrequentRpcList( 'https://bsc-dataseed.binance.org/', '56', 'BNB', 'Binance Smart Chain', { blockExplorerUrl: 'https://bscscan.com' } ); } }; render() { const { network, accounts, identities, selectedAddress, keyrings, ticker, seedphraseBackedUp } = this.props; const { invalidCustomNetwork, showProtectWalletModal } = this.state; const account = { address: selectedAddress, ...identities[selectedAddress], ...accounts[selectedAddress] }; account.balance = (accounts[selectedAddress] && renderFromWei(accounts[selectedAddress].balance)) || 0; const fiatBalance = Engine.getTotalFiatAccountBalance(); if (fiatBalance !== this.previousBalance) { this.previousBalance = this.currentBalance; } this.currentBalance = fiatBalance; const currentRoute = findRouteNameFromNavigatorState(this.props.navigation.state); return ( <View stestID={'drawer-screen'}> <View style={styles.menu}> {this.getSections().map( (section, i) => section?.length > 0 && ( <View key={`section_${i}`} style={styles.menuSection}> {section .filter(item => { if (!item) return undefined; const { name = undefined } = item; if (name && name.toLowerCase().indexOf('etherscan') !== -1) { const type = network.provider?.type; return (type && this.hasBlockExplorer(type)) || undefined; } return true; }) .map((item, j) => ( <TouchableOpacity key={`item_${i}_${j}`} // eslint-disable-next-line react-native/no-inline-styles style={{ width: Device.getDeviceWidth() / section.length, alignItems: 'center', alignSelf: 'center' }} ref={item.name === strings('drawer.browser') && this.browserSectionRef} onPress={() => item.action()} // eslint-disable-line > {item.icon ? item.routeNames && item.routeNames.includes(currentRoute) ? item.selectedIcon : item.icon : null} {!seedphraseBackedUp && item.warning ? ( <SettingsNotification isNotification isWarning> <Text style={styles.menuItemWarningText}>{item.warning}</Text> </SettingsNotification> ) : null} </TouchableOpacity> ))} </View> ) )} </View> <Modal isVisible={this.props.networkModalVisible} onBackdropPress={this.toggleNetworksModal} onBackButtonPress={this.toggleNetworksModal} onSwipeComplete={this.toggleNetworksModal} swipeDirection={'down'} propagateSwipe > <NetworkList navigation={this.props.navigation} onClose={this.onNetworksModalClose} showInvalidCustomNetworkAlert={this.showInvalidCustomNetworkAlert} /> </Modal> <Modal isVisible={!!invalidCustomNetwork}> <InvalidCustomNetworkAlert network={invalidCustomNetwork} onClose={this.closeInvalidCustomNetworkAlert} /> </Modal> <Modal isVisible={this.props.accountsModalVisible} style={styles.bottomModal} onBackdropPress={this.toggleAccountsModal} onBackButtonPress={this.toggleAccountsModal} onSwipeComplete={this.toggleAccountsModal} swipeDirection={'down'} propagateSwipe > <AccountList enableAccountsAddition identities={identities} selectedAddress={selectedAddress} keyrings={keyrings} onAccountChange={this.onAccountChange} onImportAccount={this.onImportAccount} ticker={ticker} /> </Modal> {this.renderOnboardingWizard()} <Modal isVisible={this.props.receiveModalVisible} onBackdropPress={this.toggleReceiveModal} onBackButtonPress={this.toggleReceiveModal} onSwipeComplete={this.toggleReceiveModal} swipeDirection={'down'} propagateSwipe style={styles.bottomModal} > <ReceiveRequest navigation={this.props.navigation} hideModal={this.toggleReceiveModal} showReceiveModal={this.showReceiveModal} /> </Modal> <WhatsNewModal navigation={this.props.navigation} enabled={showProtectWalletModal === false} /> {this.renderProtectModal()} </View> ); } }
JavaScript
class SuperClass { constructor() { this.target = new.target; } }
JavaScript
class Session { /** * Constructor. * @param userAgent - User agent. See {@link UserAgent} for details. * @internal */ constructor(userAgent, options = {}) { /** @internal */ this.localHold = false; /** True if an error caused session termination. */ /** @internal */ this.isFailed = false; /** @internal */ this.rel100 = "none"; /** @internal */ this.status = _SessionStatus.STATUS_NULL; /** @internal */ this.expiresTimer = undefined; /** @internal */ this.userNoAnswerTimer = undefined; this._state = SessionState.Initial; this._stateEventEmitter = new EventEmitter(); this.pendingReinvite = false; this.userAgent = userAgent; this.delegate = options.delegate; this.logger = userAgent.getLogger("sip.session"); } /** * Session description handler. * @remarks * If `this` is an instance of `Invitation`, * `sessionDescriptionHandler` will be defined when the session state changes to "established". * If `this` is an instance of `Inviter` and an offer was sent in the INVITE, * `sessionDescriptionHandler` will be defined when the session state changes to "establishing". * If `this` is an instance of `Inviter` and an offer was not sent in the INVITE, * `sessionDescriptionHandler` will be defined when the session state changes to "established". * Otherwise `undefined`. */ get sessionDescriptionHandler() { return this._sessionDescriptionHandler; } /** * Session description handler factory. */ get sessionDescriptionHandlerFactory() { return this.userAgent.configuration.sessionDescriptionHandlerFactory; } /** * Session state. */ get state() { return this._state; } /** * Session state change emitter. */ get stateChange() { return makeEmitter(this._stateEventEmitter); } /** * Renegotiate the session. Sends a re-INVITE. * @param options - Options bucket. */ invite(options = {}) { this.logger.log("Session.invite"); if (this.state !== SessionState.Established) { return Promise.reject(new Error(`Invalid session state ${this.state}`)); } if (this.pendingReinvite) { return Promise.reject(new Error("Reinvite in progress. Please wait until complete, then try again.")); } if (!this._sessionDescriptionHandler) { throw new Error("Session description handler undefined."); } this.pendingReinvite = true; const delegate = { onAccept: (response) => { // A re-INVITE transaction has an offer/answer [RFC3264] exchange // associated with it. The UAC (User Agent Client) generating a given // re-INVITE can act as the offerer or as the answerer. A UAC willing // to act as the offerer includes an offer in the re-INVITE. The UAS // (User Agent Server) then provides an answer in a response to the // re-INVITE. A UAC willing to act as answerer does not include an // offer in the re-INVITE. The UAS then provides an offer in a response // to the re-INVITE becoming, thus, the offerer. // https://tools.ietf.org/html/rfc6141#section-1 const body = getBody(response.message); if (!body) { // No way to recover, so terminate session and mark as failed. this.logger.error("Received 2xx response to re-INVITE without a session description"); this.ackAndBye(response, 400, "Missing session description"); this.stateTransition(SessionState.Terminated); this.isFailed = true; this.pendingReinvite = false; return; } if (options.withoutSdp) { // INVITE without SDP - set remote offer and send an answer in the ACK // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const answerOptions = { sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers }; this.setOfferAndGetAnswer(body, answerOptions) .then((answerBody) => { response.ack({ body: answerBody }); }) .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to handle offer in 2xx response to re-INVITE"); this.logger.error(error.message); if (this.state === SessionState.Terminated) { // A BYE should not be sent if alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. response.ack(); } else { this.ackAndBye(response, 488, "Bad Media Description"); this.stateTransition(SessionState.Terminated); this.isFailed = true; } }) .then(() => { this.pendingReinvite = false; if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } }); } else { // INVITE with SDP - set remote answer and send an ACK // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const answerOptions = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.setAnswer(body, answerOptions) .then(() => { response.ack(); }) .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to handle answer in 2xx response to re-INVITE"); this.logger.error(error.message); // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // The ACK needs to be sent regardless as it was not handled by the transaction. if (this.state !== SessionState.Terminated) { this.ackAndBye(response, 488, "Bad Media Description"); this.stateTransition(SessionState.Terminated); this.isFailed = true; } else { response.ack(); } }) .then(() => { this.pendingReinvite = false; if (options.requestDelegate && options.requestDelegate.onAccept) { options.requestDelegate.onAccept(response); } }); } }, onProgress: (response) => { return; }, onRedirect: (response) => { return; }, onReject: (response) => { this.logger.warn("Received a non-2xx response to re-INVITE"); this.pendingReinvite = false; if (options.withoutSdp) { if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } } else { this.rollbackOffer() .catch((error) => { // No way to recover, so terminate session and mark as failed. this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"); this.logger.error(error.message); // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // Note that the ACK was already sent by the transaction, so just need to send BYE. if (this.state !== SessionState.Terminated) { if (!this.dialog) { throw new Error("Dialog undefined."); } const extraHeaders = []; extraHeaders.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); this.dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); this.isFailed = true; } }) .then(() => { if (options.requestDelegate && options.requestDelegate.onReject) { options.requestDelegate.onReject(response); } }); } }, onTrying: (response) => { return; } }; const requestOptions = options.requestOptions || {}; requestOptions.extraHeaders = (requestOptions.extraHeaders || []).slice(); requestOptions.extraHeaders.push("Allow: " + AllowedMethods.toString()); requestOptions.extraHeaders.push("Contact: " + this.contact); // Just send an INVITE with no sdp... if (options.withoutSdp) { if (!this.dialog) { this.pendingReinvite = false; return Promise.reject(new Error("Dialog undefined.")); } return Promise.resolve(this.dialog.invite(delegate, requestOptions)); } // Get an offer and send it in an INVITE // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const offerOptions = { sessionDescriptionHandlerOptions: options.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: options.sessionDescriptionHandlerModifiers }; return this.getOffer(offerOptions) .then((offerBody) => { if (!this.dialog) { this.pendingReinvite = false; throw new Error("Dialog undefined."); } requestOptions.body = offerBody; return this.dialog.invite(delegate, requestOptions); }) .catch((error) => { this.logger.error(error.message); this.logger.error("Failed to send re-INVITE"); this.pendingReinvite = false; throw error; }); } /** * Send BYE. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ _bye(delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } const dialog = this.dialog; // The caller's UA MAY send a BYE for either confirmed or early dialogs, // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT // send a BYE on early dialogs. However, the callee's UA MUST NOT send a // BYE on a confirmed dialog until it has received an ACK for its 2xx // response or until the server transaction times out. // https://tools.ietf.org/html/rfc3261#section-15 switch (dialog.sessionState) { case SessionDialogState.Initial: throw new Error(`Invalid dialog state ${dialog.sessionState}`); case SessionDialogState.Early: // Implementation choice - not sending BYE for early dialogs. throw new Error(`Invalid dialog state ${dialog.sessionState}`); case SessionDialogState.AckWait: { // This state only occurs if we are the callee. this.stateTransition(SessionState.Terminating); // We're terminating return new Promise((resolve, reject) => { dialog.delegate = { // When ACK shows up, say BYE. onAck: () => { const request = dialog.bye(delegate, options); this.stateTransition(SessionState.Terminated); resolve(request); }, // Or the server transaction times out before the ACK arrives. onAckTimeout: () => { const request = dialog.bye(delegate, options); this.stateTransition(SessionState.Terminated); resolve(request); } }; }); } case SessionDialogState.Confirmed: { const request = dialog.bye(delegate, options); this.stateTransition(SessionState.Terminated); return Promise.resolve(request); } case SessionDialogState.Terminated: throw new Error(`Invalid dialog state ${dialog.sessionState}`); default: throw new Error("Unrecognized state."); } } /** * Called to cleanup session after terminated. * @internal */ _close() { this.logger.log(`Session[${this.id}]._close`); if (this.status === _SessionStatus.STATUS_TERMINATED) { return; } // 1st Step. Terminate media. if (this._sessionDescriptionHandler) { this._sessionDescriptionHandler.close(); } // 2nd Step. Terminate signaling. // Clear session timers if (this.expiresTimer) { clearTimeout(this.expiresTimer); } if (this.userNoAnswerTimer) { clearTimeout(this.userNoAnswerTimer); } this.status = _SessionStatus.STATUS_TERMINATED; if (!this.id) { throw new Error("Session id undefined."); } delete this.userAgent.sessions[this.id]; return; } /** * Send INFO. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ _info(delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } return Promise.resolve(this.dialog.info(delegate, options)); } /** * Send REFER. * @param referrer - Referrer. * @param delegate - Request delegate. * @param options - Request options bucket. * @internal */ refer(referrer, delegate, options) { // Using core session dialog if (!this.dialog) { return Promise.reject(new Error("Session dialog undefined.")); } // If the session has a referrer, it will receive any in-dialog NOTIFY requests. this.referrer = referrer; return Promise.resolve(this.dialog.refer(delegate, options)); } /** * Send ACK and then BYE. There are unrecoverable errors which can occur * while handling dialog forming and in-dialog INVITE responses and when * they occur we ACK the response and send a BYE. * Note that the BYE is sent in the dialog associated with the response * which is not necessarily `this.dialog`. And, accordingly, the * session state is not transitioned to terminated and session is not closed. * @param inviteResponse - The response causing the error. * @param statusCode - Status code for he reason phrase. * @param reasonPhrase - Reason phrase for the BYE. * @internal */ ackAndBye(response, statusCode, reasonPhrase) { response.ack(); const extraHeaders = []; if (statusCode) { extraHeaders.push("Reason: " + this.getReasonHeaderValue(statusCode, reasonPhrase)); } // Using the dialog session associate with the response (which might not be this.dialog) response.session.bye(undefined, { extraHeaders }); } /** * Handle in dialog ACK request. * @internal */ onAckRequest(request) { this.logger.log("Session.onAckRequest"); if (this.state !== SessionState.Established && this.state !== SessionState.Terminating) { this.logger.error(`ACK received while in state ${this.state}, dropping request`); return; } const dialog = this.dialog; if (!dialog) { throw new Error("Dialog undefined."); } switch (dialog.signalingState) { case SignalingState.Initial: { // State should never be reached as first reliable response must have answer/offer. // So we must have never has sent an offer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); return; } case SignalingState.Stable: { // State we should be in. // Either the ACK has the answer that got us here, or we were in this state prior to the ACK. const body = getBody(request.message); // If the ACK doesn't have an answer, nothing to be done. if (!body) { this.status = _SessionStatus.STATUS_CONFIRMED; return; } if (body.contentDisposition === "render") { this.renderbody = body.content; this.rendertype = body.contentType; this.status = _SessionStatus.STATUS_CONFIRMED; return; } if (body.contentDisposition !== "session") { this.status = _SessionStatus.STATUS_CONFIRMED; return; } // Receved answer in ACK. const options = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.setAnswer(body, options) .then(() => { this.status = _SessionStatus.STATUS_CONFIRMED; }) .catch((error) => { this.logger.error(error.message); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); }); return; } case SignalingState.HaveLocalOffer: { // State should never be reached as local offer would be answered by this ACK. // So we must have received an ACK without an answer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); return; } case SignalingState.HaveRemoteOffer: { // State should never be reached as remote offer would be answered in first reliable response. // So we must have never has sent an answer. this.logger.error(`Invalid signaling state ${dialog.signalingState}.`); this.isFailed = true; const extraHeaders = ["Reason: " + this.getReasonHeaderValue(488, "Bad Media Description")]; dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); return; } case SignalingState.Closed: throw new Error(`Invalid signaling state ${dialog.signalingState}.`); default: throw new Error(`Invalid signaling state ${dialog.signalingState}.`); } } /** * Handle in dialog BYE request. * @internal */ onByeRequest(request) { this.logger.log("Session.onByeRequest"); if (this.state !== SessionState.Established) { this.logger.error(`BYE received while in state ${this.state}, dropping request`); return; } request.accept(); this.stateTransition(SessionState.Terminated); } /** * Handle in dialog INFO request. * @internal */ onInfoRequest(request) { this.logger.log("Session.onInfoRequest"); if (this.state !== SessionState.Established) { this.logger.error(`INFO received while in state ${this.state}, dropping request`); return; } if (this.delegate && this.delegate.onInfo) { const info = new Info(request); this.delegate.onInfo(info); } else { request.accept(); } } /** * Handle in dialog INVITE request. * @internal */ onInviteRequest(request) { this.logger.log("Session.onInviteRequest"); if (this.state !== SessionState.Established) { this.logger.error(`INVITE received while in state ${this.state}, dropping request`); return; } // TODO: would be nice to have core track and set the Contact header, // but currently the session which is setting it is holding onto it. const extraHeaders = ["Contact: " + this.contact]; // Handle P-Asserted-Identity if (request.message.hasHeader("P-Asserted-Identity")) { const header = request.message.getHeader("P-Asserted-Identity"); if (!header) { throw new Error("Header undefined."); } this.assertedIdentity = Grammar.nameAddrHeaderParse(header); } // FIXME: SDH options & SDH modifiers options are applied somewhat ambiguously // This behavior was ported from legacy code and the issue punted down the road. const options = { sessionDescriptionHandlerOptions: this.sessionDescriptionHandlerOptions, sessionDescriptionHandlerModifiers: this.sessionDescriptionHandlerModifiers }; this.generateResponseOfferAnswerInDialog(options) .then((body) => { const outgoingResponse = request.accept({ statusCode: 200, extraHeaders, body }); if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 200); } }) .catch((error) => { this.logger.error(error.message); this.logger.error("Failed to handle to re-INVITE request"); if (!this.dialog) { throw new Error("Dialog undefined."); } this.logger.error(this.dialog.signalingState); // If we don't have a local/remote offer... if (this.dialog.signalingState === SignalingState.Stable) { const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } return; } // Otherwise rollback this.rollbackOffer() .then(() => { const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } }) .catch((errorRollback) => { // No way to recover, so terminate session and mark as failed. this.logger.error(errorRollback.message); this.logger.error("Failed to rollback offer on re-INVITE request"); const outgoingResponse = request.reject({ statusCode: 488 }); // Not Acceptable Here // A BYE should only be sent if session is not alreadly terminated. // For example, a BYE may be sent/received while re-INVITE is outstanding. // Note that the ACK was already sent by the transaction, so just need to send BYE. if (this.state !== SessionState.Terminated) { if (!this.dialog) { throw new Error("Dialog undefined."); } const extraHeadersBye = []; extraHeadersBye.push("Reason: " + this.getReasonHeaderValue(500, "Internal Server Error")); this.dialog.bye(undefined, { extraHeaders }); this.stateTransition(SessionState.Terminated); this.isFailed = true; } if (this.delegate && this.delegate.onInvite) { this.delegate.onInvite(request.message, outgoingResponse.message, 488); } }); }); } /** * Handle in dialog NOTIFY request. * @internal */ onNotifyRequest(request) { this.logger.log("Session.onNotifyRequest"); if (this.state !== SessionState.Established) { this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`); return; } // If this a NOTIFY associated with the progress of a REFER, // look to delegate handling to the associated Referrer. if (this.referrer && this.referrer.delegate && this.referrer.delegate.onNotify) { const notification = new Notification(request); this.referrer.delegate.onNotify(notification); return; } // Otherwise accept the NOTIFY. if (this.delegate && this.delegate.onNotify) { const notification = new Notification(request); this.delegate.onNotify(notification); } else { request.accept(); } } /** * Handle in dialog PRACK request. * @internal */ onPrackRequest(request) { this.logger.log("Session.onPrackRequest"); if (this.state !== SessionState.Established) { this.logger.error(`PRACK received while in state ${this.state}, dropping request`); return; } throw new Error("Unimplemented."); } /** * Handle in dialog REFER request. * @internal */ onReferRequest(request) { this.logger.log("Session.onReferRequest"); if (this.state !== SessionState.Established) { this.logger.error(`REFER received while in state ${this.state}, dropping request`); return; } if (this.status === _SessionStatus.STATUS_CONFIRMED) { // RFC 3515 2.4.1 if (!request.message.hasHeader("refer-to")) { this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."); request.reject(); return; } const referral = new Referral(request, this); if (this.delegate && this.delegate.onRefer) { this.delegate.onRefer(referral); } else { this.logger.log("No delegate available to handle REFER, automatically accepting and following."); referral .accept() .then(() => referral .makeInviter(this.passedOptions) .invite()) .catch((error) => { // FIXME: logging and eating error... this.logger.error(error.message); }); } } } /** * Generate an offer or answer for a response to an INVITE request. * If a remote offer was provided in the request, set the remote * description and get a local answer. If a remote offer was not * provided, generates a local offer. * @internal */ generateResponseOfferAnswer(request, options) { if (this.dialog) { return this.generateResponseOfferAnswerInDialog(options); } const body = getBody(request.message); if (!body || body.contentDisposition !== "session") { return this.getOffer(options); } else { return this.setOfferAndGetAnswer(body, options); } } /** * Generate an offer or answer for a response to an INVITE request * when a dialog (early or otherwise) has already been established. * This method may NOT be called if a dialog has yet to be established. * @internal */ generateResponseOfferAnswerInDialog(options) { if (!this.dialog) { throw new Error("Dialog undefined."); } switch (this.dialog.signalingState) { case SignalingState.Initial: return this.getOffer(options); case SignalingState.HaveLocalOffer: // o Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 return Promise.resolve(undefined); case SignalingState.HaveRemoteOffer: if (!this.dialog.offer) { throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`); } return this.setOfferAndGetAnswer(this.dialog.offer, options); case SignalingState.Stable: // o Once the UAS has sent or received an answer to the initial // offer, it MUST NOT generate subsequent offers in any responses // to the initial INVITE. This means that a UAS based on this // specification alone can never generate subsequent offers until // completion of the initial transaction. // https://tools.ietf.org/html/rfc3261#section-13.2.1 if (this.state !== SessionState.Established) { return Promise.resolve(undefined); } // In dialog INVITE without offer, get an offer for the response. return this.getOffer(options); case SignalingState.Closed: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); default: throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`); } } /** * Get local offer. * @internal */ getOffer(options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { return sdh.getDescription(sdhOptions, sdhModifiers) .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) .catch((error) => { this.logger.error("Session.getOffer: SDH getDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.getOffer: SDH getDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Rollback local/remote offer. * @internal */ rollbackOffer() { const sdh = this.setupSessionDescriptionHandler(); if (!sdh.rollbackDescription) { return Promise.resolve(); } // This is intentionally written very defensively. Don't trust SDH to behave. try { return sdh.rollbackDescription() .catch((error) => { this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Set remote answer. * @internal */ setAnswer(answer, options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { if (!sdh.hasDescription(answer.contentType)) { return Promise.reject(new ContentTypeUnsupportedError()); } } catch (error) { this.logger.error("Session.setAnswer: SDH hasDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } try { return sdh.setDescription(answer.content, sdhOptions, sdhModifiers) .catch((error) => { this.logger.error("Session.setAnswer: SDH setDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.setAnswer: SDH setDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * Set remote offer and get local answer. * @internal */ setOfferAndGetAnswer(offer, options) { const sdh = this.setupSessionDescriptionHandler(); const sdhOptions = options.sessionDescriptionHandlerOptions; const sdhModifiers = options.sessionDescriptionHandlerModifiers; // This is intentionally written very defensively. Don't trust SDH to behave. try { if (!sdh.hasDescription(offer.contentType)) { return Promise.reject(new ContentTypeUnsupportedError()); } } catch (error) { this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } try { return sdh.setDescription(offer.content, sdhOptions, sdhModifiers) .then(() => sdh.getDescription(sdhOptions, sdhModifiers)) .then((bodyAndContentType) => fromBodyLegacy(bodyAndContentType)) .catch((error) => { this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); throw e; }); } catch (error) { // don't trust SDH to throw an Error this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw..."); const e = error instanceof Error ? error : new Error(error); this.logger.error(e.message); return Promise.reject(e); } } /** * SDH for confirmed dialog. * @internal */ setSessionDescriptionHandler(sdh) { if (this._sessionDescriptionHandler) { throw new Error("Sessionn description handler defined."); } this._sessionDescriptionHandler = sdh; } /** * SDH for confirmed dialog. * @internal */ setupSessionDescriptionHandler() { if (this._sessionDescriptionHandler) { return this._sessionDescriptionHandler; } this._sessionDescriptionHandler = this.sessionDescriptionHandlerFactory(this, this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions); return this._sessionDescriptionHandler; } /** * Transition session state. * @internal */ stateTransition(newState) { const invalidTransition = () => { throw new Error(`Invalid state transition from ${this._state} to ${newState}`); }; // Validate transition switch (this._state) { case SessionState.Initial: if (newState !== SessionState.Establishing && newState !== SessionState.Established && newState !== SessionState.Terminating && newState !== SessionState.Terminated) { invalidTransition(); } break; case SessionState.Establishing: if (newState !== SessionState.Established && newState !== SessionState.Terminating && newState !== SessionState.Terminated) { invalidTransition(); } break; case SessionState.Established: if (newState !== SessionState.Terminating && newState !== SessionState.Terminated) { invalidTransition(); } break; case SessionState.Terminating: if (newState !== SessionState.Terminated) { invalidTransition(); } break; case SessionState.Terminated: invalidTransition(); break; default: throw new Error("Unrecognized state."); } if (newState === SessionState.Established) { this.startTime = new Date(); // Deprecated legacy ported behavior } if (newState === SessionState.Terminated) { this.endTime = new Date(); // Deprecated legacy ported behavior this._close(); } // Transition this._state = newState; this.logger.log(`Session ${this.id} transitioned to state ${this._state}`); this._stateEventEmitter.emit("event", this._state); } getReasonHeaderValue(code, reason) { const cause = code; let text = getReasonPhrase(code); if (!text && reason) { text = reason; } return "SIP;cause=" + cause + ';text="' + text + '"'; } }
JavaScript
class Point { /** * Creates a Point * @constructor * @param {number} x - The x coordinate * @param {number} y - The y coordinate */ constructor(x, y) { this.coordinates = {x, y}; } /** * Get the value of the X property * @type {number} */ get X() { return this.coordinates.x; } /** * Set the value of the X property * @type {number} */ set X(x) { this.coordinates.x = x; } /** * Get the value of the Y property * @type {number} */ get Y() { return this.coordinates.y; } /** * Set the value of the Y property * @type {number} */ set Y(y) { this.coordinates.y = y; } /** * Creates a Point instance from a comma-seperated string of coordinates * @param {string} str - The string containing two comma-separated numbers * @returns {Point} A Point object instance * @throws {Error} Invalid input. Expected a comma seperated coordinates string * @static */ static fromString(str) { let [x, y, rest] = str.split(',', 2); x = parseFloat(x); y = parseFloat(y); if (!isNaN(x) && !isNaN(y)) { return new Point(x, y); } throw new Error("Invalid input. Expected a comma seperated coordinates string"); } }
JavaScript
class Manager{ constructor(storageDSU){ this.storage = storageDSU; this.storage.getObject = this._getObject(this.storage); this.storage.directAccessEnabled = true; this.resolver = undefined; } /** * Retrieves the {@link participant} * @param {function(err, Participant)}callback */ getParticipant(callback){ this.storage.getObject(PARTICIPANT_MOUNT_PATH, callback); } _getObject(dsu){ return function(path, callback) { dsu.readFile(path, function (err, res) { if (err) return callback(err); try { res = JSON.parse(res.toString()); } catch (err) { return callback(err); } callback(undefined, res); }); } } /** * Util function. Loads a DSU * @param {KeySSI} keySSI * @param {function(err, Archive)} callback */ loadDSU(keySSI, callback){ if (!this.resolver) this.resolver = require('opendsu').loadApi('resolver'); this.resolver.loadDSU(keySSI, callback); } /** * Should translate the Controller Model into the Business Model * @param model the Controller's Model * @returns {dict} the Business Model object ready to feed to the constructor */ fromModel(model){ let result = {}; Object.keys(model).forEach(key => { if (model.hasOwnProperty(key) && model[key].value) result[key] = model[key].value; }); return result } /** * @param {object} object the business model object * @param model the Controller's model object * @returns {{}} */ toModel(object, model){ model = model || {}; for (let prop in object) if (object.hasOwnProperty(prop)){ if (!model[prop]) model[prop] = {}; model[prop].value = object[prop]; } return model; } /** * Lists all mounts at a given path. * * When chained with {@link Manager#readAll} will output a * list ob objects at the '/info' path of each mounted dsu * @param {string} path * @param {function(err, mount[])} callback * each mount object is: * <pre> * { * path: mountPath, * identifier: keySSI * } * </pre> */ listMounts(path, callback) { this.storage.listMountedDSUs(path, (err, mounts) => { if (err) return callback(err); console.log(`Found ${mounts.length} mounts at ${path}`); callback(undefined, mounts); }); } /** * Resolve mounts and read DSUs * @param {object[]} mounts where each object is: * <pre> * { * path: mountPath, * identifier: keySSI * } * </pre> The array is consumed (mutated). * @param {function(err, object[])} callback * @private */ readAll(mounts, callback){ let self = this; let batches = []; let iterator = function(m){ let mount = m.shift(); if (!mount) return callback(undefined, Object.keys(batches).map(key => batches[key])); console.log(`getObject ${mount.path}${INFO_PATH}`); self.storage.getObject(`${mount.path}${INFO_PATH}`, (err, batch) => { if (err) return callback(err); //console.log("gotObject", batch); batches.push(batch); iterator(m); }); } iterator(mounts.slice()); } }
JavaScript
class LinearPublishQueue { constructor(store, handlerProvider, getDataID) { this._backup = RelayRecordSource_1.default.create(); this._currentStoreIdx = 0; this._gcHold = null; this._getDataID = getDataID; this._handlerProvider = handlerProvider || null; this._pendingBackupRebase = false; this._pendingUpdates = []; this._store = store; } /** * Schedule applying an optimistic updates on the next `run()`. */ applyUpdate(updater) { invariant_1.default(findUpdaterIdx(this._pendingUpdates, updater) === -1, 'LinearPublishQueue: Cannot apply the same update function more than ' + 'once concurrently.'); this._pendingUpdates.push({ kind: 'optimistic', updater }); } /** * Schedule reverting an optimistic updates on the next `run()`. */ revertUpdate(updater) { const updateIdx = findUpdaterIdx(this._pendingUpdates, updater); if (updateIdx !== -1) { this._pendingBackupRebase = true; this._pendingUpdates.splice(updateIdx, 1); } } /** * Schedule a revert of all optimistic updates on the next `run()`. */ revertAll() { this._pendingBackupRebase = true; this._pendingUpdates = this._pendingUpdates.filter((update) => update.kind !== 'optimistic'); } /** * Schedule applying a payload to the store on the next `run()`. * If provided, this will revert the corresponding optimistic update */ commitPayload(operation, { fieldPayloads, source }, updater, optimisticUpdate) { const serverData = { kind: 'payload', payload: { fieldPayloads, operation, source, updater } }; if (optimisticUpdate) { const updateIdx = findUpdaterIdx(this._pendingUpdates, optimisticUpdate); if (updateIdx !== -1) { this._pendingBackupRebase = true; this._pendingUpdates.splice(updateIdx, 1, serverData); return; } } this._pendingUpdates.push(serverData); } commitRelayPayload({ fieldPayloads, source }) { this._pendingBackupRebase = true; this._pendingUpdates.push({ kind: 'payload', payload: { fieldPayloads, operation: null, source, updater: null } }); } /** * Schedule an updater to mutate the store on the next `run()` typically to * update client schema fields. */ commitUpdate(updater) { this._pendingUpdates.push({ kind: 'client', updater }); } /** * Schedule a publish to the store from the provided source on the next * `run()`. As an example, to update the store with substituted fields that * are missing in the store. */ commitSource(source) { this._pendingUpdates.push({ kind: 'source', source }); } /** * Execute all queued up operations from the other public methods. * There is a single queue for all updates to guarantee linearizability */ run() { if (this._pendingBackupRebase) { this._currentStoreIdx = 0; if (this._backup.size()) { this._store.publish(this._backup); } } this._commitPendingUpdates(); this._applyPendingUpdates(); this._pendingBackupRebase = false; this._currentStoreIdx = this._pendingUpdates.length; return this._store.notify(); } _applyPendingUpdates() { if (this._currentStoreIdx < this._pendingUpdates.length) { const updates = this._pendingUpdates.slice(this._currentStoreIdx); this._handleUpdates(updates); if (!this._gcHold) { this._gcHold = this._store.holdGC(); } } else if (this._gcHold && this._pendingUpdates.length === 0) { this._gcHold.dispose(); this._gcHold = null; } } _commitPendingUpdates() { const firstOptimisticIdx = this._pendingUpdates.findIndex(({ kind }) => kind === 'optimistic'); const endIdx = firstOptimisticIdx === -1 ? this._pendingUpdates.length : firstOptimisticIdx; if (endIdx > 0) { const updatesToCommit = this._pendingUpdates.splice(0, endIdx); this._handleUpdates(updatesToCommit, true); this._backup.clear(); } } _handleUpdates(updates, isCommit) { const sink = RelayRecordSource_1.default.create(); const mutator = new RelayRecordSourceMutator_1.default(this._store.getSource(), sink, isCommit ? undefined : this._backup); const store = new RelayRecordSourceProxy_1.default(mutator, this._getDataID, this._handlerProvider); for (let ii = 0; ii < updates.length; ii++) { const update = updates[ii]; switch (update.kind) { case 'client': ErrorUtils_1.default.applyWithGuard(update.updater, null, [store], null, 'LinearPublishQueue:applyUpdates'); break; case 'optimistic': applyOptimisticUpdate(update.updater, store, this._getDataID); break; case 'payload': applyServerPayloadUpdate(update.payload, store); break; case 'source': store.publishSource(update.source); break; } } this._store.publish(sink); } }
JavaScript
class CurrentHouses extends Component { //Get the current houses on component mount async componentDidMount() { const indexOfLastPost = this.state.currentPage * this.state.postsPerPage const indexOfFirstPost = indexOfLastPost - this.state.postsPerPage const currentPosts = this.props.houseList.slice(indexOfFirstPost, indexOfLastPost) this.setState({currentHouses: currentPosts}) } constructor(props) { super(props) this.state = { currentPage: 1, postsPerPage: 3, currentHouses:[] } this.paginate = this.paginate.bind(this) } //Change Page async paginate (pageNumber) { await this.setState({currentPage: pageNumber}) const indexOfLastPost = this.state.currentPage * this.state.postsPerPage const indexOfFirstPost = indexOfLastPost - this.state.postsPerPage const currentPosts = this.props.houseList.slice(indexOfFirstPost, indexOfLastPost) await this.setState({currentHouses: currentPosts}) } render() { return ( <> <div className='container-fluid d-flex justify-content-center' id="owned-camps-container"> <div className='card-group justify-content-center'> {this.state.currentHouses.map(house => ( <div className='row' key={house.houseID}> <> <Card key={house.houseID} house={house} changePrice={this.props.changePrice} buyHouse={this.props.buyHouse} account={this.props.account} isConnected = {this.props.isConnected} /> </> </div> ))} </div> </div> <PageNav postsPerPage={this.state.postsPerPage} totalPosts={this.props.houseList.length} paginate={this.paginate} currentPage={this.state.currentPage} /> <div className='row float-right'> <label className='mr-2'>Houses Per Page:</label> <select className='form-control-sm mb-2 mr-5' id='housesPerPage' ref={(housesPerPage) => { this.housesPerPage = housesPerPage }} onChange={() => { this.setState({postsPerPage: this.housesPerPage.value.toString()}) this.paginate(1) }} > <option value='3'> 3 </option> <option value='6'> 6 </option> <option value='9'> 9 </option> <option value='12'> 12 </option> </select> </div> </> ) } }
JavaScript
class LoginController { /** * Performs login based on an input email and password. * * @param {*} req * @param {*} res * @param {*} next * @returns A JWT token. */ static async login(req, res, next) { const errors = validationResult(req); if (!errors.isEmpty()) { let messages = []; errors.errors.map((error) => { messages.push(error.msg); }); return res.status(400).json(new ClientMessage(true, messages)); } try { passport.authenticate('local', async (error, user) => { if (error) { return res.status(500).json(new ClientMessage(true, [error.message])); } if (!user) { return res.status(401).send(); } req.login(user, { session: false }, async (error) => { if (error) return next(error); const body = { id: user.id, email: user.email, name: user.name, role: user.role, totpValidated: user.totpValidated, totpEnabled: user.totpEnabled, totpLoggedIn: false, }; const { validator, selector } = req.body; if (validator && selector && user.totpEnabled && user.totpValidated) { const hashedValidator = await User.hashPassword(validator); const authToken = await AuthToken.findOne({ where: { selector, }, }); if (authToken) { const hashEqual = await bcrypt.compare( validator, authToken.hashedValidator, ); if (hashEqual && isBefore(new Date(), authToken.expires)) { const newValidator = Crypto.randomBytes(64).toString('base64'); const newSelector = Crypto.randomBytes(12).toString('base64'); authToken.hashedValidator = await User.hashPassword( newValidator, ); authToken.selector = newSelector; await authToken.save(); body.selector = newSelector; body.validator = newValidator; body.totpLoggedIn = true; logger.info( `${user.email} successfully logged into TOTP using a Remember Me token`, ); } } } logger.info( `${user.email} successfully logged in using local strategy`, ); const token = jwt.sign({ user: body }, JWT_SECRET, { expiresIn: '2h', }); return res.json({ token }); }); })(req, res, next); } catch (error) { return next(error); } } static async loginTotp(req, res, next) { const errors = validationResult(req); if (!errors.isEmpty()) { let messages = []; errors.errors.map((error) => { messages.push(error.msg); }); return res.status(400).json(new ClientMessage(true, messages)); } // Set the request user here instead of storing it in session. It's only needed when loggin in. const { userId } = req.body; const user = await User.findByPk(userId); req.user = user; try { passport.authenticate('totp', async (error, user) => { if (error) { return res.status(500).json(new ClientMessage(true, [error.message])); } if (!user) { return res.status(401).send(); } req.login(user, { session: false }, async (error) => { if (error) return next(error); const body = { id: user.id, email: user.email, name: user.name, role: user.role, totpValidated: user.totpValidated, totpEnabled: user.totpEnabled, totpLoggedIn: true, }; const rememberMe = req.body.rememberMe; if (rememberMe) { const validator = Crypto.randomBytes(64).toString('base64'); const selector = Crypto.randomBytes(12).toString('base64'); const authToken = AuthToken.build({ hashedValidator: await User.hashPassword(validator), selector, userId: user.id, expires: add(new Date(), { days: 7 }), }); body.selector = selector; body.validator = validator; await authToken.save(); } logger.info(`${user.email} successfully logged in using TOTP`); const token = jwt.sign({ user: body }, JWT_SECRET, { expiresIn: '2h', }); return res.json({ token }); }); })(req, res, next); } catch (error) { return next(error); } } }
JavaScript
class Warp extends PlugInBlock { /** * Constructor for warp block * * @param {PlugInBlock} parentBlock - The block before this warp one * @param {number} warpFactor - factor for warp (be sure to have a * factor adapted to data order of magnitude) */ constructor (parentBlock, warpFactor = 1) { let setters = { 'warpFactor': (factor) => { this._warpFactorNode.number = factor;} }; super(parentBlock, setters); this._warpFactor = warpFactor; this._warpFactorNode = undefined; this._warpTranslation = undefined; this.inputDataDim = 3; } _process () { // Create a FloatNode representing the warp factor in shaders this._warpFactorNode = new THREE.FloatNode(this._warpFactor); // Create the translation vector used in shaders this._warpTranslation = new THREE.OperatorNode( this._inputDataNode, this._warpFactorNode, THREE.OperatorNode.MUL ); // Add the node to materials this.addTransformNode('ADD', this._warpTranslation); } /** * Change input for warp effect * @param {string} dataName - Name of the input data of which you want * to set input components for this plug-in * @param {string[]} componentNames - A list of components that you * want as input. */ _setInput (dataName, componentNames) { super._setInput(dataName, componentNames); if (this._processed && this._warpTranslation) { this._warpTranslation.a = this._inputDataNode; this.updateMaterial(); } } }
JavaScript
class XsensDot extends EventEmitter { constructor(identifier, options) { super() this.identifier = identifier this.configuration = {} this.peripheral = options.peripheral this.characteristics = options.characteristics || {} debug(`${this.identifier}/XsensDot - initialized new Xsens DOT instance`) } connect = async () => { if (this.connected) return this.peripheral.removeAllListeners() this.peripheral.on('disconnect', async () => { debug(`${this.identifier}/disconnect`) this.emit('disconnect') }) await this.peripheral.connectAsync() const { characteristics } = await this.peripheral.discoverAllServicesAndCharacteristicsAsync() this.characteristics = {} for (const characteristic of characteristics) { this.characteristics[characteristic.uuid] = characteristic } this.configuration = await this.queryConfiguration() debug(`${this.identifier}/connect - connected`) } disconnect = async () => { await this.peripheral.disconnectAsync() } queryConfiguration = async () => { if (!this.connected) return const informationCharacteristic = this.characteristics[XSENS_DOT_BLE_SPEC.configuration.characteristics.information.uuid] const controlCharacteristic = this.characteristics[XSENS_DOT_BLE_SPEC.configuration.characteristics.control.uuid] const information = await informationCharacteristic.readAsync() const control = await controlCharacteristic.readAsync() const configuration = { tag: this.readTag(control, 8), output_rate: this.readOutputRate(control, 24), filter_index: this.readFilterIndex(control, 26), address: this.readAddress(information, 0), firmware: { version: this.readVersion(information, 6), date: this.readDate(information, 9), }, softdevice_version: this.readSoftdeviceVersion(information, 16), serial: this.readSerialNumber(information, 20), product_code: this.readProductCode(information, 28), } debug(`${this.identifier} - queryConfiguration:`, configuration) return configuration } subscribeStatus = async (notify = true) => { if (!this.connected) return false const reportCharacteristic = this.characteristics[XSENS_DOT_BLE_SPEC.configuration.characteristics.report.uuid] if (notify) { await reportCharacteristic.subscribeAsync() reportCharacteristic.on('data', this.listenerStatus.bind(this)) } else { await reportCharacteristic.unsubscribeAsync() reportCharacteristic.removeListener('data', this.listenerStatus) } debug(`${this.identifier}/subscribeStatus - status notifications ${notify ? 'enabled' : 'disabled'}`) return true } unsubscribeStatus = async () => { return await this.subscribeStatus(false) } listenerStatus = (data) => { const status = XSENS_DOT_BLE_SPEC.configuration.characteristics.report.status[data.readInt8(0)] // 1 byte debug(`${this.identifier}/listenerStatus - status notification:`, status) this.emit('status', status) } subscribeBattery = async (notify = true) => { if (!this.connected) return false const batteryCharacteristic = this.characteristics[XSENS_DOT_BLE_SPEC.battery.characteristics.battery.uuid] if (notify) { await batteryCharacteristic.subscribeAsync() batteryCharacteristic.on('data', this.listenerBattery.bind(this)) batteryCharacteristic.read() } else { await batteryCharacteristic.unsubscribeAsync() batteryCharacteristic.removeListener('data', this.listenerBattery) } debug(`${this.identifier}/subscribeBattery - battery notifications ${notify ? 'enabled' : 'disabled'}`) return true } unsubscribeBattery = async () => { return await this.subscribeBattery(false) } listenerBattery = (data) => { const battery = { // Battery level (%) level: data.readInt8(0), // 1 byte // Battery charging (boolean) charging: data.readInt8(1) ? true : false, // 1 byte } debug(`${this.identifier}/listenerBattery - battery notification:`, battery) this.emit('battery', battery) } subscribeMeasurement = async (payloadType = XSENS_DOT_PAYLOAD_TYPE.completeQuaternion, notify = true) => { if (!this.connected) return false const service = XSENS_DOT_BLE_SPEC.measurement const control = service.characteristics.control const measurement = service.characteristics[service.payloadCharacteristic[payloadType]] if (typeof measurement === 'undefined') { throw new Error(`Measurement subscription request for unknown payload type (${payloadType})`) } const controlCharacteristic = this.characteristics[control.uuid] const measurementCharacteristic = this.characteristics[measurement.uuid] const message = Buffer.from([control.type.measurement, notify ? control.action.start : control.action.stop, measurement.payload[payloadType]]) await controlCharacteristic.writeAsync(message, false) if (notify) { await measurementCharacteristic.subscribeAsync() measurementCharacteristic.on('data', this.listenerMeasurement.bind(this, payloadType)) } else { await measurementCharacteristic.unsubscribeAsync() measurementCharacteristic.removeListener('data', this.listenerMeasurement) } debug(`${this.identifier}/subscribeMeasurement - measurement notifications ${notify ? 'enabled' : 'disabled'}`) return true } unsubscribeMeasurement = async (payloadType) => { return await this.subscribeMeasurement(payloadType, false) } listenerMeasurement = (payloadType, data) => { let measurement = {} switch (payloadType) { case XSENS_DOT_PAYLOAD_TYPE.extendedQuaternion: measurement = { timestamp: this.readTimestamp(data, 0), quaternion: this.readQuaternion(data, 4), freeAcceleration: this.readAcceleration(data, 20), status: this.readStatus(data, 32), clipCountAcc: this.readClipCount(data, 34), clipCountGyr: this.readClipCount(data, 35), } break case XSENS_DOT_PAYLOAD_TYPE.completeQuaternion: measurement = { timestamp: this.readTimestamp(data, 0), quaternion: this.readQuaternion(data, 4), freeAcceleration: this.readAcceleration(data, 20), } break case XSENS_DOT_PAYLOAD_TYPE.extendedEuler: measurement = { timestamp: this.readTimestamp(data, 0), euler: this.readEuler(data, 4), freeAcceleration: this.readAcceleration(data, 16), status: this.readStatus(data, 28), clipCountAcc: this.readClipCount(data, 30), clipCountGyr: this.readClipCount(data, 31), } break case XSENS_DOT_PAYLOAD_TYPE.completeEuler: measurement = { timestamp: this.readTimestamp(data, 0), euler: this.readEuler(data, 4), freeAcceleration: this.readAcceleration(data, 16), } break case XSENS_DOT_PAYLOAD_TYPE.orientationQuaternion: measurement = { timestamp: this.readTimestamp(data, 0), quaternion: this.readQuaternion(data, 4), } break case XSENS_DOT_PAYLOAD_TYPE.orientationEuler: measurement = { timestamp: this.readTimestamp(data, 0), euler: this.readEuler(data, 4), } break case XSENS_DOT_PAYLOAD_TYPE.freeAcceleration: measurement = { timestamp: this.readTimestamp(data, 0), freeAcceleration: this.readAcceleration(data, 4), } break } debug(`${this.identifier}/listenerMeasurement - measurement notification:`, measurement) this.emit('measurement', measurement) } readAddress = (data, offset) => { const pad = (n) => { return (n.length < 2 ? '0' : '') + n } const address = new Array(6) for (let i = 0; i < address.length; i++) { address[i] = pad(data.readUInt8(offset + i).toString(16)) } return address.reverse().join(':') } readVersion = (data, offset) => { return `${data.readUInt8(offset)}.${data.readUInt8(offset + 1)}.${data.readUInt8(offset + 2)}` } readDate = (data, offset) => { const pad = (n) => { return (n < 10 ? '0' : '') + n } const date = `${data.readInt16LE(offset)}-${pad(data.readInt8(offset + 2))}-${pad(data.readInt8(offset + 3))}` const time = `${pad(data.readInt8(offset + 4))}:${pad(data.readInt8(offset + 5))}:${pad(data.readInt8(offset + 6))}` return new Date(date + 'T' + time) } readSoftdeviceVersion = (data, offset) => { return `${data.readUInt32LE(offset)}` } readSerialNumber = (data, offset) => { return `${data.readBigUInt64LE(offset).toString(16)}` } readProductCode = (data, offset) => { const bytes = data.slice(offset, offset + 6) return bytes.toString('utf8', 0, 6) } readTag = (data, offset) => { const bytes = data.slice(offset, offset + 16) return bytes.toString('utf8', 0, bytes.indexOf('\x00')) } readOutputRate = (data, offset) => { return `${data.readInt8(offset)}` } readFilterIndex = (data, offset) => { return `${data.readUInt8(offset)}` } readTimestamp = (data, offset) => { return data.readUInt32LE(offset) } readQuaternion = (data, offset) => { return { w: data.readFloatLE(offset), x: data.readFloatLE(offset + 4), y: data.readFloatLE(offset + 8), z: data.readFloatLE(offset + 12), } } readEuler = (data, offset) => { return { x: data.readFloatLE(offset), y: data.readFloatLE(offset + 4), z: data.readFloatLE(offset + 8), } } readAcceleration = (data, offset) => { return { x: data.readFloatLE(offset), y: data.readFloatLE(offset + 4), z: data.readFloatLE(offset + 8), } } readStatus = (data, offset) => { let status = data.readInt16LE(offset) status = (status & 0x1ff) << 8 return status } readClipCount = (data, offset) => { return data.readInt8(offset) } get connected() { const connected = this.state === PERIPHERAL_STATE.connected && Object.keys(this.characteristics).length > 0 return connected } get connecting() { return this.state === PERIPHERAL_STATE.connecting } get state() { return this.peripheral.state } }
JavaScript
class FacebookAdapter extends botbuilder_1.BotAdapter { /** * Create an adapter to handle incoming messages from Facebook and translate them into a standard format for processing by your bot. * * The Facebook Adapter can be used in 2 modes: * * bound to a single Facebook page * * multi-tenancy mode able to serve multiple pages * * To create an app bound to a single Facebook page, include that page's `access_token` in the options. * * To create an app that can be bound to multiple pages, include `getAccessTokenForPage` - a function in the form `async (pageId) => page_access_token` * * To use with Botkit: * ```javascript * const adapter = new FacebookAdapter({ * verify_token: process.env.FACEBOOK_VERIFY_TOKEN, * app_secret: process.env.FACEBOOK_APP_SECRET, * access_token: process.env.FACEBOOK_ACCESS_TOKEN * }); * const controller = new Botkit({ * adapter: adapter, * // other options * }); * ``` * * To use with BotBuilder: * ```javascript * const adapter = new FacebookAdapter({ * verify_token: process.env.FACEBOOK_VERIFY_TOKEN, * app_secret: process.env.FACEBOOK_APP_SECRET, * access_token: process.env.FACEBOOK_ACCESS_TOKEN * }); * const server = restify.createServer(); * server.use(restify.plugins.bodyParser()); * server.post('/api/messages', (req, res) => { * adapter.processActivity(req, res, async(context) => { * // do your bot logic here! * }); * }); * ``` * * In multi-tenancy mode: * ```javascript * const adapter = new FacebookAdapter({ * verify_token: process.env.FACEBOOK_VERIFY_TOKEN, * app_secret: process.env.FACEBOOK_APP_SECRET, * getAccessTokenForPage: async(pageId) => { * // do something to fetch the page access token for pageId. * return token; * }) * }); *``` * * @param options Configuration options */ constructor(options) { super(); /** * Name used by Botkit plugin loader * @ignore */ this.name = 'Facebook Adapter'; /** * A customized BotWorker object that exposes additional utility methods. * @ignore */ this.botkit_worker = botworker_1.FacebookBotWorker; this.options = Object.assign({ api_host: 'graph.facebook.com', api_version: 'v3.2' }, options); if (!this.options.access_token && !this.options.getAccessTokenForPage) { const err = 'Adapter must receive either an access_token or a getAccessTokenForPage function.'; if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } if (!this.options.app_secret) { const err = 'Provide an app_secret in order to validate incoming webhooks and better secure api requests'; if (!this.options.enable_incomplete) { throw new Error(err); } else { console.error(err); } } if (this.options.enable_incomplete) { const warning = [ '', '****************************************************************************************', '* WARNING: Your adapter may be running with an incomplete/unsafe configuration. *', '* - Ensure all required configuration options are present *', '* - Disable the "enable_incomplete" option! *', '****************************************************************************************', '' ]; console.warn(warning.join('\n')); } this.middlewares = { spawn: [ (bot, next) => __awaiter(this, void 0, void 0, function* () { bot.api = yield this.getAPI(bot.getConfig('activity')); next(); }) ] }; } /** * Botkit-only: Initialization function called automatically when used with Botkit. * * Amends the webhook_uri with an additional behavior for responding to Facebook's webhook verification request. * @param botkit */ init(botkit) { return __awaiter(this, void 0, void 0, function* () { debug('Add GET webhook endpoint for verification at: ', botkit.getConfig('webhook_uri')); if (botkit.webserver) { botkit.webserver.get(botkit.getConfig('webhook_uri'), (req, res) => { if (req.query['hub.mode'] === 'subscribe') { if (req.query['hub.verify_token'] === this.options.verify_token) { res.send(req.query['hub.challenge']); } else { res.send('OK'); } } }); } }); } /** * Get a Facebook API client with the correct credentials based on the page identified in the incoming activity. * This is used by many internal functions to get access to the Facebook API, and is exposed as `bot.api` on any BotWorker instances passed into Botkit handler functions. * * ```javascript * let api = adapter.getAPI(activity); * let res = api.callAPI('/me/messages', 'POST', message); * ``` * @param activity An incoming message activity */ getAPI(activity) { return __awaiter(this, void 0, void 0, function* () { if (this.options.access_token) { return new facebook_api_1.FacebookAPI(this.options.access_token, this.options.app_secret, this.options.api_host, this.options.api_version); } else { if (activity.recipient.id) { let pageid = activity.recipient.id; // if this is an echo, the page id is actually in the from field if (activity.channelData && activity.channelData.message && activity.channelData.message.is_echo === true) { pageid = activity.from.id; } const token = yield this.options.getAccessTokenForPage(pageid); if (!token) { throw new Error('Missing credentials for page.'); } return new facebook_api_1.FacebookAPI(token, this.options.app_secret, this.options.api_host, this.options.api_version); } else { // No API can be created, this is debug('Unable to create API based on activity: ', activity); } } }); } /** * Converts an Activity object to a Facebook messenger outbound message ready for the API. * @param activity */ activityToFacebook(activity) { const message = { recipient: { id: activity.conversation.id }, message: { text: activity.text, sticker_id: undefined, attachment: undefined, quick_replies: undefined }, messaging_type: 'RESPONSE', tag: undefined, notification_type: undefined, persona_id: undefined, sender_action: undefined }; // map these fields to their appropriate place if (activity.channelData) { if (activity.channelData.messaging_type) { message.messaging_type = activity.channelData.messaging_type; } if (activity.channelData.tag) { message.tag = activity.channelData.tag; } if (activity.channelData.sticker_id) { message.message.sticker_id = activity.channelData.sticker_id; } if (activity.channelData.attachment) { message.message.attachment = activity.channelData.attachment; } if (activity.channelData.persona_id) { message.persona_id = activity.channelData.persona_id; } if (activity.channelData.notification_type) { message.notification_type = activity.channelData.notification_type; } if (activity.channelData.sender_action) { message.sender_action = activity.channelData.sender_action; // from docs: https://developers.facebook.com/docs/messenger-platform/reference/send-api/ // Cannot be sent with message. Must be sent as a separate request. // When using sender_action, recipient should be the only other property set in the request. delete (message.message); } // make sure the quick reply has a type if (activity.channelData.quick_replies) { message.message.quick_replies = activity.channelData.quick_replies.map(function (item) { const quick_reply = Object.assign({}, item); if (!item.content_type) quick_reply.content_type = 'text'; return quick_reply; }); } } debug('OUT TO FACEBOOK > ', JSON.stringify(message, null, 4)); return message; } /** * Standard BotBuilder adapter method to send a message from the bot to the messaging API. * [BotBuilder reference docs](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/botadapter?view=botbuilder-ts-latest#sendactivities). * @param context A TurnContext representing the current incoming message and environment. * @param activities An array of outgoing activities to be sent back to the messaging API. */ sendActivities(context, activities) { return __awaiter(this, void 0, void 0, function* () { const responses = []; for (let a = 0; a < activities.length; a++) { const activity = activities[a]; if (activity.type === botbuilder_1.ActivityTypes.Message) { const message = this.activityToFacebook(activity); try { const api = yield this.getAPI(context.activity); const res = yield api.callAPI('/me/messages', 'POST', message); if (res) { responses.push({ id: res.message_id }); } debug('RESPONSE FROM FACEBOOK > ', JSON.stringify(res, null, 4)); } catch (err) { console.error('Error sending activity to Facebook:', err); } } else if (activity.type === botbuilder_1.ActivityTypes.Typing) { activity.channelData = { sender_action: "typing_on" }; const message = this.activityToFacebook(activity); try { const api = yield this.getAPI(context.activity); const res = yield api.callAPI('/me/messages', 'POST', message); if (res) { responses.push({ id: res.message_id }); } debug('RESPONSE FROM FACEBOOK > ', JSON.stringify(res, null, 4)); } catch (err) { console.error('Error sending activity to Facebook:', err); } } else { // If there are ever any non-message type events that need to be sent, do it here. debug('Unknown message type encountered in sendActivities: ', activity.type); } } return responses; }); } /** * Facebook adapter does not support updateActivity. * @ignore */ // eslint-disable-next-line updateActivity(context, activity) { return __awaiter(this, void 0, void 0, function* () { debug('Facebook adapter does not support updateActivity.'); }); } /** * Facebook adapter does not support updateActivity. * @ignore */ // eslint-disable-next-line deleteActivity(context, reference) { return __awaiter(this, void 0, void 0, function* () { debug('Facebook adapter does not support deleteActivity.'); }); } /** * Standard BotBuilder adapter method for continuing an existing conversation based on a conversation reference. * [BotBuilder reference docs](https://docs.microsoft.com/en-us/javascript/api/botbuilder-core/botadapter?view=botbuilder-ts-latest#continueconversation) * @param reference A conversation reference to be applied to future messages. * @param logic A bot logic function that will perform continuing action in the form `async(context) => { ... }` */ continueConversation(reference, logic) { return __awaiter(this, void 0, void 0, function* () { const request = botbuilder_1.TurnContext.applyConversationReference({ type: 'event', name: 'continueConversation' }, reference, true); const context = new botbuilder_1.TurnContext(this, request); return this.runMiddleware(context, logic); }); } /** * Accept an incoming webhook request and convert it into a TurnContext which can be processed by the bot's logic. * @param req A request object from Restify or Express * @param res A response object from Restify or Express * @param logic A bot logic function in the form `async(context) => { ... }` */ processActivity(req, res, logic) { return __awaiter(this, void 0, void 0, function* () { debug('IN FROM FACEBOOK >', JSON.stringify(req.body, null, 4)); if ((yield this.verifySignature(req, res)) === true) { const event = req.body; if (event.entry) { for (let e = 0; e < event.entry.length; e++) { let payload = null; const entry = event.entry[e]; // handle normal incoming stuff if (entry.changes) { payload = entry.changes; } else if (entry.messaging) { payload = entry.messaging; } for (let m = 0; m < payload.length; m++) { yield this.processSingleMessage(payload[m], logic); } // handle standby messages (this bot is not the active receiver) if (entry.standby) { payload = entry.standby; for (let m = 0; m < payload.length; m++) { const message = payload[m]; // indiciate that this message was received in standby mode rather than normal mode. message.standby = true; yield this.processSingleMessage(message, logic); } } } res.status(200); res.end(); } } }); } /** * Handles each individual message inside a webhook payload (webhook may deliver more than one message at a time) * @param message * @param logic */ processSingleMessage(message, logic) { return __awaiter(this, void 0, void 0, function* () { // in case of Checkbox Plug-in sender.id is not present, instead we should look at optin.user_ref if (!message.sender && message.optin && message.optin.user_ref) { message.sender = { id: message.optin.user_ref }; } const activity = { channelId: 'facebook', timestamp: new Date(), // @ts-ignore ignore missing optional fields conversation: { id: message.sender.id }, from: { id: message.sender.id, name: message.sender.id }, recipient: { id: message.recipient.id, name: message.recipient.id }, channelData: message, type: botbuilder_1.ActivityTypes.Event, text: null }; if (message.message) { activity.type = botbuilder_1.ActivityTypes.Message; activity.text = message.message.text; if (activity.channelData.message.is_echo) { activity.type = botbuilder_1.ActivityTypes.Event; } // copy fields like attachments, sticker, quick_reply, nlp, etc. for (const key in message.message) { activity.channelData[key] = message.message[key]; } if (activity.channelData.message.quick_reply && activity.channelData.message.quick_reply.payload.length > 0) { activity.text = activity.channelData.message.quick_reply.payload; } } else if (message.postback) { activity.type = botbuilder_1.ActivityTypes.Message; activity.text = message.postback.payload; } const context = new botbuilder_1.TurnContext(this, activity); yield this.runMiddleware(context, logic); }); } /* * Verifies the SHA1 signature of the raw request payload before bodyParser parses it * Will abort parsing if signature is invalid, and pass a generic error to response */ verifySignature(req, res) { return __awaiter(this, void 0, void 0, function* () { const expected = req.headers['x-hub-signature']; const hmac = crypto.createHmac('sha1', this.options.app_secret); hmac.update(req.rawBody, 'utf8'); const calculated = 'sha1=' + hmac.digest('hex'); if (expected !== calculated) { res.status(401); debug('Token verification failed, Ignoring message'); throw new Error('Invalid signature on incoming request'); } else { return true; } }); } }
JavaScript
class WheeledVehicle extends Vehicle { constructor(id, name, price, wheels) { super(id, name, price); // console.log(`Please wait, wheeled vehicle ${name} is creating.......`); this.wheels = wheels; } driveVehicle() { console.log(`We are driving ${this.name} on ${this.wheels} wheels`) } }
JavaScript
class Main { /** * Constructor creates and initializes the variables needed for * the application */ constructor() { // Initialize images this.originalImg = document.getElementById('original-img'); this.originalImg.style.width = "112px"; this.originalImg.style.height = "112px"; this.noisyImg = document.getElementById('noisy-img'); this.noisyImg.style.width = "112px"; this.noisyImg.style.height = "112px"; this.restoredImg = document.getElementById('restored-img'); this.restoredImg.style.width = "112px"; this.restoredImg.style.height = "112px"; // Initialize buttons this.newDigit = document.getElementById('new-digit'); this.newDigit.onclick = () => this.updateInputTensor(); this.newNoise = document.getElementById('new-noise'); this.newNoise.onclick = () => this.updateNoiseTensor(); tf.loadModel('model/model.json').then((model) => { this.model = model; this.initializeTensors(); }); } /** * Initialize tensors. */ initializeTensors() { this.noiseTensor = tf.randomNormal([28, 28, 1], 0, 0.5); this.updateInputTensor(); } updateInputTensor() { let randInt = Math.floor(Math.random() * 1002); let temp = new Image(); temp.src = 'test_digits/' + randInt + '.png'; temp.onload = () => { if (this.inputTensor) { this.inputTensor.dispose(); } this.inputTensor = tf.tidy(() => tf.fromPixels(temp, 1).toFloat().div(tf.scalar(255)) ); tf.toPixels(this.inputTensor, this.originalImg); this.updateDistortedTensor(); } } updateNoiseTensor() { this.noiseTensor.dispose(); this.noiseTensor = tf.randomNormal([28, 28, 1], 0, 0.5); this.updateDistortedTensor(); } updateDistortedTensor() { if (this.distortedTensor) { this.distortedTensor.dispose(); } this.distortedTensor = tf.tidy(() => { return this.noiseTensor.add(this.inputTensor).clipByValue(0, 1); }); tf.toPixels(this.distortedTensor, this.noisyImg); this.updateFixedTensor(); } updateFixedTensor() { if (this.fixedTensor) { this.fixedTensor.dispose(); } this.fixedTensor = tf.tidy(() => { return this.model.predict(this.distortedTensor.expandDims()).squeeze(); }); tf.toPixels(this.fixedTensor, this.restoredImg); } }
JavaScript
class Tooltip extends Component { // TODO: Make tooltip visible from props; Add tests for components with createPortal static propTypes = { /** Is tooltip on top or on bottom from target */ position: PropTypes.oneOf(['top', 'bottom', 'right', 'left']), /** Tooltip background color */ state: PropTypes.oneOf(['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark', 'link']), /** Tooltip message */ body: PropTypes.oneOfType([PropTypes.string, PropTypes.object, PropTypes.func]), bodyStyle: PropTypes.object, }; static defaultProps = { position: 'top', state: 'dark', }; state = { isTooltipVisible: false }; get bodyPosition() { if (!this.trigger) { return {}; } const {left, top } = getElementCouplingPoint(this.trigger, this.props.position); return { left, top, }; } get content() { const { body } = this.props; if (typeof body === 'string') { return ( <div dangerouslySetInnerHTML={{ __html: body }}></div> ); } return body; } get body() { const { body, state, position, bodyStyle } = this.props; const { isTooltipVisible } = this.state; if (!!body && (!!isTooltipVisible)) { return createPortal( (<div ref={(div) => this.tooltipBody = div} role="tooltip" className={classnames( 'wrc-tooltip__body', [`wrc-tooltip__body--${state}`], [`wrc-tooltip__body--${position}`] )} style={{ ...this.bodyPosition, ...bodyStyle }}> {this.content} </div >), getPortalContainer() ); } return null; } handleMouseEnter = () => { this.setState({ isTooltipVisible: true }); } handleMouseLeave = () => { this.setState({ isTooltipVisible: false }); } render() { const { children, className, style, visible } = this.props; return ( <div className={classnames('wrc-tooltip', className)} style={style} ref={div => this.trigger = div} onMouseEnter={(visible === undefined) ? this.handleMouseEnter : undefined} onMouseLeave={(visible === undefined) ? this.handleMouseLeave : undefined}> {children} {this.body} </div> ); } }
JavaScript
class PermissionsTable extends BotTable { /** * This table's name. * @type {string} */ static get PERMISSIONS_TABLE_NAME() { return PERMISSIONS_TABLE_NAME; } /** * Gets the class representing a row in this collection. * @return {Object} the row class */ getRowClass() { return OrgPermission; } /** * Gets an instance of a class representing a row in this collection, based on the provided values * @param {Object} dbObj the raw object from DB * @return {Object} the row class' instance */ getRowInstance(dbObject) { return new OrgPermission(dbObject); } /** * Gets this collection's name. * @return {string} the table name */ getTableName() { return PERMISSIONS_TABLE_NAME; } }
JavaScript
class Emitter { /** * Constructor. */ constructor() { this.events = {}; } /** * On event. Calls the listener function when the given * event occurs. * * @param {string} event event name. * @param {function} listener listener function. */ on(event, listener) { const handler = this.events[event]; if (handler === undefined) { this.events[event] = listener; } else if (typeof handler === 'function') { this.events[event] = [handler, listener]; } else { handler.push(listener); } } /** * Emit event. Emits the event to the listeners. * * @param {string} event event name. * @param {any} args event arguments. */ emit(event, ...args) { const handler = this.events[event]; if (handler !== undefined) { if (typeof handler === 'function') { handler(...args); } else { handler.forEach((listener) => listener(...args)); } } } }
JavaScript
class Engine { constructor() { } /** * Initializes every module in the engine and load the resources of the game. */ initialize() { Render_1.Render.initialize(); AssetManager_1.AssetManager.initialize(); Input_1.Input.initialize(); SceneManager_1.SceneManager.initialize(); Mesh_1.Mesh.initialize(); /**Asset declaration */ let vertexshaderAssetglsl = AssetManager_1.AssetManager.getAsset("assets/textures/2.glsl"); let vertexshaderAsset = AssetManager_1.AssetManager.getAsset("assets/textures/1.txt"); let mesh = new Mesh_1.Mesh("cube.json"); let mesh2 = new Mesh_1.Mesh("Model.json"); let texture = new Texture_1.Texture("assets/textures/crate.png"); let material = new Material_1.Material("material", texture, TextureMeshShader_1.TextureMeshShader.program); let materialdeer = new Material_1.Material("material", texture); this.resize(); const promises = AssetManager_1.AssetManager.getPromises(); const handlers = AssetManager_1.AssetManager.getHandlers(); Promise.all(promises).then(data => { for (let i = 0; i < data.length; i++) { handlers[i].onSyncLoad(data[i]); } /**Deer */ let deer = new GameObject_1.GameObject("deer"); deer.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let component3 = new RenderableComponent_1.RenderableComponent(deer, mesh2, materialdeer); deer.transform.position = new Vector3_1.Vector3(30, 0, 50); deer.transform.rotateX(GlMatrix_1.GlMatrix.toRadian(-90)); /**Directional Light */ let dirGameObject = new GameObject_1.GameObject("directionalLightGameObject"); let dirLightPlayer = new DirectionalLightComponent_1.DirectionalLightComponent(dirGameObject); dirGameObject.transform.forward = new Vector3_1.Vector3(1, 1, 1); /**Player */ let player = new GameObject_1.GameObject("playerGameObject"); player.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); player.transform.position = new Vector3_1.Vector3(1, 0.5, 5); let renderComponentPlayer = new RenderableComponent_1.RenderableComponent(player, mesh); let boxColliderOfPlayer = new BoxColliderComponent_1.BoxColliderComponent(player); boxColliderOfPlayer.isTrigger = false; let playerController = new ControllerComponent_1.ControllerComponent(player); /**Animated Component */ let animatedGo = new GameObject_1.GameObject("animatedGo"); animatedGo.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); animatedGo.transform.position = new Vector3_1.Vector3(20, 1, 20); let testcomponet = new AnimationComponent_1.AnimationComponent(animatedGo); let component = new RenderableComponent_1.RenderableComponent(animatedGo, mesh, material); /**Platform 1 */ let boxPlatform1 = new GameObject_1.GameObject("boxPlatform1", new Vector3_1.Vector3(10, 0, 10)); boxPlatform1.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform1); boxPlatformCollider.isTrigger = false; let boxPlatform1Render = new RenderableComponent_1.RenderableComponent(boxPlatform1, mesh, material); /**Platform 2 */ let boxPlatform2 = new GameObject_1.GameObject("boxPlatform2", new Vector3_1.Vector3(10, 3.8, 12)); boxPlatform2.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider2 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform2); boxPlatformCollider2.isTrigger = false; let boxPlatform2Render = new RenderableComponent_1.RenderableComponent(boxPlatform2, mesh, material); /**Platform 3 */ let boxPlatform3 = new GameObject_1.GameObject("boxPlatform3", new Vector3_1.Vector3(8, 8, 12)); boxPlatform3.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider3 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform3); boxPlatformCollider3.isTrigger = false; let boxPlatform2Render3 = new RenderableComponent_1.RenderableComponent(boxPlatform3, mesh, material); /**Platform 4*/ let boxPlatform4 = new GameObject_1.GameObject("boxPlatform4", new Vector3_1.Vector3(8, 12, 15)); boxPlatform4.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider4 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform4); boxPlatformCollider4.isTrigger = false; let boxPlatform2Render4 = new RenderableComponent_1.RenderableComponent(boxPlatform4, mesh, material); /**Platform 5*/ let boxPlatform5 = new GameObject_1.GameObject("boxPlatform5", new Vector3_1.Vector3(8, 14, 19)); boxPlatform5.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider5 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform5); boxPlatformCollider5.isTrigger = false; let boxPlatform2Render5 = new RenderableComponent_1.RenderableComponent(boxPlatform5, mesh, material); /**Platform 6*/ let boxPlatform6 = new GameObject_1.GameObject("boxPlatform6", new Vector3_1.Vector3(14, 14, 19)); boxPlatform6.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider6 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform6); boxPlatformCollider6.isTrigger = false; let boxPlatform2Render6 = new RenderableComponent_1.RenderableComponent(boxPlatform6, mesh, material); /**Platform 7*/ let boxPlatform7 = new GameObject_1.GameObject("boxPlatform7", new Vector3_1.Vector3(19, 16, 19)); boxPlatform7.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider7 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform7); boxPlatformCollider7.isTrigger = false; let boxPlatform2Render7 = new RenderableComponent_1.RenderableComponent(boxPlatform7, mesh, material); /**Platform 8 Moving*/ let boxPlatform8 = new GameObject_1.GameObject("boxPlatform8", new Vector3_1.Vector3(23, 16, 19)); boxPlatform8.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider8 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform8); boxPlatformCollider8.isTrigger = false; let movingPlatform8 = new MovingPlatformComponent_1.MovingPlatformComponent(boxPlatform8, new Vector3_1.Vector3(29, 16, 19)); let boxPlatform2Render8 = new RenderableComponent_1.RenderableComponent(boxPlatform8, mesh, material); /**Platform9 Moving*/ let boxPlatform9 = new GameObject_1.GameObject("boxPlatform9", new Vector3_1.Vector3(31, 16, 19)); boxPlatform9.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider9 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform9); boxPlatformCollider9.isTrigger = false; let movingPlatform9 = new MovingPlatformComponent_1.MovingPlatformComponent(boxPlatform9, new Vector3_1.Vector3(36, 20, 19)); let boxPlatform2Render9 = new RenderableComponent_1.RenderableComponent(boxPlatform9, mesh, material); /**Platform10*/ let boxPlatform10 = new GameObject_1.GameObject("boxPlatform10", new Vector3_1.Vector3(40, 25, 19)); boxPlatform10.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider10 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform10); boxPlatformCollider10.isTrigger = false; let boxPlatform2Render10 = new RenderableComponent_1.RenderableComponent(boxPlatform10, mesh, material); /**Platform11*/ let boxPlatform11 = new GameObject_1.GameObject("boxPlatform11", new Vector3_1.Vector3(40, 27, 19)); boxPlatform11.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider11 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform11); boxPlatformCollider11.isTrigger = false; let boxPlatform2Render11 = new RenderableComponent_1.RenderableComponent(boxPlatform11, mesh, material); /**Platform12*/ let boxPlatform12 = new GameObject_1.GameObject("boxPlatform12", new Vector3_1.Vector3(40, 29, 19)); boxPlatform12.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider12 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform12); boxPlatformCollider12.isTrigger = false; let boxPlatform2Render12 = new RenderableComponent_1.RenderableComponent(boxPlatform12, mesh, material); /**Platform13*/ let boxPlatform13 = new GameObject_1.GameObject("boxPlatform13", new Vector3_1.Vector3(50, 29, 19)); boxPlatform13.transform.scale = new Vector3_1.Vector3(0.1, 0.1, 0.1); let boxPlatformCollider13 = new BoxColliderComponent_1.BoxColliderComponent(boxPlatform13); boxPlatformCollider13.isTrigger = false; let boxPlatform2Render13 = new RenderableComponent_1.RenderableComponent(boxPlatform13, mesh, material); /**Collectable 1 */ let collectable1 = new GameObject_1.GameObject("collectable1"); collectable1.transform.position = new Vector3_1.Vector3(1, 0.8, 1); let renderCollectable1 = new RenderableComponent_1.RenderableComponent(collectable1, mesh); let collectableCollider1 = new BoxColliderComponent_1.BoxColliderComponent(collectable1); collectable1.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let collectableComponent1 = new CollectableComponent_1.CollectableComponent(collectable1); /**Collectable 2 */ let collectable2 = new GameObject_1.GameObject("collectable2"); collectable2.transform.position = new Vector3_1.Vector3(14, 16, 20); let renderCollectable2 = new RenderableComponent_1.RenderableComponent(collectable2, mesh); let collectableCollider2 = new BoxColliderComponent_1.BoxColliderComponent(collectable2); collectable2.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let collectableComponent2 = new CollectableComponent_1.CollectableComponent(collectable2); /**Collectable 3 */ let collectable3 = new GameObject_1.GameObject("collectable3"); collectable3.transform.position = new Vector3_1.Vector3(40, 31, 20); let renderCollectable3 = new RenderableComponent_1.RenderableComponent(collectable3, mesh); let collectableCollider3 = new BoxColliderComponent_1.BoxColliderComponent(collectable3); collectable3.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let collectableComponent3 = new CollectableComponent_1.CollectableComponent(collectable3); /**Collectable 4 */ let collectable4 = new GameObject_1.GameObject("collectable4"); collectable4.transform.position = new Vector3_1.Vector3(47, 33, 19); let renderCollectable4 = new RenderableComponent_1.RenderableComponent(collectable4, mesh); let collectableCollider34 = new BoxColliderComponent_1.BoxColliderComponent(collectable4); collectable4.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let collectableComponent4 = new CollectableComponent_1.CollectableComponent(collectable4); /**Collectable 5 */ let collectable5 = new GameObject_1.GameObject("collectable5"); collectable5.transform.position = new Vector3_1.Vector3(60, 26, 19); let renderCollectable5 = new RenderableComponent_1.RenderableComponent(collectable5, mesh); let collectableCollider35 = new BoxColliderComponent_1.BoxColliderComponent(collectable5); collectable5.transform.scale = new Vector3_1.Vector3(0.03, 0.03, 0.03); let collectableComponent5 = new CollectableComponent_1.CollectableComponent(collectable5); /**Scene Two index 1 */ let SceneTwo = SceneManager_1.SceneManager.createNewScene("endScene"); SceneManager_1.SceneManager.changeScene(1); let goSceneTwo = new GameObject_1.GameObject("goSceneTwo"); let renderCompGoSceneTwo = new RenderableComponent_1.RenderableComponent(goSceneTwo, Mesh_1.Mesh.defaultCube); SceneManager_1.SceneManager.changeScene(0); this.awake(); this.start(); this.gameLoop(); }); } /** * First function to be called from the engine works for initialize classes and variables. */ awake() { let gos = SceneManager_1.SceneManager.actualScene.getAllGameObjects(); for (let name in gos) { let go = gos[name]; let components = go.getComponents(); for (let i = 0; i < components.length; i++) { components[i].awake(); } } } /** * Every class should be already initialized and the game will start. */ start() { Time_1.Time.start(); SceneManager_1.SceneManager.actualScene.printAllGameObjects(); let gos = SceneManager_1.SceneManager.actualScene.getAllGameObjects(); for (let name in gos) { let go = gos[name]; let components = go.getComponents(); for (let i = 0; i < components.length; i++) { components[i].start(); } } } /** * Game loop of the Engine the order of execution is: * * Time * * Render * * Dinamic assets * * Corutines * * Message * * Components * * Inputs */ gameLoop() { Time_1.Time.thick(); Render_1.Render.update(); MessageManager_1.MessageManager.update(); for (let i = 0; i < Engine.corutineList.length; i++) { Engine.corutineList[i].next(); } let gos = SceneManager_1.SceneManager.actualScene.getAllGameObjects(); //fixed update call if (Time_1.Time.pastFixedTime()) { Physics_1.Physics.fixedUpdate(); for (let name in gos) { let go = gos[name]; if (go.enabled) { let components = go.getComponents(); for (let i = 0; i < components.length; i++) { if (components[i].enabled) { components[i].fixedUpdate(); } } } } } //update call for (let name in gos) { let go = gos[name]; if (go.enabled) { let components = go.getComponents(); for (let i = 0; i < components.length; i++) { if (components[i].enabled) { components[i].update(); } } } } Input_1.Input.update(); requestAnimationFrame(this.gameLoop.bind(this)); } instanciateCube() { console.log("funciona"); } /** * Stops the game engine */ stop() { } /** * Resizes the canvas. */ resize() { Render_1.Render.resize(); } /** * Add a corutine to the execution of the game. * @param {any} corutine */ static addCorutine(corutine) { Engine.corutineList.push(corutine); } }
JavaScript
class App extends Component { // constructor() is always called with props constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; // this is the initial search term on page load this.videoSearch('surfboards'); } // at least for now, I prefer to have render() right after constructor() render() { // this is lodash, basically limits how frequently this.videoSearch can be called // function (term) { this.videoSearch(term)...} const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300); return ( <div> {/* we pass a callback to SearchBar */} {/* we pass a property, onSearchTermChange to SearchBar that calls videoSearch */} {/* */} <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList // we're passing onVideoSelect as a callback to VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo})} // this is passing props to VideoList, parent to child videos={this.state.videos}/> </div> ); } videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { // this.setState({videos}) = this.setState({ videos: videos}) this.setState({ videos: videos, // grabs the first video from the 5 search results selectedVideo: videos[0] }); }); } }
JavaScript
class actorData { /** * @constructs actorData * @param {array} type - Type of actor. * @param {array} countries - Array of actor countries. * @param {array} countriesCount - Array of frequencies for each country. * @param {array} motives - Array of employee numbers. * @param {array} motivesCount - Aray of frequencies for each employee count. * @param {array} varieties - Array of actor varieties. * @param {array} varietiesCount - Array of frequencies for each variety. */ constructor (type, countries, countriesCount, motives, motivesCount, varieties, varietiesCount) { /** * @property {array) type - Type of actor. */ this.type = type; /** * @property {object} countries - Data object storing country information. */ this.countries = { country: countries, count: countriesCount }; /** * @property {object} varieties - Data object storing country information. */ this.varieties = { variety: varieties, count: varietiesCount }; /** * @property {object} countries - Data object storing country information. */ this.motives = { motive: motives, count: motivesCount }; } //end of constructor //cascaded object create function for actorData (technically a factory) /** * Alternative copy constructor. * @function actorData#createactorData * @param {object} object - Contains actorData properties (countries, countriesCount, motive, motiveCount, variety, varietyCount). */ createActorData(object) { if(object.type==="actorData"){ return new actorData(object.type, object.countries, object.countriesCount, object.motive, object.motiveCount, object.variety, object.varietyCount); } else { //end of if //if type is not actorData, write error to console and return error for handling console.log("Error: Invalid Type"); return -1; } //end of else } //end of createactorData method /** * Returns a string representation of object. * @function actorData#toString * @returns String representation of class. */ toString() { return (JSON.stringify(this.object)); } } //end of actorDatas class
JavaScript
class RoadsignHintCard extends Component { @tracked showModal = false constructor() { super(...arguments); this.besluitUri = this.args.info.selectionContext.resource; this.editor = this.args.info.editor; this.location = this.args.info.location; } @action openRoadsignModal() { this.showModal = true; } @action closeRoadsignModal() { this.showModal = false; } @action async insertMaatregelenInArtikel( maatregelConcepten ){ const selection = this.editor.selectContext(this.location, { typeof: 'http://lblod.data.gift/vocabularies/editor/SnippetAttachment' }); const rdfa = await this.generateRdfa(selection, maatregelConcepten); this.editor.update(selection, { before : { innerHTML: rdfa, property: 'eli:has_part', typeof: 'besluit:Artikel', resource: `http://data.lblod.info/artikels/${v4()}` } }); // We want to keep the hint open, so no removal this.showModal = false; } async generateRdfa( selection, maatregelConcepten ){ const maatregelen = []; const triples = triplesInSelection(selection); for(const maatregelC of maatregelConcepten){ const verkeerstekenUri = this .findVerkeerstekenForVerkeersbordConcept( triples, maatregelC.verkeersbordconceptUris[0] ); //Assumes 1 bord ber maatregelC const maatregelUri = `http://data.lblod.info/mobiliteitsmaatregel/id/${v4()}`; maatregelen.push( ` <li property="mobiliteit:heeftMobiliteitsMaatregel" resource="${maatregelUri}" typeof="mobiliteit:Mobiliteitsmaatregel"> <span property="mobiliteit:wordtAangeduidDoor" resource=${verkeerstekenUri} typeof="mobiliteit:Verkeersbord-Verkeersteken"> <span property="mobiliteit:heeftVerkeersbordconcept" resource=${maatregelC.verkeersbordconceptUris[0]} typeof="mobiliteit:Verkeersbordconcept"> <img property="mobiliteit:grafischeWeergave" src="${(await loadVerkeersbordconcept(maatregelC.verkeersbordconceptUris[0])).grafischeWeergave}"/> </span> </span> <span property="lblodmow:heeftMaatregelconcept" resource=${maatregelC.uri} typeof=${maatregelC.type}> <span property="dct:description">${maatregelC.description}</span> </span> </li> ` ); } const artikel = ` <div property="eli:number" datatype="xsd:string"> Artikel <span class="mark-highlight-manual">nummer</span> </div> <span style="display:none;" property="eli:language" resource="http://publications.europa.eu/resource/authority/language/NLD" typeof="skos:Concept">&nbsp;</span> <div property="prov:value" datatype="xsd:string"> &nbsp; De verkeerssituatie zal worden gesignaleerd met de volgende maatregelen: <ul> ${maatregelen.join("\n")} </ul </div> `; return artikel; } findVerkeerstekenForVerkeersbordConcept( triples, verkeersbordConcept ){ return (triples.find(t => t.predicate === 'https://data.vlaanderen.be/ns/mobiliteit#heeftVerkeersbordconcept' && t.object === verkeersbordConcept ) || {}).subject; } }
JavaScript
class HasTerm extends Qualification { /** * Constructor */ constructor() { super(); this.setInput("taxonomy", null); this.setInput("matchTerm", null); this.setInput("field", "slug"); } /** * Evaluates if this qualification meets the correct criteria, which it does if the term exists. * * @param aData * The data that needs to meet the correct criteria. * * @return Boolean The result of the evalutation. */ qualify(aData) { //console.log("wprr/routing/qualification/wp/HasTerm::qualify"); //console.log(aData); let taxonomy = this.getInput("taxonomy"); let matchTerm = this.getInput("matchTerm"); let field = this.getInput("field"); let terms = Wprr.objectPath(aData, "post.linkedItem.postData.terms." + taxonomy); console.log(">>>>>", terms); if(!terms) { terms = Wprr.objectPath(aData, "queriedData.terms." + taxonomy); } if(terms) { let currentArray = terms; let currentArrayLength = currentArray.length; for(let i = 0; i < currentArrayLength; i++) { let currentTerm = currentArray[i]; if(currentTerm[field] === matchTerm) { return true; } } } return false; } /** * Creates a new instance of this class. * * @param aTaxonomy String The taxonomy to check in. * @param aMatchTerm * The value that the term should match. * @param aField String The field to check (eg. id, slug, name). * * @return HasTerm The new instance */ static create(aTaxonomy, aMatchTerm, aField = null) { let newHasTerm = new HasTerm(); newHasTerm.setInputWithoutNull("taxonomy", aTaxonomy); newHasTerm.setInputWithoutNull("matchTerm", aMatchTerm); newHasTerm.setInputWithoutNull("field", aField); return newHasTerm; } }
JavaScript
class SayAnything { move(me, other, log) { var names = me.board.remaining.map(function(who) { return who.name; }); names = names.filter(function(name) { return name != me.who.name; }); var index = parseInt(Math.random() * names.length); log('Choosing randomly: ' + names[index]); return names[index]; } }
JavaScript
class AppliedHighlightedFields { /** * Constructs a highlighted field map which consists of mappings from fields to highlighted * value strings. * * @param {Object<string, string|object|array>} data Keyed by fieldName. It may consist of nested fields * * Example object: * * { * description: 'likes <strong>apple</strong> pie and green <strong>apple</strong>s', * c_favoriteFruits: [ * { * apples: ['Granny Smith','Upton Pyne <strong>Apple</strong>'], * pears: ['Callery Pear'] * } * ] * } */ constructor (data = {}) { Object.assign(this, data); } /** * Constructs an AppliedHighlightedFields object from an answers-core HighlightedField * * @param {import('@yext/answers-core').HighlightedFields} highlightedFields * @returns {AppliedHighlightedFields} */ static fromCore (highlightedFields) { if (!highlightedFields || typeof highlightedFields !== 'object') { return {}; } const appliedHighlightedFields = this.computeHighlightedDataRecursively(highlightedFields); return new AppliedHighlightedFields(appliedHighlightedFields); } /** * Given an answers-core HighlightedFields tree, returns a new tree * with highlighting applied to the leaf nodes. * * @param {import('@yext/answers-core').HighlightedFields} highlightedFields * @returns {AppliedHighlightedFields} */ static computeHighlightedDataRecursively (highlightedFields) { if (this.isHighlightedFieldLeafNode(highlightedFields)) { const { value, matchedSubstrings } = highlightedFields; return new HighlightedValue().buildHighlightedValue(value, matchedSubstrings); } if (Array.isArray(highlightedFields)) { return highlightedFields.map( childFields => this.computeHighlightedDataRecursively(childFields)); } return Object.entries(highlightedFields) .reduce((computedFields, [fieldName, childFields]) => { computedFields[fieldName] = this.computeHighlightedDataRecursively(childFields); return computedFields; }, {}); } static isHighlightedFieldLeafNode ({ matchedSubstrings, value }) { return matchedSubstrings !== undefined && value !== undefined; } }
JavaScript
class Config { /** * @param {(string|object)} [jsonOrObject] - The contents of config.json, or a JavaScript object * exported from a .js config file. */ constructor(jsonOrObject) { if (typeof jsonOrObject === 'undefined') { jsonOrObject = {}; } if (typeof jsonOrObject === 'string') { jsonOrObject = JSON.parse( (stripJsonComments(stripBom.strip(jsonOrObject)) || '{}') ); } if (typeof jsonOrObject !== 'object') { jsonOrObject = {}; } this._config = mergeRecurse(defaults, jsonOrObject); } /** * Get the merged configuration values. */ get() { return this._config; } }
JavaScript
class PodJobDetails extends models['JobDetails'] { /** * Create a PodJobDetails. * @member {array} [copyProgress] Copy progress per account. */ constructor() { super(); } /** * Defines the metadata of PodJobDetails * * @returns {object} metadata of PodJobDetails * */ mapper() { return { required: false, serializedName: 'Pod', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'jobDetailsType', clientName: 'jobDetailsType' }, uberParent: 'JobDetails', className: 'PodJobDetails', modelProperties: { expectedDataSizeInTeraBytes: { required: false, serializedName: 'expectedDataSizeInTeraBytes', type: { name: 'Number' } }, jobStages: { required: false, serializedName: 'jobStages', type: { name: 'Sequence', element: { required: false, serializedName: 'JobStagesElementType', type: { name: 'Composite', className: 'JobStages' } } } }, contactDetails: { required: true, serializedName: 'contactDetails', type: { name: 'Composite', className: 'ContactDetails' } }, shippingAddress: { required: true, serializedName: 'shippingAddress', type: { name: 'Composite', className: 'ShippingAddress' } }, errorDetails: { required: false, serializedName: 'errorDetails', type: { name: 'Sequence', element: { required: false, serializedName: 'JobErrorDetailsElementType', type: { name: 'Composite', className: 'JobErrorDetails' } } } }, jobDetailsType: { required: true, serializedName: 'jobDetailsType', isPolymorphicDiscriminator: true, type: { name: 'String' } }, copyProgress: { required: false, serializedName: 'copyProgress', type: { name: 'Sequence', element: { required: false, serializedName: 'CopyProgressElementType', type: { name: 'Composite', className: 'CopyProgress' } } } } } } }; } }
JavaScript
class Controller { /** * Constructor. * @param {!angular.Scope} $scope * @param {!angular.JQLite} $element * @param {!angular.$compile} $compile * @ngInject */ constructor($scope, $element, $compile) { /** * @type {?angular.Scope} * @protected */ this.scope = $scope; /** * @type {?angular.JQLite} * @private */ this.element_ = $element; /** * @type {?angular.$compile} * @private */ this.compile_ = $compile; /** * @type {?string} * @protected */ this.id = null; /** * @type {!Array<!ListEntry>} * @protected */ this.items = []; /** * @type {string} * @protected */ this.prefix = ''; /** * @type {string} * @protected */ this.suffix = ''; getDispatcher().listen(GoogEventType.PROPERTYCHANGE, this.onChange, false, this); $scope.$on('$destroy', this.onDestroy_.bind(this)); } /** * Cleanup * * @private */ onDestroy_() { getDispatcher().unlisten(GoogEventType.PROPERTYCHANGE, this.onChange, false, this); this.scope = null; this.element_ = null; this.compile_ = null; // Prevent element leaks when destroying lists by cleaning up the items. // Keep around the items so when the list is displayed again it recompiles the items this.items.forEach(function(item) { item.element = undefined; }); } /** * Handles list change * * @param {PropertyChangeEvent} evt The list change event * @protected */ onChange(evt) { var oldItem = evt.getOldValue(); var newItem = evt.getNewValue(); if (evt.getProperty() === this.id) { if (oldItem && !newItem) { removeNode(oldItem.element[0]); this.scope.$emit(ListEventType.CHANGE); } else { this.update_(); } } } /** * Updates the displayed UI * * @private */ update_() { // Always attempt to get the updated list of items, or use the scope list of items if it doesnt exist var items = get(this.id || '') || this.items; var prefix = this.prefix || ''; var suffix = this.suffix || ''; if (this.scope && items) { for (var i = 0, n = items.length; i < n; i++) { var item = items[i]; if (!item.element) { var dir = item.markup; if (dir.indexOf('<') === -1) { dir = '<' + dir + '></' + dir + '>'; } var html = prefix + dir + suffix; var elScope = this.scope.$new(); item.element = this.compile_(html)(elScope); item.scope = elScope; // Assumption: existing items will not change in priority. If they do, they must be removed and added again. if (i === 0) { // Insert as the first child. this.element_.prepend(item.element); } else { // Insert after the previous item's element. This takes the extra precaution to insert after the last element, // in case the previous markup produced multiple elements. const previous = items[i - 1].element; item.element.insertAfter(previous[previous.length - 1]); } } } this.scope.$emit(ListEventType.CHANGE); } } }
JavaScript
class SniperCode_FsCliPackage { Color = Color Inquirer = Inquirer; program = program; Option = Option; File_System = File_System; fs = fs; path = path; UcFirst = UcFirst; shell_command = shell_command; scan_dir_recursive_depth = scan_dir_recursive_depth; }
JavaScript
class Node{ constructor(){ this.children = []; this.parent = null; } add(thing){ //chainable so you can a.add(b).add(c) to make a->b->c this.children.push(thing); thing.parent = this; if(thing._onAdd)thing._onAdd(); return thing; } _onAdd(){} remove(thing){ var index = this.children.indexOf( thing ); if ( index !== - 1 ) { thing.parent = null; this.children.splice( index, 1 ); } return this; } getTopParent(){ //find the parent of the parent of the... until there's no more parents. const MAX_CHAIN = 100; let parentCount = 0; let root = this; while(root !== null && root.parent !== null && parentCount < MAX_CHAIN){ root = root.parent; parentCount+= 1; } if(parentCount >= MAX_CHAIN)throw new Error("Unable to find top-level parent!"); return root; } getDeepestChildren(){ //find all leaf nodes from this node //this algorithm can probably be improved if(this.children.length == 0)return [this]; let children = []; for(let i=0;i<this.children.length;i++){ let childsChildren = this.children[i].getDeepestChildren(); for(let j=0;j<childsChildren.length;j++){ children.push(childsChildren[j]); } } return children; } getClosestDomain(){ /* Find the DomainNode that this Node is being called from. Traverse the chain of parents upwards until we find a DomainNode, at which point we return it. This allows an output to resize an array to match a domainNode's numCallsPerActivation, for example. Note that this returns the MOST RECENT DomainNode ancestor - it's assumed that domainnodes overwrite one another. */ const MAX_CHAIN = 100; let parentCount = 0; let root = this.parent; //start one level up in case this is a DomainNode already. we don't want that while(root !== null && root.parent !== null && !root.isDomainNode && parentCount < MAX_CHAIN){ root = root.parent; parentCount+= 1; } if(parentCount >= MAX_CHAIN)throw new Error("Unable to find parent!"); if(root === null || !root.isDomainNode)throw new Error("No DomainNode parent found!"); return root; } onAfterActivation(){ // do nothing //but call all children for(var i=0;i<this.children.length;i++){ this.children[i].onAfterActivation(); } } }
JavaScript
class Transformation extends Node{ constructor(options){ super(); EXP.Utils.assertPropExists(options, "expr"); // a function that returns a multidimensional array EXP.Utils.assertType(options.expr, Function); this.expr = options.expr; } evaluateSelf(...coordinates){ //evaluate this Transformation's _expr, and broadcast the result to all children. let result = this.expr(...coordinates); if(result.constructor !== Array)result = [result]; for(var i=0;i<this.children.length;i++){ this.children[i].evaluateSelf(coordinates[0],coordinates[1], ...result); } } clone(){ let thisExpr = this.expr; let clone = new Transformation({expr: thisExpr.bind()}); for(var i=0;i<this.children.length;i++){ clone.add(this.children[i].clone()); } return clone; } makeLink(){ //like a clone, but will use the same expr as this Transformation. //useful if there's a specific function that needs to be used by a bunch of objects return new LinkedTransformation(this); } }
JavaScript
class VectorOutput extends LineOutput{ constructor(options = {}){ /* width: number. units are in screenY/400. opacity: number color: hex code or THREE.Color() lineJoin: "bevel" or "round". default: round. Don't change this after initialization. */ super(options); } init(){ this.arrowMaterial = new THREE.LineBasicMaterial({color: this._color, linewidth: this._width, opacity:this._opacity}); super.init(); this.arrowheads = []; //TODO: make the arrow tip colors match the colors of the lines' tips const circleResolution = 12; const arrowheadSize = 0.3; const EPSILON = 0.00001; this.EPSILON = EPSILON; this.coneGeometry = new THREE.CylinderBufferGeometry( 0, arrowheadSize, arrowheadSize*1.7, circleResolution, 1 ); let arrowheadOvershootFactor = 0.1; //used so that the line won't rudely clip through the point of the arrowhead this.coneGeometry.translate( 0, - arrowheadSize + arrowheadOvershootFactor, 0 ); this._coneUpDirection = new THREE.Vector3(0,1,0); } _onFirstActivation(){ super._onFirstActivation(); if(this.itemDimensions.length > 1){ this.numArrowheads = this.itemDimensions.slice(0,this.itemDimensions.length-1).reduce(function(prev, current){ return current + prev; }); }else{ //assumed itemDimensions isn't a nonzero array. That should be the constructor's problem. this.numArrowheads = 1; } //remove any previous arrowheads for(var i=0;i<this.arrowheads.length;i++){ let arrow = this.arrowheads[i]; exports.threeEnvironment.scene.remove(arrow); } this.arrowheads = new Array(this.numArrowheads); for(var i=0;i<this.numArrowheads;i++){ this.arrowheads[i] = new THREE.Mesh(this.coneGeometry, this.arrowMaterial); this.mesh.add(this.arrowheads[i]); } console.log("number of arrowheads (= number of lines):"+ this.numArrowheads); } evaluateSelf(i, t, x, y, z){ //it's assumed i will go from 0 to this.numCallsPerActivation, since this should only be called from an Area. super.evaluateSelf(i,t,x,y,z); const lastDimensionLength = this.itemDimensions[this.itemDimensions.length-1]; let firstCoordinate = i % lastDimensionLength; let endingNewLine = firstCoordinate == lastDimensionLength-1; if(endingNewLine){ //we need to update arrows //calculate direction of last line segment //this point is currentPointIndex-1 because currentPointIndex was increased by 1 during super.evaluateSelf() let index = (this._currentPointIndex-1)*this._outputDimensions*4; let prevX = this._vertices[(this._currentPointIndex-2)*this._outputDimensions*4]; let prevY = this._vertices[(this._currentPointIndex-2)*this._outputDimensions*4+1]; let prevZ = this._vertices[(this._currentPointIndex-2)*this._outputDimensions*4+2]; let dx = prevX - this._vertices[index]; let dy = prevY - this._vertices[index+1]; let dz = prevZ - this._vertices[index+2]; let lineNumber = Math.floor(i / lastDimensionLength); Utils$1.assert(lineNumber <= this.numArrowheads); //this may be wrong let directionVector = new THREE.Vector3(-dx,-dy,-dz); //Make arrows disappear if the line is small enough //One way to do this would be to sum the distances of all line segments. I'm cheating here and just measuring the distance of the last vector, then multiplying by the number of line segments (naively assuming all line segments are the same length) let length = directionVector.length() * (lastDimensionLength-1); const effectiveDistance = 3; let clampedLength = Math.max(0, Math.min(length/effectiveDistance, 1)); //shrink function designed to have a steep slope close to 0 but mellow out at 0.5 or so in order to avoid the line width overcoming the arrowhead width //In Chrome, three.js complains whenever something is set to 0 scale. Adding an epsilon term is unfortunate but necessary to avoid console spam. this.arrowheads[lineNumber].scale.setScalar(Math.acos(1-2*clampedLength)/Math.PI + this.EPSILON); //position/rotation comes after since .normalize() modifies directionVector in place let pos = this.arrowheads[lineNumber].position; pos.x = x === undefined ? 0 : x; pos.y = y === undefined ? 0 : y; pos.z = z === undefined ? 0 : z; if(length > 0){ //directionVector.normalize() fails with 0 length this.arrowheads[lineNumber].quaternion.setFromUnitVectors(this._coneUpDirection, directionVector.normalize() ); } } } set color(color){ //currently only a single color is supported. //I should really make it possible to specify color by a function. this._color = color; this.setAllVerticesToColor(color); this.arrowMaterial.color = new THREE.Color(this._color); } get color(){ return this._color; } set opacity(opacity){ this.arrowMaterial.opacity = opacity; this.arrowMaterial.transparent = opacity < 1; this.material.transparent = opacity < 1 || this.lineJoinType == "ROUND"; this.arrowMaterial.visible = opacity > 0; //mesh is always transparent this.material.opacity = opacity; this.material.visible = opacity > 0; this._opacity = opacity; this._uniforms.opacity.value = opacity; } get opacity(){ return this._opacity; } removeSelfFromScene(){ exports.threeEnvironment.scene.remove(this.mesh); for(var i=0;i<this.numArrowheads;i++){ exports.threeEnvironment.scene.remove(this.arrowheads[i]); } } clone(){ return new VectorOutput({width: this.width, color: this.color, opacity: this.opacity,lineJoinType: this.lineJoinType}); } }
JavaScript
class UndoItem{ constructor(target, toValues, fromValues, duration, optionalArguments){ this.target = target; this.toValues = toValues; this.fromValues = fromValues; this.duration = duration; this.type = TRANSITIONTO; this.optionalArguments = optionalArguments; } }
JavaScript
class MockGameObject extends GameObject { #position_ = null; #rotation_ = null; // Overridden to avoid creating a real object on the server. createInternal(options) { this.#position_ = options.position; this.#rotation_ = options.rotation; return ++globalMockObjectId; } // Overridden to avoid destroying a real object on the server. destroyInternal() {} // --------------------------------------------------------------------------------------------- get position() { return this.#position_; } set position(value) { this.#position_ = value; } get rotation() { return this.#rotation_; } set rotation(value) { this.#rotation_ = value; } // --------------------------------------------------------------------------------------------- attachToVehicle(vehicle, offset, rotation) {} // --------------------------------------------------------------------------------------------- setMaterial(index, modelId, txdName, textureName, color) {} // --------------------------------------------------------------------------------------------- async moveToInternal(position, speed) {} async editInternal(player) {} }
JavaScript
class SearchQuery extends Listing { static endpoint = SearchEndpoint; static fetch(apiOptions, queryOrOptions, options={}) { if (typeof queryOrOptions === 'string') { options.q = queryOrOptions; } else { options = { ...options, ...queryOrOptions }; } return super.fetch(apiOptions, options); } static fetchPostsAndComments(apiOptions, queryOrOptions, options={}) { options = { ...options, include_facets: 'off', type: [ 'sr', 'link' ], sort: 'relevance', t: 'all', }; return this.fetch(apiOptions, queryOrOptions, options); } static fetchPosts(apiOptions, queryOrOptions, options={}) { options = { ...options, include_facets: 'off', type: [ 'link' ], sort: 'relevance', t: 'all', }; return this.fetch(apiOptions, queryOrOptions, options); } static fetchSubreddits(apiOptions, queryOrOptions, options={}) { options = { ...options, include_facets: 'off', type: [ 'sr' ], sort: 'relevance', t: 'all', }; return this.fetch(apiOptions, queryOrOptions, options); } expectedNumberOfPosts(query) { return (query.limit || 25) - RESERVED_FOR_SUBBREDITS; } get afterId() { return withQueryAndResult(this.apiResponse, (query, results) => { const limit = this.expectedNumberOfPosts(query); const posts = results.filter(record => record.type === POST); return posts.length >= limit ? last(posts).uuid : null; }); } get posts() { return this.apiResponse.results .filter(record => record.type === POST) .map(this.apiResponse.getModelFromRecord); } get subreddits() { return this.apiResponse.results .filter(record => record.type === SUBREDDIT) .map(this.apiResponse.getModelFromRecord); } }
JavaScript
class Transaction{ constructor(fromAddress, toAddress, amount){ this.fromAddress = fromAddress; this.toAddress = toAddress; this.amount = amount; } }
JavaScript
class Block{ constructor(timestamp, transactions, previousHash = ''){ this.timestamp = timestamp; this.transactions = transactions; this.previousHash = previousHash; this.hash = this.calculateHash(); this.nonce = 0; } calculateHash(){ return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString(); } mineBlock(difficulty){ while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")){ this.nonce++; this.hash = this.calculateHash(); } console.log("Block mined: " + this.hash); } }
JavaScript
class Blockchain { constructor(){ this.chain = [this.createGenesisBlock()]; this.difficulty = 2; this.pendingTransactions = []; this.miningReward = 100; } createGenesisBlock(){ return new Block("01/01/2017", "Genesis Block", "0"); } getLatestBlock(){ return this.chain[this.chain.length - 1]; } //we no long need the addBlock method we will //replace this now with the a method to //mine pending transactions // addBlock(newBlock){ // newBlock.previousHash = this.getLatestBlock().hash; // newBlock.mineBlock(this.difficulty); // this.chain.push(newBlock); // } minePendingTransactions(miningRewardAddress){ let block = new Block(Date.now(), this.pendingTransactions); //real world crypto currencies it is not possible to //add all pending transactions to an array //because there is simply WAY TOO MANY transactions //going on. //instead miners get to choose which transactions //to include and which they dont. //Miners pick their transactions to include //now we mine the block with the difficulty block.mineBlock(this.difficulty); //now reset pending transactions area and //create a new transaction to give the miner //his/her reward this.pendingTransactions = [ new Transaction(null, miningRewardAddress, this.miningReward) ]; console.log('Block successfully mined'); this.chain.push(block); } //add a way to push the transaction to the pending //transactions createTransaction(transaction){ this.pendingTransactions.push(transaction); } getBalanceOfAddress(address){ let balance = 0; //loop over all blocks in our blockchain for(const block of this.chain){ for (const trans of block.transactions){ //if you are the from address you would be //decreasing your balance //if you are the to address you would be //increasing your balance if(trans.fromAddress === address){ balance -= trans.amount; } if (trans.toAddress === address){ balance += trans.amount; } } } return balance; } isChainValid(){ for(let i = 1; i < this.chain.length; i++){ const currentBlock = this.chain[i]; const previousBlock = this.chain[i - 1]; if (currentBlock.hash !== currentBlock.calculateHash()){ return false; } if(currentBlock.previousHash !== previousBlock.hash){ return false; } } return true; } }
JavaScript
class ChunkNameCache { chunks = {} chunkNames = new Set() get(source) { if (this.chunks[source]) { return this.chunks[source] } let name = getShortChunkName(source) const originalName = name let i = 0 // eslint-disable-next-line no-constant-condition while (true) { if (this.chunkNames.has(name)) { // if this chunk name is already in use by a different source then we // append a unique ID to it name = `${originalName}.${i}` i++ } else { break } } this.chunkNames.add(name) this.chunks[source] = name return name } }
JavaScript
class RangeChart extends LitElement { static get properties() { return { /** * The name to say "Hello" to. */ ID: {type: String}, }; } constructor() { super(); this.name = ; } render() { return html``; } }
JavaScript
class Duration{ constructor({ type = 4, dot = 0 } = {}) { extend(this, { type, dot }) } /** * Type of duration. * @constant * @default duration */ $type = 'duration' /** * Def id used in the SVG <defs> element. * ``` * defId := 'd' type dot * ``` * *E.g.* * ``` * Note defId * ---------------- * 1. d41 * 1_ d80 * 1= d160 * 1-.. d22 * ``` * @type {string} * @readonly */ get defId() { return `d${this.type}${this.dot}` } /** * `(Getter)` Duration measured in quarter note. * @type {number} */ get quarter() { const d = 4 / this.type return this.dot === 0 ? d : this.dot === 1 ? d * 1.5 : d * 1.75 } /** * `(Getter)` Duration in second * Affected by the tempo. * @type {number} * @readonly */ get second() { return this.quarter * 60 / 80 // / TEMPO; } /** * `(Getter)` Number of underbars in the beam. * @type {number} * @readonly */ get underbar() { return TYPE_TO_UNDERBAR[this.type] || 0 } /** * @return {string} */ toString() { return TYPE_TO_STRING[this.type] + DOT_TO_STRING[this.dot] } /** * [toJSON description] * @return {Object} */ toJSON = makeToJSON({ type: 4, dot: 0 }) }
JavaScript
class Repulsion extends Attraction { /** * Constructs an Repulsion behaviour instance. * * @param {Vector3D} targetPosition - The position the particles will be repelled from * @param {number} force - The repulsion force scalar multiplier * @param {number} radius - The repulsion radius * @param {number} life - The life of the particle * @param {function} easing - The behaviour's decaying trend * @return void */ constructor(targetPosition, force, radius, life, easing, isEnabled = true) { super(targetPosition, force, radius, life, easing, isEnabled); /** * @desc Repulsion is attraction with negative force. * @type {number} */ this.force *= -1; /** * @desc The class type. * @type {string} */ this.type = type; } /** * Resets the behaviour properties. * * @param {Vector3D} targetPosition - the position the particles will be attracted to * @param {number} force - the attraction force multiplier * @param {number} radius - the attraction radius * @param {number} life - the life of the particle * @param {function} easing - The behaviour's decaying trend * @return void */ reset(targetPosition, force, radius, life, easing) { super.reset(targetPosition, force, radius, life, easing); this.force *= -1; } /** * Creates a Body initializer from JSON. * * @param {object} json - The JSON to construct the instance from. * @property {number} json.x - The target position x value * @property {number} json.y - The target position y value * @property {number} json.z - The target position z value * @property {number} json.force - The attraction force scalar multiplier * @property {number} json.life - The life of the particle * @property {string} json.easing - The behaviour's decaying trend * @return {Body} */ static fromJSON(json) { const { x, y, z, force, radius, life, easing, isEnabled = true } = json; return new Repulsion( new Vector3D(x, y, z), force, radius, life, getEasingByName(easing), isEnabled ); } }
JavaScript
class SubLayer extends React.Component { componentWillMount() { this.yPos = new Animated.Value(-this.props.offset); this.startLoop(this.yPos, () => { this.yPos.setValue(0); }); } startLoop(yPos, fn) { Animated.timing(yPos, { toValue: -this.props.height, duration: this.props.speed, easing: Easing.linear, useNativeDriver: true, }).start((animation) => { if (animation.finished && fn) { fn(); this.startLoop(yPos, fn); } }) } render() { return ( <View> <Animated.View style={[ styles.container, { transform: [{ translateY: this.yPos }] } ]}> <ParallelPaths width={this.props.width} height={this.props.height} color={this.props.color} /> </Animated.View> <Animated.View style={[ styles.container, { top: this.props.height }, { transform: [{ translateY: this.yPos }] } ]}> <ParallelPaths width={this.props.width} height={this.props.height} color={this.props.color} /> </Animated.View> </View> ); } }
JavaScript
class IdentityAttributeEnum extends AbstractEnum { static getNiceLabel(key) { return super.getNiceLabel(`core:enums.IdentityAttributeEnum.${key}`); } static getHelpBlockLabel(key) { return super.getNiceLabel(`core:enums.IdentityAttributeEnum.helpBlock.${key}`); } static findKeyBySymbol(sym) { return super.findKeyBySymbol(this, sym); } static findSymbolByKey(key) { return super.findSymbolByKey(this, key); } static getField(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { case this.USERNAME: { return 'username'; } case this.EXTERNAL_CODE: { return 'externalCode'; } case this.DISABLED: { return 'disabled'; } case this.FIRSTNAME: { return 'firstName'; } case this.LASTNAME: { return 'lastName'; } case this.EMAIL: { return 'email'; } case this.PHONE: { return 'phone'; } case this.TITLE_BEFORE: { return 'titleBefore'; } case this.TITLE_AFTER: { return 'titleAfter'; } case this.DESCRIPTION: { return 'description'; } case this.ASSIGNED_ROLES: { return 'assignedRoles'; } case this.ASSIGNED_ROLES_FOR_SYSTEM: { return 'assignedRolesForSystem'; } case this.FORM_PROJECTION: { return 'formProjection'; } case this.STATE: { return 'state'; } default: { return null; } } } static getEnum(field) { if (!field) { return null; } switch (field) { case 'username': { return this.USERNAME; } case 'externalCode': { return this.EXTERNAL_CODE; } case 'disabled': { return this.DISABLED; } case 'firstName': { return this.FIRSTNAME; } case 'lastName': { return this.LASTNAME; } case 'email': { return this.EMAIL; } case 'phone': { return this.PHONE; } case 'titleBefore': { return this.TITLE_BEFORE; } case 'titleAfter': { return this.TITLE_AFTER; } case 'description': { return this.DESCRIPTION; } case 'assignedRoles': { return this.ASSIGNED_ROLES; } case 'assignedRolesForSystem': { return this.ASSIGNED_ROLES_FOR_SYSTEM; } case 'formProjection': { return this.FORM_PROJECTION; } case 'state': { return this.STATE; } default: { return null; } } } static getLevel(key) { if (!key) { return null; } const sym = super.findSymbolByKey(this, key); switch (sym) { default: { return 'default'; } } } }
JavaScript
class FsClient { constructor (ctx, zones) { ow(zones, ow.array.label('zones')) this.paths = ctx.get('paths') this.markdownOptions = ctx.get('markdownOptions') this.versions = [] this.markdownExtensions = ['.md', '.markdown', '.mkd', '.mkdown'] this.watcher = null zones.forEach((zone) => (zone.versions.forEach((version) => (this.addVersion(zone.slug, version))))) } /** * Returns a boolean telling if file should be processed * as a markup file or not * * @method _useFile * * @param {String} item * * @return {Boolean} * * @private */ _useFile (item) { if (item.stats.isDirectory()) { return false } if (basename(item.path).startsWith('_')) { return false } const extension = extname(item.path) return this.markdownExtensions.indexOf(extension) > -1 } /** * Returns a tree of markdown files for a given version * * @method _versionTree * * @param {Object} version * * @return {Promise<Object>} * * @private */ _versionTree (version) { return new Promise((resolve, reject) => { const filesTree = [] fs .exists(version.absPath) .then((exists) => { if (!exists) { throw new Error(`Directory ${version.location} referenced by ${version.no} doesn't exists`) } klaw(version.absPath) .on('data', (item) => { if (this._useFile(item)) { filesTree.push(item.path) } }) .on('end', () => { version.scanned = true resolve({ filesTree, version }) }) .on('error', reject) }) .catch(reject) }) } /** * Converts the file tree of a version to it's contents tree * * @method _versionContentTree * * @param {Object} options.version * @param {Array} options.filesTree * * @return {Object} * * @private */ async _versionContentTree ({ version, filesTree }) { const treeInstance = new Tree(version.absPath, filesTree, this.markdownOptions) const tree = await treeInstance.process() return { version, tree } } /** * Returns a boolean telling watcher whether to ignore * the event or not * * @method _ignoreEvent * * @param {String} event * @param {String} path * * @return {Boolean} * * @private */ _ignoreEvent (event, path) { if (event === 'unlinkDir') { return false } /** * Ignore when file is not markdown or is a draft */ if (!this._useFile({ stats: { isDirectory () { return false } }, path: path })) { return true } /** * Finally ignore when event is not in one of the following events */ return ['add', 'change', 'unlink'].indexOf(event) === -1 } /** * Returns the data for the event * * @method _getEventData * * @param {String} event * @param {String} path * * @return {String|Dfile} * * @private */ async _getEventData (event, path) { path = normalize(path) /** * Directory was removed. If directory is the base path * to a version, then we will emit `unlink:version` * event. */ if (event === 'unlinkDir') { const versions = this._getVersionsForPath(path) if (versions.length) { versions.forEach((version) => (this.unwatchVersion(version.zoneSlug, version))) return { event: 'unlink:version', data: versions } } } /** * If event is unlink, then we should look for that * path version and return the `version` along * with file baseName */ if (event === 'unlink') { const versions = this._getFileVersions(path) if (!versions.length) { throw new Error(`${path} file is not part of version tree`) } return { event: 'unlink:doc', data: { versions, baseName: path.replace(`${versions[0].absPath}${sep}`, '') } } } /** * If file is changed, then look for the file version and * return the dFile instance. */ if (['add', 'change'].indexOf(event) > -1) { const versions = this._getFileVersions(path) if (!versions.length) { throw new Error(`${path} file is not part of version tree`) } const file = new Dfile(path, versions[0].absPath, this.markdownOptions) await file.parse() return { event: `${event}:doc`, data: { versions, file } } } /** * We shouldn't reach here, if we do then return the * data as it is */ return { event, data: path } } /** * Returns the version for a given changed file. Chances are * this can be undefined * * @method _getFileVersions * * @param {String} location * * @return {Object|Undefined} * * @private */ _getFileVersions (location) { return this.versions.filter((version) => location.startsWith(`${version.absPath}${sep}`)) } /** * Returns the versions if their absPath are same as the location * * @method _getVersionsForPath * * @param {String} location * * @return {Array|Undefined} */ _getVersionsForPath (location) { return this.versions.filter((version) => location === version.absPath) } /** * Add version to the versions list. Also adds `absPath` * to the version node. * * @method addVersion * * @param {String} zoneSlug * @param {Object} version * * @return {Object} */ addVersion (zoneSlug, version) { ow(zoneSlug, ow.string.label('zoneSlug').nonEmpty) ow(version, ow.object.label('version').hasKeys('no', 'location')) ow(version.no, ow.string.label('version.no').nonEmpty) ow(version.location, ow.string.label('version.location').nonEmpty) const location = this.paths.versionDocsPath(version.location) version = Object.assign({ absPath: location, scanned: false, zoneSlug }, version) const existingVersion = this.versions.find((v) => v.no === version.no && v.zoneSlug === zoneSlug) if (!existingVersion) { this.versions.push(version) } else { Object.assign(existingVersion, version) } return version } /** * Generate a files tree for all the versions * * @method filesTree * * @return {Array} */ filesTree () { return Promise.all(this.versions.filter(({ scanned }) => !scanned).map(this._versionTree.bind(this))) } /** * Generates a content tree for all the versions * * @method tree * * @return {Array} */ async tree () { const filesTree = await this.filesTree() const output = await Promise.all(filesTree.map(this._versionContentTree.bind(this))) output.toJSON = function () { return this.map((node) => node.toJSON()) } return output } /** * Stop watching a given version * * @method unwatchVersion * * @param {String} zoneSlug * @param {String} location * * @return {void} */ unwatchVersion (zoneSlug, version) { ow(zoneSlug, ow.string.label('zoneSlug').nonEmpty) ow(version.no, ow.string.label('version.no').nonEmpty) if (!this.watcher) { throw new Error('make sure to start the watcher before calling unwatchVersion') } const versionIndex = this.versions.findIndex((v) => v.no === version.no && v.zoneSlug === zoneSlug) const sharedLocation = !!this.versions.find((v) => { return v.location === version.location && (v.no !== version.no || v.zoneSlug !== zoneSlug) }) /** * Return when version not found */ if (versionIndex === -1) { return } const [ removedVersion ] = this.versions.splice(versionIndex, 1) /** * Return if remvoed version location is shared with some * other version. We don't want to unwatch it. */ if (sharedLocation) { return } debug('attempt to unwatch location %s', removedVersion.absPath) this.watcher.unwatch(removedVersion.absPath) } /** * Start watching a new version after the watcher has started * * @method watchVersion * * @param {String} zoneSlug * @param {Object} version * * @return {void} */ watchVersion (zoneSlug, version) { ow(zoneSlug, ow.string.label('zoneSlug').nonEmpty) ow(version, ow.object.label('version').hasKeys('no', 'location')) ow(version.location, ow.string.label('version.location').nonEmpty) ow(version.no, ow.string.label('version.no').nonEmpty) if (!this.watcher) { throw new Error('make sure to start the watcher before calling watchVersion') } const addedVersion = this.addVersion(zoneSlug, version) this.watcher.watch(addedVersion.absPath) } /** * Watch for file changes. The callback will be invoked for following events * and receives different arguments based on the type of event. * * | event | args | * |---------|-----------| * | add | dFile | * | remove | filePath | * | change | dFile | * * @method watch * * @param {Function} onChange * * @return {void} */ watch (onChange) { ow(onChange, ow.function) const locations = this.versions.map(({ absPath }) => absPath) if (!this.watcher) { this.watcher = new Watcher(this.paths.configFile(), locations, { onChange, ignoreEvent: this._ignoreEvent.bind(this), getEventData: this._getEventData.bind(this) }) } this.watcher.hook() } }
JavaScript
class ColumnNullChecker { constructor(column) { this.column = column } enforceNotNull() { if (this.column == null) { throw 'Invalid column' } if (this.column.Fields == null) { throw 'Invalid column' } } }
JavaScript
class FieldColumnFactory { constructor() { } /** * setParam * @param {*} index index of the column * @param {*} column column name of the column * @param {*} callback callback of the column */ setParam(index, column, callback) { this.column = column } /** * create a column template */ createColumn() { let field = this.column let currentWidth = field.Width == null ? 120 : field.Width; let columnTemplate = { field: field.Name, headerText: field.Header, width: currentWidth, type: field.DataType, editType: field.DataType } return columnTemplate } }
JavaScript
class StandardColumnFactory { constructor() { } /** * CSet the parameters of the column * @param {*} index index - no used * @param {*} column column description to be used * @param {*} callback callback not used */ setParam(index, column, callback) { this.column = column this.checker = new ColumnNullChecker(column) } /** * create a column */ createColumn() { this.checker.enforceNotNull() if (this.column.Fields.length > 0) { let field = this.column.Fields[0] let currentWidth = field.Width == null ? 120 : field.Width; let columnTemplate = { field: field.Name, headerText: this.column.headerText, width: currentWidth, type: field.DataType, editType: field.DataType } return columnTemplate } return null; } }
JavaScript
class CheckBoxColumnFactory { constructor() { } /** * Set a parameters * @param {*} index Index to be used * @param {*} column Column to be used * @param {*} callback Callback */ setParam(index, column, callback) { this.index = index this.column = column this.callback = callback this.checker = new ColumnNullChecker(column) } /** * createColumn */ createColumn() { this.checker.enforceNotNull() if ((this.column.Fields.length) > 0) { let field = this.column.Fields[0] let columnTemplate = { field: field.Name, headerText: this.column.Header, allowEditing: true, type: "boolean", editType: "booleanedit", displayAsCheckBox: "true" } return columnTemplate; } } }
JavaScript
class SelectionColumnFactory { constructor() { } /** * Set parameters * @param {*} index index to be used * @param {*} column column to be used * @param {*} callback callback to be used */ setParam(index, column, callback) { this.index = index this.checker = new ColumnNullChecker(column) this.column = column this.callback = callback } /** * createColumn */ createColumn() { this.checker.enforceNotNull() if (this.column.Fields.length > 0) { let field = this.column.Fields[0] let currentWidth = field.Width == null ? 120 : field.Width; let columnTemplate = { field: field.Name, headerText: this.column.Header, width: currentWidth, type: field.DataType, editType: field.DataType } let cacheValue = { index: idx, func: this.selectionTemplate, args: this.column.Fields[0].SelectionValues } if (callback != null) { this.callback(cacheValue) } return columnTemplate } } }
JavaScript
class CodeNameColumnFactory { constructor() { } /** * setParameters. * @param {*} index index to be used * @param {*} column column to be used * @param {*} callback calback to be used after column creation */ setParam(index, column, callback) { this.index = index this.column = column this.callback = callback this.checker = new ColumnNullChecker(column) } /** * create a column to be used * @todo localize the header text */ createColumn() { this.checker.enforceNotNull() if (this.column.Fields.length > 0) { let field = this.column.Fields[0] let currentWidth = field.Width == null ? 120 : field.Width; let columnTemplate = { field: field.Name, headerText: this.column.headerText, width: currentWidth, type: field.DataType, editType: field.DataType } return columnTemplate } let columns = [] if (this.column.Fields.length > 0) { // create fields. this.column.Fields.forEach(field => { let currentWidth = field.Width == null ? 120 : field.Width; let fieldColumn = { field: field.Name, headerText: field.Header, width: currentWidth, allowEditing: true, type: field.DataType, editType: field.DataType } columns.push(fieldColumn); }) let columnTemplate = { headerText: "Busca", allowEditing: false } columns.push(columnTemplate) let cacheValue = { index: idx - 1, args: this.column, modalState: false, modalTitle: this.column.ModalTitle } this.callback(cacheValue) return columns } } }
JavaScript
class AbstractColumnFactory { /** * @param index index to be used * @param column column description * @param callback to be used. */ constructor() { this.dispatcher = { 'Standard': new StandardColumnFactory(), 'Checkbox': new CheckBoxColumnFactory(), 'Selection': new SelectionColumnFactory(), 'CodeName': new CodeNameColumnFactory(), /* Just used in codename */ 'Field': new FieldColumnFactory() /* Just used in the modals*/ } } /** * create a column given a type * @param {*} columnType Column type to be used. * @param {*} index Index to be used. * @param {*} column Column to be used. * @param {*} callback Callback to be used */ createColumn(columnType, index, column, callback) { if (columnType == null) { throw 'Null argument exception' } if ((columnType != 'Standard') && (columnType != 'Checkbox') && (columnType != 'Selection') && (columnType != 'Field') && (columnType != 'CodeName')) { throw 'Invalid column type' } this.dispatcher[columnType].setParam(index,column, callback) return this.dispatcher[columnType].createColumn() } }
JavaScript
class ImpressumMenuItem { constructor(menu) { this.menu = menu } init() { this.menu.navItems.push({ id: "impressum", title: gettext('Impressum'), url: "/pages/impressum/", text: 'Impressum', order: 10 }) } }
JavaScript
class Container { constructor(id, name, rb) { this.rb = rb; this.id = id; this.panelItem = null; this.name = name; this.el = null; this.elContent = null; this.owner = null; this.level = 0; // number of containers "above" this.parent = null; // parent container } init(owner) { this.owner = owner; this.el = owner.getElement(); this.elContent = owner.getContentElement(); this.panelItem = owner.getPanelItem(); this.parent = owner.getContainer(); this.level = 0; let parent = this.parent; while (parent !== null) { this.level++; parent = parent.getParent(); } } /** * Called after initialization is finished. */ setup() { } remove() { } appendElement(el) { if (this.elContent !== null) { this.elContent.append(el); } } getId() { return this.id; } getName() { return this.name; } getPanelItem() { return this.panelItem; } setPanelItem(panelItem) { this.panelItem = panelItem; } getLevel() { return this.level; } getParent() { return this.parent; } setParent(parent) { this.parent = parent; this.level = 0; while (parent !== null) { this.level++; parent = parent.getParent(); } } isSelected() { if (this.owner !== null && this.rb.isSelectedObject(this.owner.getId())) { return true; } return false; } /** * Returns true if the given element type can be added to this container. * @param {String} elementType */ isElementAllowed(elementType) { return false; } /** * Update container style when an element is currently dragged over this container. */ dragOver() { if (this.el !== null) { this.el.addClass('rbroElementDragOver'); } } /** * Returns absolute container offset. * @returns {Object} x and y offset coordinates. */ getOffset() { return { x: 0, y: 0 }; } /** * Returns offset relative to other container. * @param {Container} otherContainer * @returns {Object} x and y offset coordinates. */ getOffsetTo(otherContainer) { if (otherContainer !== null && otherContainer != this) { let offset = this.getOffset(); let otherOffset = otherContainer.getOffset(); return { x: offset.x - otherOffset.x, y: offset.y - otherOffset.y }; } return { x: 0, y: 0 }; } /** * Returns container size. * @returns {Object} width and height of container. */ getSize() { return { width: 0, height: 0 }; } /** * Returns container content size. * @returns {Object} width and height of container content area. */ getContentSize() { return { width: 0, height: 0 }; } /** * Returns true if given absolute position is inside container. * @param {Number} posX - absolute x coordinate. * @param {Number} posY - absolute y coordinate. */ isInside(posX, posY) { let offset = this.getOffset(); let size = this.getSize(); posX -= offset.x; posY -= offset.y; if (posX >= 0 && posY >= 0 && posX < size.width && posY < size.height) { return true; } return false; } clearErrors() { } }
JavaScript
class MutableConnection extends Connection { /** * Creates a new connection to a particular Thingworx server. * * @param {string|Server} server - the Thingworx server for which to create a connection. * @param {object} authParams - the authentication parameters used to authenticate to the * Thingworx server. See the documentation of Thingworx.collections() or Thingworx.connect() for * details of these parameters. */ constructor(server, authParams) { let serverInstance; if (typeof server === 'string') { serverInstance = Server.getServer(server); } else if (server.constructor.name === 'Server') { serverInstance = server; } else { throw new Error('Server parameter should be either a string or an instance of the Server class.'); } const modifyOptions = OptionsModifier.getModifier(authParams); super(serverInstance, modifyOptions); } /** * Creates a proxy for accessing the entity collections of the connection's server. * The proxy is mutable (that is, once created, you are able to change its authentication * parameters later on). * * @returns {Proxy} a proxy representing the entity collections of the connection's server. */ createEntityCollectionProxies() { return ProxyCreator.createMutableEntityCollectionProxies(this); } /** * Sets new authentication parameters with which to make requests. * * @param {object} authParams - the new authentication parameters used to communicate to the * Thingworx server. See the documentation of Thingworx.collections() or Thingworx.connect() for * details of these parameters. */ setAuthParams(authParams) { this.modifyOptions = OptionsModifier.getModifier(authParams); } }
JavaScript
class RnsContainer { constructor (props) { this.register = props.register; this.resolver = props.resolver; this.transfer = props.transfer; this.register.setContainer(this); this.resolver.setContainer(this); this.transfer.setContainer(this); } }
JavaScript
class Application { constructor({name, version}) { this.name = name; this.version = version; this.context = new Map(); this.subscriptions = new Map(); this.middleware = new WaltzMiddleware(); } /** * * @param {function(Error):void} handler * @returns {Application} */ registerErrorHandler(handler){ fromEvent(window,"error").pipe( map(ev => ev.error) ).subscribe(handler); return this; } /** * Wraps the context with a promise * * @param {string} id * @param {*|PromiseLike<*>} context * @returns {Application} */ registerContext(id, context){ if(this.context.has(id)){ this.context.get(id).resolve(context); } else { const deferred = new Deferred() this.context.set(id, deferred); deferred.resolve(context); } return this; } /** * Returns a promise of the context requested. * * The promise is either has been already resolved with a context value or will wait till * {@link Application#registerContext} is called. * * @param id * @returns {Promise<*>} */ getContext(id){ const deferred = this.context.get(id) || new Deferred(); this.context.set(id, deferred); return deferred; } /** * Deletes context associated with id. Rejects corresponding promise. * * @param {string} id */ unregisterContext(id){ const deferred = this.context.get(id) || new Deferred(); deferred.reject(`Context ${id} has been unregistered`); this.context.delete(id); } /** * Reset context for this application */ clearContext(){ this.context = null; this.context = new Map(); } /** * Subscribes to the observable provided so that every next/error is dispatched via the middleware using specified topic and channel. * * Unsubscribes on completion. * * If consumers need to tweak the observable use {@link Application#registerContext} instead. * * @param {string|number|Symbol} id * @param {function(Application):Observable|Observable} observableFactory * @param {string} [topic=id] topic * @param {string} [channel='channel:external'] channel * @returns {Application} */ registerObservable(id, observableFactory, topic= id, channel = kExternalChannel){ if(this.subscriptions.has(id)) throw new Error(`Observable ${id} is already registered!`); this.subscriptions.set(id, (typeof observableFactory === 'function' ? observableFactory(this) : observableFactory).subscribe({ next: payload => this.middleware.dispatch(topic, channel, payload), error: err => this.middleware.dispatchError(topic, channel, err), complete: () => this.unregisterObservable(id) })); return this; } /** * Unsubscribes from the observable * * @param {string|number|Symbol} id */ unregisterObservable(id){ if(this.subscriptions.has(id)){ this.subscriptions.get(id).unsubscribe(); this.subscriptions.delete(id); } else { console.debug(`Attempt to unregister non-registered observable ${id}`); } } clearSubscriptions(){ this.subscriptions.forEach(subscription => subscription.unsubscribe()); this.subscriptions = new Map(); } /** * * @param {function(Application):typeof Controller} controllerFactory * @returns {Application} */ registerController(controllerFactory){ this.middleware.registerController(controllerFactory(this)); return this; } /** * * @param name * @return {Controller} */ getController(name){ return this.middleware.controllers.get(name); } /** * * @param {function(Application):typeof WaltzWidget} widgetFactory * @returns {Application} */ registerWidget(widgetFactory){ this.middleware.registerController(widgetFactory(this)); return this; } /** * * @param id * @return {WaltzWidget} */ getWidget(id){ return this.middleware.controllers.get(id); } _safe(what){ return function(unsafe){ try{ unsafe[what](); } catch (e) { console.error("Failed to render controller!", e); } } } /** * This application starting point * * @returns {Application} */ run(){ this.middleware.controllers.forEach(this._safe('run')); return this; } }
JavaScript
class BoardColors { static PRIORITIES = { [Piece.WHITE]: [0, 1], [Piece.BLACK]: [1, 0], }; static ALL = [Piece.WHITE, Piece.BLACK]; /** Creation. */ constructor() { this._priority = null; } /** * First color index. * @return {intger} Index. */ get firstPriority() { this._checkWasSetted(); return this._priority[0]; } /** * Second color index. * @return {intger} Index. */ get secondPriority() { this._checkWasSetted(); return this._priority[1]; } /** * Current color. * @return {string} Color. */ get current() { return BoardColors.ALL[this.firstPriority]; } /** * Opponent color. * @return {string|null} Color. */ get opponent() { return BoardColors.ALL[this.secondPriority]; } /** Check whether color was setted or not. */ _checkWasSetted() { if (!this._priority) { throw Error('Board color wasn\'t setted.'); } } /** * Set current. * @param {string} color - One of `Piece.ALL_COLORS`. */ setCurrent(color) { if (!Piece.ALL_COLORS.includes(color)) { throw Error(`'${color}' is wrong color value. Use any of ${Piece.ALL_COLORS}.`); } this._priority = BoardColors.PRIORITIES[color]; } /** Change colors priority. */ changePriority() { this._priority = [this.secondPriority, this.firstPriority]; } }
JavaScript
class UrlLoader { constructor(url, options = {}) { this.url = url; this.options = options; this.html = null; this.status = 200; } /** * Go natively to the URL. Used as fallback */ fallback() { document.location = this.url; } responseIsCacheable(response) { if (response.status !== 200) { return false; } const cacheControl = response.headers.get("Cache-Control"); return !cacheControl || cacheControl.indexOf("no-cache") === -1; } /** * Load the page with the content of the page * * @return {Promise} */ load() { // It's cached? if (this.html) { return new Promise((accept) => accept(new Page(this.url, parseHtml(this.html), this.status)) ); } return fetch(this.url, this.options) .then((res) => { if (this.url.split("#", 1).shift() !== res.url.split("#", 1).shift()) { this.url = res.url; } if (!this.responseIsCacheable(res)) { this.html = false; } this.status = res.status; return res; }) .then((res) => res.text()) .then((html) => { if (this.html !== false) { this.html = html; } return new Page(this.url, parseHtml(html), this.status); }); } }
JavaScript
class FormLoader extends UrlLoader { constructor(form, options = {}) { if (!options.method) { options.method = (form.method || "GET").toUpperCase(); } let url; if (options.url) { url = options.url; delete options.url; } else { url = form.action.split("?", 2).shift(); } if (options.method === "GET") { url += "?" + new URLSearchParams(new FormData(form)); } else if (options.method === "POST" && !options.body) { options.body = new FormData(form); } super(url, options); this.form = form; } responseIsCacheable() { return false; } /** * Submit natively the form. Used as fallback */ fallback() { this.form.submit(); } }
JavaScript
class Connection { constructor(main, shard) { this.socket = null; this.hbinterval = null; this.hbfunc = null; this.hbtimer = null; this.s = -1; this.session = -1; this.shard = shard; this.main = main; } /** * @description Function that is called and send an event when client receive 11 opcode * @see https://discord.com/developers/docs/topics/gateway#heartbeating **/ acknowledge() { this.main.emit('DEBUG', this.shard, 'Sent in response to receiving a heartbeat to acknowledge that it has been received.'); this.hbfunc = this.beat; } /** * @description Function for periodically send heartbeat * @see https://discord.com/developers/docs/topics/gateway#heartbeating **/ beat() { this.main.emit('DEBUG', this.shard, 'Fired periodically by the client to keep the connection alive.'); this.socket.send(e({ op: 1, d: this.s })); this.hbfunc = this.resume; } /** * @description Function that is called when server send a 7 reconnect opcode * @see https://discord.com/developers/docs/topics/gateway#resuming **/ resume() { this.main.emit('DEBUG', this.shard, 'Resume a previous session that was disconnected.'); this.close().then(() => this.connect() ).then(() => { this.main.emit('DEBUG', this.shard, 'Sent resume packet'); this.socket.send(e({ op: 6, d: { token: this.main.token, session_id: this.session, seq: this.s } })); }); } /** * @description Function for close websocket connection **/ close() { this.main.emit('DEBUG', this.shard, 'Client attempting to close connection'); if (this.hbtimer) { clearInterval(this.hbtimer); } return new Promise((resolve, reject) => { if (this.socket.readyState !== 3) { this.socket.close(1001, 'Closed connection'); this.socket.removeAllListeners('close'); this.socket.once('close', () => { this.main.emit('DEBUG', this.shard, 'Client closed connection'); resolve(); }); } else { resolve(); } }); } /** * @description Function that is called for connect to Discord Api * @see https://discord.com/developers/docs/topics/gateway#connecting-to-the-gateway **/ connect(cb) { this.main.emit('DEBUG', this.shard, 'starting connection packet'); return new Promise((resolve, reject) => { this.socket = new WebSocket(this.main.url + '?encoding=' + encoding); this.socket.once('open', () => { this.main.emit('DEBUG', this.shard, 'opened connection'); this.socket.once('message', p((payload) => { this.main.emit('DEBUG', this.shard, 'recieved heartbeat info ' + JSON.stringify(payload.d)); this.hbinterval = payload.d.heartbeat_interval; this.hbfunc = this.beat; if (this.hbtimer) { clearInterval(this.hbtimer); } this.hbtimer = setInterval(() => this.hbfunc(), this.hbinterval); if (!cb) { setTimeout(() => resolve(this.identify()), 5000 - Date.now() + this.main.lastReady); } else { resolve(cb()); } })); }); this.socket.once('close', (code, reason) => { this.main.emit('DEBUG', this.shard, 'server closed connection. code: ' + code + ', reason: ' + reason + ' reconnecting in 10'); setTimeout(() => this.close().then(() => this.connect()), 10000); }); this.socket.once('error', () => { this.main.emit('DEBUG', this.shard, 'recieved error ' + e.message + ', reconnecting in 5'); setTimeout(() => this.close().then(() => this.connect()), 5000); }); }); } /** * @description Function that is called for send data to Discord Api **/ send(data) { this.socket.send(e(data)); } /** * @description Function that is called for send identify opcode to the client * @see https://discord.com/developers/docs/topics/gateway#connecting-to-the-gateway **/ identify() { return new Promise((resolve, reject) => { this.main.emit('DEBUG', this.shard, 'sent identify packet'); this.socket.send(e({ op: 2, d: { token: this.main.token, properties: {}, shard: [this.shard, this.main.shards], compress: false, large_threshold: 250, presence: {} } })); this.socket.on('message', p((payload) => { this.s = payload.s; this.main.emit('PAYLOAD', this.shard, payload); if (payload.op === 11) { this.acknowledge(); } else if (payload.t === 'RESUMED') { this.main.emit('DEBUG', this.shard, 'successfully resumed'); } else if (payload.op === 0) { this.main.emit(payload.t, this.shard, payload.d); } })); this.socket.once('message', p((payload) => { if (payload.t === 'READY') { this.session = payload.d.session_id; this.main.emit('DEBUG', this.shard, 'is ready'); resolve({ timeReady: Date.now(), socket: this }); } else if (payload.op === 9) { this.main.emit('DEBUG', this.shard, 'invalid session, reconnecting in 5'); setTimeout(() => this.close().then(() => this.connect()), 5000); } })); }); } }
JavaScript
class GatewaySocket extends EventEmitter { constructor(token, shards = 'auto') { super(); this.token = token; this.shards = shards; this.sockets = new Map(); this.lastReady = 0; } /** * @description Function for get gateway info **/ getGatewayInfo() { return new Promise((resolve, reject) => { require('https').get({ hostname: 'discordapp.com', path: '/api/gateway/bot', headers: { Authorization: "Bot " + this.token } }, (res) => { let data = ''; res.on('data', (d) => { data += d; }); res.on('end', () => { resolve(JSON.parse(data)); }); }).on('error', reject); }); } /** * @description Function for connect to Discord Api using sharding * @see https://discord.com/developers/docs/topics/gateway#sharding **/ async connect(start = 0, end) { const { url, shards } = await this.getGatewayInfo(); this.url = url; if (isNaN(this.shards)) { this.shards = shards; } end = end || this.shards; for (let i = start; i < end; i++) { if (this.sockets.get(i)) { await this.sockets.get(i).close(); } this.sockets.set(i, new Connection(this, i)); this.lastReady = (await this.sockets.get(i).connect()).timeReady; } } /** * @description Function for send shards data to Discord Api * @see https://discord.com/developers/docs/topics/gateway#sharding **/ send(data, shard = 0) { this.sockets.get(shard).send(data); } }
JavaScript
class DateUtil { /** * Returns the date, formatted or as words if recent. * * @param {moment} date The UTC date. * @param {object} t The translation. Any function that accepts a key and * returns a translated string may be used. * @returns {boolean} Returns the formatted date. */ static formatDate(date, t) { if (!date) { return null; } if (!(t instanceof Function)) { return null; } const utcDate = moment.utc(date, 'YYYY-MM-DD'); let result = ''; if (this.isToday(utcDate)) { result = t('today'); } else if (this.isYesterday(utcDate)) { result = t('yesterday'); } else if (this.isWithinLastWeek(utcDate)) { result = t('withinWeek').replace('{days}', moment.utc().diff(utcDate, 'days')); } else { result = utcDate.format('YYYY-MM-DD'); } return result; } /** * Returns a value indicating whether the specified date is today or not. * * @param {moment} date The UTC date. * @returns {boolean} Returns true if the date is today; otherwise, false. */ static isToday(date) { if (!date) { return false; } const todaysDate = moment().utc(); return (todaysDate.year() === date.year() && todaysDate.month() === date.month() && todaysDate.date() === date.date() ); } /** * Returns a value indicating whether the specified date is within the last week or not. * * @param {moment} date The UTC date. * @returns {boolean} Returns true if the date occurs within the past week; otherwise, false. */ static isWithinLastWeek(date) { if (!date) { return false; } const sevenDaysAgo = moment.utc().startOf('day').subtract(6, 'days'); return date.startOf('day') >= sevenDaysAgo && date.startOf('day') <= moment.utc().startOf('day'); } /** * Returns a value indicating whether the specified date is yesterday or not. * * @param {moment} date The UTC date. * @returns {boolean} Returns true if the date is yesterday; otherwise, false. */ static isYesterday(date) { if (!date) { return false; } const yesterday = moment.utc().subtract(1, 'days'); return date.year() === yesterday.year() && date.month() === yesterday.month() && date.date() === yesterday.date(); } /** * Checks if the date is a valid date or not. * * @param {string} date The date. * @returns {boolean} Returns true if the date is a valid date; otherwise, false. */ static isValid(date) { return date && new Date(date).toString() !== 'Invalid Date'; } }
JavaScript
class NotificationController { /** * Get notification for a user * @param {Object} req The request object * @param {Object} res The response object * @returns {Promise} res */ static async getUserNotifications(req, res) { const query = await NotificationService.getNotifications({ receiver: req.user.id }); return response.successMessage(res, `${req.user.firstName}'s notifications`, 200, query); } /** * View a spesific notification * @param {Object} req The request object * @param {Object} res The response object * @returns {Promise} res */ static async getNotificationById(req, res) { const query = await NotificationService.getNotification({ id: req.params.id, receiver: req.user.id }); return response.successMessage(res, 'A spesific notification', 200, query); } /** * Change user preference for email and in app notification * @param {Object} req The request object * @param {Object} res The response object * @returns {Promise} res */ static async changePreference(req, res) { const { emailNotification, appNotification } = req.body; await UserService.updateUser(req.user.email, { appNotification, emailNotification }); return response.successMessage(res, 'Successfully update user preference.', 200); } /** * Update all notifications as read * @param {Object} req The request object * @param {Object} res The response object * @returns {Promise} res */ static async updateNotificationsStatus(req, res) { await NotificationService.updateNotifications({ receiver: req.user.id, read: false }, { read: true }); return response.successMessage(res, 'Successfully marked all notifications as read.', 200); } /** * Update a notification as read * @param {Object} req The request object * @param {Object} res The response object * @returns {Promise} res */ static async updateNotificationStatus(req, res) { await NotificationService.updateNotifications({ id: req.params.notificationID, receiver: req.user.id }, { read: req.body.isRead }); return response.successMessage(res, 'Successfully marked a notification as read.', 200); } }
JavaScript
class InventoryContainer extends Component { render() { return ( <React.Fragment> <ReceiveBarcode /> <TilesHolder /> </React.Fragment> ); } }
JavaScript
class ProjectUpdateParameters { /** * Create a ProjectUpdateParameters. * @member {object} [tags] The resource tags for the machine learning * project. * @member {string} [friendlyName] The friendly name for this project. * @member {string} [description] The description of this project. * @member {string} [gitrepo] The reference to git repo for this project. */ constructor() { } /** * Defines the metadata of ProjectUpdateParameters * * @returns {object} metadata of ProjectUpdateParameters * */ mapper() { return { required: false, serializedName: 'ProjectUpdateParameters', type: { name: 'Composite', className: 'ProjectUpdateParameters', modelProperties: { tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, friendlyName: { required: false, serializedName: 'properties.friendlyName', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, gitrepo: { required: false, serializedName: 'properties.gitrepo', type: { name: 'String' } } } } }; } }
JavaScript
class Authenticator { AUTH_HOST = 'https://connect-testing.secupay-ag.de'; constructor (credentials) { this.credentials = credentials; this.apiClient = new ApiClient(); } /** * Function to getting token for every type of grant - * (client, application user and device). * * @returns {Promise<T | never>} */ getToken() { return this.getTokenDependingOnExistence() .catch((error) => { console.error(error); }); } /** * Function to getting a token depending on its existence. * * @returns {Request|PromiseLike<T | never>|Promise<T | never>} */ getTokenDependingOnExistence() { return this.apiClient.cachePool.exists(this.credentials.getUniqueKey()) .then(exists => exists ? this.getSpecificToken() : this.getNewToken()); } /** * Function to getting specific token depending on grant type. * * @returns {*} */ getSpecificToken() { return this.apiClient.cachePool.getItem(this.credentials.getUniqueKey()) .then(token => this.credentials instanceof OAuthDeviceCredentials ? this.getDeviceToken(token) : this.getTokenDependingOnExpiration(token)); } /** * Function to getting token for device grant. * * @param token */ getDeviceToken(token) { this.apiClient.basePath = this.AUTH_HOST; this.changeCredentialsBeforeObtainingTokenForDevice(token); return this.apiClient.cachePool.exists(this.credentials.getUniqueKey()) .then(exists => exists ? this.obtainDeviceToken() : this.getNewDeviceTokenFromApi(token)); } /** * Function to changing credentials before obtaining token for device grant. * * @param token */ changeCredentialsBeforeObtainingTokenForDevice(token) { let credentials = this.credentials.getCredentials(); delete credentials.uuid; credentials.code = token.device_code; this.credentials.setCredentials(credentials); } /** * Function to obtaining device token. * If the token wasn't expired function returns token, * in other case function gets new device token from refresh token. * * @returns {Request|PromiseLike<T | never>|Promise<T | never>} */ obtainDeviceToken() { return this.apiClient.cachePool.getItem(this.credentials.getUniqueKey()) .then(token => this.apiClient.cachePool.isExpired(token) ? this.getNewDeviceTokenFromRefreshToken() : token); } /** * Function to getting new device token from refresh token. * * @returns {Request|PromiseLike<T | never>|Promise<T | never>} */ getNewDeviceTokenFromRefreshToken() { return this.apiClient.cachePool.exists(this.credentials.getUniqueKey()) .then(exists => exists ? this.getTokenFromRefreshToken() : (() => { throw 'Token not exists' })()); } /** * Function to getting a token from given refresh token. * * @returns {*} */ getTokenFromRefreshToken() { return this.apiClient.cachePool.getItem(this.credentials.getUniqueKey()) .then((refreshToken) => { this.changeCredentialsToRefreshCredentials(refreshToken); return this.getTokenDependingOnExistence(); }); } /** * Function to changing credentials to refresh credentials. * * @param refresh_token */ changeCredentialsToRefreshCredentials({ refresh_token }) { this.credentials = OAuthRefreshCredentials.from( this.credentials.credentials.client_id, this.credentials.credentials.client_secret, refresh_token ); } /** * Function to getting new device token from API. * * @param token * @returns {Promise<any | never>} */ getNewDeviceTokenFromApi(token) { return this.getTokenFromApi() .then((response) => { return this.setObtainedToken(response); }) .catch((error) => { error = JSON.parse(error.response.text); error = error.error; if (error === 'authorization_pending') { return this.authenticateFirstTime(token); } }); } /** * Function to getting token from API. * * @returns {Promise} */ getTokenFromApi() { return this.apiClient.callApi( 'oauth/token',//path 'POST',//httpMethod {},//pathParams {},//queryParams {'Content-Type':'application/json'},//headerParams {},//formParams this.credentials.getCredentials(),//bodyParam [],//authNames [],//contentTypes []//accepts //returnType ); } /** * Function to setting obtained token in cache. * * @param response * @returns {*} */ setObtainedToken(response) { let token = response.response.body; this.apiClient.cachePool.setItem(this.credentials.getUniqueKey(), token); return token; } /** * Function to authenticating as a device grant first time. * * @param codeToken * @returns {Promise<any | never | never>} */ authenticateFirstTime(codeToken) { this.apiClient.getPrinter().printUserCode(codeToken); if (codeToken.device_code === undefined) { throw 'device_code not found in token'; } else if (codeToken.expires_in === undefined) { throw 'expires_in not found in token'; } else if (codeToken.interval === undefined) { throw 'interval not found in token'; } else { return this.tryToObtainTokenForDevice(codeToken.expires_in, codeToken.interval); } } /** * Function to trying to obtain a token for a device. * * @param expiresIn * @param interval * @returns {Promise<any | never>} */ tryToObtainTokenForDevice(expiresIn, interval) { return new Promise((resolve, reject) => { let tryObtainToken = setInterval(() => { return this.getTokenFromApi() .then((response) => { clearInterval(tryObtainToken); resolve(this.setObtainedToken(response)); }) .catch(() => { if (expiresIn > 0) { expiresIn = expiresIn - interval; } else { clearInterval(tryObtainToken); reject('Unfortunately, the access token could not be obtained.'); } }); }, interval * 1000); }); } /** * Function to getting token depending on an expiration. * * @param token * @returns {*} */ getTokenDependingOnExpiration(token) { return this.apiClient.cachePool.isExpired(token) ? this.getNewToken() : token; } /** * Function to getting new token using API call. * * @returns {Promise<any | never>} */ getNewToken() { this.apiClient.basePath = this.AUTH_HOST + '/'; return this.getTokenFromApi() .then((response)=> { let token = this.setObtainedToken(response); return this.credentials instanceof OAuthDeviceCredentials ? this.getDeviceToken(token) : token; }); } /** * Getter for API client, which allows making requests. * * @returns {*|(function(): obj)|{default?: ApiClient}|module:ApiClient} */ getApiClient() { return this.apiClient; } /** * Setter for API client, which allows making requests. * * @param apiClient */ setApiClient(apiClient) { this.apiClient = apiClient; } }
JavaScript
class DjangoInclude extends BodyComponent { static allowedAttributes = { template: 'string' }; static endingTag = true; render() { return `{% include '${this.getAttribute('template')}' %}`; } }
JavaScript
class ExportedData { eventHandlerMap = new Map(); data = new Map(); emit(type, ...args) { emitEvent(this.eventHandlerMap)(type, ...args); } addEventListener(type, handler) { this.eventHandlerMap = addEventListener(this.eventHandlerMap)(type, handler); } updateData(data) { this.data = data; // console.log('Data changed to', data); this.emit('change', data); } }
JavaScript
class ViewController extends Craft.UI.DefaultRootViewController { /** * StickyHeaderNavi constructor * * @param {Object} options - options * @param {Object} options.header - Header contents * @param {Boolean} options.enableSwipeBack - true to enable page back by swipe gesture (default false) * @param {Craft.UI.View|Craft.UI.ViewController|Craft.Widget.StickyHeaderNavi.Page} options.page - initial page (not work if you call bringup() at start) * @param {Boolean} options.custombackbtn - use custom back button instead of framework prepared one */ constructor(options){ super(); this.packagename = 'Craft.Widget.StickyHeaderNavi.ViewController'; this.stack = []; // history. NOTE: this is only effective in the standalone mode this.currentView = ''; // current viewing page component this.Pages = {}; // support to access page object by its componentId, and manages metadata this.parent = ''; // parent StickyHeaderNavi this.header = options.header; this.backbtn = options.backbtn; this.initialPage = options.page; // this.initialPage will be deleted after appended to the this.contents_holder, and moved to this.currentView this.custombackbtn = options.custombackbtn; // boolean this.enableSwipeBack = options.enableSwipeBack; // BackButton and swipeback is only available in the standalone mode. if( !Craft.UI.Device.isStandaloneMode() ){ // browser mode this.backbtn = null; this.enableSwipeBack = false; this.custombackbtn = false; // cancel for browser mode }else{ // standalone if( this.custombackbtn ){ this.backbtn = null; // this.backbtn should be defined by deployCustomBackBtn implementation } } } /** * viewDidLoad * * setup controlled elements * * @override * @protected */ viewDidLoad(callback){ // component holders this.back_holder = this.shadow.getElementById("back"); this.contents_holder = this.shadow.getElementById("contents"); this.header_holder = this.shadow.getElementById("header"); this.marker = this.shadow.getElementById("marker"); this.header.setViewController(this); if( !this.header.isViewLoaded ){ this.header.loadView(); } this.header.viewWillAppear(); this.header_holder.appendChild(this.header.view); this.header.viewDidAppear(); // setup back button if( this.custombackbtn ){ // delegate defining this.backbtn this.deployCustomBackBtn(); }else{ // define this.backbtn by myself if( this.backbtn ){ this.backbtn.setViewController(this); if( !this.backbtn.isViewLoaded ){ this.backbtn.loadView(); } this.backbtn.viewWillAppear(); this.back_holder.appendChild(this.backbtn.view); this.backbtn.viewDidAppear(); } } // enable swipe right to page back if( this.enableSwipeBack ){ Craft.Core.Gesture.enableSwipe({ target : this.contents_holder, right : (event) => { this.back(); } }); } // fire ContentTapped event occured on the `contents` (DefaultViewController does on this.view) Craft.Core.Gesture.enableTap({ target : this.contents_holder, tap : (event) => { Craft.Core.NotificationCenter.notify('ContentTapped',event); } }); // open initial page if defined if( this.initialPage ){ this.open(this.initialPage); } if( callback ){ callback() } } /** * viewDidAppear * * initial setup of sticky handler * * @override * @protected */ viewDidAppear(){ this.updateStickyHandler(); } /** * update sticky handler * * this should be automatically called when you update header content * * @protected */ updateStickyHandler(){ let header_large_height = this.header.getLargeHeight(); // original height let threshold = this.header.getStickyThreshold(); this.marker.style["top"] = threshold + 'px'; this.observer = new IntersectionObserver((entries, observer) => { if( entries[0].isIntersecting ){ this.header_holder.classList.remove("header_sticky"); this.contents_holder.style["margin-top"] = '0px'; this.back_holder.style["margin-top"] = '0px'; this.header.onExitSticky(); this.contents_holder.classList.remove('contents_safe_shift'); }else{ this.header_holder.classList.add("header_sticky"); this.contents_holder.style["margin-top"] = `${header_large_height}px`; this.back_holder.style["margin-top"] = `-${header_large_height}px`; this.header.onEnterSticky(); this.contents_holder.classList.add('contents_safe_shift'); } }); this.observer.observe(this.marker); } /** * Define custom back button (this.backbtn) * * If you would like use your own customized back button instead of framework prepared one, * you have to set custombackbtn:true flag to constructor, * and implement deployCustomBackBtn delegation method * with code instantiating your back button and setting this.backbtn. * * BTW, you may delegate deployCustomBackBtn() to your Header implementation. * (The back button may be on your header) * * @example * * deployCustomBackBtn(){ * // delegate to header * this.header.deployCustomBackBtn(); * } * * // in header implementation * deployCustomBackBtn(){ * this.views.backbtn = new MyBackBtn(); * this.appendView(this.views.backbtn); * this.viewController.backbtn = this.views.backbtn; * } * * @protected */ deployCustomBackBtn(){} // * * * * * * * * * * * * * * * * * * * * /** * Open a page * * @param {Object} options - options * @param {Craft.Core.Component} options.page - page component * @param {Function} options.callback - callback * @param {Craft.Core.Route} options.route - Route object */ open(options){ let page = options.page; let callback = options.callback; let route = options.route; let event = route ? route.event : null; // event is defined if open is called by browser back/forward with popstate event let launch = route ? route.launch : false; // true if called from RootViewController#bringup let disappearingView = this.currentView; let appearingView = page; appearingView.setViewController(this); if( !appearingView.isViewLoaded ){ appearingView.loadView(); } if( disappearingView ){ disappearingView.viewWillDisappear(); this.Pages[disappearingView.componentId].scrollTop = document.documentElement.scrollTop; } appearingView.viewWillAppear( () => { if( disappearingView ){ disappearingView.viewDidDisappear(); disappearingView.view.remove(); } this.Pages[appearingView.componentId] = { page:appearingView, scrollTop:0 }; this.stack.push(appearingView); this.contents_holder.appendChild(appearingView.view); appearingView.showComponent(); appearingView.viewDidAppear(); this.currentView = appearingView; if( launch ){ // launching the app window.history.replaceState( { componentId:this.currentView.componentId, timestamp:Date.now() }, this.currentView.title, Craft.Core.Context.getRouter().normalize(this.currentView.path) ); }else{ if( !event ){ // in app navigation window.history.pushState( { componentId:this.currentView.componentId, timestamp:Date.now() }, this.currentView.title, Craft.Core.Context.getRouter().normalize(this.currentView.path) ); } } if( this.currentView.title ){ document.title = this.currentView.title; } if( window.pageYOffset > this.header.getStickyThreshold() ){ window.scrollTo(0,this.header.getStickyThreshold()+1); this.contents_holder.classList.add('contents_safe_shift'); }else{ this.contents_holder.classList.remove('contents_safe_shift'); } if( this.backbtn ){ if( this.stack.length > 1 ){ this.backbtn.view.style['display'] = 'block'; this.header.onAppearBackButton(); }else{ this.backbtn.view.style['display'] = 'none'; this.header.onDisappearBackButton(); } } if( callback ){ callback(); } }); } /** * Page back (for standalone mode) * * @param {Function} callback - callback */ back(callback){ if( this.stack.length <= 1 ){ // no more history return; } let index = this.stack.length - 1; if( index < 1 ){ index = 1; } let disappearingViews = this.stack.splice(index); let disappearingView = this.currentView; let appearingView = this.stack[this.stack.length-1]; for( let i=0; i<disappearingViews.length; i++ ){ disappearingViews[i].viewWillDisappear(); } appearingView.viewWillAppear( () => { if( this.Pages[appearingView.componentId].scrollTop ){ document.documentElement.scrollTop = this.Pages[appearingView.componentId].scrollTop; }else{ document.documentElement.scrollTop = 0; } delete this.Pages[disappearingView.componentId]; disappearingView.viewDidDisappear(); disappearingView.view.remove(); this.contents_holder.appendChild(appearingView.view); appearingView.showComponent(); appearingView.viewDidAppear(); this.currentView = appearingView; if( appearingView.path ){ window.history.pushState( { componentId:this.currentView.componentId, timestamp:Date.now() }, this.currentView.title, Craft.Core.Context.getRouter().normalize(this.currentView.path) ); } if( this.currentView.title ){ document.title = this.currentView.title; } if( this.backbtn && (this.stack.length === 1) ){ this.backbtn.view.style['display'] = 'none'; this.header.onDisappearBackButton(); } if( callback ){ callback(); } }); } // * * * * * * * * * * * * * * * * * * * * /** * style * @protected */ style(componentId){ return ` * { box-sizing:border-box; } :host { width: 100vw; margin: 0px; padding: 0px; } .root { width: 100vw; } .back { position: fixed; width: 44px; height: 44px; z-index: 9999; } .header { position: relative; } .header_sticky { position: fixed; top: 0; width: 100%; } .marker { position: absolute; top: 0px; width: 1px; height: 1px; margin-top: -1px; } .contents { } .contents_safe_shift { padding-top: env(safe-area-inset-top); } `; } /** * template * @protected */ template(componentId){ return ` <div id="root" class="root"> <div class="back" id="back"></div> <div class="header" id="header"></div> <div class="marker" id="marker"></div> <div class="cotents" id="contents"></div> </div> `; } }
JavaScript
class Node { constructor(val) { this.val = val; this.left = null; this.right = null; } }
JavaScript
class Engineer extends Employee { constructor(name, id, email, github) { super(name, id, email); this.github = github; } getGithub() { return this.github; } getRole() { return "Engineer" } }
JavaScript
class EmbeddedArrayField extends Component { render() { const { resource, children, source, record } = this.props; const layoutProps = { resource, basePath: '/', record }; const elements = _.get(record, source) || []; const elementsWithIndex = _.map(elements, (el, k) => _.merge(el, { _index: k })); return ( <div> {_.map( elementsWithIndex, (element, i) => <SimpleShowLayout {...layoutProps} key={i}> {React.Children.map(children, child => React.cloneElement(child, { source: child.props.source ? `${source}[${i}].${child.props.source}` : `${source}[${i}]`, }), )} </SimpleShowLayout>, this, )} </div> ); } }
JavaScript
class CustomDocument extends Document { static async getInitialProps(ctx) { resetServerContext(); const sheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: App => props => sheet.collectStyles(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), }; } finally { sheet.seal(); } } render() { return ( <Html lang="en"> <Head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Official website for the Sharks Ice Team." /> <meta name="build version" content={version} /> <link rel="apple-touch-icon" sizes="192x192" href="/ITLogo_192x192.png" /> <link rel="icon" href="/favicon.ico" /> <link rel="manifest" href="/manifest.json" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } }
JavaScript
class Multiqueue{ constructor(){ this._lock = new Lock(); this._queues = {} } async enqueue(dest = Err.required("dest"), obj = Err.required("obj"), timeout, onTimeout){ Logger.debug("Enqueueing object for: " + dest); if (!this._queues.hasOwnProperty(dest)){ try { await this._lock.acquire(); if(!this._queues.hasOwnProperty(dest)){ this._queues[dest] = new MessageQueueBlocking(); } }catch(e){ Logger.error("Error enqueueing message: " + e) }finally{ this._lock.release(); } } //Here we are sure that queue exists let queue = this._queues[dest]; try{ await queue.enqueue(obj); if (typeof timeout === "number" && timeout > 0){ setTimeout(this.getTimeoutHandler(dest, obj, onTimeout), timeout); } }catch(e){ Logger.error("Error enqueueing message: " + e) }finally{ queue.unlock(); } } getTimeoutHandler(key, obj, onTimeout){ let self = this return async ()=>{ Logger.debug("standard onTimeout handler called for expired object.") let queue = self.get(key) let removed = await queue.remove(obj); if (removed === undefined){ Logger.debug("Object has been processed in time") return; } if (typeof onTimeout === "function"){ onTimeout(obj); } } } get(key){ Logger.debug("Get queue request for key: " + key + " Existing keys are: " + JSON.stringify(Object.keys(this._queues))) return this._queues[key]; } isEmpty(key){ return this._queues.hasOwnProperty(key) ? this._queues[key].isEmpty() : true; } }
JavaScript
class Polygon { constructor(sides) { this.sides = sides; } perimeter() { let result = 0; for (let side of this.sides) { result += side; } return result; } }
JavaScript
class SkillItem extends Component { render() { return( <div> {/* <Logo /> */} <div className="skillbar" data-percent={this.props.dataPercent}> <div className="skillbar-title-main">{this.props.skill}</div> <div className="skill-bar-percent-main">{this.props.dataPercent}</div> <div className="skillbar-bar-main" style={{width: this.props.dataPercent}}></div> </div> </div> ) } }
JavaScript
class FormattingElementList { constructor(treeAdapter) { this.length = 0; this.entries = []; this.treeAdapter = treeAdapter; this.bookmark = null; } //Noah Ark's condition //OPTIMIZATION: at first we try to find possible candidates for exclusion using //lightweight heuristics without thorough attributes check. _getNoahArkConditionCandidates(newElement) { const candidates = []; if (this.length >= NOAH_ARK_CAPACITY) { const neAttrsLength = this.treeAdapter.getAttrList(newElement).length; const neTagName = this.treeAdapter.getTagName(newElement); const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } const element = entry.element; const elementAttrs = this.treeAdapter.getAttrList(element); const isCandidate = this.treeAdapter.getTagName(element) === neTagName && this.treeAdapter.getNamespaceURI(element) === neNamespaceURI && elementAttrs.length === neAttrsLength; if (isCandidate) { candidates.push({ idx: i, attrs: elementAttrs }); } } } return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates; } _ensureNoahArkCondition(newElement) { const candidates = this._getNoahArkConditionCandidates(newElement); let cLength = candidates.length; if (cLength) { const neAttrs = this.treeAdapter.getAttrList(newElement); const neAttrsLength = neAttrs.length; const neAttrsMap = Object.create(null); //NOTE: build attrs map for the new element so we can perform fast lookups for (let i = 0; i < neAttrsLength; i++) { const neAttr = neAttrs[i]; neAttrsMap[neAttr.name] = neAttr.value; } for (let i = 0; i < neAttrsLength; i++) { for (let j = 0; j < cLength; j++) { const cAttr = candidates[j].attrs[i]; if (neAttrsMap[cAttr.name] !== cAttr.value) { candidates.splice(j, 1); cLength--; } if (candidates.length < NOAH_ARK_CAPACITY) { return; } } } //NOTE: remove bottommost candidates until Noah's Ark condition will not be met for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) { this.entries.splice(candidates[i].idx, 1); this.length--; } } } //Mutations insertMarker() { this.entries.push({ type: FormattingElementList.MARKER_ENTRY }); this.length++; } pushElement(element, token) { this._ensureNoahArkCondition(element); this.entries.push({ type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } insertElementAfterBookmark(element, token) { let bookmarkIdx = this.length - 1; for (; bookmarkIdx >= 0; bookmarkIdx--) { if (this.entries[bookmarkIdx] === this.bookmark) { break; } } this.entries.splice(bookmarkIdx + 1, 0, { type: FormattingElementList.ELEMENT_ENTRY, element: element, token: token }); this.length++; } removeEntry(entry) { for (let i = this.length - 1; i >= 0; i--) { if (this.entries[i] === entry) { this.entries.splice(i, 1); this.length--; break; } } } clearToLastMarker() { while (this.length) { const entry = this.entries.pop(); this.length--; if (entry.type === FormattingElementList.MARKER_ENTRY) { break; } } } //Search getElementEntryInScopeWithTagName(tagName) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.MARKER_ENTRY) { return null; } if (this.treeAdapter.getTagName(entry.element) === tagName) { return entry; } } return null; } getElementEntry(element) { for (let i = this.length - 1; i >= 0; i--) { const entry = this.entries[i]; if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) { return entry; } } return null; } } //Entry types
JavaScript
class SLNode { // The constructor is built to take 1 parameter; the value of the node we want // to create constructor(value) { // The node's actual value being set to the value passed in through the constructor this.value = value; // And the pointer that refers to the node next in the sequence after // this node. Note it starts as null, because when you first create a node, // it is not connected to anything. this.next = null; } }
JavaScript
class SLList { constructor() { // The head marks the beginning of the linked list. this.head = null; // Note that it's null. This is because when you first create a list, it's empty! } // Write a method that returns a boolean based on whether or not the list // is empty. HINT! Check out isEmpty(value) { return this.head === null; // if (this.head != null) { // return false; // } else { // return true; // } } /**************************************************************** */ // Write a method that will add to the back of a singly linked list. // Essentially, have a runner start at the head, traverse along to the end, // then create a new node at the end, and reassign the last node's .next pointer // to the new node. addToBack(value) { let runner = this.head; if (this.isEmpty()) { this.head = new SLNode(value); return this; } while (runner.next !== null) { runner = runner.next; } runner.next = new SLNode(value); return this; } // Here's a gimme: This will print the contents of a singly linked list. printList() { // We need to initialize an empty string let toPrint = ""; // And start a runner at the head of the list. let runner = this.head; // We want to perform something every time runner isn't null while (runner != null) { // Add the new value and an arrow (oh so fancy, I know!) // to the string we want to print toPrint += `${runner.value} -> `; // And move runner to the next node. This is gonna be your // bread and butter when it comes to linked lists runner = runner.next; } // What good is our print list method if it doesn't console log?! console.log(toPrint); // And just so we can chain methods (idk why you'd want to chain from print list, // but why not), just return this. return this; } }
JavaScript
class ViewContext { // Will eventually be split into TileViewContext and ViewContext /** * View Component */ constructor() { var self = this; self.propipe = new PropertyPipeline(self) .set("cache", { package: {} }) .set("children", {}) .set("frameCounter", 0) .save(); } // Was working on VCCAssign --> /** * Cache packets of refrences * Also for contexts to have easy access to other contexts * @param {String} cacheIdentifier * @param {Object[]} properties */ createCachePackage(cacheIdentifier, properties) { this.cache.package[cacheIdentifier] = properties; } /** * Get a cached package * @param {String} cacheIdentifier */ getCachePackage(cacheIdentifier) { return this.cache.package[cacheIdentifier]; } /** * Assign a context, must have certain methods to identify as a VCCompatableContext * * Adding contexts links them all together, with respect to the parent * This allows easy access to readily needed states while maintaining structure * @param {any} context */ assignContext(contextInstance) { // If the contextInstance is a VCCompatibleContext if (VCContextCompatableInterface.confirm(contextInstance.__proto__)) { contextInstance.VCCAssign(this); } } }
JavaScript
class AttributeSnapshot{ constructor( object, attributesArray_String ){ var self = this; self.object = object; self.snapshots = {}; self.createSnap(); } // Returns weather the attributes has changed from the snapshot compare(){ var diff = 0, self = this; attributesArray_String.map( ( attr )=>{ diff+= self.snapshots[attr] == self.object[attr] ? 0 : 1; }); return diff <= 0; } createSnap(){ var self = this; attributesArray_String.map( ( attr )=>{ self.snapshots[attr] = self.object[attr]; }); } }
JavaScript
class CapitalizeValueConverter { toView( string ) { if ( !string ) { return string } return string.substr( 0, 1 ).toUpperCase() + string.substr( 1 ); } }
JavaScript
class InfluencersCell extends Component { constructor(props) { super(props); this.limit = props.limit; const recordInfluencers = props.influencers || []; this.influencers = []; _.each(recordInfluencers, (influencer) => { _.each(influencer, (influencerFieldValue, influencerFieldName) => { this.influencers.push({ influencerFieldName, influencerFieldValue }); }); }); // Allow one more influencer than the supplied limit as displaying // 'and 1 more' would take up an extra line. const showAll = this.influencers.length <= (this.limit + 1); this.state = { showAll }; } toggleAllInfluencers() { this.setState({ showAll: !this.state.showAll }); } renderInfluencers() { const numberToDisplay = this.state.showAll === false ? this.limit : this.influencers.length; const displayInfluencers = this.influencers.slice(0, numberToDisplay); this.othersCount = Math.max(this.influencers.length - numberToDisplay, 0); if (this.othersCount === 1) { // Display the additional influencer. displayInfluencers.push(this.influencers[this.limit]); this.othersCount = 0; } return displayInfluencers.map((influencer, index) => { return ( <div key={index}>{influencer.influencerFieldName}: {influencer.influencerFieldValue}</div> ); }); } renderOthers() { if (this.othersCount > 0) { return ( <div> <EuiLink onClick={() => this.toggleAllInfluencers()} > and {this.othersCount} more </EuiLink> </div> ); } else if (this.influencers.length > this.limit + 1) { return ( <div> <EuiLink onClick={() => this.toggleAllInfluencers()} > show less </EuiLink> </div> ); } } render() { return ( <div> {this.renderInfluencers()} {this.renderOthers()} </div> ); } }
JavaScript
class ModifyImageAttributeRequest { /** * Constructs a new <code>ModifyImageAttributeRequest</code>. * Contains the parameters for ModifyImageAttribute. * @alias module:model/ModifyImageAttributeRequest * @param imageId {String} */ constructor(imageId) { ModifyImageAttributeRequest.initialize(this, imageId); } /** * 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, imageId) { obj['ImageId'] = imageId; } /** * Constructs a <code>ModifyImageAttributeRequest</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/ModifyImageAttributeRequest} obj Optional instance to populate. * @return {module:model/ModifyImageAttributeRequest} The populated <code>ModifyImageAttributeRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ModifyImageAttributeRequest(); if (data.hasOwnProperty('Attribute')) { obj['Attribute'] = ApiClient.convertToType(data['Attribute'], 'String'); } if (data.hasOwnProperty('Description')) { obj['Description'] = AttributeValue.constructFromObject(data['Description']); } if (data.hasOwnProperty('DryRun')) { obj['DryRun'] = ApiClient.convertToType(data['DryRun'], 'Boolean'); } if (data.hasOwnProperty('ImageId')) { obj['ImageId'] = ApiClient.convertToType(data['ImageId'], 'String'); } if (data.hasOwnProperty('LaunchPermission')) { obj['LaunchPermission'] = LaunchPermissionModifications.constructFromObject(data['LaunchPermission']); } if (data.hasOwnProperty('OperationType')) { obj['OperationType'] = OperationType.constructFromObject(data['OperationType']); } if (data.hasOwnProperty('ProductCodes')) { obj['ProductCodes'] = ApiClient.convertToType(data['ProductCodes'], ['String']); } if (data.hasOwnProperty('UserGroups')) { obj['UserGroups'] = ApiClient.convertToType(data['UserGroups'], ['String']); } if (data.hasOwnProperty('UserIds')) { obj['UserIds'] = ApiClient.convertToType(data['UserIds'], ['String']); } if (data.hasOwnProperty('Value')) { obj['Value'] = ApiClient.convertToType(data['Value'], 'String'); } } return obj; } }
JavaScript
class PluginConfigRegistry { constructor() { this._registry = new Map(); } /** * adds a plugin to the registry * * @param {string} pluginName * @param {string} configName * @param {Object} config * * @returns {Map<any, any>} */ set(pluginName, configName, config) { const pluginConfigs = this._createPluginConfigRegistry(pluginName); return pluginConfigs.set(configName, config); } /** * returns a config from the registry * * @param {string} pluginName * @param {string} configName * * @returns {any} */ get(pluginName, configName = false) { const pluginConfigs = this._createPluginConfigRegistry(pluginName); if (configName && pluginConfigs.has(configName)) { return pluginConfigs.get(configName); } else if (configName) { throw new Error(`The config "${configName}" is not registered for the plugin "${pluginName}"!`); } return pluginConfigs; } /** * removes a config from the registry * * @param {string} pluginName * @param {string} configName * * @returns {PluginConfigRegistry} */ delete(pluginName, configName) { const pluginConfigs = this._createPluginConfigRegistry(pluginName); pluginConfigs.delete(configName); return this; } /** * clears the registry * * @returns {PluginConfigRegistry} */ clear() { this._registry.clear(); return this; } /** * creates the map for a plugin if not already existing * and returns it * * @param {string} pluginName * * @returns {Map<any, any>} * @private */ _createPluginConfigRegistry(pluginName) { if (!pluginName) { throw new Error('A plugin name must be given!'); } if (!this._registry.has(pluginName)) { this._registry.set(pluginName, new Map()); } return this._registry.get(pluginName); } }
JavaScript
class SmartState extends BaseFileState { /** * Constructs a new combined state * * @param {Object} fileInfo Object containing existing state data */ constructor(fileInfo) { super(fileInfo); if (Object.keys(fileInfo).length === 1) { let stat = fs.statSync(this.path); this._lastModified = stat.mtime.getTime(); this._size = stat.size; this._sha1 = null; } } /** * Gets the last modification date of the file * * @return {number} Last modified date in miliseconds */ get lastModified() { return this._lastModified; } /** * Gets the file size of the file * * @return {number} File size in bytes */ get size() { return this._size; } /** * Gets the SHA-1 hash of the file's content * * @return {string} SHA-1 content hash */ get sha1() { if (this._sha1 === null) { this._sha1 = this.computeSha1(); } return this._sha1; } /** * Computes the sha1 hash of the files content * * @return {string} Computed sha1 hash */ computeSha1() { let hash = crypto.createHash('sha1'); hash.update(fs.readFileSync(this.path)); return hash.digest('hex'); } /** * Checks if this file state is different than another given file state * * We do the checks in order of fastest to slowest. First check the * modification times, then for different file size and last one is SHA-1 * content hash. * * @param {FileState} otherState File state to check against * @return {boolean} True if the two file states are different, false otherwise */ isDifferentThan(otherState) { if (this.path !== otherState.path) { throw new Error(`Can only compare files with the same path, but tried to compare ${this._path} with ${otherState.path}`); } if (this.lastModified === otherState.lastModified) { return false; } return this.size !== otherState.size || this.sha1 !== otherState.sha1; } /** * @inheritdoc */ toJson() { return { path: this.path, lastModified: this.lastModified, size: this.size, sha1: this.sha1 }; } }
JavaScript
class Navbar extends Component { constructor() { super(); this.state = { showMenu: false, }; this.showMenu = this.showMenu.bind(this); this.closeMenu = this.closeMenu.bind(this); } showMenu(event) { event.preventDefault(); /* Show dropdown menu on click */ this.setState({ showMenu: true }, () => { document.addEventListener('click', this.closeMenu); }); } /* Close dropdown menu on click */ closeMenu() { this.setState({ showMenu: false }, () => { document.removeEventListener('click', this.closeMenu); }); } render() { return ( <StyledNavbar> <img src={logo} className="companyLogo" alt="logo" /> <button onClick={this.showMenu}> <img src={hamburger} alt="hamburger" /> </button> { this.state.showMenu ? ( <div className="menu"> <NavLink to="/">Hem</NavLink> <NavLink to="/service">Tjänster</NavLink> <NavLink to="/kontakt">Kontakt</NavLink> </div> ) : (null) } {/* Show nav when window over 800px*/} <nav> <NavLink to="/">Hem</NavLink> <NavLink to="/service">Tjänster</NavLink> <NavLink to="/kontakt">Kontakt</NavLink> </nav> </StyledNavbar> ); } }
JavaScript
class SlideShow { /** * Constructor of the class that require the container element of the slideshow * @param imgContainer * @param options * @returns {SlideShow} */ constructor(imgContainer, options) { if (imgContainer === undefined) { throw new Error('First param \'imgContainer\' must be set. Please set an image container.'); } imgContainer = this.stringToID(imgContainer); this.imgContainer = imgContainer; this.currentImg = ''; this.appendStyle(imgContainer); if (options != undefined) { this.manageOptions(options); } return this; } /** * Method that append the css of the slideshow to the head element * @param imgContainer */ appendStyle(imgContainer) { $('#style-slideshow').remove(); $('head').append('<style id="style-slideshow">' + imgContainer + '{width:100%;height:300px;}' + imgContainer + ' img {height: 100%;width: 100%;margin: auto;object-fit: cover;}</style>'); } /** * Add a '#' a the beginning of a string if their is none * @param str * @returns {String} */ stringToID(str) { if (str.substring(0, 1) != '#') { str = '#' + str; } return str; } /** * Add an image to the slideshow * @param url * @returns {*|jQuery|HTMLElement} */ addImage(url) { // Creation of the image let img = $('<img src=\'' + url + '\' alt=\'image\'>'); // We append the image to the image container $(this.imgContainer).append(img); // We hide the image if it's not the first child if (img.is(':first-child')) { this.currentImg = img; } else { img.hide(); } return img; } /** * Add several images to the slideshow * @param urls * @returns {SlideShow} */ addImages(urls) { for (let i = 0; i < urls.length; i++) { this.addImage(urls[i]); } return this; } /** * Show the next image * @returns {Image} */ nextImage() { let nextImg = $(this.currentImg).next(); if (nextImg.length == 0) { nextImg = $(this.imgContainer).children().first(); } return this.showImage(nextImg); } /** * Show the previous image * @returns {Image} */ prevImage() { let nextImg = $(this.currentImg).prev(); if (nextImg.length == 0) { nextImg = $(this.imgContainer).children().last(); } return this.showImage(nextImg); } /** * Display an image * @param img * @returns {Image} */ showImage(img) { // We hide the current image and show the image given as parameter $(this.currentImg).hide(); $(img).show(); // We set the current image to be the image given as parameter this.currentImg = img; this.currentImg.trigger('show'); return img; } /** * Empty the slideshow * @returns {SlideShow} */ clearImage() { $(this.imgContainer).empty(); return this; } /** * Function that manage the options * @param options */ manageOptions(options) { if (options.hasOwnProperty('buttonNextId')) { $(this.stringToID(options.buttonNextId)).click(this.nextImage.bind(this)); } if (options.hasOwnProperty('buttonPrevId')) { $(this.stringToID(options.buttonPrevId)).click(this.prevImage.bind(this)); } if (options.hasOwnProperty('buttonClearId')) { $(this.stringToID(options.buttonClearId)).click(this.clearImage.bind(this)); } } }
JavaScript
class Entry extends Component { render() { const entry = this.props.entry; return ( <Row> <Col m={1} s={2} l={1} className="rank"> {entry.rank} </Col> <Col m={2} s={4} l={2}> <img className="entryImage" src={entry.image} alt="" /> </Col> <Col m={9} s={6} l={4} className="entryInfo"> <div>{entry.name}</div> <div className="entryUrlText"><a href={entry.url}>{entry.urlText}</a></div> </Col> </Row>); } }
JavaScript
class PopupBase extends Component { render () { const { show, width, height, inline, pixel, children, arrow } = this.props const arrowTranslator = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' } return ( <Container width={width} height={height} show={show} inline={inline} pixel={pixel} arrow={arrow}> <ArrowBox position={arrowTranslator[arrow]}> {children} </ArrowBox> </Container> ) } }
JavaScript
class Pair { /** * Creates a new Pair instance * @param {Component} key Key component * @param {Component} value Value component */ constructor(key, value) { this._key = key; this._value = value; } render(el) { this._key.render(el); this._value.render(el); } unrender() { this._key.unrender(); this._value.unrender(); } /** * Get the key component. * @returns {Component} the key component */ getKeyComponent() { return this._key; } /** * Get the value component. * @returns {Component} the value component */ getValueComponent() { return this._value; } }