_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40400 | sendAWSRequest | train | function sendAWSRequest(req) {
return new Promise((resolve, reject) => {
const send = new AWS.NodeHttpClient()
send.handleRequest(req, null, (res) => {
let body = ''
res.on('data', (chunk) => {
body += chunk
})
res.on('end', () => {
const { headers, statusCode } = res
... | javascript | {
"resource": ""
} |
q40401 | signAWSRequest | train | function signAWSRequest({ credentials, request }) {
const signer = new AWS.Signers.V4(request, 'es')
signer.addAuthorization(credentials, new Date())
return request
} | javascript | {
"resource": ""
} |
q40402 | resolveAndSetEventIdAndSeqNos | train | function resolveAndSetEventIdAndSeqNos(record, userRecord, state, context) {
// Get the resolveEventIdAndSeqNos function to use
const resolveEventIdAndSeqNos = settings.getResolveEventIdAndSeqNosFunction(context);
if (!resolveEventIdAndSeqNos) {
const errMsg = `FATAL - Cannot resolve event id & sequence numb... | javascript | {
"resource": ""
} |
q40403 | setMessageIdsAndSeqNos | train | function setMessageIdsAndSeqNos(state, messageIdsAndSeqNos) {
const {ids, keys, seqNos} = messageIdsAndSeqNos || {};
setIds(state, ids);
setKeys(state, keys);
setSeqNos(state, seqNos);
return state;
} | javascript | {
"resource": ""
} |
q40404 | init | train | function init(targetBuild) {
// CONSIDER: The `|| StaticBuild.current` isn't really necessary.
build = targetBuild || StaticBuild.current;
initViewEngines();
// Request Pipeline
initFavicon();
initLogging();
initApiProxy();
initParsing();
initCssLESS();
initSASS();
initViewRouting();
initErrorHa... | javascript | {
"resource": ""
} |
q40405 | prepareEmbed | train | function prepareEmbed(embedID) {
var embed = document.getElementById(embedID);
if (!isEmbeddedVideo(embed)) {
throw new Error('embed must be an iframe');
}
enableAPIControl(embed);
} | javascript | {
"resource": ""
} |
q40406 | isAPIEnabled | train | function isAPIEnabled(embed) {
var regex = '\/?api=1&player_id=' + embed.id;
regex = new RegExp(regex);
return regex.test(embed.src);
} | javascript | {
"resource": ""
} |
q40407 | Request | train | function Request(conn, cmd, args) {
// current connection
this.conn = conn;
// command name
this.cmd = cmd;
// command arguments may be modified
// during validation
this.args = args;
// raw command arguments, injected by the server
this.raw = null;
// server will inject this
// based upon th... | javascript | {
"resource": ""
} |
q40408 | destroy | train | function destroy() {
this.conn = null;
this.cmd = null;
this.args = null;
this.db = null;
this.info = null;
this.conf = null;
this.def = null;
} | javascript | {
"resource": ""
} |
q40409 | execute | train | function execute(req, res) {
this.state.pubsub.subscribe(req.conn, req.args);
} | javascript | {
"resource": ""
} |
q40410 | markdown_table | train | function markdown_table (headers, table) {
// FIXME: Implement better markdown table formating
return ARRAY([headers, [ "---", "---" ]]).concat(table).map(cols => '| ' + ARRAY(cols).join(' | ') + ' |').join('\n');
} | javascript | {
"resource": ""
} |
q40411 | _orphan | train | function _orphan(_el) {
var id = _jsPlumb.getId(_el);
var pos = _jsPlumb.getOffset(_el);
_el.parentNode.removeChild(_el);
_jsPlumb.getContainer().appendChild(_el);
_jsPlumb.setPosition(_el, pos);
delete _el._jsPlumbGroup;
_unbindDragHan... | javascript | {
"resource": ""
} |
q40412 | _pruneOrOrphan | train | function _pruneOrOrphan(p) {
if (!_isInsideParent(p.el, p.pos)) {
p.el._jsPlumbGroup.remove(p.el);
if (prune) {
_jsPlumb.remove(p.el);
} else {
_orphan(p.el);
}
}
} | javascript | {
"resource": ""
} |
q40413 | _revalidate | train | function _revalidate(_el) {
var id = _jsPlumb.getId(_el);
_jsPlumb.revalidate(_el);
_jsPlumb.dragManager.revalidateParent(_el, id);
} | javascript | {
"resource": ""
} |
q40414 | camelo | train | function camelo(input, regex, uc) {
regex = regex || DEFAULT_SPLIT;
var splits = null;
if (Array.isArray(regex)) {
regex = new RegExp(regex.map(reEscape).join("|"), "g");
} else if (typeof regex === "boolean") {
uc = regex;
regex = DEFAULT_SPLIT;
}
splits = input.spli... | javascript | {
"resource": ""
} |
q40415 | startWorker | train | function startWorker(triggeredByError=false){
return new Promise(function(resolve){
// default restart delay
let restartDelay = 0;
// worker restart because of died process ?
if (triggeredByError === true){
// increment restart counter
_restartCounter++;
... | javascript | {
"resource": ""
} |
q40416 | stopWorker | train | function stopWorker(worker){
return new Promise(function(resolve, reject){
// set kill timeout
const killTimeout = setTimeout(() => {
// kill the worker
worker.kill();
// failed to disconnect within given time
reject(new Error(`process ${w... | javascript | {
"resource": ""
} |
q40417 | shutdown | train | function shutdown(){
// trigger stop on all workers
// catch errors thrown by killed workers
return Promise.all(Object.values(_cluster.workers).map(worker => stopWorker(worker).catch(err => _logger.error(err))));
} | javascript | {
"resource": ""
} |
q40418 | setOutput | train | function setOutput(output) {
if (!output ||
typeof output.log !== 'function') {
throw Error('logger.setOutput: expect an object as the parameter with "log" and "error" properties.');
}
outputFunctions = {
log: output.log,
error: (typeof outp... | javascript | {
"resource": ""
} |
q40419 | joinMsgArgs | train | function joinMsgArgs(msgArgs) {
if (!msgArgs) {
return '';
}
return msgArgs.map((arg) => {
if (arg === null) {
return 'null';
} else if (typeof arg === 'undefined') {
return 'undefined';
} else if (typeof arg ===... | javascript | {
"resource": ""
} |
q40420 | writeLog | train | function writeLog(levelName, varArgs) { // eslint-disable-line no-unused-vars
const args = [].slice.call(arguments);
args.splice(0, 1);
const str = format(new Date(), levelName, label, args);
if (LEVELS[levelName] <= LEVELS.warn) {
outputFunctions.error(str)... | javascript | {
"resource": ""
} |
q40421 | genPassOfDay | train | function genPassOfDay(d, s = DEFAULT_SEED) {
if (!(d instanceof Date)) {
throw new TypeError('Date is not a Date instance');
}
if (typeof s !== 'string') {
throw new TypeError('Seed is not a String instance');
}
if (s.length < 1) {
throw new Error('Seed min length: 1');
}
const seed = s.rep... | javascript | {
"resource": ""
} |
q40422 | train | function(args) {
let service = args.service;
let record = args.record;
if (!service || !record || !record.module || !record.enable) {
return;
}
if (service.master) {
record.module.masterHandler(service.agent, null, function(err) {
logger.error('interval push should not have a callback.');
});
} else {
... | javascript | {
"resource": ""
} | |
q40423 | wrap | train | function wrap(nodes) {
nodes = nodes || [];
if ('string' == typeof nodes) {
nodes = new DOMParser().parseFromString(nodes);
}
if (nodes.attrNS && nodes._related) {
// attempt to re-wrap Collection, return it directly
return nodes;
} else if (nodes.documentElement) {
nodes = [ nodes.documentEl... | javascript | {
"resource": ""
} |
q40424 | unique | train | function unique(ar) {
var a = []
, i = -1
, j
, has;
while (++i < ar.length) {
j = -1;
has = false;
while (++j < a.length) {
if (a[j] === ar[i]) {
has = true;
break;
}
}
if (!has) { a.push(ar[i]); }
}
return a;
} | javascript | {
"resource": ""
} |
q40425 | Collection | train | function Collection(nodes) {
this.length = 0;
if (nodes) {
nodes = unique(nodes);
this.length = nodes.length;
// add each node to an index-based property on collection, in order to
// appear "array"-like
for (var i = 0, len = nodes.length; i < len; i++) {
this[i] = nodes[i];
}
}
} | javascript | {
"resource": ""
} |
q40426 | disableRules | train | async function disableRules(rules) {
return Object.keys(rules)
.reduce((collection, rule) => ({
...collection,
[rule]: OFF,
}), {});
} | javascript | {
"resource": ""
} |
q40427 | build | train | function build (conf, undertaker, done) {
return undertaker.series(
require('./clean').bind(null, conf, undertaker),
undertaker.parallel(
require('../scripts/lintScripts').bind(null, conf, undertaker),
require('../styles/lintStyles').bind(null, conf, undertaker)
),
undertaker.parallel(
... | javascript | {
"resource": ""
} |
q40428 | train | function () {
// Remove the other tooltips
// if it was requested.
if (this.reset !== false)
this.resetTooltip();
// Create the tooltip elements
var container = $("<div>").attr({
"class": "error-label-container"
}).a... | javascript | {
"resource": ""
} | |
q40429 | Database | train | function Database(store, opts) {
opts = opts || {};
// the store that holds this database
this._store = store;
// do not coerce values to strings
this.raw = opts.raw !== undefined ? opts.raw : true;
// pattern matcher
this.pattern = opts.pattern || new Pattern();
this.options = opts;
// set up in... | javascript | {
"resource": ""
} |
q40430 | Encoder | train | function Encoder(options) {
options = options || {};
Transform.call(this, {objectMode: true});
// string length chunk for bulk strings, strings large than this amount
// are broken over process ticks so as not to block the event loop
// note this is character length, not byte length
this.strlen = options.s... | javascript | {
"resource": ""
} |
q40431 | pack | train | function pack(arr, buf) {
assert(Array.isArray(arr), 'array expected');
var i;
buf = buf || new Buffer(0);
buf = _preamble(buf, arr);
for(i = 0;i < arr.length;i++) {
buf = _arr(buf, arr[i]);
}
return buf;
} | javascript | {
"resource": ""
} |
q40432 | value | train | function value(val, buf, simple) {
buf = buf || new Buffer(0);
var type = typeof val;
// coerce booleans to integers
val = type === 'boolean' ? Number(val) : val;
// treat floats as strings
if(type === 'number' && parseInt(val) !== val) {
val = '' + val;
}
// String instances are treated as simpl... | javascript | {
"resource": ""
} |
q40433 | train | function() {
var self = this;
molecuel.once('mlcl::elements::registrations:pre', function(module) {
elements = module;
self.wishlistSchema = {
name: { type: String, list: true, trim: true},
creation: { type: Date, 'default': Date.now, form: {readonly: true}},
entries: {
},
l... | javascript | {
"resource": ""
} | |
q40434 | baseWeight | train | function baseWeight(player, target, card, game) {
let weight = card.damage || 0
weight += Math.min(player.maxHp - player.hp, (parseInt(card.hp) || 0))
weight += card.missTurns / 2 || 0
// Prefer to contact weaker targets
weight += ((target.maxHp - player.hp) / 10)
// Unstoppable cards are instantly more v... | javascript | {
"resource": ""
} |
q40435 | findNext | train | function findNext(array, item) {
return array[(Util.findIndex(array, el => el === item) + 1) % array.length]
} | javascript | {
"resource": ""
} |
q40436 | getAttackResults | train | function getAttackResults(_cards) {
// Force the cards into an array. Clone is too
// to avoid side effects from the simulation.
const cards = Util.clone(Array.isArray(_cards) ? _cards : [_cards])
const Junkyard = require('./junkyard')
const game = new Junkyard('1', '')
game.addPlayer('2', '')
game.addPla... | javascript | {
"resource": ""
} |
q40437 | getCardWeight | train | function getCardWeight(player, target, card, game) {
let moves = []
if (card.validPlays) {
moves = card.validPlays(player, target, game)
}
if (card.validCounters && target.discard.length) {
moves = card.validCounters(player, target, game)
}
if (card.validDisasters) {
moves = card.validDisasters(... | javascript | {
"resource": ""
} |
q40438 | getPlayerCounters | train | function getPlayerCounters(player, attacker, game) {
return player.hand
.map((card) => {
return card.validCounters ? card.validCounters(player, attacker, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((counterA, counterB) => counterB.weight - counterA.wei... | javascript | {
"resource": ""
} |
q40439 | getPlayerDisasters | train | function getPlayerDisasters(player, game) {
return player.hand
.map((card) => {
return card.validDisasters ? card.validDisasters(player, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((disasterA, disasterB) => disasterB.weight - disasterA.weight)
} | javascript | {
"resource": ""
} |
q40440 | getPlayerPlays | train | function getPlayerPlays(player, game) {
// Shuffle so that equal-weighted players aren't
// always prioritized by their turn order
return Util.shuffle(game.players)
.reduce((plays, target) => {
if (player === target) {
return plays
}
return plays.concat(
player.hand
... | javascript | {
"resource": ""
} |
q40441 | remove | train | function remove(array, fn) {
const idx = array.findIndex(fn)
if (idx !== -1) {
array.splice(idx, 1)
}
} | javascript | {
"resource": ""
} |
q40442 | train | function (arr, groupSize) {
var groups = [];
groupSize = groupSize || 100;
arr.forEach(function (n, i) {
var index = Math.trunc(i / groupSize);
if (groups.length === index) {
groups.push([]);
}
groups[index].push(n);
});
return groups;
} | javascript | {
"resource": ""
} | |
q40443 | normalize | train | function normalize(arr) {
const n = copy(arr);
let len = 0;
for (const v of n) len += v * v;
if (len > 0) {
const coeff = 1 / Math.sqrt(len);
for (let k = 0; k < n.length; k++) {
n[k] *= coeff;
}
}
return n;
} | javascript | {
"resource": ""
} |
q40444 | perspective4 | train | function perspective4(fieldAngle, aspect, near, far, result) {
result = result || new Float32Array(16);
var f = Math.tan(Math.PI * 0.5 - 0.5 * fieldAngle);
var rangeInv = 1.0 / (near - far);
result[0] = f / aspect;
result[1] = 0;
result[2] = 0;
result[3] = 0;
result[4] = 0;
result[... | javascript | {
"resource": ""
} |
q40445 | streamOutput | train | function streamOutput( callback ) {
return function(err, filenames) {
if (err) {
callback(err, null);
} else {
// Create read streams from each input
var streams = []
for (var i=0; i<filenames.suffix.length; i++)
streams.push([
fs.createReadStream( filenames.basename + filenames.suffix[i]),
... | javascript | {
"resource": ""
} |
q40446 | processAsBuffer | train | function processAsBuffer( file ) {
return function( callback ) {
var json = JSON.parse(file.contents);
callback( json, path.dirname(file.path) );
}
} | javascript | {
"resource": ""
} |
q40447 | compileJBB | train | function compileJBB( config, parseCallback, resultCallback ) {
// Continue compiling the JBB bundle
var compile = function( bundleJSON, bundlePath, tempName ) {
// Update path in config
if (!config['path'])
config['path'] = path.dirname(bundlePath);
// Create the JBB bundle
JBBCompiler.compile(
bund... | javascript | {
"resource": ""
} |
q40448 | train | function( bundleJSON, bundlePath, tempName ) {
// Update path in config
if (!config['path'])
config['path'] = path.dirname(bundlePath);
// Create the JBB bundle
JBBCompiler.compile(
bundleJSON,
tempName,
config,
function() {
// Check for sparse bundles
if (config['sparse']) {
... | javascript | {
"resource": ""
} | |
q40449 | train | function( err, streams ) {
// Get base name
var path = originalFile.path;
var parts = path.split("."); parts.pop();
var baseName = parts.join(".");
// Push each stream to output
for (var i=0; i<streams.length; i++) {
var f = originalFile.clone();
f.contents = streams[i][0]; // C... | javascript | {
"resource": ""
} | |
q40450 | signals | train | function signals() {
/**
* Signal handler.
*/
function interrupt(signal) {
this.log.notice('received %s, scheduling shutdown', signal);
this.shutdown(0, process.exit);
}
interrupt = interrupt.bind(this);
function iterate(signal) {
/* test environment listener leak */
if(process.list... | javascript | {
"resource": ""
} |
q40451 | promiseThen | train | function promiseThen(success, reject, notify){
/**
* @define {object} Return a new promise
*/
var def = Deferred();
/**
* Resolved promise
* @example example
* @param {string} A string key for the event system
* @param {function} A callback when event is triggered
* @return {object} Returns ... | javascript | {
"resource": ""
} |
q40452 | resolve | train | function resolve(){
var args = Array.prototype.slice.call(arguments);
event.trigger('resolve', args);
} | javascript | {
"resource": ""
} |
q40453 | PancakesAngularPlugin | train | function PancakesAngularPlugin(opts) {
this.templateDir = path.join(__dirname, 'transformers');
this.pancakes = opts.pluginOptions.pancakes;
// initialize Jyt plugins
this.registerJytPlugins();
// initialize all directives and load them into memory
this.initDirectives(opts);
// i... | javascript | {
"resource": ""
} |
q40454 | train | function( path, cb ) {
// Set the content path
octofish.setContentPath( path );
// Use the content path to retrieve content
octofish.github.repos.getContent( octofish.config.contentOpts, function ( err, res ) {
var data = null;
// Handle any error
i... | javascript | {
"resource": ""
} | |
q40455 | train | function( authType ) {
switch ( authType.toLowerCase() ) {
case 'basic':
console.log( 'Attempting to use basic authorisation' );
getBasicAuth() ? cb_success() : cb_failure();
break;
case 'oauth':
... | javascript | {
"resource": ""
} | |
q40456 | train | function() {
auth.type = 'basic';
auth.username = process.env.GHusername || octofish.config.auth.username || null;
auth.password = process.env.GHpassword || octofish.config.auth.password || null;
if ( !auth.password || !auth.username ) {
return false;
... | javascript | {
"resource": ""
} | |
q40457 | Predator | train | function Predator(options) {
if (!(this instanceof Predator)) {
return new Predator(options);
}
if (!options || !options.app) {
throw new Error('options.app is required');
}
// 主目录
this.home = pathFn.resolve(options.home || '.');
// app
this.app = options.app;
// build 目录
this.buildDir =... | javascript | {
"resource": ""
} |
q40458 | createQueuePusher | train | function createQueuePusher(providerName, method, insertMethod, queue) {
return function() {
let args = arguments;
// Add provide method to invokeQueue to execute it on bootstrap.
(queue || invokeQueue)[insertMethod || 'push'](function provide(injector) {
// Get provider
let provider = injector.get(... | javascript | {
"resource": ""
} |
q40459 | estimateFalsePositiveRate | train | function estimateFalsePositiveRate(numValues, numBuckets, numHashes)
{
// Formula for false positives is (1-e^(-kn/m))^k
// k - number of hashes
// n - number of set entries
// m - number of buckets
var expectedFalsePositivesRate = Math.pow((1 - Math.exp(-numHashes * numValues / numBuckets)), numHashes);
return... | javascript | {
"resource": ""
} |
q40460 | _reset | train | function _reset() {
this._queue = [];
this._commands = [{cmd: Constants.MAP.multi.name, args: []}];
this._multi = false;
} | javascript | {
"resource": ""
} |
q40461 | _abort | train | function _abort(err) {
this._queue = null;
this._commands = null;
// listen for the event so we can clean reference
function onError() {
this._client = null;
}
this._client.once('error', onError.bind(this));
this._client.emit('error', err);
} | javascript | {
"resource": ""
} |
q40462 | loadFile | train | function loadFile(filepath, defaultObj) {
defaultObj = defaultObj || {};
if (!isFile(filepath)) { return defaultObj; }
var extension = path.extname(filepath).replace(/^\./, '');
var contents = supportedExtensions[extension](filepath);
return assign({}, defaultObj, contents);
} | javascript | {
"resource": ""
} |
q40463 | createPost | train | function createPost( file, options ) {
resetDoc();
var _formatDate = options && typeof options.formatDate === 'function' ?
options.formatDate : formatDate,
post = new Post();
// Parse front matter to get as many post attributes as possible
parseFrontMatter( file, post, options );
// Get category from pa... | javascript | {
"resource": ""
} |
q40464 | formatDate | train | function formatDate( date ) {
var dateString = '';
date = new Date( date );
dateString = date.getMonth() + 1;
dateString += '/';
dateString += date.getDate();
dateString += '/';
dateString += date.getFullYear();
return dateString;
} | javascript | {
"resource": ""
} |
q40465 | getCategoryFromPath | train | function getCategoryFromPath( file ) {
var category = '',
i = 0,
parts = file.path.split('/'),
len = parts.length,
last = len - 1;
for ( ; i < len; i++ ) {
/*
* If previous path part is "posts" and the
* current path part isn't the last path part
*/
if ( parts[i - 1] === 'posts' && i !== l... | javascript | {
"resource": ""
} |
q40466 | getTitleFromPath | train | function getTitleFromPath( file, options ) {
var _titleSeparator = options && options.titleSeparator ?
options.titleSeparator : titleSeparator,
i = 0,
parts = file.path.split('/'),
fileParts = parts[parts.length - 1].split('.'),
filename = fileParts[0],
fileNameParts = filename.split( _titleSeparat... | javascript | {
"resource": ""
} |
q40467 | highlightPostSyntax | train | function highlightPostSyntax( post ) {
var codeTags = [],
i = 0,
len = 0;
doc = doc || createDom( post.content );
codeTags = doc.querySelectorAll('pre code');
len = codeTags.length;
for ( ; i < len; i++ ) {
// Replace class names beginning with "lang-" with "language-" for Highlight.js
codeTags[i]... | javascript | {
"resource": ""
} |
q40468 | isCustomFrontMatter | train | function isCustomFrontMatter( attr ) {
if ( attr !== 'title' && attr !== 'category' && attr !== 'content' &&
attr !== 'created' && attr !== 'excerpt' && attr !== 'updated' ) {
return true;
} else {
return false;
}
} | javascript | {
"resource": ""
} |
q40469 | parseFrontMatter | train | function parseFrontMatter( file, post, options ) {
var _formatDate = options && typeof options.formatDate === 'function' ?
options.formatDate : formatDate,
content = frontMatter( file.contents.toString() ),
prop = '';
if ( content.attributes ) {
post.category = content.attributes.category || '';
post... | javascript | {
"resource": ""
} |
q40470 | sortPosts | train | function sortPosts( a, b ) {
var dateA = new Date( a.created ),
dateB = new Date( b.created );
// See if dates match
if ( dateB - dateA === 0 ) {
// See if categories are the same
if ( a.category === b.category ) {
// Sort by title
return a.title.localeCompare( b.title );
// Sort by category
} ... | javascript | {
"resource": ""
} |
q40471 | removePostsContent | train | function removePostsContent( posts, options ) {
var _sortPosts = options && typeof options.sortPosts === 'function' ?
options.sortPosts : sortPosts,
i = 0,
len = 0;
// Posts should be objects separated by commas but not wrapped in []
posts = JSON.parse( '[' + posts.contents.toString() + ']' );
len = po... | javascript | {
"resource": ""
} |
q40472 | diamondLeftToVic | train | function diamondLeftToVic(lead) {
var m = lead.p;
var z = lead;
var x = z.l;
var y = x.r;
var a = y.l;
var b = y.r;
x.flag = false;
y.l = x;
x.p = y;
y.r = z;
z.p = y;
x.r = a;
a.p = x;
z.l = b;
b.p = z;
if (m.r === lead) {
m.r = y;
}
else ... | javascript | {
"resource": ""
} |
q40473 | rbInsertFixup | train | function rbInsertFixup(tree, n) {
// When inserting the node (at any place other than the root), we always color it red.
// This is so that we don't violate the height invariant.
// However, this may violate the color invariant, which we address by recursing back up the tree.
n.flag = true;
if (!n.p... | javascript | {
"resource": ""
} |
q40474 | glb | train | function glb(tree, node, key, comp, low) {
if (node === tree.z) {
return low;
}
else if (comp(key, node.key) >= 0) {
// The node key is a valid lower bound, but may not be the greatest.
// Take the right link in search of larger keys.
return maxNode(node, glb(tree, node.r, ke... | javascript | {
"resource": ""
} |
q40475 | lub | train | function lub(tree, node, key, comp, high) {
if (node === tree.z) {
return high;
}
else if (comp(key, node.key) <= 0) {
// The node key is a valid upper bound, but may not be the least.
return minNode(node, lub(tree, node.l, key, comp, high), comp);
}
else {
// Take th... | javascript | {
"resource": ""
} |
q40476 | Middleware | train | function Middleware(name) {
if (!(this instanceof Middleware)) return new Middleware(name);
this.name = name || '';
Object.defineProperty(this, '_', {
enumerable: false,
configurable: false,
value: {
length: 0,
ordered: null,
weights: new Map()
... | javascript | {
"resource": ""
} |
q40477 | train | function(err, req, res, next) {
function done(error) {
log(req, util.format('middleware-end %s', name));
next(error);
}
if (err && !errHandler) {
log(req, util.format('skipped %s Hook is not for error handling', name));
next(err);
} else... | javascript | {
"resource": ""
} | |
q40478 | create | train | function create(delay) {
let timeoutId;
let _reject;
const promise = new Promise((resolve, reject) => {
_reject = reject;
timeoutId = setTimeout(() => {
resolve();
pendingPromises.delete(promise);
}, delay);
});
pendingPromises.set(promise, {
timeoutId,
... | javascript | {
"resource": ""
} |
q40479 | clear | train | async function clear(promise) {
if (!pendingPromises.has(promise)) {
return Promise.reject(new YError('E_BAD_DELAY'));
}
const { timeoutId, reject } = pendingPromises.get(promise);
clearTimeout(timeoutId);
reject(new YError('E_DELAY_CLEARED'));
pendingPromises.delete(promise);
log('de... | javascript | {
"resource": ""
} |
q40480 | getField | train | function getField(field) {
return function map(element) {
if (element) {
if (Array.isArray(element)) {
return element.map(map).join('');
}
else if (typeof element === 'string') {
return element;
}
else if (typeof element === 'object') {
return element[field];
... | javascript | {
"resource": ""
} |
q40481 | getList | train | function getList() {
if(!COMMAND_LIST) {
COMMAND_LIST = [];
for(var z in this.execs) {
COMMAND_LIST.push(this.execs[z].definition.getDefinition());
}
}
return COMMAND_LIST;
} | javascript | {
"resource": ""
} |
q40482 | info | train | function info(req, res) {
var list = []
, i
, exec;
for(i = 0;i < req.args.length;i++) {
exec = this.execs[req.args[i]];
list.push(exec ? exec.definition.getDefinition() : null);
}
res.send(null, list);
} | javascript | {
"resource": ""
} |
q40483 | getkeys | train | function getkeys(req, res) {
var keys = []
// target command
, tcmd = req.args[0]
, def = Constants.MAP[tcmd];
if(def) {
keys = def.getKeys(req.args.slice(1));
}
res.send(null, keys);
} | javascript | {
"resource": ""
} |
q40484 | count | train | function count(req, res) {
var list = getList.call(this);
return res.send(null, list.length);
} | javascript | {
"resource": ""
} |
q40485 | execute | train | function execute(req, res) {
if(req.info.command.sub) {
this.delegate(req, res);
// no subcommand return command list
}else{
var list = getList.call(this);
return res.send(null, list);
}
} | javascript | {
"resource": ""
} |
q40486 | buildPaths | train | function buildPaths(file, arr) {
if (!grunt.file.exists(file)) {
grunt.log.warn('File "' + file + '" not found');
return null;
}
arr.unshift(file);
var namespaces = pathTable[file];
if (namespaces && namespaces.length) {
for (var i = namespaces.length, ns; i-- > 0;) {
ns = ... | javascript | {
"resource": ""
} |
q40487 | create | train | function create({
pending = false, // eslint-disable-line no-shadow
refreshing = false, // eslint-disable-line no-shadow
fulfilled = false, // eslint-disable-line no-shadow
rejected = false, // eslint-disable-line no-shadow
value = null,
reason = null,
}) {
return {
pending,
... | javascript | {
"resource": ""
} |
q40488 | cloneById | train | function cloneById (v, k) {
if (Array.isArray(v)) {
let match = find(v, it => String(it[options.idField]) === String(k));
return match? cloneDeep(match) : (options.keepOrig? k : null);
} else {
return String(v[options.idField]) === String(k)? cloneDeep(v) : (options.keepOrig? k : null);
}
... | javascript | {
"resource": ""
} |
q40489 | train | function(req, topic, messages){
payloads[0]['topic'] = topic
payloads[0]['messages']= JSON.stringify(messages);
console.log(payloads[0]['messages']);
setTimeout(function () {
producer.send(payloads, function (err, data) {
if(err){
console.log(err);
}
... | javascript | {
"resource": ""
} | |
q40490 | train | function(callback){
if(source['brokerId']!='null'){
db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
mqttHost = result[0]['ipAddress'];
mqttPort = result[0]['port'];
console.log(result);
... | javascript | {
"resource": ""
} | |
q40491 | train | function(callback){
var o_id = BSON.ObjectID.createFromHexString(source['_id']);
db.db(dbName).collection(collectionName).find({_id:o_id}).toArray(function(err,result){
response.send(result);
o_id = null;
});
} | javascript | {
"resource": ""
} | |
q40492 | train | function(callback){
var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
if(result.length!=0){
roadmapNum = roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
}
else{
roadmapNum = roadMapId... | javascript | {
"resource": ""
} | |
q40493 | lset | train | function lset(index, value) {
if(index < 0) index = this._data.length + index;
// command should validate the index
if(index < 0 || index >= this._data.length) return null;
this._data[index] = value;
} | javascript | {
"resource": ""
} |
q40494 | linsert | train | function linsert(beforeAfter, pivot, value) {
//console.dir(pivot);
//console.dir(this._data);
var ind = this.indexOf(pivot);
if(ind === -1) return ind;
// note beforeAfter can be a buffer
ind = (('' + beforeAfter) === BEFORE) ? ind : ind + 1;
this._data.splice(ind, 0, value);
return this._data.length;
... | javascript | {
"resource": ""
} |
q40495 | lindex | train | function lindex(index) {
if(index < 0) index = this._data.length + index;
return this._data[index] || null;
} | javascript | {
"resource": ""
} |
q40496 | lrem | train | function lrem(count, value) {
var ind, deleted = 0;
if(count === 0) {
while((ind = this.indexOf(value)) !== -1) {
this._data.splice(ind, 1);
deleted++;
}
}else if(count > 0) {
while((ind = this.indexOf(value)) !== -1 && (deleted < count)) {
this._data.splice(ind, 1);
deleted++;... | javascript | {
"resource": ""
} |
q40497 | lrange | train | function lrange(start, stop) {
if(start < 0) start = this._data.length + start;
if(stop < 0) stop = this._data.length + stop;
stop++;
return this._data.slice(start, stop);
} | javascript | {
"resource": ""
} |
q40498 | iterateKeys | train | function iterateKeys() {
var obj = getKeyObject(db, j);
if(obj === null) return onKeysComplete();
encoder.write(obj, function onWrite() {
j++;
setImmediate(iterateKeys);
});
} | javascript | {
"resource": ""
} |
q40499 | train | function (user, req, cb) {
CoreController.getPluginViewDefaultTemplate({
viewname: 'email/user/forgot_password_link',
themefileext: appSettings.templatefileextension,
},
function (err, templatepath) {
if (err) {
cb(err);
} else {
// console.log('emailForgotPasswordLink templatepath', templat... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.