_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q33300
init
train
function init() { // {{{2 /** * Class constructor * * @method constructor */ O.inherited(this)(); this.setMaxListeners(Consts.coreListeners); this.subjectState = this.SUBJECT_STATE.INIT; this.homeTimeOffset = 0; this.lastTid = 0; // {{{3 /** * Autoincemental part of last transaction id created in this shard and peer * * @property lastTid * @type Number */ this.lastEid = 0; // {{{3 /** * Autoincremental part of last entry id created in this shard and peer * * @property lastEid * @type Number */ this.cache = {}; // {{{3 /** * Object containing entries * * @property cache * @type Object */ // }}}3 return true; }
javascript
{ "resource": "" }
q33301
arrayIncludesWith
train
function arrayIncludesWith(array, value, comparator) { var index = -1, length = array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; }
javascript
{ "resource": "" }
q33302
arrayReduceRight
train
function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; }
javascript
{ "resource": "" }
q33303
baseExtremum
train
function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? current === current : comparator(current, computed))) { var computed = current, result = value; } } return result; }
javascript
{ "resource": "" }
q33304
stringSize
train
function stringSize(string) { if (!(string && reHasComplexSymbol.test(string))) { return string.length; } var result = reComplexSymbol.lastIndex = 0; while (reComplexSymbol.test(string)) { result++; } return result; }
javascript
{ "resource": "" }
q33305
cacheHas
train
function cacheHas(cache, value) { var map = cache.__data__; if (isKeyable(value)) { var data = map.__data__, hash = typeof value == 'string' ? data.string : data.hash; return hash[value] === HASH_UNDEFINED; } return map.has(value); }
javascript
{ "resource": "" }
q33306
baseHas
train
function baseHas(object, key) { // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, // that are composed entirely of index properties, return `false` for // `hasOwnProperty` checks of them. return hasOwnProperty.call(object, key) || typeof object == 'object' && key in object && getPrototypeOf(object) === null; }
javascript
{ "resource": "" }
q33307
basePick
train
function basePick(object, props) { object = Object(object); return arrayReduce(props, function (result, key) { if (key in object) { result[key] = object[key]; } return result; }, {}); }
javascript
{ "resource": "" }
q33308
basePullAll
train
function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; }
javascript
{ "resource": "" }
q33309
indexKeys
train
function indexKeys(object) { var length = object ? object.length : undefined; if (isLength(length) && (isArray(object) || isString(object) || isArguments(object))) { return baseTimes(length, String); } return null; }
javascript
{ "resource": "" }
q33310
mergeDefaults
train
function mergeDefaults(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { baseMerge(objValue, srcValue, undefined, mergeDefaults, stack.set(srcValue, objValue)); } return objValue; }
javascript
{ "resource": "" }
q33311
sample
train
function sample(collection) { var array = isArrayLike(collection) ? collection : values(collection), length = array.length; return length > 0 ? array[baseRandom(0, length - 1)] : undefined; }
javascript
{ "resource": "" }
q33312
size
train
function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { var result = collection.length; return result && isString(collection) ? stringSize(collection) : result; } return keys(collection).length; }
javascript
{ "resource": "" }
q33313
isTypedArray
train
function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; }
javascript
{ "resource": "" }
q33314
keys
train
function keys(object) { var isProto = isPrototype(object); if (!(isProto || isArrayLike(object))) { return baseKeys(object); } var indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; for (var key in object) { if (baseHas(object, key) && !(skipIndexes && (key == 'length' || isIndex(key, length))) && !(isProto && key == 'constructor')) { result.push(key); } } return result; }
javascript
{ "resource": "" }
q33315
parseInt
train
function parseInt(string, radix, guard) { // Chrome fails to trim leading <BOM> whitespace characters. // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } string = toString(string).replace(reTrim, ''); return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); }
javascript
{ "resource": "" }
q33316
words
train
function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord; } return string.match(pattern) || []; }
javascript
{ "resource": "" }
q33317
mixin
train
function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = isObject(options) && 'chain' in options ? options.chain : true, isFunc = isFunction(object); arrayEach(methodNames, function (methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function () { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; }
javascript
{ "resource": "" }
q33318
subtract
train
function subtract(minuend, subtrahend) { var result; if (minuend === undefined && subtrahend === undefined) { return 0; } if (minuend !== undefined) { result = minuend; } if (subtrahend !== undefined) { result = result === undefined ? subtrahend : result - subtrahend; } return result; }
javascript
{ "resource": "" }
q33319
onWindowLoad
train
function onWindowLoad() { self.isLoaded = true; onPluginStart(); if (windowLoadListenderAttached) { window.removeEventListener('load', onWindowLoad, false); } }
javascript
{ "resource": "" }
q33320
isCordova
train
function isCordova() { var isCordova = null; var idxIsCordova = window.location.search.indexOf('isCordova='); if (idxIsCordova >= 0) { var isCordova = window.location.search.substring(idxIsCordova + 10); if (isCordova.indexOf('&') >= 0) { isCordova = isCordova.substring(0, isCordova.indexOf('&')); } } return (isCordova == 'true'); }
javascript
{ "resource": "" }
q33321
createAccessors
train
function createAccessors(keys) { var fname; lodash.forEach(keys, function(key) { key.replace(/[^\w\d-]/g, ''); // get<key> fname = createFnName('get', key); self[fname] = function() { return getKey(ns + key); }; // set<key> fname = createFnName('set', key); self[fname] = function(value) { return setKey(ns + key, value); }; // remove<key> fname = createFnName('remove', key); self[fname] = function() { return removeKey(ns + key); }; }); }
javascript
{ "resource": "" }
q33322
timeout
train
function timeout(message) { $log.warn('Plugin client request timeout: ' + serialize(message)); var promiseIndex = lodash.findIndex(promises, function(promise) { return promise.id == message.header.id; }); if (promiseIndex >= 0) { var promise = lodash.pullAt(promises, promiseIndex); message.response = { statusCode: 408, statusText: 'REQUEST_TIMED_OUT', data: { message: 'Request timed out.' } } promise[0].onComplete(message); } else { $log.warn('Message request timed out but there is no promise to fulfill: ' + serialize(message)); } }
javascript
{ "resource": "" }
q33323
transport
train
function transport(message) { return { header: message.header, request: message.request, response: message.response } }
javascript
{ "resource": "" }
q33324
match
train
function match(mapEntry, request, route) { var keys = []; var m = pathToRegexpService.pathToRegexp(mapEntry.path, keys).exec(request.url); if (!m) { return false; } if (mapEntry.method != request.method) { return false; } route.params = {}; route.path = m[0]; route.handler = mapEntry.handler; // Assign url parameters to the request. for (var i = 1; i < m.length; i++) { var key = keys[i - 1]; var prop = key.name; var val = decodeParam(m[i]); if (val !== undefined || !(hasOwnProperty.call(route.params, prop))) { route.params[prop] = val; } } request.params = route.params; return true; }
javascript
{ "resource": "" }
q33325
setConfig
train
function setConfig(configs) { configProperties = platformConfigs; provider.platform[platformName] = {}; addConfig(configProperties, configProperties.platform[platformName]); createConfig(configProperties.platform[platformName], provider.platform[platformName], ''); }
javascript
{ "resource": "" }
q33326
train
function(app) { this._super(app); const vendorTree = this.treePaths.vendor; // Import the PubNub package and shim. app.import(`${vendorTree}/pubnub.js`); app.import(`${vendorTree}/shims/pubnub.js`, { exports: { PubNub: ['default'] } }); }
javascript
{ "resource": "" }
q33327
train
function(vendorTree) { const pubnubPath = path.dirname(require.resolve('pubnub/dist/web/pubnub.js')); const pubnubTree = new Funnel(pubnubPath, { src: 'pubnub.js', dest: './', annotation: 'Funnel (PubNub)' }); return mergeTrees([vendorTree, pubnubTree]); }
javascript
{ "resource": "" }
q33328
defaultProps
train
function defaultProps( target, overwrite ) { overwrite = overwrite || {}; for( var prop in overwrite ) { if( target.hasOwnProperty(prop) && _isValid( overwrite[ prop ] ) ) { target[ prop ] = overwrite[ prop ]; } } return target; }
javascript
{ "resource": "" }
q33329
train
function(action, weight) { if(weight===undefined) { weight=0; } this.tasks.push({ name: action, weight: weight}); }
javascript
{ "resource": "" }
q33330
train
function () { var tasks = this.tasks.sort(function(a,b) { if (a.weight < b.weight) { return -1; } if (a.weight > b.weight) { return 1; } return 0; }); var queue = []; for(var i=0;i<tasks.length; i+=1) { queue.push(tasks[i].name); } return queue; }
javascript
{ "resource": "" }
q33331
throwWapper
train
function throwWapper( callback ) { return function( resultSet ) { callback( resultSet.err || null, resultSet.err ? null : resultSet.result, ...resultSet.argument ); if ( resultSet.err ) { throw resultSet.err; } return resultSet; }; }
javascript
{ "resource": "" }
q33332
init
train
function init(schema, name) { // {{{2 /** * Kind constructor * * @param schema {Object|String} Schema containing the kind * @param name {String} Unique kind name within the schema * * @method constructor */ this.name = name; // {{{3 /** * Kind name unique within a schema * * @property name * @type String */ this.schema = typeof schema === 'string' ? // {{{3 O.data.schemas[schema] : schema ; /** * Schema to which the kind is assigned * * @property schema * @type Object */ if (! this.schema) { throw O.log.error('Missing schema', schema); } if (this.name in this.schema.kinds) { throw O.log.error(this.schema, 'Duplicit kind', this.name); } this.schema.kinds[this.name] = this; // }}}3 // O.callChain(this, 'init')(); // console.log('KIND INIT', this.schema.name, this.name); }
javascript
{ "resource": "" }
q33333
isException
train
function isException(url, exceptions) { if (exceptions && Array.isArray(exceptions)) { for (let i = 0; i < exceptions.length; i++) { if ((new RegExp(exceptions[i])).test(expressUtility.getBaseRoute(url))) { // Found exception return true; } } } return false; }
javascript
{ "resource": "" }
q33334
preCast
train
function preCast(value, parameterDefinition) { switch (parameterDefinition.type) { case 'array': { let values; switch (parameterDefinition.collectionFormat) { case 'ssv': values = value.split(' '); break; case 'tsv': values = value.split('\t'); break; case 'pipes': values = value.split('|'); break; case 'csv': default: values = value.split(','); break; } const result = values.map(v => { return preCast(v, parameterDefinition.items); }); return result; } case 'boolean': { if (typeof (value) == 'string') { return value.toLowerCase() === 'true' || value.toLowerCase() === 'false' ? value.toLowerCase() === 'true' : value; } else { return value; } } case 'integer': { const result = Number(value); return Number.isInteger(result) ? result : value; } case 'number': { const result = Number(value); return Number.isNaN(result) ? value : result; } case 'object': { try { return JSON.parse(value); } catch (ex) { return value; } } default: { return value; } } }
javascript
{ "resource": "" }
q33335
postCast
train
function postCast(value, parameterDefinition) { const type = parameterDefinition.type; const format = parameterDefinition.format; if (type === 'string' && (format === 'date' || format === 'date-time')) { return new Date(value); } else { return value; } }
javascript
{ "resource": "" }
q33336
gridMesh
train
function gridMesh(nx, ny, origin, dx, dy) { //Unpack default arguments origin = origin || [0,0] if(!dx || dx.length < origin.length) { dx = dup(origin.length) if(origin.length > 0) { dx[0] = 1 } } if(!dy || dy.length < origin.length) { dy = dup(origin.length) if(origin.length > 1) { dy[1] = 1 } } //Initialize cells var cells = [] , positions = dup([(nx+1) * (ny+1), origin.length]) , i, j, k, q, d = origin.length for(j=0; j<ny; ++j) { for(i=0; i<nx; ++i) { cells.push([ p(i,j,nx), p(i+1, j,nx), p(i, j+1,nx) ]) cells.push([ p(i+1,j,nx), p(i+1,j+1,nx), p(i,j+1,nx) ]) } } //Initialize positions for(j=0; j<=ny; ++j) { for(i=0; i<=nx; ++i) { q = positions[ p(i, j, nx) ] for(k=0; k<d; ++k) { q[k] = origin[k] + dx[k] * i + dy[k] * j } } } return { positions: positions, cells: cells } }
javascript
{ "resource": "" }
q33337
buildEntitiesLookup
train
function buildEntitiesLookup(items, radix) { var i, chr, entity, lookup = {}; if (items) { items = items.split(','); radix = radix || 10; // Build entities lookup table for (i = 0; i < items.length; i += 2) { chr = String.fromCharCode(parseInt(items[i], radix)); // Only add non base entities if (!baseEntities[chr]) { entity = '&' + items[i + 1] + ';'; lookup[chr] = entity; lookup[entity] = chr; } } return lookup; } }
javascript
{ "resource": "" }
q33338
train
function(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || chr; }); }
javascript
{ "resource": "" }
q33339
train
function(text, attr, entities) { entities = entities || namedEntities; return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || entities[chr] || chr; }); }
javascript
{ "resource": "" }
q33340
addValidChildren
train
function addValidChildren(validChildren) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; // Invalidate the schema cache if the schema is mutated mapCache[settings.schema] = null; validChildren && each(split(validChildren, ','), function(rule) { var parent, prefix, matches = childRuleRegExp.exec(rule); if (matches) { prefix = matches[1]; // Add/remove items from default parent = prefix ? children[matches[2]] : children[matches[2]] = { '#comment': {} }; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { '-' === prefix ? delete parent[child] : parent[child] = {}; }); } }); }
javascript
{ "resource": "" }
q33341
train
function(node) { var self = this; node.parent && node.remove(); self.insert(node, self); self.remove(); return self; }
javascript
{ "resource": "" }
q33342
train
function() { var i, l, selfAttrs, selfAttr, cloneAttrs, self = this, clone = new Node(self.name, self.type); // Clone element attributes if (selfAttrs = self.attributes) { cloneAttrs = []; cloneAttrs.map = {}; for (i = 0, l = selfAttrs.length; i < l; i++) { selfAttr = selfAttrs[i]; // Clone everything except id if ('id' !== selfAttr.name) { cloneAttrs[cloneAttrs.length] = { name: selfAttr.name, value: selfAttr.value }; cloneAttrs.map[selfAttr.name] = selfAttr.value; } } clone.attributes = cloneAttrs; } clone.value = self.value; clone.shortEnded = self.shortEnded; return clone; }
javascript
{ "resource": "" }
q33343
train
function(wrapper) { var self = this; self.parent.insert(wrapper, self); wrapper.append(self); return self; }
javascript
{ "resource": "" }
q33344
train
function() { var node, next, self = this; for (node = self.firstChild; node;) { next = node.next; self.insert(node, self, true); node = next; } self.remove(); }
javascript
{ "resource": "" }
q33345
train
function(name) { var node, self = this, collection = []; for (node = self.firstChild; node; node = walk(node, self)) { node.name === name && collection.push(node); } return collection; }
javascript
{ "resource": "" }
q33346
train
function() { var nodes, i, node, self = this; // Remove all children if (self.firstChild) { nodes = []; // Collect the children for (node = self.firstChild; node; node = walk(node, self)) { nodes.push(node); } // Remove the children i = nodes.length; while (i--) { node = nodes[i]; node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; } } self.firstChild = self.lastChild = null; return self; }
javascript
{ "resource": "" }
q33347
compress2
train
function compress2(target, a, b, c) { if (!canCompress(a)) { return; } if (!canCompress(b)) { return; } if (!canCompress(c)) { return; } // Compress styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c]; delete styles[a]; delete styles[b]; delete styles[c]; }
javascript
{ "resource": "" }
q33348
train
function(styles, elementName) { var name, value, css = ''; function serializeStyles(name) { var styleList, i, l, value; styleList = validStyles[name]; if (styleList) { for (i = 0, l = styleList.length; i < l; i++) { name = styleList[i]; value = styles[name]; value && (css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'); } } } function isValid(name, elementName) { var styleMap; styleMap = invalidStyles['*']; if (styleMap && styleMap[name]) { return false; } styleMap = invalidStyles[elementName]; if (styleMap && styleMap[name]) { return false; } return true; } // Serialize styles according to schema if (elementName && validStyles) { // Serialize global styles and element specific styles serializeStyles('*'); serializeStyles(elementName); } else { // Output the styles in the order they are inside the object for (name in styles) { value = styles[name]; !value || invalidStyles && !isValid(name, elementName) || (css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'); } } return css; }
javascript
{ "resource": "" }
q33349
find
train
function find(selector) { var arr = [], $ = this.air, slice = this.slice; this.each(function(el) { arr = arr.concat(slice.call($(selector, el).dom)); }); return $(arr); }
javascript
{ "resource": "" }
q33350
fv
train
function fv(vals, key) { if (!vals) return; vals.forEach(function(v) { if (v.key === key && vals[key] !== 'Not available') { return vals[key]; } }); }
javascript
{ "resource": "" }
q33351
hasMatchingJadeFileInPages
train
function hasMatchingJadeFileInPages(srcDir, url, pages, jadeOptions, callback) { if (typeof pages[url] === 'undefined') { // get the possible jade file path var extension = path.extname(url); var jadeFilePath; var htmlFilePath; if (extension === ".html" /* || extension === ".htm" */) { jadeFilePath = path.join(srcDir, url.substring(0, url.length - extension.length) + ".jade"); htmlFilePath = path.join(srcDir, url); } else { jadeFilePath = path.join(srcDir, url + "/index.jade"); htmlFilePath = path.join(srcDir, url + "/index.html"); } // see if the jadefile exsists fs.exists(jadeFilePath, function (exsits) { // store the result in a new HTML page pages[url] = new HTMLPage({ matchingJadeFilePath: (exsits)?jadeFilePath:null, htmlFilePath: htmlFilePath, jadeOptions: jadeOptions }); callback(!!pages[url].matchingJadeFilePath, pages[url]); }); } else { callback(!!pages[url].matchingJadeFilePath, pages[url]); } }
javascript
{ "resource": "" }
q33352
train
function( input, null_text ) { if ( input == null || input === undefined ) return null_text || ''; if ( typeof input === 'object' && Object.prototype.toString.call(input) === '[object Date]' ) return input.toDateString(); if ( input.toString ) return input.toString().replace(/\n/g, '<br />').replace(/''/g, "'"); return ''; }
javascript
{ "resource": "" }
q33353
train
function( name, value, options, checked ) { options = options || {}; if(checked) options.checked = "checked"; return this.input_field_tag(name, value, 'checkbox', options); }
javascript
{ "resource": "" }
q33354
range
train
function range(start, stop) { if (arguments.length <= 1) { stop = start || 0; start = 0; } var length = Math.max(stop - start, 0); var idx = 0; var arr = new Array(length); while(idx < length) { arr[idx++] = start; start += 1; } return arr; }
javascript
{ "resource": "" }
q33355
train
function(n) { // n is out of range, don't do anything if (n > this.props.numPages || n < 1) return; if (this.props.onClick) this.props.onClick(n); this.setState({ page: n }); }
javascript
{ "resource": "" }
q33356
archify
train
function archify (scripts, alpha) { let names = Object.keys(scripts) if (alpha) { names = names.sort() } return { label: `${names.length} scripts`, nodes: names.map(n => scripts[n]) } }
javascript
{ "resource": "" }
q33357
isLifeCycleScript
train
function isLifeCycleScript (prefix, name, scripts) { const re = new RegExp("^" + prefix) const root = name.slice(prefix.length) return Boolean(name.match(re) && (scripts[root] || BUILTINS.includes(root))) }
javascript
{ "resource": "" }
q33358
getRunAllScripts
train
function getRunAllScripts (cmd) { const re = RegExp("(?:npm-run-all" + RE_FLAGS + RE_NAMES + ")+", "gi") const cmds = getMatches(re, cmd).map(m => // clean spaces m.match.trim().split(" ").filter(x => x)) return unique(flatten(cmds)) }
javascript
{ "resource": "" }
q33359
onProcCallGet
train
function onProcCallGet(method, path, args) { // log('onProcCallGet('+JSON.stringify(arguments)); let pathSplit = path.split('/'); const serviceid = pathSplit.shift(); const propname = pathSplit.join('/'); const bInfo = (args.info === 'true'); if (serviceid == '') { // access 'admin/' => service list let re = {net: {}, server_status: {}}; if (bInfo) { re._info = {leaf: false}; } re.net = ipv4.getMACs(); re.id = {}; if (bInfo) { re.net._info = { leaf: false, doc: {short: 'Mac address of recognized network peers'}, }; re.server_status._info={ leaf: true, doc: {short: 'Check server memory/swap status'}, }; re.id._info = {leaf: true, doc:{short: 'Get unique ID of this PicoGW'}}; } return re; } if (propname == '') { // access 'admin/serviceid/' => property list let ret; switch (serviceid) { case 'net': const macs = ipv4.getMACs(); // log(JSON.stringify(macs)); ret = macs; for (const [mac, macinfo] of Object.entries(macs)) { if (bInfo) { ret[mac]._info = { leaf: true, doc: {short: (macinfo.ip || 'IP:null')}, }; } } return ret; case 'server_status': return new Promise((ac, rj)=>{ exec('vmstat', (err, stdout, stderr) => { if (err) { ac({error: 'Command execution failed.', result: err}); } else if (stdout !== null) { ac({success: true, result: stdout.split('\n')}); } else { ac({error: 'Command execution failed.', result: stderr}); } }); }); case 'id': return {id:exports.getMyID()}; } return {error: 'No such service:'+serviceid}; } switch (serviceid) { case 'net': const m = ipv4.getMACs()[propname]; if (m == undefined) { return {error: 'No such mac address:'+propname}; } return m; } return {error: 'No such service:'+serviceid}; }
javascript
{ "resource": "" }
q33360
listNetInterfaces
train
function listNetInterfaces() { return new Promise((ac, rj) => { exec('nmcli d', (err, stdout, stderr) => { const lines = stdout.split('\n'); if (err || lines.length<2) { rj({error: 'No network available.'}); return; } lines.shift(); // Correct visible APs should be listed let bWlanExist = false; const interfaces = []; lines.forEach((line)=>{ let sp = line.trim().split(/\s+/); if (sp.length < 4 || sp[0]=='lo') return; // Illegally formatted line if (sp[0].indexOf('wlan')==0) bWlanExist = true; interfaces.push(sp[0]); }); ac([interfaces, bWlanExist]); }); }); }
javascript
{ "resource": "" }
q33361
routeSet
train
async function routeSet(target, netInterface, rootPwd) { const connName = await searchConnNameFromNetworkInterface(netInterface); const prevRoutes = await searchPrevRoutes(target); if (prevRoutes.length == 1) { if (prevRoutes[0].connName === connName && prevRoutes[0].target === target && prevRoutes[0].gatewayIP === '0.0.0.0') { return; // no need to do anything } } await routeDelete(target, rootPwd); const cmds = [ ['nmcli', 'connection', 'modify', connName, '+ipv4.routes', `${target} 0.0.0.0`], ['nmcli', 'connection', 'down', connName], ['nmcli', 'connection', 'up', connName], ]; return await executeCommands(cmds, null, {sudo: true, password: rootPwd}); }
javascript
{ "resource": "" }
q33362
routeDelete
train
async function routeDelete(target, rootPwd) { const prevRoutes = await searchPrevRoutes(target); if (prevRoutes.length == 0) { return; // no need to do anything } const cmds = []; for (const prevRoute of prevRoutes) { cmds.push([ 'nmcli', 'connection', 'modify', prevRoute.connName, '-ipv4.routes', `${prevRoute.target} ${prevRoute.gatewayIP}`]); cmds.push(['nmcli', 'connection', 'down', prevRoute.connName]); cmds.push(['nmcli', 'connection', 'up', prevRoute.connName]); } return await executeCommands(cmds, null, {sudo: true, password: rootPwd}); }
javascript
{ "resource": "" }
q33363
listConnections
train
async function listConnections() { const connList = await executeCommand( ['nmcli', '-f', 'NAME,DEVICE', '-t', 'connection', 'show']); const ret = {}; connList.split('\n').map((l) => { return l.split(/:/); }).filter((ary) => { return ary[0] && ary[1]; }).forEach((ary) => { ret[ary[0]] = ary[1]; }); return ret; }
javascript
{ "resource": "" }
q33364
searchPrevRoutes
train
async function searchPrevRoutes(target) { const connNames = await listConnectionNames(); const ret = []; for (const connName of connNames) { const cmd = [ 'nmcli', '-f', 'IP4.ROUTE', 'connection', 'show', connName, ]; const output = await executeCommand(cmd); for (const line of output.split('\n')) { const exs = `dst\\s*=\\s*${target},\\snh\\s*=\\s*([\\d\.]+)`; const re = line.match(new RegExp(exs)); if (!re) { continue; } ret.push({ connName: connName, target: target, gatewayIP: re[1], }); } } return ret; }
javascript
{ "resource": "" }
q33365
searchConnNameFromIP
train
async function searchConnNameFromIP(ip) { // eslint-disable-line no-unused-vars const connNames = await listConnectionNames(); const gipnum = ipv4.convToNum(ip); for (const connName of connNames) { const cmd = [ 'nmcli', '-f', 'IP4.ADDRESS', 'connection', 'show', connName, ]; const output = await executeCommand(cmd); for (const line of output.split('\n')) { const re = line.match(/\s+([\d\.]+)\/([\d]+)/); if (!re) { continue; } const ip = ipv4.convToNum(re[1]); const mask = parseInt(re[2]); if ((ip & mask) == (gipnum & mask)) { return connName; } } } return null; }
javascript
{ "resource": "" }
q33366
searchConnNameFromNetworkInterface
train
async function searchConnNameFromNetworkInterface(netInterface) { // eslint-disable-line no-unused-vars const conns = await listConnections(); for (const [connName, nif] of Object.entries(conns)) { if (nif === netInterface) { return connName; } } return null; }
javascript
{ "resource": "" }
q33367
executeCommand
train
function executeCommand(cmd, option) { option = option || {}; return new Promise((ac, rj)=>{ let okMsg = ''; let erMsg=''; log('Exec:'+cmd.join(' ')); let child; if (option.sudo) { child = sudo(cmd, {password: option.password}); } else { child = spawn(cmd[0], cmd.slice(1)); } child.stdout.on('data', (dat)=>{ okMsg += dat.toString(); }); child.stderr.on('data', (dat)=>{ erMsg += dat.toString(); }); child.on('close', (code)=>{ if (code == 0) { ac(okMsg); } else { rj('Error in executing\n' +'$ '+cmd.join(' ')+'\n\n' + erMsg); } }); child.on('error', (err)=>{ rj(err); }); }); }
javascript
{ "resource": "" }
q33368
executeCommands
train
async function executeCommands(commands, ignoreErrorFunc, option) { const ret = []; for (const cmd of commands) { const r = await executeCommand(cmd, option).catch((e) => { if (ignoreErrorFunc && ignoreErrorFunc(cmd)) { // ignore error return ''; } throw e; }); ret.push(r); } return ret; }
javascript
{ "resource": "" }
q33369
search
train
function search(req, res, next) { res.__apiMethod = 'search'; buildQuery.call(this, req).exec(function (err, obj) { if (err) { var isCastError = (err.name === 'CastError') || (err.message && err.message[0] === '$') || (err.message === 'and needs an array') ; if (isCastError) return next( new ModelAPIError(400, err.message) ); return next(err); } res.json(obj); }); }
javascript
{ "resource": "" }
q33370
installModule
train
function installModule (module, modulesDir, callback) { let details = module.split('/'); let devModulePath = resolve(modulesDir, module); fs.access(resolve(modulesDir, module), err => { // skip next steps if module already exists if (!err || err.code !== 'ENOENT') { return callback(); } exec('git clone git@github.com:' + details[0] + '/' + details[1] + '.git ' + devModulePath, err => { if (err) { return callback(err); } exec('cd ' + devModulePath + '; npm i', err => { if (err) { return callback(err); } // create a symlink to the babelify presets // it is required in order for babelify to work fs.symlink(resolve(__dirname, '../../', 'babel-preset-es2015'), resolve(devModulePath, 'node_modules/babel-preset-es2015'), err => { if (err) { return callback(err); } callback(); }); }); }); }); }
javascript
{ "resource": "" }
q33371
setupSymlinks
train
function setupSymlinks (module, modulesDir, callback) { let details = module.split('/'); let modulePath = resolve(NODE_MODULES, details[1]); let devModulePath = resolve(modulesDir, module); rimraf(modulePath, err => { if (err) { return callback(err); } fs.symlink(devModulePath, modulePath, err => { if (err) { return callback(err); } callback(); }); }); }
javascript
{ "resource": "" }
q33372
watchModule
train
function watchModule (module, modulesDir) { const pathToModule = resolve(modulesDir, module); const pathToHandlers = resolve(HANDLER_BASE, module); modules[module] = { handlers: [] }; fs.readdir(pathToHandlers, (err, files) => { if (err) { return console.log(new Error('Failed to get handler files for module: ' + module)); } files.forEach(file => { if (file.length < 3 || file.indexOf('bundle.') === 0 || file.substr(file.length - 3) !== '.js') { return; } modules[module].handlers.push(pathToHandlers + '/' + file); }); let watchList = modules[module].handlers.concat([pathToModule]); let watcher = chokidar.watch(watchList, { ignored: /(^|[\/\\])\../, persistent: true }); watcher.on('change', (path, stats) => { // rebundle based on the type of the file if (modules[module].handlers.indexOf(path) < 0) { modules[module].handlers.forEach(handler => bundleHandler(pathToHandlers, module, handler.substr(handler.lastIndexOf('/') + 1))); } else { bundleHandler(pathToHandlers, module, path.substr(path.lastIndexOf('/') + 1)); } }); }); }
javascript
{ "resource": "" }
q33373
bundleHandler
train
function bundleHandler (pathToHandlers, module, file) { // only rebundle if js file changed if (file.length < 3 || file.indexOf('bundle.') === 0 || file.substr(file.length - 3) !== '.js') { return; } // only rebundle if handler was already bundled before fs.access(pathToHandlers + '/bundle.' + file, err => { if (err && err.code === 'ENOENT') { return ; } let fnIri = module + '/' + file.slice(0, -3); // remove the old bundle fs.unlink(pathToHandlers + '/bundle.' + file, err => { if (err) { console.log('Failed to delete old bundle for handler: ' + fnIri); return console.log(err); } // build the new bundle console.log('Bundle handler: ' + fnIri); runtime.bundle(fnIri, {}, (err) => { if (err) { console.log('Failed to bundle handler: ' + fnIri); return console.log(err); } console.log('Bundle done for handler: ' + fnIri); }); }); }); }
javascript
{ "resource": "" }
q33374
remoteRequest
train
function remoteRequest(moduleName, methodName, argsArr) { // TODO: Handle moduleName properly // TODO: Better ID generation const id = Math.floor(Math.random() * 10000000); const serializedRequest = serializer.request(id, methodName, argsArr); return sendRequest(serializedRequest).then((res) => { const response = serializer.deserialize(res.text); if (response.type === 'success') { return response.payload.result; } else if (response.type === 'error') { throw response.payload.error; } else { // TODO: Better error handling throw response; } }); }
javascript
{ "resource": "" }
q33375
train
function () { var self = this; base._create.apply(self, arguments); if (self.options.actions.listAction) { self._adaptListActionforAbp(); } if (self.options.actions.createAction) { self._adaptCreateActionforAbp(); } if (self.options.actions.updateAction) { self._adaptUpdateActionforAbp(); } if (self.options.actions.deleteAction) { self._adaptDeleteActionforAbp(); } }
javascript
{ "resource": "" }
q33376
train
function () { var self = this; var originalListAction = self.options.actions.listAction; self.options.actions.listAction = function (postData, jtParams) { return $.Deferred(function ($dfd) { var input = $.extend({}, postData, { skipCount: jtParams.jtStartIndex, maxResultCount: jtParams.jtPageSize, sorting: jtParams.jtSorting }); originalListAction.method(input) .done(function (result) { $dfd.resolve({ "Result": "OK", "Records": result.items || result[originalListAction.recordsField], "TotalRecordCount": result.totalCount, originalResult: result }); }) .fail(function (error) { self._handlerForFailOnAbpRequest($dfd, error); }); }); }; }
javascript
{ "resource": "" }
q33377
train
function () { var self = this; var originalCreateAction = self.options.actions.createAction; self.options.actions.createAction = function (postData) { return $.Deferred(function ($dfd) { var input = $.extend({}, postData); originalCreateAction.method(input) .done(function (result) { $dfd.resolve({ "Result": "OK", "Record": originalCreateAction.recordField ? result[originalCreateAction.recordField] : result, originalResult: result }); }) .fail(function (error) { self._handlerForFailOnAbpRequest($dfd, error); }); }); }; }
javascript
{ "resource": "" }
q33378
train
function () { var self = this; var originalUpdateAction = self.options.actions.updateAction; self.options.actions.updateAction = function (postData) { return $.Deferred(function ($dfd) { var input = $.extend({}, postData); originalUpdateAction.method(input) .done(function (result) { var jtableResult = { "Result": "OK", originalResult: result }; if (originalUpdateAction.returnsRecord) { if (originalUpdateAction.recordField) { jtableResult.Record = result[originalUpdateAction.recordField]; } else { jtableResult.Record = result; } } $dfd.resolve(jtableResult); }) .fail(function (error) { self._handlerForFailOnAbpRequest($dfd, error); }); }); }; }
javascript
{ "resource": "" }
q33379
train
function () { var self = this; var originalDeleteAction = self.options.actions.deleteAction; self.options.actions.deleteAction = function (postData) { return $.Deferred(function ($dfd) { var input = $.extend({}, postData); originalDeleteAction.method(input) .done(function (result) { $dfd.resolve({ "Result": "OK", originalResult: result }); }) .fail(function (error) { self._handlerForFailOnAbpRequest($dfd, error); }); }); }; }
javascript
{ "resource": "" }
q33380
options
train
function options(req, res) { res.__apiMethod = 'options'; res.status(200); res.json(this.urls()); }
javascript
{ "resource": "" }
q33381
MongoCache
train
function MongoCache(options) { options = options || {}; var url = options.url || 'http://localhost/openam-agent', expireAfterSeconds = options.expireAfterSeconds || 60, collectionName = options.collectionName || 'agentcache'; this.collection = mongodb.MongoClient.connectAsync(url).then(function (db) { var collection = db.collection(collectionName); return collection.createIndex('timestamp', {expireAfterSeconds: expireAfterSeconds}).then(function () { return collection; }); }); }
javascript
{ "resource": "" }
q33382
append
train
function append() { var i, l = this.length, el, args = this.slice.call(arguments); function it(node, index) { // content elements to insert el.each(function(ins) { ins = (index < (l - 1)) ? ins.cloneNode(true) : ins; node.appendChild(ins); }); } for(i = 0;i < args.length;i++) { // wrap content el = this.air(args[i]); // matched parent elements (targets) this.each(it); } return this; }
javascript
{ "resource": "" }
q33383
rotate
train
function rotate(cb) { var retryCount var newName if (self.writable && didWrite && !rotating) { // we wrote something to the log, and are not in process of rotating rotating = true retryCount = 0 newName = getRotatedName() fs.stat(newName, doesNewNameExist) // see if the new filename already exist } else end() function doesNewNameExist(err, stat) { if (err instanceof Error && err.code === 'ENOENT') { // we can use newName! buffer = [] // start logging to memory instead of the stream closeStream('Log rotated to: ' + path.basename(newName) + '\n', renameLog) } else { if (!err) { // newFile already exists if (++retryCount < maxRetry) setTimeout(retry, rotateAttemptWait) else end(new Error('Renamed logfile exists')) } else end(err) // some other error } } function retry() { //** stream.write('retry') if (self.writable) { newName = getRotatedName() fs.stat(newName, doesNewNameExist) // see if the new filename already exist } else end() } function renameLog(err) { // we are in buffer mode, closed stream if (self.writable && !err) fs.rename(self.filename, newName, createWriteStream) else flushBuffer(err) } function createWriteStream(err) { if (self.writable && !err) if (!(err = openStream())) while (buffer.length && self.writable) { stream.write(buffer.shift()) } flushBuffer(err) } function flushBuffer(err) { //** stream.write('flushBuffer') buffer = null rotating = false end(err) } function end(err) { if (!err) { if (cb) cb() } else { emitError(err) if (cb) cb(err) } } }
javascript
{ "resource": "" }
q33384
resolve
train
function resolve(obj, propstr, default_val){ // special case, no test and assignment needed for optional default_val; we don't mind if default_val is undefined! // note: eval called on propstr! var rv; if(obj === undefined){ rv = default_val; } else if(obj.hasOwnProperty(propstr)) { rv = obj[propstr]; } else { //treat [] as index 0 propstr = propstr.replace(/\[\]/g,'[0]'); // try drilling down complex propstr like 'foo.bar.quux' or array. try { //eval like this to enable "with {}" in strict mode (for babel compatibility) rv = (new Function( "with(this) { return " + propstr + "}")).call(obj); } catch(e) { rv = undefined; } } return (rv === undefined ) ? default_val : rv; }
javascript
{ "resource": "" }
q33385
loadMonaco
train
function loadMonaco(monaco) { var deps = [ 'vs/editor/editor.main.nls', 'vs/editor/editor.main' ]; charto.monaco = monaco; // Monaco loader sets exports, then gets confused by them. exports = void 0; return(new Promise(function(resolve, reject) { monaco.require(deps, resolve); })); }
javascript
{ "resource": "" }
q33386
updateCollected
train
function updateCollected(err, result) { if (typeof result !== 'object') { collection.err = collection.err || new Error('Invalid acrhitect plugin format'); return; } collection.err = collection.err || err; if (!collection.loaded) { collection.result = result; collection.loaded = true; return; } for (var i in result) { if (result.hasOwnProperty(i)) { if (collection.result.hasOwnProperty(i)) { collection.err = collection.err || new Error('Service overloading not supported: ' + i); return; } collection.result[i] = result[i]; } } }
javascript
{ "resource": "" }
q33387
_resolvePackageSync
train
function _resolvePackageSync(base, relativePath) { var packageJsonPath; var packagePath; // try to fetch node package try { packageJsonPath = _resolvePackagePathSync(base, PATH.join(relativePath, 'package.json')); packagePath = dirname(packageJsonPath); } catch (err) { if (err.code !== 'ENOENT') { throw err; } // try to resolve package itself packagePath = _resolvePackagePathSync(base, relativePath); } // compiling resolved metadata var packageJson = packageJsonPath && require(packageJsonPath) || {}; var metadata = packageJson.pym || {}; metadata.interface = metadata.interface || packageJson.pym ? 'pym' : packageJson.plugin ? 'architect' : // what 'bout amd? 'commonjs'; // load package itself var packageMainPath; var nodeModule; switch (metadata.interface) { case 'pym': packageMainPath = PATH.join(packagePath, metadata.main || packageJson.main); nodeModule = require(packageMainPath); metadata.provides = metadata.provides || nodeModule.provides || []; metadata.consumes = metadata.consumes || nodeModule.consumes || []; metadata.packagePath = packagePath; metadata.exports = nodeModule; break; case 'architect': var pluginData = packageJson.plugin || {}; nodeModule = require(packagePath); metadata.provides = pluginData.provides || nodeModule.provides || []; metadata.consumes = pluginData.consumes || nodeModule.consumes || []; metadata.packagePath = packagePath; metadata.exports = _wrapToArchitect(nodeModule, metadata); break; default: throw new Error('Unsupported package format ' + relativePath); } return metadata; }
javascript
{ "resource": "" }
q33388
_resolvePackagePathSync
train
function _resolvePackagePathSync(base, relativePath) { var originalBase = base; if (!(base in packagePathCache)) { packagePathCache[base] = {}; } var cache = packagePathCache[base]; if (relativePath in cache) { return cache[relativePath]; } var packagePath; if (relativePath[0] === '.' || relativePath[0] === '/') { packagePath = resolve(base, relativePath); if (existsSync(packagePath)) { packagePath = realpathSync(packagePath); cache[relativePath] = packagePath; return packagePath; } } else { var newBase; while (base) { packagePath = resolve(base, 'node_modules', relativePath); if (existsSync(packagePath)) { packagePath = realpathSync(packagePath); cache[relativePath] = packagePath; return packagePath; } newBase = resolve(base, '..'); if (base === newBase) { break; } base = newBase; } } var err = new Error('Can\'t find "' + relativePath + '" relative to "' + originalBase + '"'); err.code = 'ENOENT'; throw err; }
javascript
{ "resource": "" }
q33389
_$updateRecord
train
function _$updateRecord(name, obj, mode = 'shallow', lockedKeys = [], protectedKeys = []) { if (!Object.keys(updateModes).includes(mode)) throw new TypeError('Unsupported mode'); lockedKeys.push(this.datasetRecordIdKey); if (mode === 'shallow') return this.record._$updateRecordShallowP(name, obj, lockedKeys); if (mode === 'overwrite') { return this.record._$updateRecordOverwriteP(name, obj, lockedKeys, protectedKeys); } if (mode === 'removeKeys') { return this.record._$updateRecordRemoveKeysP(name, obj, lockedKeys, protectedKeys); } return this.record._$updateRecordDeepP(name, obj, mode, lockedKeys); }
javascript
{ "resource": "" }
q33390
train
function(stream, post) { this._credentials = []; this._status = {}; this._modules = { stream: stream || Stream, post: post || Post }; }
javascript
{ "resource": "" }
q33391
QueryConfig
train
function QueryConfig (req, res, config) { var sort = req.query.sort var order = req.query.order var select = req.query.select var skip = req.query.skip var limit = req.query.limit var page = req.query.page var perPage = config.perPage || 10 var idAttribute = config.idParam ? req.params[config.idParam] : req.params.idAttribute var query = config.query || {} var updateRef = config.updateRef var conditions = query.conditions || {} var options = query.options || {} var fields = query.fields || '' var subDoc = config.subDoc var data = req.body // sort order if (sort && (order === 'desc' || order === 'descending' || order === '-1')) { options.sort = '-' + sort } if (sort && (order === 'asc' || order === 'ascending' || order === '1')) { options.sort = sort } if (skip) { options.skip = skip } if (limit) { options.limit = limit } // pagination if (page) { options.skip = page * perPage options.limit = perPage } // to find unique record for update, remove and findOne if (idAttribute) { conditions[config.idAttribute || '_id'] = idAttribute } while (subDoc) { idAttribute = subDoc.idParam ? req.params[subDoc.idParam] : req.params.idAttribute if (idAttribute) { subDoc.conditions = {} subDoc.conditions[subDoc.idAttribute] = idAttribute } subDoc = subDoc.subDoc } if (select) { fields = select.replace(/,/g, ' ') } return { conditions: conditions, subDoc: config.subDoc, fields: fields, options: options, data: data, callback: callback(req, res, updateRef) } }
javascript
{ "resource": "" }
q33392
train
function (color, angle) { var hsl, color0, color2; if (!angle) { angle = 30; } hsl = ColorHelper.rgbToHSL(color); hsl[0] = (hsl[0] + angle) % 360; color0 = ColorHelper.hslToHexColor(hsl); color0 = ColorHelper.darken(color0, 8); color0 = ColorHelper.saturate(color0, -6); hsl = ColorHelper.rgbToHSL(color); hsl[0] = (hsl[0] - angle + 360) % 360; color2 = ColorHelper.hslToHexColor(hsl); return [color0, color, color2]; }
javascript
{ "resource": "" }
q33393
train
function (startColor, endColor, count) { var lightness, hsl = ColorHelper.rgbToHSL(startColor); if (count === undefined) { count = endColor; lightness = hsl[2] - 20 * count; if (lightness < 0) { lightness = 100 - hsl[2]; } endColor = ColorHelper.hslToHexColor([hsl[0], hsl[1], lightness]); } return ColorFactory.interpolate(startColor, endColor, count); }
javascript
{ "resource": "" }
q33394
oncurlyclose
train
function oncurlyclose(state, curly, suber) { curly.count--; if (suber.protostring && curly.count === curly.protocount) { suber.protostring = null; } }
javascript
{ "resource": "" }
q33395
get
train
function get(cache, keys) { if (keys.length === 0) { return cache.get(sentinel); } const [key, ...restKeys] = keys; const nestedCache = cache.get(key); if (!nestedCache) { return undefined; } return get(nestedCache, restKeys); }
javascript
{ "resource": "" }
q33396
DataManager
train
function DataManager(hoist, type, bucket) { this.type = type; this.hoist = hoist; this.url = hoist._configs.data + "/" + type; this.bucket = bucket; }
javascript
{ "resource": "" }
q33397
iterateKeys
train
function iterateKeys(keys) { async.forEach(keys, readKey, function (err) { return err ? callback(err) : callback(null, keyinfo); }); }
javascript
{ "resource": "" }
q33398
createDirs
train
function createDirs(next) { if (!options.files || !options.files.length) { return next(); } self.ssh({ keys: options.keys, server: options.server, tunnel: options.tunnel, remoteUser: options.remoteUser, commands: ['mkdir -p ' + options.files.map(function (file) { return path.dirname(file.target); }).join(' ')] }).on('error', function (err) { if (!hasErr) { hasErr = true; next(err); } }).on('complete', function () { if (!hasErr) { next(); } }); }
javascript
{ "resource": "" }
q33399
uploadFiles
train
function uploadFiles(next) { return options.files && options.files.length ? async.forEachSeries(options.files, uploadFile, next) : next(); }
javascript
{ "resource": "" }