_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q58700
getIndicesOfCharacter
validation
function getIndicesOfCharacter( text, characterToFind ) { const indices = []; if ( text.indexOf( characterToFind ) > -1 ) { for ( let i = 0; i < text.length; i++ ) { if ( text[ i ] === characterToFind ) { indices.push( i ); } } } return indices; }
javascript
{ "resource": "" }
q58701
replaceCharactersByIndex
validation
function replaceCharactersByIndex( text, indices, substitute ) { const modifiedTextSplitByLetter = text.split( "" ); indices.forEach( function( index ) { modifiedTextSplitByLetter.splice( index, 1, substitute ); } ); return modifiedTextSplitByLetter.join( "" ); }
javascript
{ "resource": "" }
q58702
validation
function( values ) { this._hasScore = false; this._identifier = ""; this._hasMarks = false; this._marker = emptyMarker; this.score = 0; this.text = ""; this.marks = []; if ( isUndefined( values ) ) { values = {}; } if ( ! isUndefined( values.score ) ) { this.setScore( values.score ); } if ( ! isUndefined( values.text ) ) { this.setText( values.text ); } if ( ! isUndefined( values.marks ) ) { this.setMarks( values.marks ); } }
javascript
{ "resource": "" }
q58703
validation
function( sentence, locale ) { this._sentenceText = sentence || ""; this._locale = locale || defaultAttributes.locale; this._isPassive = false; }
javascript
{ "resource": "" }
q58704
validation
function( app ) { var elems = [ "content", "focusKeyword", "synonyms" ]; for ( var i = 0; i < elems.length; i++ ) { document.getElementById( elems[ i ] ).addEventListener( "input", app.refresh.bind( app ) ); } document.getElementById( "locale" ).addEventListener( "input", setLocale.bind( app ) ); document.getElementById( "premium" ).addEventListener( "input", setPremium.bind( app ) ); }
javascript
{ "resource": "" }
q58705
streamToString
validation
async function streamToString(readableStream) { return new Promise((resolve, reject) => { const chunks = []; readableStream.on("data", data => { chunks.push(data.toString()); }); readableStream.on("end", () => { resolve(chunks.join("")); }); readableStream.on("error", reject); }); }
javascript
{ "resource": "" }
q58706
authenticate
validation
function authenticate() { const authPromtpts = [ { type: "text", name: "username", message: "Username" }, { type: "password", name: "password", message: "Password" } ]; let session; // prompts returns a `Promise` that resolves with the users input return prompts(authPromtpts) .then(({ username, password }) => { session = new UserSession({ username, password }); // this will generate a token and use it to get into about a user return session.getUser(); }) .then(self => { return session; }) .catch(error => { // in case of an `ArcGISRequestError` assume the `username` and `password` // are incorrect run the `authenticate` function again if (error.name === "ArcGISRequestError") { console.log( chalk.bold.red("Incorrect username and/or password please try again") ); return authenticate(); } // if this is a different error just log the error message and exit console.log( `${chalk.bold.red(error.name)} ${chalk.bold.red(error.message)}` ); }); }
javascript
{ "resource": "" }
q58707
searchForItems
validation
function searchForItems(session) { const searchPrompts = [ { type: "text", name: "searchText", message: "Search Query" }, { type: "list", name: "itemTypes", message: "Item Types" }, { type: "list", name: "itemTags", message: "Tags" }, { type: "number", name: "number", message: "How Many?" } ]; // prompts returns a `Promise` that resolves with the users input return prompts(searchPrompts).then( //use ES2015 destructuring so we don't make any extra variables ({ searchText, itemTypes, itemTags, number }) => { const query = new SearchQueryBuilder() .match(session.username) .in("owner"); // format the search query for item types const types = itemTypes.filter(type => type.length); // format the search query for item types if (types.length) { query.and().startGroup(); types.forEach((type, index, types) => { query.match(type).in("type"); if (index !== types.length - 1) { query.or(); } }); query.endGroup(); } // format the search query for item tags const tags = itemTags.filter(tag => tag.length); if (tags.length) { query.and().startGroup(); tags.forEach((tag, index, tags) => { query.match(tag).in("tags"); if (index !== tags.length - 1) { query.or(); } }); query.endGroup(); } // format the search query for the search text if (searchText.length) { query.and().match(searchText); } console.log(chalk.blue(`Searching ArcGIS Online: ${query.toParam()}`)); return searchItems({ authentication: session, q: query, num: number }) .then(response => { return { response, session }; }) .catch(err => { console.warn(err); }) } ); }
javascript
{ "resource": "" }
q58708
deleteItems
validation
async function deleteItems(items, session) { // create our iterator which should return a `Promise` const asyncIterable = { [Symbol.asyncIterator]: () => ({ // every time we ask for a new item next: function() { // remove the next item from the array const item = items.pop(); // we are done if there is no item if (!item) { return Promise.resolve({ done: true }); } // prompt to delete this item. return deleteItem(item, session); } }) }; // lets get our `next` function so we can itterate over it const { next } = asyncIterable[Symbol.asyncIterator](); for ( let { done, deleted, item } = await next(); // start condition, call next and wait for the `Promise` to resolve, results are destructed. !done; // end condition, { done, deleted, item } = await next() // action on every loop, sets up the next round of checks ) { if (deleted) { console.log(chalk.green(`${item.title} deleted successfuly\n`)); } else { console.log(chalk.gray(`${item.title} skipped\n`)); } } // since this is inside an async function code execution is stopped at the loop // this will return an empty resolved `Promise` when the loop is done. return Promise.resolve(); }
javascript
{ "resource": "" }
q58709
validation
function() { // remove the next item from the array const item = items.pop(); // we are done if there is no item if (!item) { return Promise.resolve({ done: true }); } // prompt to delete this item. return deleteItem(item, session); }
javascript
{ "resource": "" }
q58710
validation
function (kb, x, displayables) { var t = kb.findTypeURIs(subject) for (var k = 0; k < displayables.length; k++) { if ($rdf.Util.mediaTypeClass(displayables[k]).uri in t) { return true } } return false }
javascript
{ "resource": "" }
q58711
validation
function (newPaneOptions) { var kb = UI.store var newInstance = newPaneOptions.newInstance if (!newInstance) { let uri = newPaneOptions.newBase if (uri.endsWith('/')) { uri = uri.slice(0, -1) newPaneOptions.newBase = uri } newInstance = kb.sym(uri) } var contentType = mime.lookup(newInstance.uri) if (!contentType || !contentType.includes('html')) { newInstance = $rdf.sym(newInstance.uri + '.html') } newPaneOptions.newInstance = newInstance // Save for creation system console.log('New dokieli will make: ' + newInstance) var htmlContents = DOKIELI_TEMPLATE var filename = newInstance.uri.split('/').slice(-1)[0] filename = decodeURIComponent(filename.split('.')[0]) const encodedTitle = filename.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') htmlContents = htmlContents.replace('<title>', '<title>' + encodedTitle) htmlContents = htmlContents.replace('</article>', '<h1>' + encodedTitle + '</h1></article>') console.log('@@ New HTML for Dok:' + htmlContents) return new Promise(function (resolve, reject) { kb.fetcher.webOperation('PUT', newInstance.uri, { data: htmlContents, contentType: 'text/html' }) .then(function () { console.log('new Dokieli document created at ' + newPaneOptions.newInstance) resolve(newPaneOptions) }).catch(function (err) { console.log('Error creating dokelili dok at ' + newPaneOptions.newInstance + ': ' + err) }) }) }
javascript
{ "resource": "" }
q58712
validation
function (subject) { var kb = UI.store var ns = UI.ns var t = kb.findTypeURIs(subject) if (t[ns.ldp('Resource').uri]) return 'Sharing' // @@ be more sophisticated? if (t[ns.ldp('Container').uri]) return 'Sharing' // @@ be more sophisticated? if (t[ns.ldp('BasicContainer').uri]) return 'Sharing' // @@ be more sophisticated? // check being allowed to see/change shgaring? return null // No under other circumstances }
javascript
{ "resource": "" }
q58713
validation
function (kb, x, contentTypes) { var cts = kb.fetcher.getHeader(x, 'content-type') if (cts) { for (var j = 0; j < cts.length; j++) { for (var k = 0; k < contentTypes.length; k++) { if (cts[j].indexOf(contentTypes[k]) >= 0) { return true } } } } return false }
javascript
{ "resource": "" }
q58714
validation
function () { var query = new $rdf.Query('IRC log entries') var v = [] var vv = ['chan', 'msg', 'date', 'list', 'pred', 'creator', 'content'] vv.map(function (x) { query.vars.push(v[x] = $rdf.variable(x)) }) query.pat.add(v['chan'], ns.foaf('chatEventList'), v['list']) // chatEventList query.pat.add(v['list'], v['pred'], v['msg']) // query.pat.add(v['msg'], ns.dc('date'), v['date']) query.pat.add(v['msg'], ns.dc('creator'), v['creator']) query.pat.add(v['msg'], ns.dc('description'), v['content']) return query }
javascript
{ "resource": "" }
q58715
Click
validation
function Click (e) { var target = UI.utils.getTarget(e) if (UI.utils.getTerm(target).termType !== 'Literal') return this.literalModification(target) // this prevents the generated inputbox to be clicked again e.preventDefault() e.stopPropagation() }
javascript
{ "resource": "" }
q58716
removefromview
validation
function removefromview () { var trIterator for (trIterator = removedTr; trIterator.childNodes.length === 1; trIterator = trIterator.previousSibling); if (trIterator === removedTr) { var theNext = trIterator.nextSibling if (theNext.nextSibling && theNext.childNodes.length === 1) { var predicateTd = trIterator.firstChild predicateTd.setAttribute('rowspan', parseInt(predicateTd.getAttribute('rowspan')) - 1) theNext.insertBefore(trIterator.firstChild, theNext.firstChild) } removedTr.parentNode.removeChild(removedTr) } else { // !DisplayOptions["display:block on"].enabled){ predicateTd = trIterator.firstChild predicateTd.setAttribute('rowspan', parseInt(predicateTd.getAttribute('rowspan')) - 1) removedTr.parentNode.removeChild(removedTr) } }
javascript
{ "resource": "" }
q58717
WildCardButtons
validation
function WildCardButtons () { var menuDiv = myDocument.getElementById(outline.UserInput.menuID) var div = menuDiv.insertBefore(myDocument.createElement('div'), menuDiv.firstChild) var input1 = div.appendChild(myDocument.createElement('input')) var input2 = div.appendChild(myDocument.createElement('input')) input1.type = 'button'; input1.value = 'New...' input2.type = 'button'; input2.value = 'Know its URI' function highlightInput (e) { // same as the one in newMenu() var menu = myDocument.getElementById(outline.UserInput.menuID) if (menu.lastHighlight) menu.lastHighlight.className = '' menu.lastHighlight = UI.utils.ancestor(UI.utils.getTarget(e), 'INPUT') if (!menu.lastHighlight) return // mouseover <TABLE> menu.lastHighlight.className = 'activeItem' } div.addEventListener('mouseover', highlightInput, false) input1.addEventListener('click', this.createNew, false) input2.addEventListener('click', this.inputURI, false) }
javascript
{ "resource": "" }
q58718
validation
function (subject) { var target = kb.any(subject, ns.meeting('target')) || subject var count = kb.each(target, predicate).length if (count > 0) { return UI.utils.label(predicate) + ' ' + count } return null }
javascript
{ "resource": "" }
q58719
validation
function (subject) { var kb = UI.store var t = kb.findTypeURIs(subject) var QU = $rdf.Namespace('http://www.w3.org/2000/10/swap/pim/qif#') var WF = $rdf.Namespace('http://www.w3.org/2005/01/wf/flow#') if (t['http://www.w3.org/ns/pim/trip#Trip'] || // If in any subclass subject.uri === 'http://www.w3.org/ns/pim/trip#Trip' || t['http://www.w3.org/2005/01/wf/flow#Task'] || t['http://www.w3.org/2000/10/swap/pim/qif#Transaction'] || // subject.uri == 'http://www.w3.org/2000/10/swap/pim/qif#Transaction' || QU('Transaction') in kb.findSuperClassesNT(subject) || kb.holds(subject, WF('attachment'))) return 'attachments' return null }
javascript
{ "resource": "" }
q58720
validation
function (kb, subject) { if (kb.updater.editable(subject.doc(), kb)) return subject.doc() var store = kb.any(subject.doc(), QU('annotationStore')) return store }
javascript
{ "resource": "" }
q58721
validation
function (c) { var sortBy = kb.sym({ 'http://www.w3.org/2005/01/wf/flow#Task': 'http://purl.org/dc/elements/1.1/created', 'http://www.w3.org/ns/pim/trip#Trip': // @@ put this into the ontologies 'http://www.w3.org/2002/12/cal/ical#dtstart', 'http://www.w3.org/2000/10/swap/pim/qif#Transaction': 'http://www.w3.org/2000/10/swap/pim/qif#date', 'http://www.w3.org/2000/10/swap/pim/qif#SupportingDocument': 'http://purl.org/dc/elements/1.1/date'}[subject.uri]) if (!sortBy) { sortBy = kb.any(subject, UI.ns.ui('sortBy')) } return sortBy }
javascript
{ "resource": "" }
q58722
validation
function (x, event, selected) { if (selected) { currentSubject = x } else { currentSubject = null if (currentMode === 1) deselectObject() } // If all are displayed, refresh would just annoy: if (currentMode !== 0) showFiltered(currentMode) // Refresh the objects }
javascript
{ "resource": "" }
q58723
validation
function () { var id = mb.getUser(Post.creator).id var xupdateStatus = doc.getElementById('xupdateStatus') var xinReplyToContainer = doc.getElementById('xinReplyToContainer') var xupdateSubmit = doc.getElementById('xupdateSubmit') xupdateStatus.value = '@' + id + ' ' xupdateStatus.focus() xinReplyToContainer.value = post.uri xupdateSubmit.value = 'Reply' }
javascript
{ "resource": "" }
q58724
validation
function (a, success) { if (success) { that.notify('Post deleted.') // update the ui to reflect model changes. var deleteThisNode = evt.target.parentNode deleteThisNode.parentNode.removeChild(deleteThisNode) kb.removeMany(deleteMe) } else { that.notify('Oops, there was a problem, please try again') evt.target.disabled = true } }
javascript
{ "resource": "" }
q58725
validation
function (a, success) { if (success) { var deleteContainer = kb.statementsMatching( undefined, SIOC('container_of'), kb.sym(doc.getElementById( 'post_' + evt.target.parentNode.id).getAttribute('content'))) sparqlUpdater.batch_delete_statement(deleteContainer, mbconfirmDeletePost) } else { that.notify('Oops, there was a problem, please try again') evt.target.disabled = false } }
javascript
{ "resource": "" }
q58726
displayFormsForRelation
validation
function displayFormsForRelation (pred, allowCreation) { var sts = kb.statementsMatching(subject, pred) const outliner = panes.getOutliner(dom) if (sts.length) { for (var i = 0; i < sts.length; i++) { outliner.appendPropertyTRs(box, [ sts[i] ]) var form = sts[i].object var cell = dom.createElement('td') box.lastChild.appendChild(cell) if (allowCreation) { cell.appendChild(UI.widgets.newButton( dom, kb, null, null, subject, form, store, function (ok, body) { if (ok) { // dom.outlineManager.GotoSubject(newThing@@, true, undefined, true, undefined); // rerender(box); // Deleted forms at the moment } else complain('Sorry, failed to save your change:\n' + body) })) } var formdef = kb.statementsMatching(form, ns.rdf('type')) if (!formdef.length) formdef = kb.statementsMatching(form) if (!formdef.length) complain('No data about form') else { UI.widgets.editFormButton(dom, box, form, formdef[0].why, complainIfBad) } } box.appendChild(dom.createElement('hr')) } else { mention('There are currently no known forms to make a ' + label + '.') } }
javascript
{ "resource": "" }
q58727
validation
function (subject) { var kb = UI.store var n = kb.each( undefined, ns.rdf('type'), subject).length if (n > 0) return 'List (' + n + ')' // Show how many in hover text return null // Suppress pane otherwise }
javascript
{ "resource": "" }
q58728
viewAndSaveQuery
validation
function viewAndSaveQuery (outline, selection) { var qs = outline.qs UI.log.info('outline.doucment is now ' + outline.document.location) var q = saveQuery(selection, qs) /* if (tabulator.isExtension) { // tabulator.drawInBestView(q) } else */ for (let i = 0; i < qs.listeners.length; i++) { qs.listeners[i].getActiveView().view.drawQuery(q) qs.listeners[i].updateQueryControls(qs.listeners[i].getActiveView()) } }
javascript
{ "resource": "" }
q58729
validation
function (store, subject) { kb.fetcher.nowOrWhenFetched(store.uri, subject, function (ok, body) { if (!ok) return complain('Cannot load store ' + store.uri + ': ' + body) // Render the forms var forms = UI.widgets.formsFor(subject) // complain('Form for editing this form:'); for (var i = 0; i < forms.length; i++) { var form = forms[i] var heading = dom.createElement('h4') box.appendChild(heading) if (form.uri) { var formStore = $rdf.Util.uri.document(form) if (formStore.uri !== form.uri) { // The form is a hash-type URI var e = box.appendChild(UI.widgets.editFormButton( dom, box, form, formStore, complainIfBad)) e.setAttribute('style', 'float: right;') } } var anchor = dom.createElement('a') anchor.setAttribute('href', form.uri) heading.appendChild(anchor) anchor.textContent = UI.utils.label(form, true) /* Keep tis as a reminder to let a New one have its URI given by user mention("Where will this information be stored?") var ele = dom.createElement('input'); box.appendChild(ele); ele.setAttribute('type', 'text'); ele.setAttribute('size', '72'); ele.setAttribute('maxlength', '1024'); ele.setAttribute('style', 'font-size: 80%; color:#222;'); ele.value = store.uri */ UI.widgets.appendForm(dom, box, {}, subject, form, store, complainIfBad) } }) // end: when store loded }
javascript
{ "resource": "" }
q58730
validation
function (kb, subject, path) { if (path.length === 0) return [ subject ] var oo = kb.each(subject, path[0]) var res = [] for (var i = 0; i < oo.length; i++) { res = res.concat(followeach(kb, oo[i], path.slice(1))) } return res }
javascript
{ "resource": "" }
q58731
validation
function (subject, dom) { var outliner = panes.getOutliner(dom) var kb = UI.store var arg = UI.ns.arg subject = kb.canon(subject) // var types = kb.findTypeURIs(subject) var div = dom.createElement('div') div.setAttribute('class', 'argumentPane') // var title = kb.any(subject, UI.ns.dc('title')) var comment = kb.any(subject, UI.ns.rdfs('comment')) if (comment) { var para = dom.createElement('p') para.setAttribute('style', 'margin-left: 2em; font-style: italic;') div.appendChild(para) para.textContent = comment.value } div.appendChild(dom.createElement('hr')) var plist = kb.statementsMatching(subject, arg('support')) outliner.appendPropertyTRs(div, plist, false) div.appendChild(dom.createElement('hr')) plist = kb.statementsMatching(subject, arg('opposition')) outliner.appendPropertyTRs(div, plist, false) div.appendChild(dom.createElement('hr')) return div }
javascript
{ "resource": "" }
q58732
propertyTree
validation
function propertyTree (subject) { // print('Proprty tree for '+subject) var rep = myDocument.createElement('table') var lastPred = null var sts = subjects[sz.toStr(subject)] // relevant statements if (!sts) { // No statements in tree rep.appendChild(myDocument.createTextNode('...')) // just empty bnode as object return rep } sts.sort() var same = 0 var predicateTD // The cell which holds the predicate for (var i = 0; i < sts.length; i++) { var st = sts[i] var tr = myDocument.createElement('tr') if (st.predicate.uri !== lastPred) { if (lastPred && same > 1) predicateTD.setAttribute('rowspan', '' + same) predicateTD = myDocument.createElement('td') predicateTD.setAttribute('class', 'pred') var anchor = myDocument.createElement('a') anchor.setAttribute('href', st.predicate.uri) anchor.addEventListener('click', UI.widgets.openHrefInOutlineMode, true) anchor.appendChild(myDocument.createTextNode(UI.utils.predicateLabelForXML(st.predicate))) predicateTD.appendChild(anchor) tr.appendChild(predicateTD) lastPred = st.predicate.uri same = 0 } same++ var objectTD = myDocument.createElement('td') objectTD.appendChild(objectTree(st.object)) tr.appendChild(objectTD) rep.appendChild(tr) } if (lastPred && same > 1) predicateTD.setAttribute('rowspan', '' + same) return rep }
javascript
{ "resource": "" }
q58733
objectTree
validation
function objectTree (obj) { var res switch (obj.termType) { case 'NamedNode': let anchor = myDocument.createElement('a') anchor.setAttribute('href', obj.uri) anchor.addEventListener('click', UI.widgets.openHrefInOutlineMode, true) anchor.appendChild(myDocument.createTextNode(UI.utils.label(obj))) return anchor case 'Literal': if (!obj.datatype || !obj.datatype.uri) { res = myDocument.createElement('div') res.setAttribute('style', 'white-space: pre-wrap;') res.textContent = obj.value return res } else if (obj.datatype.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') { res = myDocument.createElement('div') res.setAttribute('class', 'embeddedXHTML') res.innerHTML = obj.value // Try that @@@ beware embedded dangerous code return res } return myDocument.createTextNode(obj.value) // placeholder - could be smarter, case 'BlankNode': if (obj.toNT() in doneBnodes) { // Break infinite recursion referencedBnodes[(obj.toNT())] = true let anchor = myDocument.createElement('a') anchor.setAttribute('href', '#' + obj.toNT().slice(2)) anchor.setAttribute('class', 'bnodeRef') anchor.textContent = '*' + obj.toNT().slice(3) return anchor } doneBnodes[obj.toNT()] = true // Flag to prevent infinite recursion in propertyTree var newTable = propertyTree(obj) doneBnodes[obj.toNT()] = newTable // Track where we mentioned it first if (UI.utils.ancestor(newTable, 'TABLE') && UI.utils.ancestor(newTable, 'TABLE').style.backgroundColor === 'white') { newTable.style.backgroundColor = '#eee' } else { newTable.style.backgroundColor = 'white' } return newTable case 'Collection': res = myDocument.createElement('table') res.setAttribute('class', 'collectionAsTables') for (var i = 0; i < obj.elements.length; i++) { var tr = myDocument.createElement('tr') res.appendChild(tr) tr.appendChild(objectTree(obj.elements[i])) } return res case 'Graph': res = panes.dataContents.statementsAsTables(obj.statements, myDocument) res.setAttribute('class', 'nestedFormula') return res case 'Variable': res = myDocument.createTextNode('?' + obj.uri) return res } throw new Error('Unhandled node type: ' + obj.termType) }
javascript
{ "resource": "" }
q58734
validation
function (subject, myDocument) { function alternativeRendering () { var sz = UI.rdf.Serializer(UI.store) var res = sz.rootSubjects(sts) var roots = res.roots var p = {} p.render = function (s2) { var div = myDocument.createElement('div') div.setAttribute('class', 'withinDocumentPane') var plist = kb.statementsMatching(s2, undefined, undefined, subject) outliner.appendPropertyTRs(div, plist, false, function (pred, inverse) { return true }) return div } for (var i = 0; i < roots.length; i++) { var tr = myDocument.createElement('TR') var root = roots[i] tr.style.verticalAlign = 'top' var td = outliner.outlineObjectTD(root, undefined, tr) tr.appendChild(td) div.appendChild(tr) outliner.outlineExpand(td, root, {'pane': p}) } } function mainRendering () { var initialRoots = [] // Ordering: start with stuff about this doc if (kb.holds(subject, undefined, undefined, subject)) initialRoots.push(subject) // Then about the primary topic of the document if any var ps = kb.any(subject, UI.ns.foaf('primaryTopic'), undefined, subject) if (ps) initialRoots.push(ps) div.appendChild(panes.dataContents.statementsAsTables(sts, myDocument, initialRoots)) } var outliner = panes.getOutliner(myDocument) var kb = UI.store var div = myDocument.createElement('div') div.setAttribute('class', 'dataContentPane') // Because of smushing etc, this will not be a copy of the original source // We could instead either fetch and re-parse the source, // or we could keep all the pre-smushed triples. var sts = kb.statementsMatching(undefined, undefined, undefined, subject) // @@ slow with current store! if ($rdf.keepThisCodeForLaterButDisableFerossConstantConditionPolice) { alternativeRendering() } else { mainRendering() } return div }
javascript
{ "resource": "" }
q58735
validation
function (subject) { var kb = UI.store var ns = UI.ns var t = kb.findTypeURIs(subject) if (t[ns.ldp('Container').uri] || t[ns.ldp('BasicContainer').uri]) { var contents = kb.each(subject, ns.ldp('contains')) var count = 0 contents.map(function (file) { if (UI.widgets.isImage(file)) count++ }) return count > 0 ? 'Slideshow' : null } return null }
javascript
{ "resource": "" }
q58736
removeAndRefresh
validation
function removeAndRefresh (d) { var table = d.parentNode var par = table.parentNode var placeholder = dom.createElement('table') placeholder.setAttribute('style', 'width: 100%;') par.replaceChild(placeholder, table) table.removeChild(d) par.replaceChild(table, placeholder) // Attempt to }
javascript
{ "resource": "" }
q58737
optOnIconMouseDownListener
validation
function optOnIconMouseDownListener (e) { // outlineIcons.src.icon_opton needed? var target = thisOutline.targetOf(e) var p = target.parentNode termWidget.replaceIcon(p.parentNode, outlineIcons.termWidgets.optOn, outlineIcons.termWidgets.optOff, optOffIconMouseDownListener) p.parentNode.parentNode.removeAttribute('optional') }
javascript
{ "resource": "" }
q58738
handleFileSelect
validation
function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); // Get the FileList object that contains the list of files that were dropped var files = evt.dataTransfer.files; // this UI is only built for a single file so just dump the first one dumpFile(files[0]); }
javascript
{ "resource": "" }
q58739
sha1
validation
function sha1(buffer, offset, length) { offset = offset || 0; length = length || buffer.length; var subArray = dicomParser.sharedCopy(buffer, offset, length); var rusha = new Rusha(); return rusha.digest(subArray); }
javascript
{ "resource": "" }
q58740
getMarkdownToTextConverter
validation
function getMarkdownToTextConverter() { const remark = require('remark') const strip = require('strip-markdown') const converter = remark().use(strip) return (md) => String(converter.processSync(md)) }
javascript
{ "resource": "" }
q58741
validation
function(password, count) { // Errors if(!password) throw new Error('Missing argument !'); if(!count || count <= 0) throw new Error('Please provide a count number above 0'); // Processing let data = password; console.time('sha3^n generation time'); for (let i = 0; i < count; ++i) { data = CryptoJS.SHA3(data, { outputLength: 256 }); } console.timeEnd('sha3^n generation time'); // Result return { 'priv': CryptoJS.enc.Hex.stringify(data) }; }
javascript
{ "resource": "" }
q58742
validation
function(privateKey, password) { // Errors if (!privateKey || !password) throw new Error('Missing argument !'); //if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !'); // Processing let pass = derivePassSha(password, 20); let r = encrypt(privateKey, convert.hexToUint8(pass.priv)); // Result return { ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext), iv: convert.uint8ToHex(r.iv) }; }
javascript
{ "resource": "" }
q58743
validation
function(senderPriv, recipientPub, msg) { // Errors if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !'); //if (!Helpers.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !'); //if (!Helpers.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !'); // Processing let iv = nacl.randomBytes(16) //console.log("IV:", convert.uint8ToHex(iv)); let salt = nacl.randomBytes(32) let encoded = _encode(senderPriv, recipientPub, msg, iv, salt); // Result return encoded; }
javascript
{ "resource": "" }
q58744
validation
function(recipientPrivate, senderPublic, _payload) { // Errorsp if(!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !'); // Processing let binPayload = convert.hexToUint8(_payload); let salt = new Uint8Array(binPayload.buffer, 0, 32); let iv = new Uint8Array(binPayload.buffer, 32, 16); let payload = new Uint8Array(binPayload.buffer, 48); let keyPair = createKeyPairFromPrivateKeyString(recipientPrivate); let pk = convert.hexToUint8(senderPublic); let encKey = deriveSharedKey(keyPair, pk, salt); let encIv = { iv: ua2words(iv, 16) }; let encrypted = { 'ciphertext': ua2words(payload, payload.length) }; let plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv); // Result let hexplain = CryptoJS.enc.Hex.stringify(plain); return hexplain; }
javascript
{ "resource": "" }
q58745
validation
function(ua, uaLength) { let temp = []; for (let i = 0; i < uaLength; i += 4) { let x = ua[i] * 0x1000000 + (ua[i + 1] || 0) * 0x10000 + (ua[i + 2] || 0) * 0x100 + (ua[i + 3] || 0); temp.push((x > 0x7fffffff) ? x - 0x100000000 : x); } return CryptoJS.lib.WordArray.create(temp, uaLength); }
javascript
{ "resource": "" }
q58746
validation
function(destUa, cryptowords) { for (let i = 0; i < destUa.length; i += 4) { let v = cryptowords.words[i / 4]; if (v < 0) v += 0x100000000; destUa[i] = (v >>> 24); destUa[i + 1] = (v >>> 16) & 0xff; destUa[i + 2] = (v >>> 8) & 0xff; destUa[i + 3] = v & 0xff; } return destUa; }
javascript
{ "resource": "" }
q58747
validation
function(p) { var dx = p.x - this.x, dy = p.y - this.y; return dx * dx + dy * dy; }
javascript
{ "resource": "" }
q58748
validation
function(e) { var self = this; // necessary for mobile webkit devices (manual focus triggering // is ignored unless invoked within a click event) // also necessary to reopen a dropdown that has been closed by // closeAfterSelect if (!self.isFocused || !self.isOpen) { self.focus(); e.preventDefault(); } }
javascript
{ "resource": "" }
q58749
validation
function(data) { var key = hash_key(data[this.settings.valueField]); if (typeof key === 'undefined' || key === null || this.options.hasOwnProperty(key)) return false; data.$order = data.$order || ++this.order; this.options[key] = data; return key; }
javascript
{ "resource": "" }
q58750
validation
function() { var self = this; self.loadedSearches = {}; self.userOptions = {}; self.renderCache = {}; var options = self.options; $.each(self.options, function(key, value) { if(self.items.indexOf(key) == -1) { delete options[key]; } }); self.options = self.sifter.items = options; self.lastQuery = null; self.trigger('option_clear'); }
javascript
{ "resource": "" }
q58751
validation
function(values, silent) { this.buffer = document.createDocumentFragment(); var childNodes = this.$control[0].childNodes; for (var i = 0; i < childNodes.length; i++) { this.buffer.appendChild(childNodes[i]); } var items = $.isArray(values) ? values : [values]; for (var i = 0, n = items.length; i < n; i++) { this.isPending = (i < n - 1); this.addItem(items[i], silent); } var control = this.$control[0]; control.insertBefore(this.buffer, control.firstChild); this.buffer = null; }
javascript
{ "resource": "" }
q58752
validation
function(value, silent) { var self = this; var $item, i, idx; $item = (value instanceof $) ? value : self.getItem(value); value = hash_key($item.attr('data-value')); i = self.items.indexOf(value); if (i !== -1) { $item.remove(); if ($item.hasClass('active')) { idx = self.$activeItems.indexOf($item[0]); self.$activeItems.splice(idx, 1); } self.items.splice(i, 1); self.lastQuery = null; if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) { self.removeOption(value, silent); } if (i < self.caretPos) { self.setCaret(self.caretPos - 1); } self.refreshState(); self.updatePlaceholder(); self.updateOriginalInput({silent: silent}); self.positionDropdown(); self.trigger('item_remove', value, $item); } }
javascript
{ "resource": "" }
q58753
validation
function() { if (!this.isRequired) return false; var invalid = !this.items.length; this.isInvalid = invalid; this.$control_input.prop('required', invalid); this.$input.prop('required', !invalid); }
javascript
{ "resource": "" }
q58754
validation
function() { var self = this; var trigger = self.isOpen; if (self.settings.mode === 'single' && self.items.length) { self.hideInput(); // Do not trigger blur while inside a blur event, // this fixes some weird tabbing behavior in FF and IE. // See #1164 if (!self.isBlurring) { self.$control_input.blur(); // close keyboard on iOS } } self.isOpen = false; self.$dropdown.hide(); self.setActiveOption(null); self.refreshState(); if (trigger) self.trigger('dropdown_close', self.$dropdown); }
javascript
{ "resource": "" }
q58755
validation
function($el) { var caret = Math.min(this.caretPos, this.items.length); var el = $el[0]; var target = this.buffer || this.$control[0]; if (caret === 0) { target.insertBefore(el, target.firstChild); } else { target.insertBefore(el, target.childNodes[caret]); } this.setCaret(caret + 1); }
javascript
{ "resource": "" }
q58756
validation
function(templateName, data) { var value, id, label; var html = ''; var cache = false; var self = this; var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i; if (templateName === 'option' || templateName === 'item') { value = hash_key(data[self.settings.valueField]); cache = !!value; } // pull markup from cache if it exists if (cache) { if (!isset(self.renderCache[templateName])) { self.renderCache[templateName] = {}; } if (self.renderCache[templateName].hasOwnProperty(value)) { return self.renderCache[templateName][value]; } } // render markup html = $(self.settings.render[templateName].apply(this, [data, escape_html])); // add mandatory attributes if (templateName === 'option' || templateName === 'option_create') { if (!data[self.settings.disabledField]) { html.attr('data-selectable', ''); } } else if (templateName === 'optgroup') { id = data[self.settings.optgroupValueField] || ''; html.attr('data-group', id); if(data[self.settings.disabledField]) { html.attr('data-disabled', ''); } } if (templateName === 'option' || templateName === 'item') { html.attr('data-value', value || ''); } // update cache if (cache) { self.renderCache[templateName][value] = html[0]; } return html[0]; }
javascript
{ "resource": "" }
q58757
updateMetrics
validation
function updateMetrics() { isVwDirty = false; DPR = window.devicePixelRatio; cssCache = {}; sizeLengthCache = {}; pf.DPR = DPR || 1; units.width = Math.max(window.innerWidth || 0, docElem.clientWidth); units.height = Math.max(window.innerHeight || 0, docElem.clientHeight); units.vw = units.width / 100; units.vh = units.height / 100; evalId = [ units.height, units.width, DPR ].join("-"); units.em = pf.getEmValue(); units.rem = units.em; }
javascript
{ "resource": "" }
q58758
parseDescriptors
validation
function parseDescriptors() { // 9. Descriptor parser: Let error be no. var pError = false, // 10. Let width be absent. // 11. Let density be absent. // 12. Let future-compat-h be absent. (We're implementing it now as h) w, d, h, i, candidate = {}, desc, lastChar, value, intVal, floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps // from the following list: for (i = 0 ; i < descriptors.length; i++) { desc = descriptors[ i ]; lastChar = desc[ desc.length - 1 ]; value = desc.substring(0, desc.length - 1); intVal = parseInt(value, 10); floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by // a U+0077 LATIN SMALL LETTER W character if (regexNonNegativeInteger.test(value) && (lastChar === "w")) { // If width and density are not both absent, then let error be yes. if (w || d) {pError = true;} // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. // Otherwise, let width be the result. if (intVal === 0) {pError = true;} else {w = intVal;} // If the descriptor consists of a valid floating-point number followed by // a U+0078 LATIN SMALL LETTER X character } else if (regexFloatingPoint.test(value) && (lastChar === "x")) { // If width, density and future-compat-h are not all absent, then let error // be yes. if (w || d || h) {pError = true;} // Apply the rules for parsing floating-point number values to the descriptor. // If the result is less than zero, let error be yes. Otherwise, let density // be the result. if (floatVal < 0) {pError = true;} else {d = floatVal;} // If the descriptor consists of a valid non-negative integer followed by // a U+0068 LATIN SMALL LETTER H character } else if (regexNonNegativeInteger.test(value) && (lastChar === "h")) { // If height and density are not both absent, then let error be yes. if (h || d) {pError = true;} // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. Otherwise, let future-compat-h // be the result. if (intVal === 0) {pError = true;} else {h = intVal;} // Anything else, Let error be yes. } else {pError = true;} } // (close step 13 for loop) // 15. If error is still no, then append a new image source to candidates whose // URL is url, associated with a width width if not absent and a pixel // density density if not absent. Otherwise, there is a parse error. if (!pError) { candidate.url = url; if (w) { candidate.w = w;} if (d) { candidate.d = d;} if (h) { candidate.h = h;} if (!h && !d && !w) {candidate.d = 1;} if (candidate.d === 1) {set.has1x = true;} candidate.set = set; candidates.push(candidate); } }
javascript
{ "resource": "" }
q58759
extend
validation
function extend(style, rule, sheet, newStyle = {}) { mergeExtend(style, rule, sheet, newStyle) mergeRest(style, rule, sheet, newStyle) return newStyle }
javascript
{ "resource": "" }
q58760
convertCase
validation
function convertCase(style) { const converted = {} for (const prop in style) { const key = prop.indexOf('--') === 0 ? prop : hyphenate(prop) converted[key] = style[prop] } if (style.fallbacks) { if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase) else converted.fallbacks = convertCase(style.fallbacks) } return converted }
javascript
{ "resource": "" }
q58761
ResourceNamespace
validation
function ResourceNamespace(stripe, resources) { for (var name in resources) { var camelCaseName = name[0].toLowerCase() + name.substring(1); var resource = new resources[name](stripe); this[camelCaseName] = resource; } }
javascript
{ "resource": "" }
q58762
validation
function(args) { if (args.length < 1 || !isPlainObject(args[0])) { return {}; } if (!utils.isOptionsHash(args[0])) { return args.shift(); } var argKeys = Object.keys(args[0]); var optionKeysInArgs = argKeys.filter(function(key) { return OPTIONS_KEYS.indexOf(key) > -1; }); // In some cases options may be the provided as the first argument. // Here we're detecting a case where there are two distinct arguments // (the first being args and the second options) and with known // option keys in the first so that we can warn the user about it. if (optionKeysInArgs.length > 0 && optionKeysInArgs.length !== argKeys.length) { emitWarning( 'Options found in arguments (' + optionKeysInArgs.join(', ') + '). Did you mean to pass an options ' + 'object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.' ); } return {}; }
javascript
{ "resource": "" }
q58763
validation
function(args) { var opts = { auth: null, headers: {}, }; if (args.length > 0) { var arg = args[args.length - 1]; if (utils.isAuthKey(arg)) { opts.auth = args.pop(); } else if (utils.isOptionsHash(arg)) { var params = args.pop(); var extraKeys = Object.keys(params).filter(function(key) { return OPTIONS_KEYS.indexOf(key) == -1; }); if (extraKeys.length) { emitWarning('Invalid options found (' + extraKeys.join(', ') + '); ignoring.'); } if (params.api_key) { opts.auth = params.api_key; } if (params.idempotency_key) { opts.headers['Idempotency-Key'] = params.idempotency_key; } if (params.stripe_account) { opts.headers['Stripe-Account'] = params.stripe_account; } if (params.stripe_version) { opts.headers['Stripe-Version'] = params.stripe_version; } } } return opts; }
javascript
{ "resource": "" }
q58764
validation
function(sub) { var Super = this; var Constructor = hasOwn.call(sub, 'constructor') ? sub.constructor : function() { Super.apply(this, arguments); }; // This initialization logic is somewhat sensitive to be compatible with // divergent JS implementations like the one found in Qt. See here for more // context: // // https://github.com/stripe/stripe-node/pull/334 Object.assign(Constructor, Super); Constructor.prototype = Object.create(Super.prototype); Object.assign(Constructor.prototype, sub); return Constructor; }
javascript
{ "resource": "" }
q58765
validation
function(obj) { if (typeof obj !== 'object') { throw new Error('Argument must be an object'); } Object.keys(obj).forEach(function(key) { if (obj[key] === null || obj[key] === undefined) { delete obj[key]; } }); return obj; }
javascript
{ "resource": "" }
q58766
safeExec
validation
function safeExec(cmd, cb) { try { utils._exec(cmd, cb); } catch (e) { cb(e, null); } }
javascript
{ "resource": "" }
q58767
validation
function(opts) { if (!opts) { throw new Error.StripeError({ message: 'Options are required', }); } opts.timestamp = Math.floor(opts.timestamp) || Math.floor(Date.now() / 1000); opts.scheme = opts.scheme || signature.EXPECTED_SCHEME; opts.signature = opts.signature || signature._computeSignature(opts.timestamp + '.' + opts.payload, opts.secret); var generatedHeader = [ 't=' + opts.timestamp, opts.scheme + '=' + opts.signature, ].join(','); return generatedHeader; }
javascript
{ "resource": "" }
q58768
StripeResource
validation
function StripeResource(stripe, urlData) { this._stripe = stripe; this._urlData = urlData || {}; this.basePath = utils.makeURLInterpolator(this.basePath || stripe.getApiField('basePath')); this.resourcePath = this.path; this.path = utils.makeURLInterpolator(this.path); if (this.includeBasic) { this.includeBasic.forEach(function(methodName) { this[methodName] = StripeResource.BASIC_METHODS[methodName]; }, this); } this.initialize.apply(this, arguments); }
javascript
{ "resource": "" }
q58769
stripeMethod
validation
function stripeMethod(spec) { return function() { var self = this; var args = [].slice.call(arguments); var callback = typeof args[args.length - 1] == 'function' && args.pop(); var requestPromise = utils.callbackifyPromiseWithTimeout(makeRequest(self, args, spec, {}), callback) if (spec.methodType === 'list') { var autoPaginationMethods = makeAutoPaginationMethods(self, args, spec, requestPromise); Object.assign(requestPromise, autoPaginationMethods); } return requestPromise; }; }
javascript
{ "resource": "" }
q58770
validation
function(cb) { if (Stripe.USER_AGENT_SERIALIZED) { return cb(Stripe.USER_AGENT_SERIALIZED); } this.getClientUserAgentSeeded(Stripe.USER_AGENT, function(cua) { Stripe.USER_AGENT_SERIALIZED = cua; cb(Stripe.USER_AGENT_SERIALIZED); }) }
javascript
{ "resource": "" }
q58771
validation
function(seed, cb) { var self = this; utils.safeExec('uname -a', function(err, uname) { var userAgent = {}; for (var field in seed) { userAgent[field] = encodeURIComponent(seed[field]); } // URI-encode in case there are unusual characters in the system's uname. userAgent.uname = encodeURIComponent(uname || 'UNKNOWN'); if (self._appInfo) { userAgent.application = self._appInfo; } cb(JSON.stringify(userAgent)) }); }
javascript
{ "resource": "" }
q58772
createSharingUrl
validation
function createSharingUrl (network) { return this.baseNetworks[network].sharer .replace(/@url/g, encodeURIComponent(this.url)) .replace(/@title/g, encodeURIComponent(this.title)) .replace(/@description/g, encodeURIComponent(this.description)) .replace(/@quote/g, encodeURIComponent(this.quote)) .replace(/@hashtags/g, this.generateHashtags(network, this.hashtags)) .replace(/@media/g, this.media) .replace(/@twitteruser/g, this.twitterUser ? '&via=' + this.twitterUser : ''); }
javascript
{ "resource": "" }
q58773
share
validation
function share (network) { this.openSharer(network, this.createSharingUrl(network)); this.$root.$emit('social_shares_open', network, this.url); this.$emit('open', network, this.url); }
javascript
{ "resource": "" }
q58774
touch
validation
function touch (network) { window.open(this.createSharingUrl(network), '_self'); this.$root.$emit('social_shares_open', network, this.url); this.$emit('open', network, this.url); }
javascript
{ "resource": "" }
q58775
openSharer
validation
function openSharer (network, url) { var this$1 = this; // If a popup window already exist it will be replaced, trigger a close event. var popupWindow = null; if (popupWindow && this.popup.interval) { clearInterval(this.popup.interval); popupWindow.close();// Force close (for Facebook) this.$root.$emit('social_shares_change', network, this.url); this.$emit('change', network, this.url); } popupWindow = window.open( url, 'sharer', 'status=' + (this.popup.status ? 'yes' : 'no') + ',height=' + this.popup.height + ',width=' + this.popup.width + ',resizable=' + (this.popup.resizable ? 'yes' : 'no') + ',left=' + this.popup.left + ',top=' + this.popup.top + ',screenX=' + this.popup.left + ',screenY=' + this.popup.top + ',toolbar=' + (this.popup.toolbar ? 'yes' : 'no') + ',menubar=' + (this.popup.menubar ? 'yes' : 'no') + ',scrollbars=' + (this.popup.scrollbars ? 'yes' : 'no') + ',location=' + (this.popup.location ? 'yes' : 'no') + ',directories=' + (this.popup.directories ? 'yes' : 'no') ); popupWindow.focus(); // Create an interval to detect popup closing event this.popup.interval = setInterval(function () { if (popupWindow.closed) { clearInterval(this$1.popup.interval); popupWindow = undefined; this$1.$root.$emit('social_shares_close', network, this$1.url); this$1.$emit('close', network, this$1.url); } }, 500); }
javascript
{ "resource": "" }
q58776
mounted
validation
function mounted () { if (!inBrowser) { return; } /** * Center the popup on dual screens * http://stackoverflow.com/questions/4068373/center-a-popup-window-on-screen/32261263 */ var dualScreenLeft = $window.screenLeft !== undefined ? $window.screenLeft : screen.left; var dualScreenTop = $window.screenTop !== undefined ? $window.screenTop : screen.top; var width = $window.innerWidth ? $window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width); var height = $window.innerHeight ? $window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height); this.popup.left = ((width / 2) - (this.popup.width / 2)) + dualScreenLeft; this.popup.top = ((height / 2) - (this.popup.height / 2)) + dualScreenTop; }
javascript
{ "resource": "" }
q58777
loadAndParseFile
validation
function loadAndParseFile(filename, settings, nextFile) { if (settings.debug) { debug('loadAndParseFile(\'' + filename +'\')'); debug('totalFiles: ' + settings.totalFiles); debug('filesLoaded: ' + settings.filesLoaded); } if (filename !== null && typeof filename !== 'undefined') { $.ajax({ url: filename, async: settings.async, cache: settings.cache, dataType: 'text', success: function (data, status) { if (settings.debug) { debug('Succeeded in downloading ' + filename + '.'); debug(data); } parseData(data, settings); nextFile(); }, error: function (jqXHR, textStatus, errorThrown) { if (settings.debug) { debug('Failed to download or parse ' + filename + '. errorThrown: ' + errorThrown); } if (jqXHR.status === 404) { settings.totalFiles -= 1; } nextFile(); } }); } }
javascript
{ "resource": "" }
q58778
validation
function(event, g) { var chartPos = utils.findPos(g.canvas_); var box = { left: chartPos.x, right: chartPos.x + g.canvas_.offsetWidth, top: chartPos.y, bottom: chartPos.y + g.canvas_.offsetHeight }; var pt = { x: utils.pageX(event), y: utils.pageY(event) }; var dx = distanceFromInterval(pt.x, box.left, box.right), dy = distanceFromInterval(pt.y, box.top, box.bottom); return Math.max(dx, dy); }
javascript
{ "resource": "" }
q58779
validation
function(event, g, context) { // Right-click should not initiate a zoom. if (event.button && event.button == 2) return; context.initializeMouseDown(event, g, context); if (event.altKey || event.shiftKey) { DygraphInteraction.startPan(event, g, context); } else { DygraphInteraction.startZoom(event, g, context); } // Note: we register mousemove/mouseup on document to allow some leeway for // events to move outside of the chart. Interaction model events get // registered on the canvas, which is too small to allow this. var mousemove = function(event) { if (context.isZooming) { // When the mouse moves >200px from the chart edge, cancel the zoom. var d = distanceFromChart(event, g); if (d < DRAG_EDGE_MARGIN) { DygraphInteraction.moveZoom(event, g, context); } else { if (context.dragEndX !== null) { context.dragEndX = null; context.dragEndY = null; g.clearZoomRect_(); } } } else if (context.isPanning) { DygraphInteraction.movePan(event, g, context); } }; var mouseup = function(event) { if (context.isZooming) { if (context.dragEndX !== null) { DygraphInteraction.endZoom(event, g, context); } else { DygraphInteraction.maybeTreatMouseOpAsClick(event, g, context); } } else if (context.isPanning) { DygraphInteraction.endPan(event, g, context); } utils.removeEvent(document, 'mousemove', mousemove); utils.removeEvent(document, 'mouseup', mouseup); context.destroy(); }; g.addAndTrackEvent(document, 'mousemove', mousemove); g.addAndTrackEvent(document, 'mouseup', mouseup); }
javascript
{ "resource": "" }
q58780
validation
function(event, g, context) { if (context.cancelNextDblclick) { context.cancelNextDblclick = false; return; } // Give plugins a chance to grab this event. var e = { canvasx: context.dragEndX, canvasy: context.dragEndY, cancelable: true, }; if (g.cascadeEvents_('dblclick', e)) { return; } if (event.altKey || event.shiftKey) { return; } g.resetZoom(); }
javascript
{ "resource": "" }
q58781
getControlPoints
validation
function getControlPoints(p0, p1, p2, opt_alpha, opt_allowFalseExtrema) { var alpha = (opt_alpha !== undefined) ? opt_alpha : 1/3; // 0=no smoothing, 1=crazy smoothing var allowFalseExtrema = opt_allowFalseExtrema || false; if (!p2) { return [p1.x, p1.y, null, null]; } // Step 1: Position the control points along each line segment. var l1x = (1 - alpha) * p1.x + alpha * p0.x, l1y = (1 - alpha) * p1.y + alpha * p0.y, r1x = (1 - alpha) * p1.x + alpha * p2.x, r1y = (1 - alpha) * p1.y + alpha * p2.y; // Step 2: shift the points up so that p1 is on the l1–r1 line. if (l1x != r1x) { // This can be derived w/ some basic algebra. var deltaY = p1.y - r1y - (p1.x - r1x) * (l1y - r1y) / (l1x - r1x); l1y += deltaY; r1y += deltaY; } // Step 3: correct to avoid false extrema. if (!allowFalseExtrema) { if (l1y > p0.y && l1y > p1.y) { l1y = Math.max(p0.y, p1.y); r1y = 2 * p1.y - l1y; } else if (l1y < p0.y && l1y < p1.y) { l1y = Math.min(p0.y, p1.y); r1y = 2 * p1.y - l1y; } if (r1y > p1.y && r1y > p2.y) { r1y = Math.max(p1.y, p2.y); l1y = 2 * p1.y - r1y; } else if (r1y < p1.y && r1y < p2.y) { r1y = Math.min(p1.y, p2.y); l1y = 2 * p1.y - r1y; } } return [l1x, l1y, r1x, r1y]; }
javascript
{ "resource": "" }
q58782
validation
function(dygraph) { this.dygraph_ = dygraph; /** * Array of points for each series. * * [series index][row index in series] = |Point| structure, * where series index refers to visible series only, and the * point index is for the reduced set of points for the current * zoom region (including one point just outside the window). * All points in the same row index share the same X value. * * @type {Array.<Array.<Dygraph.PointType>>} */ this.points = []; this.setNames = []; this.annotations = []; this.yAxes_ = null; // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and // yticks are outputs. Clean this up. this.xTicks_ = null; this.yTicks_ = null; }
javascript
{ "resource": "" }
q58783
validation
function(event, g, contextB) { // prevents mouse drags from selecting page text. if (event.preventDefault) { event.preventDefault(); // Firefox, Chrome, etc. } else { event.returnValue = false; // IE event.cancelBubble = true; } var canvasPos = utils.findPos(g.canvas_); contextB.px = canvasPos.x; contextB.py = canvasPos.y; contextB.dragStartX = utils.dragGetX_(event, contextB); contextB.dragStartY = utils.dragGetY_(event, contextB); contextB.cancelNextDblclick = false; contextB.tarp.cover(); }
javascript
{ "resource": "" }
q58784
validation
function(idx) { // If we've previously found a non-NaN point and haven't gone past it yet, // just use that. if (nextPointIdx >= idx) return; // We haven't found a non-NaN point yet or have moved past it, // look towards the right to find a non-NaN point. for (var j = idx; j < points.length; ++j) { // Clear out a previously-found point (if any) since it's no longer // valid, we shouldn't use it for interpolation anymore. nextPoint = null; if (!isNaN(points[j].yval) && points[j].yval !== null) { nextPointIdx = j; nextPoint = points[j]; break; } } }
javascript
{ "resource": "" }
q58785
validateNativeFormat
validation
function validateNativeFormat(data) { const firstRow = data[0]; const firstX = firstRow[0]; if (typeof firstX !== 'number' && !utils.isDateLike(firstX)) { throw new Error(`Expected number or date but got ${typeof firstX}: ${firstX}.`); } for (let i = 1; i < firstRow.length; i++) { const val = firstRow[i]; if (val === null || val === undefined) continue; if (typeof val === 'number') continue; if (utils.isArrayLike(val)) continue; // e.g. error bars or custom bars. throw new Error(`Expected number or array but got ${typeof val}: ${val}.`); } }
javascript
{ "resource": "" }
q58786
validation
function(opt_options) { this.canvas_ = document.createElement("canvas"); opt_options = opt_options || {}; this.direction_ = opt_options.direction || null; }
javascript
{ "resource": "" }
q58787
validation
function(div) { var sizeSpan = document.createElement('span'); sizeSpan.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;'); div.appendChild(sizeSpan); var oneEmWidth=sizeSpan.offsetWidth; div.removeChild(sizeSpan); return oneEmWidth; }
javascript
{ "resource": "" }
q58788
Keycloak
validation
function Keycloak (config, keycloakConfig) { // If keycloakConfig is null, Config() will search for `keycloak.json`. this.config = new Config(keycloakConfig); this.grantManager = new GrantManager(this.config); this.stores = [ BearerStore ]; if (!config) { throw new Error('Adapter configuration must be provided.'); } // Add the custom scope value this.config.scope = config.scope; if (config && config.store && config.cookies) { throw new Error('Either `store` or `cookies` may be set, but not both'); } if (config && config.store) { this.stores.push(new SessionStore(config.store)); } else if (config && config.cookies) { this.stores.push(CookieStore); } this.config.idpHint = config.idpHint; }
javascript
{ "resource": "" }
q58789
GrantManager
validation
function GrantManager (config) { this.realmUrl = config.realmUrl; this.clientId = config.clientId; this.secret = config.secret; this.publicKey = config.publicKey; this.public = config.public; this.bearerOnly = config.bearerOnly; this.notBefore = 0; this.rotation = new Rotation(config); }
javascript
{ "resource": "" }
q58790
Rotation
validation
function Rotation (config) { this.realmUrl = config.realmUrl; this.minTimeBetweenJwksRequests = config.minTimeBetweenJwksRequests; this.jwks = []; this.lastTimeRequesTime = 0; }
javascript
{ "resource": "" }
q58791
Config
validation
function Config (config) { if (!config) { config = path.join(process.cwd(), 'keycloak.json'); } if (typeof config === 'string') { this.loadConfiguration(config); } else { this.configure(config); } }
javascript
{ "resource": "" }
q58792
Enforcer
validation
function Enforcer (keycloak, config) { this.keycloak = keycloak; this.config = config || {}; if (!this.config.response_mode) { this.config.response_mode = 'permissions'; } if (!this.config.resource_server_id) { this.config.resource_server_id = this.keycloak.getConfig().clientId; } }
javascript
{ "resource": "" }
q58793
Token
validation
function Token (token, clientId) { this.token = token; this.clientId = clientId; if (token) { try { const parts = token.split('.'); this.header = JSON.parse(Buffer.from(parts[0], 'base64').toString()); this.content = JSON.parse(Buffer.from(parts[1], 'base64').toString()); this.signature = Buffer.from(parts[2], 'base64'); this.signed = parts[0] + '.' + parts[1]; } catch (err) { this.content = { exp: 0 }; } } }
javascript
{ "resource": "" }
q58794
filterCss
validation
function filterCss(abstractSyntaxTree, allowedStyles) { if (!allowedStyles) { return abstractSyntaxTree; } var filteredAST = cloneDeep(abstractSyntaxTree); var astRules = abstractSyntaxTree.nodes[0]; var selectedRule; // Merge global and tag-specific styles into new AST. if (allowedStyles[astRules.selector] && allowedStyles['*']) { selectedRule = mergeWith( cloneDeep(allowedStyles[astRules.selector]), allowedStyles['*'], function(objValue, srcValue) { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } } ); } else { selectedRule = allowedStyles[astRules.selector] || allowedStyles['*']; } if (selectedRule) { filteredAST.nodes[0].nodes = astRules.nodes.reduce(filterDeclarations(selectedRule), []); } return filteredAST; }
javascript
{ "resource": "" }
q58795
stringifyStyleAttributes
validation
function stringifyStyleAttributes(filteredAST) { return filteredAST.nodes[0].nodes .reduce(function(extractedAttributes, attributeObject) { extractedAttributes.push( attributeObject.prop + ':' + attributeObject.value ); return extractedAttributes; }, []) .join(';'); }
javascript
{ "resource": "" }
q58796
filterDeclarations
validation
function filterDeclarations(selectedRule) { return function (allowedDeclarationsList, attributeObject) { // If this property is whitelisted... if (selectedRule.hasOwnProperty(attributeObject.prop)) { var matchesRegex = selectedRule[attributeObject.prop].some(function(regularExpression) { return regularExpression.test(attributeObject.value); }); if (matchesRegex) { allowedDeclarationsList.push(attributeObject); } } return allowedDeclarationsList; }; }
javascript
{ "resource": "" }
q58797
readUint64
validation
function readUint64(buffer, offset) { var hi = (buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3] << 0) >>> 0; var lo = (buffer[offset + 4] << 24 | buffer[offset + 5] << 16 | buffer[offset + 6] << 8 | buffer[offset + 7] << 0) >>> 0; return hi * 0x100000000 + lo; }
javascript
{ "resource": "" }
q58798
check
validation
function check(type, hash, callback) { if (typeof type !== "string") throw new TypeError("type must be string"); if (typeof hash !== "string") throw new TypeError("hash must be string"); if (hasCache[hash]) return callback(null, true); local.hasHash(hash, function (err, has) { if (err) return callback(err); hasCache[hash] = has; callback(null, has); }); }
javascript
{ "resource": "" }
q58799
readLength
validation
function readLength() { var byte = delta[deltaOffset++]; var length = byte & 0x7f; var shift = 7; while (byte & 0x80) { byte = delta[deltaOffset++]; length |= (byte & 0x7f) << shift; shift += 7; } return length; }
javascript
{ "resource": "" }