_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q6800
train
function(urls){ if(this.hCards.length > -1){ // remove all organisational hCards using fn = org.organization-name pattern var i = this.hCards.length; while (i--) { if(this.hCards[i].org && this.hCards[i].org[0]['organization-name']){ if( this.hCards[i].fn === this.hCards[i].org[0]['organization-name'] ){ this.hCards.splice(i,1); } } } // if there is only one hcard use that if(this.hCards.length === 1){ this.representativehCard = this.hCards[0]; }else{ i = this.hCards.length; var x = 0; while (x < i) { var hcard = this.hCards[x]; if(hcard.url){ // match the urls of the hcard to the known urls for (var y = 0; y < urls.length; y++) { for (var z = 0; z < hcard.url.length; z++) { if( utils.compareUrl(urls[y], hcard.url[z]) ){ this.representativehCard = hcard; } } } // match the xfn urls of the page to hcard urls if(this.xfn.length > -1){ for (var z = 0; z < this.xfn.length; z++) { for (var y = 0; y < hcard.url.length; y++) { if( this.xfn[z].link !== undefined && this.xfn[z].rel !== undefined && utils.compareUrl(hcard.url[y], this.xfn[z].link) && this.xfn[z].rel === 'me'){ this.representativehCard = hcard; } } } } } x++; } } } // if we have a hresume use contact hcard if(this.hResumes.length !== 0){ if(this.hResumes[0].contact){ this.representativehCard = this.hResumes[0].contact // description if(this.hResumes[0].summary !== '') this.representativehCard.note = this.hResumes[0].summary; // job role // org } } this.filterRepresentativehCard(); }
javascript
{ "resource": "" }
q6801
train
function(){ var i = filters.length, x = 0, urlObj = url.parse(this.url, parseQueryString=false); while (x < i) { if(filters[x].domain === urlObj.hostname){ for (var y = 0; y < filters[x].hCardBlockList.length; y++) { delete this.representativehCard.properties[filters[x].hCardBlockList[y]]; } } x++; } }
javascript
{ "resource": "" }
q6802
winnow
train
function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); }
javascript
{ "resource": "" }
q6803
train
function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }
javascript
{ "resource": "" }
q6804
finalPropName
train
function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; }
javascript
{ "resource": "" }
q6805
train
function( element, set ) { var i = 0, length = set.length; for ( ; i < length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }
javascript
{ "resource": "" }
q6806
train
function( element ) { var placeholder, cssPosition = element.css( "position" ), position = element.position(); // Lock in margins first to account for form elements, which // will change margin if you explicitly set height // see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380 // Support: Safari element.css( { marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ); if ( /^(static|relative)/.test( cssPosition ) ) { cssPosition = "absolute"; placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( { // Convert inline to inline block to account for inline elements // that turn to inline block based on content (like img) display: /^(inline|ruby)/.test( element.css( "display" ) ) ? "inline-block" : "block", visibility: "hidden", // Margins need to be set to account for margin collapse marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ), "float": element.css( "float" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ) .addClass( "ui-effects-placeholder" ); element.data( dataSpace + "placeholder", placeholder ); } element.css( { position: cssPosition, left: position.left, top: position.top } ); return placeholder; }
javascript
{ "resource": "" }
q6807
RestAPI
train
function RestAPI() { this.models = {}; this.router = express.Router(); this.router.use(require('res-error')({ log: false })); }
javascript
{ "resource": "" }
q6808
hasRole
train
function hasRole(user = null, role = null) { return user && role && user.hasRole(role); }
javascript
{ "resource": "" }
q6809
decodeStr
train
function decodeStr(s, decoder) { try { return decoder(s); } catch (e) { return QueryString.unescape(s, true); } }
javascript
{ "resource": "" }
q6810
smartquotes
train
function smartquotes(context) { if (typeof document !== 'undefined' && typeof context === 'undefined') { listen.runOnReady(() => element(document.body)); return smartquotes; } else if (typeof context === 'string') { return string(context); } else { return element(context); } }
javascript
{ "resource": "" }
q6811
omit
train
function omit (obj, props) { props = Array.prototype.slice.call(arguments, 1); var keys = Object.keys(obj); var newObj = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (props.indexOf(key) === -1) { newObj[key] = obj[key]; } } return newObj; }
javascript
{ "resource": "" }
q6812
Output
train
function Output(native) { this.native = native; this.id = native.id; this.manufacturer = native.manufacturer; this.name = native.name; this.version = native.version; }
javascript
{ "resource": "" }
q6813
typeOf
train
function typeOf (value) { var type = { hasValue: false, isArray: false, isPOJO: false, isNumber: false, }; if (value !== undefined && value !== null) { type.hasValue = true; var typeName = typeof value; if (typeName === 'number') { type.isNumber = !isNaN(value); } else if (Array.isArray(value)) { type.isArray = true; } else { type.isPOJO = (typeName === 'object') && !(value instanceof RegExp) && !(value instanceof Date); } } return type; }
javascript
{ "resource": "" }
q6814
_registerProxy
train
function _registerProxy(eventChannel) { if (eventChannel && "function" === typeof eventChannel.registerProxy) { eventChannel.registerProxy({ trigger: function () { _postMessage.call(this, Array.prototype.slice.apply(arguments), ACTION_TYPE.TRIGGER); }, context: this }); } }
javascript
{ "resource": "" }
q6815
_initializeSerialization
train
function _initializeSerialization(options) { this.useObjects = false === options.useObjects ? options.useObjects : _getUseObjectsUrlIndicator(); if ("undefined" === typeof this.useObjects) { // Defaults to true this.useObjects = true; } options.useObjects = this.useObjects; // Define the serialize/deserialize methods to be used if ("function" !== typeof options.serialize || "function" !== typeof options.deserialize) { if (this.useObjects && PostMessageUtilities.hasPostMessageObjectsSupport()) { this.serialize = _de$serializeDummy; this.deserialize = _de$serializeDummy; } else { this.serialize = PostMessageUtilities.stringify; this.deserialize = JSON.parse; } options.serialize = this.serialize; options.deserialize = this.deserialize; } else { this.serialize = options.serialize; this.deserialize = options.deserialize; } }
javascript
{ "resource": "" }
q6816
_initializeCommunication
train
function _initializeCommunication(options) { var mapping; var onmessage; // Grab the event channel and initialize a new mapper this.eventChannel = options.eventChannel || new Channels({ events: options.events, commands: options.commands, reqres: options.reqres }); this.mapper = new PostMessageMapper(this.eventChannel); // Bind the mapping method to the mapper mapping = this.mapper.toEvent.bind(this.mapper); // Create the message handler which uses the mapping method onmessage = _createMessageHandler(mapping).bind(this); // Initialize a message channel with the message handler this.messageChannel = new PostMessageChannel(options, onmessage); }
javascript
{ "resource": "" }
q6817
_initializeCache
train
function _initializeCache(options) { this.callbackCache = new Cacher({ max: PostMessageUtilities.parseNumber(options.maxConcurrency, DEFAULT_CONCURRENCY), ttl: PostMessageUtilities.parseNumber(options.timeout, DEFAULT_TIMEOUT), interval: CACHE_EVICTION_INTERVAL }); }
javascript
{ "resource": "" }
q6818
_initializeFailFast
train
function _initializeFailFast(options) { var messureTime = PostMessageUtilities.parseNumber(options.messureTime, DEFAULT_MESSURE_TIME); this.circuit = new CircuitBreaker({ timeWindow: messureTime, slidesNumber: Math.ceil(messureTime / 100), tolerance: PostMessageUtilities.parseNumber(options.messureTolerance, DEFAULT_MESSURE_TOLERANCE), calibration: PostMessageUtilities.parseNumber(options.messureCalibration, DEFAULT_MESSURE_CALIBRATION), onopen: PostMessageUtilities.parseFunction(options.ondisconnect, true), onclose: PostMessageUtilities.parseFunction(options.onreconnect, true) }); }
javascript
{ "resource": "" }
q6819
_postMessage
train
function _postMessage(args, name) { return this.circuit.run(function (success, failure, timeout) { var message = _prepare.call(this, args, name, timeout); if (message) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } } else { // Cache is full, as a fail fast mechanism, we should not continue failure(); } }.bind(this)); }
javascript
{ "resource": "" }
q6820
_returnMessage
train
function _returnMessage(message, target) { return this.circuit.run(function (success, failure) { try { var initiated = this.messageChannel.postMessage.call(this.messageChannel, message, target); if (false === initiated) { failure(); } else { success(); } } catch (ex) { failure(); } }.bind(this)); }
javascript
{ "resource": "" }
q6821
_prepare
train
function _prepare(args, name, ontimeout) { var method; var ttl; var id = PostMessageUtilities.createUniqueSequence(MESSAGE_PREFIX + name + PostMessageUtilities.SEQUENCE_FORMAT); args.unshift(id, name); if (_isTwoWay(name)) { if (1 < args.length && "function" === typeof args[args.length - 1]) { method = args.pop(); } else if (2 < args.length && !isNaN(args[args.length - 1]) && "function" === typeof args[args.length - 2]) { ttl = parseInt(args.pop(), 10); method = args.pop(); } if (method) { if (!this.callbackCache.set(id, method, ttl, function (id, callback) { ontimeout(); _handleTimeout.call(this, id, callback); }.bind(this))) { // Cache is full, as a fail fast mechanism, we will not continue return void 0; } } } return this.mapper.toMessage.apply(this.mapper, args); }
javascript
{ "resource": "" }
q6822
_handleTimeout
train
function _handleTimeout(id, callback) { // Handle timeout if (id && "function" === typeof callback) { try { callback.call(null, new Error("Callback: Operation Timeout!")); } catch (ex) { /* istanbul ignore next */ PostMessageUtilities.log("Error while trying to handle the timeout using the callback", "ERROR", "PostMessageCourier"); } } }
javascript
{ "resource": "" }
q6823
_handleReturnMessage
train
function _handleReturnMessage(id, method) { var callback = this.callbackCache.get(id, true); var args = method && method.args; if ("function" === typeof callback) { // First try to parse the first parameter in case the error is an object if (args && args.length && args[0] && "Error" === args[0].type && "string" === typeof args[0].message) { args[0] = new Error(args[0].message); } try { callback.apply(null, args); } catch (ex) { PostMessageUtilities.log("Error while trying to handle the returned message from request/command", "ERROR", "PostMessageCourier"); } } }
javascript
{ "resource": "" }
q6824
reportFile
train
function reportFile (filepath, data) { var lines = [] // Filename lines.push(colors.magenta.underline(path.relative(appRoot.path, filepath))) // Loop file specific error/warning messages data.results.forEach(function (file) { file.messages.forEach(function (msg) { var context = colors.yellow((options.showFilePath ? filepath + ':' : 'line ') + msg.line + ':' + msg.column) var message = colors.cyan(msg.message + (options.showRuleNames ? ' (' + msg.ruleId + ')' : '')) lines.push(context + '\t' + message) }) }) // Error/Warning count lines.push(logSymbols.error + ' ' + colors.red(data.errorCount + ' error' + (data.errorCount === 1 ? 's' : '')) + '\t' + logSymbols.warning + ' ' + colors.yellow(data.warningCount + ' warning' + (data.errorCount === 1 ? 's' : ''))) return lines.join('\n') + '\n' }
javascript
{ "resource": "" }
q6825
readFileSync
train
function readFileSync (args) { var file = args.file; var config = args.config; var error, response; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { error = err; response = res; }); if (error) { throw error; } else { setHttpMetadata(file, response); return response.data; } }
javascript
{ "resource": "" }
q6826
readFileAsync
train
function readFileAsync (args) { var file = args.file; var config = args.config; var next = args.next; safeCall(sendRequest, false, file.url, config, function handleResponse (err, res) { if (err) { next(err); } else { setHttpMetadata(file, res); next(null, res.data); } }); }
javascript
{ "resource": "" }
q6827
sendRequest
train
function sendRequest (async, url, config, callback) { var req = new XMLHttpRequest(); req.open('GET', url, async); req.onerror = handleError; req.ontimeout = handleError; req.onload = handleResponse; setXHRConfig(req, config); req.send(); function handleResponse () { var res = { status: getResponseStatus(req.status, url), headers: parseResponseHeaders(req.getAllResponseHeaders()), data: req.response || req.responseText, }; if (res.status >= 200 && res.status < 300) { callback(null, res); } else if (res.status < 200 || res.status < 400) { callback(ono('Invalid/unsupported HTTP %d response', res.status)); } else { callback(ono('HTTP %d error occurred (%s)', res.status, req.statusText)); } } function handleError (err) { callback(err); } }
javascript
{ "resource": "" }
q6828
setXHRConfig
train
function setXHRConfig (req, config) { try { req.withCredentials = config.http.withCredentials; } catch (err) { // Some browsers don't allow `withCredentials` to be set for synchronous requests } try { req.timeout = config.http.timeout; } catch (err) { // Some browsers don't allow `timeout` to be set for synchronous requests } // Set request headers Object.keys(config.http.headers).forEach(function (key) { var value = config.http.headers[key]; if (value !== undefined) { req.setRequestHeader(key, value); } }); }
javascript
{ "resource": "" }
q6829
parseResponseHeaders
train
function parseResponseHeaders (headers) { var parsed = {}; if (headers) { headers.split('\n').forEach(function (line) { var separatorIndex = line.indexOf(':'); var key = line.substr(0, separatorIndex).trim().toLowerCase(); var value = line.substr(separatorIndex + 1).trim().toLowerCase(); if (key) { parsed[key] = value; } }); } return parsed; }
javascript
{ "resource": "" }
q6830
validateConfig
train
function validateConfig (config) { var type = typeOf(config); if (type.hasValue && !type.isPOJO) { throw ono('Invalid arguments. Expected a configuration object.'); } }
javascript
{ "resource": "" }
q6831
encodeHeader
train
function encodeHeader(header) { var cursor = new BufferCursor(new buffer.Buffer(6)); cursor.writeUInt16BE(header.getFileType()); cursor.writeUInt16BE(header._trackCount); cursor.writeUInt16BE(header.getTicksPerBeat() & 0x7FFF); return encodeChunk('MThd', cursor.buffer); }
javascript
{ "resource": "" }
q6832
isSecure
train
function isSecure(url) { if (typeof url !== 'string') { return false; } var parts = url.split('://'); if (parts[0] === 'https') { return true; } return false; }
javascript
{ "resource": "" }
q6833
__fallbackChecks
train
function __fallbackChecks(err) { if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try uri_index = uri_index + 1; return __call(); } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http uri_index = 0; protocol = 'http'; return __call(); } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt uri_index = 0; protocol = 'http'; host = 'webfist.org'; // webfist will // 1. make a query to the webfist server for the users account // 2. from the response, get a link to the actual webfinger json data // (stored somewhere in control of the user) // 3. make a request to that url and get the json // 4. process it like a normal webfinger response var URL = __buildURL(); self.__fetchJRD(URL, cb, function (data) { // get link to users JRD self.__processJRD(URL, data, cb, function (result) { if ((typeof result.idx.links.webfist === 'object') && (typeof result.idx.links.webfist[0].href === 'string')) { self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) { self.__processJRD(URL, JRD, cb, function (result) { return cb(null, cb); }); }); } }); }); } else { return cb(err); } }
javascript
{ "resource": "" }
q6834
_wrapCalls
train
function _wrapCalls(options){ return function(){ var api; options.func.apply(options.context, Array.prototype.slice.call(arguments, 0)); for (var i = 0; i < externalAPIS.length; i++) { api = externalAPIS[i]; if (api[options.triggerType]) { try { api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0)); } catch (exc) {} } } }; }
javascript
{ "resource": "" }
q6835
callAsyncPlugin
train
function callAsyncPlugin (pluginHelper, methodName, args, callback) { var plugins = pluginHelper.filter(filterByMethod(methodName)); args.schema = pluginHelper[__internal].schema; args.config = args.schema.config; safeCall(callNextPlugin, plugins, methodName, args, callback); }
javascript
{ "resource": "" }
q6836
getNodeVaue
train
function getNodeVaue(path, obj) { // Gets a value from a JSON object // vcard[0].url[0] var output = null; try { var arrayDots = path.split("."); for (var i = 0; i < arrayDots.length; i++) { if (arrayDots[i].indexOf('[') > -1) { // Reconstructs and adds access to array of objects var arrayAB = arrayDots[i].split("["); var arrayName = arrayAB[0]; var arrayPosition = Number(arrayAB[1].substring(0, arrayAB[1].length - 1)); if (obj[arrayName] != null || obj[arrayName] != 'undefined') { if (obj[arrayName][arrayPosition] != null || obj[arrayName][arrayPosition] != 'undefined') obj = obj[arrayName][arrayPosition]; } else { currentObject = null; } } else { // Adds access to a property using property array ["given-name"] if (obj[arrayDots[i]] != null || obj[arrayDots[i]] != 'undefined') obj = obj[arrayDots[i]]; } } output = obj; } catch (err) { // Add error capture output = null; } return output; }
javascript
{ "resource": "" }
q6837
getIdentity
train
function getIdentity(urlStr, urlTemplates, www) { var identity = {}; urlObj = urlParser.parse(urlStr); // Loop all the urlMappings for site object for(var y = 0; y <= urlTemplates.length-1; y++){ urlTemplate = urlTemplates[y]; // remove http protocol urlTemplate = removeHttpHttps(urlTemplate); // if the urlTemplate contains a username or userid parse it if (urlTemplate != '' && (urlTemplate.indexOf('{username}') > -1 || urlTemplate.indexOf('{userid}') > -1)) { // break up url template var parts = urlTemplate.split(/\{userid\}|\{username\}/), startMatch = false, endMatch = false, user = urlObj.href // remove protocol, querystring and fragment user = user.replace(urlObj.hash, ''); user = user.replace(urlObj.search, ''); user = removeHttpHttps(user); // remove www if subdomain is optional if(www){ user = user.replace('www.', '') ; urlStr = urlStr.replace('www.', '') ; } // remove any trailing / if (endsWith(user,'/')) user = user.substring(0, user.length - 1); // remove unwanted front section of url string if (user.indexOf(parts[0]) === 0){ startMatch = true; part = parts[0]; user = user.substring(part.length, user.length); } // remove unwanted end section of url string if (parts.length === 2){ // if no end part or its just and trailing / if (parts[1].length > 0 && parts[1] !== '/'){ // end part matches template if (endsWith(user,parts[1])){ endMatch = true; user = user.replace(parts[1], ''); } else if (endsWith(user,parts[1] + '/')) { // end part matches template with a trailing / endMatch = true; user = user.replace(parts[1] + '/', ''); } } else { endMatch = true; } } // if the user contain anymore / then do not use it if (user.indexOf("/") > -1) endMatch = false; if (startMatch && endMatch){ identity = {}; identity.domain = urlObj.host; identity.matchedUrl = urlStr; if (urlTemplate.indexOf("{username}") > -1){ identity.userName = user; identity.sgn = "sgn://" + urlObj.host + "/?ident=" + user; } if (urlTemplate.indexOf("{userid}") > -1){ identity.userId = user; identity.sgn = "sgn://" + urlObj.host + "/?pk=" + user; } break; } } } return identity; }
javascript
{ "resource": "" }
q6838
endsWith
train
function endsWith(str,test){ var lastIndex = str.lastIndexOf(test); return (lastIndex != -1) && (lastIndex + test.length == str.length); }
javascript
{ "resource": "" }
q6839
isUrl
train
function isUrl (obj) { if(isString(obj)){ if((obj.indexOf('http://') > -1 || obj.indexOf('https://') > -1) && obj.indexOf('.') > -1) return true else return false }else{ return false; } }
javascript
{ "resource": "" }
q6840
encodeTrack
train
function encodeTrack(track) { var events = track.getEvents(), data = [], length = events.length, i, runningStatus = null, result; for (i = 0; i < length; i += 1) { result = encodeEvent(events[i], runningStatus); runningStatus = result.runningStatus; data[i] = result.data; } return encodeChunk('MTrk', buffer.Buffer.concat(data)); }
javascript
{ "resource": "" }
q6841
AnalyzeSourceCodeMiddleware
train
function AnalyzeSourceCodeMiddleware (context) { var grunt = context.grunt; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { var src = util.sortFilesBeforeSubfolders (filesArray.src); // Load the script files and scan them for module definitions. src.forEach (function (path) { if (!grunt.file.exists (path)) { warn ('Source file "' + path + '" not found.'); return; } // Read the script and scan it for module declarations. var script = grunt.file.read (path); /** @type {ModuleHeaderInfo[]} */ var moduleHeaders; try { moduleHeaders = sourceExtract.extractModuleHeaders (script); } catch (e) { if (typeof e === 'string') return warn (e + NL + reportErrorLocation (path)); throw e; } // Ignore irrelevant files. if (!moduleHeaders.length) { if (!filesArray.forceInclude || !grunt.file.isMatch ({matchBase: true}, filesArray.forceInclude, path)) { info ('Ignored file: %', path.cyan); return; } context.standaloneScripts.push ({ path: path, content: script }); } else moduleHeaders.forEach (function (header) { setupModuleInfo (header, script, path); }); }); }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { /* jshint unused: vars */ // Do nothing }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Store information about the specified module retrieved from the given source code on the specified file. * * @param {ModuleHeaderInfo} moduleHeader * @param {string} fileContent * @param {string} filePath */ function setupModuleInfo (moduleHeader, fileContent, filePath) { // Get information about the specified module. var module = context.modules[moduleHeader.name]; // If this is the first time a specific module is mentioned, create the respective information record. if (!module) module = context.modules[moduleHeader.name] = new ModuleDef (moduleHeader.name); // Skip the file if it defines an external module. else if (module.external) return; // Reject additional attempts to redeclare a module (only appending is allowed). else if (module.head && !moduleHeader.append) fatal ('Can\'t redeclare module <cyan>%</cyan>', moduleHeader.name); // The file is appending definitions to a module declared elsewhere. if (moduleHeader.append) { // Append the file path to the paths list. if (!~module.bodyPaths.indexOf (filePath)) { module.bodies.push (fileContent); module.bodyPaths.push (filePath); } } // Otherwise, the file contains a module declaration. else { if (module.head) fatal ('Duplicate module definition: <cyan>%</cyan>', moduleHeader.name); module.head = fileContent; module.headPath = filePath; module.requires = moduleHeader.requires; } module.configFn = moduleHeader.configFn; } }
javascript
{ "resource": "" }
q6842
resolveURL
train
function resolveURL (args) { var from = args.from; var to = args.to; var next = args.next; if (protocolPattern.test(from) || protocolPattern.test(to)) { // It's a URL, not a filesystem path, so let some other plugin resolve it return next(); } if (from) { // The `from` path needs to be a directory, not a file. So, if the last character is NOT a // path separator, then we need to remove the filename from the path if (pathSeparators.indexOf(from[from.length - 1]) === -1) { from = path.dirname(from); } return path.resolve(from, to); } else { // Resolve the `to` path against the current working directory return path.resolve(to); } }
javascript
{ "resource": "" }
q6843
readFileSync
train
function readFileSync (args) { var file = args.file; var next = args.next; if (isUnsupportedPath(file.url)) { // It's not a filesystem path, so let some other plugin handle it return next(); } var filepath = getFileSystemPath(file.url); inferFileMetadata(file); return fs.readFileSync(filepath); }
javascript
{ "resource": "" }
q6844
inferFileMetadata
train
function inferFileMetadata (file) { file.mimeType = lowercase(mime.lookup(file.url) || null); file.encoding = lowercase(mime.charset(file.mimeType) || null); }
javascript
{ "resource": "" }
q6845
validatePlugins
train
function validatePlugins (plugins) { var type = typeOf(plugins); if (type.hasValue) { if (type.isArray) { // Make sure all the items in the array are valid plugins plugins.forEach(validatePlugin); } else { throw ono('Invalid arguments. Expected an array of plugins.'); } } }
javascript
{ "resource": "" }
q6846
generate
train
function generate (opts) { var options = opts || {}, genCount = Math.abs(options.count) >>> 0, // min/max word count in a sentence minCount = Math.abs(options.minCount) || 5, maxCount = Math.abs(options.maxCount) || 20, formater = options.format == '\\uXXXX' ? formatOutput : undefined, periods = extendPeriod(options.toleratedPeriods || ''); var avail = 0; var genHelper = function (genFn) { return formater === undefined ? genFn : function () { return formatOutput(genFn.apply(undefined, arguments)); }; }, genWords = genHelper(options.freq === true ? freqUsedWordsGen : wordsGen), wordCountFn = function () { var count = rand(minCount, maxCount); return count >= avail ? avail - 1 : count; }, genPeriod = genHelper(function () { return periods[rand(0, periods.length)]; }), genSentences = function (genEachSentenceFn) { var gen = { text: '', total: 0, sentenceCount: 0 }; while ((avail = genCount - gen.total) > 0) { gen.total += genEachSentenceFn(gen); gen.sentenceCount++; } return gen; }; return genSentences(function (gen) { var currentWordCount = wordCountFn(); gen.text += genWords(currentWordCount); gen.text += genPeriod(); return currentWordCount + 1; }); }
javascript
{ "resource": "" }
q6847
getCharAt
train
function getCharAt (index) { var code = this.charCodeAt(index); // BMP if (code < 0xD800 || code > 0xDFFF) { return String.fromCharCode(code); } // high surrogate if (code < 0xDC00) { // access the low surrogate var nextCode = this.charCodeAt(index + 1); if (isNaN(nextCode)) return false; if (nextCode < 0xDC00 || nextCode > 0xDFFF) return false; return String.fromCharCode(code, nextCode); } else { // low surrogate return false; } }
javascript
{ "resource": "" }
q6848
File
train
function File (schema) { /** * The {@link Schema} that this file belongs to. * * @type {Schema} */ this.schema = schema; /** * The file's full (absolute) URL, without any hash * * @type {string} */ this.url = ''; /** * The file's data. This can be any data type, including a string, object, array, binary, etc. * * @type {*} */ this.data = undefined; /** * The file's MIME type (e.g. "application/json", "text/html", etc.), if known. * * @type {?string} */ this.mimeType = undefined; /** * The file's encoding (e.g. "utf-8", "iso-8859-2", "windows-1251", etc.), if known * * @type {?string} */ this.encoding = undefined; /** * Internal stuff. Use at your own risk! * * @private */ this[__internal] = { /** * Keeps track of the state of each file as the schema is being read. * * @type {number} */ state: 0, }; }
javascript
{ "resource": "" }
q6849
authNeeded
train
function authNeeded () { if (args.write === true) { return true } if (args.channel.indexOf('private-') === 0) { return true } if (args.channel.indexOf('presence-') === 0) { return true } return false; }
javascript
{ "resource": "" }
q6850
BuildForeignScriptsMiddleware
train
function BuildForeignScriptsMiddleware (context) { //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { /* jshint unused: vars */ // Do nothing }; this.build = function (targetScript) { // Output the standalone scripts (if any). if (context.standaloneScripts.length) { // Debug Build if (context.options.debugBuild && context.options.debugBuild.enabled) { var rep = context.options.debugBuild.rebaseDebugUrls; context.prependOutput += (context.standaloneScripts.map (function (e) { var path = e.path.replace (MATCH_PATH_SEP, '/'); // Convert file paths to URLs. if (rep) for (var i = 0, m = rep.length; i < m; ++i) path = path.replace (rep[i].match, rep[i].replaceWith); if (path) // Ignore empty path; it means that this middleware should not output a script tag. return util.sprintf ('<script src=\"%\"></script>', path); return ''; }) .filter (function (x) {return x;}) // Remove empty paths. .join ('\\\n')); } // Release Build else if (context.options.releaseBuild && context.options.releaseBuild.enabled) { /** @type {string[]} */ var output = context.standaloneScripts.map (function (e) { return e.content; }).join (NL); util.writeFile (targetScript, output); //Note: the ensuing release/debug build step will append to the file created here. } } }; }
javascript
{ "resource": "" }
q6851
parseHeader
train
function parseHeader(cursor) { var chunk, fileType, trackCount, timeDivision; try { chunk = parseChunk('MThd', cursor); } catch (e) { if (e instanceof error.MIDIParserError) { throw new error.MIDINotMIDIError(); } } fileType = chunk.readUInt16BE(); trackCount = chunk.readUInt16BE(); timeDivision = chunk.readUInt16BE(); if ((timeDivision & 0x8000) === 0) { timeDivision = timeDivision & 0x7FFF; } else { throw new error.MIDINotSupportedError( 'Expressing time in SMPTE format is not supported yet' ); } return new Header(fileType, trackCount, timeDivision); }
javascript
{ "resource": "" }
q6852
File
train
function File(data, callback) { stream.Duplex.call(this); this._header = new Header(); this._tracks = []; if (data && buffer.Buffer.isBuffer(data)) { this.setData(data, callback || noop); } }
javascript
{ "resource": "" }
q6853
defaultFormatter
train
function defaultFormatter (message) { return `team: ${message.team} channel: ${message.channel} user: ${message.user} text: ${message.text}` }
javascript
{ "resource": "" }
q6854
MakeReleaseBuildMiddleware
train
function MakeReleaseBuildMiddleware (context) { var options = context.options.releaseBuild; /** * Grunt's verbose output API. * @type {Object} */ var verboseOut = context.grunt.log.verbose; /** @type {string[]} */ var traceOutput = []; //-------------------------------------------------------------------------------------------------------------------- // EVENTS //-------------------------------------------------------------------------------------------------------------------- context.listen (ContextEvent.ON_AFTER_ANALYZE, function () { if (options.enabled) { var space = context.verbose ? NL : ''; writeln ('%Generating the <cyan>release</cyan> build...%', space, space); scanForOptimization (context); } }); context.listen (ContextEvent.ON_BEFORE_DEPS, function (/*ModuleDef*/ module) { if (options.enabled) { if (module.nonOptimizedContainer) traceOutput.push ('(function () {\n'); } }); //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (/*ModuleDef*/ module) { if (!options.enabled) return; if (module.nonOptimizedContainer) traceOutput.push ('\n}) ();'); // Fist process the head module declaration. if (!module.head) return util.warn ('Module <cyan>%</cyan> has no declaration.', module.name); var headPath = module.headPath; var head, headWasOutput = context.outputtedFiles[headPath]; if (!headWasOutput) { head = module.optimize ? optimize (module.head, headPath, module) : {status: STAT.INDENTED, data: module.head}; context.outputtedFiles[headPath] = true; } var isEmpty = headWasOutput ? true : sourceExtract.matchWhiteSpaceOrComments (head.data); outputModuleHeader (module, headWasOutput, headPath); if (!headWasOutput) { // Prevent the creation of an empty (or comments-only) self-invoking function. // In that case, the head content will be output without a wrapping closure. if (!module.bodies.length && isEmpty) { // Output the comments (if any). if (head.data.trim ()) traceOutput.push (head.data); // Output a module declaration with no definitions. traceOutput.push (sprintf ('angular.module (\'%\', %);%', module.name, util.toQuotedList (module.requires), options.moduleFooter) ); return; } } // Enclose the module contents in a self-invoking function which receives the module instance as an argument. if (module.optimize) // Begin closure. traceOutput.push ('(function (' + options.moduleVar + ') {\n'); // Insert module declaration. if (!headWasOutput) traceOutput.push (conditionalIndent (head)); outputModuleDefinitions (module, headWasOutput); // End closure. if (module.optimize) traceOutput.push (sprintf ('\n}) (angular.module (\'%\', %%));%', module.name, util.toQuotedList (module.requires), module.configFn || '', options.moduleFooter)); }; this.build = function (targetScript) { if (!options.enabled) return; if (context.prependOutput) traceOutput.unshift (context.prependOutput); if (context.appendOutput) traceOutput.push (context.appendOutput); util.writeFile (targetScript, traceOutput.join (NL)); }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Outputs a module information header. * * @param {ModuleDef} module * @param {boolean} headWasOutput * @param {string} headPath */ function outputModuleHeader (module, headWasOutput, headPath) { if (module.bodies.length || !headWasOutput) { traceOutput.push (LINE2, '// Module: ' + module.name, '// Optimized: ' + (module.optimize ? 'Yes' : 'No')); if (!headWasOutput) traceOutput.push ('// File: ' + headPath); else { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; // Find first body who's corresponding file was not yet output. if (!context.outputtedFiles[bodyPath]) { traceOutput.push ('// File: ' + bodyPath); break; } } } traceOutput.push (LINE2, ''); } } /** * Insert additional module definitions. * * @param {ModuleDef} module * @param {boolean} headWasOutput */ function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } } /** * Calls sourceTrans.optimize() and handles the result. * * @param {string} source * @param {string} path For error messages. * @param {ModuleDef} module * @returns {OperationResult} The transformed source code. * @throws Error Sanity check. */ function optimize (source, path, module) { var result = sourceTrans.optimize (source, module.name, options.moduleVar); var stat = sourceTrans.TRANS_STAT; switch (result.status) { case stat.OK: //---------------------------------------------------------- // Module already enclosed in a closure with no arguments. //---------------------------------------------------------- return /** @type {OperationResult} */ { status: STAT.INDENTED, data: sourceTrans.renameModuleRefExps (module, options.indent + result.data, options.moduleVar) }; case stat.NO_CLOSURE_FOUND: //---------------------------------------------------------- // Unwrapped source code. // It must be validated to make sure it's safe. //---------------------------------------------------------- if (path) verboseOut.write ('Validating ' + path.cyan + '...'); var valid = sourceTrans.validateUnwrappedCode (source); if (valid) // The code passed validation. verboseOut.ok (); else { verboseOut.writeln ('FAILED'.yellow); warnAboutGlobalCode (valid, path); // If --force, continue. } // Either the code is valid or --force was used, so process it. return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleRefExps (module, source, options.moduleVar) }; case stat.RENAME_REQUIRED: //---------------------------------------------------------- // Module already enclosed in a closure, with its reference // passed in as the function's argument. //---------------------------------------------------------- /** @type {ModuleClosureInfo} */ var modInfo = result.data; if (!options.renameModuleRefs) { warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' + '<cyan>moduleVar=\'%\'</cyan>.%%%', modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path), getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.') ); // If --force, continue. } return /** @type {OperationResult} */ { status: STAT.OK, data: sourceTrans.renameModuleVariableRefs (modInfo.closureBody, modInfo.moduleVar, options.moduleVar) }; case stat.INVALID_DECLARATION: warn ('Wrong module declaration: <cyan>%</cyan>', result.data); // If --force, continue. break; default: throw new Error ('Optimize failed. It returned ' + JSON.stringify (result)); } // Optimization failed. Return the unaltered source code. return /** @type {OperationResult} */ {status: STAT.OK, data: source}; } /** * Returns the given text indented unless it was already indented. * @param {OperationResult} result * @return {string} */ function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); } /** * Isses a warning about problematic code found on the global scope. * @param {Object} sandbox * @param {string} path */ function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); } }
javascript
{ "resource": "" }
q6855
outputModuleDefinitions
train
function outputModuleDefinitions (module, headWasOutput) { for (var i = 0, m = module.bodies.length; i < m; ++i) { var bodyPath = module.bodyPaths[i]; if (!bodyPath) console.log (module.name, i, module.bodies.length, module.bodyPaths); // Skip bodies who's corresponding file was already output. if (context.outputtedFiles[bodyPath]) continue; context.outputtedFiles[bodyPath] = true; var body = module.optimize ? optimize (module.bodies[i], bodyPath, module) : {status: STAT.INDENTED, data: module.bodies[i]}; if (i || !headWasOutput) traceOutput.push (LINE, '// File: ' + bodyPath, LINE, ''); traceOutput.push (conditionalIndent (body)); } }
javascript
{ "resource": "" }
q6856
conditionalIndent
train
function conditionalIndent (result) { return result.status === STAT.INDENTED ? result.data : indent (result.data, 1, options.indent); }
javascript
{ "resource": "" }
q6857
warnAboutGlobalCode
train
function warnAboutGlobalCode (sandbox, path) { var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL + (path ? reportErrorLocation (path) : '') + getExplanation ( 'This kind of code will behave differently between release and debug builds.' + NL + 'You should wrap it in a self-invoking function and/or assign global variables/functions ' + 'directly to the window object.' ) ); if (context.verbose) { var found = false; util.forEachProperty (sandbox, function (k, v) { if (!found) { found = true; msg += ' Detected globals:'.yellow + NL; } msg += (typeof v === 'function' ? ' function '.blue : ' var '.blue) + k.cyan + NL; }); } warn (msg + '>>'.yellow); }
javascript
{ "resource": "" }
q6858
scanForOptimization
train
function scanForOptimization (context) { var module, verboseOut = context.grunt.log.verbose; // Track repeated files to determine which modules can be optimized. Object.keys (context.modules).forEach (function (name) { if (context.modules.hasOwnProperty (name)) { module = context.modules[name]; if (!module.external) module.filePaths ().forEach (function (path) { if (!context.filesRefCount[path]) context.filesRefCount[path] = 1; else { verboseOut.writeln (util.csprintf ('white', 'Not optimizing <cyan>%</cyan> because it shares some/all of its files with other modules.', name)); ++context.filesRefCount[path]; module.optimize = false; } }); } }); // Determine which modules can act as containers for non-optimized sections of code. scan (context.options.mainModule, true); /** * Search for unoptimizable modules. * @param {string} moduleName * @param {boolean?} first=false Is this the root module? * @returns {boolean} `true` if the module is not optimizable. */ function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; } function disableOptimizationsForChildrenOf (module) { if (module.external) return; for (var i = 0, m = module.requires.length; i < m; ++i) { var sub = context.modules[module.requires[i]]; if (sub.external) continue; if (sub.optimize) verboseOut.writeln (util.csprintf ('white', "Also disabling optimizations for <cyan>%</cyan>.", sub.name.cyan)); sub.optimize = false; disableOptimizationsForChildrenOf (sub); } } }
javascript
{ "resource": "" }
q6859
scan
train
function scan (moduleName, first) { var module = context.modules[moduleName]; if (!module) throw new Error (sprintf ("Module '%' was not found.", moduleName)); // Ignore the module if it's external. if (module.external) return false; if (!module.optimize) { if (first) module.nonOptimizedContainer = true; disableOptimizationsForChildrenOf (module); return true; } for (var i = 0, m = module.requires.length, any = false; i < m; ++i) if (scan (module.requires[i])) //Note: scan() still must be called for ALL submodules! any = true; if (any) module.nonOptimizedContainer = true; return false; }
javascript
{ "resource": "" }
q6860
validatePriority
train
function validatePriority (priority) { var type = typeOf(priority); if (type.hasValue && !type.isNumber) { throw ono('Invalid arguments. Expected a priority number.'); } }
javascript
{ "resource": "" }
q6861
deepAssign
train
function deepAssign (target, source) { var keys = Object.keys(source); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var oldValue = target[key]; var newValue = source[key]; target[key] = deepClone(newValue, oldValue); } return target; }
javascript
{ "resource": "" }
q6862
deepClone
train
function deepClone (value, oldValue) { var type = typeOf(value); var clone; if (type.isPOJO) { var oldType = typeOf(oldValue); if (oldType.isPOJO) { // Return a merged clone of the old POJO and the new POJO clone = deepAssign({}, oldValue); return deepAssign(clone, value); } else { return deepAssign({}, value); } } else if (type.isArray) { clone = []; for (var i = 0; i < value.length; i++) { clone.push(deepClone(value[i])); } } else if (type.hasValue) { // string, boolean, number, function, Date, RegExp, etc. // Just return it as-is return value; } }
javascript
{ "resource": "" }
q6863
crawl
train
function crawl (obj, file) { var type = typeOf(obj); if (!type.isPOJO && !type.isArray) { return; } if (type.isPOJO && isFileReference(obj)) { // We found a file reference, so resolve it resolveFileReference(obj.$ref, file); } // Crawl this POJO or Array, looking for nested JSON References // // NOTE: According to the spec, JSON References should not have any properties other than "$ref". // However, in practice, many schema authors DO add additional properties. Because of this, // we crawl JSON Reference objects just like normal POJOs. If the schema author has added // additional properties, then they have opted-into this non-spec-compliant behavior. var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = obj[key]; crawl(value, file); } }
javascript
{ "resource": "" }
q6864
getBitbucketId
train
function getBitbucketId (text) { text = 'markdown-header-' + text .toLowerCase() .replace(/\\(.)/g, (_m, c) => c.charCodeAt(0)) // add escaped chars with their charcode .normalize('NFKD').replace(/[\u0300-\u036f]/g, '') .replace(/[^\w\s-]/g, '') .replace(/\s+/g, '-') // whitespace .replace(/-+/g, '-') // duplicated hyphen .replace(/^-+|-+$/g, '') // heading/ tailing hyphen return text }
javascript
{ "resource": "" }
q6865
getPandocId
train
function getPandocId (text) { text = text .replace(emojiRegex(), '') // Strip emojis .toLowerCase() .trim() .replace(/%25|%/ig, '') // remove single % signs .replace(RE_ENTITIES, '') // remove xml/html entities .replace(RE_SPECIALS, '') // single chars that are removed but not [.-] .replace(/\s+/g, '-') // whitespaces .replace(/^-+|-+$/g, '') // heading/ tailing hyphen .replace(RE_CJK, '') // CJK punctuations that are removed if (/^[0-9-]+$/.test(text)) { text = 'section' } return text }
javascript
{ "resource": "" }
q6866
getMarkedId
train
function getMarkedId (text) { return entities.decode(text) .toLowerCase() .trim() .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~_]/g, '') .replace(/\s/g, '-') }
javascript
{ "resource": "" }
q6867
getMarkDownItAnchorId
train
function getMarkDownItAnchorId (text) { text = text .replace(/^[<]|[>]$/g, '') // correct markdown format bold/url text = entities.decode(text) .toLowerCase() .trim() .replace(/\s+/g, '-') return encodeURIComponent(text) }
javascript
{ "resource": "" }
q6868
slugger
train
function slugger (header, mode) { mode = mode || 'marked' let replace switch (mode) { case MODE.MARKED: replace = getMarkedId break case MODE.MARKDOWNIT: return getMarkDownItAnchorId(header) case MODE.GITHUB: replace = getGithubId break case MODE.GITLAB: replace = getGitlabId break case MODE.PANDOC: replace = getPandocId break case MODE.BITBUCKET: replace = getBitbucketId break case MODE.GHOST: replace = getGhostId break default: throw new Error('Unknown mode: ' + mode) } const href = replace(asciiOnlyToLowerCase(header.trim())) return encodeURI(href) }
javascript
{ "resource": "" }
q6869
registerHelpListener
train
function registerHelpListener (controller, helpInfo) { controller.hears('^help ' + helpInfo.command + '$', 'direct_mention,direct_message', (bot, message) => { let replyText = helpInfo.text if (typeof helpInfo.text === 'function') { let helpOpts = _.merge({botName: bot.identity.name}, _.pick(message, ['team', 'channel', 'user'])) replyText = helpInfo.text(helpOpts) } bot.reply(message, replyText) }) }
javascript
{ "resource": "" }
q6870
toEvent
train
function toEvent(message) { if (message) { if (message.error) { PostMessageUtilities.log("Error on message: " + message.error, "ERROR", "PostMessageMapper"); return function() { return message; }; } else { return _getMappedMethod.call(this, message); } } }
javascript
{ "resource": "" }
q6871
toMessage
train
function toMessage(id, name) { return { method: { id: id, name: name, args: Array.prototype.slice.call(arguments, 2) } }; }
javascript
{ "resource": "" }
q6872
_getMappedMethod
train
function _getMappedMethod(message) { var method = message && message.method; var name = method && method.name; var args = method && method.args; var eventChannel = this.eventChannel; return function() { if (eventChannel && eventChannel[name]) { return eventChannel[name].apply(eventChannel, args); } else { /* istanbul ignore next */ PostMessageUtilities.log("No channel exists", "ERROR", "PostMessageMapper"); } }; }
javascript
{ "resource": "" }
q6873
train
function( numberOfOptions ) { var visualCaptchaSession = this.session[ this.namespace ], imageValues = []; // Avoid the next IF failing if a string with a number is sent numberOfOptions = parseInt( numberOfOptions, 10 ); // If it's not a valid number, default to 5 if ( ! numberOfOptions || ! _.isNumber(numberOfOptions) || isNaN(numberOfOptions) ) { numberOfOptions = 5; } // Set the minimum numberOfOptions to four if ( numberOfOptions < 4 ) { numberOfOptions = 4; } // Shuffle all imageOptions this.imageOptions = _.shuffle( this.imageOptions ); // Get a random sample of X images visualCaptchaSession.images = _.sample( this.imageOptions, numberOfOptions ); // Set a random value for each of the images, to be used in the frontend visualCaptchaSession.images.forEach( function( image, index ) { var randomValue = crypto.randomBytes( 20 ).toString( 'hex' ); imageValues.push( randomValue ); visualCaptchaSession.images[ index ].value = randomValue; }); // Select a random image option, pluck current valid image option visualCaptchaSession.validImageOption = _.sample( _.without( visualCaptchaSession.images, visualCaptchaSession.validImageOption ) ); // Select a random audio option, pluck current valid audio option visualCaptchaSession.validAudioOption = _.sample( _.without( this.audioOptions, visualCaptchaSession.validAudioOption ) ); // Set random hashes for audio and image field names, and add it in the frontend data object visualCaptchaSession.frontendData = { values: imageValues, imageName: this.getValidImageOption().name, imageFieldName: crypto.randomBytes( 20 ).toString( 'hex' ), audioFieldName: crypto.randomBytes( 20 ).toString( 'hex' ) }; }
javascript
{ "resource": "" }
q6874
train
function( response, fileType ) { var fs = require( 'fs' ), mime = require( 'mime' ), audioOption = this.getValidAudioOption(), audioFileName = audioOption ? audioOption.path : '',// If there's no audioOption, we set the file name as empty audioFilePath = __dirname + '/audios/' + audioFileName, mimeType, stream; // If the file name is empty, we skip any work and return a 404 response if ( audioFileName ) { // We need to replace '.mp3' with '.ogg' if the fileType === 'ogg' if ( fileType === 'ogg' ) { audioFileName = audioFileName.replace( /\.mp3/gi, '.ogg' ); audioFilePath = audioFilePath.replace( /\.mp3/gi, '.ogg' ); } else { fileType = 'mp3';// This isn't doing anything, really, but I feel better with it } fs.exists( audioFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( audioFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( audioFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so audio files can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
javascript
{ "resource": "" }
q6875
train
function( index, response, isRetina ) { var fs = require( 'fs' ), imageOption = this.getImageOptionAtIndex( index ), imageFileName = imageOption ? imageOption.path : '',// If there's no imageOption, we set the file name as empty imageFilePath = __dirname + '/images/' + imageFileName, mime = require( 'mime' ), mimeType, stream; // Force boolean for isRetina if ( ! isRetina ) { isRetina = false; } else { isRetina = true; } // If retina is requested, change the file name if ( isRetina ) { imageFileName = imageFileName.replace( /\.png/gi, '@2x.png' ); imageFilePath = imageFilePath.replace( /\.png/gi, '@2x.png' ); } // If the index is non-existent, the file name will be empty, same as if the options weren't generated if ( imageFileName ) { fs.exists( imageFilePath, function( exists ) { if ( exists ) { mimeType = mime.getType( imageFilePath ); // Set the appropriate mime type response.set( 'content-type', mimeType ); // Make sure this is not cached response.set( 'cache-control', 'no-cache, no-store, must-revalidate' ); response.set( 'pragma', 'no-cache' ); response.set( 'expires', 0 ); stream = fs.createReadStream( imageFilePath ); var responseData = []; if ( stream ) { stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { if ( ! response.headerSent ) { var finalData = Buffer.concat( responseData ); response.write( finalData ); // Add some noise randomly, so images can't be saved and matched easily by filesize or checksum var noiseData = crypto.randomBytes(Math.round((Math.random() * 1999)) + 501).toString('hex'); response.write( noiseData ); response.end(); } }); } else { response.status( 404 ).send( 'Not Found' ); } } else { response.status( 404 ).send( 'Not Found' ); } }); } else { response.status( 404 ).send( 'Not Found' ); } }
javascript
{ "resource": "" }
q6876
connect
train
async function connect(address) { const running = await isRunning(address) if (!running) { throw errCouldNotConnect } return siadWrapper(address) }
javascript
{ "resource": "" }
q6877
walk
train
function walk(obj, path, initializeMissing = false) { let newObj = obj; if (path) { const ar = path.split('.'); while (ar.length) { const k = ar.shift(); if (initializeMissing && obj[k] == null) { newObj[k] = {}; newObj = newObj[k]; } else if (k in newObj) { newObj = newObj[k]; } else { throw new Error(`cannot find configuration param '${path}'`); } } } return newObj; }
javascript
{ "resource": "" }
q6878
getSlackbotConfig
train
function getSlackbotConfig (config) { return _.defaults(config.botkit, {debug: !!config.debug}, botkitDefaults) }
javascript
{ "resource": "" }
q6879
formatConfig
train
function formatConfig (config) { _.defaults(config, {debug: false, plugins: []}) config.debugOptions = config.debugOptions || {} config.connectedTeams = new Set() if (!Array.isArray(config.plugins)) { config.plugins = [config.plugins] } config.scopes = _.chain(config.plugins) .map('scopes') .flatten() .concat(_.isArray(config.scopes) ? config.scopes : []) .uniq() .remove(_.isString.bind(_)) .value() config.isSlackApp = !config.slackToken if (!config.slackToken && !(config.clientId && config.clientSecret && config.port)) { logger.error(`Missing configuration. Config must include either slackToken AND/OR clientId, clientSecret, and port`) process.exit(1) } }
javascript
{ "resource": "" }
q6880
lerpW
train
function lerpW(a, wa, b, wb) { var d = wb - wa var t = -wa / d if(t < 0.0) { t = 0.0 } else if(t > 1.0) { t = 1.0 } var ti = 1.0 - t var n = a.length var r = new Array(n) for(var i=0; i<n; ++i) { r[i] = t * a[i] + ti * b[i] } return r }
javascript
{ "resource": "" }
q6881
connect
train
function connect() { return new Promise(function (resolve, reject) { navigator.requestMIDIAccess().then(function (access) { resolve(new Driver(access)); }).catch(function () { reject(new Error('MIDI access denied')); }); }); }
javascript
{ "resource": "" }
q6882
train
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.url){ logger.log('fetch page: ' + this.url); // if there is a cache and it holds the url if(cache &&cache.has(this.url)){ // http status - content located elsewhere, retrieve from there this.statusCode = 305; this.requestTime = 0; this.html = cache.get(this.url); logger.log('fetched html from cache: ' + this.url); this.parse(function(){ callback(this); }) // if not get the html from the url }else{ this.startedRequest = new Date(); var self = this; var requestObj = { uri: this.url, headers: options.httpHeaders } request(requestObj, function(requestErrors, response, body){ if(!requestErrors && response.statusCode === 200){ self.endedRequest = new Date(); self.requestTime = self.endedRequest.getTime() - self.startedRequest.getTime(); logger.log('fetched html from page: ' + self.requestTime + 'ms - ' + self.url); self.statusCode = response.statusCode; self.html = body; if(cache){ cache.set(self.url, body); } self.parse(function(){ self.status = "fetched"; callback(self); }) }else{ logger.warn('error requesting page: ' + self.url); self.error = 'error requesting page: ' + self.url; self.status = "errored"; callback(); } }); } }else{ logger.warn('no url given'); this.error = 'no url given'; this.status = "errored"; callback(); } }
javascript
{ "resource": "" }
q6883
train
function(callback){ var options = {},// utils.clone( this.options ), self = this; options.baseUrl = self.url; self.startedUFParse = new Date(); //console.log(self.url) try { parser.parseHtml (self.html, options, function(err, data){ //console.log( JSON.stringify(data) ); if(data){ self.profile.hCards = self.getArrayOfContentType(data, 'h-card' ); self.profile.hResumes = self.getArrayOfContentType(data, 'hresume' ); self.profile.xfn = self.getArrayOfContentType(data, 'xfn' ); } if(callback){ callback(); } }); } catch(err) { self.options.logger.warn('error parsing microformats in page: ' + self.url); self.error = err; callback(); } self.endedUFParse = new Date(); self.parseTime = self.endedUFParse.getTime() - self.startedUFParse.getTime(); self.options.logger.log('time to parse microformats in page: ' + self.parseTime + 'ms - ' + self.url); }
javascript
{ "resource": "" }
q6884
train
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.apiInterface){ logger.info('fetch data from api: ' + this.apiInterface.name); var sgn = this.profile.identity.sgn || '', self = this; try { this.apiInterface.getProfile(this.url, sgn, options, function(hCard){ if(hCard){ self.profile.hCards = [hCard]; } self.status = "fetched"; callback(); }); } catch(err) { logger.warn('error getting api data with plugin for: ' + self.domain + ' - ' + err); self.error = err; self.status = "errored"; callback(); } } }
javascript
{ "resource": "" }
q6885
IncludeRequiredScriptsMiddleware
train
function IncludeRequiredScriptsMiddleware (context) { var path = require ('path'); /** * Paths of the required scripts. * @type {string[]} */ var paths = []; /** * File content of the required scripts. * @type {string[]} */ var sources = []; /** * Map of required script paths, as they are being resolved. * Prevents infinite recursion and redundant scans. * Note: paths will be registered here *before* being added to `paths`. * @type {Object.<string,boolean>} */ var references = {}; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { util.info ("Scanning <cyan>%</cyan> for non-angular script dependencies...", module.name); scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = paths.map (function (path, i) { return { path: path, content: sources[i] }; }); util.arrayAppend (context.standaloneScripts, scripts); if (context.standaloneScripts.length) { var list = context.standaloneScripts.map ( function (e, i) { return ' ' + (i + 1) + '. ' + e.path; } ).join (util.NL); util.info ("Required non-angular scripts:%<cyan>%</cyan>", util.NL, list); } }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to scripts and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match , r = new RegExp (MATCH_DIRECTIVE); while ((match = r.exec (sourceCode))) { match[1].split (/\s*,\s*/).forEach (function (s) { var m = s.match (/(["'])(.*?)\1/); if (!m) util.warn ('syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\t', s, util.NL, filePath); else { var url = m[2]; var requiredPath = path.normalize (path.dirname (filePath) + '/' + url); // Check if this script was not already referenced. if (!references[requiredPath]) { references[requiredPath] = true; var source = context.grunt.file.read (requiredPath); // First, see if the required script has its own 'requires'. // If so, they must be required *before* the current script. scan (source, requiredPath); // Let's register the dependency now. paths.push (requiredPath); sources.push (source); } } }); } } }
javascript
{ "resource": "" }
q6886
prep
train
function prep (id) { id = id.replace(/(?:%20|\+)/g, ' ') id = self.headingAutoId({ text: id }) return id }
javascript
{ "resource": "" }
q6887
train
function (fieldname, file, filename) { const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || []; if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) { this.status = 400; this.body = { message: 'Invalid file format ' + filename ? 'for this file' + filename : '' }; } }
javascript
{ "resource": "" }
q6888
createHeaderGetter
train
function createHeaderGetter(str) { var header = str.toLowerCase() return headerGetter function headerGetter(req, res) { // set appropriate Vary header res.vary(str) // multiple headers get joined with comma by node.js core return (req.headers[header] || '').split(/ *, */) } }
javascript
{ "resource": "" }
q6889
PatternEmitter
train
function PatternEmitter() { EventEmitter.call(this); this.event = ''; this._regexesCount = 0; this._events = this._events || {}; this._patternEvents = this._patternEvents || {}; this._regexes = this._regexes || {}; }
javascript
{ "resource": "" }
q6890
iterate
train
function iterate(self, interceptors, args, after) { if (!interceptors || !interceptors.length) { after.apply(self, args); return; } var i = 0; var len = interceptors.length; if (!len) { after.apply(self, args); return; } function nextInterceptor() { if (i === len) { i++; after.apply(self, arguments); } else if (i < len) { var used = false; var interceptor = interceptors[i++]; interceptor.apply(self, Array.prototype.slice.call(arguments, 1).concat(function next(err) { // // Do not allow multiple continuations // if (used) { return; } used = true; if (!err || !callback) { nextInterceptor.apply(null, waterfall ? arguments : args); } else { after.call(self, err); } })); } } nextInterceptor.apply(null, args); }
javascript
{ "resource": "" }
q6891
createTransaction
train
function createTransaction (database, sequelizeTransaction) { const transaction = Object.assign(sequelizeTransaction, { getImplementation () { return sequelizeTransaction }, perform (changeset) { return database.applyChangeset(changeset, { transaction }) } }) return transaction }
javascript
{ "resource": "" }
q6892
train
function(fn, suffix) { if(suffix.charAt(0) !== '.') { suffix = '.' + suffix; } if(fn.length <= suffix.length) { return false; } var str = fn.substring(fn.length - suffix.length).toLowerCase(); suffix = suffix.toLowerCase(); return str === suffix; }
javascript
{ "resource": "" }
q6893
combineReducers
train
function combineReducers (reducers) { const databaseReducers = Object.keys(reducers) .map((collectionName) => { const reducer = reducers[ collectionName ] return createDatabaseReducer(reducer, collectionName) }) return (database, event) => { const changesets = databaseReducers.map((reducer) => reducer(database, event)) return combineChangesets(changesets) } }
javascript
{ "resource": "" }
q6894
createDatabaseReducer
train
function createDatabaseReducer (collectionReducer, collectionName) { return (database, event) => { const collection = database.collections[ collectionName ] if (!collection) { throw new Error(`Collection '${collectionName}' not known by database instance.`) } return collectionReducer(collection, event) } }
javascript
{ "resource": "" }
q6895
isReady
train
function isReady(aImage) { // first check : load status if (typeof aImage.complete === "boolean" && !aImage.complete) return false; // second check : validity of source (can be 0 until bitmap has been fully parsed by browser) return !(typeof aImage.naturalWidth !== "undefined" && aImage.naturalWidth === 0); }
javascript
{ "resource": "" }
q6896
onReady
train
function onReady(aImage, aCallback, aErrorCallback) { // if this didn't resolve in a full second, we presume the Image is corrupt var MAX_ITERATIONS = 60; var iterations = 0; function readyCheck() { if (Loader.isReady(aImage)) { aCallback(); } else if (++iterations === MAX_ITERATIONS) { if (typeof aErrorCallback === "function") aErrorCallback(); console.warn("Image could not be resolved. This shouldn't occur."); } else { // requestAnimationFrame preferred over a timeout as // browsers will fire this when the DOM is actually ready (e.g. Image is rendered) window.requestAnimationFrame(readyCheck); } } readyCheck(); }
javascript
{ "resource": "" }
q6897
listRequest
train
function listRequest (path, options = {}, cb) { if (typeof options === 'function') { cb = options; options = {}; } // serialise options let opts = []; for (let k in options) { // The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most // 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the // query to 2000 chars. We could be more precise and regenerate the URL until we reach as close // as possible to 4096, but frankly if you're searching for a string longer than 2000 characters // you're probably doing something wrong. if (k === 'query') { if (options.query.length > 2000) options.query = options.query.substr(0, 2000); opts.push(`query=${encodeURIComponent(options.query)}`); } else if (k === 'filter') { let filts = []; for (let f in options.filter) { if (Array.isArray(options.filter[f])) { options.filter[f].forEach(val => { filts.push(`${f}:${val}`); }); } else { filts.push(`${f}:${options.filter[f]}`); } } opts.push(`filter=${filts.join(',')}`); } else if (k === 'facet' && options.facet) opts.push('facet=t'); else opts.push(`${k}=${options[k]}`); } if (opts.length) path += `?${opts.join('&')}`; return GET(path, (err, msg) => { if (err) return cb(err); let objects = msg.items; delete msg.items; let nextOffset = 0 , isDone = false , nextOptions ; // /types is a list but it does not behave like the other lists // Once again the science.ai League of JStice saves the day papering over inconsistency! if (msg['items-per-page'] && msg.query) { nextOffset = msg.query['start-index'] + msg['items-per-page']; if (nextOffset > msg['total-results']) isDone = true; nextOptions = assign({}, options, { offset: nextOffset }); } else { isDone = true; nextOptions = assign({}, options); } cb(null, objects, nextOptions, isDone, msg); }); }
javascript
{ "resource": "" }
q6898
template
train
function template(str, data, options) { var data = data || {}; var options = options || {}; var keys = Array.isArray(data) ? Array.apply(null, { length: data.length }).map(Number.call, Number) : Object.keys(data); var len = keys.length; if (!len) { return str; } var before = options.before !== undefined ? options.before : '${'; var after = options.after !== undefined ? options.after : '}'; var escape = options.escape !== undefined ? options.escape : '\\'; var clean = options.clean !== undefined ? options.clean : false; cache[escape] = cache[escape] || escapeRegExp(escape); cache[before] = cache[before] || escapeRegExp(before); cache[after] = cache[after] || escapeRegExp(after); var begin = escape ? '(' + cache[escape] + ')?' + cache[before] : cache[before]; var end = cache[after]; for (var i = 0; i < len; i++) { str = str.replace(new RegExp(begin + String(keys[i]) + end, 'g'), function(match, behind) { return behind ? match : String(data[keys[i]]) }); } if (escape) { str = str.replace(new RegExp(escapeRegExp(escape) + escapeRegExp(before), 'g'), before); } return clean ? template.clean(str, options) : str; }
javascript
{ "resource": "" }
q6899
bootstrap
train
function bootstrap (bootstrappers) { const bootstrapPromise = bootstrappers.reduce( (metaPromise, bootstrapper) => metaPromise.then((prevMeta) => Promise.resolve(bootstrapper(prevMeta)).then((newMeta) => Object.assign({}, prevMeta, newMeta)) ), Promise.resolve({}) ).then((meta) => checkIfReadyToBoot(meta)) /** * @param {int} [port] * @param {string} [hostname] * @return {Promise<Http.Server>} * @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback */ bootstrapPromise.listen = function listen (port, hostname) { return bootstrapPromise.then((meta) => promisifiedListen(meta.app, port, hostname)) } return bootstrapPromise }
javascript
{ "resource": "" }