_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q31400 | isInt | train | function isInt(obj) {
var type = sType(obj);
return (_.has(obj, '$value') && (type === 'xsd:int' || type === 'int'));
} | javascript | {
"resource": ""
} |
q31401 | hasKeys | train | function hasKeys(obj) {
return (!Array.isArray(obj) && _.isObject(obj) && _.keys(obj).length > 0);
} | javascript | {
"resource": ""
} |
q31402 | filterValidPaths | train | function filterValidPaths(type, paths, version) {
var valid = [];
version = env.schema[version] || env.schema['5.1'];
_.forEach(paths, function(p) {
if (env.schema.hasProperty(version, type, p)) {
valid.push(p);
}
});
return valid;
} | javascript | {
"resource": ""
} |
q31403 | newError | train | function newError(errorCode, errorMessage) {
var errObj;
if (_.isObject(errorCode)) {
errObj = errorCode;
}
else if (typeof(errorCode) === 'number') {
errObj = {
errorCode: errorCode,
};
if (errorMessage) {
errObj.message = errorMessage;
}
}
else {
errObj = {errorCode: 500};
}
return new Promise(function(resolve, reject) {
reject(errObj);
});
} | javascript | {
"resource": ""
} |
q31404 | getSessionId | train | function getSessionId(cookie) {
if (typeof(cookie.cookies) === 'string') {
var idx = cookie.cookies.indexOf('=');
if (idx !== -1) {
return _.trim(cookie.cookies.substring(idx + 1), '"') || null;
}
}
return null;
} | javascript | {
"resource": ""
} |
q31405 | log | train | function log(obj, message) {
obj = obj || [];
obj.push({
time: new Date(),
log: message
});
return obj;
} | javascript | {
"resource": ""
} |
q31406 | train | function() {
if(savedMessageFromLastFail) {
// Last time we tried to publish there was a failure preventing it from ending up on the wall.
// In such a case, we want to pre-populate the user's message with the same message from last time.
// See 20552: ('Write Something..' text is lost on network error when attempting to share)
wallPostObj.message = savedMessageFromLastFail;
savedMessageFromLastFail = "";
}
// The backend passes in the following:
// wallPostObj: Contains the copy for the wall post
// withThesePermissions: permissions needed to post on the wall
// accessToken: the facebook token needed to set up the session
// tokenExpiry: the date the facebook token expires
// onSuccessCBToken: Callback method on success
// onCancelledCBToken: When the user cancels post
backend.handlePostRequest_({
facebookKeyValues: wallPostObj,
accessToken: settings.get("facebook.access_token"),
tokenExpire: settings.get("facebook.expires_at"),
onSuccessCBToken: kirin.wrapCallback(function() {
console.log("Publish successful");
successCallback();
}, "Facebook.", "publish."),
onCancelledCBToken: kirin.wrapCallback(function() {
console.log("Publish was cancelled");
if(_.isFunction(cancelCallback)) {
cancelCallback();
}
}, "Facebook.", "cancelled."),
onFailureCBToken: kirin.wrapCallback(function(devErrMsg) {
console.log("Publish failed");
showFacebookFailMsg();
failureCallback(devErrMsg);
}, "Facebook.", "failure.")
});
} | javascript | {
"resource": ""
} | |
q31407 | genSession | train | function genSession (baseUrl, devId, authHash, platform) {
let url = baseUrl + 'createsessionjson/' + devId + '/' +
authHash + '/' + util.getUtcTime()
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
let sessionID = JSON.parse(body)
switch (platform) {
case 'smitePC':
process.env.SMITE_PC_SESSION = sessionID.session_id
resolve(sessionID)
break
case 'smiteXBOX':
process.env.SMITE_XBOX_SESSION = sessionID.session_id
resolve(sessionID)
break
case 'smitePS4':
process.env.SMITE_PS4_SESSION = sessionID.session_id
resolve(sessionID)
break
case 'paladinsPC':
process.env.PALADINS_PC_SESSION = sessionID.session_id
resolve(sessionID)
break
case 'paladinsXBOX':
process.env.PALADINS_XBOX_SESSION = sessionID.session_id
resolve(sessionID)
break
case 'paladinsPS4':
process.env.PALADINS_PS4_SESSION = sessionID.session_id
resolve(sessionID)
}
} else {
reject(error)
}
})
})
} | javascript | {
"resource": ""
} |
q31408 | taskAsync | train | function taskAsync(args, result) {
// format the result
result = env.format(result);
// if the delete should not be asyncronous and the task should be monitored
if (args.async === false) {
// set the polling period and timeout defaults
args.delay = !isNaN(args.delay) ? args.delay : 1000;
args.timeout = (!isNaN(args.timeout) && args.timeout >= 0) ? args.timeout : 0;
// start the monitor
return task(result.id, args.delay, args.timeout, (new Date()).valueOf());
}
// return the result
return result;
} | javascript | {
"resource": ""
} |
q31409 | assignRequest | train | function assignRequest (target, source, obj = {}, term) {
_.merge(target, _.omit(source, ['term']), obj)
if (term == true) target.term = source.term
} | javascript | {
"resource": ""
} |
q31410 | processTerm | train | function processTerm (handler, obj = {}, isDefault) {
let req = {
term: this._request.term.then(value => {
assignRequest(req, this._request, obj)
if (this._request.error && !isDefault) return null
if (isDefault) req.error = null
return handler(value, req)
})
}
return new v(this._client, req)
} | javascript | {
"resource": ""
} |
q31411 | processBranch | train | function processBranch (args, resolve, reject) {
let condition = args.shift()
let val = args.shift()
let las = _.last(args)
return Promise.resolve(condition)
.then(c => {
if (c === true) {
return Promise.resolve(_.isFunction(val) ? val() : val)
.then(resolve, reject)
} else if (args.length === 1) {
return Promise.resolve(_.isFunction(las) ? las() : las)
.then(resolve, reject)
} else {
return processBranch(args, resolve, reject)
}
}, reject)
} | javascript | {
"resource": ""
} |
q31412 | performRetrieve | train | function performRetrieve (req) {
return this._client.retrieve(req.args, req.options)
.then(result => {
req.args = {}
req.options = {}
return result
})
} | javascript | {
"resource": ""
} |
q31413 | train | function(url, done) {
var urlParts = urlUtil.parse(url, true),
filename = urlParts.pathname,
auth = urlParts.auth;
if (S(filename).endsWith("/")) filename += "index"; // Append
var filePath = path.resolve(
process.cwd(),
outPath,
S(urlParts.hostname).replaceAll("\\.", "-").s,
"./" + filename + "." + format),
args = [captureScript, url, filePath, '--username', username,
'--password', password, '--paper-orientation', paperOrientation,
'--paper-margin', paperMargin, '--paper-format', paperFormat,
'--viewport-width', viewportWidth, '--viewport-height', viewportHeight];
var phantom = childProcess.execFile(phantomPath, args, function(err, stdout, stderr) {
if (verbose && stdout) console.log("---\nPhantomJS process stdout [%s]:\n" + stdout + "\n---", phantom.pid);
if (verbose && stderr) console.log("---\nPhantomJS process stderr [%s]:\n" + stderr + "\n---", phantom.pid);
if (verbose) console.log("Rendered %s to %s", url, filePath);
done(err);
});
if (verbose)
console.log("Spawning PhantomJS process [%s] to rasterize '%s' to '%s'", phantom.pid, url, filePath);
} | javascript | {
"resource": ""
} | |
q31414 | rootSearch | train | function rootSearch(args) {
// get the datacenters
return _client.retrieve({
type: 'Datacenter',
properties: ['name', 'datastoreFolder', 'hostFolder', 'networkFolder', 'vmFolder']
})
.then(function(dcs) {
// look through each of the dcs and map the return values
return Promise.map(dcs, function(dc) {
var folderId;
// get the correct folder id to start search from or if searching
if (args.type === 'Datastore') {
folderId = dc.datastoreFolder;
}
else if (args.type === 'HostSystem') {
folderId = dc.hostFolder;
}
else if (args.type === 'Network') {
folderId = dc.networkFolder;
}
else if (args.type === 'VirtualMachine') {
folderId = dc.vmFolder;
}
// return the entity details
return {
type: 'Folder',
id: folderId
};
});
});
} | javascript | {
"resource": ""
} |
q31415 | findByNameEx | train | function findByNameEx(args, matches) {
// create a variable to store the matches
matches = matches || [];
// set option defaults
args.name = Array.isArray(args.name) ? args.name : [args.name];
args.recursive = (typeof(args.recursive) === 'boolean') ? args.recursive : false;
args.limit = !isNaN(args.limit) ? args.limit : 1;
args.properties = args.properties || [];
// check for a starting point, if one doesnt exist begin at the datacenter level
if (!args.parent) {
return rootSearch(args)
.then(function(parents) {
return findByNameEx({
type : args.type,
name : args.name,
properties : args.properties,
parent : parents,
recursive : args.recursive,
limit : args.limit
}, matches);
});
}
// convert the parent to an array if it is not one
args.parent = Array.isArray(args.parent) ? args.parent : [args.parent];
// perform the search
return Promise.each(args.parent, function(parent) {
// check if the match limit is met
if (matches.length >= args.limit) {
return;
}
// perform the search on each name
return Promise.each(args.name, function(name) {
// check if the match limit is met
if (matches.length >= args.limit) {
return;
}
// perform the search
return _client.getServiceContent({
method: 'FindChild',
service: 'searchIndex',
params: {
entity: util.moRef(parent.type, parent.id),
name: name
}
})
.then(function(result) {
var id = _.get(result, '$value');
if (id) {
matches.push(id);
}
});
})
.then(function() {
// check if the match limit is met, if not and recursive
// attempt to descend the child objects
if (matches.length < args.limit && args.recursive) {
// get the children of the current parent
return _client.retrieve({
type: parent.type,
id: parent.id,
properties: ['childEntity']
})
.then(function(mo) {
var parents = [];
// get all of the child folders
_.forEach(_.get(mo, '[0].childEntity'), function(child) {
if (child.match(/^group-.*/)) {
parents.push({
type: 'Folder',
id: child
});
}
});
// if there were folders, recurse
if (parents.length > 0) {
return findByNameEx({
type : args.type,
name : args.name,
properties : args.properties,
parent : parents,
recursive : args.recursive,
limit : args.limit
}, matches);
}
});
}
});
})
.then(function() {
return matches;
});
} | javascript | {
"resource": ""
} |
q31416 | findByName | train | function findByName(args) {
// validate the types
if (!args.type || !_.includes(['Datastore', 'HostSystem', 'Network', 'VirtualMachine'], args.type)) {
return new Promise(function(resolve, reject) {
reject({
errorCode: 400,
message: 'Invalid search type. Valid types are Datastore, HostSystem, Network, and VirtualMachine'
});
});
}
// start the search
return findByNameEx(args).then(function(matches) {
// if no matches return an empty array
if (!matches || (Array.isArray(matches) && matches.length === 0)) {
return [];
}
// check for an ID only response and format the matches as an array of objects
else if (Array.isArray(args.properties) && (args.properties.length === 0 || args.properties[0] === 'id')) {
return _.map(matches, function(id) {
return {id: id};
});
}
// otherwise add get the items with their properties
return _client.retrieve({
type: args.type,
id: matches,
properties: args.properties
});
});
} | javascript | {
"resource": ""
} |
q31417 | Resource | train | function Resource(spec, options) {
if (!(this instanceof Resource)) {
return new Resource(spec, options);
}
if (typeof spec !== 'object') {
throw new Error('resource spec must be an object');
}
debug('create resource %s', spec.path, spec);
this.spec = spec;
this.list = [];
this.options = options || {};
this.middleware = {};
this.operations = {};
} | javascript | {
"resource": ""
} |
q31418 | c | train | function c(color, text) {
if(chaiParam.config.disableColors)
return text;
return chalk[color](text);
} | javascript | {
"resource": ""
} |
q31419 | fillEmptyOptionsFromPrompt | train | function fillEmptyOptionsFromPrompt (options, args, callback, startPosition) {
if (typeof startPosition === 'undefined') {
startPosition = 0
}
if (startPosition < 0) {
throw new RangeError('Start position must not be negative')
}
if (startPosition > args.length) {
throw new RangeError('Start position (' + startPosition +
') is greater than length of args (' + args.length + ')')
}
if (startPosition === args.length) {
callback(null, options)
} else {
var arg = args[startPosition]
if (options[arg.name]) {
fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1)
} else {
module.exports.getValueFromPrompt(arg.title || arg.name, arg.confirm,
function (error, result) {
if (error) {
callback(error)
} else {
options[arg.name] = result
fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1)
}
}
)
}
}
} | javascript | {
"resource": ""
} |
q31420 | train | function (program) {
var verbosity = program.verbose
if (program.quiet) {
verbosity = 0
} else if (typeof verbosity === 'undefined') {
verbosity = 1
}
return verbosity
} | javascript | {
"resource": ""
} | |
q31421 | train | function (title, confirm, callback) {
var fullTitle = title.indexOf('Confirm') === 0 ? title : 'Enter ' + title
fullTitle += ':'
read({
prompt: fullTitle,
silent: true
}, function (error, result) {
if (error) {
process.stdout.write('\n')
callback(provisionUtil.createFormattedDxlError(
'Error obtaining value for prompt: ' + title))
} else if (result) {
if (confirm) {
module.exports.getValueFromPrompt('Confirm ' + title, false,
function (error, confirmationResult) {
if (error) {
process.stdout.write('\n')
callback(provisionUtil.createFormattedDxlError(
'Error obtaining confirmation value for prompt: ' + title))
} else if (result === confirmationResult) {
callback(null, result)
} else {
process.stdout.write('Values for ' + title +
' do not match. Try again.\n')
module.exports.getValueFromPrompt(title, true, callback)
}
}
)
} else {
callback(null, result)
}
} else {
process.stdout.write('Value cannot be empty. Try again.\n')
module.exports.getValueFromPrompt(title, confirm, callback)
}
})
} | javascript | {
"resource": ""
} | |
q31422 | train | function (hostname, command) {
var hostInfo = {hostname: hostname, user: '', password: ''}
var hostInfoKeys = ['port', 'user', 'password', 'truststore']
hostInfoKeys.forEach(function (hostInfoKey) {
if (command[hostInfoKey]) {
hostInfo[hostInfoKey] = command[hostInfoKey]
delete command[hostInfoKey]
}
})
return hostInfo
} | javascript | {
"resource": ""
} | |
q31423 | Api | train | function Api(spec, options) {
if (!(this instanceof Api)) {
return new Api(spec, options);
}
if (typeof spec !== 'object') {
throw new Error('api spec must be an object');
}
options = options || {};
// path alias for both resourcePath and doc path
if (spec.path) {
if (!spec.resourcePath) spec.resourcePath = spec.path;
if (!options.path) options.path = spec.path;
delete spec.path;
}
// allow user to pass description in spec
if (spec.description) {
if (!options.description) options.description = spec.description;
delete spec.description;
}
// user resourcePath for doc path if not set
if (!options.path && spec.resourcePath) {
options.path = spec.resourcePath;
}
debug('create api %s', spec.resourcePath, spec);
this.env = new Environment();
this.spec = spec;
this.list = [];
this.options = options;
this.middleware = {};
this.models = {};
this.nicknames = {};
this.resources = {};
} | javascript | {
"resource": ""
} |
q31424 | train | function(self, obj)
{
self.stack = '';
for(var key in obj)
{
self[key] = obj[key];
}
} | javascript | {
"resource": ""
} | |
q31425 | train | function(s, p, o)
{
if(p in s)
{
if(s[p].constructor === Array)
{
s[p].push(o);
}
else
{
s[p] = [s[p], o];
}
}
else
{
s[p] = o;
}
} | javascript | {
"resource": ""
} | |
q31426 | train | function(ctx)
{
// TODO: reduce calls to this function by caching keywords in processor
// state
var rval =
{
'@id': '@id',
'@language': '@language',
'@literal': '@literal',
'@type': '@type'
};
if(ctx)
{
// gather keyword aliases from context
var keywords = {};
for(var key in ctx)
{
if(ctx[key].constructor === String && ctx[key] in rval)
{
keywords[ctx[key]] = key;
}
}
// overwrite keywords
for(var key in keywords)
{
rval[key] = keywords[key];
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31427 | train | function(ctx, term)
{
var rval = null;
if(term in ctx)
{
if(ctx[term].constructor === String)
{
rval = ctx[term];
}
else if(ctx[term].constructor === Object && '@id' in ctx[term])
{
rval = ctx[term]['@id'];
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31428 | train | function(ctx, iri, usedCtx)
{
var rval = null;
// check the context for a term that could shorten the IRI
// (give preference to terms over prefixes)
for(var key in ctx)
{
// skip special context keys (start with '@')
if(key.length > 0 && key[0] !== '@')
{
// compact to a term
if(iri === _getTermIri(ctx, key))
{
rval = key;
if(usedCtx !== null)
{
usedCtx[key] = _clone(ctx[key]);
}
break;
}
}
}
// term not found, if term is @type, use keyword
if(rval === null && iri === '@type')
{
rval = _getKeywords(ctx)['@type'];
}
// term not found, check the context for a prefix
if(rval === null)
{
for(var key in ctx)
{
// skip special context keys (start with '@')
if(key.length > 0 && key[0] !== '@')
{
// see if IRI begins with the next IRI from the context
var ctxIri = _getTermIri(ctx, key);
if(ctxIri !== null)
{
var idx = iri.indexOf(ctxIri);
// compact to a prefix
if(idx === 0 && iri.length > ctxIri.length)
{
rval = key + ':' + iri.substr(ctxIri.length);
if(usedCtx !== null)
{
usedCtx[key] = _clone(ctx[key]);
}
break;
}
}
}
}
}
// could not compact IRI
if(rval === null)
{
rval = iri;
}
return rval;
} | javascript | {
"resource": ""
} | |
q31429 | train | function(ctx, term, usedCtx)
{
var rval = term;
// get JSON-LD keywords
var keywords = _getKeywords(ctx);
// 1. If the property has a colon, it is a prefix or an absolute IRI:
var idx = term.indexOf(':');
if(idx !== -1)
{
// get the potential prefix
var prefix = term.substr(0, idx);
// expand term if prefix is in context, otherwise leave it be
if(prefix in ctx)
{
// prefix found, expand property to absolute IRI
var iri = _getTermIri(ctx, prefix);
rval = iri + term.substr(idx + 1);
if(usedCtx !== null)
{
usedCtx[prefix] = _clone(ctx[prefix]);
}
}
}
// 2. If the property is in the context, then it's a term.
else if(term in ctx)
{
rval = _getTermIri(ctx, term);
if(usedCtx !== null)
{
usedCtx[term] = _clone(ctx[term]);
}
}
// 3. The property is a keyword.
else
{
for(var key in keywords)
{
if(term === keywords[key])
{
rval = key;
break;
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31430 | train | function(ctx)
{
// sort keys
var rval = {};
var keys = Object.keys(ctx).sort();
for(var k in keys)
{
var key = keys[k];
rval[key] = ctx[key];
}
return rval;
} | javascript | {
"resource": ""
} | |
q31431 | train | function(value)
{
var rval = false;
// Note: A value is a subject if all of these hold true:
// 1. It is an Object.
// 2. It is not a literal.
// 3. It has more than 1 key OR any existing key is not '@id'.
if(value !== null && value.constructor === Object && !('@literal' in value))
{
var keyCount = Object.keys(value).length;
rval = (keyCount > 1 || !('@id' in value));
}
return rval;
} | javascript | {
"resource": ""
} | |
q31432 | train | function(v1, v2)
{
var rval = 0;
if(v1.constructor === Array && v2.constructor === Array)
{
for(var i = 0; i < v1.length && rval === 0; ++i)
{
rval = _compare(v1[i], v2[i]);
}
}
else
{
rval = (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0));
}
return rval;
} | javascript | {
"resource": ""
} | |
q31433 | train | function(o1, o2, key)
{
var rval = 0;
if(key in o1)
{
if(key in o2)
{
rval = _compare(o1[key], o2[key]);
}
else
{
rval = -1;
}
}
else if(key in o2)
{
rval = 1;
}
return rval;
} | javascript | {
"resource": ""
} | |
q31434 | train | function(o1, o2)
{
var rval = 0;
if(o1.constructor === String)
{
if(o2.constructor !== String)
{
rval = -1;
}
else
{
rval = _compare(o1, o2);
}
}
else if(o2.constructor === String)
{
rval = 1;
}
else
{
rval = _compareObjectKeys(o1, o2, '@literal');
if(rval === 0)
{
if('@literal' in o1)
{
rval = _compareObjectKeys(o1, o2, '@type');
if(rval === 0)
{
rval = _compareObjectKeys(o1, o2, '@language');
}
}
// both are '@id' objects
else
{
rval = _compare(o1['@id'], o2['@id']);
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31435 | train | function(a, b)
{
var rval = 0;
/*
3. For each property, compare sorted object values.
3.1. The bnode with fewer objects is first.
3.2. For each object value, compare only literals and non-bnodes.
3.2.1. The bnode with fewer non-bnodes is first.
3.2.2. The bnode with a string object is first.
3.2.3. The bnode with the alphabetically-first string is first.
3.2.4. The bnode with a @literal is first.
3.2.5. The bnode with the alphabetically-first @literal is first.
3.2.6. The bnode with the alphabetically-first @type is first.
3.2.7. The bnode with a @language is first.
3.2.8. The bnode with the alphabetically-first @language is first.
3.2.9. The bnode with the alphabetically-first @id is first.
*/
for(var p in a)
{
// skip IDs (IRIs)
if(p !== '@id')
{
// step #3.1
var lenA = (a[p].constructor === Array) ? a[p].length : 1;
var lenB = (b[p].constructor === Array) ? b[p].length : 1;
rval = _compare(lenA, lenB);
// step #3.2.1
if(rval === 0)
{
// normalize objects to an array
var objsA = a[p];
var objsB = b[p];
if(objsA.constructor !== Array)
{
objsA = [objsA];
objsB = [objsB];
}
// compare non-bnodes (remove bnodes from comparison)
objsA = objsA.filter(function(e) {return !_isNamedBlankNode(e);});
objsB = objsB.filter(function(e) {return !_isNamedBlankNode(e);});
rval = _compare(objsA.length, objsB.length);
}
// steps #3.2.2-3.2.9
if(rval === 0)
{
objsA.sort(_compareObjects);
objsB.sort(_compareObjects);
for(var i = 0; i < objsA.length && rval === 0; ++i)
{
rval = _compareObjects(objsA[i], objsB[i]);
}
}
if(rval !== 0)
{
break;
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31436 | train | function(prefix)
{
var count = -1;
var ng = {
next: function()
{
++count;
return ng.current();
},
current: function()
{
return '_:' + prefix + count;
},
inNamespace: function(iri)
{
return iri.indexOf('_:' + prefix) === 0;
}
};
return ng;
} | javascript | {
"resource": ""
} | |
q31437 | train | function(parent, parentProperty, value, subjects)
{
var flattened = null;
if(value === null)
{
// drop null values
}
else if(value.constructor === Array)
{
// list of objects or a disjoint graph
for(var i in value)
{
_flatten(parent, parentProperty, value[i], subjects);
}
}
else if(value.constructor === Object)
{
// already-expanded value or special-case reference-only @type
if('@literal' in value || parentProperty === '@type')
{
flattened = _clone(value);
}
// graph literal/disjoint graph
else if(value['@id'].constructor === Array)
{
// cannot flatten embedded graph literals
if(parent !== null)
{
throw {
message: 'Embedded graph literals cannot be flattened.'
};
}
// top-level graph literal
for(var idx in value['@id'])
{
_flatten(parent, parentProperty, value['@id'][idx], subjects);
}
}
// regular subject
else
{
// create or fetch existing subject
var subject;
if(value['@id'] in subjects)
{
// FIXME: '@id' might be a graph literal (as {})
subject = subjects[value['@id']];
}
else
{
// FIXME: '@id' might be a graph literal (as {})
subject = {'@id': value['@id']};
subjects[value['@id']] = subject;
}
flattened = {'@id': subject['@id']};
// flatten embeds
for(var key in value)
{
var v = value[key];
// drop null values, skip @id (it is already set above)
if(v !== null && key !== '@id')
{
if(key in subject)
{
if(subject[key].constructor !== Array)
{
subject[key] = [subject[key]];
}
}
else
{
subject[key] = [];
}
_flatten(subject[key], key, v, subjects);
if(subject[key].length === 1)
{
// convert subject[key] to object if it has only 1
subject[key] = subject[key][0];
}
}
}
}
}
// string value
else
{
flattened = value;
}
// add flattened value to parent
if(flattened !== null && parent !== null)
{
if(parent.constructor === Array)
{
// do not add duplicate IRIs for the same property
var duplicate = false;
if(flattened.constructor === Object && '@id' in flattened)
{
duplicate = (parent.filter(function(e)
{
return (e.constructor === Object && '@id' in e &&
e['@id'] === flattened['@id']);
}).length > 0);
}
if(!duplicate)
{
parent.push(flattened);
}
}
else
{
parent[parentProperty] = flattened;
}
}
} | javascript | {
"resource": ""
} | |
q31438 | train | function(b)
{
var rval = '';
var first = true;
for(var p in b)
{
if(p !== '@id')
{
if(first)
{
first = false;
}
else
{
rval += '|';
}
// property
rval += '<' + p + '>';
// object(s)
var objs = (b[p].constructor === Array) ? b[p] : [b[p]];
for(var oi in objs)
{
var o = objs[oi];
if(o.constructor === Object)
{
// ID (IRI)
if('@id' in o)
{
if(_isBlankNodeIri(o['@id']))
{
rval += '_:';
}
else
{
rval += '<' + o['@id'] + '>';
}
}
// literal
else
{
rval += '"' + o['@literal'] + '"';
// type literal
if('@type' in o)
{
rval += '^^<' + o['@type'] + '>';
}
// language literal
else if('@language' in o)
{
rval += '@' + o['@language'];
}
}
}
// plain literal
else
{
rval += '"' + o + '"';
}
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31439 | train | function(input, frame)
{
var rval = false;
// check if type(s) are specified in frame and input
var type = '@type';
if('@type' in frame &&
input.constructor === Object && type in input)
{
var tmp = (input[type].constructor === Array) ?
input[type] : [input[type]];
var types = (frame[type].constructor === Array) ?
frame[type] : [frame[type]];
for(var t = 0; t < types.length && !rval; ++t)
{
type = types[t];
for(var i in tmp)
{
if(tmp[i] === type)
{
rval = true;
break;
}
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31440 | train | function(input, frame)
{
var rval = false;
// frame must not have a specific type
var type = '@type';
if(!(type in frame))
{
// get frame properties that must exist on input
var props = Object.keys(frame).filter(function(e)
{
// filter non-keywords
return e.indexOf('@') !== 0;
});
if(props.length === 0)
{
// input always matches if there are no properties
rval = true;
}
// input must be a subject with all the given properties
else if(input.constructor === Object && '@id' in input)
{
rval = true;
for(var i in props)
{
if(!(props[i] in input))
{
rval = false;
break;
}
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31441 | train | function(iri)
{
var iris = Object.keys(embeds);
for(var i in iris)
{
i = iris[i];
if(i in embeds && embeds[i].parent !== null &&
embeds[i].parent['@id'] === iri)
{
delete embeds[i];
removeDependents(i);
}
}
} | javascript | {
"resource": ""
} | |
q31442 | train | function(
subjects, input, frame, embeds, autoembed, parent, parentKey, options)
{
var rval = null;
// prepare output, set limit, get array of frames
var limit = -1;
var frames;
if(frame.constructor === Array)
{
rval = [];
frames = frame;
if(frames.length === 0)
{
frames.push({});
}
}
else
{
frames = [frame];
limit = 1;
}
// iterate over frames adding input matches to list
var values = [];
for(var i = 0; i < frames.length && limit !== 0; ++i)
{
// get next frame
frame = frames[i];
if(frame.constructor !== Object)
{
throw {
message: 'Invalid JSON-LD frame. ' +
'Frame must be an object or an array.',
frame: frame
};
}
// create array of values for each frame
values[i] = [];
for(var n = 0; n < input.length && limit !== 0; ++n)
{
// add input to list if it matches frame specific type or duck-type
var next = input[n];
if(_isType(next, frame) || _isDuckType(next, frame))
{
values[i].push(next);
--limit;
}
}
}
// for each matching value, add it to the output
for(var i1 in values)
{
for(var i2 in values[i1])
{
frame = frames[i1];
var value = values[i1][i2];
// if value is a subject, do subframing
if(_isSubject(value))
{
value = _subframe(
subjects, value, frame, embeds, autoembed,
parent, parentKey, options);
}
// add value to output
if(rval === null)
{
rval = value;
}
else
{
// determine if value is a reference to an embed
var isRef = (_isReference(value) && value['@id'] in embeds);
// push any value that isn't a parentless reference
if(!(parent === null && isRef))
{
rval.push(value);
}
}
}
}
return rval;
} | javascript | {
"resource": ""
} | |
q31443 | RDFMakeTerm | train | function RDFMakeTerm(formula,val, canonicalize) {
if (typeof val != 'object') {
if (typeof val == 'string')
return new N3Parser.Literal(val);
if (typeof val == 'number')
return new N3Parser.Literal(val); // @@ differet types
if (typeof val == 'boolean')
return new N3Parser.Literal(val?"1":"0", undefined,
N3Parser.Symbol.prototype.XSDboolean);
else if (typeof val == 'number')
return new N3Parser.Literal(''+val); // @@ datatypes
else if (typeof val == 'undefined')
return undefined;
else // @@ add converting of dates and numbers
throw "Can't make Term from " + val + " of type " + typeof val;
}
return val;
} | javascript | {
"resource": ""
} |
q31444 | Environment | train | function Environment(options) {
if (!(this instanceof Environment)) {
return new Environment(options);
}
// defaults
options = lodash.defaults(options || {}, {
setup: true,
});
this.env = jjv();
this.env.defaultOptions.checkRequired = true;
this.env.defaultOptions.useDefault = true;
this.env.defaultOptions.useCoerce = false;
this._jjve = jjve(this.env);
if (options.setup) this.setup();
} | javascript | {
"resource": ""
} |
q31445 | updateBrokerCertChain | train | function updateBrokerCertChain (configDir, certChainFile, certChain, verbosity) {
var caBundleFileName = util.getConfigFilePath(configDir, certChainFile)
if (verbosity) {
console.log('Updating certs in ' + caBundleFileName)
}
provisionUtil.saveToFile(caBundleFileName, certChain)
} | javascript | {
"resource": ""
} |
q31446 | updateBrokerListInConfigFile | train | function updateBrokerListInConfigFile (configFileName, brokerLines, verbosity) {
if (verbosity) {
console.log('Updating DXL config file at ' + configFileName)
}
var inBrokerSection = false
var linesAfterBrokerSection = []
var configFileData = util.getConfigFileData(configFileName)
// Replace the current contents of the broker section with the new broker
// lines. Preserve existing content in the file which relates to other
// sections - for example, the 'Certs' section.
var newConfigLines = configFileData.lines.reduce(
function (acc, line) {
if (line === '[Brokers]') {
inBrokerSection = true
acc.push(line)
} else {
if (inBrokerSection) {
// Skip over any existing lines in the broker section since these
// will be replaced.
if (line.match(/^\s*($|[;#])/)) {
// Preserve any empty/comment lines if there is another section
// after the Broker section. Comments may pertain to the content of
// the next section.
linesAfterBrokerSection.push(line)
} else if (line.match(/^\[.*]$/)) {
// A section after the broker section has been reached.
inBrokerSection = false
Array.prototype.push.apply(acc, brokerLines)
if (linesAfterBrokerSection.length === 0) {
newConfigLines.push(configFileData.lineSeparator)
} else {
Array.prototype.push.apply(acc,
linesAfterBrokerSection)
}
acc.push(line)
} else {
// A broker config entry in the existing file, which will be
// replaced by the new broker lines, has been encountered. Any
// prior empty/comment lines which had been stored so far would
// be between broker config entries. Those lines should be dropped
// since they might not line up with the new broker list data.
linesAfterBrokerSection = []
}
} else {
acc.push(line)
}
}
return acc
}, []
)
if (inBrokerSection) {
Array.prototype.push.apply(newConfigLines, brokerLines)
}
// Flatten the broker line array back into a string, delimited using the
// line separator which appeared to be used in the original config file.
var newConfig = newConfigLines.join(configFileData.lineSeparator)
if (inBrokerSection) {
newConfig += configFileData.lineSeparator
}
provisionUtil.saveToFile(configFileName, newConfig)
} | javascript | {
"resource": ""
} |
q31447 | train | function(models, options) {
var i, l, index, model;
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, l = models.length; i < l; i++) {
model = this.getByCid(models[i]) || this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byCid[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
} | javascript | {
"resource": ""
} | |
q31448 | add | train | function add(table, inp, state, action, next) {
table[state<<8|inp] = ((action | 0) << 4) | ((next === undefined) ? state : next);
} | javascript | {
"resource": ""
} |
q31449 | add_list | train | function add_list(table, inps, state, action, next) {
for (var i=0; i<inps.length; i++)
add(table, inps[i], state, action, next);
} | javascript | {
"resource": ""
} |
q31450 | AnsiParser | train | function AnsiParser(terminal) {
this.initial_state = 0; // 'GROUND' is default
this.current_state = this.initial_state|0;
// clone global transition table
this.transitions = new Uint8Array(4095);
this.transitions.set(TRANSITION_TABLE);
// global non pushable buffers for multiple parse invocations
this.osc = '';
this.params = [0];
this.collected = '';
// back reference to terminal
this.term = terminal || {};
var instructions = ['inst_p', 'inst_o', 'inst_x', 'inst_c',
'inst_e', 'inst_H', 'inst_P', 'inst_U', 'inst_E'];
for (var i=0; i<instructions.length; ++i)
if (!(instructions[i] in this.term))
this.term[instructions[i]] = function() {};
} | javascript | {
"resource": ""
} |
q31451 | getSetting | train | function getSetting (config, section, setting, required, readFromFile,
configPath) {
if (typeof (required) === 'undefined') { required = true }
if (typeof (configPath) === 'undefined') { configPath = null }
if (!config[section]) {
if (required) {
throw new DxlError('Required section not found in config: ' +
section)
} else {
return null
}
}
if (!config[section][setting]) {
if (required) {
throw new DxlError('Required setting not found in config: ' +
setting)
} else {
return null
}
}
var value = config[section][setting]
if (readFromFile) {
var fileToRead = util.getConfigFilePath(configPath, value)
if (fs.existsSync(fileToRead)) {
try {
value = fs.readFileSync(fileToRead)
} catch (err) {
throw new DxlError('Unable to read file for ' + setting + ': ' +
err.message)
}
} else {
throw new DxlError('Unable to locate file for ' + setting +
': ' + value)
}
}
return value
} | javascript | {
"resource": ""
} |
q31452 | mergeOptions | train | function mergeOptions(parsedOptions) {
return Object.keys(autoflowOptions).reduce(function (accum, k) {
if (!accum[k]) accum[k] = autoflowOptions[k];
return accum;
}, parsedOptions);
} | javascript | {
"resource": ""
} |
q31453 | describe | train | function describe(ctx) {
try {
return ctx.operation.spec.method + ' ' +
ctx.operation.resource.spec.path + ' ';
} catch (err) {
return '';
}
} | javascript | {
"resource": ""
} |
q31454 | validate | train | function validate(res, result) {
if (!result) return true;
var err = new Error('Validation failed');
try {
err.errors = result.errors();
} catch (err) {
err.errors = [result.validation];
}
err.expose = true;
err.statusCode = 400;
err.toJSON = function() {
return {
message: this.message,
errors: this.errors,
};
};
res.sf.reply(err);
} | javascript | {
"resource": ""
} |
q31455 | lookup | train | function lookup(obj, type, name) {
while (obj) {
if (obj[type] && obj[type].hasOwnProperty(name)) {
return obj[type][name];
}
obj = obj.parent;
}
} | javascript | {
"resource": ""
} |
q31456 | validateOptions | train | function validateOptions(operation, type, useCoerce) {
var options = { useCoerce: useCoerce };
// capitalize type
var suffix = type[0].toUpperCase() + type.slice(1);
// Get remove option (ex: options.removeHeader)
var removeAdditional = lookup(operation, 'options', 'remove' + suffix);
if (typeof removeAdditional === 'undefined') {
removeAdditional = true;
}
options.removeAdditional = !!removeAdditional;
return options;
} | javascript | {
"resource": ""
} |
q31457 | before | train | function before(ctx) {
var fn = lookup(ctx.operation, 'middleware', 'before');
var prefix = describe(ctx);
if (fn) {
return fn(ctx);
} else {
debug(prefix + 'before middleware disabled (not defined)');
}
} | javascript | {
"resource": ""
} |
q31458 | header | train | function header(ctx) {
var prefix = describe(ctx);
var schema = transform.parameters(ctx.operation.spec, 'header');
if (!schema) {
debug(prefix + 'header middleware disabled (no schema)');
return;
}
var env = ctx.operation.resource.api.env;
var options = validateOptions(ctx.operation, 'header', true);
// Create a list of headers to split on comma
var allowMultiple = {};
ctx.operation.spec.parameters.forEach(function(parameter) {
if (parameter.paramType === 'header' && parameter.allowMultiple) {
var name = parameter.name.toLowerCase();
allowMultiple[name] = constants.singleHeaders.indexOf(name) < 0;
}
});
schema = {
type: 'object',
properties: { header: schema },
required: ['header'],
};
return function(req, res, next) {
var header = lodash.cloneDeep(req.headers);
// This only works for small subset of headers before Node v0.11
lodash.forOwn(header, function(value, name) {
if (allowMultiple[name]) header[name] = value.split(', ');
});
if (validate(res, env.validate(schema, { header: header }, options))) {
req.sf.header = header;
next();
}
};
} | javascript | {
"resource": ""
} |
q31459 | produces | train | function produces(ctx) {
var mimes = ctx.operation.spec.produces ||
ctx.operation.resource.api.spec.produces || [];
var prefix = describe(ctx);
if (!mimes.length) {
debug(prefix + 'produces validation disabled (no produces)');
}
return function(req, res, next) {
req.sf.accept = accepts(req);
if (!mimes.length) return next();
var types = req.sf.accept.types(mimes);
if (!types) {
debug(prefix + 'produces mime not supported: "%s" not in "%s"',
req.headers.accept, mimes);
var err = new Error('Not acceptable (' +
req.headers.accept + '), supports: ' +
mimes.join(', '));
err.statusCode = 406;
err.expose = true;
return res.sf.reply(err);
}
if (typeof types === 'string') types = [types];
types.some(function(type) {
if (!req.sf.router.encoder[type]) return;
res.sf.produce = {
encoder: req.sf.router.encoder[type],
mime: type
};
return true;
});
next();
};
} | javascript | {
"resource": ""
} |
q31460 | query | train | function query(ctx) {
var prefix = describe(ctx);
var schema = transform.parameters(ctx.operation.spec, 'query');
if (!schema) {
debug(prefix + 'query middleware disabled (no schema)');
return;
}
var env = ctx.operation.resource.api.env;
var options = validateOptions(ctx.operation, 'query', true);
schema = {
type: 'object',
properties: { query: schema },
required: ['query'],
};
return function(req, res, next) {
var query = lodash.clone(req.sf.url.query);
if (validate(res, env.validate(schema, { query: query }, options))) {
req.sf.query = query;
next();
}
};
} | javascript | {
"resource": ""
} |
q31461 | authenticate | train | function authenticate(ctx) {
var fn = lookup(ctx.operation, 'middleware', 'authenticate');
var prefix = describe(ctx);
if (fn) {
return fn(ctx);
} else {
debug(prefix + 'authenticate middleware disabled (not defined)');
}
} | javascript | {
"resource": ""
} |
q31462 | consumes | train | function consumes(ctx) {
if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return;
var mimes = ctx.operation.spec.consumes ||
ctx.operation.resource.api.spec.consumes || [];
var prefix = describe(ctx);
if (!mimes.length) {
debug(prefix + 'consumes middleware disabled (no consumes)');
return;
}
return function(req, res, next) {
if (req.sf.text && !is(req, mimes)) {
debug(prefix + 'consumes mime not supported: "%s" not in "%s"',
req.headers['content-type'], mimes);
var err = new Error('Unsupported Content-Type (' +
req.headers['content-type'] + '), supports: ' +
mimes.join(', '));
err.statusCode = 415;
err.expose = true;
return res.sf.reply(err);
}
next();
};
} | javascript | {
"resource": ""
} |
q31463 | raw | train | function raw(ctx) {
if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return;
var limit = lookup(ctx.operation, 'options', 'bodyLimit') || '100kb';
return function(req, res, next) {
rawBody(req, {
length: req.headers['content-length'],
limit: limit,
encoding: http.CHARSET
}, function(err, text) {
if (err) {
if (err.statusCode) return res.sf.reply(err);
return next(err);
}
req.sf.text = text;
// Mimic body-parser for use by proxies
if (text && text.length) {
req.body = text;
}
next();
});
};
} | javascript | {
"resource": ""
} |
q31464 | form | train | function form(ctx) {
if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return;
var mimes = ctx.operation.spec.consumes ||
ctx.operation.resource.api.spec.consumes || [];
var mime = 'application/x-www-form-urlencoded';
var prefix = describe(ctx);
var decode = ctx.router.decoder[mime];
if (mimes.indexOf(mime) === -1) {
debug(prefix + 'form middleware disabled (no consumes)');
return;
}
var env = ctx.operation.resource.api.env;
var options = validateOptions(ctx.operation, 'form', true);
var schema = transform.parameters(ctx.operation.spec, 'form');
if (!schema) {
debug(prefix + 'form middleware disabled (no schema)');
return;
}
schema = {
type: 'object',
properties: { form: schema },
required: ['form'],
};
return function(req, res, next) {
if (is(req, [mime])) {
var form;
try {
form = decode(req.sf.text);
} catch (err) {
return next(err);
}
form = req.sf.form = lodash.clone(form);
if (validate(res, env.validate(schema, { form: form }, options))) {
next();
}
} else {
next();
}
};
} | javascript | {
"resource": ""
} |
q31465 | body | train | function body(ctx) {
if (['HEAD', 'GET'].indexOf(ctx.operation.spec.method) >= 0) return;
var consumeMimes = ctx.operation.spec.consumes ||
ctx.operation.resource.api.spec.consumes || [];
var mimes = lodash.intersection(consumeMimes,
Object.keys(ctx.router.decoder));
var prefix = describe(ctx);
if (!mimes.length) {
debug(prefix + 'body middleware disabled (no consumes)');
return;
}
var env = ctx.operation.resource.api.env;
var options = validateOptions(ctx.operation, 'form', false);
var schema = transform.parameters(ctx.operation.spec, 'body');
if (!schema) {
debug(prefix + 'body middleware disabled (no schema)');
return;
}
return function(req, res, next) {
var mime = is(req, mimes);
var bodyErr;
if (mime) {
var body;
if (req.sf.text) {
try {
body = ctx.router.decoder[mime](req.sf.text);
} catch (err) {
debug(prefix + 'body decoder failed', err);
bodyErr = new Error('Decode body failed');
bodyErr.statusCode = 400;
bodyErr.parent = err;
bodyErr.expose = true;
return next(bodyErr);
}
} else if (schema.required) {
bodyErr = new Error('Body required');
bodyErr.statusCode = 400;
bodyErr.expose = true;
return next(bodyErr);
} else {
return next();
}
req.sf.body = body;
if (validate(res, env.validate(schema, { body: body }, options))) {
next();
}
} else if (schema.required) {
bodyErr = new Error('Body required');
bodyErr.statusCode = 400;
bodyErr.expose = true;
return next(bodyErr);
} else {
next();
}
};
} | javascript | {
"resource": ""
} |
q31466 | authorize | train | function authorize(ctx) {
var fn = lookup(ctx.operation, 'middleware', 'authorize');
var prefix = describe(ctx);
if (fn) {
return fn(ctx);
} else {
debug(prefix + 'authorize middleware disabled (not defined)');
}
} | javascript | {
"resource": ""
} |
q31467 | after | train | function after(ctx) {
var fn = lookup(ctx.operation, 'middleware', 'after');
var prefix = describe(ctx);
if (fn) {
return fn(ctx);
} else {
debug(prefix + 'after middleware disabled (not defined)');
}
} | javascript | {
"resource": ""
} |
q31468 | getScript | train | function getScript(cfg) {
var script = function(cfg) {
$('#J_Qrcode').qrcode({
'render': 'canvas',
'size': cfg.size || 150,
'color': '#3a3',
'text': cfg.text
});
var canvas = $('#J_Qrcode canvas')[0];
// here is the most important part because if you dont replace you will get a DOM 18 exception.
var imageData = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
endCallback(imageData);
};
return '(' + script.toString() + ')(' + JSON.stringify(cfg) + ');';
} | javascript | {
"resource": ""
} |
q31469 | startInlineServices | train | function startInlineServices() {
// Provide a webhook definition
var hook = {
name: 'Inline Sample',
events: ['message.sent'],
path: '/inline_sample_message_sent',
};
// Register this webhook with Layer's Services
webhooksServices.register({
secret: SECRET,
url: HOST + ':' + PORT,
hooks: [hook]
});
// Listen for events from Layer's Services, and call our callbackAsync with each event
webhooksServices.listen({
expressApp: app,
secret: SECRET,
hooks: [hook]
}, redis);
// Setup your callback to handle the webhook events
queue.process(hook.name, 50, function(job, done) {
console.log(new Date().toLocaleString() + ': Inline Sample: Message Received from ' + (job.data.message.sender.user_id || job.data.message.sender.name));
done();
});
} | javascript | {
"resource": ""
} |
q31470 | _typedParse | train | function _typedParse(loc, type, data, callback) {
switch(type.toLowerCase()) {
case 'text':
case 'plain':
case 'text/plain':
callback(null, data);
break;
case 'json':
case 'jsonld':
case 'json-ld':
case 'ld+json':
case 'application/json':
case 'application/ld+json':
try {
callback(null, JSON.parse(data));
}
catch(ex) {
callback({
message: 'Error parsing JSON.',
contentType: type,
url: loc,
exception: ex.toString()
});
}
break;
case 'xml':
case 'html':
case 'xhtml':
case 'text/html':
case 'application/xhtml+xml':
if(typeof jsdom === 'undefined') {
callback({
message: 'jsdom module not found.',
contentType: type,
url: loc
});
break;
}
if(typeof RDFa === 'undefined') {
callback({
message: 'RDFa module not found.',
contentType: type,
url: loc
});
break;
}
// input is RDFa
try {
jsdom.env({
html: data,
done: function(errors, window) {
if(errors && errors.length > 0) {
return callback({
message: 'DOM Errors:',
errors: errors,
url: loc
});
}
try {
// extract JSON-LD from RDFa
RDFa.attach(window.document);
jsonld.fromRDF(window.document.data,
{format: 'rdfa-api'}, callback);
}
catch(ex) {
// FIXME: expose RDFa/jsonld ex?
callback({
message: 'RDFa extraction error.',
contentType: type,
url: loc
});
}
}
});
}
catch(ex) {
// FIXME: expose jsdom(?) ex?
callback({
message: 'jsdom error.',
contentType: type,
url: loc
});
}
break;
default:
callback({
message: 'Unknown Content-Type.',
contentType: type,
url: loc
});
}
} | javascript | {
"resource": ""
} |
q31471 | requestProvisionConfig | train | function requestProvisionConfig (managementService, csr, verbosity, callback) {
managementService.request('Requesting client certificate', PROVISION_COMMAND,
{csrString: csr}, verbosity, callback)
} | javascript | {
"resource": ""
} |
q31472 | brokersForConfig | train | function brokersForConfig (brokerLines) {
return brokerLines.reduce(function (acc, brokerLine) {
var brokerElements = brokerLine.split('=')
if (brokerElements.length !== 2) {
throw new DxlError('Invalid key value pair for broker entry: ' +
brokerLine)
}
acc[brokerElements[0]] = brokerElements[1]
return acc
}, {})
} | javascript | {
"resource": ""
} |
q31473 | storeProvisionConfig | train | function storeProvisionConfig (config, configDir, filePrefix,
privateKeyFileName, verbosity) {
if (typeof config !== 'string') {
throw new DxlError('Unexpected data type for response: ' +
typeof config)
}
var configElements = config.split(',')
if (configElements.length < 3) {
throw new DxlError('Did not receive expected number of response ' +
'elements. Expected: 3, Received: ' + configElements.length +
'. Value: ' + config)
}
var brokerLines = configElements[2].split(
/[\r\n]+/).filter(function (brokerLine) {
return brokerLine.length > 0
}
)
var brokers = brokersForConfig(brokerLines)
var certFileName = filePrefix + '.crt'
var configString = ini.encode({
Certs: {
BrokerCertChain: DEFAULT_BROKER_CERT_CHAIN_FILE_NAME,
CertFile: path.basename(certFileName),
PrivateKey: path.basename(privateKeyFileName)
},
Brokers: brokers
}).replace(/\\;/g, ';')
var configFileName = path.join(configDir,
provisionUtil.DEFAULT_CONFIG_FILE_NAME)
if (verbosity) {
console.log('Saving DXL config file to ' + configFileName)
}
provisionUtil.saveToFile(configFileName, configString)
var caBundleFileName = path.join(configDir,
DEFAULT_BROKER_CERT_CHAIN_FILE_NAME)
if (verbosity) {
console.log('Saving ca bundle file to ' + caBundleFileName)
}
provisionUtil.saveToFile(caBundleFileName, configElements[0])
var fullCertFileName = path.join(configDir, certFileName)
if (verbosity) {
console.log('Saving client certificate file to ' + fullCertFileName)
}
provisionUtil.saveToFile(fullCertFileName, configElements[1])
} | javascript | {
"resource": ""
} |
q31474 | ManagementService | train | function ManagementService (hostInfo) {
if (!hostInfo.hostname) {
throw new TypeError('Hostname is required for management service requests')
}
if (!hostInfo.user) {
throw new TypeError('User name is required for management service requests')
}
if (!hostInfo.password) {
throw new TypeError('Password is required for management service requests')
}
this.hostname = hostInfo.hostname
this.port = hostInfo.port || ManagementService.DEFAULT_PORT
this.auth = hostInfo.user + ':' + hostInfo.password
this.trustStoreFile = hostInfo.truststore
} | javascript | {
"resource": ""
} |
q31475 | httpGet | train | function httpGet (description, currentRedirects, requestOptions, verbosity,
responseCallback) {
var requestUrl = toUrlString(requestOptions)
var responseBody = ''
if (verbosity > 1) {
console.log('HTTP request to: ' + requestUrl)
}
var request = https.get(requestOptions, function (response) {
if (verbosity > 1) {
console.log('HTTP response status code: ' + response.statusCode)
}
if (response.statusCode === 302) {
if (currentRedirects === HTTP_MAX_REDIRECTS) {
responseCallback(provisionUtil.createFormattedDxlError(
'Reached maximum redirects for request to ' + requestUrl, description)
)
} else {
var redirectLocation = response.headers.location
if (!redirectLocation) {
responseCallback(provisionUtil.createFormattedDxlError(
'Redirect with no location specified for ' +
requestUrl, description))
return
}
if (verbosity > 1) {
console.log('HTTP response redirect to: ' + redirectLocation)
}
var parsedRedirectLocation = url.parse(redirectLocation)
if ((parsedRedirectLocation.hostname &&
(parsedRedirectLocation.hostname !== requestOptions.hostname)) ||
(parsedRedirectLocation.port &&
(parsedRedirectLocation.port !== requestOptions.port))) {
responseCallback(provisionUtil.createFormattedDxlError(
'Redirect to different host or port not supported. ' +
'Original URL: ' + requestUrl +
'. Redirect URL: ' + redirectLocation + '.', description))
return
}
if (response.headers['set-cookie']) {
if (!requestOptions.headers) {
requestOptions.headers = {}
}
requestOptions.headers.cookie = response.headers['set-cookie']
}
requestOptions.path = response.headers.location
httpGet(description, currentRedirects + 1, requestOptions, verbosity,
responseCallback)
response.resume()
return
}
}
response.on('data', function (chunk) {
responseBody += chunk
})
response.on('end', function () {
if (response.statusCode >= 200 && response.statusCode <= 299) {
responseCallback(null, responseBody)
} else {
responseCallback(provisionUtil.createFormattedDxlError(
'Request to ' + requestUrl +
' failed with HTTP error code: ' + response.statusCode +
'. Reason: ' + response.statusMessage + '.', description))
}
})
})
request.on('error', function (error) {
responseCallback(provisionUtil.createFormattedDxlError(
'Error processing request to ' + requestUrl + ': ' + error,
description))
})
} | javascript | {
"resource": ""
} |
q31476 | Assemble | train | function Assemble(options) {
if (!(this instanceof Assemble)) {
return new Assemble(options);
}
Templates.call(this, options);
this.is('assemble');
this.initCore();
} | javascript | {
"resource": ""
} |
q31477 | train | function(e) {
this._tabReset();
if (e.which == 9) {
this.flags.keyTab = true;
if (e.shiftKey) { this.flags.keyShift = true; }
}
} | javascript | {
"resource": ""
} | |
q31478 | train | function(current, $scope) {
var $selfRef = this;
var selectables = $selfRef._tabItems($scope);
var nextIndex = 0;
if ($(current).length === 1){
var currentIndex = selectables.index(current);
if (currentIndex + 1 < selectables.length) {
nextIndex = currentIndex + 1;
}
}
return selectables.eq(nextIndex);
} | javascript | {
"resource": ""
} | |
q31479 | Operation | train | function Operation(spec, options, fn) {
if (typeof options === 'function') {
fn = [].slice.call(arguments).slice(1);
options = {};
} else if (Array.isArray(options)) {
fn = options;
options = {};
} else if (!Array.isArray(fn)) {
fn = [].slice.call(arguments).slice(2);
}
if (!(this instanceof Operation)) {
return new Operation(spec, options, fn);
}
if (typeof spec !== 'object') {
throw new Error('operation spec must be an object');
}
debug('create operation', spec);
this.spec = spec;
this.options = options || {};
this.fn = fn;
this.middleware = {};
} | javascript | {
"resource": ""
} |
q31480 | train | function(n, symbol, dp, callback) {
if (n < 0 || n > 7) {
throw "Invalid digit number";
}
if (!(symbol in MAX7219._Font)) {
throw "Invalid symbol string";
}
var byte = MAX7219._Font[symbol] | (dp ? (1 << 7) : 0);
this._shiftOut(MAX7219._Registers["Digit" + n], byte, callback);
} | javascript | {
"resource": ""
} | |
q31481 | train | function(callback) {
if (!this._decodeModes) {
this.setDecodeNone();
}
for (var i = 0; i < this._decodeModes.length; i++) {
var mode = this._decodeModes[i];
if (mode == 0) {
this.setDigitSegmentsByte(i, 0x00, callback);
} else {
this.setDigitSymbol(i, " ", false, callback);
}
}
} | javascript | {
"resource": ""
} | |
q31482 | train | function(brightness, callback) {
if (brightness < 0 || brightness > 15) {
throw "Invalid brightness number";
}
this._shiftOut(MAX7219._Registers.Intensity, brightness, callback);
} | javascript | {
"resource": ""
} | |
q31483 | train | function(limit, callback) {
if (limit < 1 || limit > 8) {
throw "Invalid scan limit number";
}
this._shiftOut(MAX7219._Registers.ScanLimit, limit - 1, callback);
} | javascript | {
"resource": ""
} | |
q31484 | train | function(firstByte, secondByte, callback) {
if (!this._spi) {
throw "SPI device not initialized";
}
for (var i = 0; i < this._buffer.length; i += 2) {
this._buffer[i] = MAX7219._Registers.NoOp;
this._buffer[i + 1] = 0x00;
}
var offset = this._activeController * 2;
this._buffer[offset] = firstByte;
this._buffer[offset + 1] = secondByte;
this._spi.write(this._buffer, callback);
} | javascript | {
"resource": ""
} | |
q31485 | registerService | train | function registerService (client, service) {
clearTtlTimeout(service)
if (client.connected) {
var request = new Request(DXL_SERVICE_REGISTER_REQUEST_TOPIC)
request.payload = JSON.stringify({
serviceType: service.info.serviceType,
metaData: service.info.metadata,
requestChannels: service.info.topics,
ttlMins: service.info.ttl,
serviceGuid: service.info.serviceId
})
request.destinationTenantGuids = service.info.destinationTenantGuids
client.asyncRequest(request,
function (error) {
if (service.onFirstRegistrationCallback) {
service.onFirstRegistrationCallback(error)
service.onFirstRegistrationCallback = null
}
})
service.ttlTimeout = setTimeout(registerService,
service.info.ttl * 60 * 1000, client, service)
}
} | javascript | {
"resource": ""
} |
q31486 | unregisterService | train | function unregisterService (client, service, callback) {
if (client.connected) {
var request = new Request(DXL_SERVICE_UNREGISTER_REQUEST_TOPIC)
request.payload = JSON.stringify({
serviceGuid: service.info.serviceId})
var unregisterCallback = null
if (callback) {
unregisterCallback = function (error) { callback(error) }
}
client.asyncRequest(request, unregisterCallback)
}
Object.keys(service.callbacksByTopic).forEach(function (topic) {
service.callbacksByTopic[topic].forEach(function (callback) {
client.removeRequestCallback(topic, callback)
})
})
clearTtlTimeout(service)
} | javascript | {
"resource": ""
} |
q31487 | findOpenSslBin | train | function findOpenSslBin (opensslBin) {
if (opensslBin) {
if (!fs.existsSync(opensslBin)) {
throw new DxlError('Unable to find openssl at: ' + opensslBin)
}
} else {
opensslBin = which.sync('openssl', {nothrow: true})
if (!opensslBin && (os.platform() === 'win32')) {
opensslBin = DEFAULT_OPENSSL_WIN32_INSTALL_DIRS.reduce(
function (acc, candidatePath) {
candidatePath = path.join(candidatePath, 'openssl.exe')
if (!acc && fs.existsSync(candidatePath)) {
acc = candidatePath
}
return acc
},
null
)
}
if (!opensslBin) {
throw new DxlError('Unable to find openssl from system path')
}
}
return opensslBin
} | javascript | {
"resource": ""
} |
q31488 | indentedLogOutput | train | function indentedLogOutput (logOutput) {
logOutput = logOutput.toString()
if (logOutput) {
logOutput = '\n ' + logOutput.toString().replace(/(\r?\n)/g, '$1 ')
}
return logOutput
} | javascript | {
"resource": ""
} |
q31489 | buildCsrSubject | train | function buildCsrSubject (commonName, options) {
var subject = '/CN=' + commonName
Object.keys(SUBJECT_ATTRIBUTES).forEach(function (key) {
if (options[key]) {
subject = subject + '/' + SUBJECT_ATTRIBUTES[key].name + '=' +
options[key]
}
})
return subject
} | javascript | {
"resource": ""
} |
q31490 | train | function (description, commandArgs, opensslBin, verbosity,
input) {
opensslBin = findOpenSslBin(opensslBin)
if (verbosity) {
if (description) {
console.log(description)
}
if (verbosity > 1) {
console.log("Running openssl. Path: '" + opensslBin +
"', Command: '" + commandArgs.join(' '))
}
}
var command = childProcess.spawnSync(opensslBin, commandArgs,
input ? {input: input} : {})
if (command.stdout && (verbosity > 1)) {
console.log('OpenSSL OUTPUT LOG: ' + indentedLogOutput(command.stdout))
}
if (command.stderr && ((command.status !== 0) || (verbosity > 1))) {
provisionUtil.logError(indentedLogOutput(command.stderr),
{header: 'OpenSSL ERROR LOG', verbosity: verbosity})
}
if (command.status !== 0) {
var errorMessage = 'openssl execution failed'
if (command.error) {
errorMessage = command.error.message
}
if (command.status) {
errorMessage = errorMessage + ', status code: ' + command.status
}
throw provisionUtil.createFormattedDxlError(errorMessage, description)
}
return command
} | javascript | {
"resource": ""
} | |
q31491 | adjust | train | function adjust(r, e, time, def) {
const requested = r[def.field];
const current = def.get(time, e.options);
if(r.relationToCurrent === 'auto') {
if(requested < current) {
time = def.set(def.adjuster(time, 1, e.options), requested, e.options);
} else {
time = def.set(time, requested, e.options);
}
} else if(r.relationToCurrent === 'current-period') {
if(def.parentData(r) && requested < current) {
time = def.set(def.adjuster(time, 1, e.options), requested, e.options);
} else {
time = def.set(time, requested, e.options);
}
} else if(r.relationToCurrent === 'future') {
if(requested <= current) {
time = def.set(def.adjuster(time, 1, e.options), requested, e.options);
} else {
time = def.set(time, requested, e.options);
}
} else if(r.relationToCurrent === 'past') {
if(requested >= current) {
time = def.set(def.adjuster(time, -1, e.options), requested, e.options);
} else {
time = def.set(time, requested, e.options);
}
}
return time;
} | javascript | {
"resource": ""
} |
q31492 | traverse | train | function traverse(value, cbs) {
cbs = cbs || {};
if (Array.isArray(value)) {
if (cbs.beforeArray) value = cbs.beforeArray(value, cbs);
value = value.map(function(v) {
return traverse(v, cbs);
});
if (cbs.afterArray) value = cbs.afterArray(value, cbs);
} else if (typeof value === 'object') {
if (cbs.beforeObject) value = cbs.beforeObject(value, cbs);
Object.keys(value).forEach(function(key) {
value[key] = traverse(value[key], cbs);
});
if (cbs.afterObject) value = cbs.afterObject(value, cbs);
}
return value;
} | javascript | {
"resource": ""
} |
q31493 | transform | train | function transform(value, options) {
options = options || {};
return traverse(value, {
beforeObject: function(v) {
if (options.removeFormats &&
typeof v.format === 'string' &&
typeof v.type === 'string' &&
v.type !== 'string') {
delete v.format;
}
return v;
},
afterObject: function(v) {
if (options.convertRefs &&
typeof v.type === 'string' &&
constants.notModel.indexOf(v.type) < 0) {
return { $ref: v.type };
}
return v;
},
});
} | javascript | {
"resource": ""
} |
q31494 | model | train | function model(spec) {
var schema = lodash.cloneDeep(spec);
delete schema.id;
schema = transform(schema, {
removeFormats: true,
});
return schema;
} | javascript | {
"resource": ""
} |
q31495 | getText | train | function getText(msg) {
return msg.parts.filter(function (part) {
return part.mime_type === 'text/plain';
}).map(function (part) {
return part.body;
}).join('; ');
} | javascript | {
"resource": ""
} |
q31496 | rollTheDie | train | function rollTheDie(msg, text) {
var conversationId = msg.conversation.id;
var matches = text.match(/die (\d+)/i);
if (matches && matches[1]) {
var dieCount = Number(matches[1]);
var result = [];
if (dieCount > 20) {
layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'So much death is a terrible thing to ask of me. You should be ashamed!');
} else {
for (var i = 0; i < dieCount; i++) {
result.push(Math.floor(Math.random() * 6) + 1); // Simple 6 sided die
}
layerClient.messages.sendTextFromName(conversationId, 'Die-bot', 'Rolled a ' + result.join(', ').replace(/(.*),(.*)/, '$1 and$2'));
}
}
} | javascript | {
"resource": ""
} |
q31497 | foodTalk | train | function foodTalk (msg, text) {
var conversationId = msg.conversation.id;
var matches = text.match(/eat my (.+?)\b/i);
if (matches) {
layerClient.messages.sendTextFromName(conversationId, 'Food-bot', 'My ' + matches[1] + ' taste a lot better than yours');
} else {
var messages = [
'I\'m eating yummy carbon',
'I\'m eating yummy silicon',
'I\'m eating your keyboard. Yummy!',
'I\'m nibbling on your screen. Sorry about the dead pixels.',
'I\'m eating your fingers. Seriously, you should get more of these!',
'Feed me....'
];
layerClient.messages.sendTextFromName(conversationId, 'Food-bot', messages[Math.floor(Math.random() * 6)]);
}
} | javascript | {
"resource": ""
} |
q31498 | logEvents | train | function logEvents(flowFn, eventWildcard) {
if (typeof(flowFn) !== 'function') { // only wildcard provided
eventWildcard = flowFn;
flowFn = undefined;
}
if (!flowFn) flowFn = autoflow; // use global
trackTasks();
return logEventsMod.logEvents(flowFn, eventWildcard);
} | javascript | {
"resource": ""
} |
q31499 | train | function (command, id) {
id = id || '';
if (id) {
this.queue.push(id);
}
SocketService.emit('execute', {
command: command,
id: id
});
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.