_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45500
train
function(value) { if (value === null) { return []; } else if (Array.isArray(value)) { if (value.every(Selectivity.isValidId)) { return value; } else { throw new Error('Value contains invalid IDs'); } } else { throw new Error('Value for MultiSelectivity instance should be an array'); } }
javascript
{ "resource": "" }
q45501
EventListener
train
function EventListener(el, context) { this.context = context || null; this.el = el; this.events = {}; this._onEvent = this._onEvent.bind(this); }
javascript
{ "resource": "" }
q45502
train
function(eventName, selector, callback) { if (!isString(selector)) { callback = selector; selector = ''; } if (callback) { var events = this.events[eventName]; if (events) { events = events[selector]; if (events) { for (var i = 0; i < events.length; i++) { if (events[i] === callback) { events.splice(i, 1); i--; } } } } } else { this.events[eventName][selector] = []; } }
javascript
{ "resource": "" }
q45503
train
function(eventName, selector, callback) { if (!isString(eventName)) { var eventsMap = eventName; for (var key in eventsMap) { if (eventsMap.hasOwnProperty(key)) { var split = key.split(' '); if (split.length > 1) { this.on(split[0], split[1], eventsMap[key]); } else { this.on(split[0], eventsMap[key]); } } } return; } if (!isString(selector)) { callback = selector; selector = ''; } if (!this.events.hasOwnProperty(eventName)) { var useCapture = CAPTURED_EVENTS.indexOf(eventName) > -1; this.el.addEventListener(eventName, this._onEvent, useCapture); this.events[eventName] = {}; } if (!this.events[eventName].hasOwnProperty(selector)) { this.events[eventName][selector] = []; } if (this.events[eventName][selector].indexOf(callback) < 0) { this.events[eventName][selector].push(callback); } }
javascript
{ "resource": "" }
q45504
train
function(options) { var extraClass = options.dropdownCssClass ? ' ' + options.dropdownCssClass : '', searchInput = ''; if (options.showSearchInput) { extraClass += ' has-search-input'; var placeholder = options.searchInputPlaceholder; searchInput = '<div class="selectivity-search-input-container">' + '<input type="text" class="selectivity-search-input"' + (placeholder ? ' placeholder="' + escape(placeholder) + '"' : '') + '>' + '</div>'; } return ( '<div class="selectivity-dropdown' + extraClass + '">' + searchInput + '<div class="selectivity-results-container"></div>' + '</div>' ); }
javascript
{ "resource": "" }
q45505
train
function(options) { var extraClass = options.highlighted ? ' highlighted' : ''; return ( '<span class="selectivity-multiple-selected-item' + extraClass + '" ' + 'data-item-id="' + escape(options.id) + '">' + (options.removable ? '<a class="selectivity-multiple-selected-item-remove">' + '<i class="fa fa-remove"></i>' + '</a>' : '') + escape(options.text) + '</span>' ); }
javascript
{ "resource": "" }
q45506
train
function(options) { return ( '<div class="selectivity-result-item' + (options.disabled ? ' disabled' : '') + '"' + ' data-item-id="' + escape(options.id) + '">' + escape(options.text) + (options.submenu ? '<i class="selectivity-submenu-icon fa fa-chevron-right"></i>' : '') + '</div>' ); }
javascript
{ "resource": "" }
q45507
SubmenuPlugin
train
function SubmenuPlugin(selectivity, options) { /** * Optional parent dropdown menu from which this dropdown was opened. */ this.parentMenu = options.parentMenu; Dropdown.call(this, selectivity, options); this._closeSubmenuTimeout = 0; this._openSubmenuTimeout = 0; }
javascript
{ "resource": "" }
q45508
setSelectable
train
function setSelectable(item) { if (item.children) { item.children.forEach(setSelectable); } if (item.submenu) { item.selectable = !!item.selectable; } }
javascript
{ "resource": "" }
q45509
moveHighlight
train
function moveHighlight(dropdown, delta) { var results = dropdown.results; if (!results.length) { return; } var resultItems = [].slice.call(dropdown.el.querySelectorAll('.selectivity-result-item')); function scrollToHighlight() { var el; if (dropdown.highlightedResult) { el = findResultItem(resultItems, dropdown.highlightedResult.id); } else if (dropdown.loadMoreHighlighted) { el = dropdown.$('.selectivity-load-more'); } if (el && el.scrollIntoView) { el.scrollIntoView(delta < 0); } } if (dropdown.submenu) { moveHighlight(dropdown.submenu, delta); return; } var defaultIndex = delta > 0 ? 0 : resultItems.length - 1; var index = defaultIndex; var highlightedResult = dropdown.highlightedResult; if (highlightedResult) { var highlightedResultItem = findResultItem(resultItems, highlightedResult.id); index = resultItems.indexOf(highlightedResultItem) + delta; if (delta > 0 ? index >= resultItems.length : index < 0) { if (dropdown.hasMore) { dropdown.highlightLoadMore(); scrollToHighlight(); return; } else { index = defaultIndex; } } } var resultItem = resultItems[index]; var result = Selectivity.findNestedById(results, selectivity.getRelatedItemId(resultItem)); if (result) { dropdown.highlight(result, { delay: !!result.submenu }); scrollToHighlight(); } }
javascript
{ "resource": "" }
q45510
Selectivity
train
function Selectivity(options) { /** * Reference to the currently open dropdown. */ this.dropdown = null; /** * DOM element to which this instance is attached. */ this.el = options.element; /** * Whether the input is enabled. * * This is false when the option readOnly is false or the option removeOnly is false. */ this.enabled = !options.readOnly && !options.removeOnly; /** * DOM element for the input. * * May be null as long as there is no visible input. It is set by initInput(). */ this.input = null; /** * Array of items from which to select. If set, this will be an array of objects with 'id' and * 'text' properties. * * If given, all items are expected to be available locally and all selection operations operate * on this local array only. If null, items are not available locally, and a query function * should be provided to fetch remote data. */ this.items = null; /** * Options passed to the Selectivity instance or set through setOptions(). */ this.options = {}; /** * Mapping of templates. * * Custom templates can be specified in the options object. */ this.templates = assign({}, Selectivity.Templates); /** * The last used search term. */ this.term = ''; this.setOptions(options); if (options.value) { this.setValue(options.value, { triggerChange: false }); } else { this.setData(options.data || null, { triggerChange: false }); } this.el.setAttribute('tabindex', options.tabIndex || 0); this.events = new EventListener(this.el, this); this.events.on({ blur: this._blur, mouseenter: this._mouseenter, mouseleave: this._mouseleave, 'selectivity-close': this._closed }); }
javascript
{ "resource": "" }
q45511
train
function() { this.events.destruct(); var el = this.el; while (el.firstChild) { el.removeChild(el.firstChild); } el.selectivity = null; }
javascript
{ "resource": "" }
q45512
train
function(id) { var items = this.items; if (items) { return Selectivity.findNestedById(items, id); } else if (id === null) { return null; } else { return { id: id, text: '' + id }; } }
javascript
{ "resource": "" }
q45513
train
function(elementOrEvent) { var el = elementOrEvent.target || elementOrEvent; while (el) { if (el.hasAttribute('data-item-id')) { break; } el = el.parentNode; } if (!el) { return null; } var id = el.getAttribute('data-item-id'); // IDs can be either numbers or strings, but attribute values are always strings, so we // will have to find out whether the item ID ought to be a number or string ourselves. if (Selectivity.findById(this._data || [], id)) { return id; } else { var dropdown = this.dropdown; while (dropdown) { if (Selectivity.findNestedById(dropdown.results, id)) { return id; } // FIXME: reference to submenu plugin doesn't belong in base dropdown = dropdown.submenu; } var number = parseInt(id, 10); return '' + number === id ? number : id; } }
javascript
{ "resource": "" }
q45514
train
function(input, options) { this.input = input; var selectivity = this; var inputListeners = this.options.inputListeners || Selectivity.InputListeners; inputListeners.forEach(function(listener) { listener(selectivity, input, options); }); if (!options || options.search !== false) { input.addEventListener('keyup', function(event) { if (!event.defaultPrevented) { selectivity.search(event.target.value); } }); } }
javascript
{ "resource": "" }
q45515
train
function(newData, options) { options = options || {}; newData = this.validateData(newData); this._data = newData; this._value = this.getValueForData(newData); if (options.triggerChange !== false) { this.triggerChange(); } }
javascript
{ "resource": "" }
q45516
train
function(options) { options = options || {}; var selectivity = this; Selectivity.OptionListeners.forEach(function(listener) { listener(selectivity, options); }); if ('items' in options) { this.items = options.items ? Selectivity.processItems(options.items) : null; } if ('templates' in options) { assign(this.templates, options.templates); } assign(this.options, options); this.enabled = !this.options.readOnly && !this.options.removeOnly; }
javascript
{ "resource": "" }
q45517
train
function(newValue, options) { options = options || {}; newValue = this.validateValue(newValue); this._value = newValue; if (this.options.initSelection) { this.options.initSelection( newValue, function(data) { if (this._value === newValue) { this._data = this.validateData(data); if (options.triggerChange !== false) { this.triggerChange(); } } }.bind(this) ); } else { this._data = this.getDataForValue(newValue); if (options.triggerChange !== false) { this.triggerChange(); } } }
javascript
{ "resource": "" }
q45518
train
function(templateName, options) { var template = this.templates[templateName]; if (!template) { throw new Error('Unknown template: ' + templateName); } if (typeof template === 'function') { var templateResult = template(options); return typeof templateResult === 'string' ? templateResult.trim() : templateResult; } else if (template.render) { return template.render(options).trim(); } else { return template.toString().trim(); } }
javascript
{ "resource": "" }
q45519
train
function(options) { var data = assign({ data: this._data, value: this._value }, options); this.triggerEvent('change', data); this.triggerEvent('selectivity-change', data); }
javascript
{ "resource": "" }
q45520
train
function(eventName, data) { var event = document.createEvent('Event'); event.initEvent(eventName, /* bubbles: */ false, /* cancelable: */ true); assign(event, data); this.el.dispatchEvent(event); return !event.defaultPrevented; }
javascript
{ "resource": "" }
q45521
train
function(item) { if (item && Selectivity.isValidId(item.id) && isString(item.text)) { return item; } else { throw new Error('Item should have id (number or string) and text (string) properties'); } }
javascript
{ "resource": "" }
q45522
EmailInput
train
function EmailInput(options) { MultipleInput.call( this, assign( { createTokenItem: createEmailItem, showDropdown: false, tokenizer: emailTokenizer }, options ) ); this.events.on('blur', function() { var input = this.input; if (input && isValidEmail(lastWord(input.value))) { this.add(createEmailItem(input.value)); } }); }
javascript
{ "resource": "" }
q45523
SelectivityDropdown
train
function SelectivityDropdown(selectivity, options) { this.el = parseElement( selectivity.template('dropdown', { dropdownCssClass: selectivity.options.dropdownCssClass, searchInputPlaceholder: selectivity.options.searchInputPlaceholder, showSearchInput: options.showSearchInput }) ); /** * DOM element to add the results to. */ this.resultsContainer = this.$('.selectivity-results-container'); /** * Boolean indicating whether more results are available than currently displayed in the * dropdown. */ this.hasMore = false; /** * The currently highlighted result item. */ this.highlightedResult = null; /** * Boolean whether the load more link is currently highlighted. */ this.loadMoreHighlighted = false; /** * Options passed to the dropdown constructor. */ this.options = options; /** * The results displayed in the dropdown. */ this.results = []; /** * Selectivity instance. */ this.selectivity = selectivity; this._closed = false; this._lastMousePosition = {}; this.close = this.close.bind(this); this.position = this.position.bind(this); if (selectivity.options.closeOnSelect !== false) { selectivity.events.on('selectivity-selecting', this.close); } this.addToDom(); this.showLoading(); if (options.showSearchInput) { selectivity.initInput(this.$('.selectivity-search-input')); selectivity.focus(); } var events = {}; events['click ' + LOAD_MORE_SELECTOR] = this._loadMoreClicked; events['click ' + RESULT_ITEM_SELECTOR] = this._resultClicked; events['mouseenter ' + LOAD_MORE_SELECTOR] = this._loadMoreHovered; events['mouseenter ' + RESULT_ITEM_SELECTOR] = this._resultHovered; this.events = new EventListener(this.el, this); this.events.on(events); this._attachScrollListeners(); this._suppressWheel(); setTimeout(this.triggerOpen.bind(this), 1); }
javascript
{ "resource": "" }
q45524
train
function() { if (!this._closed) { this._closed = true; removeElement(this.el); this.selectivity.events.off('selectivity-selecting', this.close); this.triggerClose(); this._removeScrollListeners(); } }
javascript
{ "resource": "" }
q45525
train
function(item, options) { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(getItemSelector(RESULT_ITEM_SELECTOR, item.id)), HIGHLIGHT_CLASS, true); this.highlightedResult = item; this.loadMoreHighlighted = false; this.selectivity.triggerEvent('selectivity-highlight', { item: item, id: item.id, reason: (options && options.reason) || 'unspecified' }); }
javascript
{ "resource": "" }
q45526
train
function() { toggleClass(this.$(HIGHLIGHT_SELECTOR), HIGHLIGHT_CLASS, false); toggleClass(this.$(LOAD_MORE_SELECTOR), HIGHLIGHT_CLASS, true); this.highlightedResult = null; this.loadMoreHighlighted = true; }
javascript
{ "resource": "" }
q45527
train
function() { removeElement(this.$(LOAD_MORE_SELECTOR)); this.resultsContainer.innerHTML += this.selectivity.template('loading'); this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { add: true, hasMore: !!response.more }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this._showResults.bind(this, [], { add: true }), offset: this.results.length, selectivity: this.selectivity, term: this.term }); }
javascript
{ "resource": "" }
q45528
train
function(items) { var selectivity = this.selectivity; return items .map(function(item) { var result = selectivity.template(item.id ? 'resultItem' : 'resultLabel', item); if (item.children) { result += selectivity.template('resultChildren', { childrenHtml: this.renderItems(item.children) }); } return result; }, this) .join(''); }
javascript
{ "resource": "" }
q45529
train
function(term) { this.term = term; if (this.options.items) { term = Selectivity.transformText(term); var matcher = this.selectivity.options.matcher || Selectivity.matcher; this._showResults( this.options.items .map(function(item) { return matcher(item, term); }) .filter(function(item) { return !!item; }), { term: term } ); } else if (this.options.query) { this.options.query({ callback: function(response) { if (response && response.results) { this._showResults(Selectivity.processItems(response.results), { hasMore: !!response.more, term: term }); } else { throw new Error('callback must be passed a response object'); } }.bind(this), error: this.showError.bind(this), offset: 0, selectivity: this.selectivity, term: term }); } }
javascript
{ "resource": "" }
q45530
train
function(id) { var item = Selectivity.findNestedById(this.results, id); if (item && !item.disabled && item.selectable !== false) { var options = { id: id, item: item }; if (this.selectivity.triggerEvent('selectivity-selecting', options)) { this.selectivity.triggerEvent('selectivity-selected', options); } } }
javascript
{ "resource": "" }
q45531
train
function(message, options) { this.resultsContainer.innerHTML = this.selectivity.template('error', { escape: !options || options.escape !== false, message: message }); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
javascript
{ "resource": "" }
q45532
train
function() { this.resultsContainer.innerHTML = this.selectivity.template('loading'); this.hasMore = false; this.results = []; this.highlightedResult = null; this.loadMoreHighlighted = false; this.position(); }
javascript
{ "resource": "" }
q45533
train
function(results, options) { if (options.add) { removeElement(this.$('.selectivity-loading')); } else { this.resultsContainer.innerHTML = ''; } var filteredResults = this.selectivity.filterResults(results); var resultsHtml = this.renderItems(filteredResults); if (options.hasMore) { resultsHtml += this.selectivity.template('loadMore'); } else if (!resultsHtml && !options.add) { resultsHtml = this.selectivity.template('noResults', { term: options.term }); } this.resultsContainer.innerHTML += resultsHtml; this.results = options.add ? this.results.concat(results) : results; this.hasMore = options.hasMore; var value = this.selectivity.getValue(); if (value && !Array.isArray(value)) { var item = Selectivity.findNestedById(results, value); if (item) { this.highlight(item, { reason: 'current_value' }); } } else if ( this.options.highlightFirstItem !== false && (!options.add || this.loadMoreHighlighted) ) { this._highlightFirstItem(filteredResults); } this.position(); }
javascript
{ "resource": "" }
q45534
SingleInput
train
function SingleInput(options) { Selectivity.call( this, assign( { // Dropdowns for single-value inputs should open below the select box, unless there // is not enough space below, in which case the dropdown should be moved up just // enough so it fits in the window, but never so much that it reaches above the top. positionDropdown: function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); } }, options ) ); this.rerender(); if (options.showSearchInputInDropdown === false) { this.initInput(this.$('.selectivity-single-select-input'), { search: false }); } this.events.on({ change: this.rerenderSelection, click: this._clicked, 'click .selectivity-search-input': stopPropagation, 'click .selectivity-single-selected-item-remove': this._itemRemoveClicked, 'focus .selectivity-single-select-input': this._focused, 'selectivity-selected': this._resultSelected }); }
javascript
{ "resource": "" }
q45535
train
function(el, selectEl) { var rect = selectEl.getBoundingClientRect(); var dropdownTop = rect.bottom; var deltaUp = Math.min( Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0), rect.top + rect.height ); assign(el.style, { left: rect.left + 'px', top: dropdownTop - deltaUp + 'px', width: rect.width + 'px' }); }
javascript
{ "resource": "" }
q45536
patchEvents
train
function patchEvents($el) { $.each(EVENT_PROPERTIES, function(eventName, properties) { $el.on(eventName, function(event) { if (event.originalEvent) { properties.forEach(function(propertyName) { event[propertyName] = event.originalEvent[propertyName]; }); } }); }); }
javascript
{ "resource": "" }
q45537
LZ4_compress
train
function LZ4_compress (input, options) { var output = [] var encoder = new Encoder(options) encoder.on('data', function (chunk) { output.push(chunk) }) encoder.end(input) return Buffer.concat(output) }
javascript
{ "resource": "" }
q45538
LZ4_uncompress
train
function LZ4_uncompress (input, options) { var output = [] var decoder = new Decoder(options) decoder.on('data', function (chunk) { output.push(chunk) }) decoder.end(input) return Buffer.concat(output) }
javascript
{ "resource": "" }
q45539
colorCoords
train
function colorCoords(channel, color) { let x, y, xmax, ymax; switch (channel) { case 'r': xmax = 255; ymax = 255; x = color.b; y = ymax - color.g; break; case 'g': xmax = 255; ymax = 255; x = color.b; y = ymax - color.r; break; case 'b': xmax = 255; ymax = 255; x = color.r; y = ymax - color.g; break; case 'h': xmax = 100; ymax = 100; x = color.s; y = ymax - color.l; break; case 's': xmax = 360; ymax = 100; x = color.h; y = ymax - color.l; break; case 'l': xmax = 360; ymax = 100; x = color.h; y = ymax - color.s; break; } return { xmax, ymax, x, y }; }
javascript
{ "resource": "" }
q45540
colorCoordValue
train
function colorCoordValue(channel, pos) { const color = {}; pos.x = Math.round(pos.x); pos.y = Math.round(pos.y); switch (channel) { case 'r': color.b = pos.x; color.g = 255 - pos.y; break; case 'g': color.b = pos.x; color.r = 255 - pos.y; break; case 'b': color.r = pos.x; color.g = 255 - pos.y; break; case 'h': color.s = pos.x; color.l = 100 - pos.y; break; case 's': color.h = pos.x; color.l = 100 - pos.y; break; case 'l': color.h = pos.x; color.s = 100 - pos.y; break; } return color; }
javascript
{ "resource": "" }
q45541
train
function(archive) { return { type: "buttercup-archive", exported: Date.now(), format: archive.getFormat(), groups: archive.getGroups().map(group => group.toObject()) }; }
javascript
{ "resource": "" }
q45542
stripDestructiveCommands
train
function stripDestructiveCommands(history) { const destructiveSlugs = Object.keys(Inigo.Command) .map(key => Inigo.Command[key]) .filter(command => command.d) .map(command => command.s); return history.filter(command => { return destructiveSlugs.indexOf(getCommandType(command)) < 0; }); }
javascript
{ "resource": "" }
q45543
rehydrate
train
function rehydrate(dehydratedString) { const { name, id, sourceCredentials, archiveCredentials, type, colour, order } = JSON.parse(dehydratedString); const source = new ArchiveSource(name, sourceCredentials, archiveCredentials, { id, type }); source.type = type; if (colour) { source._colour = colour; } if (order >= 0) { source.order = order; } return source; }
javascript
{ "resource": "" }
q45544
dedupe
train
function dedupe(arr) { return arr.filter(function(item, pos) { return arr.indexOf(item) === pos; }); }
javascript
{ "resource": "" }
q45545
flattenEntries
train
function flattenEntries(archives) { return archives.reduce(function _reduceArchiveEntries(items, archive) { return [ ...items, ...getAllEntries(archive.getGroups()).map(function _expandEntry(entry) { return { entry, archive }; }) ]; }, []); }
javascript
{ "resource": "" }
q45546
train
function(movingGroup, target) { let targetArchive, groupDesc; if (target.type === "Archive") { // destination is an archive targetArchive = target; groupDesc = describe(movingGroup._getRemoteObject(), "0"); } else if (target.type === "Group") { // destination is a group targetArchive = target._getArchive(); groupDesc = describe(movingGroup._getRemoteObject(), target.getID()); } else { throw new Error(`Unknown remote type: ${target.type}`); } // execute each command in the destination archive groupDesc.forEach(function(command) { targetArchive ._getWestley() .execute(command) .pad(); }); // delete movingGroup.delete(/* skip trash */ true); }
javascript
{ "resource": "" }
q45547
deriveKeyFromPassword
train
function deriveKeyFromPassword(password, salt, rounds, bits) { checkBrowserSupport(); const subtleCrypto = window.crypto.subtle; let params = { name: "PBKDF2", hash: "SHA-256", salt: stringToArrayBuffer(salt), iterations: rounds }, bytes = bits / 8, keysLen = bytes / 2; return subtleCrypto .importKey( "raw", stringToArrayBuffer(password), { name: "PBKDF2" }, false, // not extractable ["deriveBits"] ) .then(keyData => subtleCrypto.deriveBits(params, keyData, bits)) .then(derivedData => Promise.all([ subtleCrypto.importKey("raw", derivedData.slice(0, keysLen), "AES-CBC", true, ["encrypt", "decrypt"]), subtleCrypto.importKey("raw", derivedData.slice(keysLen, keysLen * 2), "AES-CBC", true, [ "encrypt", "decrypt" ]) ]) ) .then(aesKeys => Promise.all([subtleCrypto.exportKey("raw", aesKeys[0]), subtleCrypto.exportKey("raw", aesKeys[1])]) ) .then(rawKeys => joinBuffers(rawKeys[0], rawKeys[1])) .then(arrBuff => addHexSupportToArrayBuffer(arrBuff)); // HAXOR }
javascript
{ "resource": "" }
q45548
credentialsToDatasource
train
function credentialsToDatasource(sourceCredentials) { return Promise.resolve() .then(function() { const datasourceDescriptionRaw = sourceCredentials.getValueOrFail("datasource"); const datasourceDescription = typeof datasourceDescriptionRaw === "string" ? JSON.parse(datasourceDescriptionRaw) : datasourceDescriptionRaw; if (typeof datasourceDescription.type !== "string") { throw new VError("Invalid or missing type"); } const datasource = objectToDatasource(datasourceDescription, sourceCredentials); return { datasource, credentials: sourceCredentials }; }) .catch(function __handleCreationError(err) { throw new VError(err, "Failed creating datasources"); }); }
javascript
{ "resource": "" }
q45549
credentialsToSource
train
function credentialsToSource(sourceCredentials, archiveCredentials, initialise = false, contentOverride = null) { let updated = false; const onUpdate = () => { updated = true; }; return credentialsToDatasource(sourceCredentials) .then(function __handleInitialisation(result) { const datasource = result.datasource; const defaultArchive = Archive.createWithDefaults(); if (typeof contentOverride === "string") { datasource.setContent(contentOverride); } datasource.once("updated", onUpdate); return initialise ? datasource.save(defaultArchive.getHistory(), archiveCredentials).then(() => Object.assign( { archive: defaultArchive }, result ) ) : datasource .load(archiveCredentials) .then(history => Archive.createFromHistory(history)) .then(archive => Object.assign( { archive }, result ) ); }) .then(function __datasourceToSource(result) { const workspace = new Workspace(); if (typeof contentOverride === "string") { // Content is overridden, so it cannot be modified: // Setting to readOnly is a safety measure const westley = result.archive._getWestley(); westley.readOnly = true; } result.datasource.removeListener("updated", onUpdate); workspace.setArchive(result.archive, result.datasource, archiveCredentials); return { workspace, sourceCredentials, archiveCredentials, updated }; }); }
javascript
{ "resource": "" }
q45550
applyFieldDescriptor
train
function applyFieldDescriptor(entry, descriptor) { setEntryValue(entry, descriptor.field, descriptor.property, descriptor.value); }
javascript
{ "resource": "" }
q45551
consumeEntryFacade
train
function consumeEntryFacade(entry, facade) { const facadeType = getEntryFacadeType(entry); if (facade && facade.type) { const properties = entry.getProperty(); const attributes = entry.getAttribute(); if (facade.type !== facadeType) { throw new Error(`Failed consuming entry data: Expected type "${facadeType}" but received "${facade.type}"`); } // update data (facade.fields || []).forEach(field => applyFieldDescriptor(entry, field)); // remove missing properties Object.keys(properties).forEach(propKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "property" && property === propKey ); if (typeof correspondingField === "undefined") { entry.deleteProperty(propKey); } }); // remove missing attributes Object.keys(attributes).forEach(attrKey => { const correspondingField = facade.fields.find( ({ field, property }) => field === "attribute" && property === attrKey ); if (typeof correspondingField === "undefined") { entry.deleteAttribute(attrKey); } }); } else { throw new Error("Failed consuming entry data: Invalid item passed as a facade"); } }
javascript
{ "resource": "" }
q45552
setEntryValue
train
function setEntryValue(entry, property, name, value) { switch (property) { case "property": return entry.setProperty(name, value); case "attribute": return entry.setAttribute(name, value); default: throw new Error(`Cannot set value: Unknown property type: ${property}`); } }
javascript
{ "resource": "" }
q45553
train
function(command) { var patt = /("[^"]*")/, quotedStringPlaceholder = "__QUOTEDSTR__", escapedQuotePlaceholder = "__ESCAPED_QUOTE__", matches = [], match; command = command.replace(/\\\"/g, escapedQuotePlaceholder); while ((match = patt.exec(command))) { var matched = match[0]; command = command.substr(0, match.index) + quotedStringPlaceholder + command.substr(match.index + matched.length); matches.push(matched.substring(1, matched.length - 1)); } var parts = command.split(" "); parts = parts.map(function(part) { var item = part.trim(); if (item === quotedStringPlaceholder) { item = matches.shift(); } item = item.replace(new RegExp(escapedQuotePlaceholder, "g"), '"'); return item; }); return parts; }
javascript
{ "resource": "" }
q45554
findEntriesByCheck
train
function findEntriesByCheck(groups, compareFn) { var foundEntries = [], newEntries; groups.forEach(function(group) { newEntries = group.getEntries().filter(compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } newEntries = findEntriesByCheck(group.getGroups(), compareFn); if (newEntries.length > 0) { foundEntries = foundEntries.concat(newEntries); } }); return foundEntries; }
javascript
{ "resource": "" }
q45555
findGroupsByCheck
train
function findGroupsByCheck(groups, compareFn) { var foundGroups = groups.filter(compareFn); groups.forEach(function(group) { var subFound = findGroupsByCheck(group.getGroups(), compareFn); if (subFound.length > 0) { foundGroups = foundGroups.concat(subFound); } }); return foundGroups; }
javascript
{ "resource": "" }
q45556
getAllEntries
train
function getAllEntries(groups) { return groups.reduce(function(current, group) { const theseEntries = group.getEntries(); const subEntries = getAllEntries(group.getGroups()); if (theseEntries.length > 0) { current = current.concat(theseEntries); } if (subEntries.length > 0) { current = current.concat(subEntries); } return current; }, []); }
javascript
{ "resource": "" }
q45557
calculateCommonRecentCommand
train
function calculateCommonRecentCommand(archiveA, archiveB) { var historyA = archiveA._getWestley().getHistory(), historyB = archiveB._getWestley().getHistory(), aLen = historyA.length, bLen = historyB.length, a, b; for (a = aLen - 1; a >= 0; a -= 1) { if (getCommandType(historyA[a]) === "pad") { var paddingA = getPaddingID(historyA[a]); for (b = bLen - 1; b >= 0; b -= 1) { if (getCommandType(historyB[b]) === "pad" && getPaddingID(historyB[b]) === paddingA) { return { a: a, b: b, historyA: historyA, historyB: historyB }; } } } } return false; }
javascript
{ "resource": "" }
q45558
createFieldDescriptor
train
function createFieldDescriptor( entry, title, entryPropertyType, entryPropertyName, { multiline = false, secret = false, formatting = false, removeable = false } = {} ) { const value = getEntryValue(entry, entryPropertyType, entryPropertyName); return { title, field: entryPropertyType, property: entryPropertyName, value, secret, multiline, formatting, removeable }; }
javascript
{ "resource": "" }
q45559
getEntryURLs
train
function getEntryURLs(properties, preference = ENTRY_URL_TYPE_ANY) { const urlRef = Object.keys(properties) .filter(key => URL_PROP.test(key)) .reduce( (output, nextKey) => Object.assign(output, { [nextKey]: properties[nextKey] }), {} ); if (preference === ENTRY_URL_TYPE_GENERAL || preference === ENTRY_URL_TYPE_LOGIN) { return Object.keys(urlRef) .sort((a, b) => { if (preference === ENTRY_URL_TYPE_GENERAL) { const general = /^ur[li]$/i; const aVal = general.test(a) ? 1 : 0; const bVal = general.test(b) ? 1 : 0; return bVal - aVal; } else if (preference === ENTRY_URL_TYPE_LOGIN) { const login = /login/i; const aVal = login.test(a) ? 1 : 0; const bVal = login.test(b) ? 1 : 0; return bVal - aVal; } return 0; }) .map(key => urlRef[key]); } else if (preference === ENTRY_URL_TYPE_ICON) { const iconProp = Object.keys(urlRef).find(key => URL_PROP_ICON.test(key)); return iconProp ? [urlRef[iconProp]] : []; } // Default is "any" URLs return objectValues(urlRef); }
javascript
{ "resource": "" }
q45560
getEntryValue
train
function getEntryValue(entry, property, name) { switch (property) { case "property": return entry.getProperty(name); case "meta": return entry.getMeta(name); case "attribute": return entry.getAttribute(name); default: throw new Error(`Cannot retrieve value: Unknown property type: ${property}`); } }
javascript
{ "resource": "" }
q45561
isValidProperty
train
function isValidProperty(name) { for (var keyName in EntryProperty) { if (EntryProperty.hasOwnProperty(keyName)) { if (EntryProperty[keyName] === name) { return true; } } } return false; }
javascript
{ "resource": "" }
q45562
scheduleExecution
train
function scheduleExecution(step, clearContainerCache, contexts) { if (!scheduledCall) { scheduledCall = { _step: step, _clearContainerCache: clearContainerCache, _contexts: contexts, }; requestAnimationFrame(executeScheduledCall); return; } scheduledCall._step = Math.min(scheduledCall._step, step); // Merge parameters for reevaluate if (scheduledCall._step === 3) { scheduledCall._clearContainerCache = scheduledCall._clearContainerCache || clearContainerCache; if (scheduledCall._contexts && contexts) { scheduledCall._contexts = scheduledCall._contexts.concat(contexts); } } }
javascript
{ "resource": "" }
q45563
startObserving
train
function startObserving() { if (config.skipObserving) { return; } // Reprocess now scheduleExecution(1); window.addEventListener('DOMContentLoaded', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('load', scheduleExecution.bind(undefined, 1, undefined, undefined)); window.addEventListener('resize', scheduleExecution.bind(undefined, 3, true, undefined)); var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; if (MutationObserver) { observer = new MutationObserver(checkMutations); observer.observe(document.documentElement, { childList: true, subtree: true, }); } else { window.addEventListener('DOMNodeInserted', onDomMutate); window.addEventListener('DOMNodeRemoved', onDomMutate); } }
javascript
{ "resource": "" }
q45564
checkMutations
train
function checkMutations(mutations) { // Skip iterating the nodes, if a run is already scheduled, to improve performance if (scheduledCall && (scheduledCall._level < 3 || !scheduledCall._contexts)) { return; } var addedNodes = []; var stylesChanged = false; var replacedSheets = []; processedSheets.forEach(function(newNode) { replacedSheets.push(newNode); }); arrayFrom(mutations).forEach(function(mutation) { addedNodes.push.apply(addedNodes, arrayFrom(mutation.addedNodes).filter(function(node) { return node.nodeType === 1; })); arrayFrom(mutation.removedNodes).forEach(function(node) { var index = addedNodes.indexOf(node); if (index !== -1) { addedNodes.splice(index, 1); } else if ( (node.tagName === 'LINK' || node.tagName === 'STYLE') && replacedSheets.indexOf(node) === -1 ) { stylesChanged = true; } }); }); addedNodes.forEach(function(node) { if (node.sheet && replacedSheets.indexOf(node) === -1) { stylesChanged = true; } }); if (stylesChanged) { scheduleExecution(1); } else if (addedNodes.length) { scheduleExecution(3, false, addedNodes); } }
javascript
{ "resource": "" }
q45565
onDomMutate
train
function onDomMutate(event) { var mutation = { addedNodes: [], removedNodes: [], }; mutation[ (event.type === 'DOMNodeInserted' ? 'added' : 'removed') + 'Nodes' ] = [event.target]; domMutations.push(mutation); // Delay the call to checkMutations() setTimeout(function() { checkMutations(domMutations); domMutations = []; }); }
javascript
{ "resource": "" }
q45566
loadExternal
train
function loadExternal(href, callback) { var cacheEntryType = typeof requestCache[href]; if (cacheEntryType === 'string') { callback(requestCache[href]); return; } else if (cacheEntryType === 'object') { requestCache[href].push(callback); return; } requestCache[href] = [callback] var isDone = false; var done = function(response) { if (!isDone) { response = response || ''; requestCache[href].forEach(function(cachedCallback) { setTimeout(function() { cachedCallback(response); }); }); requestCache[href] = response; } isDone = true; }; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } done(xhr.status === 200 && xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e) { if (window.XDomainRequest) { xhr = new XDomainRequest(); xhr.onprogress = /* istanbul ignore next: fix for a rare IE9 bug */ function() {}; xhr.onload = xhr.onerror = xhr.ontimeout = function() { done(xhr.responseText); }; try { xhr.open('GET', href); xhr.send(); } catch(e2) { done(); } } else { done(); } } }
javascript
{ "resource": "" }
q45567
fixRelativeUrls
train
function fixRelativeUrls(cssText, href) { var base = resolveRelativeUrl(href, document.baseURI); return cssText.replace(URL_VALUE_REGEXP, function(match, quote, url1, url2) { var url = url1 || url2; if (!url) { return match; } return 'url(' + (quote || '"') + resolveRelativeUrl(url, base) + (quote || '"') + ')'; }); }
javascript
{ "resource": "" }
q45568
buildStyleCache
train
function buildStyleCache() { styleCache = { width: {}, height: {}, }; var rules; for (var i = 0; i < styleSheets.length; i++) { if (styleSheets[i].disabled) { continue; } try { rules = styleSheets[i].cssRules; if (!rules || !rules.length) { continue; } } catch(e) { continue; } buildStyleCacheFromRules(rules); } }
javascript
{ "resource": "" }
q45569
updateClassesRead
train
function updateClassesRead(treeNodes, dontMarkAsDone) { var hasChanges = false; var i, node, j, query; for (i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; if (!node._done) { for (j = 0; j < node._queries.length; j++) { query = node._queries[j]; var queryMatches = evaluateQuery(node._element.parentNode, query); if (queryMatches !== hasQuery(node._element, query)) { node._changes.push([queryMatches, query]); } } node._done = !dontMarkAsDone; } hasChanges = updateClassesRead(node._children, dontMarkAsDone || node._changes.length) || node._changes.length || hasChanges; } return hasChanges; }
javascript
{ "resource": "" }
q45570
updateClassesWrite
train
function updateClassesWrite(treeNodes) { var node, j; for (var i = 0; i < treeNodes.length; i++) { node = treeNodes[i]; for (j = 0; j < node._changes.length; j++) { (node._changes[j][0] ? addQuery : removeQuery)(node._element, node._changes[j][1]); } node._changes = []; updateClassesWrite(node._children); } }
javascript
{ "resource": "" }
q45571
buildElementsTree
train
function buildElementsTree(contexts) { contexts = contexts || [document]; var queriesArray = Object.keys(queries).map(function(key) { return queries[key]; }); var selector = queriesArray.map(function(query) { return query._selector; }).join(','); var elements = []; contexts.forEach(function(context) { for (var node = context.parentNode; node; node = node.parentNode) { // Skip nested contexts if (contexts.indexOf(node) !== -1) { return; } } if (context !== document && elementMatchesSelector(context, selector)) { elements.push(context); } elements.push.apply(elements, arrayFrom(context.querySelectorAll(selector))); }); var tree = []; var treeCache = createCacheMap(); elements.forEach(function(element) { if (element === documentElement) { return; } var treeNode = { _element: element, _children: [], _queries: [], _changes: [], _done: false, }; var children = tree; for (var node = element.parentNode; node; node = node.parentNode) { if (treeCache.get(node)) { children = treeCache.get(node)._children; break; } } treeCache.set(element, treeNode); children.push(treeNode); queriesArray.forEach(function(query) { if (elementMatchesSelector(element, query._selector)) { treeNode._queries.push(query); } }); }); return tree; }
javascript
{ "resource": "" }
q45572
evaluateQuery
train
function evaluateQuery(parent, query) { var container = getContainer(parent, query._prop); var qValues = query._values.slice(0); var i; var cValue; if (query._prop === 'width' || query._prop === 'height') { cValue = getSize(container, query._prop); } else { cValue = getComputedStyle(container).getPropertyValue(query._prop); } if (query._filter) { var color = parseColor(cValue); if (query._filter[0] === 'h') { cValue = color[0]; } else if (query._filter[0] === 's') { cValue = color[1]; } else if (query._filter[0] === 'l') { cValue = color[2]; } else if (query._filter[0] === 'a') { cValue = color[3]; } else { return false; } } else if (query._valueType === 'c') { cValue = parseColor(cValue).join(','); } else if (query._valueType === 'l') { for (i = 0; i < qValues.length; i++) { qValues[i] = getComputedLength(qValues[i], parent); } if (typeof cValue === 'string') { cValue = getComputedLength(cValue, parent); } } else if (query._valueType === 'n') { cValue = parseFloat(cValue); } else if (typeof cValue === 'string') { cValue = cValue.trim(); } if (( query._types[0][0] === '>' || query._types[0][0] === '<' ) && ( typeof cValue !== 'number' || typeof qValues[0] !== 'number' )) { return false; } for (i = 0; i < qValues.length; i++) { if (!( (query._types[i] === '>=' && cValue >= qValues[i]) || (query._types[i] === '<=' && cValue <= qValues[i]) || (query._types[i] === '>' && cValue > qValues[i]) || (query._types[i] === '<' && cValue < qValues[i]) || (query._types[i] === '=' && cValue === qValues[i]) )) { return false; } } return true; }
javascript
{ "resource": "" }
q45573
getContainer
train
function getContainer(element, prop) { var cache; if (containerCache.has(element)) { cache = containerCache.get(element); if (cache[prop]) { return cache[prop]; } } else { cache = {}; containerCache.set(element, cache); } if (element === documentElement) { cache[prop] = element; } else if (prop !== 'width' && prop !== 'height') { // Skip transparent background colors if (prop === 'background-color' && !parseColor(getComputedStyle(element).getPropertyValue(prop))[3]) { cache[prop] = getContainer(element.parentNode, prop); } else { cache[prop] = element; } } // Skip inline elements else if (getComputedStyle(element).display === 'inline') { cache[prop] = getContainer(element.parentNode, prop); } else if (isFixedSize(element, prop)) { cache[prop] = element; } else { var parentNode = element.parentNode; // Skip to next positioned ancestor for absolute positioned elements if (getComputedStyle(element).position === 'absolute') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && ['relative', 'absolute'].indexOf(getComputedStyle(parentNode).position) === -1 ) { parentNode = parentNode.parentNode; } } // Skip to next ancestor with a transform applied for fixed positioned elements if (getComputedStyle(element).position === 'fixed') { while ( parentNode.parentNode && parentNode.parentNode.nodeType === 1 && [undefined, 'none'].indexOf( getComputedStyle(parentNode).transform || getComputedStyle(parentNode).MsTransform || getComputedStyle(parentNode).WebkitTransform ) !== -1 ) { parentNode = parentNode.parentNode; } } var parentContainer = getContainer(parentNode, prop); while (getComputedStyle(parentNode).display === 'inline') { parentNode = parentNode.parentNode; } if (parentNode === parentContainer && !isIntrinsicSize(element, prop)) { cache[prop] = element; } else { cache[prop] = parentContainer; } } return cache[prop]; }
javascript
{ "resource": "" }
q45574
isIntrinsicSize
train
function isIntrinsicSize(element, prop) { var computedStyle = getComputedStyle(element); if (computedStyle.display === 'none') { return false; } if (computedStyle.display === 'inline') { return true; } // Non-floating non-absolute block elements (only width) if ( prop === 'width' && ['block', 'list-item', 'flex', 'grid'].indexOf(computedStyle.display) !== -1 && computedStyle.cssFloat === 'none' && computedStyle.position !== 'absolute' && computedStyle.position !== 'fixed' ) { return false; } var originalStyle = getOriginalStyle(element, prop); // Fixed size if (originalStyle && originalStyle.match(LENGTH_REGEXP)) { return false; } // Percentage size if (originalStyle && originalStyle.substr(-1) === '%') { return false; } // Calc expression if (originalStyle && originalStyle.substr(0, 5) === 'calc(') { return false; } // Elements without a defined size return true; }
javascript
{ "resource": "" }
q45575
getSize
train
function getSize(element, prop) { var style = getComputedStyle(element); if (prop === 'width') { return element.offsetWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.paddingLeft) - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight); } else { return element.offsetHeight - parseFloat(style.borderTopWidth) - parseFloat(style.paddingTop) - parseFloat(style.borderBottomWidth) - parseFloat(style.paddingBottom); } }
javascript
{ "resource": "" }
q45576
getComputedLength
train
function getComputedLength(value, element) { var length = value.match(LENGTH_REGEXP); if (!length) { return parseFloat(value); } value = parseFloat(length[1]); var unit = length[2].toLowerCase(); if (FIXED_UNIT_MAP[unit]) { return value * FIXED_UNIT_MAP[unit]; } if (unit === 'vw') { return value * window.innerWidth / 100; } if (unit === 'vh') { return value * window.innerHeight / 100; } if (unit === 'vmin') { return value * Math.min(window.innerWidth, window.innerHeight) / 100; } if (unit === 'vmax') { return value * Math.max(window.innerWidth, window.innerHeight) / 100; } // em units if (unit === 'rem') { element = documentElement; } if (unit === 'ex') { value /= 2; } return parseFloat(getComputedStyle(element).fontSize) * value; }
javascript
{ "resource": "" }
q45577
getOriginalStyle
train
function getOriginalStyle(element, prop) { var matchedRules = []; var value; var j; matchedRules = sortRulesBySpecificity( filterRulesByElementAndProp(styleCache[prop], element, prop) ); // Add style attribute matchedRules.unshift({ _rule: { style: element.style, }, }); // Loop through all important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) === 'important' ) { return value; } } // Loop through all non-important styles for (j = 0; j < matchedRules.length; j++) { if ( (value = matchedRules[j]._rule.style.getPropertyValue(prop)) && matchedRules[j]._rule.style.getPropertyPriority(prop) !== 'important' ) { return value; } } return undefined; }
javascript
{ "resource": "" }
q45578
parseColor
train
function parseColor(color) { // Let the browser round the RGBA values for consistency parseColorStyle.cssText = 'color:' + color; color = parseColorStyle.color; if (!color || !color.split || !color.split('(')[1]) { return [0, 0, 0, 0]; } color = color.split('(')[1].split(',').map(parseFloat); if (color[3] === undefined) { color[3] = 1; } else if (!color[3]) { color[0] = color[1] = color[2] = 0; } color[3] = Math.round(color[3] * 255); return rgbaToHsla(color); }
javascript
{ "resource": "" }
q45579
filterRulesByElementAndProp
train
function filterRulesByElementAndProp(rules, element, prop) { var foundRules = []; if (element.id) { foundRules = foundRules.concat(rules['#' + element.id] || []); } (element.getAttribute('class') || '').split(/\s+/).forEach(function(className) { foundRules = foundRules.concat(rules['.' + className] || []); }); foundRules = foundRules .concat(rules[element.tagName.toLowerCase()] || []) .concat(rules['*'] || []); return foundRules.filter(function(rule) { return rule._rule.style.getPropertyValue(prop) && ( !rule._rule.parentRule || rule._rule.parentRule.type !== 4 // @media rule || matchesMedia(rule._rule.parentRule.media.mediaText) ) && elementMatchesSelector(element, rule._selector); }); }
javascript
{ "resource": "" }
q45580
createCacheMap
train
function createCacheMap() { if (typeof Map === 'function') { return new Map(); } var keys = []; var values = []; function getIndex(key) { return keys.indexOf(key); } function get(key) { return values[getIndex(key)]; } function has(key) { return getIndex(key) !== -1; } function set(key, value) { var index = getIndex(key); if (index === -1) { index = keys.push(key) - 1; } values[index] = value; } function deleteFunc(key) { var index = getIndex(key); if (index === -1) { return false; } delete keys[index]; delete values[index]; return true; } function forEach(callback) { keys.forEach(function(key, index) { if (key !== undefined) { callback(values[index], key); } }); } return { set: set, get: get, has: has, delete: deleteFunc, forEach: forEach, }; }
javascript
{ "resource": "" }
q45581
arrayFrom
train
function arrayFrom(arrayLike) { if (Array.from) { return Array.from(arrayLike); } var array = []; for (var i = 0; i < arrayLike.length; i++) { array[i] = arrayLike[i]; } return array; }
javascript
{ "resource": "" }
q45582
indexOfElementInArray
train
function indexOfElementInArray(element, array) { if (!array) return -1; if (array.indexOf) { return array.indexOf(element); } var len = array.length, i; for (i = 0; i < len; i += 1) { if (array[i] === element) { return i; } } return -1; }
javascript
{ "resource": "" }
q45583
Link
train
function Link(fromId, toId, data, id) { this.fromId = fromId; this.toId = toId; this.data = data; this.id = id; }
javascript
{ "resource": "" }
q45584
train
function(freq, alphabetSize) { // As in BZip2HuffmanStageEncoder.java (from jbzip2): // The Huffman allocator needs its input symbol frequencies to be // sorted, but we need to return code lengths in the same order as // the corresponding frequencies are passed in. // The symbol frequency and index are merged into a single array of // integers - frequency in the high 23 bits, index in the low 9 // bits. // 2^23 = 8,388,608 which is higher than the maximum possible // frequency for one symbol in a block // 2^9 = 512 which is higher than the maximum possible // alphabet size (== 258) // Sorting this array simultaneously sorts the frequencies and // leaves a lookup that can be used to cheaply invert the sort var i, mergedFreq = []; for (i=0; i<alphabetSize; i++) { mergedFreq[i] = (freq[i] << 9) | i; } mergedFreq.sort(function(a,b) { return a-b; }); var sortedFreq = mergedFreq.map(function(v) { return v>>>9; }); // allocate code lengths in place. (result in sortedFreq array) HuffmanAllocator.allocateHuffmanCodeLengths(sortedFreq, MAX_HUFCODE_BITS); // reverse the sort to put codes & code lengths in order of input symbols this.codeLengths = Util.makeU8Buffer(alphabetSize); for (i=0; i<alphabetSize; i++) { var sym = mergedFreq[i] & 0x1FF; this.codeLengths[sym] = sortedFreq[i]; } }
javascript
{ "resource": "" }
q45585
train
function(inStream, block, length, crc) { var pos = 0; var lastChar = -1; var runLength = 0; while (pos < length) { if (runLength===4) { block[pos++] = 0; if (pos >= length) { break; } } var ch = inStream.readByte(); if (ch === EOF) { break; } crc.updateCRC(ch); if (ch !== lastChar) { lastChar = ch; runLength = 1; } else { runLength++; if (runLength > 4) { if (runLength < 256) { block[pos-1]++; continue; } else { runLength = 1; } } } block[pos++] = ch; } return pos; }
javascript
{ "resource": "" }
q45586
train
function(selectors, groups, input) { var i, j, k; for (i=0, k=0; i<input.length; i+=GROUP_SIZE) { var groupSize = Math.min(GROUP_SIZE, input.length - i); var best = 0, bestCost = groups[0].cost(input, i, groupSize); for (j=1; j<groups.length; j++) { var groupCost = groups[j].cost(input, i, groupSize); if (groupCost < bestCost) { best = j; bestCost = groupCost; } } selectors[k++] = best; } }
javascript
{ "resource": "" }
q45587
train
function(array) { var length = array.length; array[0] += array[1]; var headNode, tailNode, topNode, temp; for (headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) { if ((topNode >= length) || (array[headNode] < array[topNode])) { temp = array[headNode]; array[headNode++] = tailNode; } else { temp = array[topNode++]; } if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) { temp += array[headNode]; array[headNode++] = tailNode + length; } else { temp += array[topNode++]; } array[tailNode] = temp; } }
javascript
{ "resource": "" }
q45588
train
function(array, maximumLength) { var currentNode = array.length - 2; var currentDepth; for (currentDepth = 1; (currentDepth < (maximumLength - 1)) && (currentNode > 1); currentDepth++) { currentNode = first (array, currentNode - 1, 0); } return currentNode; }
javascript
{ "resource": "" }
q45589
train
function(array) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth, availableNodes, lastNode, i; for (currentDepth = 1, availableNodes = 2; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = first (array, lastNode - 1, 0); for (i = availableNodes - (lastNode - firstNode); i > 0; i--) { array[nextNode--] = currentDepth; } availableNodes = (lastNode - firstNode) << 1; } }
javascript
{ "resource": "" }
q45590
train
function(array, nodesToMove, insertDepth) { var firstNode = array.length - 2; var nextNode = array.length - 1; var currentDepth = (insertDepth == 1) ? 2 : 1; var nodesLeftToMove = (insertDepth == 1) ? nodesToMove - 2 : nodesToMove; var availableNodes, lastNode, offset, i; for (availableNodes = currentDepth << 1; availableNodes > 0; currentDepth++) { lastNode = firstNode; firstNode = (firstNode <= nodesToMove) ? firstNode : first (array, lastNode - 1, nodesToMove); offset = 0; if (currentDepth >= insertDepth) { offset = Math.min (nodesLeftToMove, 1 << (currentDepth - insertDepth)); } else if (currentDepth == (insertDepth - 1)) { offset = 1; if ((array[firstNode]) == lastNode) { firstNode++; } } for (i = availableNodes - (lastNode - firstNode + offset); i > 0; i--) { array[nextNode--] = currentDepth; } nodesLeftToMove -= offset; availableNodes = (lastNode - firstNode + offset) << 1; } }
javascript
{ "resource": "" }
q45591
train
function(array, maximumLength) { switch (array.length) { case 2: array[1] = 1; case 1: array[0] = 1; return; } /* Pass 1 : Set extended parent pointers */ setExtendedParentPointers (array); /* Pass 2 : Find number of nodes to relocate in order to achieve * maximum code length */ var nodesToRelocate = findNodesToRelocate (array, maximumLength); /* Pass 3 : Generate code lengths */ if ((array[0] % array.length) >= nodesToRelocate) { allocateNodeLengths (array); } else { var insertDepth = maximumLength - (Util.fls(nodesToRelocate - 1)); allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth); } }
javascript
{ "resource": "" }
q45592
train
function(size, extraStates, lgDistanceModelFactory, lengthBitsModelFactory) { var i; var bits = Util.fls(size-1); this.extraStates = +extraStates || 0; this.lgDistanceModel = lgDistanceModelFactory(2*bits + extraStates); // this.distanceModel[n] used for distances which are n-bits long, // but only n-2 bits are encoded: the top bit is known to be one, // and the next bit is encoded by the lgDistanceModel. this.distanceModel = []; for (i=3 ; i <= bits; i++) { var numBits = i - 2; this.distanceModel[i] = lengthBitsModelFactory(1<<numBits); } }
javascript
{ "resource": "" }
q45593
train
function(T, C, n, k) { var i; for (i = 0; i < k; i++) { C[i] = 0; } for (i = 0; i < n; i++) { C[T[i]]++; } }
javascript
{ "resource": "" }
q45594
train
function(T, SA, C, B, n, k) { var b, i, j; var c0, c1; /* compute SAl */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, false); /* find starts of buckets */ j = n - 1; b = B[c1 = T[j]]; j--; SA[b++] = (T[j] < c1) ? ~j : j; for (i = 0; i < n; i++) { if ((j = SA[i]) > 0) { ASSERT(T[j] >= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(i < b); j--; SA[b++] = (T[j] < c1) ? ~j : j; SA[i] = 0; } else if (j < 0) { SA[i] = ~j; } } /* compute SAs */ if (C === B) { getCounts(T, C, n, k); } getBuckets(C, B, k, 1); /* find ends of buckets */ for (i = n-1, b = B[c1 = 0]; i >= 0; i--) { if ((j = SA[i]) > 0) { ASSERT(T[j] <= T[j+1]); if ((c0 = T[j]) !== c1) { B[c1] = b; b = B[c1 = c0]; } ASSERT(b <= i); j--; SA[--b] = (T[j] > c1) ? ~(j+1) : j; SA[i] = 0; } } }
javascript
{ "resource": "" }
q45595
train
function(size, root, bitstream, max_weight) { var i; // default: all alphabet symbols are used console.assert(size && typeof(size)==='number'); if( !root || root > size ) root = size; // create the initial escape node // at the tree root if ( root <<= 1 ) { root--; } // create root+1 htables (coding table) // XXX this could be views on a backing Uint32 array? this.table = []; for (i=0; i<=root; i++) { this.table[i] = new HTable(0,0,0,0); } // this.map => mapping for symbols to nodes this.map = []; // this.size => the alphabet size if( this.size = size ) { for (i=0; i<size; i++) { this.map[i] = 0; } } // this.esc => the current tree height // this.root => the root of the tree this.esc = this.root = root; if (bitstream) { this.readBit = bitstream.readBit.bind(bitstream); this.writeBit = bitstream.writeBit.bind(bitstream); } this.max_weight = max_weight; // may be null or undefined }
javascript
{ "resource": "" }
q45596
pathToLines
train
function pathToLines(path) { var lines = []; var curr = null; path.forEach(function(cmd) { if(cmd[0] == PATH_COMMAND.MOVE) { curr = cmd[1]; } if(cmd[0] == PATH_COMMAND.LINE) { var pt = cmd[1]; lines.push(new Line(curr, pt)); curr = pt; } if(cmd[0] == PATH_COMMAND.QUADRATIC_CURVE) { var pts = [curr, cmd[1], cmd[2]]; for(var t=0; t<1; t+=0.1) { var pt = calcQuadraticAtT(pts,t); lines.push(new Line(curr, pt)); curr = pt; } } if(cmd[0] === PATH_COMMAND.BEZIER_CURVE) { var pts = [curr, cmd[1], cmd[2], cmd[3]]; bezierToLines(pts,10).forEach(pt => { lines.push(new Line(curr,pt)) curr = pt }) } }); return lines; }
javascript
{ "resource": "" }
q45597
calcBezierAtT
train
function calcBezierAtT(p, t) { var x = (1-t)*(1-t)*(1-t)*p[0].x + 3*(1-t)*(1-t)*t*p[1].x + 3*(1-t)*t*t*p[2].x + t*t*t*p[3].x; var y = (1-t)*(1-t)*(1-t)*p[0].y + 3*(1-t)*(1-t)*t*p[1].y + 3*(1-t)*t*t*p[2].y + t*t*t*p[3].y; return new Point(x, y); }
javascript
{ "resource": "" }
q45598
calcMinimumBounds
train
function calcMinimumBounds(lines) { var bounds = { x: Number.MAX_VALUE, y: Number.MAX_VALUE, x2: Number.MIN_VALUE, y2: Number.MIN_VALUE } function checkPoint(pt) { bounds.x = Math.min(bounds.x,pt.x); bounds.y = Math.min(bounds.y,pt.y); bounds.x2 = Math.max(bounds.x2,pt.x); bounds.y2 = Math.max(bounds.y2,pt.y); } lines.forEach(function(line) { checkPoint(line.start); checkPoint(line.end); }) return bounds; }
javascript
{ "resource": "" }
q45599
calcSortedIntersections
train
function calcSortedIntersections(lines,y) { var xlist = []; for(var i=0; i<lines.length; i++) { var A = lines[i].start; var B = lines[i].end; if(A.y<y && B.y>=y || B.y<y && A.y>=y) { var xval = A.x + (y-A.y) / (B.y-A.y) * (B.x-A.x); xlist.push(xval); } } return xlist.sort(function(a,b) { return a-b; }); }
javascript
{ "resource": "" }