_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34600 | UI | train | function UI(options) {
if (!(this instanceof UI)) {
var ui = Object.create(UI.prototype);
UI.apply(ui, arguments);
return ui;
}
debug('initializing from <%s>', __filename);
this.options = utils.createOptions(options);
this.appendedLines = 0;
this.height = 0;
this.initInterface();
} | javascript | {
"resource": ""
} |
q34601 | train | function(crontab) {
let _config = this[$EXTRA];
_config.logger.info(`Setting up cron schedule ${crontab}`);
_config.job = new CronJob({
cronTime: crontab,
onTick: _.bind(co.wrap(this._cronCallback), this),
start: true,
});
/* calculate and save time between runs */
// we add 1 second to next date otherwise, _getNextDateFrom() returns
// the same date back
let nextRunDate = _config.job.nextDate().add(1, 'seconds');
_config.timeBetweenRunsMs =
_config.job.cronTime._getNextDateFrom(nextRunDate).valueOf() - nextRunDate.valueOf();
} | javascript | {
"resource": ""
} | |
q34602 | arraysAppendUniqueAdapter | train | function arraysAppendUniqueAdapter(to, from, merge)
{
// transfer actual values
from.reduce(function(target, value)
{
// append only if new element isn't present yet
if (target.indexOf(value) == -1)
{
target.push(merge(undefined, value));
}
return target;
}, to);
return to;
} | javascript | {
"resource": ""
} |
q34603 | fieldPicker | train | function fieldPicker(fields)
{
var map = {};
if (fields instanceof Array) {
fields.forEach(function(f) { map[f] = f; });
} else if (typeof fields === 'object') {
for (var key in fields) {
map[key] = fields[key];
}
}
return function(input, output) {
var target = output || input;
for (var key in target) {
if (map[key] === undefined)
delete target[key];
}
};
} | javascript | {
"resource": ""
} |
q34604 | splitOnce | train | function splitOnce(str, character) {
const i = str.indexOf(character);
return [ str.slice(0, i), str.slice(i+1) ];
} | javascript | {
"resource": ""
} |
q34605 | getRndColor | train | function getRndColor() {
const r = (255 * Math.random()) | 0,
g = (255 * Math.random()) | 0,
b = (255 * Math.random()) | 0;
return "rgb(" + r + "," + g + "," + b + ")";
} | javascript | {
"resource": ""
} |
q34606 | getDependencies | train | function getDependencies(component, Prism) {
// Cast require to an Array
const deps = [].concat(component.require || []);
if (Prism) {
return deps.filter(
dep =>
// Remove dependencies that are already loaded
!Prism.languages[dep]
);
}
return deps;
} | javascript | {
"resource": ""
} |
q34607 | clean | train | function clean(done) {
var del = require('del');
del(cfg.destination).then(function () {
if (typeof done === 'function') done();
else process.exit();
});
} | javascript | {
"resource": ""
} |
q34608 | serve | train | function serve() {
var browserSync = require('browser-sync');
browserSync({
server: {
baseDir: cfg.destination
},
ui: false,
online: false,
open: false,
minify: false
});
gulp.watch(['*'], {cwd: cfg.destination}).on('change', browserSync.reload);
} | javascript | {
"resource": ""
} |
q34609 | train | function(type, obj) {
switch (type) {
case 'greet':
var name = _.get(obj, 'profile.displayName') || _.get(obj, 'username', '') || obj;
return _.get(name, 'length') ? name : 'Hey';
break;
}
return obj;
} | javascript | {
"resource": ""
} | |
q34610 | createSlicer | train | function createSlicer(version) {
if (version !== undefined) {
// For invalidation.
var currentVersion = localStorage.getItem(LS_VERSION_KEY);
if (version > currentVersion) {
localStorage.removeItem('redux');
localStorage.setItem(LS_VERSION_KEY, version);
}
}
return function (paths) {
return function (state) {
var syncedState = {};
Object.keys(state).forEach(function (path) {
// Loop through each branch of the state, building our synced state.
var substate = state[path];
if (!substate) {
return;
}
if (substate.__persist) {
// Only persist if __persist is specified.
var persist = substate.__persist;
if (persist === true) {
// Sync the whole state if __persist is just `true`.
syncedState[path] = substate;
} else if (persist.constructor === Function) {
// Sync state according to function.
var subsubstate = persist(substate);
// Always have to keep __persist around.
if (!subsubstate.__persist) {
subsubstate.__persist = persist;
}
syncedState[path] = subsubstate;
} else if (persist.constructor === Array) {
(function () {
// Sync state filtering by array of keys.
var subsubstate = {};
persist.forEach(function (key) {
subsubstate[key] = substate[key];
});
// Always have to keep __persist around.
if (!subsubstate.__persist) {
subsubstate.__persist = persist;
}
syncedState[path] = subsubstate;
})();
} else if (persist.constructor === String) {
// Deserialized a stored persist function. eval is OK here, right?
syncedState[path] = eval(persist)(substate);
}
}
});
return syncedState;
};
};
} | javascript | {
"resource": ""
} |
q34611 | idx2pos | train | function idx2pos(idx, prelen, linelen) {
prelen = prelen || 0;
linelen = linelen || 50;
idx = Number(idx);
return Math.max(0, idx - prelen - Math.floor((idx - prelen)/(linelen + 1))) + 1;
} | javascript | {
"resource": ""
} |
q34612 | string2Boolean | train | function string2Boolean (string, defaultTrue) {
// console.log('2bool:', String(string).toLowerCase());
switch (String(string).toLowerCase()) {
case '':
return (defaultTrue === undefined) ? false : defaultTrue;
case 'true':
case '1':
case 'yes':
case 'y':
return true;
case 'false':
case '0':
case 'no':
case 'n':
return false;
default:
// you could throw an error, but 'undefined' seems a more logical reply
return undefined;
}
} | javascript | {
"resource": ""
} |
q34613 | calculateUpdate | train | function calculateUpdate(currentSelection, currentValue, newValue) {
var currentCursor = currentSelection.start,
newCursor = currentCursor,
diff = newValue.length - currentValue.length,
idx;
var lengthDelta = newValue.length - currentValue.length;
var currentTail = currentValue.substring(currentCursor);
// check if we can remove common ending from the equation
// to be able to properly detect a selection change for
// the following scenarios:
//
// * (AAATTT|TF) => (AAAT|TF)
// * (AAAT|TF) => (AAATTT|TF)
//
if (newValue.lastIndexOf(currentTail) === newValue.length - currentTail.length) {
currentValue = currentValue.substring(0, currentValue.length - currentTail.length);
newValue = newValue.substring(0, newValue.length - currentTail.length);
}
// diff
var diff = createDiff(currentValue, newValue);
if (diff) {
if (diff.type === 'remove') {
newCursor = diff.newStart;
} else {
newCursor = diff.newEnd;
}
}
return range(newCursor);
} | javascript | {
"resource": ""
} |
q34614 | buildNativeCoClientBuilder | train | function buildNativeCoClientBuilder(clientBuilder) {
return function nativeCoClientBuilder(config) {
var connection = clientBuilder(config);
connection.connectAsync = promissory(connection.connect);
connection.queryAsync = promissory(connection.query);
// for backwards compatibility
connection.connectPromise = connection.connectAsync;
connection.queryPromise = connection.queryAsync;
return connection;
};
} | javascript | {
"resource": ""
} |
q34615 | BuildbotPoller | train | function BuildbotPoller(options, interval) {
Poller.call(this, 'buildbot', options, interval);
this._host = this._options['host'];
this._port = this._options['port'];
this._username = this._options['username'];
this._password = this._options['password'];
this._numBuilds = this._options['num_builds'];
this._fetchBuildDataReqObj = null;
} | javascript | {
"resource": ""
} |
q34616 | MongoStore | train | function MongoStore(options) {
options = options || {};
for (var property in defaultOptions) {
if (defaultOptions.hasOwnProperty(property)) {
if (!options.hasOwnProperty(property) || (typeof defaultOptions[property] !== typeof options[property]))
options[property] = defaultOptions[property];
}
}
Store.call(this, options.store);
var dbProperties = ["name", "prefix", "servers", "credentials", "URLParam", "extraParam"];
var dbPropertiesLen = dbProperties.length;
var dbOptions = {};
for (var i = 0; i < dbPropertiesLen; i++)
dbOptions[dbProperties[i]] = options[dbProperties[i]];
this.mongo = new Mongo(dbOptions);
this.mongo.ensureIndex(options.collection, {expires: 1}, {expireAfterSeconds: 0}, function (err, result) {
if (err)
throw new Error('Error setting TTL index on collection : ' + options.collection + ' <' + err + '>');
});
this._options = {
"collection": options.collection,
"stringify": options.stringify,
"expireAfter": options.expireAfter
};
} | javascript | {
"resource": ""
} |
q34617 | train | function(e) {
var stack = e.stacktrace;
var lines = stack.split('\n'), ANON = '{anonymous}', lineRE = /.*line (\d+), column (\d+) in ((<anonymous function\:?\s*(\S+))|([^\(]+)\([^\)]*\))(?: in )?(.*)\s*$/i, i, j, len;
for (i = 2, j = 0, len = lines.length; i < len - 2; i++) {
if (lineRE.test(lines[i])) {
var location = RegExp.$6 + ':' + RegExp.$1 + ':' + RegExp.$2;
var fnName = RegExp.$3;
fnName = fnName.replace(/<anonymous function\:?\s?(\S+)?>/g, ANON);
lines[j++] = fnName + '@' + location;
}
}
lines.splice(j, lines.length - j);
return lines;
} | javascript | {
"resource": ""
} | |
q34618 | train | function(e) {
var lines = e.message.split('\n'), ANON = '{anonymous}', lineRE = /Line\s+(\d+).*script\s+(http\S+)(?:.*in\s+function\s+(\S+))?/i, i, j, len;
for (i = 4, j = 0, len = lines.length; i < len; i += 2) {
//TODO: RegExp.exec() would probably be cleaner here
if (lineRE.test(lines[i])) {
lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) + ' -- ' + lines[i + 1].replace(/^\s+/, '');
}
}
lines.splice(j, lines.length - j);
return lines;
} | javascript | {
"resource": ""
} | |
q34619 | train | function(curr) {
var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], fn, args, maxStackSize = 10;
while (curr && stack.length < maxStackSize) {
fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
args = Array.prototype.slice.call(curr['arguments'] || []);
stack[stack.length] = fn + '(' + this.stringifyArguments(args) + ')';
curr = curr.caller;
}
return stack;
} | javascript | {
"resource": ""
} | |
q34620 | train | function(args) {
for (var i = 0; i < args.length; ++i) {
var arg = args[i];
if (arg === undefined) {
args[i] = 'undefined';
} else if (arg === null) {
args[i] = 'null';
} else if (arg.constructor) {
if (arg.constructor === Array) {
if (arg.length < 3) {
args[i] = '[' + this.stringifyArguments(arg) + ']';
} else {
args[i] = '[' + this.stringifyArguments(Array.prototype.slice.call(arg, 0, 1)) + '...' + this.stringifyArguments(Array.prototype.slice.call(arg, -1)) + ']';
}
} else if (arg.constructor === Object) {
args[i] = '#object';
} else if (arg.constructor === Function) {
args[i] = '#function';
} else if (arg.constructor === String) {
args[i] = '"' + arg + '"';
}
}
}
return args.join(',');
} | javascript | {
"resource": ""
} | |
q34621 | arrayHasValue | train | function arrayHasValue(arr, value) {
var idx = arr.indexOf(value);
if (idx !== -1) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q34622 | getTextNodes | train | function getTextNodes(el) {
el = el || document.body
var doc = el.ownerDocument || document
, walker = doc.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false)
, textNodes = []
, node
while (node = walker.nextNode()) {
textNodes.push(node)
}
return textNodes
} | javascript | {
"resource": ""
} |
q34623 | rangesIntersect | train | function rangesIntersect(rangeA, rangeB) {
return rangeA.compareBoundaryPoints(Range.END_TO_START, rangeB) === -1 &&
rangeA.compareBoundaryPoints(Range.START_TO_END, rangeB) === 1
} | javascript | {
"resource": ""
} |
q34624 | createRangeFromNode | train | function createRangeFromNode(node) {
var range = node.ownerDocument.createRange()
try {
range.selectNode(node)
} catch (e) {
range.selectNodeContents(node)
}
return range
} | javascript | {
"resource": ""
} |
q34625 | rangeIntersectsNode | train | function rangeIntersectsNode(range, node) {
if (range.intersectsNode) {
return range.intersectsNode(node)
} else {
return rangesIntersect(range, createRangeFromNode(node))
}
} | javascript | {
"resource": ""
} |
q34626 | getRangeTextNodes | train | function getRangeTextNodes(range) {
var container = range.commonAncestorContainer
, nodes = getTextNodes(container.parentNode || container)
return nodes.filter(function (node) {
return rangeIntersectsNode(range, node) && isNonEmptyTextNode(node)
})
} | javascript | {
"resource": ""
} |
q34627 | replaceNode | train | function replaceNode(replacementNode, node) {
remove(replacementNode)
node.parentNode.insertBefore(replacementNode, node)
remove(node)
} | javascript | {
"resource": ""
} |
q34628 | unwrap | train | function unwrap(el) {
var range = document.createRange()
range.selectNodeContents(el)
replaceNode(range.extractContents(), el)
} | javascript | {
"resource": ""
} |
q34629 | undo | train | function undo(nodes) {
nodes.forEach(function (node) {
var parent = node.parentNode
unwrap(node)
parent.normalize()
})
} | javascript | {
"resource": ""
} |
q34630 | createWrapperFunction | train | function createWrapperFunction(wrapperEl, range) {
var startNode = range.startContainer
, endNode = range.endContainer
, startOffset = range.startOffset
, endOffset = range.endOffset
return function wrapNode(node) {
var currentRange = document.createRange()
, currentWrapper = wrapperEl.cloneNode()
currentRange.selectNodeContents(node)
if (node === startNode && startNode.nodeType === 3) {
currentRange.setStart(node, startOffset)
startNode = currentWrapper
startOffset = 0
}
if (node === endNode && endNode.nodeType === 3) {
currentRange.setEnd(node, endOffset)
endNode = currentWrapper
endOffset = 1
}
currentRange.surroundContents(currentWrapper)
return currentWrapper
}
} | javascript | {
"resource": ""
} |
q34631 | Message | train | function Message(data, source){
source = source || {}
this.data = data
this.key = source.key
this.sourceChannel = source.name
} | javascript | {
"resource": ""
} |
q34632 | train | function(options, content, res) {
return function (/*function*/ callback) {
// create the post data to send to the User Modeling service
var post_data = {
'contentItems' : [{
'userid' : 'dummy',
'id' : 'dummyUuid',
'sourceid' : 'freetext',
'contenttype' : 'text/plain',
'language' : 'en',
'content': content
}]
};
// Create a request to POST to the User Modeling service
var profile_req = https.request(options, function(result) {
result.setEncoding('utf-8');
var response_string = '';
result.on('data', function(chunk) {
response_string += chunk;
});
result.on('end', function() {
if (result.statusCode != 200) {
var error = JSON.parse(response_string);
// render error if the results are less than 100 words
callback({'message': error.user_message}, null);
} else
callback(null,response_string);
});
});
profile_req.on('error', function(e) {
callback(e,null);
});
profile_req.write(JSON.stringify(post_data));
profile_req.end();
}
} | javascript | {
"resource": ""
} | |
q34633 | train | function(name) {
try {
debug(`Loading ${name} configuration`);
return waigo.load(`config/${name}`);
} catch (e) {
debug(`Error loading config: ${name}`);
debug(e);
return null;
}
} | javascript | {
"resource": ""
} | |
q34634 | train | function (destPath, srcPaths, options) {
let stream,
b,
finalPaths = [];
return new Promise(function (resolve, reject) {
_.each(srcPaths, function (path) {
// deal with file globs
if (glob.hasMagic(path)) {
glob.sync(path).forEach((p) => {
p = utils.scopePaths(p);
finalPaths.push(p);
});
} else {
path = utils.scopePaths(path);
finalPaths.push(path);
}
});
// add required parameters for watchify
options.cache = {};
options.packageCache = {};
options.debug = options.watch;
b = browserify(options);
b.transform(envify({
_: 'purge',
NODE_ENV: options.env
}), {global: true});
// must add each path individual unfortunately.
finalPaths.forEach(function (path) {
b.add(path);
});
options.ignore.forEach((file) => {
b.ignore(file);
});
options.exclude.forEach((file) => {
b.exclude(file);
});
// require global files
_.each(options.requires, function (path, id) {
// options.requires can be an array of strings or an object
id = typeof id == "string" ? id : path;
b.require(path, {expose: id});
});
if (options.watch) {
b.plugin(watchify);
// re-bundle when updated
b.on('update', function () {
console.log('file updated!');
b.bundle();
});
}
b.on('bundle', function (stream) {
console.log('browserifying bundle...');
writeBrowserifyBundleStreamToFile(stream, destPath)
.then(function () {
console.log('done browserifying bundle!');
resolve();
})
.catch(function (e) {
console.log('browserifying failed');
console.log(e);
reject(e);
});
});
stream = b.bundle();
}.bind(this));
} | javascript | {
"resource": ""
} | |
q34635 | train | function (stream, destPath) {
let data = '';
return new Promise(function (resolve, reject) {
stream.on('error', reject);
stream.on('data', function (d) {
data += d.toString();
});
stream.on('end', function () {
fs.outputFile(destPath, data, function (err) {
if (!err) {
resolve();
} else {
reject(err);
}
});
});
});
} | javascript | {
"resource": ""
} | |
q34636 | fillMatrix | train | function fillMatrix(id, t, l, w, h) {
for (var y = t; y < t + h;) {
for (var x = l; x < l + w;) {
matrix[y + '-' + x] = id;
++x > maxX && (maxX = x);
}
++y > maxY && (maxY = y);
}
} | javascript | {
"resource": ""
} |
q34637 | json2jison | train | function json2jison (grammar, options) {
options = options || {};
var s = "";
s += genDecls(grammar, options);
s += genBNF(grammar.bnf, options);
return s;
} | javascript | {
"resource": ""
} |
q34638 | genLex | train | function genLex (lex) {
var s = [];
if (lex.macros) {
for (var macro in lex.macros) if (lex.macros.hasOwnProperty(macro)) {
s.push(macro, ' ', lex.macros[macro], '\n');
}
}
if (lex.actionInclude) {
s.push('\n%{\n', lex.actionInclude, '\n%}\n');
}
s.push('\n%%\n');
if (lex.rules) {
for (var rule;rule=lex.rules.shift();) {
s.push(genLexRegex(rule[0]), ' ', genLexRule(rule[1]), '\n');
}
}
s.push('\n');
return s.join('');
} | javascript | {
"resource": ""
} |
q34639 | fsReaddirSync | train | function fsReaddirSync(root, files, fp) {
if (typeof root !== 'string') {
throw new TypeError('fsReaddir.sync: expect `root` to be string');
}
fp = fp || '';
files = files || [];
var dir = path.join(root, fp);
if (fs.statSync(dir).isDirectory()) {
fs.readdirSync(dir).forEach(function(name) {
fsReaddirSync(root, files, path.join(dir, name));
});
} else {
files.push(fp);
}
return files;
} | javascript | {
"resource": ""
} |
q34640 | copyFileIntoDirectory | train | function copyFileIntoDirectory(srcPath, destPath) {
return ensureDestinationDirectory(destPath).then(function () {
return new Promise(function (resolve, reject) {
fs.readFile(srcPath, 'utf8', function (err, contents) {
if (!err) {
resolve();
} else {
reject(err);
}
fs.outputFile(destPath + '/' + path.basename(srcPath), contents, function (err) {
if (!err) {
resolve();
} else {
reject(err);
}
});
});
});
});
} | javascript | {
"resource": ""
} |
q34641 | copyFile | train | function copyFile(srcPath, destPath) {
let srcFileInfo = path.parse(srcPath) || {};
if (!path.extname(destPath) && srcFileInfo.ext) {
// destination is a directory!
return copyFileIntoDirectory(srcPath, destPath);
} else {
return new Promise(function (resolve, reject) {
fs.copy(srcPath, destPath, function (err) {
if (!err) {
resolve();
} else {
reject(err);
}
});
});
}
} | javascript | {
"resource": ""
} |
q34642 | getSourceDestinationPath | train | function getSourceDestinationPath (srcPath) {
let dests = _.keys(options.files);
return _.find(dests, function (destPath) {
let paths = options.files[destPath];
return _.find(paths, function (p) {
return p === srcPath || srcPath.indexOf(p) !== -1;
});
});
} | javascript | {
"resource": ""
} |
q34643 | train | function (tx) {
var outs = [];
tx.outputs.forEach(function (o) {
outs.push(new TransactionOutput(o.satoshis,o.script.toBuffer()));
});
return outs;
} | javascript | {
"resource": ""
} | |
q34644 | filterTitle | train | function filterTitle(posts) {
var reTitle = title.map(function makeRE(word) {
return new RegExp(word, 'i');
});
return posts.filter(function filterPosts(post) {
return reTitle.every(function checkRE(regex) {
return regex.test(post.title) || regex.test(post.slug);
});
});
} | javascript | {
"resource": ""
} |
q34645 | filterFolder | train | function filterFolder(posts) {
var reFolder = new RegExp(folder);
return posts.filter(function filterPosts(post) {
return reFolder.test(post.source.substr(0, post.source.lastIndexOf(path.sep)));
});
} | javascript | {
"resource": ""
} |
q34646 | filterTag | train | function filterTag(posts) {
var reTag = new RegExp(tag);
return posts.filter(function filterPosts(post) {
return post.tags.data.some(function checkRe(postTag) {
return reTag.test(postTag.name);
});
});
} | javascript | {
"resource": ""
} |
q34647 | filterCategory | train | function filterCategory(posts) {
var reCat = new RegExp(cat);
return posts.filter(function filterPosts(post) {
return post.categories.data.some(function checkRe(postCat) {
return reCat.test(postCat.name);
});
});
} | javascript | {
"resource": ""
} |
q34648 | filterLayout | train | function filterLayout(posts) {
var reLayout = new RegExp(layout, 'i');
return posts.filter(function filterPosts(post) {
return reLayout.test(post.layout);
});
} | javascript | {
"resource": ""
} |
q34649 | filterBefore | train | function filterBefore(posts) {
before = moment(before.replace(/\//g, '-'), 'MM-DD-YYYY', true);
if (!before.isValid()) {
console.log(chalk.red('Before date is not valid (expecting `MM-DD-YYYY`), ignoring argument.'));
return posts;
}
return posts.filter(function filterPosts(post) {
return moment(post.date).isBefore(before);
});
} | javascript | {
"resource": ""
} |
q34650 | filterAfter | train | function filterAfter(posts) {
after = moment(after.replace(/\//g, '-'), 'MM-DD-YYYY', true);
if (!after.isValid()) {
console.log(chalk.red('After date is not valid (expecting `MM-DD-YYYY`), ignoring argument.'));
return posts;
}
return posts.filter(function filterPosts(post) {
return moment(post.date).isAfter(after);
});
} | javascript | {
"resource": ""
} |
q34651 | openFile | train | function openFile(file) {
var edit;
if (!editor || gui) {
open(file);
} else {
edit = spawn(editor, [file], {stdio: 'inherit'});
edit.on('exit', process.exit);
}
} | javascript | {
"resource": ""
} |
q34652 | Bitid | train | function Bitid(params) {
params = params || {};
var self = this;
this._nonce = params.nonce;
this.callback = url.parse(params.callback, true);
this.signature = params.signature;
this.address = params.address;
this.unsecure = params.unsecure;
this._uri = !params.uri ? buildURI() : url.parse(params.uri, true);
function buildURI() {
var uri = self.callback;
uri.protocol = SCHEME;
var params = {};
params[PARAM_NONCE] = self._nonce;
if(self.unsecure) params[PARAM_UNSECURE] = 1;
uri.query = params;
uri.href = url.format(uri);
return uri;
}
} | javascript | {
"resource": ""
} |
q34653 | getPresetsString | train | function getPresetsString(presetArray) {
if (!presetArray.includes("react-app")) {
presetArray.push("react-app");
}
return presetArray.map(attachRequestResolve("preset")).join(",");
} | javascript | {
"resource": ""
} |
q34654 | connect | train | function connect(obj, cb) {
if (obj.db) {
return cb();
}
if (obj.pending) {
return setImmediate(function () {
connect(obj, cb);
});
}
obj.pending = true;
var url = constructMongoLink(obj.config.name, obj.config.prefix, obj.config.servers, obj.config.URLParam, obj.config.credentials);
if (!url) {
return cb(generateError(190));
}
mongoSkin.connect(url, obj.config.extraParam, function (err, db) {
if (err) {
obj.pending = false;
return cb(err);
} else {
db.on('timeout', function () {
console.log("Connection To Mongo has timed out!");
obj.flushDb();
});
db.on('close', function () {
console.log("Connection To Mongo has been closed!");
obj.flushDb();
});
if (obj.db)
obj.db.close();
obj.db = db;
obj.pending = false;
return cb();
}
});
/**
*constructMongoLink: is a function that takes the below param and return the URL need to by mongoskin.connect
*
* @param dbName
* @param prefix
* @param servers
* @param params
* @param credentials
* @returns {*}
*/
function constructMongoLink(dbName, prefix, servers, params, credentials) {
if (dbName && Array.isArray(servers)) {
var url = "mongodb://";
if (credentials && Object.hasOwnProperty.call(credentials, 'username') && credentials.hasOwnProperty.call(credentials, 'password')) {
url = url.concat(credentials.username, ':', credentials.password, '@');
}
servers.forEach(function (element, index, array) {
url = url.concat(element.host, ':', element.port, (index === array.length - 1 ? '' : ','));
});
url = url.concat('/');
if (prefix) url = url.concat(prefix);
url = url.concat(dbName);
if (params && 'object' === typeof params && Object.keys(params).length) {
url = url.concat('?');
for (var i = 0; i < Object.keys(params).length; i++) {
url = url.concat(Object.keys(params)[i], '=', params[Object.keys(params)[i]], i === Object.keys(params).length - 1 ? '' : "&");
}
}
return url;
}
return null;
}
} | javascript | {
"resource": ""
} |
q34655 | _SubRange | train | function _SubRange(low, high) {
this.low = low;
this.high = high;
this.length = 1 + high - low;
} | javascript | {
"resource": ""
} |
q34656 | manageNginx | train | function manageNginx (action, callback) {
// TODO: research if sending signals is better
// i.e. sudo nginx -s stop|quit|reload
exec(`sudo service nginx ${action}`, (err, stdout, stderr) => {
if (err) return callback(err)
return callback()
})
} | javascript | {
"resource": ""
} |
q34657 | Project | train | function Project(path) {
path = path || PWD;
this.root = '';
this.storage = '';
this.ignore = [];
this.resolvePaths(path);
} | javascript | {
"resource": ""
} |
q34658 | train | function (module_name, module_folder) {
var module_path = path.resolve(module_folder);
// load current keystore
let keystored = {};
const filename = ".iotdb/keystore.json";
_.cfg.load.json([ filename ], docd => keystored = _.d.compose.deep(keystored, docd.doc));
// change it
_.d.set(keystored, "/modules/" + module_name, module_path)
// save it
fs.writeFile(filename, JSON.stringify(keystored, null, 2));
console.log("- installed homestar module!");
console.log(" name:", module_name);
console.log(" path:", module_path);
} | javascript | {
"resource": ""
} | |
q34659 | train | function (module_name, module_folder) {
var iotdb_dir = path.join(process.cwd(), module_folder, "node_modules", "iotdb");
console.log("- cleanup");
console.log(" path:", iotdb_dir);
try {
_rmdirSync(iotdb_dir);
} catch (x) {
}
} | javascript | {
"resource": ""
} | |
q34660 | train | function (module_name, module_folder, callback) {
var module_folder = path.resolve(module_folder)
var module_packaged = _load_package(module_folder);
var module_dependencies = _.d.get(module_packaged, "/dependencies");
if (!module_dependencies) {
return callback();
}
module_dependencies = _.keys(module_dependencies);
var _install_next = function() {
if (module_dependencies.length === 0) {
return callback();
}
var dname = module_dependencies.pop();
var dependency_folder = path.join(module_folder, "node_modules", dname);
var dependency_homestard = _load_homestar(dependency_folder);
var is_module = _.d.get(dependency_homestard, "/module", false);
if (!is_module) {
return _install_next();
}
console.log("- found dependency:", dname);
_install(dname, function() {
try {
console.log("- cleanup");
console.log(" path:", dependency_folder);
_rmdirSync(dependency_folder);
} catch (x) {
}
_install_next();
});
}
_install_next();
} | javascript | {
"resource": ""
} | |
q34661 | train | function() {
try {
var statbuf = fs.statSync(folder);
if (statbuf.isDirectory()) {
return;
}
}
catch (x) {
}
try {
fs.mkdirSync("node_modules");
} catch (x) {
}
statbuf = fs.statSync(folder);
if (statbuf.isDirectory()) {
return;
}
} | javascript | {
"resource": ""
} | |
q34662 | readFile | train | function readFile(path, callback) {
nodeFs.readFile(path, function (err, binary) {
if (err) {
if (err.code === "ENOENT") return callback();
return callback(err);
}
return callback(null, binary);
});
} | javascript | {
"resource": ""
} |
q34663 | readChunk | train | function readChunk(path, start, end, callback) {
if (end < 0) {
return readLastChunk(path, start, end, callback);
}
var stream = nodeFs.createReadStream(path, {
start: start,
end: end - 1
});
var chunks = [];
stream.on("readable", function () {
var chunk = stream.read();
if (chunk === null) return callback(null, Buffer.concat(chunks));
return chunks.push(chunk);
});
stream.on("error", function (err) {
if (err.code === "ENOENT") return callback();
return callback(err);
});
} | javascript | {
"resource": ""
} |
q34664 | readLastChunk | train | function readLastChunk(path, start, end, callback) {
nodeFs.open(path, "r", function (err, fd) {
if (err) {
if (err.code === "EACCES") return callback();
return callback(err);
}
var buffer = new Buffer(4096);
var length = 0;
read();
// Only the first read needs to seek.
// All subsequent reads will continue from the end of the previous.
start = null;
function read() {
if (buffer.length - length === 0) {
grow();
}
nodeFs.read(fd, buffer, length, buffer.length - length, start, onread);
}
function onread(err, bytesRead) {
if (err) return callback(err);
length += bytesRead;
if (bytesRead === 0) {
return callback(null, buffer.slice(0, buffer.length + end));
}
read();
}
function grow() {
var newBuffer = new Buffer(buffer.length * 2);
buffer.copy(newBuffer);
buffer = newBuffer;
}
});
} | javascript | {
"resource": ""
} |
q34665 | writeFile | train | function writeFile(path, binary, callback) {
mkdirp(nodePath.dirname(path), function (err) {
if (err) return callback(err);
nodeFs.writeFile(path, binary, callback);
});
} | javascript | {
"resource": ""
} |
q34666 | rename | train | function rename(oldPath, newPath, callback) {
var oldBase = nodePath.dirname(oldPath);
var newBase = nodePath.dirname(newPath);
if (oldBase === newBase) {
return nodeFs.rename(oldPath, newPath, callback);
}
mkdirp(nodePath.dirname(path), function (err) {
if (err) return callback(err);
nodeFs.rename(oldPath, newPath, callback);
});
} | javascript | {
"resource": ""
} |
q34667 | emojiLogger | train | function emojiLogger(msg, type, override) {
// Get the type
var _type = emojiLogger.types[type || "info"];
if (!_type) {
throw new Err(`There is no such logger type: ${type}`, "NO_SUCH_LOGGER_TYPE");
}
emojiLogger.log(msg, _type, override);
} | javascript | {
"resource": ""
} |
q34668 | train | function (targetFilePath, abspaths) {
// Change 'assets/mdeditor.min.js' to 'assets/' and 'mdeditor.min.js'
var pathFilename = _splitPathAndFilename(targetFilePath);
var targetPath = pathFilename[0];
var targetFilename = pathFilename[1];
// bug fix: assets/xxxxxxxx.mdeditor.min.js, xxxxxxxx can't contain '/' or white character
// otherwise 'assets/mdeditor/1111.mmm.min.js' matched target filename: 'assets/mmm.min.js', which is incorrect.
var filenamePattern = new RegExp(targetPath + '[^\\/\\s]+?\\.' + targetFilename);
// Find the revision file based on targetFilePath defined in html template, if there are multiple files matched, pick up the latest one.
var revTargetFilePath = null;
var revTargetFileModifyTime = null;
for (var index in abspaths) {
if (abspaths[index].match(filenamePattern)) { // there could be more than one revision files matched filenamePattern
// match the first revision file.
if (revTargetFilePath === null) {
revTargetFilePath = abspaths[index];
// match the one more revision files, pick up the latest files.
} else {
if (revTargetFileModifyTime === null) {
revTargetFileModifyTime = fs.lstatSync(revTargetFilePath).mtime;
}
var currentFileModifyTime = fs.lstatSync(abspaths[index]).mtime;
if (currentFileModifyTime > revTargetFileModifyTime) {
revTargetFilePath = abspaths[index];
revTargetFileModifyTime = currentFileModifyTime;
}
}
}
}
if (revTargetFilePath === null) {
grunt.warn('In the file: ' + templateFilename + ', the target filename: ' + targetFilePath + ' has not been handled to produce a corresponding revision file.');
}
return revTargetFilePath;
} | javascript | {
"resource": ""
} | |
q34669 | findPosSubword | train | function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type;
for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
break;
}
}
}
return Pos(start.line, pos);
} | javascript | {
"resource": ""
} |
q34670 | Task | train | function Task(task) {
_.extend(this, task);
if (task != undefined) this.createId();
// Short id
this.__defineGetter__('id', function () {
return this.__uuid__.substr(0, 8).toString();
});
// Keyword
this.__defineGetter__('keyword', function () {
return this.labels[0].replace('#', '').toUpperCase();
});
// Stemmed
this.__defineGetter__('stemmed', function () {
return (this.title+' '+this.body).toLowerCase()
.split(' ').map(stem).join(' ');
});
// All
this.__defineGetter__('all', function () {
return '*';
});
} | javascript | {
"resource": ""
} |
q34671 | train | function (v, paramd) {
var nd = {};
var _add = function(v) {
if (!_.is.String(v)) {
return false;
}
var vmatch = v.match(/^([-a-z0-9]*):.+/);
if (!vmatch) {
return false;
}
var nshort = vmatch[1];
var nurl = _namespace[nshort];
if (!nurl) {
return false;
}
nd[nshort] = nurl;
return true;
};
var _walk = function(o) {
if (_.is.Object(o)) {
for (var key in o) {
if (!_add(key)) {
continue;
} else if (!key.match(/^iot/)) {
continue;
} else if (key === "iot:help") {
continue;
}
var sv = o[key];
if (_walk(sv)) {
nd[key] = {
"@id": _ld_expand(key),
"@type": "@id"
};
}
}
} else if (_.is.Array(o)) {
var any = false;
o.map(function(sv) {
_add(sv);
any |= _walk(sv);
});
return any;
} else if (_.is.String(o)) {
if (_add(o)) {
return true;
}
}
};
_walk(v);
if (!v["@context"]) {
v["@context"] = {};
}
_.extend(v["@context"], nd);
return v;
} | javascript | {
"resource": ""
} | |
q34672 | train | function () { // eslint-disable-line object-shorthand
// Inits helper
helper.init(this);
// Check cli args for output format, and override on existance of string.
if (typeof pluginBuildFlag === 'string' || pluginBuildFlag instanceof String) {
helper.config.format = pluginBuildFlag;
}
// Fill summary array
this.book.summary.walk((article) => {
helper.summary.push(article);
});
} | javascript | {
"resource": ""
} | |
q34673 | train | function () { // eslint-disable-line object-shorthand
const self = this;
const outputPath = helper.getOutput();
// Render template.
const rawContent = helper.renderTemp({summary: helper.summary});
// Create output dir.
mkdirp.sync(path.parse(outputPath).dir);
// Compile rendered main file
return helper.pandocCompile(rawContent)
.then((compiledContent) => {
// Write file to output dir.
fs.writeFileSync(outputPath, compiledContent);
// Log action.
self.log.info.ln('plugin-build(output):', helper.config.output);
});
} | javascript | {
"resource": ""
} | |
q34674 | train | function (page) { // eslint-disable-line object-shorthand
// Fill summary with compiled page content
helper.summary.forEach((article, i, array) => {
if (article.path === page.path) {
array[i].content = page.content;
}
});
// Returns unchanged page.
return page;
} | javascript | {
"resource": ""
} | |
q34675 | sendJson | train | function sendJson(data, options, callback) {
var jsonData = JSON.stringify(data);
return this.send(jsonData, options, callback);
} | javascript | {
"resource": ""
} |
q34676 | find_props | train | function find_props(schema) {
var props = _(schema.paths).keys().without('_id', 'id')
// transform the schema tree into an array for filtering
.map(function(key) { return { name : key, value : _.get(schema.tree, key) }; })
// remove paths that are annotated with csv: false
.filter(function(node) {
return typeof node.value.csv === 'undefined' || node.value.csv;
})
// remove virtuals that are annotated with csv: false
.filter(function(node) {
var opts = node.value.options;
if (!opts) return true;
return typeof opts.csv === 'undefined' || opts.csv;
})
// remove complex object types
.filter(function(node) {
var path = schema.paths[node.name];
if (!path) return true;
// filter out any of these types of properties
return [ 'Array', 'Object', 'Mixed' ].indexOf(path.instance) === -1;
})
// materialize , end chain
.pluck('name').value();
// _id at the beginning
props.unshift('_id');
return props;
} | javascript | {
"resource": ""
} |
q34677 | prop_to_csv | train | function prop_to_csv(prop) {
var val = String(prop);
if (val === 'undefined') val = '';
return '"' + val.toString().replace(/"/g, '""') + '"';
} | javascript | {
"resource": ""
} |
q34678 | train | function(view_config, raw_hash) {
for (var name in raw_hash) {
if (Lava.schema.DEBUG && this._allowed_hash_options.indexOf(name) == -1) Lava.t("Hash option is not supported: " + name);
if (name in this._view_config_property_setters) {
this[this._view_config_property_setters[name]](view_config, raw_hash[name]);
} else {
view_config[name] = raw_hash[name];
}
}
} | javascript | {
"resource": ""
} | |
q34679 | train | function(result, raw_expression) {
if (raw_expression.arguments.length != 1) Lava.t("Expression block requires exactly one argument");
var config = {
type: 'view',
"class": 'Expression',
argument: raw_expression.arguments[0]
};
if (raw_expression.prefix == '$') {
config.container = {type: 'Morph'};
}
result.push(config);
} | javascript | {
"resource": ""
} | |
q34680 | train | function(result, tag) {
var is_void = Lava.isVoidTag(tag.name),
tag_start_text = "<" + tag.name
+ this.renderTagAttributes(tag.attributes)
+ (is_void ? '/>' : '>'),
inner_template,
count;
this. _compileString(result, tag_start_text);
if (Lava.schema.DEBUG && is_void && tag.content) Lava.t("Void tag with content");
if (!is_void) {
if (tag.content) {
inner_template = this.compileTemplate(tag.content);
count = inner_template.length;
if (count && typeof (inner_template[0]) == 'string') {
this._compileString(result, inner_template.shift());
count--;
}
if (count) {
result.splice.apply(result, [result.length, 0].concat(inner_template));
}
}
this. _compileString(result, "</" + tag.name + ">");
}
} | javascript | {
"resource": ""
} | |
q34681 | train | function(raw_tag) {
var container_config = {
type: 'Element',
tag_name: raw_tag.name
};
if ('attributes' in raw_tag) this._parseContainerStaticAttributes(container_config, raw_tag.attributes);
if ('x' in raw_tag) this._parseContainerControlAttributes(container_config, raw_tag.x);
return /** @type {_cElementContainer} */ container_config;
} | javascript | {
"resource": ""
} | |
q34682 | train | function(container_config, x) {
var i,
count,
name;
if ('event' in x) {
if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");
container_config.events = {};
for (name in x.event) {
container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);
}
}
// Attribute binding. Example: x:bind:src="<any_valid_expression>"
if ('bind' in x) {
if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");
container_config.property_bindings = this._parseBindingsHash(x.bind);
}
if ('style' in x) {
if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");
container_config.style_bindings = this._parseBindingsHash(x.style);
}
if ('classes' in x) {
var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
class_bindings = {};
for (i = 0, count = arguments.length; i < count; i++) {
class_bindings[i] = arguments[i];
}
container_config.class_bindings = class_bindings;
}
if ('container_class' in x) {
container_config['class'] = x.container_class;
}
} | javascript | {
"resource": ""
} | |
q34683 | train | function(blocks, view_config) {
var current_block,
result = [],
type,
i = 0,
count = blocks.length,
x;
for (; i < count; i++) {
current_block = blocks[i];
type = (typeof(current_block) == 'string') ? 'string' : current_block.type;
if (type == 'tag') {
x = current_block.x;
if (x) {
if ('type' in x) {
if ('widget' in x) Lava.t("Malformed tag: both x:type and x:widget present");
type = x.type;
if (['view', 'container', 'static'].indexOf(type) == -1) Lava.t("Unknown x:type attribute: " + type);
} else if ('widget' in x) {
type = 'widget';
} else if (Lava.sugar_map[current_block.name]) {
type = 'sugar';
} else {
Lava.t("Tag with control attributes and no sugar or type on it: " + current_block.name);
}
} else if (Lava.sugar_map[current_block.name]) {
type = 'sugar';
} // else type = 'tag' - default
}
this[this._compile_handlers[type]](result, current_block, view_config);
}
return result;
} | javascript | {
"resource": ""
} | |
q34684 | train | function(raw_blocks) {
var result = this.asBlocks(this.compileTemplate(raw_blocks));
if (result.length != 1) Lava.t("Expected: exactly one view, got either several or none.");
if (result[0].type != 'view' && result[0].type != 'widget') Lava.t("Expected: view, got: " + result[0].type);
return result[0];
} | javascript | {
"resource": ""
} | |
q34685 | train | function(template) {
var i = 0,
count = template.length,
result = [];
for (; i < count; i++) {
if (typeof(template[i]) == 'string') {
if (!Lava.EMPTY_REGEX.test(template[i])) Lava.t("Text between tags is not allowed in this context. You may want to use a lava-style comment ({* ... *})");
} else {
result.push(template[i]);
}
}
return result;
} | javascript | {
"resource": ""
} | |
q34686 | train | function() {
return {
type: 'widget',
"class": Lava.schema.widget.DEFAULT_EXTENSION_GATEWAY,
extender_type: Lava.schema.widget.DEFAULT_EXTENDER
}
} | javascript | {
"resource": ""
} | |
q34687 | train | function(raw_string) {
var map = Firestorm.String.quote_escape_map,
result;
try {
result = eval("(" + raw_string.replace(this.UNQUOTE_ESCAPE_REGEX, function (a) {
var c = map[a];
return typeof c == 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + ")");
} catch (e) {
Lava.t("Malformed string: " + raw_string);
}
return result;
} | javascript | {
"resource": ""
} | |
q34688 | train | function(raw_directive, view_config, is_top_directive) {
var directive_name = raw_directive.name,
config = this._directives_schema[directive_name];
if (!config) Lava.t("Unknown directive: " + directive_name);
if (config.view_config_presence) {
if (view_config && !config.view_config_presence) Lava.t('Directive must not be inside view definition: ' + directive_name);
if (!view_config && config.view_config_presence) Lava.t('Directive must be inside view definition: ' + directive_name);
}
if (config.is_top_directive && !is_top_directive) Lava.t("Directive must be at the top of the block content: " + directive_name);
return this['_x' + directive_name](raw_directive, view_config);
} | javascript | {
"resource": ""
} | |
q34689 | train | function(destination, source, name_list) {
for (var i = 0, count = name_list.length; i < count; i++) {
var name = name_list[i];
if (name in source) destination[name] = source[name];
}
} | javascript | {
"resource": ""
} | |
q34690 | train | function(raw_tag) {
if (Lava.schema.DEBUG && (!raw_tag.content || raw_tag.content.length != 1 || raw_tag.content[0] == '')) Lava.t("Malformed resources options tag");
return {
type: 'options',
value: Lava.parseOptions(raw_tag.content[0])
};
} | javascript | {
"resource": ""
} | |
q34691 | train | function(raw_tag) {
if (Lava.schema.DEBUG && raw_tag.content && raw_tag.content.length != 1) Lava.t("Malformed resources string tag");
var result = {
type: 'string',
value: raw_tag.content ? raw_tag.content[0].trim() : ''
};
if (raw_tag.attributes.description) result.description = raw_tag.attributes.description;
return result;
} | javascript | {
"resource": ""
} | |
q34692 | train | function(raw_tag) {
if (Lava.schema.DEBUG && (!raw_tag.content)) Lava.t("Malformed resources plural string tag");
var plural_tags = Lava.parsers.Common.asBlockType(raw_tag.content, 'tag'),
i = 0,
count = plural_tags.length,
plurals = [],
result;
if (Lava.schema.DEBUG && count == 0) Lava.t("Malformed resources plural string definition");
for (; i < count; i++) {
if (Lava.schema.DEBUG && (plural_tags[i].name != 'string' || !plural_tags[i].content || !plural_tags[i].content[0])) Lava.t("Resources, malformed plural string");
plurals.push(plural_tags[i].content[0].trim());
}
result = {
type: 'plural_string',
value: plurals
};
if (raw_tag.attributes.description) result.description = raw_tag.attributes.description;
return result;
} | javascript | {
"resource": ""
} | |
q34693 | train | function(raw_directive) {
if (Lava.schema.DEBUG) {
if (!raw_directive.attributes || !raw_directive.attributes.title) Lava.t("define: missing 'title' attribute");
if (raw_directive.attributes.title.indexOf(' ') != -1) Lava.t("Widget title must not contain spaces");
if ('resource_id' in raw_directive.attributes) Lava.t("resource_id is not allowed on define");
if (this._current_widget_title) Lava.t("Nested defines are not allowed: " + raw_directive.attributes.title);
}
this._current_widget_title = raw_directive.attributes.title;
var widget_config = this._parseWidgetDefinition(raw_directive);
this._current_widget_title = null;
widget_config.is_extended = false; // reserve it for serialization
if (Lava.schema.DEBUG && ('class_locator' in widget_config)) Lava.t("Dynamic class names are allowed only in inline widgets, not in x:define");
Lava.storeWidgetSchema(raw_directive.attributes.title, widget_config);
} | javascript | {
"resource": ""
} | |
q34694 | train | function(raw_directive) {
var widget_config = this._parseWidgetDefinition(raw_directive);
if (Lava.schema.DEBUG && ('sugar' in widget_config)) Lava.t("Inline widgets must not have sugar");
if (Lava.schema.DEBUG && !widget_config['class'] && !widget_config['extends']) Lava.t("x:define: widget definition is missing either 'controller' or 'extends' attribute");
if (raw_directive.attributes.resource_id) widget_config.resource_id = Lava.parsers.Common.parseResourceId(raw_directive.attributes.resource_id);
widget_config.type = 'widget';
return widget_config;
} | javascript | {
"resource": ""
} | |
q34695 | train | function(config, raw_tag, config_property_name) {
if (Lava.schema.DEBUG && !('attributes' in raw_tag)) Lava.t("option: missing attributes");
if (Lava.schema.DEBUG && (!raw_tag.content || raw_tag.content.length != 1)) Lava.t("Malformed option: " + raw_tag.attributes.name);
var option_type = raw_tag.attributes.type,
result;
if (option_type) {
if (option_type == 'targets') {
result = Lava.parsers.Common.parseTargets(raw_tag.content[0]);
} else if (option_type == 'expressions') {
result = Lava.ExpressionParser.parse(raw_tag.content[0], Lava.ExpressionParser.SEPARATORS.SEMICOLON);
} else {
Lava.t("Unknown option type: " + option_type);
}
} else {
result = Lava.parseOptions(raw_tag.content[0]);
}
Lava.store(config, config_property_name, raw_tag.attributes.name, result);
} | javascript | {
"resource": ""
} | |
q34696 | train | function(config, name, raw_tag) {
if (Lava.schema.DEBUG && (name in config)) Lava.t("Object already exists: " + name + ". Ensure, that x:options and x:properties directives appear before x:option and x:property.");
if (Lava.schema.DEBUG && (!raw_tag.content || raw_tag.content.length != 1)) Lava.t("Malformed directive or tag for config property: " + name);
config[name] = Lava.parseOptions(raw_tag.content[0]);
} | javascript | {
"resource": ""
} | |
q34697 | train | function(widget_config, raw_directive, config_property_name) {
if (Lava.schema.DEBUG && !('attributes' in raw_directive)) Lava.t("option: missing attributes");
if (Lava.schema.DEBUG && (!raw_directive.content || raw_directive.content.length != 1)) Lava.t("Malformed property: " + raw_directive.attributes.name);
Lava.store(widget_config, config_property_name, raw_directive.attributes.name, raw_directive.content[0]);
} | javascript | {
"resource": ""
} | |
q34698 | train | function(raw_directive) {
if (Lava.schema.DEBUG && (!raw_directive.attributes || !raw_directive.attributes['locale'] || !raw_directive.attributes['for']))
Lava.t("Malformed x:resources definition. 'locale' and 'for' are required");
Lava.resources.addWidgetResource(
raw_directive.attributes['for'],
raw_directive.attributes['locale'],
this._parseResources(raw_directive, raw_directive.attributes['for'])
);
} | javascript | {
"resource": ""
} | |
q34699 | train | function(raw_directive) {
if (Lava.schema.DEBUG && !raw_directive.content) Lava.t("empty attach_directives");
var blocks = Lava.parsers.Common.asBlocks(raw_directive.content),
sugar = blocks[0],
directives = blocks.slice(1),
i,
count;
if (Lava.schema.DEBUG) {
if (sugar.type != 'tag' || sugar.content || directives.length == 0) Lava.t("Malformed attach_directives");
for (i = 0, count = directives.length; i < count; i++) {
if (directives[i].type != 'directive') Lava.t("Malformed attach_directives");
}
}
sugar.content = directives;
return Lava.parsers.Common.compileAsView([sugar]);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.