_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49400
children
train
function children (options) { var context = _children.call(this, options) var fn = options.fn var inverse = options.inverse var i = 0 var ret = '' var data var contextPath if (options.data) { data = handlebars.createFrame(options.data) } for (var j = context.length; i < j; i++) { depthIncrement(options) if (data) { data.index = i data.first = (i === 0) data.last = (i === (context.length - 1)) if (contextPath) { data.contextPath = contextPath + i } } ret = ret + fn(context[i], { data: data }) depthDecrement(options) } if (i === 0) { ret = inverse(this) } return ret }
javascript
{ "resource": "" }
q49401
indexChildren
train
function indexChildren (options) { var context = _children.call(this, options) var fn = options.fn var inverse = options.inverse var i = 0 var ret = '' var data var contextPath if (options.data) { data = handlebars.createFrame(options.data) } for (var j = context.length; i < j; i++) { indexDepthIncrement(options) if (data) { data.index = i data.first = (i === 0) data.last = (i === (context.length - 1)) if (contextPath) { data.contextPath = contextPath + i } } ret = ret + fn(context[i], { data: data }) indexDepthDecrement(options) } if (i === 0) { ret = inverse(this) } return ret }
javascript
{ "resource": "" }
q49402
isClassMember
train
function isClassMember (options) { var parent = arrayify(options.data.root).find(where({ id: this.memberof })) if (parent) { return parent.kind === 'class' } }
javascript
{ "resource": "" }
q49403
_orphans
train
function _orphans (options) { options.hash.memberof = undefined return _identifiers(options).filter(function (identifier) { if (identifier.kind === 'external') { return identifier.description && identifier.description.length > 0 } else { return true } }) }
javascript
{ "resource": "" }
q49404
_children
train
function _children (options) { if (!this.id) return [] var min = options.hash.min delete options.hash.min options.hash.memberof = this.id var output = _identifiers(options) output = output.filter(function (identifier) { if (identifier.kind === 'external') { return identifier.description && identifier.description.length > 0 } else { return true } }) if (output.length >= (min || 0)) return output }
javascript
{ "resource": "" }
q49405
descendants
train
function descendants (options) { var min = typeof options.hash.min !== 'undefined' ? options.hash.min : 2 delete options.hash.min options.hash.memberof = this.id var output = [] function iterate (childrenList) { if (childrenList.length) { childrenList.forEach(function (child) { output.push(child) iterate(_children.call(child, options)) }) } } iterate(_children.call(this, options)) if (output.length >= (min || 0)) return output }
javascript
{ "resource": "" }
q49406
exported
train
function exported (options) { var exp = arrayify(options.data.root).find(where({ '!kind': 'module', id: this.id })) return exp || this }
javascript
{ "resource": "" }
q49407
parentObject
train
function parentObject (options) { return arrayify(options.data.root).find(where({ id: this.memberof })) }
javascript
{ "resource": "" }
q49408
parseLink
train
function parseLink (text) { if (!text) return '' var results = [] var matches = null var link1 = /{@link (\S+?)}/g // {@link someSymbol} var link2 = /\[(.+?)\]{@link (\S+?)}/g // [caption here]{@link someSymbol} var link3 = /{@link ([^\s}]+?)\|(.+?)}/g // {@link someSymbol|caption here} var link4 = /{@link ([^\s}\|]+?) (.+?)}/g // {@link someSymbol Caption Here} while ((matches = link4.exec(text)) !== null) { results.push({ original: matches[0], caption: matches[2], url: matches[1] }) text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString()) } while ((matches = link3.exec(text)) !== null) { results.push({ original: matches[0], caption: matches[2], url: matches[1] }) text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString()) } while ((matches = link2.exec(text)) !== null) { results.push({ original: matches[0], caption: matches[1], url: matches[2] }) text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString()) } while ((matches = link1.exec(text)) !== null) { results.push({ original: matches[0], caption: matches[1], url: matches[1] }) text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString()) } return results }
javascript
{ "resource": "" }
q49409
parentName
train
function parentName (options) { function instantiate (input) { if (/^[A-Z]{3}/.test(input)) { return input.replace(/^([A-Z]+)([A-Z])/, function (str, p1, p2) { return p1.toLowerCase() + p2 }) } else { return input.charAt(0).toLowerCase() + input.slice(1) } } /* don't bother with a parentName for exported identifiers */ if (this.isExported) return '' if (this.memberof && this.kind !== 'constructor') { var parent = arrayify(options.data.root).find(where({ id: this.memberof })) if (parent) { if (this.scope === 'instance') { var name = parent.typicalname || parent.name return instantiate(name) } else if (this.scope === 'static' && !(parent.kind === 'class' || parent.kind === 'constructor')) { return parent.typicalname || parent.name } else { return parent.name } } else { return this.memberof } } }
javascript
{ "resource": "" }
q49410
train
function (iters) { var diff = util.now() - start; if (!setupComplete) { if (iters <= 0 && diff > PING_TIMEOUT) { frozenTabEnvironmentDetected(); util.events.emit('setupComplete'); } else { timeout = setTimeout(function () { recursiveTimeout(iters - 1); }, 5); } } }
javascript
{ "resource": "" }
q49411
train
function(value) { var T; if (value && value._bsontype) { T = value._bsontype; } else { T = Object.prototype.toString.call(value).replace(/\[object (\w+)\]/, '$1'); } if (T === 'Object') { T = 'Document'; } return T; }
javascript
{ "resource": "" }
q49412
train
function(type, value) { if (type.name === 'String') { // crop strings at 10k characters if (value.length > 10000) { value = value.slice(0, 10000); } } type.values.pushSome(value); }
javascript
{ "resource": "" }
q49413
train
function(path, value, schema) { var bsonType = getBSONType(value); // if semantic type detection is enabled, the type is the semantic type // or the original bson type if no semantic type was detected. If disabled, // it is always the bson type. var typeName = (options.semanticTypes) ? getSemanticType(value, path) || bsonType : bsonType; var type = schema[typeName] = _.get(schema, typeName, { name: typeName, bsonType: bsonType, path: path, count: 0 }); type.count++; // recurse into arrays by calling `addToType` for each element if (typeName === 'Array') { type.types = _.get(type, 'types', {}); type.lengths = _.get(type, 'lengths', []); type.lengths.push(value.length); _.each(value, function(v) { addToType(path, v, type.types); }); // recurse into nested documents by calling `addToField` for all sub-fields } else if (typeName === 'Document') { type.fields = _.get(type, 'fields', {}); _.forOwn(value, function(v, k) { addToField(path + '.' + k, v, type.fields); }); // if the `storeValues` option is enabled, store some example values } else if (options.storeValues) { type.values = _.get(type, 'values', bsonType === 'String' ? new Reservoir(100) : new Reservoir(10000)); addToValue(type, value); } }
javascript
{ "resource": "" }
q49414
initialize
train
function initialize() { const transition = new ExpandableTransition( this.ui.content ); this.transition = transition.init(); if ( this.ui.content.classList.contains( ExpandableTransition.CLASSES.EXPANDED ) ) { this.ui.target.classList.add( this.classes.targetExpanded ); } else { this.ui.target.classList.add( this.classes.targetCollapsed ); } const expandableGroup = closest( this.ui.target, '.' + this.classes.group ); this.isAccordionGroup = expandableGroup !== null && expandableGroup.classList.contains( this.classes.groupAccordion ); if ( this.isAccordionGroup ) { Events.on( 'accordionActivated', _accordionActivatedHandler.bind( this ) ); } }
javascript
{ "resource": "" }
q49415
expandableClickHandler
train
function expandableClickHandler() { this.transition.toggleExpandable(); this.toggleTargetState( this.ui.target ); if ( this.isAccordionGroup ) { if ( this.activeAccordion ) { this.activeAccordion = false; } else { Events.trigger( 'accordionActivated', { target: this } ); this.activeAccordion = true; } } }
javascript
{ "resource": "" }
q49416
toggleTargetState
train
function toggleTargetState( element ) { if ( element.classList.contains( this.classes.targetExpanded ) ) { this.ui.target.classList.add( this.classes.targetCollapsed ); this.ui.target.classList.remove( this.classes.targetExpanded ); } else { this.ui.target.classList.add( this.classes.targetExpanded ); this.ui.target.classList.remove( this.classes.targetCollapsed ); } }
javascript
{ "resource": "" }
q49417
expand
train
function expand() { this.dispatchEvent( 'expandBegin', { target: this } ); if ( !previousHeight || element.scrollHeight > previousHeight ) { previousHeight = element.scrollHeight; } element.style.maxHeight = previousHeight + 'px'; _baseTransition.applyClass( CLASSES.EXPANDED ); return this; }
javascript
{ "resource": "" }
q49418
stylesComponents
train
function stylesComponents() { return gulp.src( 'packages/' + ( component || '*' ) + '/src/*.less' ) .pipe( gulpIgnore.exclude( vf => { /* Exclude Less files that don't share the same name as the directory they're in. This filters out things like cf-vars.less but still includes cf-core.less. */ const matches = vf.path.match( /\/([\w-]*)\/src\/([\w-]*)\.less/ ); // We also exclude cf-grid. It needs its own special task. See below. return matches[2] === 'cf-grid' || matches[1] !== matches[2]; } ) ) .pipe( gulpLess( { paths: [ 'node_modules/cf-*/src/' ], compress: true } ) ) .pipe( gulpPostcss( [ autoprefixer( { browsers: BROWSER_LIST.LAST_2_PLUS_IE_8_AND_UP } ) ] ) ) .pipe( gulpRename( path => { path.dirname = component || path.dirname; path.dirname = path.dirname.replace( '/src', '' ); path.extname = '.min.css'; } ) ) .pipe( gulp.dest( 'packages' ) ); }
javascript
{ "resource": "" }
q49419
stylesGrid
train
function stylesGrid() { return gulp.src( 'packages/cf-grid/src-generated/*.less' ) .pipe( gulpLess( { paths: [ 'node_modules/cf-*/src/' ], compress: true } ) ) .pipe( gulpPostcss( [ autoprefixer( { grid: true, browsers: BROWSER_LIST.LAST_2_PLUS_IE_8_AND_UP } ) ] ) ) .pipe( gulpRename( { basename: 'cf-grid', extname: '.min.css' } ) ) .pipe( gulp.dest( 'packages/cf-grid' ) ); }
javascript
{ "resource": "" }
q49420
stylesDocs
train
function stylesDocs() { return gulp.src( 'docs/src/css/main.less' ) .pipe( gulpLess( { paths: [ 'node_modules/cf-*/src/' ], compress: true } ) ) .pipe( gulpPostcss( [ autoprefixer( { browsers: BROWSER_LIST.LAST_2_PLUS_IE_8_AND_UP } ) ] ) ) .pipe( gulp.dest( 'docs/dist/css/' ) ); }
javascript
{ "resource": "" }
q49421
lintStyles
train
function lintStyles() { // Pass all command line flags to Stylelint. const options = minimist( process.argv.slice( 2 ) ); const willFix = options.fix || false; return gulp.src( [ 'packages/**/*.less', '!packages/cf-*/node_modules/**/*.less', '!packages/cf-grid/src-generated/*.less' ] ) .pipe( gulpStylelint( { failAfterError: true, fix: willFix, reporters: [ { formatter: 'string', console: true } ] } ) ) .pipe( gulp.dest( 'packages' ) ); }
javascript
{ "resource": "" }
q49422
initialize
train
function initialize() { this.sortClass = UNDEFINED; this.sortColumnIndex = UNDEFINED; this.sortDirection = UNDEFINED; this.tableData = []; this.bindProperties(); if ( this.ui.sortButton ) { this.sortColumnIndex = this.getColumnIndex(); this.sortDirection = DIRECTIONS.UP; if ( this.ui.sortButton.classList.contains( this.classes.sortDown ) ) { this.sortDirection = DIRECTIONS.DOWN; } this.updateTable(); } }
javascript
{ "resource": "" }
q49423
bindProperties
train
function bindProperties() { let sortDirection; Object.defineProperty( this, 'sortDirection', { configurable: true, get: function() { return sortDirection; }, set: function( value ) { if ( value === DIRECTIONS.UP ) { this.sortClass = this.classes.sortUp; } else if ( value === DIRECTIONS.DOWN ) { this.sortClass = this.classes.sortDown; } sortDirection = value; } } ); }
javascript
{ "resource": "" }
q49424
updateTableData
train
function updateTableData( columnIndex ) { let cell; const rows = this.ui.tableBody.querySelectorAll( 'tr' ); this.tableData = []; columnIndex = columnIndex || this.sortColumnIndex; for ( let i = 0, len = rows.length; i < len; ++i ) { cell = rows[i].cells[columnIndex]; if ( cell ) { cell = cell.textContent.trim(); } this.tableData.push( [ cell, rows[i] ] ); } const sortType = this.ui.sortButton.getAttribute( 'data-sort_type' ); this.tableData.sort( this.tableDataSorter( this.sortDirection, sortType ) ); return this.tableData; }
javascript
{ "resource": "" }
q49425
updateTableDom
train
function updateTableDom() { const tableBody = this.ui.tableBody; /* Empty the table body to prepare for sorting the rows TODO: It might make sense to use innerHTML from a performance and garbage collection standpoint. */ while ( tableBody.lastChild ) { tableBody.removeChild( tableBody.lastChild ); } const documentFragment = document.createDocumentFragment(); for ( let i = 0; i < this.tableData.length; i++ ) { documentFragment.appendChild( this.tableData[i][1] ); } tableBody.appendChild( documentFragment ); this.trigger( 'table:updated' ); return tableBody; }
javascript
{ "resource": "" }
q49426
onRowLinkClick
train
function onRowLinkClick( event ) { let target = event.target; if ( target && target.tagName === 'A' ) { return; } target = closest( event.target, 'tr' ); const link = target.querySelector( 'a' ); if ( link ) { window.location = link.getAttribute( 'href' ); } }
javascript
{ "resource": "" }
q49427
AtomicComponent
train
function AtomicComponent( element, attributes ) { this.element = element; this.initializers = []; this.uId = this.uniqueId( 'ac' ); assign( this, attributes ); this.processModifiers(); this.ensureElement(); this.setCachedElements(); this.initializers.push( this.initialize ); this.initializers.forEach( function( func ) { if ( isFunction( func ) ) func.apply( this, arguments ); }, this ); this.trigger( 'component:initialized' ); }
javascript
{ "resource": "" }
q49428
train
function( attributes ) { let property; for ( property in attributes ) { if ( attributes.hasOwnProperty( property ) ) { this.element.setAttribute( property, attributes[property] ); } } }
javascript
{ "resource": "" }
q49429
getBinary
train
function getBinary( packageName, binaryName, binaryDir ) { binaryName = binaryName || packageName; binaryDir = binaryDir || 'bin'; const pkgPath = require.resolve( packageName ); binaryDir = path.resolve( path.join( path.dirname( pkgPath ), binaryDir, '/' + binaryName ) ); return binaryDir; }
javascript
{ "resource": "" }
q49430
moveLeft
train
function moveLeft( count ) { count = count || 1; const moveClasses = [ CLASSES.MOVE_LEFT, CLASSES.MOVE_LEFT_2X, CLASSES.MOVE_LEFT_3X ]; if ( count < 1 || count > moveClasses.length ) { throw new Error( 'MoveTransition: moveLeft count is out of range!' ); } _baseTransition.applyClass( moveClasses[count - 1] ); return this; }
javascript
{ "resource": "" }
q49431
Bootprint
train
function Bootprint (withData, targetDir) { /** * Run Bootprint and write the result to the specified target directory * @param options {object} options passed to Customize#run() * @returns {Promise} a promise for the completion of the build */ this.generate = function generate (options) { return withData.run(options).then(write(targetDir)) } /** * Run the file watcher to watch all files loaded into the * current Bootprint-configuration. * The watcher run Bootprint every time one the the input files, templates or helpers changes. * @returns {EventEmitter} an EventEmitter that sends an `update`-event after each * build, but before the files are written to disc. */ this.watch = function () { return withData.watch().on('update', write(targetDir)) } }
javascript
{ "resource": "" }
q49432
loadFromFileOrHttp
train
function loadFromFileOrHttp (fileOrUrlOrData) { // If this is not a string, // it is probably already the raw data. if (typeof fileOrUrlOrData !== 'string') { return Q(fileOrUrlOrData) } // otherwise load data from url or file if (fileOrUrlOrData.match(/^https?:\/\//)) { // Use the "request" package to download data return httpGet(fileOrUrlOrData, { redirect: true, headers: { 'User-Agent': 'Bootprint/' + require('./package').version } }).then(function (result) { if (result.status !== 200) { var error = new Error('HTTP request failed with code ' + result.status) error.result = result throw error } return yaml.safeLoad(result.data, {json: true}) }, function (error) { if (error.status) { throw new Error('Got ' + error.status + ' ' + error.data + ' when requesting ' + error.url, 'E_HTTP') } else { throw error } }) } else { return Q.nfcall(fs.readFile, fileOrUrlOrData, 'utf8').then(function (data) { return yaml.safeLoad(data, {json: true}) }) } }
javascript
{ "resource": "" }
q49433
nanomatch
train
function nanomatch(list, patterns, options) { patterns = utils.arrayify(patterns); list = utils.arrayify(list); const len = patterns.length; if (list.length === 0 || len === 0) { return []; } if (len === 1) { return nanomatch.match(list, patterns[0], options); } let negated = false; const omit = []; const keep = []; let idx = -1; while (++idx < len) { const pattern = patterns[idx]; if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); negated = true; } else { keep.push.apply(keep, nanomatch.match(list, pattern, options)); } } // minimatch.match parity if (negated && keep.length === 0) { if (options && options.unixify === false) { keep = list.slice(); } else { const unixify = utils.unixify(options); for (var i = 0; i < list.length; i++) { keep.push(unixify(list[i])); } } } const matches = utils.diff(keep, omit); if (!options || options.nodupes !== false) { return utils.unique(matches); } return matches; }
javascript
{ "resource": "" }
q49434
compose
train
function compose(patterns, options, matcher) { let matchers; return memoize('compose', String(patterns), options, function() { return function(file) { // delay composition until it's invoked the first time, // after that it won't be called again if (!matchers) { matchers = []; for (var i = 0; i < patterns.length; i++) { matchers.push(matcher(patterns[i], options)); } } let len = matchers.length; while (len--) { if (matchers[len](file) === true) { return true; } } return false; }; }); }
javascript
{ "resource": "" }
q49435
blankshield
train
function blankshield(target) { if (typeof target.length === 'undefined') { addEventListener(target, 'click', clickListener); } else if (typeof target !== 'string' && !(target instanceof String)) { for (var i = 0; i < target.length; i++) { addEventListener(target[i], 'click', clickListener); } } }
javascript
{ "resource": "" }
q49436
clickListener
train
function clickListener(e) { var target, targetName, href, usedModifier; // Use global event object for IE8 and below to get target e = e || window.event; // Won't work for IE8 and below for cases when e.srcElement // refers not to the anchor, but to the element inside it e.g. an image target = e.currentTarget || e.srcElement; // Ignore anchors without an href href = target.getAttribute('href'); if (!href) return; // Ignore anchors without an unsafe target or modifier key usedModifier = (e.ctrlKey || e.shiftKey || e.metaKey); targetName = target.getAttribute('target'); if (!usedModifier && (!targetName || safeTarget(targetName))) { return; } blankshield.open(href); // IE8 and below don't support preventDefault if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return false; }
javascript
{ "resource": "" }
q49437
addEventListener
train
function addEventListener(target, type, listener) { var onType, prevListener; // Modern browsers if (target.addEventListener) { return target.addEventListener(type, listener, false); } // Older browsers onType = 'on' + type; if (target.attachEvent) { target.attachEvent(onType, listener); } else if (target[onType]) { prevListener = target[onType]; target[onType] = function() { listener(); prevListener(); }; } else { target[onType] = listener; } }
javascript
{ "resource": "" }
q49438
skipDeleted
train
function skipDeleted (model, attrs, options) { if (!options.isEager || options.parentResponse) { let softDelete = this.model ? this.model.prototype.softDelete : this.softDelete if (softDelete && !options.withDeleted) { if (settings.nullValue === null) { options.query.whereNull(`${result(this, 'tableName')}.${settings.field}`) } else { options.query.where(`${result(this, 'tableName')}.${settings.field}`, settings.nullValue) } } } }
javascript
{ "resource": "" }
q49439
train
function (options) { options = options || {} if (this.softDelete && !options.hardDelete) { let query = this.query() // Add default values to options options = merge( { method: 'update', patch: true, softDelete: true, query: query }, options ) const date = options.date ? new Date(options.date) : new Date() // Attributes to be passed to events let attrs = { [settings.field]: date } // Null out sentinel column, since NULL is not considered by SQL unique indexes if (settings.sentinel) { attrs[settings.sentinel] = null } // Make sure the field is formatted the same as other date columns attrs = this.format(attrs) return Promise.resolve() .then(() => { // Don't need to trigger hooks if there's no events registered if (!settings.events) return let events = [] // Emulate all pre update events if (settings.events.destroying) { events.push( this.triggerThen('destroying', this, options).bind(this) ) } if (settings.events.saving) { events.push( this.triggerThen('saving', this, attrs, options).bind(this) ) } if (settings.events.updating) { events.push( this.triggerThen('updating', this, attrs, options).bind(this) ) } // Resolve all promises in parallel like bookshelf does return Promise.all(events) }) .then(() => { // Check if we need to use a transaction if (options.transacting) { query = query.transacting(options.transacting) } return query .update(attrs, this.idAttribute) .where(this.format(this.attributes)) .where(`${result(this, 'tableName')}.${settings.field}`, settings.nullValue) }) .then((resp) => { // Check if the caller required a row to be deleted and if // events weren't totally disabled if (resp === 0 && options.require) { throw new this.constructor.NoRowsDeletedError('No Rows Deleted') } else if (!settings.events) { return } // Add previous attr for reference and reset the model to pristine state this.set(attrs) options.previousAttributes = this._previousAttributes this._reset() let events = [] // Emulate all post update events if (settings.events.destroyed) { events.push( this.triggerThen('destroyed', this, options).bind(this) ) } if (settings.events.saved) { events.push( this.triggerThen('saved', this, resp, options).bind(this) ) } if (settings.events.updated) { events.push( this.triggerThen('updated', this, resp, options).bind(this) ) } return Promise.all(events) }) .then(() => this) } else { return modelPrototype.destroy.call(this, options) } }
javascript
{ "resource": "" }
q49440
getNextVal
train
function getNextVal(searchVal, mapping) { let value if (isMap(mapping)) { for (let [key, val] of mapping.entries()) { if (deepEqual(key, searchVal)) { value = val break } } } else { value = (mapping.find(keyVal => deepEqual(keyVal[0], searchVal)) || [])[1] } if (typeof value === 'function') { return value() } return value }
javascript
{ "resource": "" }
q49441
stringifyVal
train
function stringifyVal(val) { return JSON.stringify( val, (key, val) => { if (typeof val === 'function') { if (val.name) { return `[Function: ${val.name}]: ${val.toString()}` } else { return `[Function]: ${val.toString()}` } } return val }, 2 ) }
javascript
{ "resource": "" }
q49442
stringify
train
function stringify(data, visitor, indent) { if (typeof data === 'function' || typeof data === 'undefined') { // eslint-disable-next-line consistent-return return undefined; } indent = parseIndent(indent); const normalized = JSON.parse(JSON.stringify(data, visitor)); function visitNode(node, options) { if (options == null) { options = {}; } switch (typeof node) { case 'boolean': return `${node}`; case 'number': if (isFinite(node)) { return `${node}`; } return 'null'; case 'string': return visitString(visitNode, indent, node, options); case 'object': if (node === null) { return 'null'; } else if (Array.isArray(node)) { return visitArray(visitNode, indent, node, options); } return visitObject(visitNode, indent, node, options); default: // eslint-disable-next-line consistent-return return undefined; } } // eslint-disable-next-line consistent-return return visitNode(normalized); }
javascript
{ "resource": "" }
q49443
AppServiceRegistration
train
function AppServiceRegistration(appServiceUrl) { this.url = appServiceUrl; this.id = null; this.hs_token = null; this.as_token = null; this.sender_localpart = null; this.rate_limited = true; this.namespaces = { users: [], aliases: [], rooms: [] }; this.protocols = null; this._cachedRegex = {}; }
javascript
{ "resource": "" }
q49444
fieldTypes
train
function fieldTypes (type) { switch (type) { case constants.ID: case constants.string: return 'string' case constants.int: case constants.float: return 'number' default: } }
javascript
{ "resource": "" }
q49445
train
function (callback) { gm(input).identify("%p ", function (err, value) { var pageCount = String(value).split(' '); if (!pageCount.length) { callback({ result: 'error', message: 'Invalid page number.' }, null); } else { // Convert selected page if (options.page !== null) { if (options.page <= pageCount.length) { callback(null, [options.page]); } else { callback({ result: 'error', message: 'Invalid page number.' }, null); } } else { callback(null, pageCount); } } }) }
javascript
{ "resource": "" }
q49446
train
function(pages, callback) { // Use eachSeries to make sure that conversion has done page by page async.eachSeries(pages, function(page, callbackmap) { var inputStream = fs.createReadStream(input); var outputFile = options.outputdir + options.outputname + '_' + page + '.' + options.type; convertPdf2Img(inputStream, outputFile, parseInt(page), function(error, result) { if (error) { return callbackmap(error); } stdout.push(result); return callbackmap(error, result); }); }, function(e) { if (e) callback(e); return callback(null, { result: 'success', message: stdout }); }); }
javascript
{ "resource": "" }
q49447
parse
train
function parse(text, visibleTextOnly) { var parser = new Parser(); var email = parser.parse(text); if (visibleTextOnly) { if (!email) return ''; else return email.getVisibleText(); } else return email; }
javascript
{ "resource": "" }
q49448
NodeAssetManifestGenerator
train
function NodeAssetManifestGenerator(inputTrees, options) { options = options || {}; this.appName = options.appName; Plugin.call(this, [ inputTrees ], { annotation: options.annotation }); }
javascript
{ "resource": "" }
q49449
AssetManifestGenerator
train
function AssetManifestGenerator(inputTrees, options) { options = options || {}; this.prepend = options.prepend || ''; this.filesToIgnore = options.filesToIgnore || []; this.supportedTypes = options.supportedTypes || DEFAULT_SUPPORTED_TYPES; this.generateURI = options.generateURI || function generateURI(filePath) { return filePath; }; Plugin.call(this, inputTrees, { annotation: options.annotation }); }
javascript
{ "resource": "" }
q49450
reduceManifestBundles
train
function reduceManifestBundles(input, manifest) { // If manifest doesn't have any bundles, then no reducing to do if (!manifest.bundles) { return input; } // Merge the bundles together, checking for collisions return Object.keys(manifest.bundles).reduce((output, bundle) => { Ember.assert(`The bundle "${bundle}" already exists.`, !output.bundles[bundle]); output.bundles[bundle] = manifest.bundles[bundle]; return output; }, input); }
javascript
{ "resource": "" }
q49451
train
function() { var tree = this._super.treeForApp.apply(this, arguments); var app = findHost(this); if (app && app.options && app.options.assetLoader && app.options.assetLoader.noManifest) { tree = new Funnel(tree, { exclude: [ 'config/asset-manifest.js', 'instance-initializers/load-asset-manifest.js' ] }); } return tree; }
javascript
{ "resource": "" }
q49452
getSubmodules
train
function getSubmodules(packageRoot) { const submodules = {}; const parentPath = resolve(packageRoot, './modules'); if (fs.existsSync(parentPath)) { //monorepo fs.readdirSync(parentPath) .forEach(item => { const itemPath = resolve(parentPath, item); const moduleInfo = getModuleInfo(itemPath); if (moduleInfo) { submodules[moduleInfo.name] = moduleInfo; } }); } else { const moduleInfo = getModuleInfo(packageRoot); submodules[moduleInfo.name] = moduleInfo; } return submodules; }
javascript
{ "resource": "" }
q49453
getHeroExample
train
function getHeroExample() { const EXAMPLES = getExamples(); const exampleNames = Object.keys(EXAMPLES); let DefaultHeroExample = exampleNames.length && EXAMPLES[0]; // HACK/ib - Check if this is a dummy example injected to keep graphgl happy // Set to null if undefined if (!DefaultHeroExample || DefaultHeroExample.title === "none") { DefaultHeroExample = null; } const HeroExample = DefaultHeroExample; if (!HeroExample) { console.warn("ocular: No hero example found", EXAMPLES); // eslint-disable-line } return HeroExample; }
javascript
{ "resource": "" }
q49454
stringify
train
function stringify(key, value) { if (value instanceof RegExp) { return value.toString(); } if (value instanceof Function) { return '[function]'; } return value; }
javascript
{ "resource": "" }
q49455
train
function(pkgManagerName, pkgName, versionRange, callback) { if (!myCache) { myCache = cache({ base: require('os').homedir() + "/.auditjs", name: 'auditjs3x', duration: 1000 * 3600 * CACHE_DURATION_HOURS //one day }); } cleanCache(); auditPackagesImpl([{pm: pkgManagerName, name: pkgName, version: versionRange}], callback); }
javascript
{ "resource": "" }
q49456
getLockfileDependencies
train
function getLockfileDependencies(root) { var deps = {}; if (root.name && root.version) { deps[root.name + "@" + root.version] = { "pm": "npm", "name": root.name, "version": root.version }; } if (root.dependencies) { for (var name in root.dependencies) { var dep = root.dependencies[name]; if (dep.version) { deps[name + "@" + dep.version] = { "pm": "npm", "name": name, "version": dep.version }; } var childDeps = getLockfileDependencies(root.dependencies[name]); for (var attr in childDeps) { deps[attr] = childDeps[attr]; } } } return Object.keys(deps).map(function (k) { return deps[k];}); }
javascript
{ "resource": "" }
q49457
exitHandler
train
function exitHandler(options, err) { if (err) { if (err.stack) { console.error(err.stack); } else { console.error(err.toString()); } } if (whitelistedVulnerabilities.length > 0) { logger.info(colors.bold.yellow("Filtering the following vulnerabilities")); logger.info(colors.bold.yellow('==================================================')); for (var i = 0; i < whitelistedVulnerabilities.length; i++) { var detail = whitelistedVulnerabilities[i]; logger.info(`${colors.bold.blue(detail['title'])} affected versions: ${colors.red(detail['package'])} ${colors.red(detail['versions'])}`); logger.info(`${detail['description']}`); logger.info(colors.bold("ID") + ": " + detail.id); if (detail.whitelistedPaths) { detail.whitelistedPaths.forEach(function(path) { logger.info(colors.bold("Ignored Path") + ": " + path); }) } logger.info(colors.bold.yellow('==================================================')); }; } logger.info(''); logger.info('Audited dependencies: ' + actualAudits + ', Vulnerable: ' + colors.bold.red(vulnerabilityCount) + ', Ignored: ' + whitelistedVulnerabilities.length); if(config.get('report')) { var filtered = whitelistedVulnerabilities.length; mkdirp('reports'); if (JUnit[0] != '<') { // This is a hack in case this gets called twice // Convert to XML JUnit = jsontoxml(JUnit); } var dom = new DOMParser().parseFromString(JUnit); dom.documentElement.setAttribute('name', `auditjs.security.${programPackage.split('.')[0]}`); dom.documentElement.setAttribute('errors', 0); dom.documentElement.setAttribute('tests', expectedAudits); dom.documentElement.setAttribute('package', 'test'); dom.documentElement.setAttribute('id', ''); dom.documentElement.setAttribute('skipped', filtered); dom.documentElement.setAttribute('failures', vulnerabilityCount); JUnit = new XMLSerializer().serializeToString(dom); logger.info( `Wrote JUnit report to reports/${output}`); fs.writeFileSync('reports/' + output, `<?xml version="1.0" encoding="UTF-8"?>\n${JUnit}`); } if (config.get('suppressExitError')) { process.exit(0); } else { process.exit(vulnerabilityCount); } }
javascript
{ "resource": "" }
q49458
checkProperties
train
function checkProperties(obj) { for (var key in obj) { if (obj[key] !== null && obj[key] != "") return false; } return true; }
javascript
{ "resource": "" }
q49459
buildDependencyObjectLookup
train
function buildDependencyObjectLookup(data, lookup, parentPath) { if (lookup == undefined) { lookup = {}; } parentPath = parentPath || ''; for(var k in data.dependencies) { var dep = data.dependencies[k]; depPath = parentPath + '/' + dep.name; var lookupKey = 'UNKNOWN'; //If we can't find a key below, something's wrong. var depToStore = dep; if (dep.name) { lookupKey = dep.name + '@' + dep.version } else if (dep._from) { lookupKey = dep._from; } else if (dep.requiredBy) { // If we can't find the node_modules folder, we'll get 'requiredBy' instead. lookupKey = k + "@" + dep.requiredBy; depToStore = extractDep(data.dependencies[k]); } var existing = lookup[lookupKey]; if (existing) { existing.depPaths.push(depPath); } else { lookup[lookupKey] = depToStore; lookup[lookupKey].depPaths = [depPath]; } buildDependencyObjectLookup(dep, lookup, depPath); } return lookup; }
javascript
{ "resource": "" }
q49460
getDependencyList
train
function getDependencyList(depMap, depLookup) { var results = []; var lookup = {}; var keys = Object.keys(depMap); for(var i = 0; i < keys.length; i++) { var name = keys[i]; // The value of o depends on the type of structure we are passed var o = depMap[name]; var spec = o.version ? name + "@" + o.version : name + "@" + o; var version = o.version ? o.version : o; var depPaths = o.depPaths ? o.depPaths : [spec]; // Only add a dependency once // We need both the local and global "auditLookup" tables. // The global lookup is used to ensure we only audit a // dependency once, but cannot be done at the same level // as the local lookup since the sub-dependencies are not // available at all locations of the dependency tree (depMap). if(lookup[spec] == undefined && auditLookup[spec] == undefined) { lookup[spec] = true; auditLookup[spec] = true; results.push({"pm": config.get("pm"), "name": name, "version": version, "depPaths": depPaths}); // If there is a possibility of recursive dependencies... if (o.version) { var dataDeps = getDepsFromDataObject(o, depLookup); if(dataDeps) { var deps = getDependencyList(dataDeps, depLookup); if(deps != undefined) { results = results.concat(deps); } } } } } return results; }
javascript
{ "resource": "" }
q49461
lookupSpecMatch
train
function lookupSpecMatch(lookup, spec) { // Direct match if (lookup[spec]) { return lookup[spec]; } // Close match var shortSpec = spec.replace(/@\D/g,'@'); if (lookup[shortSpec]) { return lookup[shortSpec]; } // Check for Semver valid match var lastIndex = spec.lastIndexOf('@'); var myName = spec.substring(0, lastIndex); var myVersion = spec.substring(lastIndex + 1); for(var k in lookup) { lastIndex = k.lastIndexOf('@'); var yourName = k.substring(0, lastIndex); var yourVersion = k.substring(lastIndex + 1); if (myName == yourName && semver.valid(yourVersion) && semver.satisfies(yourVersion, myVersion)) { return lookup[k]; } } return undefined; }
javascript
{ "resource": "" }
q49462
getDepsFromDataObject
train
function getDepsFromDataObject(data, lookup) { var results = {}; if (categories.length == 0) { for(var k in data.dependencies) { var dep = extractDep(data.dependencies[k]); results[k]=dep; } } if (lookup) { for (var i = 0; i < categories.length; i++) { var category = categories[i]; for(var k in data[category]) { var spec = k + "@" + data[category][k]; var specMatch = lookupSpecMatch(lookup, spec); // If there is no match in the lookup then this dependency was "deduped" if (specMatch) { results[k]=specMatch; } } } } return results; }
javascript
{ "resource": "" }
q49463
getValidVulnerabilities
train
function getValidVulnerabilities(productRange, details, pkg, depPaths) { var results = []; if(details != undefined) { for(var i = 0; i < details.length; i++) { var detail = details[i]; detail.depPaths = depPaths; // Do we white-list this match? var id = detail.id; if (whitelist && whitelist[id]) { var whitelistEntry = whitelist[id]; if (whitelistEntry.dependencyPaths) { for (var whitelistIdx = 0; whitelistIdx < whitelistEntry.dependencyPaths.length; whitelistIdx++) { var wDep = whitelistEntry.dependencyPaths[whitelistIdx]; var regex = new RegExp(wDep); detail.depPaths = detail.depPaths.filter(function(dDep) { if (regex.test(dDep)){ detail.whitelistedPaths = detail.whitelistedPaths || []; detail.whitelistedPaths.push(dDep); return false; } return true; }); } detail["package"] = pkg; whitelistedVulnerabilities.push(detail); if (detail.depPaths.length == 0) { console.log('SKIPPING BECAUSE ALL PATHS MATCHED') } } else { detail["package"] = pkg; whitelistedVulnerabilities.push(detail); } } else { results.push(detail); } } } return results; }
javascript
{ "resource": "" }
q49464
simplifyWhitelist
train
function simplifyWhitelist(whitelist) { var results = []; if (Array.isArray(whitelist)) { // whitelist is in Simplified format for (var i = 0; i < whitelist.length; i++) { results.push({ "id": whitelist[i] }); } } else { // whitelist is in Verbose format for (var project in whitelist) { var vlist = whitelist[project]; for (var i = 0; i < vlist.length; i++) { var id = vlist[i].id; results.push({ "id": id, "dependencyPaths": vlist[i].dependencyPaths }); } } } return results; }
javascript
{ "resource": "" }
q49465
loadConfig
train
function loadConfig() { underload('whitelist', 'whitelist.file'); if (!program['bower'] && config.has('packages.type') && config.get('packages.type') == 'bower') { program['bower'] = true; } if (!program['noNode'] && config.has('packages.withNode') && config.get('packages.withNode') == false) { program['noNode'] = true; } underload('package', 'packages.file'); underload('level', 'logging.level'); underload('quiet', 'logging.quiet'); underload('verbose', 'logging.verbose'); underload('scheme', 'server.scheme'); underload('host', 'server.host'); underload('port', 'server.port'); underload('cacheDir', 'cache.path'); underload('cacheTimeout', 'cache.timeout') underload('username', 'auth.user'); underload('token', 'auth.token'); }
javascript
{ "resource": "" }
q49466
underload
train
function underload(cmdlineName, configName) { if (!program[cmdlineName] && config.has(configName)) { program[cmdlineName] = config.get(configName); } }
javascript
{ "resource": "" }
q49467
getNoDataNode
train
function getNoDataNode () { return { category: 'none', // Used to distinguish fake nodes like this from real ones children: [], functionName: 'No data.', fileName: 'Nothing to show currently.', id: null, // Don't show any id in the url hash name: '', onStackTop: { asViewed: 0, base: 0, rootFromMean: 0 }, type: 'no-data', // Used for this node specifically, indicating no visible data areaText: 'No frames are visible', // Trailing '.' is added in info-box.js getNodeRect: function () { return { x: 0, y: 0, width: 0, height: 0 } } } }
javascript
{ "resource": "" }
q49468
toCodeAreaChildren
train
function toCodeAreaChildren (set) { return Array.from(set, (id) => { return { id } }).sort(sorter) function sorter (a, b) { return a.id.localeCompare(b.id) } }
javascript
{ "resource": "" }
q49469
autoSelectFromAB
train
function autoSelectFromAB(string, isA) { var ranges = isA ? A_CHARS : B_CHARS; var untilC = string.match(new RegExp('^(' + ranges + '+?)(([0-9]{2}){2,})([^0-9]|$)')); if (untilC) { return untilC[1] + String.fromCharCode(204) + autoSelectFromC(string.substring(untilC[1].length)); } var chars = string.match(new RegExp('^' + ranges + '+'))[0]; if (chars.length === string.length) { return string; } return chars + String.fromCharCode(isA ? 205 : 206) + autoSelectFromAB(string.substring(chars.length), !isA); }
javascript
{ "resource": "" }
q49470
encode
train
function encode(data, structure, separator) { var encoded = data.split('').map(function (val, idx) { return BINARIES[structure[idx]]; }).map(function (val, idx) { return val ? val[data[idx]] : ''; }); if (separator) { var last = data.length - 1; encoded = encoded.map(function (val, idx) { return idx < last ? val + separator : val; }); } return encoded.join(''); }
javascript
{ "resource": "" }
q49471
checksum$4
train
function checksum$4(data) { var result = 0; for (var i = 0; i < 13; i++) { result += parseInt(data[i]) * (3 - i % 2 * 2); } return Math.ceil(result / 10) * 10 - result; }
javascript
{ "resource": "" }
q49472
JsBarcode
train
function JsBarcode(element, text, options) { var api = new API(); if (typeof element === "undefined") { throw Error("No element to render on was provided."); } // Variables that will be pased through the API calls api._renderProperties = getRenderProperties(element); api._encodings = []; api._options = defaults$1; api._errorHandler = new ErrorHandler(api); // If text is set, use the simple syntax (render the barcode directly) if (typeof text !== "undefined") { options = options || {}; if (!options.format) { options.format = autoSelectBarcode(); } api.options(options)[options.format](text, options).render(); } return api; }
javascript
{ "resource": "" }
q49473
render
train
function render(renderProperties, encodings, options) { encodings = linearizeEncodings(encodings); for (var i = 0; i < encodings.length; i++) { encodings[i].options = merge(options, encodings[i].options); fixOptions(encodings[i].options); } fixOptions(options); var Renderer = renderProperties.renderer; var renderer = new Renderer(renderProperties.element, encodings, options); renderer.render(); if (renderProperties.afterRender) { renderProperties.afterRender(); } }
javascript
{ "resource": "" }
q49474
resolveTheme
train
function resolveTheme(home_) { var themePath var settings = getSettings(home_) if (!settings || !settings.theme) return undefined try { // allow specifying just the name of a built-in theme or a full path to a custom theme themePath = utl.isPath(settings.theme) ? settings.theme : path.join(__dirname, 'themes', settings.theme) return require(themePath) } catch (e) { // Specified theme path is invalid console.error(e) return undefined } }
javascript
{ "resource": "" }
q49475
afterHeadersResolve
train
function afterHeadersResolve (body, result) { logger.info(methodName+': running `afterHeaders` hook'); globalize.afterHeaders.call(threadneedle, config, null, body, params, result.response) .done( function (headers) { resolve(formatResponse(headers, body)); }, function (error) { reject(formatResponse({}, error)); } ); }
javascript
{ "resource": "" }
q49476
afterHeadersReject
train
function afterHeadersReject (error, payload, response) { logger.info(methodName+': running `afterHeaders` hook'); globalize.afterHeaders.call(threadneedle, config, error, payload, params, response) .done( function (headers) { reject(formatResponse(headers, error)); }, function (err) { reject(formatResponse({}, err || error)); } ); }
javascript
{ "resource": "" }
q49477
train
function(path, next) { var nodes = lessFiles[path].imports; if (!nodes || !nodes.length) { return next(); } var pending = nodes.length; var changed = []; nodes.forEach(function(imported){ fs.stat(imported.path, function(err, stat) { // error or newer mtime if (err || !imported.mtime || stat.mtime > imported.mtime) { changed.push(imported.path); } --pending || next(changed); }); }); }
javascript
{ "resource": "" }
q49478
getPlugins
train
function getPlugins (options) { var plugins = options.use || options.u; if (!plugins) { plugins = getDefaultPlugins(options); } else { if (typeof plugins === 'string') { plugins = [plugins]; } } var postcssBefore = options.postcssBefore || options.before || []; var postcssAfter = options.postcssAfter || options.after || []; plugins = (Array.isArray(postcssBefore) ? postcssBefore : [postcssBefore]).concat(plugins).concat(postcssAfter); // load plugins by name (if a string is used) return plugins.map(function requirePlugin (name) { // assume not strings are already required plugins if (typeof name !== 'string') { return name; } var plugin = module.parent.require(name); // custom scoped name generation if (name === 'postcss-modules-scope') { options[name] = options[name] || {}; if (!options[name].generateScopedName) { options[name].generateScopedName = generateLongName; } } if (name in options) { plugin = plugin(options[name]); } else { plugin = plugin.postcss || plugin(); } return plugin; }); }
javascript
{ "resource": "" }
q49479
train
function(el) { var mirrorEl = document.createElement('div'); mirrorEl.className = 'preview-code'; mirrorEl.style.position = 'absolute'; mirrorEl.style.left = '-9999px'; bodyEl.appendChild(mirrorEl); var maxHeight = parseInt( window.getComputedStyle(el).getPropertyValue('max-height'), 10); var codeDidChange = function(ev) { mirrorEl.textContent = this.value + '\n'; var height = mirrorEl.offsetHeight + 2; // Account for borders. if (height >= maxHeight) { this.style.overflow = 'auto'; } else { this.style.overflow = 'hidden'; } this.style.height = (mirrorEl.offsetHeight + 2) + 'px'; }; el.addEventListener('keypress', codeDidChange); el.addEventListener('keyup', codeDidChange); codeDidChange.call(el); }
javascript
{ "resource": "" }
q49480
train
function(width) { document.cookie = 'preview-width=' + width; forEach(resizeableEls, function(el) { if (width === 'auto') width = el.parentNode.offsetWidth; el.style.width = width + 'px'; // TODO: Add CSS transitions and update height after `transitionend` event postMessage(el.getElementsByTagName('iframe')[0], 'getHeight'); }); }
javascript
{ "resource": "" }
q49481
encode
train
function encode(buf) { if (buf.length != 8) { throw new TypeError("Buffer must be length 8"); } var num = new UInt64(buf.readUInt32BE(4), buf.readUInt32BE(0)); var str = ""; do { num.div(SIXTY_TWO); str = CHARS[num.remainder] + str; } while (num.greaterThan(ZERO)); return str; }
javascript
{ "resource": "" }
q49482
requestBundles
train
function requestBundles(requestedLangs = navigator.languages) { return L10nRegistry.getResources(requestedLangs, resIds).then( ({bundles}) => bundles.map( bundle => new ChromeResourceBundle(bundle.locale, bundle.resources) ) ); }
javascript
{ "resource": "" }
q49483
createHeadContextWith
train
function createHeadContextWith(createContext, bundles) { const [bundle] = bundles; if (!bundle) { return Promise.resolve(null); } return bundle.fetch().then(resources => { const ctx = createContext(bundle.lang); resources // Filter out resources which failed to load correctly (e.g. 404). .filter(res => res !== null) .forEach(res => ctx.addMessages(res)); // Save the reference to the context. contexts.set(bundle, ctx); return ctx; }); }
javascript
{ "resource": "" }
q49484
requestBundles
train
function requestBundles(requestedLangs = navigator.languages) { const newLangs = negotiateLanguages( requestedLangs, availableLangs, { defaultLocale } ); const bundles = newLangs.map( lang => new ResourceBundle(lang, resIds) ); return Promise.resolve(bundles); }
javascript
{ "resource": "" }
q49485
isElementAllowed
train
function isElementAllowed(element) { const allowed = ALLOWED_ELEMENTS[element.namespaceURI]; if (!allowed) { return false; } return allowed.indexOf(element.tagName.toLowerCase()) !== -1; }
javascript
{ "resource": "" }
q49486
isAttrAllowed
train
function isAttrAllowed(attr, element) { const allowed = ALLOWED_ATTRIBUTES[element.namespaceURI]; if (!allowed) { return false; } const attrName = attr.name.toLowerCase(); const elemName = element.tagName.toLowerCase(); // Is it a globally safe attribute? if (allowed.global.indexOf(attrName) !== -1) { return true; } // Are there no allowed attributes for this element? if (!allowed[elemName]) { return false; } // Is it allowed on this element? if (allowed[elemName].indexOf(attrName) !== -1) { return true; } // Special case for value on HTML inputs with type button, reset, submit if (element.namespaceURI === 'http://www.w3.org/1999/xhtml' && elemName === 'input' && attrName === 'value') { const type = element.type.toLowerCase(); if (type === 'submit' || type === 'button' || type === 'reset') { return true; } } return false; }
javascript
{ "resource": "" }
q49487
getIndexOfType
train
function getIndexOfType(element) { let index = 0; let child; while ((child = element.previousElementSibling)) { if (child.tagName === element.tagName) { index++; } } return index; }
javascript
{ "resource": "" }
q49488
html
train
function html(h, node) { return h.dangerous ? h.augment(node, u('raw', node.value)) : null }
javascript
{ "resource": "" }
q49489
wrap
train
function wrap(nodes, loose) { var result = [] var index = -1 var length = nodes.length if (loose) { result.push(u('text', '\n')) } while (++index < length) { if (index) { result.push(u('text', '\n')) } result.push(nodes[index]) } if (loose && nodes.length !== 0) { result.push(u('text', '\n')) } return result }
javascript
{ "resource": "" }
q49490
unknown
train
function unknown(h, node) { if (text(node)) { return h.augment(node, u('text', node.value)) } return h(node, 'div', all(h, node)) }
javascript
{ "resource": "" }
q49491
one
train
function one(h, node, parent) { var type = node && node.type var fn = own.call(h.handlers, type) ? h.handlers[type] : null // Fail on non-nodes. if (!type) { throw new Error('Expected node, got `' + node + '`') } return (typeof fn === 'function' ? fn : unknown)(h, node, parent) }
javascript
{ "resource": "" }
q49492
text
train
function text(node) { var data = node.data || {} if ( own.call(data, 'hName') || own.call(data, 'hProperties') || own.call(data, 'hChildren') ) { return false } return 'value' in node }
javascript
{ "resource": "" }
q49493
factory
train
function factory(tree, options) { var settings = options || {} var dangerous = settings.allowDangerousHTML h.dangerous = dangerous h.definition = definitions(tree, settings) h.footnotes = [] h.augment = augment h.handlers = xtend(handlers, settings.handlers || {}) visit(tree, 'footnoteDefinition', visitor) return h // Finalise the created `right`, a hast node, from `left`, an mdast node. function augment(left, right) { var data var ctx // Handle `data.hName`, `data.hProperties, `hChildren`. if (left && 'data' in left) { data = left.data if (right.type === 'element' && data.hName) { right.tagName = data.hName } if (right.type === 'element' && data.hProperties) { right.properties = xtend(right.properties, data.hProperties) } if (right.children && data.hChildren) { right.children = data.hChildren } } ctx = left && left.position ? left : {position: left} if (!generated(ctx)) { right.position = { start: position.start(ctx), end: position.end(ctx) } } return right } // Create an element for a `node`. function h(node, tagName, props, children) { if ( (children === undefined || children === null) && typeof props === 'object' && 'length' in props ) { children = props props = {} } return augment(node, { type: 'element', tagName: tagName, properties: props || {}, children: children || [] }) } function visitor(definition) { h.footnotes.push(definition) } }
javascript
{ "resource": "" }
q49494
augment
train
function augment(left, right) { var data var ctx // Handle `data.hName`, `data.hProperties, `hChildren`. if (left && 'data' in left) { data = left.data if (right.type === 'element' && data.hName) { right.tagName = data.hName } if (right.type === 'element' && data.hProperties) { right.properties = xtend(right.properties, data.hProperties) } if (right.children && data.hChildren) { right.children = data.hChildren } } ctx = left && left.position ? left : {position: left} if (!generated(ctx)) { right.position = { start: position.start(ctx), end: position.end(ctx) } } return right }
javascript
{ "resource": "" }
q49495
h
train
function h(node, tagName, props, children) { if ( (children === undefined || children === null) && typeof props === 'object' && 'length' in props ) { children = props props = {} } return augment(node, { type: 'element', tagName: tagName, properties: props || {}, children: children || [] }) }
javascript
{ "resource": "" }
q49496
toHast
train
function toHast(tree, options) { var h = factory(tree, options) var node = one(h, tree) var footnotes = footer(h) if (node && node.children && footnotes) { node.children = node.children.concat(u('text', '\n'), footnotes) } return node }
javascript
{ "resource": "" }
q49497
train
function(destination, source, deep, handleErrors) { var sourceKeys = [], key = '', i = -1; deep = deep || false; handleErrors = handleErrors || false; try { if (Array.isArray(source)) { for (i = 0; i < source.length; i++) { sourceKeys.push(i); } } else if (source) { sourceKeys = Object.keys(source); } for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (!deep || typeof source[key] !== 'object' || this.isElement(source[key])) { // All non-object properties, or all properties if shallow extend destination[key] = source[key]; } else if (Array.isArray(source[key])) { // Arrays if (!destination[key]) { destination[key] = []; } this.extend(destination[key], source[key], deep, handleErrors); } else { // Objects if (!destination[key]) { destination[key] = {}; } this.extend(destination[key], source[key], deep, handleErrors); } } } catch(err) { if (handleErrors) { this.handleExtendError(err, destination); } else { throw err; } } return destination; }
javascript
{ "resource": "" }
q49498
train
function(box1, box2) { var controlArea = box1.width * box1.height, intersectionX = -1, intersectionY = -1, intersectionArea = -1, ratio = -1; intersectionX = Math.max(0, Math.min(box1.left + box1.width, box2.left + box2.width) - Math.max(box1.left, box2.left)); intersectionY = Math.max(0, Math.min(box1.top + box1.height, box2.top + box2.height) - Math.max(box1.top, box2.top)); intersectionArea = intersectionY * intersectionX; ratio = intersectionArea / controlArea; return ratio; }
javascript
{ "resource": "" }
q49499
train
function(originalArray) { var cleanArray = [], i = -1; for (i = 0; i < originalArray.length; i++) { if (originalArray[i] !== '') { cleanArray.push(originalArray[i]); } } return cleanArray; }
javascript
{ "resource": "" }