_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q32500
train
function(source, propertyName) { if (!conbo.isAccessor(source, propertyName) && !conbo.isFunc(source, propertyName)) { if (source instanceof conbo.EventDispatcher) { conbo.makeBindable(source, [propertyName]); } else { conbo.warn('It will not be possible to detect changes to "'+propertyName+'" because "'+source.toString()+'" is not an EventDispatcher'); } } }
javascript
{ "resource": "" }
q32501
train
function(element, attributeName) { if (this.attributeExists(attributeName)) { var camelCase = conbo.toCamelCase(attributeName), ns = attributeName.split('-')[0], attrFuncs = (ns == 'cb') ? BindingUtils__cbAttrs : BindingUtils__customAttrs, fn = attrFuncs[camelCase] ; if (fn.readOnly) { fn.call(attrFuncs, element); } else { conbo.warn(attributeName+' attribute cannot be used without a value'); } } else { conbo.warn(attributeName+' attribute does not exist'); } return this; }
javascript
{ "resource": "" }
q32502
train
function(view) { if (!view) { throw new Error('view is undefined'); } if (!view.__bindings || !view.__bindings.length) { return this; } var bindings = view.__bindings; while (bindings.length) { var binding = bindings.pop(); try { binding[0].removeEventListener(binding[1], binding[2]); } catch (e) {} } delete view.__bindings; return this; }
javascript
{ "resource": "" }
q32503
train
function(rootView, namespace, type) { type || (type = 'view'); if (['view', 'glimpse'].indexOf(type) == -1) { throw new Error(type+' is not a valid type parameter for applyView'); } var typeClass = conbo[type.charAt(0).toUpperCase()+type.slice(1)], scope = this ; var rootEl = conbo.isElement(rootView) ? rootView : rootView.el; for (var className in namespace) { var classReference = scope.getClass(className, namespace); var isView = conbo.isClass(classReference, conbo.View); var isGlimpse = conbo.isClass(classReference, conbo.Glimpse) && !isView; if ((type == 'glimpse' && isGlimpse) || (type == 'view' && isView)) { var tagName = conbo.toKebabCase(className); var nodes = conbo.toArray(rootEl.querySelectorAll(tagName+':not(.cb-'+type+'):not([cb-repeat]), [cb-'+type+'='+className+']:not(.cb-'+type+'):not([cb-repeat])')); nodes.forEach(function(el) { var ep = __ep(el); // Ignore anything that's inside a cb-repeat if (!ep.closest('[cb-repeat]')) { var closestView = ep.closest('.cb-view'); var context = closestView ? closestView.cbView.subcontext : rootView.subcontext; new classReference({el:el, context:context}); } }); } } return this; }
javascript
{ "resource": "" }
q32504
train
function(className, namespace) { if (!className || !namespace) return; try { var classReference = namespace[className]; if (conbo.isClass(classReference)) { return classReference; } } catch (e) {} }
javascript
{ "resource": "" }
q32505
train
function(name, handler, readOnly, raw) { if (!conbo.isString(name) || !conbo.isFunction(handler)) { conbo.warn("registerAttribute: both 'name' and 'handler' parameters are required"); return this; } var split = conbo.toUnderscoreCase(name).split('_'); if (split.length < 2) { conbo.warn("registerAttribute: "+name+" does not include a namespace, e.g. "+conbo.toCamelCase('my-'+name)); return this; } var ns = split[0]; if (BindingUtils__reservedNamespaces.indexOf(ns) != -1) { conbo.warn("registerAttribute: custom attributes cannot to use the "+ns+" namespace"); return this; } BindingUtils__registeredNamespaces = conbo.union(BindingUtils__registeredNamespaces, [ns]); conbo.assign(handler, { readOnly: !!readOnly, raw: !!raw }); BindingUtils__customAttrs[name] = handler; return this; }
javascript
{ "resource": "" }
q32506
train
function(mask) { var borders = ['border-top','border-right', 'border-bottom', 'border-left']; var res = {}; for (var i = 0; i < 4; i++) { if (!(mask & bin(i))) res[borders[i]] = 'none'; } return res; }
javascript
{ "resource": "" }
q32507
train
function (obj) { var clone = _.clone(obj); if (obj.style) { var style = obj.style; clone.style = { "font-family": style.fontFamily, "font-size": style.fontSize + "px", "font-weight": (style.mask & bin(4)) ? "bold" : "normal", "font-style": (style.mask & bin(5)) ? "italic" : "normal", "text-decoration": (((style.mask & bin(6)) ? "underline " : "") + ((style.mask & bin(7)) ? "line-through" : "")), "text-align": style.textAlign, "color": style.color, "background-color": style.backgroundColor, "border": [style.borderWidth + "px", style.borderStyle, style.borderColor].join(" "), "padding": style.padding.join("px ") + "px" }; _.extend(clone.style, checkBorder(style.mask)); } // init style if null clone.style || (clone.style = {}); return clone; }
javascript
{ "resource": "" }
q32508
callListenersSequentially
train
function callListenersSequentially(i, args) { if (!this.events[eventName][i]) { // If there is no more listener to execute, we return a promise of the event arguments/result // So we are getting out of the recursive function return new Promise((resolve, reject) => { resolve(args); }); } const p = Promise.resolve(this.events[eventName][i].apply(this.events[eventName][i], args)); return p.then(function propagateArguments() { // We cannot use the "=>" notation here because we use `"arguments" // When an event listener has been executed, we move to the next one (recursivity) if (propagateResponses) { // Case the event must pass the result of a listener to the next one // This use case allow to transmit and alter primitive (strings, numbers ...) return callListenersSequentially.bind(this)(i + 1, arguments[0]); } // Case the event can pass the arguments to each listener // This use case allow a simple syntax for listener, compatible with fireConcurrently() // But it is not possible to transmit alterations made on primitive arguments return callListenersSequentially.bind(this)(i + 1, args); }.bind(this)); }
javascript
{ "resource": "" }
q32509
train
function (arr, callback, initialValue) { var len = arr.length; if (typeof callback !== 'function') { throw new TypeError('callback is not function!'); } // no value to return if no initial value and an empty array if (len === 0 && arguments.length == 2) { throw new TypeError('arguments invalid'); } var k = 0; var accumulator; if (arguments.length >= 3) { accumulator = arguments[2]; } else { do { if (k in arr) { accumulator = arr[k++]; break; } // if array contains no values, no initial value to return k += 1; if (k >= len) { throw new TypeError(); } } while (TRUE); } while (k < len) { if (k in arr) { accumulator = callback.call(undefined, accumulator, arr[k], k, arr); } k++; } return accumulator; }
javascript
{ "resource": "" }
q32510
train
function (o) { if (o == null) { return []; } if (S.isArray(o)) { return o; } var lengthType = typeof o.length, oType = typeof o; // The strings and functions also have 'length' if (lengthType != 'number' || // form.elements in ie78 has nodeName 'form' // then caution select // o.nodeName // window o.alert || oType == 'string' || // https://github.com/ariya/phantomjs/issues/11478 (oType == 'function' && !( 'item' in o && lengthType == 'number'))) { return [o]; } var ret = []; for (var i = 0, l = o.length; i < l; i++) { ret[i] = o[i]; } return ret; }
javascript
{ "resource": "" }
q32511
train
function (path, ext) { var result = path.match(splitPathRe) || [], basename; basename = result[3] || ''; if (ext && basename && basename.slice(-1 * ext.length) == ext) { basename = basename.slice(0, -1 * ext.length); } return basename; }
javascript
{ "resource": "" }
q32512
train
function (key, value) { var self = this, _queryMap, currentValue; if (typeof key == 'string') { parseQuery(self); _queryMap = self._queryMap; currentValue = _queryMap[key]; if (currentValue === undefined) { currentValue = value; } else { currentValue = [].concat(currentValue).concat(value); } _queryMap[key] = currentValue; } else { if (key instanceof Query) { key = key.get(); } for (var k in key) { self.add(k, key[k]); } } return self; }
javascript
{ "resource": "" }
q32513
train
function (other) { var self = this; // port and hostname has to be same return equalsIgnoreCase(self.hostname, other['hostname']) && equalsIgnoreCase(self.scheme, other['scheme']) && equalsIgnoreCase(self.port, other['port']); }
javascript
{ "resource": "" }
q32514
train
function (serializeArray) { var out = [], self = this, scheme, hostname, path, port, fragment, query, userInfo; if (scheme = self.scheme) { out.push(encodeSpecialChars(scheme, reDisallowedInSchemeOrUserInfo)); out.push(':'); } if (hostname = self.hostname) { out.push('//'); if (userInfo = self.userInfo) { out.push(encodeSpecialChars(userInfo, reDisallowedInSchemeOrUserInfo)); out.push('@'); } out.push(encodeURIComponent(hostname)); if (port = self.port) { out.push(':'); out.push(port); } } if (path = self.path) { if (hostname && !S.startsWith(path, '/')) { path = '/' + path; } path = Path.normalize(path); out.push(encodeSpecialChars(path, reDisallowedInPathName)); } if (query = ( self.query.toString.call(self.query, serializeArray))) { out.push('?'); out.push(query); } if (fragment = self.fragment) { out.push('#'); out.push(encodeSpecialChars(fragment, reDisallowedInFragment)) } return out.join(''); }
javascript
{ "resource": "" }
q32515
train
function (runtime, modNames) { S.each(modNames, function (m) { Utils.createModuleInfo(runtime, m); }); }
javascript
{ "resource": "" }
q32516
train
function (runtime, modNames) { var mods = [runtime], mod, unalias, allOk, m, runtimeMods = runtime.Env.mods; S.each(modNames, function (modName) { mod = runtimeMods[modName]; if (!mod || mod.getType() != 'css') { unalias = Utils.unalias(runtime, modName); allOk = S.reduce(unalias, function (a, n) { m = runtimeMods[n]; return a && m && m.status == ATTACHED; }, true); if (allOk) { mods.push(runtimeMods[unalias[0]].value); } else { mods.push(null); } } }); return mods; }
javascript
{ "resource": "" }
q32517
train
function (runtime, mod) { if (mod.status != LOADED) { return; } var fn = mod.fn; if (typeof fn === 'function') { // 需要解开 index,相对路径 // 但是需要保留 alias,防止值不对应 mod.value = fn.apply(mod, Utils.getModules(runtime, mod.getRequiresWithAlias())); } else { mod.value = fn; } mod.status = ATTACHED; }
javascript
{ "resource": "" }
q32518
train
function (runtime, path, rules) { var mappedRules = rules || runtime.Config.mappedRules || [], i, m, rule; for (i = 0; i < mappedRules.length; i++) { rule = mappedRules[i]; if (m = path.match(rule[0])) { return path.replace(rule[0], rule[1]); } } return path; }
javascript
{ "resource": "" }
q32519
train
function () { var self = this; if (self.packageUri) { return self.packageUri; } return self.packageUri = new S.Uri(this.getPrefixUriForCombo()); }
javascript
{ "resource": "" }
q32520
train
function () { var self = this, t, fullPathUri, packageBaseUri, packageInfo, packageName, path; if (!self.fullPathUri) { if (self.fullpath) { fullPathUri = new S.Uri(self.fullpath); } else { packageInfo = self.getPackage(); packageBaseUri = packageInfo.getBaseUri(); path = self.getPath(); // #262 if (packageInfo.isIgnorePackageNameInUri() && // native mod does not allow ignore package name (packageName = packageInfo.getName())) { path = Path.relative(packageName, path); } fullPathUri = packageBaseUri.resolve(path); if (t = self.getTag()) { t += '.' + self.getType(); fullPathUri.query.set('t', t); } } self.fullPathUri = fullPathUri; } return self.fullPathUri; }
javascript
{ "resource": "" }
q32521
train
function () { var self = this, fullPathUri; if (!self.fullpath) { fullPathUri = self.getFullPathUri(); self.fullpath = Utils.getMappedPath(self.runtime, fullPathUri.toString()); } return self.fullpath; }
javascript
{ "resource": "" }
q32522
train
function () { var self = this, runtime = self.runtime; return S.map(self.getNormalizedRequires(), function (r) { return Utils.createModuleInfo(runtime, r); }); }
javascript
{ "resource": "" }
q32523
train
function () { var self = this, normalizedRequires, normalizedRequiresStatus = self.normalizedRequiresStatus, status = self.status, requires = self.requires; if (!requires || requires.length == 0) { return requires || []; } else if ((normalizedRequires = self.normalizedRequires) && // 事先声明的依赖不能当做 loaded 状态下真正的依赖 (normalizedRequiresStatus == status)) { return normalizedRequires; } else { self.normalizedRequiresStatus = status; return self.normalizedRequires = Utils.normalizeModNames(self.runtime, requires, self.name); } }
javascript
{ "resource": "" }
q32524
train
function (moduleName) { var moduleNames = Utils.unalias(S, Utils.normalizeModNamesWithAlias(S, [moduleName])); if (Utils.attachModsRecursively(moduleNames, S)) { return Utils.getModules(S, moduleNames)[1]; } return undefined; }
javascript
{ "resource": "" }
q32525
train
function (data) { if (data && RE_NOT_WHITESPACE.test(data)) { // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context // http://msdn.microsoft.com/en-us/library/ie/ms536420(v=vs.85).aspx always return null ( win.execScript || function (data) { win[ 'eval' ].call(win, data); } )(data); } }
javascript
{ "resource": "" }
q32526
links
train
function links(options) { var page = this.page; return this.navigation.reduce(function reduce(menu, item) { if (page === item.page) item.class = (item.class || '') + ' active'; if (item.class) item.class = ' class="' + item.class + '"'; if (item.swap) item.swap = ' data-swap="' + item.swap.hide + '@' + item.swap.show + '"'; if (item.effect) item.effect = ' data-effect="' + item.effect + '"'; item.href = item.href || '#'; return menu + options.fn(item); }, ''); }
javascript
{ "resource": "" }
q32527
publish
train
function publish(loc, data) { data = data || {}; data.clientID = clientID; fayeClient.publish(loc, data); }
javascript
{ "resource": "" }
q32528
train
function(title, content, callback) { console.log('mltc'); publish('/query/moreLikeThisContent', { title: title, content: content }); results(callback); }
javascript
{ "resource": "" }
q32529
train
function(options, cb) { console.log('/watch/request', options); publish('/watch/request', options); fayeClient.subscribe('/watch/results/' + clientID, cb); }
javascript
{ "resource": "" }
q32530
isElementInViewport
train
function isElementInViewport(el) { var eap; var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var vWidth = window.innerWidth || docEl.clientWidth; var vHeight = window.innerHeight || docEl.clientHeight; var efp = function (x, y) { return document.elementFromPoint(x, y); }; var contains = el.contains ? (function (node) { return el.contains(node); }) : (function (node) { return el.compareDocumentPosition(node) == 0x10; }); // Return false if it's not in the viewport if (rect.right < 0 || rect.bottom < 0 || rect.left > vWidth || rect.top > vHeight) return false; // Return true if any of its four corners are visible return ((eap = efp(rect.left, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.top)) == el || contains(eap) || (eap = efp(rect.right, rect.bottom)) == el || contains(eap) || (eap = efp(rect.left, rect.bottom)) == el || contains(eap)); }
javascript
{ "resource": "" }
q32531
versioningJSON
train
function versioningJSON ( obj, dest, ns ) { var content = {}; content[ ns ] = obj; var json = JSON.stringify( content, null, 2 ); grunt.log.subhead( 'Generating JSON config file' ); grunt.file.write( dest + '/assets.config.json', json ); grunt.log.ok( 'File "' + dest + '/assets.config.json" created.' ); }
javascript
{ "resource": "" }
q32532
versioningPHP
train
function versioningPHP ( obj, dest, ns ) { var contents = '<?php\n'; contents += 'return array(\n'; contents += ' \'' + ns + '\' => array(\n'; for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { contents += ' \'' + key + '\' => array(\n'; contents += ' \'css\' => array(\n'; contents += extractFiles( obj[ key ].css ); contents += ' ),\n'; contents += ' \'js\' => array(\n'; contents += extractFiles( obj[ key ].js ); contents += ' ),\n'; contents += ' ),\n'; } } contents += ' )\n'; contents += ');\n'; grunt.log.subhead( 'Generating PHP config file' ); grunt.file.write( dest + '/assets.config.php', contents ); grunt.log.ok( 'File "' + dest + '/assets.config.php" created.' ); }
javascript
{ "resource": "" }
q32533
ParseMessageFromThread
train
function ParseMessageFromThread(o) { var o = UnserializeFromProcess(o); if (typeof(o) == "object" && o.name && o.args) { // Process response from the thread // Electron: If we are in the Main Process, and it is not a global message, we executed it too if (!isElectron || electron.ipcRenderer || !o.electronSenderId) { var args = o.args; var name = o.name; ThreadMessage[name].apply(ThreadMessage, args); } else { // Electron: Send the message to the correct window var electronSenderId = o.electronSenderId; ipc.sendTo(electronSenderId, "threadify-message", o); } } }
javascript
{ "resource": "" }
q32534
CheckPendingThreadRequests
train
function CheckPendingThreadRequests() { while (PendingThreadRequests.length) { var tq = PendingThreadRequests.shift(); if (!SendThreadRequest(tq)) { // No available thread, we queue the request, again PendingThreadRequests.unshift(tq); break; } } }
javascript
{ "resource": "" }
q32535
findObject
train
function findObject(c, obj, path, alreadyParsed) { if (!path) { path = []; } // Recursive reference : boooh, very wrong if (!alreadyParsed) { alreadyParsed = []; } var keys = Object.keys(obj); alreadyParsed.push(obj); for (var key = 0; key < keys.length; key++) { var i = keys[key]; if (i == "NativeModule" && isElectron) { break; } if (obj[i] === c) { path.push(i); return path; } else if (["object", "function"].indexOf(typeof(obj[i])) >= 0 && alreadyParsed.indexOf(obj[i]) == -1 && obj[i] !== null && obj[i] !== undefined) { path.push(i); var founded = findObject(c, obj[i], path, alreadyParsed); if (founded) { return founded; } else { path.pop(); } } }; return null; }
javascript
{ "resource": "" }
q32536
Threadify
train
function Threadify(options) { if (typeof(options) == "string") { options = {methods: [options]}; } else if (Array.isArray(options)) { options = {methods: options}; } else { if (options !== undefined && typeof(options) != "object") { throw new Error("[Threadify] You must specify either: \nNothing\nA string\nAn array of string\n") } } var options = Object.assign({ module: null, exportsPath: null, methods: [] }, options); // We automatically search the class or the object in the module loaded if (!options.module) { var cacheFounded = null; var pathExport = []; var parsedModule = [require.main, require.cache]; for (var i in require.cache) { var cache = require.cache[i]; // If module have exports, we search the class/object in it if (cache.exports) { var objectToSearch = {}; // We exclude electron modules because of a lot of loop references if (isElectron && cache.filename.indexOf("/node_modules/electron/") >= 0) { continue; } var pathObject = []; if (cache.exports !== this) { pathObject = findObject(this, cache.exports, [], parsedModule); } if (pathObject !== null) { cacheFounded = {module: cache, pathToClass: pathObject}; break; } } } if (!cacheFounded) { throw new Error("[Threadify] Class to threadify must be in a non-core separate module."); } else { options.module = cacheFounded.module.filename; options.exportsPath = cacheFounded.pathToClass; } } return ThreadifyAll(this, options); }
javascript
{ "resource": "" }
q32537
getSettings
train
function getSettings (def) { var settings = {} for (var s in def) { if (def.hasOwnProperty(s)) { if (s !== 'name' || s !== 'properties') { settings[ s ] = def[ s ] } } } return settings }
javascript
{ "resource": "" }
q32538
instancesFromMatches
train
function instancesFromMatches(word, text, selector) { var match, ret = []; var re = new RegExp('\\b'+utils.escapeRegex(word)+'\\b', 'gi'); var instance = 1; while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); // It's not in a tag if (text.indexOf('<' < 0) || (text.indexOf('>', match.index) > text.indexOf('<'.match.index))) { ret.push(annoLib.createInstance({exact: text.substr(match.index, word.length), instance: instance, selector: selector})); } instance++; } return ret; }
javascript
{ "resource": "" }
q32539
rangesFromMatches
train
function rangesFromMatches(word, text, selector) { var ret = [], match; var re = new RegExp('\\b'+word+'\\b', 'gi'); while ((match = re.exec(text)) !== null) { GLOBAL.debug(text.length, text.substring(0, 10), word, match.index, text.substr(match.index, word.length)); ret.push(annoLib.createRange({exact: text.substr(match.index, word.length), offset: match.index, selector: selector})); } return ret; }
javascript
{ "resource": "" }
q32540
setVocabIds
train
function setVocabIds(index, pkg, callback) { if(!pkg.tags) return callback(); if( index == pkg.tags.length ) { callback(); } else { getVocabId(pkg.tags[index].vocabulary_id, function(id) { pkg.tags[index].vocabulary_id = id; index++; setVocabIds(index, pkg, callback); }); } }
javascript
{ "resource": "" }
q32541
getVocabId
train
function getVocabId(name, callback) { if( vocabMap[name] ) return callback(vocabMap[name]); ckan.exec("vocabulary_show", {id: name}, function(err, resp) { if( err && JSON.parse(err.body).error.__type == 'Not Found Error' ) { create("vocabulary", {name: name, tags: []}, function(err, resp){ if( err ) error("Unable to create vocabulary: "+name); vocabMap[name] = resp.result.id; callback(resp.result.id); }); return; } else if( err ) { error("Unable to access vocabulary 'id:"+name+"'"); } if( !resp.success ) { if( name.match(/.*-.*-.*-.*-.*/) ) { if( err ) error("No vocabulary found for passed id"); create("vocabulary", {name: name, tags: []}, function(err, resp){ if( err ) error("Unable to create vocabulary: "+name); vocabMap[name] = resp.result.id; callback(resp.result.id); }); } } else { vocabMap[name] = resp.result.id; callback(resp.result.id); } }); }
javascript
{ "resource": "" }
q32542
format
train
function format() { var format = 'es' // default var args = process.argv.slice(2) outer: for (var i = 0; i < formats.length; i++) { for (var j = 0; j < args.length; j++) { if (args[j].slice(0, 2) !== '--') { throw new TypeError('process args usage error'); break outer } if (args[j].toLocaleLowerCase().slice(9) === formats[i]) { format = formats[i]; break outer } } } return format }
javascript
{ "resource": "" }
q32543
write
train
function write(dir, code) { return new Promise(function (resolve, reject) { fse.ensureFile(dir, (err) => { if (err) return reject(err) fs.writeFile(dir, code, 'utf-8', (err) => { if (err) { return reject(err) } console.info(chalk.red(dir) + ' ' + chalk.green(getSize(code))) resolve() }) }) }) }
javascript
{ "resource": "" }
q32544
noLeadingSpaces
train
function noLeadingSpaces(ast, file) { var lines = file.toString().split('\n'); for (var i = 0; i < lines.length; i++) { var currentLine = lines[i]; var lineIndex = i + 1; if (/^\s/.test(currentLine)) { file.message('Remove leading whitespace', { position: { start: { line: lineIndex, column: 1 }, end: { line: lineIndex } } }); } } }
javascript
{ "resource": "" }
q32545
callStaticMethod
train
function callStaticMethod(methodName, req, res, next) { res.__apiMethod = 'staticMethod'; res.__apiStaticMethod = methodName; var self = this; var methodOptions = this.apiOptions.exposeStatic[methodName] || {}; var wrapper = methodOptions.exec; if (!(wrapper instanceof Function)) wrapper = null; var httpMethod = methodOptions.method || 'post'; var params = (httpMethod !== 'get') ? req.body : req.query; var mFunc = wrapper || this.model[methodName]; mFunc.call(this.model, params, function(err, result) { if (err) return next(err); res.json(result); }); }
javascript
{ "resource": "" }
q32546
addClass
train
function addClass( element ) { const addClassNamesArray = _sliceArgs( arguments ); if ( hasClassList ) { element.classList.add.apply( element.classList, addClassNamesArray ); } else { var classes = element.className.split( ' ' ); addClassNamesArray.forEach( function( name ) { if ( classes.indexOf( name ) === -1 ) { classes.push( name ); } } ); element.className = classes.join( ' ' ); } return element; }
javascript
{ "resource": "" }
q32547
contains
train
function contains( element, className ) { className = className.replace( '.', '' ); if ( hasClassList ) { return element.classList.contains( className ); } return element.className.indexOf( className ) > -1; }
javascript
{ "resource": "" }
q32548
removeClass
train
function removeClass( element ) { const removeClassNamesArray = _sliceArgs( arguments ); if ( hasClassList ) { element.classList.remove .apply( element.classList, removeClassNamesArray ); } else { var classes = element.className.split( ' ' ); removeClassNamesArray.forEach( function( className ) { if ( className ) { classes.splice( classes.indexOf( className ), 1 ); } } ); element.className = classes.join( ' ' ); } }
javascript
{ "resource": "" }
q32549
toggleClass
train
function toggleClass( element, className, forceFlag ) { let hasClass = false; if ( hasClassList ) { hasClass = element.classList.toggle( className ); } else if ( forceFlag === false || contains( element, className ) ) { removeClass( element, forceFlag ); } else { addClass( element, className ); hasClass = true; } return hasClass; }
javascript
{ "resource": "" }
q32550
train
function (versionString, cb) { var mem = new MemoryStream(null, {readable: false}); var url = 'https://wiseplat.github.io/solc-bin/bin/soljson-' + versionString + '.js'; https.get(url, function (response) { if (response.statusCode !== 200) { cb(new Error('Error retrieving binary: ' + response.statusMessage)); } else { response.pipe(mem); response.on('end', function () { cb(null, setupMethods(requireFromString(mem.toString(), 'soljson-' + versionString + '.js'))); }); } }).on('error', function (error) { cb(error); }); }
javascript
{ "resource": "" }
q32551
train
function($done) { function procType(kv, $_done) { var jobType=kv[0], func=kv[1] JOBS.process(jobType, func._concurrent, func) $_done() } // TODO: wouldn't need to do this if async.forEach() took an object var _procs = _.zip(_.keys(__processors), _.values(__processors)) async.forEach(_procs, procType, function(err) { if (err) return $done(err); __running.process = true $done() }) }
javascript
{ "resource": "" }
q32552
train
function(config) { INIT(config) this.__init__() this.log = LOG this.jobs = JOBS MEM = new MemChecker(this, CONF.memChecker) this._ = { www: WWW ,redis: JOBS._rawQueue.client } }
javascript
{ "resource": "" }
q32553
train
function(in_type){ this._is_a = 'class_expression'; var anchor = this; /// /// Initialize. /// // in_type is always a JSON object, trivial catch of attempt to // use just a string as a class identifier. if( in_type ){ if( what_is(in_type) === 'class_expression' ){ // Unfold and re-parse (takes some properties of new // host). in_type = in_type.structure(); }else if( what_is(in_type) === 'object' ){ // Fine as it is. }else if( what_is(in_type) === 'string' ){ // Convert to a safe representation. in_type = { 'type': 'class', 'id': in_type, 'label': in_type }; } } // Every single one is a precious snowflake (which is necessary // for managing some of the aspects of the UI for some use cases). this._id = bbop.uuid(); // Derived property defaults. this._type = null; this._category = 'unknown'; this._class_id = null; this._class_label = null; this._property_id = null; this._property_label = null; // Recursive elements. this._frame = []; // this._raw_type = in_type; if( in_type ){ anchor.parse(in_type); } }
javascript
{ "resource": "" }
q32554
_class_labeler
train
function _class_labeler(ce){ var ret = ce.class_label(); // Optional ID. var cid = ce.class_id(); if( cid && cid !== ret ){ ret = '[' + cid + '] ' + ret; } return ret; }
javascript
{ "resource": "" }
q32555
train
function(config) { this._config = this._defaultConfig(); if (!config) return true; var datastore; switch(config.adapter) { case 'disk': datastore = this._adapters.disk.connection(); break; case 'redis': datastore = this._adapters.redis.connection(config.redis); break; case 'memory': default: return true; // Memory adapter by default } // Set connection this._config.connections.datastore = datastore; return true; }
javascript
{ "resource": "" }
q32556
train
function(cb) { this._loadCollections(); // Start Waterline var self = this; this._waterline.initialize(self.config, function(err, waterline) { if(err) throw err; hb.addModel('Account', waterline.collections['accounts-'+hb.env]); hb.addModel('Keyword', waterline.collections['keywords-'+hb.env]); cb(); }); }
javascript
{ "resource": "" }
q32557
miniTemplateEngine
train
function miniTemplateEngine(str, props, callback) { var isCallback = false, errorString = 'The first parameter must be a string'; if (callback && isFunction(callback)) { isCallback = true; } if (!str || !isString(str)) { if (isCallback) { callback(null, errorString); } else { throw new Error(errorString); } } if (!props || !isObject(props)) { props = {}; } if (isCallback) { setTimeout(function() { return callback( new TemplateBuilder(str, props) .getRenderedTemplate() ); }, 1); } else { return new TemplateBuilder(str, props) .getRenderedTemplate(); } }
javascript
{ "resource": "" }
q32558
rpnToTree
train
function rpnToTree(values) { let ii, len, op, stack, slice, count; stack = []; // result = []; for (ii = 0, len = values.length; ii < len; ii++) { op = values[ii]; if (op === LEFT_PAREN) { // cut out this sub and convert it to a tree slice = findMatchingRightParam(values, ii); if (!slice || slice.length === 0) { throw new Error('mismatch parentheses'); } ii += slice.length + 1; // evaluate this sub command before pushing it to the stack slice = rpnToTree(slice); stack.push(slice); } else { if (Array.isArray(op)) { stack.push(op); } else { // figure out how many arguments to take from the stack count = argCount(op); slice = stack.splice(stack.length - count, count); if (Array.isArray(slice) && slice.length === 1) { slice = arrayFlatten(slice, true); } // TODO: ugh, occasionally args will get flattened too much if (slice[0] === VALUE) { // note only happens with ALIAS_GET // log.debug('overly flat ' + JSON.stringify([op].concat(slice))); slice = [slice]; } stack.push([op].concat(slice)); } } } return stack; }
javascript
{ "resource": "" }
q32559
strip
train
function strip(file) { file.fingerprint = file.fingerprint.slice(0, -3); delete file.source; delete file.sourcemap; delete file.shrinkwrap; return file; }
javascript
{ "resource": "" }
q32560
validateParamsPresent
train
function validateParamsPresent(expectedKeys, params) { params = params || {}; var paramKeys = _.keys(params); return _.first(_.difference(expectedKeys, _.intersection(paramKeys, expectedKeys))); }
javascript
{ "resource": "" }
q32561
validateCommonParams
train
function validateCommonParams(params) { log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateCommonParams"); var expectedParams = ["method", "data", "resourcePath", "environment", "domain"]; var missingParam = validateParamsPresent(expectedParams, params); if (missingParam) { return missingParam; } //The resource Path Is Invalid If It Is An Object log.logger.debug('ResourcePath :: ', params.resourcePath); if (_.isObject(params.resourcePath)) { log.logger.debug('Resource Path Is Object, returning path key !!! ', params.resourcePath); return params.resourcePath.key; } //If it is a file request, the data entry must contain file params. if (params.fileRequest && params.fileUploadRequest) { missingParam = validateParamsPresent(["name", "type", "size", "stream"], params.data); } return missingParam; }
javascript
{ "resource": "" }
q32562
validateAppParams
train
function validateAppParams(params) { params = params || {}; var expectedAppParams = ["project", "app", "accessKey", "appApiKey", "url"]; var missingParam = validateCommonParams(params); if (missingParam) { return new Error("Missing Param " + missingParam); } missingParam = validateParamsPresent(expectedAppParams, params); if (missingParam) { return new Error("Missing MbaaS Config Param " + missingParam); } return undefined; }
javascript
{ "resource": "" }
q32563
validateAdminParams
train
function validateAdminParams(params) { log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateAdminParams"); var missingParam = validateCommonParams(params); var expectedAdminMbaasConfig = ["url", "username", "password"]; if (missingParam) { return new Error("Missing Param " + missingParam); } missingParam = validateParamsPresent(expectedAdminMbaasConfig, params); if (missingParam) { return new Error("Missing MbaaS Config Param " + missingParam); } return undefined; }
javascript
{ "resource": "" }
q32564
_buildAdminMbaasParams
train
function _buildAdminMbaasParams(params) { log.logger.debug({params: params}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams"); var basePath; basePath = config.addURIParams(constants.ADMIN_API_PATH, params); params = params || {}; var method, resourcePath; method = params.method; resourcePath = params.resourcePath; var mbaasUrl = params.__mbaasUrl; var parsedMbaasUrl = url.parse(mbaasUrl); parsedMbaasUrl.pathname = basePath + resourcePath; var adminRequestParams = { url: parsedMbaasUrl.format(), method: method, headers: { host: parsedMbaasUrl.host, 'x-fh-service-key': params.servicekey }, fileRequest: params.fileRequest, fileUploadRequest: params.fileUploadRequest, data: params.data, paginate: params.paginate, envLabel: params._label }; if (params.username && params.password) { adminRequestParams.auth = { user: params.username, pass: params.password }; } log.logger.debug({adminRequestParams: adminRequestParams}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams"); return adminRequestParams; }
javascript
{ "resource": "" }
q32565
responseHandler
train
function responseHandler(params, cb) { return function handleResponse(err, httpResponse, body) { body = body || "{}"; httpResponse = httpResponse || {}; //The response should be JSON. If it is a string, then the response should be parsed. if (_.isString(body)) { try { body = JSON.parse(body); } catch (e) { log.logger.error("FH-MBAAS-CLIENT: Invalid Response Body ", {body: body}); } } log.logger.debug("FH-MBAAS-CLIENT: Request Finish ", { err: err, httpResponse: httpResponse.statusCode, body: body }); // provide defaults if (httpResponse && httpResponse.statusCode >= 400) { err = err || {}; err.httpCode = httpResponse.statusCode; err.message = "Unexpected Status Code " + httpResponse.statusCode; } //There is a specific error message if an environment is unreachable if (httpResponse && httpResponse.statusCode === 503) { err = { httpCode: 503, message: CONSTANTS.ERROR_MESSAGES.ENVIRONMENT_UNREACHABLE.replace('{{ENVLABEL}}', params.envLabel || "") }; } // MbaaS unavailable if (err && err.code !== undefined && (err.code === "ENOTFOUND" || err.code === "ETIMEDOUT")) { err = { httpCode: httpResponse.statusCode || 500, message: "MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - " + params.envLabel || "" }; } if (err) { cb(err || body || "Unexpected Status Code " + httpResponse.statusCode); } else { cb(undefined, body); } }; }
javascript
{ "resource": "" }
q32566
doFHMbaaSRequest
train
function doFHMbaaSRequest(params, cb) { //Preventing multiple callbacks. // _.defaults(undefined, ...) === undefined, so we still need to OR with an empty object params = _.defaults(params || {}, { headers: {} }); //Adding pagination parameters if required params.url = addPaginationUrlParams(params.url, params); // add request id header to request if present if (_.isFunction(log.logger.getRequestId)) { var reqId = log.logger.getRequestId(); if (reqId) { params.headers[log.logger.requestIdHeader] = reqId; } } log.logger.debug({params: params}, "FH-MBAAS-CLIENT: doFHMbaaSRequest"); var fileData = params.data; //If it is a file upload request, the file data is assigned differently if (params.fileRequest && params.fileUploadRequest) { params.json = false; } else { //Normal JSON Request params.json = true; //Dont set a body if it is a get request if (params.method === "GET") { params.qs = params.data; } else { params.body = params.data; } } //The data field is no longer needed params = _.omit(params, 'data'); //If Mbaas Request Expects To Send/Recieve Files, then return the request value if (params.fileRequest && params.fileUploadRequest) { log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Upload Request"); var formData = {}; formData[fileData.name] = { value: fileData.stream, options: { filename: fileData.name, contentType: fileData.type } }; return request({ method: params.method, url: params.url, auth: params.auth, headers: params.headers, formData: formData }, responseHandler(params, cb)); } else if (params.fileRequest) { log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Download Request"); //File Download Request. Return the readable request stream. return cb(undefined, request(params)); } else { //Normal call. log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest Normal Request"); request(params, responseHandler(params, cb)); } }
javascript
{ "resource": "" }
q32567
_buildAppRequestParams
train
function _buildAppRequestParams(params) { params = params || {}; var basePath = config.addURIParams(constants.APP_API_PATH, params); var fullPath = basePath + params.resourcePath; var mbaasUrl = url.parse(params.url); mbaasUrl.pathname = fullPath; var headers = { 'x-fh-env-access-key': params.accessKey, 'x-fh-auth-app': params.appApiKey }; return { url: mbaasUrl.format(mbaasUrl), method: params.method, headers: headers, fileRequest: params.fileRequest, fileUploadRequest: params.fileUploadRequest, data: params.data, paginate: params.paginate }; }
javascript
{ "resource": "" }
q32568
adminRequest
train
function adminRequest(params, cb) { params = params || {}; var mbaasConf = params[constants.MBAAS_CONF_KEY]; params[constants.MBAAS_CONF_KEY] = undefined; log.logger.debug({params: params}, "FH-MBAAS-CLIENT: adminRequest "); var fullParams = _.extend(_.clone(params), mbaasConf); log.logger.info({ env: params.environment, domain: fullParams.domain, mbaasUrl: fullParams.__mbaasUrl }, "FH-MBAAS-CLIENT.adminRequest - calling mbaas:"); var invalidParamError = validateAdminParams(fullParams); if (invalidParamError) { return cb(invalidParamError); } fullParams.data = fullParams.data || {}; fullParams.data.notStats = params.notStats; fullParams = _buildAdminMbaasParams(fullParams); log.logger.debug({fullParams: fullParams}, "FH-MBAAS-CLIENT: adminRequest "); return doFHMbaaSRequest(fullParams, cb); }
javascript
{ "resource": "" }
q32569
appRequest
train
function appRequest(params, cb) { params = params || {}; var mbaasConf = params[constants.MBAAS_CONF_KEY]; params[constants.MBAAS_CONF_KEY] = undefined; //Adding Mbaas Config Params var fullParams = _.extend(_.clone(params), mbaasConf); var invalidParamError = validateAppParams(fullParams); if (invalidParamError) { return cb(invalidParamError); } fullParams = _buildAppRequestParams(fullParams); return doFHMbaaSRequest(fullParams, cb); }
javascript
{ "resource": "" }
q32570
Union
train
function Union () { debug('defining new union "type"') function UnionType (arg, data) { if (!(this instanceof UnionType)) { return new UnionType(arg, data) } debug('creating new union instance') var store if (Buffer.isBuffer(arg)) { debug('using passed-in Buffer instance to back the union', arg) assert(arg.length >= UnionType.size, 'Buffer instance must be at least ' + UnionType.size + ' bytes to back this untion type') store = arg arg = data } else { debug('creating new Buffer instance to back the union (size: %d)', UnionType.size) store = new Buffer(UnionType.size) } // set the backing Buffer store store.type = UnionType this['ref.buffer'] = store // initialise the union with values supplied if (arg) { //TODO: Sanity check - e.g. (Object.keys(arg).length == 1) for (var key in arg) { // hopefully hit the union setters this[key] = arg[key] } } UnionType._instanceCreated = true } // make instances inherit from `proto` UnionType.prototype = Object.create(proto, { constructor: { value: UnionType , enumerable: false , writable: true , configurable: true } }) UnionType.defineProperty = defineProperty UnionType.toString = toString UnionType.fields = {} // comply with ref's "type" interface UnionType.size = 0 UnionType.alignment = 0 UnionType.indirection = 1 UnionType.get = get UnionType.set = set // Read the fields list var arg = arguments[0] if (typeof arg === 'object') { Object.keys(arg).forEach(function (name) { var type = arg[name]; UnionType.defineProperty(name, type); }) } return UnionType }
javascript
{ "resource": "" }
q32571
defineProperty
train
function defineProperty (name, type) { debug('defining new union type field', name) // allow string types for convenience type = ref.coerceType(type) assert(!this._instanceCreated, 'an instance of this Union type has already ' + 'been created, cannot add new data members anymore') assert.equal('string', typeof name, 'expected a "string" field name') assert(type && /object|function/i.test(typeof type) && 'size' in type && 'indirection' in type , 'expected a "type" object describing the field type: "' + type + '"') assert(!(name in this.prototype), 'the field "' + name + '" already exists in this Union type') // define the getter/setter property Object.defineProperty(this.prototype, name, { enumerable: true , configurable: true , get: get , set: set }); var field = { type: type } this.fields[name] = field // calculate the new size and alignment recalc(this); function get () { debug('getting "%s" union field (length: %d)', name, type.size) return ref.get(this['ref.buffer'], 0, type) } function set (value) { debug('setting "%s" union field (length: %d)', name, type.size, value) return ref.set(this['ref.buffer'], 0, value, type) } }
javascript
{ "resource": "" }
q32572
createBot
train
function createBot() { var bot = function(platform, context, event, next) { context.platform = platform; bot.handle(context, event, next); }; mixin(bot, EventEmitter.prototype, false); mixin(bot, proto, false); bot.context = { __proto__: context, bot: bot }; bot.event = { __proto__: event, bot: bot }; bot.display_name = "bot"; // default, should be overwritten bot.init(); return bot; }
javascript
{ "resource": "" }
q32573
resultToContentItem
train
function resultToContentItem(esDoc) { var annoDoc = {_source : {}}; publishFields.forEach(function(f) { annoDoc._source[f] = esDoc[f]; }); return annoDoc; }
javascript
{ "resource": "" }
q32574
retrieveByURI
train
function retrieveByURI(uri, callback) { var query = { query: { term: { uri : uri } } }; getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, query, function(err, res) { if (!err && res && res.hits.total) { if (res.hits.total > 1) { // That would be weird. throw new Error('more than one result for', uri); } res = res.hits.hits[0]; } callback(err, res); }); }
javascript
{ "resource": "" }
q32575
deleteRecord
train
function deleteRecord(rType, idFun) { return function(item, callback) { GLOBAL.debug('deleting', item, rType); var tc = []; getEs().delete({ _type: rType, _id : encodeURIComponent(idFun(item))}, function(err, deleteRes) { callback(err, deleteRes); }); }; }
javascript
{ "resource": "" }
q32576
saveRecord
train
function saveRecord(rType, idFun) { return function(records, callback) { GLOBAL.debug('inserting', records.length, rType); if (!_.isArray(records)) { records = [records]; } var tc = []; records.forEach(function(d) { var meta = {_index : GLOBAL.config.ESEARCH._index, _type : rType}; if (idFun) { meta._id = idFun(d); } tc.push({ index : meta}); tc.push(d); }); getEs().bulk(tc, function (err, data) { callback(err, data, records); }); }; }
javascript
{ "resource": "" }
q32577
formQuery
train
function formQuery(params, callback) { params = params || { query: {}}; var query = formQueryLib.createFormQuery(params); var q = { _source : params.sourceFields || sourceFields, sort : params.sort || [ { "timestamp" : {"order" : "desc"}}, ], from: params.from || 0, size : querySize(params), query: query }; if (params.query && params.query.terms) { q.highlight = { fields: {"title" : {}, "text" : {}}}; } getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, q, function(err, res) { if (err) { utils.passingError(err, params); } else { res.from = params.from || 0; res.query = q; if (!res || res.hits.hits.length < 1) { GLOBAL.debug('NO HITS FOR', JSON.stringify(q, null, 2)); } } formQueryLib.filter(params.filters, res); callback(err, res); }); }
javascript
{ "resource": "" }
q32578
formCluster
train
function formCluster(params, callback) { var query = formQueryLib.createFormQuery(params); var q = { "search_request" : { _source : sourceFields.concat(['text']), sort : [ { "visitors.@timestamp" : {"order" : "desc"}}, ], size : querySize(params), query: query }, "query_hint": "*", "algorithm": "lingo", "field_mapping": { "title": ["_source.title"], "content": ["_source.text"], "url": ["_source.uri"] } }; doPost('/contentItem/_search_with_clusters', JSON.stringify(q), function(err, res) { if (err) { GLOBAL.error('formCluster, carrot2 extension not installed?', err, q); callback(err); return; } res.query = q; if (!res || res.hits.hits.length < 1) { GLOBAL.info('NO HITS FOR', JSON.stringify(q, null, 2)); } // FIXME don't send text callback(err, res); }); }
javascript
{ "resource": "" }
q32579
doPost
train
function doPost(path, data, callback) { var options = { host: GLOBAL.config.ESEARCH.server.host, port: GLOBAL.config.ESEARCH.server.port, path: GLOBAL.config.ESEARCH._index + path, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(data) } }; utils.doPostJson(options, data, callback); }
javascript
{ "resource": "" }
q32580
_getResolve
train
function _getResolve(obj) { if (!obj) return settings.get('resolver'); if (obj instanceof Resolver) return obj; if (obj.resolver) return obj.resolver; let pass = true; Resolver.resolveLike.forEach(property=>{pass &= (property in obj);}); if (pass) return obj; return new Resolver(obj); }
javascript
{ "resource": "" }
q32581
_getRoot
train
function _getRoot(obj) { return (getCallingDir(((obj && obj.basedir) ? obj.basedir : undefined)) || (obj?obj.basedir:undefined)); }
javascript
{ "resource": "" }
q32582
_loadModuleText
train
function _loadModuleText(target, source, sync=false) { const time = process.hrtime(); const loadEventEvent = new emitter.Load({target, source, sync}); const loadEvent = emitter.emit('load', loadEventEvent); const loaded = txtBuffer=>{ try { const loadedEvent = emitter.emit('loaded', new emitter.Loaded({ target, otherTarget: loadEventEvent.data.target, duration: process.hrtime(time), size: txtBuffer.byteLength, source, sync, data: txtBuffer })); return sync?txtBuffer:loadedEvent.then(()=>txtBuffer,loadError); } catch (error) { return loadError(error); } }; const loadError = error=>{ const _error = new emitter.Error({target, source, error}); emitter.emit('error', _error); if (!_error.ignore || (_error.ignore && isFunction(_error.ignore) && !_error.ignore())) throw error; }; if (!sync) return loadEvent.then(()=>readFile(loadEventEvent.data.target || target, fileCache).then(loaded, loadError), loadError); try { return loaded(readFileSync(loadEventEvent.data.target || target, fileCache)); } catch(error) { loadError(error); } }
javascript
{ "resource": "" }
q32583
_evalModuleText
train
function _evalModuleText(filename, content, userResolver, sync=true) { if (content === undefined) return; const ext = path.extname(filename); const config = _createModuleConfig(filename, content, _getResolve(userResolver)); let module = _runEval(config, settings.get(ext) || function(){}, userResolver.options || {}, sync); if ((!(config.resolver || {}).squashErrors) && fileCache.has(filename)) fileCache.delete(filename); return module; }
javascript
{ "resource": "" }
q32584
_runEval
train
function _runEval(config, parser, options, sync=true) { const time = process.hrtime(); const evalEvent = new emitter.Evaluate({ target:config.filename, source:(config.parent || {}).filename, moduleConfig: config, parserOptions: options, sync }); const evaluateEvent = emitter.emit('evaluate', evalEvent); function evaluated() { let module = ((evalEvent.data.module) ? evalEvent.data.module : parser.bind(settings)(config, options)); if (!module || !module.loaded) return module; const evaluatedEvent = emitter.emit('evaluated', new emitter.Evaluated({ target:module.filename, source:(module.parent || {}).filename, duration:process.hrtime(time), cacheSize: cache.size, exports: module.exports, sync })); try {filePaths.set(module.exports, module.filename);} catch(err) {} return sync?module:evaluatedEvent.then(()=>module); } return sync?evaluated():evaluateEvent.then(evaluated); }
javascript
{ "resource": "" }
q32585
_createModuleConfig
train
function _createModuleConfig(filename, content, userResolver) { return Object.assign({ content, filename, includeGlobals:true, syncRequire:_syncRequire(_syncRequire), resolveModulePath, resolveModulePathSync, basedir: path.dirname(filename), resolver: userResolver }, userResolver.export); }
javascript
{ "resource": "" }
q32586
_loadModuleSyncAsync
train
async function _loadModuleSyncAsync(filename, userResolver) { const localRequire = requireLike(_getResolve(userResolver).parent || settings.get('parent').filename); await promisify(setImmediate)(); return localRequire(filename); }
javascript
{ "resource": "" }
q32587
_parseRequireParams
train
function _parseRequireParams([userResolver, moduleId, callback], useSyncResolve=false) { if(isString(userResolver) || Array.isArray(userResolver)) { return [settings.get('resolver'), userResolver, moduleId, useSyncResolve]; }else { return [_getResolve(userResolver), moduleId, callback, useSyncResolve]; } }
javascript
{ "resource": "" }
q32588
syncRequire
train
function syncRequire(...params) { const [userResolver, moduleId] = _parseRequireParams(params); if (userResolver.isCoreModule(moduleId)) return getRequire()(moduleId); userResolver.basedir = userResolver.basedir || userResolver.dir; const filename = resolveModulePathSync(userResolver, moduleId, true); return _loadModuleSync(filename, userResolver); }
javascript
{ "resource": "" }
q32589
train
function (type, config) { // fail if we don't have a default for frost-page-title in the config if (!config.APP || !config.APP['frost-page-title'].defaultTitle) { return } // insert default page title if (type === 'page-title') { return config.APP['frost-page-title'].defaultTitle } }
javascript
{ "resource": "" }
q32590
contentsAsync
train
function contentsAsync(file, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (typeof cb !== 'function') { throw new TypeError('expected a callback function'); } if (!utils.isObject(file)) { cb(new TypeError('expected file to be an object')); return; } contentsSync(file, options); cb(null, file); }
javascript
{ "resource": "" }
q32591
contentsSync
train
function contentsSync(file, options) { if (!utils.isObject(file)) { throw new TypeError('expected file to be an object'); } try { // ideally we want to stat the real, initial filepath file.stat = fs.lstatSync(file.history[0]); } catch (err) { try { // if that doesn't work, try again file.stat = fs.lstatSync(file.path); } catch (err) { file.stat = new fs.Stats(); } } utils.syncContents(file, options); return file; }
javascript
{ "resource": "" }
q32592
retrieve
train
function retrieve(uri, callback) { var buffer = ''; http.get(uri, function(res) { res.on('data', function (chunk) { buffer += chunk; }); res.on('end', function() { callback(null, buffer); }); }).on('error', function(e) { callback(e); }); }
javascript
{ "resource": "" }
q32593
doPost
train
function doPost(options, data, callback) { var buffer = ''; var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { buffer += chunk; }); res.on('end', function(err) { callback(err, buffer); }); }).on('error', function(e) { callback(e); }); if (data && data.length) { req.write(data); } req.end(); }
javascript
{ "resource": "" }
q32594
checkextension
train
function checkextension(subword) { var checknext = true; if(findbehind(subword) && endshere(subword)) { wordindex = startindex(subword); prototype = getprototypeat(wordindex); curlcount = 0; prencount = 0; checknext = false; } return checknext; }
javascript
{ "resource": "" }
q32595
checksupercall
train
function checksupercall() { keywords.every(function(keyword) { if (findbehind(keyword)) { supercall = true; methodname = true; buffer = buffer.substr(0, startindex(keyword)); buffer += prototype; return false; } return true; }); }
javascript
{ "resource": "" }
q32596
endshere
train
function endshere(subword) { var nextindex = charindex + 1; return input.length === nextindex || !input[nextindex].match(METHODNAME); }
javascript
{ "resource": "" }
q32597
flush
train
function flush() { output += buffer; output += character; buffer = ''; supercall = false; methodname = false; superargs = false; }
javascript
{ "resource": "" }
q32598
morechars
train
function morechars() { switch (character) { case ';': flush(); break; case '=': case '\'': case '"': if(!supercall) { flush(); } break; default: if (supercall) { processsupercall(); } buffer += character; if (prototype && !supercall) { checksupercall(); } if(!prototype) { checkextensions(); } break; } }
javascript
{ "resource": "" }
q32599
reqeueBatch
train
function reqeueBatch(times,interval,batch) { async.retry({times: times, interval: interval}, function(cb) { syncBatch(batch,cb); }, function done(err) { if (err) { log.error("failed to sync message batch", {err: err, data: batch}); } }); }
javascript
{ "resource": "" }