_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37500 | performCmd | train | function performCmd(repoURL, path){
var deferred = Q.defer();
if(errorOccured === true){
deferred.reject();
return deferred.promise;
}
if(grunt.file.isDir(path) && options.overWrite === false){
deferred.resolve(false);
return deferred.promise;
}
va... | javascript | {
"resource": ""
} |
q37501 | cloneRepo | train | function cloneRepo(item){
var deferred = Q.defer();
var repoURL = item.repo;
var path = item.path;
deleteOldFiles(path).
then(function(){
return performCmd(repoURL, path);
}).then(function(success){
return npmInstall(path, success);
}).then(function(success){
... | javascript | {
"resource": ""
} |
q37502 | getItemList | train | function getItemList(object, path){
for (var prop in object){
if(typeof object[prop] === 'object'){
var newPath = path + (prop+'/');
getItemList(object[prop], newPath);
}else{
var item = {
path : path+prop,
repo : object[prop]
... | javascript | {
"resource": ""
} |
q37503 | npmInstall | train | function npmInstall(path, success){
var deferred = Q.defer();
// 'success' is a flag passed from the perform cmd function which states whether the function ran
if(success === false){
deferred.resolve(success);
return deferred.promise;
}
var hasPackage = grunt.file.isFile... | javascript | {
"resource": ""
} |
q37504 | train | function(data, param, value) {
if(_definition[param]) {
var paramInstance = Param(param, value, _definition[param]);
_definition[param].param.forEach(function(p) {
data[p] = paramInstance;
});
} else {
// Unsupported if operating in strict mode
if(_useStrict) {
thr... | javascript | {
"resource": ""
} | |
q37505 | train | function() {
var options = [];
Object.keys(_definition).forEach((key, i, list) => {
if(options.indexOf(_definition[key]) == -1) {
options.push(_definition[key]);
}
});
return options;
} | javascript | {
"resource": ""
} | |
q37506 | train | function(name) {
// Parse once
if(!_data) _data = _parse(_args);
// Fallback to defaults
var param = _data[name] || _definition[name];
// False for not provided
return (!param) ? false : param.value();
} | javascript | {
"resource": ""
} | |
q37507 | train | function(config, level, floor, callback) {
var floors = [];
var fromIdentifier = level ? level.identifier : null;
var options = FloorSelectionOptions.createFromIdentifiers(fromIdentifier, floor);
try{
floors = FloorController.getFloors(config.floorsDir, options);
return... | javascript | {
"resource": ""
} | |
q37508 | train | function(config, floors, ascending, logger, levelController, callback) {
var self = this;
//Itterate migrations files
async.eachSeries(floors, function(floor, callback) {
var parameters = new FloorWorkerParameters(config, logger, floor);
var floorWorker = require(floor.filePath);
va... | javascript | {
"resource": ""
} | |
q37509 | train | function(level, callback) {
_getFloors(config, level, floor, function(error, floors, options) {
return callback(error, floors, options);
})
} | javascript | {
"resource": ""
} | |
q37510 | train | function(floors, options, callback) {
if(floors != null && floors.length > 0) {
_moveElevator(config, floors, options.ascending, logger, levelController, function(error) {
return callback(error, floors, options);
});
} else {... | javascript | {
"resource": ""
} | |
q37511 | train | function(floors, options, callback) {
if(floors && options && options.ascending === false) {
levelController.saveCurrentLevel(Level.create(options.identifierRange.min), function(error) {
if(error) {
logger.error('>>>> Stuck at floor... | javascript | {
"resource": ""
} | |
q37512 | compile | train | function compile(emit) {
self.bundler.run(function(err, stats) {
// Error handling
if (err || stats.compilation.errors.length) {
// Over time we expect webpack's resolution system to change. We choose to attempt
// package installations by catching errors so as to maximize forward-comp... | javascript | {
"resource": ""
} |
q37513 | mock | train | function mock(test, object, functionName, newFunction) {
if (typeof object === "undefined") {
throw Error("Attempting to mock function " + functionName + " of undefined.")
}
// Allow test writers to still let methods pass through, in case that's needed.
var unmockedName = "unmocked_" + function... | javascript | {
"resource": ""
} |
q37514 | validUUID | train | function validUUID(uuid) {
// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is a hexadecimal digit and
// y is 8,9, A, or B
var uuidRegex = /^[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12}$/i,
result;
result = uuidRegex.exec(uuid);
return result !== null;
} | javascript | {
"resource": ""
} |
q37515 | validTimestamp | train | function validTimestamp(timestamp) {
// ^year-month-day(Thour:min:secms?timezone)?$
var year = /((?:[1-9][0-9]*)?[0-9]{4})/,
month = /(1[0-2]|0[1-9])/,
day = /(3[01]|0[1-9]|[12][0-9])/,
hour = /(2[0-3]|[01][0-9])/,
minute = /([0-5][0-9])/,
second = /([0-5][0-9])/,
... | javascript | {
"resource": ""
} |
q37516 | validatePacket | train | function validatePacket(type, packet, fn) {
debug('Type:', type);
debug('Packet:', packet);
if (!tv4.validate(packet, defaultSchemas[type])) {
return fn(tv4.error);
}
if (packet.hasOwnProperty('provider') && !validUUID(packet.provider)) {
return fn(new E... | javascript | {
"resource": ""
} |
q37517 | validateData | train | function validateData(data, schema, fn) {
debug('Schema:', schema);
debug('Data:', data);
if (!tv4.validate(data, schema)) {
return fn(tv4.error);
}
return fn(null, true);
} | javascript | {
"resource": ""
} |
q37518 | Wrapper | train | function Wrapper(manifest) {
var header = manifest.header ||
'(function(require, module, exports) { // ${name}@${version}\n\n' +
(manifest.isJSON ? 'module.exports = ' : '');
var footer = manifest.footer ||
(manifest.isJSON ? ';' : '') +
'\n\n})(fin.Hypergrid.require, fin.Hyper... | javascript | {
"resource": ""
} |
q37519 | getDefaultOptions | train | function getDefaultOptions() {
const resources = {
classnames: {
root: '',
body: ''
},
meta: [],
scriptsFoot: {
files: [],
inline: []
},
scriptsHead: {
files: [],
inline: []
},
sty... | javascript | {
"resource": ""
} |
q37520 | raiseIndent | train | function raiseIndent(lines, offset) {
offset = offset || ' ';
return lines.map((line) => offset + line);
} | javascript | {
"resource": ""
} |
q37521 | formalizeWrap | train | function formalizeWrap(wrap) {
const result = {before: '', after: ''};
if ((typeof wrap === 'string' && wrap.length > 0) || typeof wrap === 'number') {
result.before = result.after = wrap;
} else if (Array.isArray(wrap) && wrap.length > 0) {
result.before = [].slice.call(wrap, 0, 1)[0];
... | javascript | {
"resource": ""
} |
q37522 | getBlockOptions | train | function getBlockOptions(annotation, defaults) {
const optionValues = annotation.split(/\w+\:/)
.map((item) => item.replace(/<!--\s?|\s?-->|^\s+|\s+$/, ''))
.filter((item) => !!item.length);
const optionKeys = annotation.match(/(\w+)\:/gi).map((item) => item.replace(/[^\w]/, ''));
defaults ... | javascript | {
"resource": ""
} |
q37523 | convertResponse | train | function convertResponse(response) {
var results = {tables: [], indexes: []};
var i=0;
var start=0;
if (dbName) {
results.db = response[0];
start++;
i++;
}
while (i < start + tableNames.length) {
tableName = tableNames[i-start];
results.tables[... | javascript | {
"resource": ""
} |
q37524 | delegate | train | function delegate(client, fn) {
// Add this function to the current client
// and wrap with a connection check
client[fn] = function(...args) {
let self = this;
let p = null;
if (sand.profiler && sand.profiler.enabled) {
// Build the profiler request
let req = `riak ${fn} `;
if (args... | javascript | {
"resource": ""
} |
q37525 | adjustCommandArgument | train | function adjustCommandArgument(argObj) {
if (typeof argObj === "number") {
return argObj.toString()
} else if (typeof argObj === "string") {
return argObj
} else if (!argObj) {
return ""
} else {
throw new RedisCommandError(`Argument: ${inspect(argObj)}`)
}
} | javascript | {
"resource": ""
} |
q37526 | combineSearch | train | function combineSearch(tp1, tp2) {
return tp1.map(travelPlan => {
let arrival = new Date(travelPlan.legs[travelPlan.legs.length - 1].arrival)
let bestWaitTime = Infinity
let bestTravelPlan2 = tp2[0]
// Find the most appropriate corresponding second travel plan.
for (let i = 0; i < tp2.length; i++)... | javascript | {
"resource": ""
} |
q37527 | verifySize | train | function verifySize(correctSize, filepath) {
return calculateSize(filepath).then(size => {
if (size !== correctSize) {
throw new Error(`Incorrect file size: expected ${correctSize}, got ${size}`);
}
return true;
});
} | javascript | {
"resource": ""
} |
q37528 | calculateSize | train | function calculateSize(filepath) {
return new Promise((fulfill, reject) => {
fs.stat(filepath, (err, stats) => {
if (err) return reject(err);
fulfill(stats.size);
});
});
} | javascript | {
"resource": ""
} |
q37529 | train | function () {
'use strict';
var options = {
config: {
relative: true
},
src: './index.html', // source file with types of files to be glob-injected
files: [// relative paths to files to be globbed
'!./node_modules/**/*',
'!./_gulp/*',
'./**/*'
],
dest: './', // desti... | javascript | {
"resource": ""
} | |
q37530 | train | function () {
'use strict';
var options = {
config: {
starttag: '// inject:{{ext}}',
endtag: '// endinject',
addRootSlash: false,
relative: true,
transform: function (filepath) {
return '@import \'' + filepath + '\';';
}
},
src: './styles/style.scss',
file... | javascript | {
"resource": ""
} | |
q37531 | toArray | train | function toArray(set) {
var ret = [];
set.forEach(function(element) {
ret.push(element);
});
return ret;
} | javascript | {
"resource": ""
} |
q37532 | train | function() {
let schemas = utils.parseArg(arguments);
schemas.forEach(function(schema) {
utils.assert(schema.isOvt, `${utils.obj2Str(schema)} is not a valid ovt schema`);
});
} | javascript | {
"resource": ""
} | |
q37533 | _default | train | async function _default(config, routesConfig) {
const res = await (0, _startApp.default)(config);
const {
url,
app,
router,
middleware,
connect
} = res;
let methods;
if (routesConfig) {
methods = await (0, _routes.initRoutes2)(routesConfig, middleware, router);
const routes = rout... | javascript | {
"resource": ""
} |
q37534 | ip | train | function ip(input, output) {
var i = 0;
var event = input[0];
var out = [ output ];
for ( var ips in event) {
++i;
out.push([ ips, cyan + event[ips].counter + close ]);
}
if (i === 0) {
return [];
}
out.push('', [ 'unique ip', ansi.underline.open + i + ansi.underline.close ],
'');
ret... | javascript | {
"resource": ""
} |
q37535 | cc | train | function cc(input, output) {
var event = input[0];
var out = [ output ];
for ( var a in event) {
if (a != 'undefined') {
out.push([ a, cyan + event[a].counter + close ]);
}
}
if (out.length < 2) {
return [];
}
out.push('');
return out;
} | javascript | {
"resource": ""
} |
q37536 | avg | train | function avg(input, output) {
var event = input[0];
if (event.what === 0 && event.total === 0) {
return [];
}
return [ output, [ 'total', cyan + event.what.toFixed(3) + close ],
[ 'average', cyan + (event.what / event.total).toFixed(3) + close ],
[ 'max', cyan + event.max.toFixed(3) + close ],
... | javascript | {
"resource": ""
} |
q37537 | addParameter | train | function addParameter(data, parameter) {
var regex = '(' + parameter + '=[a-z0-9-]+)';
var search = window.location.search.match(regex);
if (search) {
data.push(search[1]);
}
var hash = window.location.hash.match(regex);
if (hash) {... | javascript | {
"resource": ""
} |
q37538 | getClickDataset | train | function getClickDataset(path) {
var el;
for (var i = 0; i < path.length; i++) {
el = path[i];
if (el.dataset.nctr !== undefined) {
return el.dataset;
}
}
return null;
} | javascript | {
"resource": ""
} |
q37539 | leave | train | function leave() {
var data = [];
data.push('leave=' + Math.floor(Math.random() * 10000));
post(data.join('&'), trackingUrl);
} | javascript | {
"resource": ""
} |
q37540 | initOnClick | train | function initOnClick() {
var clicks = document.querySelectorAll('[data-nctr]');
for (var i = 0; i < clicks.length; i++) {
var tag = clicks[i];
if (tag.addEventListener) {
tag.addEventListener("click", clickTrack, false);
} else... | javascript | {
"resource": ""
} |
q37541 | clickTrack | train | function clickTrack(event) {
var dataset = getClickDataset(event.path);
var data = [];
data.push('click=' + dataset.nctr);
data.push('browser=' + getBrowser());
if (dataset.ncval !== undefined) {
data.push('value=' + dataset.ncval);
... | javascript | {
"resource": ""
} |
q37542 | init | train | function init(obj = {}, prevName = '') {
return new Proxy(obj, {
get (target, name) {
if (typeof name === 'symbol' || deflectedProperties.includes(name)) {
return Reflect.get(target, name);
}
ns.resetTo(prevName);
ns.push(name);
let... | javascript | {
"resource": ""
} |
q37543 | digits | train | function digits(val, num, ch) {
return pad(val, num - val.length, ch);
} | javascript | {
"resource": ""
} |
q37544 | compile | train | function compile(templates) {
templates.forEach(partial => {
partials[partial.name] = Handlebars.compile(partial.source);
Handlebars.registerPartial(partial.name, partials[partial.name]);
});
} | javascript | {
"resource": ""
} |
q37545 | registerHandlebarsHelpers | train | function registerHandlebarsHelpers() {
Handlebars.registerHelper('foreach', function(arr, options) {
if (options.inverse && !arr.length) {
return options.inverse(this);
}
return arr
.map(function(item, index) {
item.$index = index;
item.$first = index === 0;
item.$last ... | javascript | {
"resource": ""
} |
q37546 | wrapData | train | function wrapData(entry, data, token) {
let symbol = wrapSymbols[entry.special];
if (!symbol) return data;
let symbolVal = new SymbolValue(symbol);
if (token) {
symbolVal.line = token.line;
symbolVal.column = token.column;
}
let result = new PairValue(symbolVal, new PairValue(data));
entry.special... | javascript | {
"resource": ""
} |
q37547 | pushData | train | function pushData(entry, data, token) {
if (entry.con === 2) {
throw injectError(new Error('Finished pair cannot have more values'),
token);
}
if (token) {
data.line = token.line;
data.column = token.column;
}
let wrappedData = wrapData(entry, data, token);
if (entry.comment) {
entry.c... | javascript | {
"resource": ""
} |
q37548 | parseGroup | train | function parseGroup(tokenizer) {
// Group this functon will return.
var mrow = {tag: 'mrow', children: []};
// Last child of mrow.
var lastItem;
// Current token.
var tkn;
// Current tag.
var tag;
// Macro. This is a function with this prototype: (tokenizer, mrow).
var macro;
for(;;) {
tkn = ... | javascript | {
"resource": ""
} |
q37549 | hasAttribute | train | function hasAttribute(element, name) {
assertType(element, Node, false, 'Invalid element specified');
let value = element.getAttribute(name);
if (value === '') return true;
return !noval(value);
} | javascript | {
"resource": ""
} |
q37550 | handleStrs | train | function handleStrs(strs, opts) {
const len = longest(strs)
const text = strs
.map(pad(len, opts.justify))
.map(wrap(opts))
.join('')
return {len, text}
} | javascript | {
"resource": ""
} |
q37551 | getBodyObject | train | function getBodyObject ($) {
const container = getContainer($)
// Convert the root element into an array
const children = []
container
.children()
.map((i, el) => {
children.push(convertToNode($(el)[0]))
})
return {
children: children
.filter(child => child !== null),
name: '... | javascript | {
"resource": ""
} |
q37552 | getMetadata | train | function getMetadata ($) {
const image = ($('figure[representativeofpage=true] img').attr('src') ||
$('meta[property="og:image"]').attr('content') ||
'')
const dateStr = ($('meta[property="article:modified_time"]').attr('content') ||
$('meta[property="article:pu... | javascript | {
"resource": ""
} |
q37553 | convertToNode | train | function convertToNode (element) {
switch (element.type) {
case 'tag':
return ['a', 'p', 'strong', 'em', 'b', 'em'].indexOf(element.name) !== -1
? {
name: element.name,
attrs: filterAttributes(element.name, element.attribs),
children: element
... | javascript | {
"resource": ""
} |
q37554 | convertToText | train | function convertToText (object) {
switch (typeof object) {
case 'string':
return object
case 'object':
const attrs = toPairs(object.attrs)
.map(([name, value]) => `${name}="${value}"`)
const tag = [object.name].concat(attrs)
.join(' ')
const ch... | javascript | {
"resource": ""
} |
q37555 | filterAttributes | train | function filterAttributes (name, attributes) {
const filtered = {}
if (attributes.href) {
filtered.href = attributes.href
}
return filtered
} | javascript | {
"resource": ""
} |
q37556 | _evaluateContexts | train | async function _evaluateContexts(contexts = []) {
const c = Array.isArray(contexts) ? contexts : [contexts]
const ep = c.map(evaluateContext)
const res = await Promise.all(ep)
return res
} | javascript | {
"resource": ""
} |
q37557 | arraySortByKey | train | function arraySortByKey(data, key, reverse) {
data.sort((a, b) => {
const aw = a[key] !== undefined ? (
typeof a[key] === 'function' ?
parseInt(a[key](), 10) :
parseInt(a[key], 10)
) : 0;
const bw = b[key] !== undefined ? (
typeof b[key] === 'f... | javascript | {
"resource": ""
} |
q37558 | objectSortByKey | train | function objectSortByKey(data, key, reverse) {
let keys = Object.keys(data);
keys.sort((a, b) => {
const aw = data[a][key] !== undefined ? parseInt(data[a][key], 10) : 0;
const bw = data[b][key] !== undefined ? parseInt(data[b][key], 10) : 0;
if (aw === bw) {
return 0;
... | javascript | {
"resource": ""
} |
q37559 | AbortError | train | function AbortError(message) {
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (!(this instanceof AbortError)) { return new AbortError(message); }
Error.captureStackTrace(this, AbortError);
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String... | javascript | {
"resource": ""
} |
q37560 | starx | train | function starx(obj) {
if (!isGenerator(obj) && !isIterator(obj)) throw new TypeError('obj must be a generator or iterator')
return function executor(done) {
var self = this,
done = once(done || noop),
iterator = isGenerator(obj) ? obj.call(self) : obj
process.nextTick(next)
... | javascript | {
"resource": ""
} |
q37561 | execSeries | train | function execSeries(cmds, done) {
var out = [];
async.forEachSeries(cmds, function(cmd, next) {
exec(cmd, function(err, stdout, stderr) {
out.push({
stdout: stdout,
stderr: stderr,
err: err
});
next();
});
}, function() {
done(null, out);
});
} | javascript | {
"resource": ""
} |
q37562 | parseImpact | train | function parseImpact(data) {
var impact = /([0-9]+) insertions\(\+\), ([0-9]+) deletions\(\-\)/i.exec(data);
if (impact) {
return Number(impact[1]) + Number(impact[2]);
}
return 0;
} | javascript | {
"resource": ""
} |
q37563 | MongoStorage | train | function MongoStorage(config) {
var self = this;
this.events = new EventEmitter();
config = protos.extend({
host: 'localhost',
port: 27017,
database: 'store',
collection: 'keyvalue',
username: '',
password: '',
safe: true
}, config);
if (typeof config.por... | javascript | {
"resource": ""
} |
q37564 | getThemeFromPath | train | function getThemeFromPath(dir, program, cb) {
var configPath = path.resolve(dir, "theme.json");
program.log(2, constants.LOG_SEV_INFO, "Attempting to read " + configPath);
fs.readFile(configPath, { encoding: 'utf-8' }, function (err, data) {
if (err) {
program.log(1, ... | javascript | {
"resource": ""
} |
q37565 | Server | train | function Server(options) {
//TcpServer.call(this, options);
var onError = onFatalError.bind(this);
/* istanbul ignore next: always in test env */
if(process.env.NODE_ENV !== Constants.TEST) {
process
.on('error', onError)
.on('uncaughtException', onError);
}
this._tcp = null;
this._unix... | javascript | {
"resource": ""
} |
q37566 | connection | train | function connection(socket, server) {
var conn = new Connection(socket)
, tcp = (server instanceof TcpServer);
var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
if(maxclients && (this.state.length + 1 > maxclients)) {
this.state.emit('rejected', conn.client.addr, maxclients);
this.log.debug('re... | javascript | {
"resource": ""
} |
q37567 | monitor | train | function monitor(req, res) {
var socket = req.conn.socket
, args = [req.cmd].concat(req.args)
, t = systime()
, str;
// quote command and args
args = args.map(function(arg) {
return '"' + arg + '"';
})
// TODO: figure out meaning of ip/host prefix: [0
// build up the monitor simple string... | javascript | {
"resource": ""
} |
q37568 | publish | train | function publish(conn, channel, indices, message) {
var i
, conn;
for(i = 0;i < indices.length;i++) {
conn = this._state.getClient(indices[i]);
if(conn) {
conn.write(message);
}
}
} | javascript | {
"resource": ""
} |
q37569 | delegate | train | function delegate(req, res) {
var cmd = req.info.command
, method;
if(!cmd.sub) {
throw new Error('attempt to delegate with no subcommand info');
}
method = req.exec[cmd.sub.cmd];
// subcommand is declared but the command exec handler
// has not declared the method and is attempting to delegate
... | javascript | {
"resource": ""
} |
q37570 | command | train | function command(req, res) {
this.stats.commands++;
//console.dir(this);
// guaranteed to have a string command by connection
var cmd = req.cmd
// guaranteed to have an arguments array by connection
, args = req.args
// select implementation should guarantee a valid db index
// on the connec... | javascript | {
"resource": ""
} |
q37571 | disconnect | train | function disconnect(conn, socket, err) {
//console.dir('disconnect');
// clean monitor listeners
if(this._monitor[conn.id]) {
this.removeListener('monitor', this._monitor[conn.id]);
delete this._monitor[conn.id];
}
this._state.removeConnection(conn);
} | javascript | {
"resource": ""
} |
q37572 | load | train | function load(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
var args = opts && opts.args ? opts.args : null
, defaults = path.normalize(path.join(__dirname, 'command'));
opts = opts || argv(args);
if(opts.commands === undefined) {
opts.commands = [defaults];
}else ... | javascript | {
"resource": ""
} |
q37573 | listen | train | function listen() {
var args = []
, port = this.conf.get(ConfigKey.PORT)
, socket = this.conf.get(ConfigKey.UNIXSOCKET)
, perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
, backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
, cb = typeof arguments[arguments.length - 1] === 'function'
? arguments[a... | javascript | {
"resource": ""
} |
q37574 | shutdown | train | function shutdown(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = opts || {};
var code = opts.code || 0
, i = -1
, snapshots = this.state.conf.get(ConfigKey.SAVE)
, save = typeof opts.save === 'boolean' ? opts.save : null;
if(save === null) {
save = snaps... | javascript | {
"resource": ""
} |
q37575 | createConnection | train | function createConnection() {
// create the internal socket object
var server = new Socket()
, client = new Socket();
// pair the sockets
client.pair = server;
server.pair = client;
// register the server side so it is wrapped
// in a connection and stored as an active connection
this.connection(... | javascript | {
"resource": ""
} |
q37576 | serialize | train | function serialize(node, indent) {
indent = indent || 0;
var type = node._type;
var v;
if (type < 3 || type == 7) {
var name = node.name();
if (type == 1) {
var children = node;
var ret = "";
var attrs = "";
var hasChildNodes = false;
children.forEach(function (child, i) {
var type = child._t... | javascript | {
"resource": ""
} |
q37577 | getRect | train | function getRect(element, reference) {
if (element === window) return getViewportRect();
if (!reference) reference = window;
let elements = [].concat(element);
let n = elements.length;
if (n <= 0) return null;
let refRect = getRect(reference);
if (!assert(refRect, 'Cannot determine reference FOV.')) ... | javascript | {
"resource": ""
} |
q37578 | train | function(res) {
var results = /** @type {Array.<!goog.result.Result>} */ (
res.getValue());
if (goog.array.every(results, resolvedSuccessfully)) {
combinedResult.setValue(results);
} else {
combinedResult.setError(results);
}
} | javascript | {
"resource": ""
} | |
q37579 | matchAll | train | function matchAll(exp, text) {
exp.lastIndex = 0;
var matches = [];
var match;
while ((match = exp.exec(text)) != null) {
matches.push(match[0]);
}
return matches;
} | javascript | {
"resource": ""
} |
q37580 | tokenize | train | function tokenize(text) {
var tokens = [];
if (text && text.length > 0) {
var token = '';
for (var i = 0; i < text.length; i++) {
var chr = text[i];
if (breakingChars.indexOf(chr) >= 0) {
if (token.length > 0) {
tokens.push(token);
... | javascript | {
"resource": ""
} |
q37581 | normalizePath | train | function normalizePath (path) {
// Remove double slashes
if (path.indexOf('//') !== -1) {
path = path.replace(/\/+/g, '/');
}
// Shift slash
if (path[0] === '/') {
path = path.substr(1);
}
// Pop slash
if (path[path.length - 1] === '/') {
path = path.substr(0, path.length - 1);
}
retur... | javascript | {
"resource": ""
} |
q37582 | execQuery | train | function execQuery (query) {
var match, i, arr;
if ((match = this.exec(query))) {
arr = new Array(match.length - 1);
for (i = 1; i < match.length; ++i) {
arr[i - 1] = match[i];
}
return arr;
}
return match;
} | javascript | {
"resource": ""
} |
q37583 | parse | train | function parse (expr) {
var finalRegexp,
strSlashPref;
if (typeof expr !== 'string') {
// Handle RegExp `expr`
if (expr instanceof RegExp) {
finalRegexp = new RegExp(expr);
finalRegexp.query = execQuery;
return finalRegexp;
}
throw new TypeError(
'Usage: qbus.parse(<`query` = Strin... | javascript | {
"resource": ""
} |
q37584 | isNative | train | function isNative (val) {
if (isPrimitive(val)) {
return true
}
return natives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | javascript | {
"resource": ""
} |
q37585 | isPrimitive | train | function isPrimitive (val) {
if (val === null || val === undefined || val === Infinity || isLiterallyNaN(val)) {
return true
}
return primitives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | javascript | {
"resource": ""
} |
q37586 | transform | train | function transform(file, enc, cb, opts) {
if (file.isNull()) {
cb(null, file);
}
if (file.isStream()) {
cb(new PluginError('base-apps-router', 'Streams not supported.'));
}
if (file.isBuffer()) {
var frontMatter = fm(file.contents.toString());
if (frontMat... | javascript | {
"resource": ""
} |
q37587 | _getIdentityFields | train | function _getIdentityFields(Model, record, identityFields = []) {
/*
* Definition holds the schema
* inforamtion of your model.
*/
let schema = Model.definition;
let definition;
/*
* Collect all unique keys in schema.
* We can check record and see if we have
* any present... | javascript | {
"resource": ""
} |
q37588 | train | function () {
let usingNode = false;
if (typeof process === 'object') {
if (typeof process.versions === 'object') {
if (typeof process.versions.node !== 'undefined') {
usingNode = true;
}
}
}
return usingNode;
... | javascript | {
"resource": ""
} | |
q37589 | train | function() {
var split;
var opts = {};
if (process.env.DOCKER_HOST) {
split = /tcp:\/\/([0-9.]+):([0-9]+)/g.exec(process.env.DOCKER_HOST);
if (process.env.DOCKER_TLS_VERIFY === '1') {
opts.protocol = 'https';
}
else {
opts.protocol = 'http';
}
opts.host = split[1];
if (... | javascript | {
"resource": ""
} | |
q37590 | matchPaths | train | function matchPaths(pageLinks, path) {
let result;
path = _.compact(path.split('/'));
result = _.filter(_.keys(pageLinks), key => {
const path2 = _.compact(key.split('/'));
const noMatch = _.filter(path2, fragment => {
return fragment.substring(0, 1) !== ':' && _.indexOf(path, fragment) !== _.indexO... | javascript | {
"resource": ""
} |
q37591 | controllerLinks | train | function controllerLinks(route, controllerAction, reverseRouteService) {
const controllers = sails.controllers;
const controller = _.first(controllerAction.split('.'));
const path = route.path;
const actions = _.get(controllers[controller], '_config.links') || [];
let result = {};
result[path] = [];
_.eac... | javascript | {
"resource": ""
} |
q37592 | train | function (rootdir, configData, platform) {
var configFiles = lib.getConfigFilesByTargetAndParent(rootdir, platform),
type = 'configFile';
for (var key in configFiles) {
if (configFiles.hasOwnProperty(key)) {
var configFile = configFiles[key];
var... | javascript | {
"resource": ""
} | |
q37593 | retry | train | function retry(fn, N, retryTimeout, canContinue) {
if(typeof N === "function" && retryTimeout === canContinue === undefined) {
canContinue = N;
N = retryTimeout = undefined;
}
else if(typeof retryTimeout === "function") {
canContinue = retryTimeout;
retryTimeout = undefined;
... | javascript | {
"resource": ""
} |
q37594 | _try | train | function _try() {
// Call function
Q.invoke(f)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No t... | javascript | {
"resource": ""
} |
q37595 | defaults | train | function defaults(obj, source) {
obj = obj || {};
for (var prop in source) {
if (source.hasOwnProperty(prop) && obj[prop] === void 0) {
obj[prop] = source[prop];
}
}
return obj;
} | javascript | {
"resource": ""
} |
q37596 | unique | train | function unique(arr) {
return arr.filter(function (value, idx, self) {
return self.indexOf(value) === idx;
});
} | javascript | {
"resource": ""
} |
q37597 | sortByDepth | train | function sortByDepth(arr, descending) {
arr.sort(function (a, b) {
return dom(descending ? b : a).parents().length - dom(descending ? a : b).parents().length;
});
} | javascript | {
"resource": ""
} |
q37598 | removeClass | train | function removeClass(className) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className + '(\\b|$)', 'gi'), ' ');
}
} | javascript | {
"resource": ""
} |
q37599 | prepend | train | function prepend(nodesToPrepend) {
var nodes = Array.prototype.slice.call(nodesToPrepend),
i = nodes.length;
while (i--) {
el.insertBefore(nodes[i], el.firstChild);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.