_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43300 | train | function (item) {
if($.isEmptyObject(item)){
var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()};
return [tempObj];
}else{
return item;
}
} | javascript | {
"resource": ""
} | |
q43301 | train | function (item) {
// Check if it already exists in the suggestions list. Duplicates aren't allowed.
var exists = false;
for(var j = 0; j < suggestions.length; j++){
if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){
exists=true;
... | javascript | {
"resource": ""
} | |
q43302 | train | function (item) {
var searchTerms = self.viewModel.attr('searchTerms').attr(),
searchTerm = item && (item.id || item.name || item);
searchTerms.splice(searchTerms.indexOf(searchTerm), 1);
// We are using searchTerms's setter to execute the filter, so have to set the pro... | javascript | {
"resource": ""
} | |
q43303 | xPath | train | function xPath(xPathString) {
var xResult = document.evaluate(xPathString, document, null, 0, null);
var xNodes = [];
var xRes = xResult.iterateNext();
while (xRes) {
xNodes.push(xRes);
xRes = xResult.iterateNext();
}
return xNodes;
} | javascript | {
"resource": ""
} |
q43304 | execWaitReadyFunctions | train | function execWaitReadyFunctions() {
if (isReady()) {
logger.info('Page is ready. Executing ' + callbacksOnReady.length + ' functions that are waiting.');
for (var i = 0; i < callbacksOnReady.length; i++) {
var callback = callbacksOnReady[i];
callback();
}
}
} | javascript | {
"resource": ""
} |
q43305 | whenReady | train | function whenReady(funcToExecute) {
if (isReady()) {
logger.info('Page is already loaded, instantly executing!');
funcToExecute();
return;
}
logger.info('Waiting for page to be ready');
callbacksOnReady.push(funcToExecute);
} | javascript | {
"resource": ""
} |
q43306 | train | function (adUnitSettings) {
var containers = adUnitSettings.containers;
var adContainers = [];
for (var i = 0; i < containers.length; i++) {
var container = containers[i];
var containerXPath = container.xPath;
var adContainerElements = xPath(containerXPath)... | javascript | {
"resource": ""
} | |
q43307 | render | train | function render(expr, traverse, path, state) {
if (isString(expr)) {
utils.append(expr, state);
} else if (Array.isArray(expr)) {
expr.forEach(function(w) {
render(w, traverse, path, state);
});
} else {
utils.move(expr.range[0], state);
traverse(expr, path, state);
utils.catchup(exp... | javascript | {
"resource": ""
} |
q43308 | renderExpressionMemoized | train | function renderExpressionMemoized(expr, traverse, path, state) {
var evaluated;
if (expr.type === Syntax.Identifier) {
evaluated = expr.name;
} else if (isString(expr)) {
evaluated = expr;
} else {
evaluated = genID('var');
utils.append(evaluated + ' = ', state);
render(expr, traverse, path,... | javascript | {
"resource": ""
} |
q43309 | renderDesructuration | train | function renderDesructuration(pattern, expr, traverse, path, state) {
utils.catchupNewlines(pattern.range[1], state);
var id;
if (pattern.type === Syntax.ObjectPattern && pattern.properties.length === 1) {
id = expr;
} else if (pattern.type === Syntax.ArrayPattern && pattern.elements.length === 1) {
i... | javascript | {
"resource": ""
} |
q43310 | train | function(inPositions) {
var p = inPositions;
// yay math!, rad -> deg
var a = Math.asin(p.y / p.h) * (180 / Math.PI);
// fix for range limits of asin (-90 to 90)
// Quadrants II and III
if (p.x < 0) {
a = 180 - a;
}
// Quadrant IV
if (p.x > 0 && p.y < 0) {
a += 360;
}
return a;
... | javascript | {
"resource": ""
} | |
q43311 | train | function(inPositions) {
// the least recent touch and the most recent touch determine the bounding box of the gesture event
var p = inPositions;
// center the first touch as 0,0
return {
magnitude: p.h,
xcenter: Math.abs(Math.round(p.fx + (p.x / 2))),
ycenter: Math.abs(Math.round(p.fy + (p.y / 2... | javascript | {
"resource": ""
} | |
q43312 | train | function(inInfos, inCommonInfo) {
if (inInfos) {
var cs = [];
for (var i=0, ci; (ci=inInfos[i]); i++) {
cs.push(this._createComponent(ci, inCommonInfo));
}
return cs;
}
} | javascript | {
"resource": ""
} | |
q43313 | train | function(inMethodName, inEvent, inSender) {
var fn = inMethodName && this[inMethodName];
if (fn) {
return fn.call(this, inSender || this, inEvent);
}
} | javascript | {
"resource": ""
} | |
q43314 | train | function(inMessageName, inMessage, inSender) {
//this.log(inMessageName, (inSender || this).name, "=>", this.name);
if (this.dispatchEvent(inMessageName, inMessage, inSender)) {
return true;
}
this.waterfallDown(inMessageName, inMessage, inSender || this);
} | javascript | {
"resource": ""
} | |
q43315 | restoreState | train | function restoreState(top_err) {
if (previous_state === true) {
that.pause(function madePaused(err) {
// Ignore errors?
callback(top_err);
});
} else {
callback(top_err);
}
} | javascript | {
"resource": ""
} |
q43316 | done | train | function done(err) {
that._gcw = 'done_get_creatures';
bomb.defuse();
// Unsee the 'getting_creatures' event
that.unsee('getting_creatures');
// Call next on the next tick (in case we call back with an error)
Blast.nextTick(next);
if (err) {
that.log('error', 'Error getting creatures: ' + ... | javascript | {
"resource": ""
} |
q43317 | flux | train | function flux (path) {
return function (done) {
fs.createReadStream(resolve(__dirname, path))
.pipe(docflux())
.pipe(docflux.markdown({depth: DEPTH, indent: INDENT}))
.pipe(concat(function (data) {
done(null, data.toString())
}))
}
} | javascript | {
"resource": ""
} |
q43318 | PushInitiator | train | function PushInitiator(applicationId, password, contentProviderId, evaluation) {
this.applicationId = applicationId;
this.authToken = new Buffer(applicationId + ':' + password).toString('base64');
this.contentProviderId = contentProviderId;
this.isEvaluation = evaluation || false;
} | javascript | {
"resource": ""
} |
q43319 | findById | train | function findById(id, cb) {
db.getClient(function(err, client, done) {
client.query(SELECT_ID, [id], function(err, r) {
var result = r && r.rows[0];
if(!err && !result) err = new exceptions.NotFound();
if(err) {
cb(err);
done(err);
} else {
cb(null, result);
... | javascript | {
"resource": ""
} |
q43320 | create | train | function create(body, cb) {
var validates = Schema(body);
if(!validates) {
return cb(new exceptions.BadRequest());
}
body.slug = string.slugify(body.title);
var q = qb.insert(body);
db.getClient(function(err, client, done) {
client.query(q[0], q[1], function(err, r) {
if(err) {
if(e... | javascript | {
"resource": ""
} |
q43321 | all | train | function all(options, cb) {
var q
, page = Number(options.page) || 1
, limit = Number(options.limit) || conf.objects_by_page
, offset = (page - 1) * limit;
count(function(err, count) {
if(err) { return cb(err); }
q = select('LEFT JOIN');
q += ' LIMIT ' + limit + ' OFFSET ' + offset;
d... | javascript | {
"resource": ""
} |
q43322 | nodeJsGlobalResolverFn | train | function nodeJsGlobalResolverFn(normalizedId) {
var globalId = normalizedId.id;
var x = global[globalId];
if (!x) {
var msg = 'Could not find global Node module [' + globalId + ']';
throw new Error(buildMissingDepMsg(msg, globalId, Object.keys(global)));
}
return x;
} | javascript | {
"resource": ""
} |
q43323 | nodeModulesResolverFn | train | function nodeModulesResolverFn(normalizedId) {
if (!nodeModulesAt) {
throw new Error('Before you can load external dependencies, you must specify where node_modules can be found by ' +
'setting the \'nodeModulesAt\' option when creating the context');
}
var extId = normalizedId.id;
var modulePath = pat... | javascript | {
"resource": ""
} |
q43324 | idbReadableStream | train | function idbReadableStream(db, storeName, opts) {
if (typeof db !== 'object') throw new TypeError('db must be an object')
if (typeof storeName !== 'string') throw new TypeError('storeName must be a string')
if (opts == null) opts = {}
if (typeof opts !== 'object') throw new TypeError('opts must be an object')
... | javascript | {
"resource": ""
} |
q43325 | bin | train | function bin(argv) {
var uri = argv[2]
if (!uri) {
console.error('uri is required')
}
shell.ls(uri, function(err, arr) {
for (i=0; i<arr.length; i++) {
console.log(arr[i])
}
})
} | javascript | {
"resource": ""
} |
q43326 | fileExist | train | function fileExist(fileName) {
return new Promise((resolve, reject) => {
fs.stat(fileName, (err, stats) => {
if (err === null && stats.isFile()) {
resolve(fileName);
} else {
resolve(false);
}
});
});
} | javascript | {
"resource": ""
} |
q43327 | SQL | train | function SQL(strs) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var values = [];
var text = strs.reduce(function (prev, curr, i) {
var arg = args[i - 1];
if (arg instanceof InsertValue) {
return... | javascript | {
"resource": ""
} |
q43328 | AsyncSimpleIterator | train | function AsyncSimpleIterator (options) {
if (!(this instanceof AsyncSimpleIterator)) {
return new AsyncSimpleIterator(options)
}
this.defaultOptions(options)
AppBase.call(this)
this.on = utils.emitter.compose.call(this, 'on', this.options)
this.off = utils.emitter.compose.call(this, 'off', this.options)... | javascript | {
"resource": ""
} |
q43329 | checkMediaProfileSpecType | train | function checkMediaProfileSpecType(key, value)
{
if(typeof value != 'string')
throw SyntaxError(key+' param should be a String, not '+typeof value);
if(!value.match('WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY'))
throw SyntaxError(key+' param is not one of [WEBM|MP4|WEBM_VIDEO_ON... | javascript | {
"resource": ""
} |
q43330 | createApplication | train | function createApplication(options) {
options = options || {};
var sapp = new Application();
sapp.sycle = sycle;
if (options.loadBuiltinModels) {
sapp.phase(require('./boot/builtin-models')());
}
return sapp;
} | javascript | {
"resource": ""
} |
q43331 | enqueueAll | train | function enqueueAll() {
for (let i = 0; i < count - 1; i++) {
enqueue();
}
return enqueue();
function enqueue() {
return queue.enqueue(() => new Date());
}
} | javascript | {
"resource": ""
} |
q43332 | bakeFolder | train | function bakeFolder(source, dest) {
var args = createArgs(source, dest, {});
wrapFunction('BakeFolder', args, function () {
args.files = fs.readdirSync(args.source);
args.filters = [filterHidden];
wrapFunction('FilterFiles', args, function () {
args.filters.forEach(function (filter) {
... | javascript | {
"resource": ""
} |
q43333 | defaults | train | function defaults(route, name, handle) {
if (typeof route === 'function') {
handle = route;
name = handle.name;
route = '/';
}
else if (typeof name === 'function') {
handle = name;
name = handle.name;
}
// A name needs to be provided
if (!name) throw new NameError();
// wrap sub-apps... | javascript | {
"resource": ""
} |
q43334 | NameError | train | function NameError(message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'Middleware Name Error';
this.message = message || 'The argument must be a named function or supply a name';
} | javascript | {
"resource": ""
} |
q43335 | ExistsError | train | function ExistsError(name, message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'Middleware Exists Error';
this.message = message || 'Middleware named ' + name + ' already exists. Provide an alternative name.';
} | javascript | {
"resource": ""
} |
q43336 | NotFoundError | train | function NotFoundError(name) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'Middleware Not Found Error';
this.message = name + ' not found in the current stack';
} | javascript | {
"resource": ""
} |
q43337 | Process | train | function Process(settings) {
// save arguments
this.settings = settings;
// build args
this.args = [settings.file].concat(settings.args || []);
// build env
this.env = helpers.mergeObject({}, settings.env || process.env);
if (settings.options) {
this.env.spawnOptions = JSON.stringify... | javascript | {
"resource": ""
} |
q43338 | train | function () {
var suicide = self.suicide;
self.suicide = false;
self.alive = false;
self.emit('stop', suicide);
} | javascript | {
"resource": ""
} | |
q43339 | forceClose | train | function forceClose(channel) {
if (!channel) return;
var destroyer = setTimeout(function () {
channel.destroy();
}, 200);
channel.once('close', function () {
clearTimeout(destroyer);
});
} | javascript | {
"resource": ""
} |
q43340 | interceptDeath | train | function interceptDeath(process, events) {
var closeEvent = helpers.support.close;
// all channels are closed
process.once(closeEvent ? 'close' : 'exit', events.close);
// the process died
if (closeEvent) {
process.once('exit', events.exit);
} else {
// intercept internal onexit c... | javascript | {
"resource": ""
} |
q43341 | hashsum | train | function hashsum(hash, str) {
// you have to convert from string to array buffer
var ab
// you have to represent the algorithm as an object
, algo = { name: algos[hash] }
;
if ('string' === typeof str) {
ab = str2ab(str);
} else {
ab = str;
}
... | javascript | {
"resource": ""
} |
q43342 | ab2hex | train | function ab2hex(ab) {
var dv = new DataView(ab)
, i
, len
, hex = ''
, c
;
for (i = 0, len = dv.byteLength; i < len; i += 1) {
c = dv.getUint8(i).toString(16);
if (c.length < 2) {
c = '0' + c;
}
hex += c;
}
ret... | javascript | {
"resource": ""
} |
q43343 | str2ab | train | function str2ab(stringToEncode, insertBom) {
stringToEncode = stringToEncode.replace(/\r\n/g,"\n");
var utftext = []
, n
, c
;
if (true === insertBom) {
utftext[0] = 0xef;
utftext[1] = 0xbb;
utftext[2] = 0xbf;
}
for (n = 0; n < stringT... | javascript | {
"resource": ""
} |
q43344 | escapeCurly | train | function escapeCurly (text, escapes) {
var newText = text.slice (0, escapes[0]);
for (var i = 0; i < escapes.length; i += 3) {
var from = escapes[i];
var to = escapes[i + 1];
var type = escapes[i + 2];
// Which escape do we have here?
if (type === 0) { newText += '{{';
} else { ... | javascript | {
"resource": ""
} |
q43345 | train | function(input, output, literal, cb) {
var text = '';
input.on ('data', function gatherer (data) {
text += '' + data; // Converting to UTF-8 string.
});
input.on ('end', function writer () {
try {
var write = function(data) { output.write(data); };
template(text)(write, literal);
} cat... | javascript | {
"resource": ""
} | |
q43346 | train | function(input) {
var code = 'var $_isidentifier = ' + $_isidentifier.toString() + ';\n' +
// FIXME: could we remove that eval?
'eval((' + literaltovar.toString() + ')($_scope));\n';
code += 'var $_parsers = {\n';
var parsernames = Object.keys(parsers);
for (var i = 0; i < parsernames.length; i++) {
... | javascript | {
"resource": ""
} | |
q43347 | train | function(input) {
var code = 'var $_parsers = {\n';
var parsernames = Object.keys(parsers);
for (var i = 0; i < parsernames.length; i++) {
code += ' ' + JSON.stringify(parsernames[i]) + ': ' +
parsers[parsernames[i]].toString() + ',\n';
};
code += '}\n';
code += compile(input) + '\nif (typeof $_e... | javascript | {
"resource": ""
} | |
q43348 | train | function (applicationId, deviceDetails, environment) {
if(!applicationId) {
logger.wtf('No applicationID specified');
}
this.applicationId = applicationId;
this.deviceDetails = deviceDetails;
this.environment = environment;
this._currentAds = [];
this._loadingAds = [];
this.... | javascript | {
"resource": ""
} | |
q43349 | getNewToken | train | function getNewToken(credentials, oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
... | javascript | {
"resource": ""
} |
q43350 | listLabels | train | function listLabels(auth) {
var gmail = google.gmail('v1');
gmail.users.labels.list({
auth: auth,
userId: 'me',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var labels = response.labels;
... | javascript | {
"resource": ""
} |
q43351 | processDeltas | train | function processDeltas(deltas) {
let updates = {
changed: {},
removed: {}
};
deltas.forEach(delta => {
const entityType = delta[0];
const changeType = delta[1];
const entity = delta[2];
const key = _getEntityKey(entityType, entity);
if (!key) {
// We don't know how to manage this... | javascript | {
"resource": ""
} |
q43352 | _getEntityKey | train | function _getEntityKey(entityType, entity) {
switch (entityType) {
case 'remote-application':
case 'application':
case 'unit':
return entity.name;
case 'machine':
case 'relation':
return entity.id;
case 'annotation':
return entity.tag;
default:
// This is an unknown... | javascript | {
"resource": ""
} |
q43353 | _parseEntity | train | function _parseEntity(entityType, entity) {
switch (entityType) {
case 'remote-application':
return parsers.parseRemoteApplication(entity);
case 'application':
return parsers.parseApplication(entity);
case 'unit':
return parsers.parseUnit(entity);
case 'machine':
return parsers... | javascript | {
"resource": ""
} |
q43354 | getMilliseconds | train | function getMilliseconds( time ) {
if ( typeof time == 'number' ) {
return time;
}
var matches = time.match( /(^\d*\.?\d*)(\w*)/ );
var num = matches && matches[1];
var unit = matches && matches[2];
if ( !num.length ) {
return 0;
}
num = parseFloat( num );
var mult = msUnits[ unit ] || 1;
re... | javascript | {
"resource": ""
} |
q43355 | compileFile | train | function compileFile(srcFullPath, saveOutFullPath, onlyCopy) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var content = fs.readFileSync(srcFullPath, 'utf8');
//when get file content empty, maybe file is locked
if (!content) {
return;
}
// only copy file cont... | javascript | {
"resource": ""
} |
q43356 | getFiles | train | function getFiles(paths) {
var result = fileUtil.getAllFiles(paths);
var files = result.map(function (item) {
return item.relativePath;
// return path.join(item.basePath, item.relativePath);
});
return files;
} | javascript | {
"resource": ""
} |
q43357 | TypedOneOf | train | function TypedOneOf (config) {
const oneOf = this;
// validate oneOf
if (!config.hasOwnProperty('oneOf')) {
throw Error('Invalid configuration. Missing required one-of property: oneOf. Must be an array of schema configurations.');
}
if (!Array.isArray(config.oneOf) || config.oneOf.filter(v ... | javascript | {
"resource": ""
} |
q43358 | bin | train | function bin (argv) {
program.version(pkg.version)
.usage('[options] <sourceURI> <destURI>')
.parse(argv)
var sourceURI = program.args[0]
var destURI = program.args[1]
if (!sourceURI || !destURI) {
program.help()
}
shell.mv(sourceURI, destURI, function (err, res, uri) {
if (!err) {
debu... | javascript | {
"resource": ""
} |
q43359 | train | function(evt) {
if (evt !== 'change' && evt !== 'rename') {
return;
}
fs.stat(file, function(err, current) {
if (err) {
self.logger_.error(err.message);
self.emit('error.watch', err.message);
return;
}
if (current.size !== prev.size || +current.mtime > +prev.m... | javascript | {
"resource": ""
} | |
q43360 | train | function(fn, syntheticArgs) {
var $this = this;
syntheticArgs = syntheticArgs || [];
/**
* Ensure to have it in the next event loop for better async
*/
var processResponder = function() {
try {
if (fn) {
/**
* Insert a done() or ok() argument to other needed arguments
*/
synth... | javascript | {
"resource": ""
} | |
q43361 | train | function() {
try {
if (fn) {
/**
* Insert a done() or ok() argument to other needed arguments
*/
syntheticArgs.unshift(function() {
/**
* Call the next in queue
*/
$this.next.apply($this, arguments);
});
/**
* Call the function finally
*/
... | javascript | {
"resource": ""
} | |
q43362 | train | function(err) {
/**
* If err is an Error object, break the chain and call catch
*/
if (err && (err.constructor.name === "Error" || err.constructor.name === "TypeError") && this.onCatch) {
this.onCatch(err);
return;
}
var nextFn = this.fnStack.shift();
if (nextFn) {
/**
* Ensure arguments a... | javascript | {
"resource": ""
} | |
q43363 | train | function(xml, command, version) {
var formatVersion = version || JSDAS.Formats.current;
var format = JSDAS.Formats[formatVersion][command];
var json = JSDAS.Parser.parseElement(xml, format);
return json;
} | javascript | {
"resource": ""
} | |
q43364 | train | function(xml, format) {
var out = {};
//The Document object does not have all the functionality of a standard node (i.e. it can't have attributes).
//So, if we are in the Document element, move to its ¿¿only?? child, the root.
if(xml.nodeType == 9) { //detect the Document node type
xml = xml.firstChild;
... | javascript | {
"resource": ""
} | |
q43365 | train | function(url, callback, errorcallback){
if (!this.initialized) {
this.initialize();
}
var xmlloader = JSDAS.XMLLoader; //get a reference to myself
var usingCORS = true;
var xhr = this.xhrCORS('GET', url);
if(!xhr) { //if the browser is not CORS capable, fallback to proxy if available
if(this.pro... | javascript | {
"resource": ""
} | |
q43366 | train | function(xhr){
if (xhr && (xhr.readyState == 4)) {
if (xmlloader.httpSuccess(xhr)) {
processResponse(xhr);
}
else { //if it failed, it mighht be that the source has no CORS enabled. In such case, fallback to proxy before erroring
if(usingCORS && xmlloader.proxyURL) { //if it failed when using C... | javascript | {
"resource": ""
} | |
q43367 | writeLaunchCode | train | function writeLaunchCode(config) {
var { name, stub } = config.holder
if (!name || !stub) {
throw new Error('invalid name or stub')
}
var code = `
;(function () {
var root = document.getElementById('${name}');
if (!root) throw new Error('undefined ${stub} root');
var view = window.${st... | javascript | {
"resource": ""
} |
q43368 | NoiseSampler | train | function NoiseSampler(size) {
if (!size)
throw "no size specified to NoiseSampler";
this.size = size;
this.scale = 1;
this.offset = 0;
this.smooth = true;
this.seamless = false;
// this.scales = [
// 10, 0.1, 0.2, 1
// ];
... | javascript | {
"resource": ""
} |
q43369 | train | function(x, y) {
//avoid negatives
if (this.seamless) {
x = (x%this.size + this.size)%this.size
y = (y%this.size + this.size)%this.size
} else {
x = clamp(x, 0, this.size)
y = clamp(y, 0, this.size)
}
if (this.smooth)
r... | javascript | {
"resource": ""
} | |
q43370 | is | train | function is (constructor, value) {
return value !== null && (value.constructor === constructor || value instanceof constructor);
} | javascript | {
"resource": ""
} |
q43371 | isDataBinaryRobust | train | function isDataBinaryRobust(data) {
// console.log('data is binary ?')
var patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
var text = ensureString(data);
var isBinary = patternVertex.exec(t... | javascript | {
"resource": ""
} |
q43372 | train | function(err, r) {
if (err) {
numberOfValidConnections = numberOfValidConnections - 1;
errorObject = err;
return false;
} else if (r.result['$err']) {
errorObject = r.result;
return false;
} else if (r.result['errmsg']) {
errorObject = r.result;
... | javascript | {
"resource": ""
} | |
q43373 | train | function(options) {
Configurable.call(this);
this._resources = [];
this._serializer = require(__dirname + '/lib/Serializer');
this.setAll( _.extend({}, defaults, options) );
// List of IDs used to find duplicate handlers fast
this._ids = {
// id: handler
... | javascript | {
"resource": ""
} | |
q43374 | makeValidation | train | function makeValidation(name, exp, parser) {
return function (input) {
if (typeof input !== 'string') {
throw new TypeError('Cannot validate ' + name + '. Input must be a string.');
}
var validate = function () {
return input.match(exp) ? true : false;
};
... | javascript | {
"resource": ""
} |
q43375 | pipeEvents | train | function pipeEvents(source, destination, event) {
source.on(event, function (data) {
destination.emit(event, data);
});
} | javascript | {
"resource": ""
} |
q43376 | get | train | function get(key) {
let val = process.env[key];
return val in types ? types[val] : util.isNumeric(val) ? parseFloat(val) : val;
} | javascript | {
"resource": ""
} |
q43377 | set | train | function set(key, val) {
return process.env[key] = (process.env[key] === undefined ? val : process.env[key]);
} | javascript | {
"resource": ""
} |
q43378 | load | train | function load(file) {
let contents = null;
file = path.resolve(file);
// handle .env files
if (constants.REGEX.envfile.test(file)) {
contents = util.parse(fs.readFileSync(file, 'utf8'));
// handle .js/.json files
} else {
contents = require(file);
}
return env(conten... | javascript | {
"resource": ""
} |
q43379 | init | train | function init(){
// set NODE_ENV to --env value
if (argv.env) {
set('NODE_ENV', argv.env);
}
// load evironment files
['./.env', './config/.env', './env', './config/env'].map(file => {
try {
load(file);
} catch(err) {
if (env('DEBUG')) {
... | javascript | {
"resource": ""
} |
q43380 | _expandParentsForNode | train | function _expandParentsForNode(node) {
// get the actual parent nodes in the editor
var parents = [];
$(node).parentsUntil('#tinymce').each(function(index, el) {
parents.push(el.id);
});
parents.reverse();
// TODO handling for readonly mode where only... | javascript | {
"resource": ""
} |
q43381 | selectNode | train | function selectNode($node, selectContents, multiselect, external) {
var id = $node.attr('name');
_removeCustomClasses();
// clear other selections if not multiselect
if (!multiselect) {
if (tree.currentlySelectedNodes.indexOf(id) != -1) {
tre... | javascript | {
"resource": ""
} |
q43382 | resolveCapabilities | train | function resolveCapabilities(capabilities, capabilitiesDictionary) {
if (typeof capabilities !== "string") {
// we do not know how to parse non string capabilities, let's assume it
// is selenium compliant capabilities and return it.
return capabilities;
}
// try to parse as a JSON ... | javascript | {
"resource": ""
} |
q43383 | sinonDoublistFs | train | function sinonDoublistFs(test) {
if (module.exports.trace) {
nodeConsole = require('long-con').create();
log = nodeConsole
.set('nlFirst', true)
.set('time', false)
.set('traceDepth', true)
.create(null, console.log); // eslint-disable-line no-console
nodeConsole.traceMethods('File... | javascript | {
"resource": ""
} |
q43384 | FileStub | train | function FileStub() {
this.settings = {
name: '',
buffer: new Buffer(0),
readdir: false,
parentName: '',
stats: {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 0,
blksize: 4096,
blocks: 0,
atime:... | javascript | {
"resource": ""
} |
q43385 | intermediatePaths | train | function intermediatePaths(sparse) {
const dense = {};
[].concat(sparse).forEach(function forEachPath(path) {
path = rtrimSlash(path);
dense[path] = {}; // Store as keys to omit dupes
const curParts = trimSlash(path).split('/');
const gapParts = [];
curParts.forEach(function forEachPart(part) {
... | javascript | {
"resource": ""
} |
q43386 | withOptions | train | function withOptions(scope, defaultOptions) {
return function(plugin, options) {
return scope.use(this, scope, plugin, scope.combine(defaultOptions, options))
}
} | javascript | {
"resource": ""
} |
q43387 | train | function (o) {
var r = [];
for (var i in o) {
if (o.hasOwnProperty(i)) {
r.push(i);
}
}
return r;
} | javascript | {
"resource": ""
} | |
q43388 | splitKeys | train | function splitKeys (keys) {
if (typeof(keys) === 'string') {
return keys.replace(/^\s*\.\s*/,'')
.replace(/(?:\s*\.\s*)+/g, '.')
.split('.');
}
else if (Array.isArray(keys)) {
return [].concat(keys);
}
return;
} | javascript | {
"resource": ""
} |
q43389 | Ops | train | function Ops (ref, key) {
this.ref = ref;
this.key = key;
if (this.ref[this.key] === undefined) {
this.ref[this.key] = 0;
}
this._toNumber();
this.isNumber = (typeof this.ref[this.key] === 'number');
this.isBoolean = (typeof this.ref[this.key] === 'boolean');
this.isString = (typeof this.ref[this.k... | javascript | {
"resource": ""
} |
q43390 | _createList | train | function _createList(list) {
var listContent = [];
if(list) {
listContent.push("<table>");
Ember.$.each(list, function (property, value) {
listContent.push(
"<tr><td>",
property,
"</td><td>",
value,
"</td></tr>"
);
});
listContent.push("</table>"... | javascript | {
"resource": ""
} |
q43391 | _setData | train | function _setData(data) {
_element.find('.tip-title').html(data.title || "");
_element.find('.tip-text').html(data.text || "");
_element.find('.tip-text')[data.text ? 'show' : 'hide']();
_element.find('.tip-list').html(_createList(data.kvList) || "");
} | javascript | {
"resource": ""
} |
q43392 | train | function (tipElement, svg) {
_element = tipElement;
_bubble = _element.find('.bubble');
_svg = svg;
_svgPoint = svg[0].createSVGPoint();
} | javascript | {
"resource": ""
} | |
q43393 | train | function (node, data, event) {
var point = data.position || (node.getScreenCTM ? _svgPoint.matrixTransform(
node.getScreenCTM()
) : {
x: event.x,
y: event.y
}),
windMid = _window.height() >> 1,
winWidth = _window.width(),
showAbove = point.y < ... | javascript | {
"resource": ""
} | |
q43394 | report | train | function report(test) {
return {
test_file: test.file + ': ' + test.fullTitle(),
start: test.start,
end: test.end,
exit_code: test.exit_code,
elapsed: test.duration / 1000,
error: errorJSON(test.err || {}),
url: test.url,
status: test.state
};
} | javascript | {
"resource": ""
} |
q43395 | writeLogs | train | function writeLogs(test, dirName) {
var logs =
test.fullTitle() +
'\n' +
test.file +
'\nStart: ' +
test.start +
'\nEnd: ' +
test.end +
'\nElapsed: ' +
test.duration +
'\nStatus: ' +
test.state;
if (test.state === 'fail') {
logs += '\nError: ' + test.err.stack;
}
m... | javascript | {
"resource": ""
} |
q43396 | generateFileName | train | function generateFileName(className) {
return className
.replace(/component/gi, '')
.replace(/system/gi, '')
.replace('2D', '2d')
.replace('3D', '3d')
.replace(/^[A-Z]/, function(c) {
return c.toLowerCase();
})
.replace(/[A-Z]/g, function(c) {
... | javascript | {
"resource": ""
} |
q43397 | train | function(ast, reporter, version) {
this.ast = ast;
this.reporter = reporter;
this.psykickVersion = 'psykick' + version;
// Store the Templates so the Systems can access them later
this._templatesByName = {};
} | javascript | {
"resource": ""
} | |
q43398 | CoreEvent | train | function CoreEvent(typeArg, detail) {
if (detail == undefined) {
detail = {};
}
/**
* Error:
* Failed to construct 'CustomEvent': Please use the 'new' operator, this
* DOM object constructor cannot be called as a function.
*
* In reason of that the browser did not allow to extend CustomEvent i... | javascript | {
"resource": ""
} |
q43399 | Ajax | train | function Ajax(method, url, sendData) {
DOMEventListener.call(this);
/**
* Request object.
*
* @access protected
* @type {XMLHttpRequest}
*/
this._request = new Ajax.XHRSystem();
/**
* Method of the request.
*
* @access protected
* @type {String}
*/
this._method = method;
... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.