_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| 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) {
return renderFn.call(_this, 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(
NAME + ': there was a problem rendering the template:\n' + e)
}
return output
} | 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),
deviceType: type
};
if (typeof params.log !== 'function') {
params.log = defaults.log;
}
switch (type) {
case 'proxy':
if (isBrowser()) {
console.error('Cannot create proxy in browser');
}
var Proxy = require('./src/Proxy');
return new Proxy(settings);
case 'toy':
case 'controller':
case 'observer':
var connectionModule;
if (isBrowser()) {
connectionModule = require('./src/WebClientConnection');
settings.udp4 = false;
settings.tcp = false;
settings.socketio = true;
} else {
connectionModule = require('./src/ClientConnection');
settings.socketio = false;
}
var Device = require('./src/Device');
return new Device(settings, connectionModule);
default:
throw new Error('Could not determine server type.');
}
};
} | javascript | {
"resource": ""
} |
q603 | train | function (path, errorMessage) {
if (!shell.test('-e', path)) {
shell.echo('Error: ' + errorMessage);
shell.exit(1);
}
} | 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) {
dest[key] = arg[key]
})
})
}
return dest
} | 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
// all 0, and |cur| is the closest to the actual value of the UNIX time. Now, get the current global monotonic clock
// value and do the remaining calculations.
return cur - getGlobalMonotonicClockMS();
} | 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) {
if (settings.snapshot && file.search('http://') !== -1) {
return '<link rel="stylesheet" type="text/css" href="' + path.basename(file) + '"/>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + file + '"/>';
}
});
sourceFile = sourceFile.replace('{{css}}', css.join(''));
// spit out the default sourcefile
cb(sourceFile);
} | 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>';
content += '<p><a href="/'+ patternFolder + '/' + file.filename +'">' + file.filename + '</a></p>';
content += '</div></div>';
});
content += '</body></html>';
cb(content);
});
} | 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);
});
// call the outputPatterns function that generates
// the html for every pattern
outputPatterns(patternFolder, patterns, cb);
} | 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;
}
// list all pattern files (that end with .html)
var files = [];
contents.forEach(function (content) {
if (content.substr(-5) === '.html') {
files.push(content);
}
});
// handle all the found pattern files
handleFiles(patternFolder, files, cb);
});
} | 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;
case Type.OBJECT:
x = {};
item.value.forEach(function (e) {
let key = e.key.substring(e.key.lastIndexOf('[') + 1, e.key.lastIndexOf(']'));
x[key] = _fromPersistable(e);
});
return x;
default:
_logUnknownType(item.type);
}
} | 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:
__self.value = [];
Object.keys(value).forEach(function (e) {
__self.value.push(new Persistable(key + '[' + e + ']', value[e]));
});
__self.type = typeof value;
break;
default:
_logUnknownType(typeof value);
}
}
__self.timestamp = Date.now();
__self.toOriginal = function () {
return _fromPersistable(__self);
};
} | 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 be sorted, and therefore it is impossible to get to this state in a test.
return a.key > b.key ? 1 : 0;
});
return item;
} | 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;
}
// eslint-disable-next-line no-param-reassign
schema._apolloTracerApplied = true;
forEachField(schema, (field, typeName, fieldName) => {
const functionName = `${typeName}.${fieldName}`;
if (field.resolve) {
// eslint-disable-next-line no-param-reassign
field.resolve = decorateWithTracer(
field.resolve,
{ type: 'resolve', functionName },
);
}
});
} | 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');
ctx.tracer.log('request.query', `${operation}\n${fragments}`);
ctx.tracer.log('request.variables', info.variableValues);
ctx.tracer.log('request.operationName', info.operation.name);
return root;
});
} | javascript | {
"resource": ""
} |
q615 | indexOfNode | train | function indexOfNode (host, node) {
const chs = host.childNodes;
const chsLen = chs.length;
for (let a = 0; a < chsLen; a++) {
if (chs[a] === node) {
return a;
}
}
return -1;
} | 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.
if (Array.isArray(host.childNodes)) {
if (index > -1) {
arrProto.splice.call(host.childNodes, index + eachIndex, 0, eachNode);
} else {
arrProto.push.call(host.childNodes, eachNode);
}
}
});
} | javascript | {
"resource": ""
} |
q617 | addNodeToSlot | train | function addNodeToSlot (slot, node, insertBefore) {
const isInDefaultMode = slot.assignedNodes().length === 0;
registerNode(slot, node, insertBefore, eachNode => {
if (isInDefaultMode) {
slot.__insertBefore(eachNode, insertBefore !== undefined ? insertBefore : null);
}
});
} | javascript | {
"resource": ""
} |
q618 | train | function () {
if (!window.ove.context.isInitialized) {
log.debug('Requesting an update of state configuration from server');
window.ove.socket.send({ action: Constants.Action.READ });
}
} | 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 + ']')) {
log.debug('Unable to produce list of spaces for section id:', sectionId);
Utils.sendEmptySuccess(res);
} else {
log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME + ' for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('sections[' + sectionId + '][spaces]')));
}
} | 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);
});
log.debug('Successfully computed geometry for space:', s);
server.spaceGeometries[s] = geometry;
});
}
return server.spaceGeometries;
} | 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 {
log.debug('Returning geometry for space:', spaceName);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(geometry));
}
} | 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);
}
}
});
server.state.set('sections[' + sectionId + ']', {});
server.wss.clients.forEach(function (c) {
if (c.readyState === Constants.WEBSOCKET_READY) {
c.safeSend(JSON.stringify({ appId: Constants.APP_NAME, message: { action: Constants.Action.DELETE, id: parseInt(sectionId, 10) } }));
}
});
} | javascript | {
"resource": ""
} |
|
q623 | train | function (req, res) {
_updateSections({ moveTo: req.body }, req.query.space, req.query.groupId, res);
} | 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;
if (app) {
section.app = { url: app.url, state: app.state, opacity: app.opacity };
}
log.debug('Successfully read configuration for section id:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(section));
} | 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);
log.info('Successfully deleted section:', sectionId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ ids: [ parseInt(sectionId, 10) ] }));
}
} | 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)) {
log.error('Invalid Group', 'request:', JSON.stringify(req.body));
Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group' }));
} else {
server.state.set('groups[' + groupId + ']', req.body.slice());
log.info('Successfully ' + operation + 'd group:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify({ id: parseInt(groupId, 10) }));
}
} | 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({ error: 'invalid group id' }));
} else {
log.debug('Successfully read configuration for group id:', groupId);
Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.state.get('groups[' + groupId + ']')));
}
} | 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)) {
hasNonEmptyGroups = true;
}
});
if (hasNonEmptyGroups) {
log.info('Successfully deleted group:', groupId);
} else {
server.state.set('groups', []);
log.info('Successfully deleted all groups');
}
} | 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) {
host = host.substring(host.indexOf('//') + 2);
}
if (host.indexOf('/') >= 0) {
host = host.substring(0, host.indexOf('/'));
}
}
return host;
} | javascript | {
"resource": ""
} |
|
q630 | focusAtEnd | train | function focusAtEnd(change) {
const { value } = change;
const document = value.document;
return change.collapseToEndOf(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)
}
this.initialize()
this.fromObject({pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf})
} | javascript | {
"resource": ""
} |
q632 | stackChain | train | function stackChain() {
this.extend = new TraceModifier();
this.filter = new TraceModifier();
this.format = new StackFormater();
this.version = require('./package.json').version;
} | javascript | {
"resource": ""
} |
q633 | BriToPbn | train | function BriToPbn(opts) {
if (!(this instanceof BriToPbn)) return new BriToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, opts);
} | javascript | {
"resource": ""
} |
q634 | DgeToPbn | train | function DgeToPbn(opts) {
if (!(this instanceof DgeToPbn)) return new DgeToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, 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) {
file.id = file.id.replace(file.orig.cwd, "");
sriData.path = sriData.path.replace(file.orig.cwd, "");
}
// Attach a property to the WIP manifest object
manifest[file.id] = sriData;
callback(err, manifest);
});
} | javascript | {
"resource": ""
} |
|
q636 | train | function (err, manifest) {
if (err) {
// Error generating SRI hashes
grunt.log.error("Error loading resource: " + err);
return done(false);
}
return saveJson(
options,
manifest,
writeLog(fileCount, done)
);
} | javascript | {
"resource": ""
} |
|
q637 | DupToPbn | train | function DupToPbn(opts) {
if (!(this instanceof DupToPbn)) return new DupToPbn(opts);
opts = opts || {};
this.needDirectives = true;
this.boardNumber = opts.boardNumber || 1;
stream.Transform.call(this, 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();
const block = Slate.Block.create({
type: opts.type,
nodes: [Slate.Text.create()]
});
return (change) => change.insertNodeByKey(node.key, lastIndex, block);
},
changes: {
focusAtEnd
}
};
} | 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 (isFile(a, stat)) {
a = path.dirname(a);
}
var res = path.relative(a, b);
if (res === '') {
return '.';
}
// if `b` originally had a slash, and the path ends
// with `b` missing a slash, then re-add the slash.
var noslash = trimEnd(origB, '/');
if (slashB && (res === noslash || endsWith(res, noslash))) {
res = res + '/';
}
return res;
} | 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 well handle
stat = tryStats(fp);
}
if (isObject(stat) && typeof stat.isDirectory === 'function') {
return stat.isDirectory();
}
var segs = fp.split('/');
var last = segs[segs.length - 1];
if (last && last.indexOf('.') !== -1) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q641 | isFile | train | function isFile(fp, stat) {
if (stat === true) {
stat = tryStats(fp);
}
return !isDir(fp, stat);
} | 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) {
actionData = actions[i];
context.executeAction(actionData.action, actionData.params);
}
};
} | 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
};
}
intervalsMap[interval].actions.push({
uuid: uuid,
action: action,
params: params
});
uuidMap[uuid] = intervalsMap[interval];
if (!this._periodicActionUUIDs) {
this._periodicActionUUIDs = [];
}
this._periodicActionUUIDs.push(uuid);
return true;
} | 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) {
actionData = this.constructor.periodicActions[i];
this.startPeriodicAction(actionData.uuid, actionData.action, actionData.params, actionData.interval);
}
} | 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) {
intervalData.actions.splice(i, 1);
break;
}
}
if (intervalData.actions.length === 0) {
clearInterval(intervalData.id);
intervalsMap[intervalData.interval] = null;
}
return true;
} | 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 += 1) {
uuid = this._periodicActionUUIDs[i];
this.stopPeriodicAction(uuid);
}
} | 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);
}
}
});
} else {
// still being able to provide the node to pass the node to a given function
if (_.isFunction(attributeMapping)) {
result.push(attributeMapping(node, doc));
} else {
if (node.hasChildNodes()) {
let i = 0;
const nNodes = node.childNodes.length;
while (i < nNodes) {
node.removeChild(i);
i++;
}
}
// if attribute and value == null, delete the node
if (_.isNull(attributeMapping)) {
node.parentNode.removeChild(node);
} else {
node.appendChild(doc.createTextNode(attributeMapping));
}
}
}
write(file, new XMLSerializer().serializeToString(doc), options);
if (!_.isEmpty(result)) {
return (result.length > 1) ? result : result[0];
}
} | javascript | {
"resource": ""
} |
q648 | deleteIfEmpty | train | function deleteIfEmpty(file, options) {
options = _.opts(options, {deleteDirs: true});
return fileDelete(file, _.extend(_.opts(options), {onlyEmptyDirs: 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 method as second arg');
if (hasKeybinding(binding, method)) return console.warn(`attachKeybinding: already attached ${binding} to method`, method);
if (typeof binding === 'string') addMethod(binding, method);
else Object.keys(binding).forEach((key) => addMethod(key, binding[key]))
} | 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 bindings === 'string') return removeMethod(bindings, method);
Object.keys(bindings).forEach((key) => removeMethod(key, bindings[key]));
} | 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) window.removeEventListener('keyup', bindings[char].listeners[0]);
bindings[char].methods.unshift(method);
bindings[char].listeners.unshift(listener);
window.addEventListener('keyup', listener);
} | 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);
if (!bindings[char].methods.length) {
delete bindings[char];
} else if (fnIndex === 0) {
window.addEventListener('keyup', bindings[char].listeners[0]);
}
} | javascript | {
"resource": ""
} |
q653 | hasKeybinding | train | function hasKeybinding (key, method) {
if (!bindings[key]) return false;
return method ? !!~bindings[key].methods.indexOf(method) : true;
} | 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' && !evt.target.hasAttribute('contenteditable')) || keysMatch(evt, 'esc')) {
if (keysMatch(evt, matchChar)) method(evt);
}
} | javascript | {
"resource": ""
} |
q655 | parse | train | function parse(schema, opts) {
var attrs = files.load(schema);
return attrs.protocol ?
protocols.createProtocol(attrs, opts) :
types.createType(attrs, opts);
} | 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'] = meta['avro.codec'].toString();
}
}
}
fs.closeSync(fd);
return header;
function isValid() {
if (tap.isValid()) {
return true;
}
var len = 2 * tap.buf.length;
var buf = new Buffer(len);
len = fs.readSync(fd, buf, 0, len);
tap.buf = Buffer.concat([tap.buf, buf]);
tap.pos = 0;
return false;
}
} | 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 val === 'function') val = reduceVal(parent, val);
conf[key] = evaluate(val, parent);
}
return conf;
} | javascript | {
"resource": ""
} |
q658 | reduceVal | train | function reduceVal(conf, val) {
val = val.call(conf);
return typeof val === 'function' ? reduceVal(conf, val) : val;
} | javascript | {
"resource": ""
} |
q659 | generateColors | train | function generateColors(conf) {
for (var key in conf.color) {
if (typeof conf.color[key] !== 'string') continue;
conf.color[key] = new Color(conf.color[key]);
}
return conf;
} | javascript | {
"resource": ""
} |
q660 | getUserGroups | train | function getUserGroups(user) {
try {
const output = runProgram('groups', [user]).trim();
const groupsText = isBusyboxCommand('groups') ? output : output.split(':')[1].trim();
return groupsText.split(/\s+/);
} catch (e) {
throw new Error(`Cannot resolve user ${user}`);
}
} | 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) => {
const fileWasDeleted = _fileDelete(f, options);
result = result && fileWasDeleted;
});
return result;
} | 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();
/* eslint-disable no-control-regex */
if (options.ascii) randBytes = randBytes.replace(/[^\s\x00-\x7F]/g, '');
/* eslint-enable no-control-regex */
if (options.alphanumeric) randBytes = randBytes.replace(/[^a-zA-Z0-9]/g, '');
if (options.numeric) randBytes = randBytes.replace(/[^0-9]/g, '');
data += randBytes;
}
data = data.slice(0, size);
return data;
} | javascript | {
"resource": ""
} |
q663 | base64 | train | function base64(text, operation) {
operation = operation || 'encode';
if (operation === 'decode') {
return (new Buffer(text, 'base64')).toString();
} else {
return (new Buffer(text)).toString('base64');
}
} | javascript | {
"resource": ""
} |
q664 | createTempFile | train | function createTempFile(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath((f) => fs.writeFileSync(f, ''), options.cleanup);
} | javascript | {
"resource": ""
} |
q665 | createTempDir | train | function createTempDir(options) {
options = _.opts(options, {cleanup: true});
return _createTemporaryPath(fs.mkdirSync, options.cleanup);
} | javascript | {
"resource": ""
} |
q666 | parseJson | train | function parseJson(name, type, value) {
try {
return typeof value === 'string' ?
JSON.parse(value) :
value;
} catch (e) {
throwError(name, type, 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
return hb.compile(template, options)(_.defaults(data, globalSettings), {helpers: globalHelpers});
} | javascript | {
"resource": ""
} |
q668 | renderTemplate | train | function renderTemplate(templateFile, data, options) {
return renderTemplateText(read(normalizeTemplate(templateFile)), data, options);
} | javascript | {
"resource": ""
} |
q669 | renderTemplateToFile | train | function renderTemplateToFile(templateFile, destFile, data, options) {
renderTemplateTextToFile(read(templateFile), normalizeFile(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);
} else {
const pathSplit = split(p);
const prefixSplit = split(prefix);
if (prefixSplit.length > pathSplit.length) return p;
let i = 0;
for (i = 0; i < prefixSplit.length; i++) {
if (pathSplit[i] !== prefixSplit[i]) return p;
}
return pathSplit.slice(i).join('/');
}
} | javascript | {
"resource": ""
} |
q671 | isEmptyDir | train | function isEmptyDir(dir) {
try {
return !(fs.readdirSync(dir).length > 0);
} catch (e) {
if (e.code === 'ENOENT') {
// We consider non-existent as empty
return true;
}
throw e;
}
} | javascript | {
"resource": ""
} |
q672 | size | train | function size(file) {
if (!exists(file) || !isFile(file)) {
return -1;
} else {
try {
return _fileStats(file).size;
} catch (e) {
return -1;
}
}
} | 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 = permissions;
}
if (isDir && options.recursive) {
_.each(listDirContents(file, {compact: false, includeTopDir: true}), function(data) {
_chmod(data.file, data.type === 'directory' ? dirPermissions : filePermissions);
});
} else {
_chmod(file, isDir ? dirPermissions : filePermissions);
}
} | 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);
}
var fieldNames = Object.keys(val);
if (fieldNames.some(function (s) { return !types.isValidName(s); })) {
// We have to fall back to a map.
return createType({
type: 'map',
values: combine(fieldNames.map(function (s) {
return infer(val[s], opts);
}), opts)
}, opts);
}
return createType({
type: 'record',
fields: fieldNames.map(function (s) {
return {name: s, type: infer(val[s], opts)};
})
}, opts);
default:
throw new Error(f('cannot infer type from: %j', val));
}
} | 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) {
// The spec mandates that we fall through to the underlying type if
// the logical type is invalid. We provide this option to ease
// debugging.
throw err;
}
LOGICAL_TYPE = null;
opts.namespace = namespace;
opts.registry = registry;
}
}
}
if (Array.isArray(attrs)) { // Union.
var UnionType = opts.wrapUnions ? WrappedUnionType : UnwrappedUnionType;
type = new UnionType(attrs, opts);
} else { // New type definition.
type = (function (typeName) {
var Type = TYPES[typeName];
if (Type === undefined) {
throw new Error(f('unknown type: %j', typeName));
}
return new Type(attrs, opts);
})(attrs.type);
}
return type;
} | 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) {
this[`${name}`] = val;
}
}
var constructor = ConstructorFunction(name);
constructor.getBranchType = function() { return type; };
return constructor;
});
} | javascript | {
"resource": ""
} |
q677 | FixedType | train | function FixedType(attrs, opts) {
Type.call(this, attrs, opts);
if (attrs.size !== (attrs.size | 0) || attrs.size < 1) {
throw new Error(f('invalid %s fixed size', this.getName(true)));
}
this._size = attrs.size | 0;
} | 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
var keys = attrs.keys;
if (!keys) {
keys = 'string';
}
this._keys = createType(keys, opts);
} | javascript | {
"resource": ""
} |
q679 | ArrayType | train | function ArrayType(attrs, opts) {
Type.call(this);
if (!attrs.items) {
throw new Error(f('missing array items: %j', attrs));
}
this._items = createType(attrs.items, opts);
} | 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
};
} else {
return {name: value.name, type: value.type};
}
} else if (value.aliases) {
// This is a named type (enum, fixed, record, error).
var name = value.name;
if (name) {
// If the type is anonymous, we always dereference it.
if (noDeref || registry[name]) {
return name;
}
registry[name] = true;
}
if (!EXPORT_ATTRS || !value.aliases.length) {
value.aliases = undefined;
}
}
}
return value;
});
})({});
} | 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 = _.some(_ensureArray(patternList), pattern => matcher(file, pattern));
}
if (!_.isEmpty(excludePatterList)) {
shouldExclude = _.some(_ensureArray(excludePatterList), pattern => matcher(file, pattern));
}
return shouldInclude && !shouldExclude;
} | javascript | {
"resource": ""
} |
q682 | userExists | train | function userExists(user) {
if (_.isEmpty(findUser(user, {refresh: true, throwIfNotFound: false}))) {
return false;
} else {
return true;
}
} | javascript | {
"resource": ""
} |
q683 | addQueryToUrl | train | function addQueryToUrl ({ query, decamelizeQuery=true, url }) {
if (!query) return
const transformedQuery = decamelizeQuery ? decamelizeKeys(query) : query
return {
url: url + '?' + stringify(transformedQuery)
}
} | javascript | {
"resource": ""
} |
q684 | load | train | function load(schema) {
var obj;
if (typeof schema == 'string' && schema !== 'null') {
try {
obj = JSON.parse(schema);
} catch (err) {
// No file loading here.
}
}
if (obj === undefined) {
obj = schema;
}
return obj;
} | javascript | {
"resource": ""
} |
q685 | copyBuffer | train | function copyBuffer(buf, pos, len) {
var copy = new Buffer(len);
buf.copy(copy, 0, pos, pos + len);
return copy;
} | 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`);
}
}
} else if (isPlatform('osx')) {
runProgram('dscl', ['.', '-delete', `/Groups/${group}`]);
} else if (isPlatform('windows')) {
throw new Error(`Don't know how to delete group ${group} on Windows`);
} else {
throw new Error(`Don't know how to delete group ${group} on the current platformp`);
}
} | 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 = signalsMap[signal];
}
if (!_.isFinite(pid)) return false;
try {
process.kill(pid, signal);
} catch (e) {
return false;
}
return true;
} | 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 !!text.match(pattern);
} else {
return (text.search(_escapeRegExp(pattern)) !== -1);
}
} | javascript | {
"resource": ""
} |
q689 | serializeBody | train | function serializeBody ({ decamelizeBody=true, headers, body }) {
if (!body || !isJSONRequest(headers)) return
const transformedBody = decamelizeBody ? decamelizeKeys(body) : body
return {
body: JSON.stringify(transformedBody)
}
} | 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) { types.createType(obj, opts); });
}
var messages = {};
if (attrs.messages) {
Object.keys(attrs.messages).forEach(function (key) {
messages[key] = new Message(key, attrs.messages[key], opts);
});
}
return new Protocol(name, messages, opts.registry || {});
} | 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;
this._types = types;
// Shared with subprotocols (via the prototype chain, overwriting is safe).
this._handlers = handlers || {};
// We cache a string rather than a buffer to not retain an entire slab. This
// also lets us use hashes as keys inside maps (e.g. for resolvers).
this._hs = utils.getHash(this.getSchema()).toString('binary');
} | 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 fingerprint option was set, in
// cases where the cache doesn't contain the corresponding adapter.
fgpt = ptcl.getFingerprint();
adapter = this._cache[fgpt] = new Adapter(ptcl, ptcl, fgpt);
}
this._adapter = adapter;
this._registry = new Registry(this, PREFIX_LENGTH);
this._destroyed = false;
this._interrupted = false;
this.once('_eot', function (pending) { this.emit('eot', pending); });
} | 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 is compatible.
this.emitMessage('', {}, function (err) {
if (err) {
this.emit('error', err);
}
});
}
} | 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', hreq, hres);
if (hres.match === 'NONE') {
process.nextTick(function() { emit(true); });
return;
}
// Change the default adapter.
self._adapter = adapter;
cb(null, parts.tail, adapter);
});
});
writable.write({
id: id,
payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf]
});
if (self._endWritable) {
writable.end();
}
} | 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); });
return;
}
var hres = self._createHandshakeResponse(err, hreq);
self.emit('handshake', hreq, hres);
var payload = [
HANDSHAKE_RESPONSE_TYPE.toBuffer(hres),
resBuf
];
self._writable.write({id: id, payload: payload});
if (self._endWritable) {
self._writable.end();
}
}
}
function onEnd() { self.destroy(); }
function onFinish() {
if (readable) {
readable
.removeListener('data', onRequest)
.removeListener('end', onEnd);
}
self.destroy(true);
}
} | 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) {
throw new Error('missing response');
}
this._responseType = types.createType(attrs.response, opts);
var errors = attrs.errors || [];
errors.unshift('string');
this._errorType = types.createType(errors, opts);
this._oneWay = !!attrs['one-way'];
if (this._oneWay) {
if (this._responseType.getTypeName() !== 'null' || errors.length > 1) {
throw new Error('unapplicable one-way parameter');
}
}
} | javascript | {
"resource": ""
} |
q697 | Adapter | train | function Adapter(clientPtcl, serverPtcl, fingerprint) {
this._clientPtcl = clientPtcl;
this._serverPtcl = serverPtcl;
this._fingerprint = fingerprint; // Convenience.
this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers();
} | javascript | {
"resource": ""
} |
q698 | wrapError | train | function wrapError(message, cause) {
var err = new Error(f('%s: %s', message, cause.message));
err.cause = cause;
return err;
} | javascript | {
"resource": ""
} |
q699 | encodeError | train | function encodeError(err, header) {
return Buffer.concat([
header || new Buffer([0]), // Recover the header if possible.
new Buffer([1, 0]), // Error flag and first union index.
STRING_TYPE.toBuffer(err.message)
]);
} | javascript | {
"resource": ""
} |