_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q600
customRenderFn
train
function customRenderFn(renderFn) { // The loader context. var _this = this return function (engine, template, locals, options) {
javascript
{ "resource": "" }
q601
render
train
function render(engine, str, locals, engineOptions) { try { var output = engine.render(engine.engine, str, locals, engineOptions) } catch(e) { throw new Error(
javascript
{ "resource": "" }
q602
init
train
function init(type) { return function(params) { if (!params) { params = {}; } var settings = { proxyUrl: params.proxyUrl || defaults.proxyUrl, channel: params.channel || defaults.channel, keepalive: parseFalsey(params.keepalive, defaults.keepalive), port: params.port || defaults.port, log: params.log || defaults.log, tcp: parseFalsey(params.tcp, defaults.tcp), udp4: parseFalsey(params.udp4, defaults.udp4), socketio: parseFalsey(params.socketio, defaults.socketio), onlyOneControllerPerChannel: parseFalsey(params.onlyOneControllerPerChannel, defaults.onlyOneControllerPerChannel), onlyOneToyPerChannel: parseFalsey(params.onlyOneToyPerChannel, defaults.onlyOneToyPerChannel), allowObservers: parseFalsey(params.allowObservers, defaults.allowObservers),
javascript
{ "resource": "" }
q603
train
function (path, errorMessage) { if (!shell.test('-e', path)) { shell.echo('Error: ' +
javascript
{ "resource": "" }
q604
merge
train
function merge(dest) { if (dest) { Array.prototype.slice.call(arguments, 1).forEach(function(arg) { Object.keys(arg).forEach(function(key) {
javascript
{ "resource": "" }
q605
calculateClockOffset
train
function calculateClockOffset() { const start = Date.now(); let cur = start; // Limit the iterations, just in case we're running in an environment where Date.now() has been mocked and is // constant. for (let i = 0; i < 1e6 && cur === start; i++) { cur = Date.now(); } // At this point |cur| "just" became equal to the next millisecond -- the unseen digits after |cur| are approximately
javascript
{ "resource": "" }
q606
train
function (cb) { // check if we have a custom index file set if (settings.index) { // generate the real index file path var indexFile = process.cwd() + '/' + settings.index; // check if the file exists, throw an error otherwise if (!grunt.file.exists(indexFile)) { grunt.log.error('Index file: "' + indexFile + '" not found'); cb('Index file: "' + indexFile + '" not found'); return; } // load the file contents sourceFile = grunt.file.read(indexFile); } // modify the sourcefile css according to the settings var css = settings.css.map(function (file) {
javascript
{ "resource": "" }
q607
train
function (patternFolder, patterns, cb) { getSourceFile(function generatePatterns(content) { patterns.forEach(function (file) { content += '<hr/>'; content += '<div class="pattern"><div class="display">'; content += file.content; content += '</div><div class="source"><textarea rows="6" cols="30">'; content += simpleEscaper(file.content); content += '</textarea>';
javascript
{ "resource": "" }
q608
train
function (patternFolder, files, cb) { var file, patterns = []; files.forEach(function readPattern(pattern) { file = {filename: pattern}; file.content = grunt.file.read(patternFolder + '/' + file.filename); patterns.push(file); });
javascript
{ "resource": "" }
q609
train
function (patternFolder, cb) { // read pattern folder fs.readdir(patternFolder, function (err, contents) { // check for errors if (err !== null && err.code === 'ENOENT') { grunt.log.error('Cannot find patterns folder:', patternFolder); cb('Cannot find patterns folder: ' + patternFolder); return; } //
javascript
{ "resource": "" }
q610
train
function (item) { let x; switch (item.type) { case Type.STRING: case Type.NUMBER: case Type.BOOLEAN: case Type.UNDEFINED: return item.value; case Type.ARRAY: x = []; item.value.forEach(function (e) { let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']')); x[parseInt(key, 10)] = _fromPersistable(e); }); return x;
javascript
{ "resource": "" }
q611
Persistable
train
function Persistable (key, value) { const __self = this; __self.key = key; // Set value and type of object. if (value === undefined || value === null) { __self.value = undefined; __self.type = typeof undefined; } else if (value instanceof Array) { __self.value = []; value.forEach(function (e, i) { __self.value.push(new Persistable(key + '[' + i + ']', e)); }); __self.type = Type.ARRAY; } else { switch (typeof value) { case Type.STRING: case Type.NUMBER: case Type.BOOLEAN: __self.value = value; __self.type = typeof value; break; case Type.OBJECT:
javascript
{ "resource": "" }
q612
train
function (item) { item.value.sort(function (a, b) { if (a.key < b.key) { return -1; } /* istanbul ignore next */ // Below line exists only for the sake of completeness. Generally the array will // always
javascript
{ "resource": "" }
q613
addTracingToResolvers
train
function addTracingToResolvers(schema) { // XXX this is a hacky way of making sure that the schema only gets decorated // with tracer once. if (schema._apolloTracerApplied) { // console.log('Tracing already added to resolve functions. Not adding again.'); return;
javascript
{ "resource": "" }
q614
instrumentSchemaForExpressGraphQL
train
function instrumentSchemaForExpressGraphQL(schema) { addTracingToResolvers(schema); addSchemaLevelResolveFunction(schema, (root, args, ctx, info) => { const operation = print(info.operation); const fragments = Object.keys(info.fragments).map(k => print(info.fragments[k])).join('\n');
javascript
{ "resource": "" }
q615
indexOfNode
train
function indexOfNode (host, node) { const chs = host.childNodes; const chsLen = chs.length; for (let a = 0; a < chsLen; a++) {
javascript
{ "resource": "" }
q616
registerNode
train
function registerNode (host, node, insertBefore, func) { const index = indexOfNode(host, insertBefore); eachNodeOrFragmentNodes(node, (eachNode, eachIndex) => { func(eachNode, eachIndex); if (canPatchNativeAccessors) { nodeToParentNodeMap.set(eachNode, host); } else { staticProp(eachNode, 'parentNode', host); } // When childNodes is artificial, do manual house keeping.
javascript
{ "resource": "" }
q617
addNodeToSlot
train
function addNodeToSlot (slot, node, insertBefore) { const isInDefaultMode = slot.assignedNodes().length === 0; registerNode(slot, node, insertBefore, eachNode => { if (isInDefaultMode) {
javascript
{ "resource": "" }
q618
train
function () { if (!window.ove.context.isInitialized) { log.debug('Requesting an update of state configuration from server');
javascript
{ "resource": "" }
q619
train
function (req, res) { let sectionId = req.query.oveSectionId; if (sectionId === undefined) { log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME); Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.spaces)); } else if (!server.state.get('sections[' + sectionId + ']'))
javascript
{ "resource": "" }
q620
train
function () { if (Utils.isNullOrEmpty(server.spaceGeometries) && !Utils.isNullOrEmpty(server.spaces)) { Object.keys(server.spaces).forEach(function (s) { const geometry = { w: Number.MIN_VALUE, h: Number.MIN_VALUE }; server.spaces[s].forEach(function (e) { geometry.w = Math.max(e.x + e.w, geometry.w); geometry.h = Math.max(e.y + e.h, geometry.h);
javascript
{ "resource": "" }
q621
train
function (req, res) { const spaceName = req.params.name; const geometry = _getSpaceGeometries()[spaceName]; if (Utils.isNullOrEmpty(geometry)) { log.error('Invalid Space', 'name:', spaceName); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid space' })); } else {
javascript
{ "resource": "" }
q622
train
function (sectionId) { let section = server.state.get('sections[' + sectionId + ']'); if (section.app && section.app.url) { log.debug('Flushing application at URL:', section.app.url); request.post(section.app.url + '/instances/' + sectionId + '/flush', _handleRequestError); } server.state.get('groups').forEach(function (e, groupId) { if (e.includes(parseInt(sectionId, 10))) { // The outcome of this operation is logged within the internal utility method if (e.length === 1) { _deleteGroupById(groupId); } else { e.splice(e.indexOf(parseInt(sectionId, 10)), 1); server.state.set('groups[' + groupId + ']', e); }
javascript
{ "resource": "" }
q623
train
function (req, res) { _updateSections({
javascript
{ "resource": "" }
q624
train
function (req, res) { let sectionId = req.params.id; let s = server.state.get('sections[' + sectionId + ']'); if (Utils.isNullOrEmpty(s)) { log.debug('Unable to read configuration for section id:', sectionId); Utils.sendEmptySuccess(res); return; } let section = { id: parseInt(sectionId, 10), x: s.x, y: s.y, w: s.w, h: s.h, space: Object.keys(s.spaces)[0] }; const app = s.app;
javascript
{ "resource": "" }
q625
train
function (req, res) { let sectionId = req.params.id; if (Utils.isNullOrEmpty(server.state.get('sections[' + sectionId + ']'))) { log.error('Invalid Section Id:', sectionId); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid section id' })); } else { _deleteSectionById(sectionId);
javascript
{ "resource": "" }
q626
train
function (groupId, operation, req, res) { const validateSections = function (group) { let valid = true; const sections = server.state.get('sections'); group.forEach(function (e) { if (Utils.isNullOrEmpty(sections[e])) { valid = false; } }); return valid; }; if (!req.body || !req.body.length || !validateSections(req.body)) {
javascript
{ "resource": "" }
q627
train
function (req, res) { let groupId = req.params.id; if (Utils.isNullOrEmpty(server.state.get('groups[' + groupId + ']'))) { log.error('Invalid Group Id:', groupId); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({
javascript
{ "resource": "" }
q628
train
function (groupId) { server.state.set('groups[' + groupId + ']', []); let hasNonEmptyGroups = false; server.state.get('groups').forEach(function (e) { if (!Utils.isNullOrEmpty(e)) {
javascript
{ "resource": "" }
q629
train
function (peerURL) { let host = peerURL; /* istanbul ignore else */ // The host should never be null, empty or undefined based on how this method is used. // This check is an additional precaution. if (host) { if (host.indexOf('//') >= 0) {
javascript
{ "resource": "" }
q630
focusAtEnd
train
function focusAtEnd(change) { const { value } = change; const document = value.document;
javascript
{ "resource": "" }
q631
ContentAuth
train
function ContentAuth (pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf) { if (!(this instanceof ContentAuth)) { return new ContentAuth(pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf)
javascript
{ "resource": "" }
q632
stackChain
train
function stackChain() { this.extend = new TraceModifier(); this.filter =
javascript
{ "resource": "" }
q633
BriToPbn
train
function BriToPbn(opts) { if (!(this instanceof BriToPbn)) return new BriToPbn(opts);
javascript
{ "resource": "" }
q634
DgeToPbn
train
function DgeToPbn(opts) { if (!(this instanceof DgeToPbn)) return new DgeToPbn(opts);
javascript
{ "resource": "" }
q635
train
function (manifest, file, callback) { generate(file.src, options, function (err, sriData) { // Make relative if a cwd is specified if (file.orig && file.orig.cwd) {
javascript
{ "resource": "" }
q636
train
function (err, manifest) { if (err) { // Error generating SRI hashes grunt.log.error("Error loading resource: " + err); return done(false); }
javascript
{ "resource": "" }
q637
DupToPbn
train
function DupToPbn(opts) { if (!(this instanceof DupToPbn)) return new DupToPbn(opts);
javascript
{ "resource": "" }
q638
TrailingBlock
train
function TrailingBlock(opts) { opts = opts || {}; opts.type = opts.type || 'paragraph'; opts.match = opts.match || (node => node.type === opts.type); return { validateNode: (node) => { if (node.object !== 'document') { return undefined; } const lastNode = node.nodes.last(); if (lastNode && opts.match(lastNode)) { return undefined; } const lastIndex = node.nodes.count();
javascript
{ "resource": "" }
q639
relative
train
function relative(a, b, stat) { if (typeof a !== 'string') { throw new TypeError('relative expects a string.'); } if (a == '' && !b) return a; var len = arguments.length; if (len === 1) { b = a; a = process.cwd(); stat = null; } if (len === 2 && typeof b === 'boolean') { b = a; a = process.cwd(); stat = true; } if (len === 2 && typeof b === 'object') { stat = b; b = a; a = process.cwd(); } var origB = b; // see if a slash exists before normalizing var slashA = endsWith(a, '/'); var slashB = endsWith(b, '/'); a = unixify(a); b = unixify(b); // if `a` had a slash, add it back if (slashA) { a = a + '/'; } if
javascript
{ "resource": "" }
q640
isDir
train
function isDir(fp, stat) { if (endsWith(fp, '/')) { return true; } if (stat === null) { // try to get the directory info if it hasn't been done yet // to ensure directories containing dots are
javascript
{ "resource": "" }
q641
isFile
train
function isFile(fp, stat) { if (stat === true)
javascript
{ "resource": "" }
q642
getIntervalRunner
train
function getIntervalRunner (context, actions) { return function itervalRunner () { var i = 0; var len = actions.length; var actionData = null; for (; i < len; i += 1) {
javascript
{ "resource": "" }
q643
train
function (uuid, action, params, interval) { var actions = null; if (typeof uuid !== 'string' || typeof action !== 'function') { return false; } if (interval === undefined) { if (typeof params === 'number') { interval = params; params = null; } else { interval = 100; } } if (uuidMap[uuid]) { return false; } if (!intervalsMap[interval]) { actions = []; intervalsMap[interval] = { id: setInterval(getIntervalRunner(this.context, actions), interval), interval: interval, actions: actions }; }
javascript
{ "resource": "" }
q644
train
function () { var i = 0; var len = 0; var actionData = null; if (!(this.constructor.periodicActions instanceof Array)) { return; } len = this.constructor.periodicActions.length; for (; i < len; i += 1) {
javascript
{ "resource": "" }
q645
train
function (uuid) { var intervalData = null; var i = 0; var len = 0; var actionData = null; if (typeof uuid !== 'string') { return false; } intervalData = uuidMap[uuid]; if (!intervalData) { return false; } uuidMap[uuid] = null; len = intervalData.actions.length; for (; i < len; i += 1) { actionData = intervalData.actions[i]; if (actionData.uuid === uuid) {
javascript
{ "resource": "" }
q646
train
function () { var i = 0; var len = 0; var uuid = ''; if (!this._periodicActionUUIDs) { return; } len = this._periodicActionUUIDs.length; for (; i < len; i
javascript
{ "resource": "" }
q647
_xmlFileSet
train
function _xmlFileSet(file, element, attributeMapping, options) { const doc = loadXmlFile(file, options); const node = getXmlNode(doc, element); const result = []; if (_.isReallyObject(attributeMapping)) { _.each(attributeMapping, (value, attributeName) => { if (_.isFunction(value)) { result.push(value(node.getAttributeNode(attributeName))); } else { if (_.isNull(value)) { node.removeAttribute(attributeName); } else { node.setAttribute(attributeName, value); }
javascript
{ "resource": "" }
q648
deleteIfEmpty
train
function deleteIfEmpty(file, options) { options = _.opts(options, {deleteDirs: true});
javascript
{ "resource": "" }
q649
attachKeybindings
train
function attachKeybindings (binding, method) { if (!binding) return console.warn('attachKeybinding requires character or object for binding'); if (typeof binding === 'string' && !method) console.warn('attachKeybindings requries
javascript
{ "resource": "" }
q650
removeKeybindings
train
function removeKeybindings (bindings, method) { if (!bindings) return; if (typeof bindings === 'string' && !method) console.warn('removeKeybindings requries method as second arg'); if (typeof
javascript
{ "resource": "" }
q651
addMethod
train
function addMethod (char, method) { var keyIsBound = hasKeybinding(char); var listener = keyupHandler.bind(null, char, method); bindings[char] = bindings[char] || {methods: [], listeners: []}; if (keyIsBound)
javascript
{ "resource": "" }
q652
removeMethod
train
function removeMethod (char, method) { if (!hasKeybinding(char, method)) return; var fnIndex = bindings[char].methods.indexOf(method); window.removeEventListener('keyup', bindings[char].listeners[fnIndex]); bindings[char].methods.splice(fnIndex, 1); bindings[char].listeners.splice(fnIndex, 1);
javascript
{ "resource": "" }
q653
hasKeybinding
train
function hasKeybinding (key, method) { if (!bindings[key])
javascript
{ "resource": "" }
q654
keyupHandler
train
function keyupHandler (matchChar, method, evt) { // except for esc, we don't want to fire events when somebody is typing in an input if ((evt.target.tagName !== 'INPUT' && evt.target.tagName !== 'TEXTAREA'
javascript
{ "resource": "" }
q655
parse
train
function parse(schema, opts) { var attrs = files.load(schema); return attrs.protocol ?
javascript
{ "resource": "" }
q656
extractFileHeader
train
function extractFileHeader(path, opts) { opts = opts || {}; var decode = opts.decode === undefined ? true : !!opts.decode; var size = Math.max(opts.size || 4096, 4); var fd = fs.openSync(path, 'r'); var buf = new Buffer(size); var pos = 0; var tap = new utils.Tap(buf); var header = null; while (pos < 4) { // Make sure we have enough to check the magic bytes. pos += fs.readSync(fd, buf, pos, size - pos); } if (containers.MAGIC_BYTES.equals(buf.slice(0, 4))) { do { header = containers.HEADER_TYPE._read(tap); } while (!isValid()); if (decode !== false) { var meta = header.meta; meta['avro.schema'] = JSON.parse(meta['avro.schema'].toString()); if (meta['avro.codec'] !== undefined) { meta['avro.codec'] =
javascript
{ "resource": "" }
q657
evaluate
train
function evaluate(conf, parent) { if (!conf || conf.constructor.name !== 'Object') return conf; var val; for (var key in conf) { val = conf[key]; if (typeof
javascript
{ "resource": "" }
q658
reduceVal
train
function reduceVal(conf, val) { val = val.call(conf); return typeof
javascript
{ "resource": "" }
q659
generateColors
train
function generateColors(conf) { for (var key in conf.color) { if (typeof
javascript
{ "resource": "" }
q660
getUserGroups
train
function getUserGroups(user) { try { const output = runProgram('groups', [user]).trim(); const groupsText = isBusyboxCommand('groups') ? output : output.split(':')[1].trim();
javascript
{ "resource": "" }
q661
fileDelete
train
function fileDelete(src, options) { options = _.sanitize(options, {exclude: [], deleteDirs: true, onlyEmptyDirs: false}); let result = true; const files = _matchingFilesArray(src, options); _.each(files, (f) => {
javascript
{ "resource": "" }
q662
rand
train
function rand(options) { options = _.opts(options, {size: 32, ascii: false, alphanumeric: false, numeric: false}); const size = options.size; let data = ''; while (data.length < size) { // ASCII is in range of 0 to 127 let randBytes = crypto.pseudoRandomBytes(Math.max(size, 32)).toString();
javascript
{ "resource": "" }
q663
base64
train
function base64(text, operation) { operation = operation || 'encode'; if (operation === 'decode') { return (new Buffer(text,
javascript
{ "resource": "" }
q664
createTempFile
train
function createTempFile(options) { options = _.opts(options, {cleanup: true}); return
javascript
{ "resource": "" }
q665
createTempDir
train
function createTempDir(options) { options = _.opts(options, {cleanup: true});
javascript
{ "resource": "" }
q666
parseJson
train
function parseJson(name, type, value) { try { return typeof value === 'string' ? JSON.parse(value) :
javascript
{ "resource": "" }
q667
renderTemplateText
train
function renderTemplateText(template, data, options) { data = _.opts(data, {}); options = _.opts(options, {noEscape: true, compact: false}); // TODO: We should support recursively resolving, as in IB
javascript
{ "resource": "" }
q668
renderTemplate
train
function renderTemplate(templateFile, data, options) { return
javascript
{ "resource": "" }
q669
renderTemplateToFile
train
function renderTemplateToFile(templateFile, destFile, data, options) {
javascript
{ "resource": "" }
q670
stripPathPrefix
train
function stripPathPrefix(p, prefix, options) { if (!prefix) return p; options = _.sanitize(options, {force: false}); p = _fileCleanPath(p); prefix = _fileCleanPath(prefix); if (options.force) { return path.relative(prefix, p);
javascript
{ "resource": "" }
q671
isEmptyDir
train
function isEmptyDir(dir) { try { return !(fs.readdirSync(dir).length > 0); } catch (e) { if (e.code === 'ENOENT') { //
javascript
{ "resource": "" }
q672
size
train
function size(file) { if (!exists(file) || !isFile(file)) { return -1; } else { try {
javascript
{ "resource": "" }
q673
chmod
train
function chmod(file, permissions, options) { if (!isPlatform('unix')) return; if (!exists(file)) throw new Error(`Path '${file}' does not exists`); const isDir = isDirectory(file); options = _.sanitize(options, {recursive: false}); let filePermissions = null; let dirPermissions = null; if (_.isReallyObject(permissions)) { filePermissions = permissions.file || null; dirPermissions = permissions.directory || null; } else { filePermissions = permissions; dirPermissions
javascript
{ "resource": "" }
q674
infer
train
function infer(val, opts) { opts = opts || {}; // Optional custom inference hook. if (opts.valueHook) { var type = opts.valueHook(val, opts); if (type !== undefined) { if (!types.Type.isType(type)) { throw new Error(f('invalid value hook return value: %j', type)); } return type; } } // Default inference logic. switch (typeof val) { case 'string': return createType('string', opts); case 'boolean': return createType('boolean', opts); case 'number': if ((val | 0) === val) { return createType('int', opts); } else if (Math.abs(val) < 9007199254740991) { return createType('float', opts); } return createType('double', opts); case 'object': if (val === null) { return createType('null', opts); } else if (Array.isArray(val)) { if (!val.length) { return EMPTY_ARRAY_TYPE; } return createType({ type: 'array', items: combine(val.map(function (v) { return infer(v, opts); })) }, opts); } else if (Buffer.isBuffer(val)) { return createType('bytes', opts);
javascript
{ "resource": "" }
q675
createType
train
function createType(attrs, opts) { if (attrs === null) { // Let's be helpful for this common error. throw new Error('invalid type: null (did you mean "null"?)'); } if (Type.isType(attrs)) { return attrs; } opts = opts || {}; opts.registry = opts.registry || {}; var type; if (opts.typeHook && (type = opts.typeHook(attrs, opts))) { if (!Type.isType(type)) { throw new Error(f('invalid typehook return value: %j', type)); } return type; } if (typeof attrs == 'string') { // Type reference. attrs = qualify(attrs, opts.namespace); type = opts.registry[attrs]; if (type) { // Type was already defined, return it. return type; } if (isPrimitive(attrs)) { // Reference to a primitive type. These are also defined names by default // so we create the appropriate type and it to the registry for future // reference. return opts.registry[attrs] = createType({type: attrs}, opts); } throw new Error(f('undefined type name: %s', attrs)); } if (attrs.logicalType && opts.logicalTypes && !LOGICAL_TYPE) { var DerivedType = opts.logicalTypes[attrs.logicalType]; if (DerivedType) { var namespace = opts.namespace; var registry = {}; Object.keys(opts.registry).forEach(function (key) { registry[key] = opts.registry[key]; }); try { return new DerivedType(attrs, opts); } catch (err) { if (opts.assertLogicalTypes) {
javascript
{ "resource": "" }
q676
WrappedUnionType
train
function WrappedUnionType(attrs, opts) { UnionType.call(this, attrs, opts); this._constructors = this._types.map(function (type) { // jshint -W054 var name = type.getName(true); if (name === 'null') { return null; } function ConstructorFunction(name) { return function Branch$(val) {
javascript
{ "resource": "" }
q677
FixedType
train
function FixedType(attrs, opts) { Type.call(this, attrs, opts); if (attrs.size !== (attrs.size |
javascript
{ "resource": "" }
q678
MapType
train
function MapType(attrs, opts) { Type.call(this); if (!attrs.values) { throw new Error(f('missing map values: %j', attrs)); } this._values = createType(attrs.values, opts); // Addition by Edwin Elia
javascript
{ "resource": "" }
q679
ArrayType
train
function ArrayType(attrs, opts) { Type.call(this); if (!attrs.items) { throw new Error(f('missing array items:
javascript
{ "resource": "" }
q680
stringify
train
function stringify(obj, opts) { EXPORT_ATTRS = opts && opts.exportAttrs; var noDeref = opts && opts.noDeref; // Since JS objects are unordered, this implementation (unfortunately) // relies on engines returning properties in the same order that they are // inserted in. This is not in the JS spec, but can be "somewhat" safely // assumed (more here: http://stackoverflow.com/q/5525795/1062617). return (function (registry) { return JSON.stringify(obj, function (key, value) { if (value) { if ( typeof value == 'object' && value.hasOwnProperty('default') && !value.hasOwnProperty('logicalType') ) { // This is a field. if (EXPORT_ATTRS) { return { name: value.name, type: value.type, 'default': value['default'], order: value.order !== 'ascending' ? value.order : undefined, aliases: value.aliases.length ? value.aliases : undefined
javascript
{ "resource": "" }
q681
matches
train
function matches(file, patternList, excludePatterList, options) { options = _.sanitize(options, {minimatch: false}); let shouldInclude = false; let shouldExclude = false; const matcher = options.minimatch ? (f, pattern) => minimatch(f, pattern, {dot: true, matchBase: true}) : globMatch; if (!_.isEmpty(patternList)) { shouldInclude
javascript
{ "resource": "" }
q682
userExists
train
function userExists(user) { if (_.isEmpty(findUser(user, {refresh:
javascript
{ "resource": "" }
q683
addQueryToUrl
train
function addQueryToUrl ({ query, decamelizeQuery=true, url }) { if (!query) return const transformedQuery = decamelizeQuery ?
javascript
{ "resource": "" }
q684
load
train
function load(schema) { var obj; if (typeof schema == 'string' && schema !== 'null') { try { obj = JSON.parse(schema); } catch (err) {
javascript
{ "resource": "" }
q685
copyBuffer
train
function copyBuffer(buf, pos, len) { var copy = new Buffer(len);
javascript
{ "resource": "" }
q686
deleteGroup
train
function deleteGroup(group) { if (!runningAsRoot()) return; if (!group) throw new Error('You must provide a group to delete'); if (!groupExists(group)) { return; } const groupdelBin = _safeLocateBinary('groupdel'); const delgroupBin = _safeLocateBinary('delgroup'); if (isPlatform('linux')) { if (groupdelBin !== null) { // most modern systems runProgram(groupdelBin, [group]); } else { if (_isBusyboxBinary(delgroupBin)) { // busybox-based systems runProgram(delgroupBin, [group]); } else { throw new Error(`Don't know how to delete group ${group} on this strange linux`); } }
javascript
{ "resource": "" }
q687
kill
train
function kill(pid, signal) { signal = _.isUndefined(signal) ? 'SIGINT' : signal; // process.kill does not recognize many of the well known numeric signals, // only by name if (_.isFinite(signal) && _.has(signalsMap, signal)) { signal =
javascript
{ "resource": "" }
q688
contains
train
function contains(file, pattern, options) { options = _.sanitize(options, {encoding: 'utf-8'}); if (!exists(file)) return false; const text = read(file, options); if (_.isRegExp(pattern)) { return
javascript
{ "resource": "" }
q689
serializeBody
train
function serializeBody ({ decamelizeBody=true, headers, body }) { if (!body || !isJSONRequest(headers))
javascript
{ "resource": "" }
q690
createProtocol
train
function createProtocol(attrs, opts) { opts = opts || {}; var name = attrs.protocol; if (!name) { throw new Error('missing protocol name'); } if (attrs.namespace !== undefined) { opts.namespace = attrs.namespace; } else { var match = /^(.*)\.[^.]+$/.exec(name); if (match) { opts.namespace = match[1]; } } name = types.qualify(name, opts.namespace); if (attrs.types) { attrs.types.forEach(function (obj)
javascript
{ "resource": "" }
q691
Protocol
train
function Protocol(name, messages, types, handlers) { if (types === undefined) { // Let's be helpful in case this class is instantiated directly. return createProtocol(name, messages); } this._name = name; this._messages = messages;
javascript
{ "resource": "" }
q692
MessageEmitter
train
function MessageEmitter(ptcl, opts) { opts = opts || {}; events.EventEmitter.call(this); this._ptcl = ptcl; this._strict = !!opts.strictErrors; this._endWritable = !!utils.getOption(opts, 'endWritable', true); this._timeout = utils.getOption(opts, 'timeout', 10000); this._prefix = normalizedPrefix(opts.scope); this._cache = opts.cache || {}; var fgpt = opts.serverFingerprint; var adapter; if (fgpt) { adapter = this._cache[fgpt]; } if (!adapter) { // This might happen even if the server
javascript
{ "resource": "" }
q693
StatelessEmitter
train
function StatelessEmitter(ptcl, writableFactory, opts) { MessageEmitter.call(this, ptcl, opts); this._writableFactory = writableFactory; if (!opts || !opts.noPing) { // Ping the server to check whether the remote protocol
javascript
{ "resource": "" }
q694
emit
train
function emit(retry) { if (self._interrupted) { // The request's callback will already have been called. return; } var hreq = self._createHandshakeRequest(adapter, !retry); var writable = self._writableFactory.call(self, function (err, readable) { if (err) { cb(err); return; } readable.on('data', function (obj) { debug('received response %s', obj.id); // We don't check that the prefix matches since the ID likely hasn't // been propagated to the response (see default stateless codec). var buf = Buffer.concat(obj.payload); try { var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf); var hres = parts.head; if (hres.serverHash) { adapter = self._getAdapter(hres); } } catch (err) { cb(err); return; } self.emit('handshake',
javascript
{ "resource": "" }
q695
StatelessListener
train
function StatelessListener(ptcl, readableFactory, opts) { MessageListener.call(this, ptcl, opts); var self = this; var readable; process.nextTick(function () { // Delay listening to allow handlers to be attached even if the factory is // purely synchronous. readable = readableFactory.call(this, function (err, writable) { if (err) { self.emit('error', err); // Since stateless listeners are only used once, it is safe to destroy. onFinish(); return; } self._writable = writable.on('finish', onFinish); self.emit('_writable'); }).on('data', onRequest) .on('end', onEnd); }); function onRequest(obj) { var id = obj.id; var buf = Buffer.concat(obj.payload); var err = null; try { var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf); var hreq = parts.head; var adapter = self._getAdapter(hreq); } catch (cause) { err = wrapError('invalid handshake request', cause); } if (err) { done(encodeError(err)); } else { self._receive(parts.tail, adapter, done); } function done(resBuf) { if (!self._writable) { self.once('_writable', function () { done(resBuf); });
javascript
{ "resource": "" }
q696
Message
train
function Message(name, attrs, opts) { opts = opts || {}; if (!types.isValidName(name)) { throw new Error(f('invalid message name: %s', name)); } this._name = name; var recordName = f('org.apache.avro.ipc.%sRequest', name); this._requestType = types.createType({ name: recordName, type: 'record', namespace: opts.namespace || '', // Don't leak request namespace. fields: attrs.request }, opts); // We remove the record from the registry to prevent it from being exported // in the protocol's schema. delete opts.registry[recordName]; if (!attrs.response)
javascript
{ "resource": "" }
q697
Adapter
train
function Adapter(clientPtcl, serverPtcl, fingerprint) { this._clientPtcl = clientPtcl; this._serverPtcl = serverPtcl; this._fingerprint = fingerprint; // Convenience.
javascript
{ "resource": "" }
q698
wrapError
train
function wrapError(message, cause) { var err = new Error(f('%s: %s', message,
javascript
{ "resource": "" }
q699
encodeError
train
function encodeError(err, header) { return Buffer.concat([ header || new Buffer([0]), // Recover the header if possible.
javascript
{ "resource": "" }