_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45800
splitCommand
train
function splitCommand(line) { // Make sure we get the same results irrespective of leading/trailing spaces var match = line.match(TOKEN_WHITESPACE); if (!match) { return { name: line.toUpperCase(), rest: '' }; } var name = line.substr(0, match.index).toUpperCase(); var rest = line.substr(match.index + match[0].length); return { name: name, rest: rest }; }
javascript
{ "resource": "" }
q45801
findRuntimePath
train
function findRuntimePath() { const upPkg = readPkgUp.sync(); // case 1: we're in NR itself if (upPkg.pkg.name === 'node-red') { if (checkSemver(upPkg.pkg.version,"<0.20.0")) { return path.join(path.dirname(upPkg.path), upPkg.pkg.main); } else { return path.join(path.dirname(upPkg.path),"packages","node_modules","node-red"); } } // case 2: NR is resolvable from here try { return require.resolve('node-red'); } catch (ignored) {} // case 3: NR is installed alongside node-red-node-test-helper if ((upPkg.pkg.dependencies && upPkg.pkg.dependencies['node-red']) || (upPkg.pkg.devDependencies && upPkg.pkg.devDependencies['node-red'])) { const dirpath = path.join(path.dirname(upPkg.path), 'node_modules', 'node-red'); try { const pkg = require(path.join(dirpath, 'package.json')); return path.join(dirpath, pkg.main); } catch (ignored) {} } }
javascript
{ "resource": "" }
q45802
checkSemver
train
function checkSemver(localVersion,testRange) { var parts = localVersion.split("-"); return semver.satisfies(parts[0],testRange); }
javascript
{ "resource": "" }
q45803
createNeighborArrayForNode
train
function createNeighborArrayForNode(type, direction, nodeData) { // If we want only undirected or in or out, we can roll some optimizations if (type !== 'mixed') { if (type === 'undirected') return Object.keys(nodeData.undirected); if (typeof direction === 'string') return Object.keys(nodeData[direction]); } // Else we need to keep a set of neighbors not to return duplicates const neighbors = new Set(); if (type !== 'undirected') { if (direction !== 'out') { merge(neighbors, nodeData.in); } if (direction !== 'in') { merge(neighbors, nodeData.out); } } if (type !== 'directed') { merge(neighbors, nodeData.undirected); } return take(neighbors.values(), neighbors.size); }
javascript
{ "resource": "" }
q45804
forEachInObject
train
function forEachInObject(nodeData, object, callback) { for (const k in object) { let edgeData = object[k]; if (edgeData instanceof Set) edgeData = edgeData.values().next().value; const sourceData = edgeData.source, targetData = edgeData.target; const neighborData = sourceData === nodeData ? targetData : sourceData; callback( neighborData.key, neighborData.attributes ); } }
javascript
{ "resource": "" }
q45805
nodeHasNeighbor
train
function nodeHasNeighbor(graph, type, direction, node, neighbor) { const nodeData = graph._nodes.get(node); if (type !== 'undirected') { if (direction !== 'out' && typeof nodeData.in !== 'undefined') { for (const k in nodeData.in) if (k === neighbor) return true; } if (direction !== 'in' && typeof nodeData.out !== 'undefined') { for (const k in nodeData.out) if (k === neighbor) return true; } } if (type !== 'directed' && typeof nodeData.undirected !== 'undefined') { for (const k in nodeData.undirected) if (k === neighbor) return true; } return false; }
javascript
{ "resource": "" }
q45806
attachNeighborArrayCreator
train
function attachNeighborArrayCreator(Class, description) { const { name, type, direction } = description; /** * Function returning an array or the count of certain neighbors. * * Arity 1: Return all of a node's relevant neighbors. * @param {any} node - Target node. * * Arity 2: Return whether the two nodes are indeed neighbors. * @param {any} source - Source node. * @param {any} target - Target node. * * @return {array|number} - The neighbors or the number of neighbors. * * @throws {Error} - Will throw if there are too many arguments. */ Class.prototype[name] = function(node) { // Early termination if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type) return []; if (arguments.length === 2) { const node1 = '' + arguments[0], node2 = '' + arguments[1]; if (!this._nodes.has(node1)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node1}" node in the graph.`); if (!this._nodes.has(node2)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${node2}" node in the graph.`); // Here, we want to assess whether the two given nodes are neighbors return nodeHasNeighbor( this, type, direction, node1, node2 ); } else if (arguments.length === 1) { node = '' + node; const nodeData = this._nodes.get(node); if (typeof nodeData === 'undefined') throw new NotFoundGraphError(`Graph.${name}: could not find the "${node}" node in the graph.`); // Here, we want to iterate over a node's relevant neighbors const neighbors = createNeighborArrayForNode( type === 'mixed' ? this.type : type, direction, nodeData ); return neighbors; } throw new InvalidArgumentsGraphError(`Graph.${name}: invalid number of arguments (expecting 1 or 2 and got ${arguments.length}).`); }; }
javascript
{ "resource": "" }
q45807
collectForKey
train
function collectForKey(edges, object, k) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => edges.push(edgeData.key)); else edges.push(object[k].key); return; }
javascript
{ "resource": "" }
q45808
forEachForKey
train
function forEachForKey(object, k, callback) { if (!(k in object)) return; if (object[k] instanceof Set) object[k].forEach(edgeData => callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes )); else { const edgeData = object[k]; callback( edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes ); } return; }
javascript
{ "resource": "" }
q45809
createIteratorForKey
train
function createIteratorForKey(object, k) { const v = object[k]; if (v instanceof Set) { const iterator = v.values(); return new Iterator(function() { const step = iterator.next(); if (step.done) return step; const edgeData = step.value; return { done: false, value: [ edgeData.key, edgeData.attributes, edgeData.source.key, edgeData.target.key, edgeData.source.attributes, edgeData.target.attributes ] }; }); } return Iterator.of([ v.key, v.attributes, v.source.key, v.target.key, v.source.attributes, v.target.attributes ]); }
javascript
{ "resource": "" }
q45810
createEdgeArray
train
function createEdgeArray(graph, type) { if (graph.size === 0) return []; if (type === 'mixed' || type === graph.type) return take(graph._edges.keys(), graph._edges.size); const size = type === 'undirected' ? graph.undirectedSize : graph.directedSize; const list = new Array(size), mask = type === 'undirected'; let i = 0; graph._edges.forEach((data, edge) => { if ((data instanceof UndirectedEdgeData) === mask) list[i++] = edge; }); return list; }
javascript
{ "resource": "" }
q45811
forEachEdge
train
function forEachEdge(graph, type, callback) { if (graph.size === 0) return; if (type === 'mixed' || type === graph.type) { graph._edges.forEach((data, key) => { const {attributes, source, target} = data; callback( key, attributes, source.key, target.key, source.attributes, target.attributes ); }); } else { const mask = type === 'undirected'; graph._edges.forEach((data, key) => { if ((data instanceof UndirectedEdgeData) === mask) { const {attributes, source, target} = data; callback( key, attributes, source.key, target.key, source.attributes, target.attributes ); } }); } }
javascript
{ "resource": "" }
q45812
createEdgeIterator
train
function createEdgeIterator(graph, type) { if (graph.size === 0) return Iterator.empty(); let iterator; if (type === 'mixed') { iterator = graph._edges.values(); return new Iterator(function next() { const step = iterator.next(); if (step.done) return step; const data = step.value; const value = [ data.key, data.attributes, data.source.key, data.target.key, data.source.attributes, data.target.attributes ]; return {value, done: false}; }); } iterator = graph._edges.values(); return new Iterator(function next() { const step = iterator.next(); if (step.done) return step; const data = step.value; if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) { const value = [ data.key, data.attributes, data.source.key, data.target.key, data.source.attributes, data.target.attributes ]; return {value, done: false}; } return next(); }); }
javascript
{ "resource": "" }
q45813
createEdgeArrayForNode
train
function createEdgeArrayForNode(type, direction, nodeData) { const edges = []; if (type !== 'undirected') { if (direction !== 'out') collect(edges, nodeData.in); if (direction !== 'in') collect(edges, nodeData.out); } if (type !== 'directed') { collect(edges, nodeData.undirected); } return edges; }
javascript
{ "resource": "" }
q45814
createEdgeArrayForPath
train
function createEdgeArrayForPath(type, direction, sourceData, target) { const edges = []; if (type !== 'undirected') { if (typeof sourceData.in !== 'undefined' && direction !== 'out') collectForKey(edges, sourceData.in, target); if (typeof sourceData.out !== 'undefined' && direction !== 'in') collectForKey(edges, sourceData.out, target); } if (type !== 'directed') { if (typeof sourceData.undirected !== 'undefined') collectForKey(edges, sourceData.undirected, target); } return edges; }
javascript
{ "resource": "" }
q45815
forEachEdgeForPath
train
function forEachEdgeForPath(type, direction, sourceData, target, callback) { if (type !== 'undirected') { if (typeof sourceData.in !== 'undefined' && direction !== 'out') forEachForKey(sourceData.in, target, callback); if (typeof sourceData.out !== 'undefined' && direction !== 'in') forEachForKey(sourceData.out, target, callback); } if (type !== 'directed') { if (typeof sourceData.undirected !== 'undefined') forEachForKey(sourceData.undirected, target, callback); } }
javascript
{ "resource": "" }
q45816
createEdgeIteratorForPath
train
function createEdgeIteratorForPath(type, direction, sourceData, target) { let iterator = Iterator.empty(); if (type !== 'undirected') { if ( typeof sourceData.in !== 'undefined' && direction !== 'out' && target in sourceData.in ) iterator = chain(iterator, createIteratorForKey(sourceData.in, target)); if ( typeof sourceData.out !== 'undefined' && direction !== 'in' && target in sourceData.out ) iterator = chain(iterator, createIteratorForKey(sourceData.out, target)); } if (type !== 'directed') { if ( typeof sourceData.undirected !== 'undefined' && target in sourceData.undirected ) iterator = chain(iterator, createIteratorForKey(sourceData.undirected, target)); } return iterator; }
javascript
{ "resource": "" }
q45817
attachEdgeArrayCreator
train
function attachEdgeArrayCreator(Class, description) { const { name, type, direction } = description; /** * Function returning an array of certain edges. * * Arity 0: Return all the relevant edges. * * Arity 1: Return all of a node's relevant edges. * @param {any} node - Target node. * * Arity 2: Return the relevant edges across the given path. * @param {any} source - Source node. * @param {any} target - Target node. * * @return {array|number} - The edges or the number of edges. * * @throws {Error} - Will throw if there are too many arguments. */ Class.prototype[name] = function(source, target) { // Early termination if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type) return []; if (!arguments.length) return createEdgeArray(this, type); if (arguments.length === 1) { source = '' + source; const nodeData = this._nodes.get(source); if (typeof nodeData === 'undefined') throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" node in the graph.`); // Iterating over a node's edges return createEdgeArrayForNode( type === 'mixed' ? this.type : type, direction, nodeData ); } if (arguments.length === 2) { source = '' + source; target = '' + target; const sourceData = this._nodes.get(source); if (!sourceData) throw new NotFoundGraphError(`Graph.${name}: could not find the "${source}" source node in the graph.`); if (!this._nodes.has(target)) throw new NotFoundGraphError(`Graph.${name}: could not find the "${target}" target node in the graph.`); // Iterating over the edges between source & target return createEdgeArrayForPath(type, direction, sourceData, target); } throw new InvalidArgumentsGraphError(`Graph.${name}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`); }; }
javascript
{ "resource": "" }
q45818
attachForEachEdge
train
function attachForEachEdge(Class, description) { const { name, type, direction } = description; const forEachName = 'forEach' + name[0].toUpperCase() + name.slice(1, -1); /** * Function iterating over the graph's relevant edges by applying the given * callback. * * Arity 1: Iterate over all the relevant edges. * @param {function} callback - Callback to use. * * Arity 2: Iterate over all of a node's relevant edges. * @param {any} node - Target node. * @param {function} callback - Callback to use. * * Arity 3: Iterate over the relevant edges across the given path. * @param {any} source - Source node. * @param {any} target - Target node. * @param {function} callback - Callback to use. * * @return {undefined} * * @throws {Error} - Will throw if there are too many arguments. */ Class.prototype[forEachName] = function(source, target, callback) { // Early termination if (type !== 'mixed' && this.type !== 'mixed' && type !== this.type) return; if (arguments.length === 1) { callback = source; return forEachEdge(this, type, callback); } if (arguments.length === 2) { source = '' + source; callback = target; const nodeData = this._nodes.get(source); if (typeof nodeData === 'undefined') throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" node in the graph.`); // Iterating over a node's edges return forEachEdgeForNode( type === 'mixed' ? this.type : type, direction, nodeData, callback ); } if (arguments.length === 3) { source = '' + source; target = '' + target; const sourceData = this._nodes.get(source); if (!sourceData) throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${source}" source node in the graph.`); if (!this._nodes.has(target)) throw new NotFoundGraphError(`Graph.${forEachName}: could not find the "${target}" target node in the graph.`); // Iterating over the edges between source & target return forEachEdgeForPath(type, direction, sourceData, target, callback); } throw new InvalidArgumentsGraphError(`Graph.${forEachName}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`); }; }
javascript
{ "resource": "" }
q45819
addEdge
train
function addEdge( graph, name, mustGenerateKey, undirected, edge, source, target, attributes ) { // Checking validity of operation if (!undirected && graph.type === 'undirected') throw new UsageGraphError(`Graph.${name}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`); if (undirected && graph.type === 'directed') throw new UsageGraphError(`Graph.${name}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`); if (attributes && !isPlainObject(attributes)) throw new InvalidArgumentsGraphError(`Graph.${name}: invalid attributes. Expecting an object but got "${attributes}"`); // Coercion of source & target: source = '' + source; target = '' + target; attributes = attributes || {}; if (!graph.allowSelfLoops && source === target) throw new UsageGraphError(`Graph.${name}: source & target are the same ("${source}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`); const sourceData = graph._nodes.get(source), targetData = graph._nodes.get(target); if (!sourceData) throw new NotFoundGraphError(`Graph.${name}: source node "${source}" not found.`); if (!targetData) throw new NotFoundGraphError(`Graph.${name}: target node "${target}" not found.`); // Must the graph generate an id for this edge? const eventData = { key: null, undirected, source, target, attributes }; if (mustGenerateKey) edge = graph._edgeKeyGenerator(eventData); // Coercion of edge key edge = '' + edge; // Here, we have a key collision if (graph._edges.has(edge)) throw new UsageGraphError(`Graph.${name}: the "${edge}" edge already exists in the graph.`); // Here, we might have a source / target collision if ( !graph.multi && ( undirected ? typeof sourceData.undirected[target] !== 'undefined' : typeof sourceData.out[target] !== 'undefined' ) ) { throw new UsageGraphError(`Graph.${name}: an edge linking "${source}" to "${target}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`); } // Storing some data const DataClass = undirected ? UndirectedEdgeData : DirectedEdgeData; const edgeData = new DataClass( edge, mustGenerateKey, sourceData, targetData, attributes ); // Adding the edge to the internal register graph._edges.set(edge, edgeData); // Incrementing node degree counters if (source === target) { if (undirected) sourceData.undirectedSelfLoops++; else sourceData.directedSelfLoops++; } else { if (undirected) { sourceData.undirectedDegree++; targetData.undirectedDegree++; } else { sourceData.outDegree++; targetData.inDegree++; } } // Updating relevant index updateStructureIndex( graph, undirected, edgeData, source, target, sourceData, targetData ); if (undirected) graph._undirectedSize++; else graph._directedSize++; // Emitting eventData.key = edge; graph.emit('edgeAdded', eventData); return edge; }
javascript
{ "resource": "" }
q45820
attachAttributeGetter
train
function attachAttributeGetter(Class, method, type, EdgeDataClass) { /** * Get the desired attribute for the given element (node or edge). * * Arity 2: * @param {any} element - Target element. * @param {string} name - Attribute's name. * * Arity 3 (only for edges): * @param {any} source - Source element. * @param {any} target - Target element. * @param {string} name - Attribute's name. * * @return {mixed} - The attribute's value. * * @throws {Error} - Will throw if too many arguments are provided. * @throws {Error} - Will throw if any of the elements is not found. */ Class.prototype[method] = function(element, name) { let data; if (this.type !== 'mixed' && type !== 'mixed' && type !== this.type) throw new UsageGraphError(`Graph.${method}: cannot find this type of edges in your ${this.type} graph.`); if (arguments.length > 2) { if (this.multi) throw new UsageGraphError(`Graph.${method}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`); const source = '' + element, target = '' + name; name = arguments[2]; data = getMatchingEdge(this, source, target, type); if (!data) throw new NotFoundGraphError(`Graph.${method}: could not find an edge for the given path ("${source}" - "${target}").`); } else { element = '' + element; data = this._edges.get(element); if (!data) throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" edge in the graph.`); } if (type !== 'mixed' && !(data instanceof EdgeDataClass)) throw new NotFoundGraphError(`Graph.${method}: could not find the "${element}" ${type} edge in the graph.`); return data.attributes[name]; }; }
javascript
{ "resource": "" }
q45821
getLoaderDoc
train
function getLoaderDoc(message) { let tpl = defaults.templates.loader; let str = (tpl && tpl({message: message})) || '<document></document>'; return Parser.dom(str); }
javascript
{ "resource": "" }
q45822
getErrorDoc
train
function getErrorDoc(message) { let cfg = {}; if (_.isPlainObject(message)) { cfg = message; if (cfg.status && !cfg.template && defaults.templates.status[cfg.status]) { cfg.template = defaults.templates.status[cfg.status]; } } else { cfg.template = defaults.templates.error || (() => '<document></document>'); cfg.data = {message: message}; } return Page.makeDom(cfg); }
javascript
{ "resource": "" }
q45823
initMenu
train
function initMenu() { let menuCfg = defaults.menu; // no configuration given and neither the menu created earlier // no need to proceed if (!menuCfg && !Menu.created) { return; } // set options to create menu if (menuCfg) { Menu.setOptions(menuCfg); } menuDoc = Menu.get(); Page.prepareDom(menuDoc); }
javascript
{ "resource": "" }
q45824
show
train
function show(cfg = {}) { if (_.isFunction(cfg)) { cfg = { template: cfg }; } // no template exists, cannot proceed if (!cfg.template) { console.warn('No template found!') return; } let doc = null; if (getLastDocumentFromStack() && cfg.type === 'modal') { // show as a modal if there is something on the navigation stack doc = presentModal(cfg); } else { // no document on the navigation stack, show as a document doc = Page.makeDom(cfg); cleanNavigate(doc); } return doc; }
javascript
{ "resource": "" }
q45825
showLoading
train
function showLoading(cfg = {}) { if (_.isString(cfg)) { cfg = { data: { message: cfg } }; } // use default loading template if not passed as a configuration _.defaultsDeep(cfg, { template: defaults.templates.loader, type: 'modal' }); console.log('showing loader... options:', cfg); // cache the doc for later use loaderDoc = show(cfg); return loaderDoc; }
javascript
{ "resource": "" }
q45826
showError
train
function showError(cfg = {}) { if (_.isBoolean(cfg) && !cfg && errorDoc) { // hide error navigationDocument.removeDocument(errorDoc); return; } if (_.isString(cfg)) { cfg = { data: { message: cfg } }; } // use default error template if not passed as a configuration _.defaultsDeep(cfg, { template: defaults.templates.error }); console.log('showing error... options:', cfg); // cache the doc for later use errorDoc = show(cfg); return errorDoc; }
javascript
{ "resource": "" }
q45827
pushDocument
train
function pushDocument(doc) { if (!(doc instanceof Document)) { console.warn('Cannot navigate to the document.', doc); return; } navigationDocument.pushDocument(doc); }
javascript
{ "resource": "" }
q45828
replaceDocument
train
function replaceDocument(doc, docToReplace) { if (!(doc instanceof Document) || !(docToReplace instanceof Document)) { console.warn('Cannot replace document.'); return; } navigationDocument.replaceDocument(doc, docToReplace); }
javascript
{ "resource": "" }
q45829
cleanNavigate
train
function cleanNavigate(doc, replace = false) { let navigated = false; let docs = navigationDocument.documents; let last = getLastDocumentFromStack(); if (!replace && (!last || last !== loaderDoc && last !== errorDoc)) { pushDocument(doc); } else if (last && last === loaderDoc || last === errorDoc) { // replaces any error or loader document from the current document stack console.log('replacing current error/loader...'); replaceDocument(doc, last); loaderDoc = null; errorDoc = null; } // determine the current document on the navigation stack last = replace && getLastDocumentFromStack(); // if replace is passed as a param and there is some document on the top of stack if (last) { console.log('replacing current document...'); replaceDocument(doc, last); } // dismisses any modal open modal _.delay(dismissModal, 2000); return docs[docs.length - 1]; }
javascript
{ "resource": "" }
q45830
navigateToMenuPage
train
function navigateToMenuPage() { console.log('navigating to menu...'); return new Promise((resolve, reject) => { if (!menuDoc) { initMenu(); } if (!menuDoc) { console.warn('No menu configuration exists, cannot navigate to the menu page.'); reject(); } else { cleanNavigate(menuDoc); resolve(menuDoc); } }); }
javascript
{ "resource": "" }
q45831
navigate
train
function navigate(page, options, replace) { let p = Page.get(page); if (_.isBoolean(options)) { replace = options; } else { options = options || {}; } if (_.isBoolean(options.replace)) { replace = options.replace; } console.log('navigating... page:', page, ':: options:', options); // return a promise that resolves if there was a navigation that was performed return new Promise((resolve, reject) => { if (!p) { console.error(page, 'page does not exist!'); let tpl = defaults.templates.status['404']; if (tpl) { let doc = showError({ template: tpl, title: '404', message: 'The requested page cannot be found!' }); resolve(doc); } else { reject(); } return; } p(options).then((doc) => { // support suppressing of navigation since there is no dom available (page resolved with empty document) if (doc) { // if page is a modal, show as modal window if (p.type === 'modal') { // defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-) _.defer(presentModal, doc); } else { // navigate // defer to avoid clashes with any ongoing process (tvmlkit weird behavior -_-) _.defer(cleanNavigate, doc, replace); } } // resolve promise resolve(doc); }, (error) => { // something went wrong during the page execution // warn and set the status to 500 if (error instanceof Error) { console.error(`There was an error in the page code. ${error}`); error.status = '500'; } // try showing a status level error page if it exists let statusLevelErrorTpls = defaults.templates.status; let tpl = statusLevelErrorTpls[error.status]; if (tpl) { showError(_.defaults({ template: tpl }, error.response)); resolve(error); } else { console.warn('No error handler present in the page or navigation default configurations.', error); reject(error); } }); }); }
javascript
{ "resource": "" }
q45832
presentModal
train
function presentModal(modal) { let doc = modal; // assume a document object is passed if (_.isString(modal)) { // if a modal document string is passed doc = Parser.dom(modal); } else if (_.isPlainObject(modal)) { // if a modal page configuration is passed doc = Page.makeDom(modal); } navigationDocument.presentModal(doc); modalDoc = doc; return doc; }
javascript
{ "resource": "" }
q45833
pop
train
function pop(doc) { if (doc instanceof Document) { _.defer(() => navigationDocument.popToDocument(doc)); } else { _.defer(() => navigationDocument.popDocument()); } }
javascript
{ "resource": "" }
q45834
appendStyle
train
function appendStyle(style, doc) { if (!_.isString(style) || !doc) { console.log('invalid document or style string...', style, doc); return; } let docEl = (doc.getElementsByTagName('document')).item(0); let styleString = ['<style>', style, '</style>'].join(''); let headTag = doc.getElementsByTagName('head'); headTag = headTag && headTag.item(0); if (!headTag) { headTag = doc.createElement('head'); docEl.insertBefore(headTag, docEl.firstChild); } headTag.innerHTML = styleString; }
javascript
{ "resource": "" }
q45835
prepareDom
train
function prepareDom(doc, cfg = {}) { if (!(doc instanceof Document)) { console.warn('Cannnot prepare, the provided element is not a document.'); return; } // apply defaults _.defaults(cfg, defaults); // append any default styles appendStyle(cfg.style, doc); // attach event handlers Handler.addAll(doc, cfg); return doc; }
javascript
{ "resource": "" }
q45836
makeDom
train
function makeDom(cfg, response) { // apply defaults _.defaults(cfg, defaults); // create Document let doc = Parser.dom(cfg.template, (_.isPlainObject(cfg.data) ? cfg.data: cfg.data(response))); // prepare the Document prepareDom(doc, cfg); // call the after ready method if defined in the configuration if (_.isFunction(cfg.afterReady)) { console.log('calling afterReady method...'); cfg.afterReady(doc); } // cache cfg at the document level doc.page = cfg; return doc; }
javascript
{ "resource": "" }
q45837
makePage
train
function makePage(cfg) { return (options) => { _.defaultsDeep(cfg, defaults); console.log('making page... options:', cfg); // return a promise that resolves after completion of the ajax request // if no ready method or url configuration exist, the promise is resolved immediately and the resultant dom is returned return new Promise((resolve, reject) => { if (_.isFunction(cfg.ready)) { // if present, call the ready function console.log('calling page ready... options:', options); // resolves promise with a doc if there is a response param passed // if the response param is null/falsy value, resolve with null (usefull for catching and supressing any navigation later) cfg.ready(options, (response) => resolve((response || _.isUndefined(response)) ? makeDom(cfg, response) : null), reject); } else if (cfg.url) { // make ajax request if a url is provided Ajax .get(cfg.url, cfg.options) .then((xhr) => { resolve(makeDom(cfg, xhr.response)); }, (xhr) => { // if present, call the error handler if (_.isFunction(cfg.onError)) { cfg.onError(xhr.response, xhr); } else { reject(xhr); } }); } else { // no url/ready method provided, resolve the promise immediately resolve(makeDom(cfg)); } }); } }
javascript
{ "resource": "" }
q45838
parse
train
function parse(s, data) { // if a template function is provided, call the function with data s = _.isFunction(s) ? s(data) : s; console.log('parsing string...'); console.log(s); // prepend the xml string if not already present if (!_.startsWith(s, '<?xml')) { s = xmlPrefix + s; } return parser.parseFromString(s, 'application/xml'); }
javascript
{ "resource": "" }
q45839
setAttributes
train
function setAttributes(el, attributes) { console.log('setting attributes on element...', el, attributes); _.each(attributes, (value, name) => el.setAttribute(name, value)); }
javascript
{ "resource": "" }
q45840
addItem
train
function addItem(item = {}) { if (!item.id) { console.warn('Cannot add menuitem. A unique identifier is required for the menuitem to work correctly.'); return; } let el = doc.createElement('menuItem'); // assign unique id item.attributes = _.assign({}, item.attributes, { id: item.id }); // add all attributes setAttributes(el, item.attributes); // add title el.innerHTML = `<title>${(_.isFunction(item.name) ? item.name() : item.name)}</title>`; // add page reference el.page = item.page; // appends to the menu menuBarEl.insertBefore(el, null); // cache for later use itemsCache[item.id] = el; return el; }
javascript
{ "resource": "" }
q45841
create
train
function create(cfg = {}) { if (created) { console.warn('An instance of menu already exists, skipping creation...'); return; } // defaults _.assign(defaults, cfg); console.log('creating menu...', defaults); // set attributes to the menubar element setAttributes(menuBarEl, defaults.attributes); // set attributes to the menubarTemplate element setAttributes(menuBarTpl, defaults.rootTemplateAttributes); // add all items to the menubar _.each(defaults.items, (item) => addItem(item)); // indicate done created = true; return doc; }
javascript
{ "resource": "" }
q45842
ajax
train
function ajax(url, options, method = 'GET') { if (typeof url == 'undefined') { console.error('No url specified for the ajax.'); throw new TypeError('A URL is required for making the ajax request.'); } if (typeof options === 'undefined' && typeof url === 'object' && url.url) { options = url; url = options.url; } else if (typeof url !== 'string') { console.error('No url/options specified for the ajax.'); throw new TypeError('Options must be an object for making the ajax request.'); } // default options options = Object.assign({}, defaults, options, {method: method}); console.log(`initiating ajax request... url: ${url}`, ' :: options:', options); return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); // set response type if (options.responseType) { xhr.responseType = options.responseType; } // open connection xhr.open( options.method, url, typeof options.async === 'undefined' ? true : options.async, options.user, options.password ); // set headers Object.keys(options.headers || {}).forEach(function(name) { xhr.setRequestHeader(name, options.headers[name]); }); // listen to the state change xhr.onreadystatechange = () => { if (xhr.readyState !== 4) { return; } if (xhr.status >= 200 && xhr.status <= 300) { resolve(xhr); } else { reject(xhr); } }; // error handling xhr.addEventListener('error', () => reject(xhr)); xhr.addEventListener('abort', () => reject(xhr)); // send request xhr.send(options.data); }); }
javascript
{ "resource": "" }
q45843
initLibraries
train
function initLibraries(cfg = {}) { _.each(configMap, (keys, libName) => { let lib = libs[libName]; let options = {}; _.each(keys, (key) => options[key] = cfg[key]); lib.setOptions && lib.setOptions(options); }); }
javascript
{ "resource": "" }
q45844
initAppHandlers
train
function initAppHandlers (cfg = {}) { _.each(handlers, (handler, name) => App[name] = _.partial(handler, _, (_.isFunction(cfg[name])) ? cfg[name] : _.noop)); }
javascript
{ "resource": "" }
q45845
start
train
function start(cfg = {}) { if (started) { console.warn('Application already started, cannot call start again.'); return; } initLibraries(cfg); initAppHandlers(cfg); // if already bootloaded somewhere // immediately call the onLaunch method if (cfg.bootloaded) { App.onLaunch(App.launchOptions); } started = true; }
javascript
{ "resource": "" }
q45846
reload
train
function reload(options, reloadData) { App.onReload(options); App.reload(options, reloadData); }
javascript
{ "resource": "" }
q45847
setOptions
train
function setOptions(cfg = {}) { console.log('setting handler options...', cfg); // override the default options _.defaultsDeep(handlers, cfg.handlers); }
javascript
{ "resource": "" }
q45848
setListeners
train
function setListeners(doc, cfg = {}, add = true) { if (!doc || !(doc instanceof Document)) { return; } let listenerFn = doc.addEventListener; if (!add) { listenerFn = doc.removeEventListener; } if (_.isObject(cfg.events)) { let events = cfg.events; _.each(events, (fns, e) => { let [ev, selector] = e.split(' '); let elements = null; if (!_.isArray(fns)) { // support list of event handlers fns = [fns]; } if (selector) { selector = e.substring(e.indexOf(' ') + 1); // everything after space elements = _.attempt(() => doc.querySelectorAll(selector)); // catch any errors while document selection } else { elements = [doc]; } elements = _.isError(elements) ? [] : elements; _.each(fns, (fn) => { fn = _.isString(fn) ? cfg[fn] : fn; // assume the function to be present on the page configuration obeject if (_.isFunction(fn)) { console.log((add ? 'adding' : 'removing') + ' event on documents...', ev, elements); _.each(elements, (el) => listenerFn.call(el, ev, (e) => fn.call(cfg, e))); // bind to the original configuration object } }); }) } }
javascript
{ "resource": "" }
q45849
map
train
function map(resultSet, maps, mapId, columnPrefix) { let mappedCollection = []; resultSet.forEach(result => { injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix); }); return mappedCollection; }
javascript
{ "resource": "" }
q45850
mapOne
train
function mapOne(resultSet, maps, mapId, columnPrefix, isRequired = true) { var mappedCollection = map(resultSet, maps, mapId, columnPrefix); if (mappedCollection.length > 0) { return mappedCollection[0]; } else if (isRequired) { throw new NotFoundError('EmptyResponse'); } else { return null; } }
javascript
{ "resource": "" }
q45851
injectResultInCollection
train
function injectResultInCollection(result, mappedCollection, maps, mapId, columnPrefix = '') { // Check if the object is already in mappedCollection let resultMap = maps.find(map => map.mapId === mapId); let idProperty = getIdProperty(resultMap); let predicate = idProperty.reduce((accumulator, field) => { accumulator[field.name] = result[columnPrefix + field.column]; return accumulator; }, {}); let mappedObject = mappedCollection.find(item => { for (let k in predicate) { if (item[k] !== predicate[k]) { return false; } } return true; }); // Inject only if the value of idProperty is not null (ignore joins to null records) let isIdPropertyNotNull = idProperty.every(field => result[columnPrefix + field.column] !== null); if (isIdPropertyNotNull) { // Create mappedObject if it does not exist in mappedCollection if (!mappedObject) { mappedObject = createMappedObject(resultMap); mappedCollection.push(mappedObject); } // Inject result in object injectResultInObject(result, mappedObject, maps, mapId, columnPrefix); } }
javascript
{ "resource": "" }
q45852
injectResultInObject
train
function injectResultInObject(result, mappedObject, maps, mapId, columnPrefix = '') { // Get the resultMap for this object let resultMap = maps.find(map => map.mapId === mapId); // Copy id property let idProperty = getIdProperty(resultMap); idProperty.forEach(field => { if (!mappedObject[field.name]) { mappedObject[field.name] = result[columnPrefix + field.column]; } }); const {properties, associations, collections} = resultMap; // Copy other properties properties && properties.forEach(property => { // If property is a string, convert it to an object if (typeof property === 'string') { // eslint-disable-next-line property = {name: property, column: property}; } // Copy only if property does not exist already if (!mappedObject[property.name]) { // The default for column name is property name let column = (property.column) ? property.column : property.name; mappedObject[property.name] = result[columnPrefix + column]; } }); // Copy associations associations && associations.forEach(association => { let associatedObject = mappedObject[association.name]; if (!associatedObject) { let associatedResultMap = maps.find(map => map.mapId === association.mapId); let associatedObjectIdProperty = getIdProperty(associatedResultMap); mappedObject[association.name] = null; // Don't create associated object if it's key value is null let isAssociatedObjectIdPropertyNotNull = associatedObjectIdProperty.every(field => result[association.columnPrefix + field.column] !== null ); if (isAssociatedObjectIdPropertyNotNull) { associatedObject = createMappedObject(associatedResultMap); mappedObject[association.name] = associatedObject; } } if (associatedObject) { injectResultInObject(result, associatedObject, maps, association.mapId, association.columnPrefix); } }); // Copy collections collections && collections.forEach(collection => { let mappedCollection = mappedObject[collection.name]; if (!mappedCollection) { mappedCollection = []; mappedObject[collection.name] = mappedCollection; } injectResultInCollection(result, mappedCollection, maps, collection.mapId, collection.columnPrefix); }); }
javascript
{ "resource": "" }
q45853
train
function (vObject, filter) { /** * Definition: * <!ELEMENT filter (comp-filter)> */ if (filter) { if (vObject.name == filter.name) { return this._validateFilterSet(vObject, filter["comp-filters"], this._validateCompFilter) && this._validateFilterSet(vObject, filter["prop-filters"], this._validatePropFilter); } else return false; } else return true; }
javascript
{ "resource": "" }
q45854
train
function (component, textMatch) { if (component.hasFeature && component.hasFeature(jsVObject_Node)) component = component.getValue(); var isMatching = Util.textMatch(component, textMatch.value, textMatch["match-type"]); return (textMatch["negate-condition"] ^ isMatching); }
javascript
{ "resource": "" }
q45855
train
function (component, filter) { if (!filter) return true; var start = filter.start, end = filter.end; if (!start) start = new Date(1900, 1, 1); if (!end) end = new Date(3000, 1, 1); switch (component.name) { case "VEVENT" : case "VTODO" : case "VJOURNAL" : return component.isInTimeRange(start, end); case "VALARM" : /* // If the valarm is wrapped in a recurring event, we need to // expand the recursions, and validate each. // // Our datamodel doesn't easily allow us to do this straight // in the VALARM component code, so this is a hack, and an // expensive one too. if (component.parent.name === 'VEVENT' && component.parent.RRULE) { // Fire up the iterator! it = new VObject\RecurrenceIterator(component.parent.parent, (string) component.parent.UID ) ; while (it.valid()) { expandedEvent = it.getEventObject(); // We need to check from these expanded alarms, which // one is the first to trigger. Based on this, we can // determine if we can 'give up' expanding events. firstAlarm = null; if (expandedEvent.VALARM !== null) { foreach(expandedEvent.VALARM as expandedAlarm ) { effectiveTrigger = expandedAlarm.getEffectiveTriggerTime(); if (expandedAlarm.isInTimeRange(start, end)) { return true; } if ((string)expandedAlarm.TRIGGER['VALUE'] === 'DATE-TIME' ) { // This is an alarm with a non-relative trigger // time, likely created by a buggy client. The // implication is that every alarm in this // recurring event trigger at the exact same // time. It doesn't make sense to traverse // further. } else { // We store the first alarm as a means to // figure out when we can stop traversing. if (!firstAlarm || effectiveTrigger < firstAlarm) { firstAlarm = effectiveTrigger; } } } } if (is_null(firstAlarm)) { // No alarm was found. // // Or technically: No alarm that will change for // every instance of the recurrence was found, // which means we can assume there was no match. return false; } if (firstAlarm > end) { return false; } it.next(); } return false; } else { return component.isInTimeRange(start, end); } */ case "VFREEBUSY" : throw new Exc.NotImplemented("time-range filters are currently not supported on " + component.name + " components"); case "COMPLETED" : case "CREATED" : case "DTEND" : case "DTSTAMP" : case "DTSTART" : case "DUE" : case "LAST-MODIFIED" : return (start <= component.getDateTime() && end >= component.getDateTime()); default : // throw new Exc.BadRequest("You cannot create a time-range filter on a " + component.name + " component"); return false; } }
javascript
{ "resource": "" }
q45856
train
function(name, data, enc, cbfscreatefile) { jsDAV_FS_Directory.createFile.call(this, name, data, enc, afterCreateFile.bind(this, name, cbfscreatefile)); }
javascript
{ "resource": "" }
q45857
train
function(handler, name, enc, cbfscreatefile) { jsDAV_FS_Directory.createFileStream.call(this, handler, name, enc, afterCreateFile.bind(this, name, cbfscreatefile)); }
javascript
{ "resource": "" }
q45858
train
function(name, cbfsgetchild) { var path = Path.join(this.path, name); Fs.stat(path, function(err, stat) { if (err || typeof stat == "undefined") { return cbfsgetchild(new Exc.FileNotFound("File with name " + path + " could not be located")); } cbfsgetchild(null, stat.isDirectory() ? jsDAV_FSExt_Directory.new(path) : jsDAV_FSExt_File.new(path)) }); }
javascript
{ "resource": "" }
q45859
train
function(cbfsgetchildren) { var nodes = []; Async.readdir(this.path) .stat() .filter(function(file) { return file.indexOf(jsDAV_FSExt_File.PROPS_DIR) !== 0; }) .each(function(file, cbnextdirch) { nodes.push(file.stat.isDirectory() ? jsDAV_FSExt_Directory.new(file.path) : jsDAV_FSExt_File.new(file.path) ); cbnextdirch(); }) .end(function() { cbfsgetchildren(null, nodes); }); }
javascript
{ "resource": "" }
q45860
train
function(cbfsdel) { var self = this; Async.rmtree(this.path, function(err) { if (err) return cbfsdel(err); self.deleteResourceData(cbfsdel); }); }
javascript
{ "resource": "" }
q45861
getDigest
train
function getDigest(req) { // most other servers var digest = req.headers["authorization"]; if (digest && digest.toLowerCase().indexOf("digest") === 0) return digest.substr(7); else return null; }
javascript
{ "resource": "" }
q45862
parseDigest
train
function parseDigest(digest) { if (!digest) return false; // protect against missing data var needed_parts = {"nonce": 1, "nc": 1, "cnonce": 1, "qop": 1, "username": 1, "uri": 1, "response": 1}; var data = {}; digest.replace(/(\w+)=(?:(?:")([^"]+)"|([^\s,]+))/g, function(m, m1, m2, m3) { data[m1] = m2 ? m2 : m3; delete needed_parts[m1]; return m; }); return Object.keys(needed_parts).length ? false : data; }
javascript
{ "resource": "" }
q45863
train
function(realm, req) { this.realm = realm; this.opaque = Util.createHash(this.realm); this.digest = getDigest(req); this.digestParts = parseDigest(this.digest); }
javascript
{ "resource": "" }
q45864
train
function(handler, password, cbvalidpass) { this.A1 = Util.createHash(this.digestParts["username"] + ":" + this.realm + ":" + password); this.validate(handler, cbvalidpass); }
javascript
{ "resource": "" }
q45865
train
function(handler, cbvalidate) { var req = handler.httpRequest; var A2 = req.method + ":" + this.digestParts["uri"]; var self = this; if (this.digestParts["qop"] == "auth-int") { // Making sure we support this qop value if (!(this.qop & QOP_AUTHINT)) return cbvalidate(false); // We need to add an md5 of the entire request body to the A2 part of the hash handler.getRequestBody("utf8", null, false, function(noop, body) { A2 += ":" + Util.createHash(body); afterBody(); }); } else { // We need to make sure we support this qop value if (!(this.qop & QOP_AUTH)) return cbvalidate(false); afterBody(); } function afterBody() { A2 = Util.createHash(A2); var validResponse = Util.createHash(self.A1 + ":" + self.digestParts["nonce"] + ":" + self.digestParts["nc"] + ":" + self.digestParts["cnonce"] + ":" + self.digestParts["qop"] + ":" + A2); cbvalidate(self.digestParts["response"] == validResponse); } }
javascript
{ "resource": "" }
q45866
train
function(realm, err, cbreqauth) { if (!(err instanceof Exc.jsDAV_Exception)) err = new Exc.NotAuthenticated(err); var currQop = ""; switch (this.qop) { case QOP_AUTH: currQop = "auth"; break; case QOP_AUTHINT: currQop = "auth-int"; break; case QOP_AUTH | QOP_AUTHINT: currQop = "auth,auth-int"; break; } err.addHeader("WWW-Authenticate", "Digest realm=\"" + realm + "\",qop=\"" + currQop + "\",nonce=\"" + this.nonce + "\",opaque=\"" + this.opaque + "\""); cbreqauth(err, false); }
javascript
{ "resource": "" }
q45867
train
function(handler, realm, cbauth) { var req = handler.httpRequest; this.init(realm, req); var username = this.digestParts["username"]; // No username was given if (!username) return this.requireAuth(realm, "No digest authentication headers were found", cbauth); var self = this; this.getDigestHash(realm, username, function(err, hash) { // If this was false, the user account didn't exist if (err || !hash) return self.requireAuth(realm, err || "The supplied username was not on file", cbauth); if (typeof hash != "string") { handler.handleError(new Exc.jsDAV_Exception( "The returned value from getDigestHash must be a string or null")); return cbauth(null, false); } // If this was false, the password or part of the hash was incorrect. self.validateA1(handler, hash, function(isValid) { if (!isValid) return self.requireAuth(realm, "Incorrect username", cbauth); self.currentUser = username; cbauth(null, true); }); }); }
javascript
{ "resource": "" }
q45868
train
function(opts){ opts = opts || {}; this.db = opts.db; this.config = { maxConnection : opts.maxConnection || DEFAULT_MAX_CONNECTION, connectionIdleTimeout : opts.connectionIdleTimeout || DEFAULT_CONNECTION_IDLE_TIMEOUT, maxPendingTask : opts.maxPendingTask || DEFAULT_MAX_PENDING_TASK, reconnectInterval : opts.reconnectInterval || DEFAULT_RECONNECT_INTERVAL, // allow concurrent request inside one connection, internal use only concurrentInConnection : opts.concurrentInConnection || false, // {shardId : {host : '127.0.0.1', port : 31017}} shards : opts.shards || {}, }; if(this.config.concurrentInConnection){ this.config.maxConnection = 1; } var shardIds = Object.keys(this.config.shards); if(shardIds.length === 0){ throw new Error('please specify opts.shards'); } var shards = {}; shardIds.forEach(function(shardId){ shards[shardId] = { connections : {}, // {connId : connection} freeConnections : {}, // {connId : true} connectionTimeouts : {}, // {connId : timeout} pendingTasks : [], reconnectInterval : null, }; }); this.shards = shards; this.openConnectionLock = new AsyncLock({Promise : P, maxPending : 10000}); this.collections = {}; }
javascript
{ "resource": "" }
q45869
prepareFilesForPublishing
train
async function prepareFilesForPublishing( tmpDir, files = [], ignorePatterns = null ) { // Ignored files filter const filter = ignore().add(ignorePatterns) const projectRoot = findProjectRoot() function createFilter(files, ignorePath) { let f = fs.readFileSync(ignorePath).toString() files.forEach(file => { f = f.concat(`\n!${file}`) }) return f } const ipfsignorePath = path.resolve(projectRoot, '.ipfsignore') if (pathExistsSync(ipfsignorePath)) { filter.add(createFilter(files, ipfsignorePath)) } else { const gitignorePath = path.resolve(projectRoot, '.gitignore') if (pathExistsSync(gitignorePath)) { filter.add(createFilter(files, gitignorePath)) } } const replaceRootRegex = new RegExp(`^${projectRoot}`) function filterIgnoredFiles(src) { const relativeSrc = src.replace(replaceRootRegex, '.') return !filter.ignores(relativeSrc) } // Copy files await Promise.all( files.map(async file => { const stats = await promisify(fs.lstat)(file) let destination = tmpDir if (stats.isFile()) { destination = path.resolve(tmpDir, file) } return copy(file, destination, { filter: filterIgnoredFiles, }) }) ) const manifestOrigin = path.resolve(projectRoot, MANIFEST_FILE) const manifestDst = path.resolve(tmpDir, MANIFEST_FILE) if (!pathExistsSync(manifestDst) && pathExistsSync(manifestOrigin)) { await copy(manifestOrigin, manifestDst) } const artifactOrigin = path.resolve(projectRoot, ARTIFACT_FILE) const artifactDst = path.resolve(tmpDir, ARTIFACT_FILE) if (!pathExistsSync(artifactDst) && pathExistsSync(artifactOrigin)) { await copy(artifactOrigin, artifactDst) } return tmpDir }
javascript
{ "resource": "" }
q45870
moduleDefine
train
function moduleDefine(exports, name, members) { var target = [exports]; var publicNS = null; if (name) { publicNS = createNamespace(_Global, name); target.push(publicNS); } initializeProperties(target, members, name || "<ANONYMOUS>"); return publicNS; }
javascript
{ "resource": "" }
q45871
completed
train
function completed(promise, value) { var targetState; if (value && typeof value === "object" && typeof value.then === "function") { targetState = state_waiting; } else { targetState = state_success_notify; } promise._value = value; promise._setState(targetState); }
javascript
{ "resource": "" }
q45872
timeout
train
function timeout(timeoutMS) { var id; return new Promise( function (c) { if (timeoutMS) { id = _Global.setTimeout(c, timeoutMS); } else { _BaseCoreUtils._setImmediate(c); } }, function () { if (id) { _Global.clearTimeout(id); } } ); }
javascript
{ "resource": "" }
q45873
setState
train
function setState(state) { return function (job, arg0, arg1) { job._setState(state, arg0, arg1); }; }
javascript
{ "resource": "" }
q45874
notifyCurrentDrainListener
train
function notifyCurrentDrainListener() { var listener = drainQueue.shift(); if (listener) { drainStopping(listener); drainQueue[0] && drainStarting(drainQueue[0]); listener.complete(); } }
javascript
{ "resource": "" }
q45875
notifyDrainListeners
train
function notifyDrainListeners() { var notifiedSomebody = false; if (!!drainQueue.length) { // As we exhaust priority levels, notify the appropriate drain listeners. // var drainPriority = currentDrainPriority(); while (+drainPriority === drainPriority && drainPriority > highWaterMark) { pumpingPriority = drainPriority; notifyCurrentDrainListener(); notifiedSomebody = true; drainPriority = currentDrainPriority(); } } return notifiedSomebody; }
javascript
{ "resource": "" }
q45876
addJobAtHeadOfPriority
train
function addJobAtHeadOfPriority(node, priority) { var marker = markerFromPriority(priority); if (marker.priority > highWaterMark) { highWaterMark = marker.priority; immediateYield = true; } marker._insertJobAfter(node); }
javascript
{ "resource": "" }
q45877
setAttribute
train
function setAttribute(element, attribute, value) { if (element.getAttribute(attribute) !== "" + value) { element.setAttribute(attribute, value); } }
javascript
{ "resource": "" }
q45878
addListenerToEventMap
train
function addListenerToEventMap(element, type, listener, useCapture, data) { var eventNameLowercase = type.toLowerCase(); if (!element._eventsMap) { element._eventsMap = {}; } if (!element._eventsMap[eventNameLowercase]) { element._eventsMap[eventNameLowercase] = []; } element._eventsMap[eventNameLowercase].push({ listener: listener, useCapture: useCapture, data: data }); }
javascript
{ "resource": "" }
q45879
train
function (element) { var hiddenElement = _Global.document.createElement("div"); hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-name"].scriptName] = "WinJS-node-inserted"; hiddenElement.style[_BaseUtils._browserStyleEquivalents["animation-duration"].scriptName] = "0.01s"; hiddenElement.style["position"] = "absolute"; element.appendChild(hiddenElement); exports._addEventListener(hiddenElement, "animationStart", function (e) { if (e.animationName === "WinJS-node-inserted") { var e = _Global.document.createEvent("Event"); e.initEvent("WinJSNodeInserted", false, true); element.dispatchEvent(e); } }, false); return hiddenElement; }
javascript
{ "resource": "" }
q45880
readWhitespace
train
function readWhitespace(text, offset, limit) { while (offset < limit) { var code = text.charCodeAt(offset); switch (code) { case 0x0009: // tab case 0x000B: // vertical tab case 0x000C: // form feed case 0x0020: // space case 0x00A0: // no-breaking space case 0xFEFF: // BOM break; // There are no category Zs between 0x00A0 and 0x1680. // case (code < 0x1680) && code: return offset; // Unicode category Zs // case 0x1680: case 0x180e: case (code >= 0x2000 && code <= 0x200a) && code: case 0x202f: case 0x205f: case 0x3000: break; default: return offset; } offset++; } return offset; }
javascript
{ "resource": "" }
q45881
train
function () { if (this._notificationsSent && !this._externalBegin && !this._endNotificationsPosted) { this._endNotificationsPosted = true; var that = this; Scheduler.schedule(function ItemsManager_async_endNotifications() { that._endNotificationsPosted = false; that._endNotifications(); }, Scheduler.Priority.high, null, "WinJS.UI._ItemsManager._postEndNotifications"); } }
javascript
{ "resource": "" }
q45882
tabbableElementsNodeFilter
train
function tabbableElementsNodeFilter(node) { var nodeStyle = _ElementUtilities._getComputedStyle(node); if (nodeStyle.display === "none" || nodeStyle.visibility === "hidden") { return _Global.NodeFilter.FILTER_REJECT; } if (node._tabContainer) { return _Global.NodeFilter.FILTER_ACCEPT; } if (node.parentNode && node.parentNode._tabContainer) { var managedTarget = node.parentNode._tabContainer.childFocus; // Ignore subtrees that are under a tab manager but not the child focus. If a node is contained in the child focus, either accept it (if it's tabbable itself), or skip it and find tabbable content inside of it. if (managedTarget && node.contains(managedTarget)) { return (getTabIndex(node) >= 0 ? _Global.NodeFilter.FILTER_ACCEPT : _Global.NodeFilter.FILTER_SKIP); } return _Global.NodeFilter.FILTER_REJECT; } var tabIndex = getTabIndex(node); if (tabIndex >= 0) { return _Global.NodeFilter.FILTER_ACCEPT; } return _Global.NodeFilter.FILTER_SKIP; }
javascript
{ "resource": "" }
q45883
drainQueue
train
function drainQueue(jobInfo) { function drainNext() { return drainQueue; } var queue = jobInfo.job._queue; if (queue.length === 0 && eventQueue.length > 0) { queue = jobInfo.job._queue = copyAndClearQueue(); } jobInfo.setPromise(drainOneEvent(queue).then(drainNext, drainNext)); }
javascript
{ "resource": "" }
q45884
activatedHandler
train
function activatedHandler(e) { var def = captureDeferral(e.activatedOperation); _State._loadState(e).then(function () { queueEvent({ type: activatedET, detail: e, _deferral: def.deferral, _deferralID: def.id }); }); }
javascript
{ "resource": "" }
q45885
transformWithTransition
train
function transformWithTransition(element, transition) { // transition's properties: // - duration: Number representing the duration of the animation in milliseconds. // - timing: String representing the CSS timing function that controls the progress of the animation. // - to: The value of *element*'s transform property after the animation. var duration = transition.duration * _TransitionAnimation._animationFactor; var transitionProperty = _BaseUtils._browserStyleEquivalents["transition"].scriptName; element.style[transitionProperty] = duration + "ms " + transformNames.cssName + " " + transition.timing; element.style[transformNames.scriptName] = transition.to; var finish; return new Promise(function (c) { var onTransitionEnd = function (eventObject) { if (eventObject.target === element && eventObject.propertyName === transformNames.cssName) { finish(); } }; var didFinish = false; finish = function () { if (!didFinish) { _Global.clearTimeout(timeoutId); element.removeEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd); element.style[transitionProperty] = ""; didFinish = true; } c(); }; // Watch dog timeout var timeoutId = _Global.setTimeout(function () { timeoutId = _Global.setTimeout(finish, duration); }, 50); element.addEventListener(_BaseUtils._browserEventEquivalents["transitionEnd"], onTransitionEnd); }, function () { finish(); // On cancelation, complete the promise successfully to match PVL }); }
javascript
{ "resource": "" }
q45886
disposeInstance
train
function disposeInstance(container, workPromise, renderCompletePromise) { var bindings = _ElementUtilities.data(container).bindTokens; if (bindings) { bindings.forEach(function (binding) { if (binding && binding.cancel) { binding.cancel(); } }); } if (workPromise) { workPromise.cancel(); } if (renderCompletePromise) { renderCompletePromise.cancel(); } }
javascript
{ "resource": "" }
q45887
PageControl_ctor
train
function PageControl_ctor(element, options, complete, parentedPromise) { var that = this; this._disposed = false; this.element = element = element || _Global.document.createElement("div"); _ElementUtilities.addClass(element, "win-disposable"); element.msSourceLocation = uri; this.uri = uri; this.selfhost = selfhost(uri); element.winControl = this; _ElementUtilities.addClass(element, "pagecontrol"); var profilerMarkIdentifier = " uri='" + uri + "'" + _BaseUtils._getProfilerMarkIdentifier(this.element); _WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StartTM"); var load = Promise.wrap(). then(function Pages_load() { return that.load(uri); }); var renderCalled = load.then(function Pages_init(loadResult) { return Promise.join({ loadResult: loadResult, initResult: that.init(element, options) }); }).then(function Pages_render(result) { return that.render(element, options, result.loadResult); }); this.elementReady = renderCalled.then(function () { return element; }); this.renderComplete = renderCalled. then(function Pages_process() { return that.process(element, options); }).then(function Pages_processed() { return that.processed(element, options); }).then(function () { return that; }); var callComplete = function () { complete && complete(that); _WriteProfilerMark("WinJS.UI.Pages:createPage" + profilerMarkIdentifier + ",StopTM"); }; // promises guarantee order, so this will be called prior to ready path below // this.renderComplete.then(callComplete, callComplete); this.readyComplete = this.renderComplete.then(function () { return parentedPromise; }).then(function Pages_ready() { that.ready(element, options); return that; }).then( null, function Pages_error(err) { return that.error(err); } ); }
javascript
{ "resource": "" }
q45888
moveSequenceBefore
train
function moveSequenceBefore(slotNext, slotFirst, slotLast) { slotFirst.prev.next = slotLast.next; slotLast.next.prev = slotFirst.prev; slotFirst.prev = slotNext.prev; slotLast.next = slotNext; slotFirst.prev.next = slotFirst; slotNext.prev = slotLast; return true; }
javascript
{ "resource": "" }
q45889
moveSequenceAfter
train
function moveSequenceAfter(slotPrev, slotFirst, slotLast) { slotFirst.prev.next = slotLast.next; slotLast.next.prev = slotFirst.prev; slotFirst.prev = slotPrev; slotLast.next = slotPrev.next; slotPrev.next = slotFirst; slotLast.next.prev = slotLast; return true; }
javascript
{ "resource": "" }
q45890
insertAndMergeSlot
train
function insertAndMergeSlot(slot, slotNext, mergeWithPrev, mergeWithNext) { insertSlot(slot, slotNext); var slotPrev = slot.prev; if (slotPrev.lastInSequence) { if (mergeWithPrev) { delete slotPrev.lastInSequence; } else { slot.firstInSequence = true; } if (mergeWithNext) { delete slotNext.firstInSequence; } else { slot.lastInSequence = true; } } }
javascript
{ "resource": "" }
q45891
setSlotKey
train
function setSlotKey(slot, key) { slot.key = key; // Add the slot to the keyMap, so it is possible to quickly find the slot given its key keyMap[slot.key] = slot; }
javascript
{ "resource": "" }
q45892
createAndAddSlot
train
function createAndAddSlot(slotNext, indexMapForSlot) { var slotNew = (indexMapForSlot === indexMap ? createPrimarySlot() : createSlot()); insertSlot(slotNew, slotNext); return slotNew; }
javascript
{ "resource": "" }
q45893
adjustedIndex
train
function adjustedIndex(slot) { var undefinedIndex; if (!slot) { return undefinedIndex; } var delta = 0; while (!slot.firstInSequence) { delta++; slot = slot.prev; } return ( typeof slot.indexNew === "number" ? slot.indexNew + delta : typeof slot.index === "number" ? slot.index + delta : undefinedIndex ); }
javascript
{ "resource": "" }
q45894
updateNewIndicesAfterSlot
train
function updateNewIndicesAfterSlot(slot, indexDelta) { // Adjust all the indexNews after this slot for (slot = slot.next; slot; slot = slot.next) { if (slot.firstInSequence) { var indexNew = (slot.indexNew !== undefined ? slot.indexNew : slot.index); if (indexNew !== undefined) { slot.indexNew = indexNew + indexDelta; } } } // Adjust the overall count countDelta += indexDelta; indexUpdateDeferred = true; // Increment currentRefreshID so any outstanding fetches don't cause trouble. If a refresh is in progress, // restart it (which will also increment currentRefreshID). if (refreshInProgress) { beginRefresh(); } else { currentRefreshID++; } }
javascript
{ "resource": "" }
q45895
updateNewIndices
train
function updateNewIndices(slot, indexDelta) { // If this slot is at the start of a sequence, transfer the indexNew if (slot.firstInSequence) { var indexNew; if (indexDelta < 0) { // The given slot is about to be removed indexNew = slot.indexNew; if (indexNew !== undefined) { delete slot.indexNew; } else { indexNew = slot.index; } if (!slot.lastInSequence) { // Update the next slot now slot = slot.next; if (indexNew !== undefined) { slot.indexNew = indexNew; } } } else { // The given slot was just inserted if (!slot.lastInSequence) { var slotNext = slot.next; indexNew = slotNext.indexNew; if (indexNew !== undefined) { delete slotNext.indexNew; } else { indexNew = slotNext.index; } if (indexNew !== undefined) { slot.indexNew = indexNew; } } } } updateNewIndicesAfterSlot(slot, indexDelta); }
javascript
{ "resource": "" }
q45896
updateNewIndicesFromIndex
train
function updateNewIndicesFromIndex(index, indexDelta) { for (var slot = slotsStart; slot !== slotListEnd; slot = slot.next) { var indexNew = slot.indexNew; if (indexNew !== undefined && index <= indexNew) { updateNewIndicesAfterSlot(slot, indexDelta); break; } } }
javascript
{ "resource": "" }
q45897
updateIndices
train
function updateIndices() { var slot, slotFirstInSequence, indexNew; for (slot = slotsStart; ; slot = slot.next) { if (slot.firstInSequence) { slotFirstInSequence = slot; if (slot.indexNew !== undefined) { indexNew = slot.indexNew; delete slot.indexNew; if (isNaN(indexNew)) { break; } } else { indexNew = slot.index; } // See if this sequence should be merged with the previous one if (slot !== slotsStart && slot.prev.index === indexNew - 1) { mergeSequences(slot.prev); } } if (slot.lastInSequence) { var index = indexNew; for (var slotUpdate = slotFirstInSequence; slotUpdate !== slot.next; slotUpdate = slotUpdate.next) { if (index !== slotUpdate.index) { changeSlotIndex(slotUpdate, index); } if (+index === index) { index++; } } } if (slot === slotListEnd) { break; } } // Clear any indices on slots that were moved adjacent to slots without indices for (; slot !== slotsEnd; slot = slot.next) { if (slot.index !== undefined && slot !== slotListEnd) { changeSlotIndex(slot, undefined); } } indexUpdateDeferred = false; if (countDelta && +knownCount === knownCount) { if (getCountPromise) { getCountPromise.reset(); } else { changeCount(knownCount + countDelta); } countDelta = 0; } }
javascript
{ "resource": "" }
q45898
addMarkers
train
function addMarkers(fetchResult) { var items = fetchResult.items, offset = fetchResult.offset, totalCount = fetchResult.totalCount, absoluteIndex = fetchResult.absoluteIndex, atStart = fetchResult.atStart, atEnd = fetchResult.atEnd; if (isNonNegativeNumber(absoluteIndex)) { if (isNonNegativeNumber(totalCount)) { var itemsLength = items.length; if (absoluteIndex - offset + itemsLength === totalCount) { atEnd = true; } } if (offset === absoluteIndex) { atStart = true; } } if (atStart) { items.unshift(startMarker); fetchResult.offset++; } if (atEnd) { items.push(endMarker); } }
javascript
{ "resource": "" }
q45899
itemChanged
train
function itemChanged(slot) { var itemNew = slot.itemNew; if (!itemNew) { return false; } var item = slot.item; for (var property in item) { switch (property) { case "data": // This is handled below break; default: if (item[property] !== itemNew[property]) { return true; } break; } } return ( listDataAdapter.compareByIdentity ? item.data !== itemNew.data : slot.signature !== itemSignature(itemNew) ); }
javascript
{ "resource": "" }