_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20900
unit
train
function unit(unit, type){ utils.assertType(unit, 'unit', 'unit'); // Assign if (type) { utils.assertString(type, 'type'); return new nodes.Unit(unit.val, type.string); } else { return unit.type || ''; } }
javascript
{ "resource": "" }
q20901
hsl
train
function hsl(hue, saturation, lightness){ if (1 == arguments.length) { utils.assertColor(hue, 'color'); return hue.hsla; } else { return hsla( hue , saturation , lightness , new nodes.Unit(1)); } }
javascript
{ "resource": "" }
q20902
lookup
train
function lookup(name){ utils.assertType(name, 'string', 'name'); var node = this.lookup(name.val); if (!node) return nodes.null; return this.visit(node); }
javascript
{ "resource": "" }
q20903
substr
train
function substr(val, start, length){ utils.assertString(val, 'val'); utils.assertType(start, 'unit', 'start'); length = length && length.val; var res = val.string.substr(start.val, length); return val instanceof nodes.Ident ? new nodes.Ident(res) : new nodes.String(res); }
javascript
{ "resource": "" }
q20904
imageSize
train
function imageSize(img, ignoreErr) { utils.assertType(img, 'string', 'img'); try { var img = new Image(this, img.string); } catch (err) { if (ignoreErr) { return [new nodes.Unit(0), new nodes.Unit(0)]; } else { throw err; } } // Read size img.open(); var size = img.size(); i...
javascript
{ "resource": "" }
q20905
saturation
train
function saturation(color, value){ if (value) { var hslaColor = color.hsla; return hsla( new nodes.Unit(hslaColor.h), value, new nodes.Unit(hslaColor.l), new nodes.Unit(hslaColor.a) ) } return component(color, new nodes.String('saturation')); }
javascript
{ "resource": "" }
q20906
error
train
function error(msg){ utils.assertType(msg, 'string', 'msg'); var err = new Error(msg.val); err.fromStylus = true; throw err; }
javascript
{ "resource": "" }
q20907
importFile
train
function importFile(node, file, literal) { var importStack = this.importStack , Parser = require('../parser') , stat; // Handling the `require` if (node.once) { if (this.requireHistory[file]) return nodes.null; this.requireHistory[file] = true; if (literal && !this.includeCSS) { return...
javascript
{ "resource": "" }
q20908
define
train
function define(name, expr, global){ utils.assertType(name, 'string', 'name'); expr = utils.unwrap(expr); var scope = this.currentScope; if (global && global.toBoolean().isTrue) { scope = this.global.scope; } var node = new nodes.Ident(name.val, expr); scope.add(node); return nodes.null; }
javascript
{ "resource": "" }
q20909
train
function (invite, cb) { var id = api.keys.sync.id() var data = ref.parseInvite(invite) api.contact.async.followerOf(id, data.key, function (_, follows) { if (follows) console.log('already following', cb()) else console.log('accept invite:' + invite, accept(invite, cb)) }) }
javascript
{ "resource": "" }
q20910
_init
train
function _init () { if (_locale) return // TODO: Depject this! i18nL.configure({ directory: appRoot + '/locales', defaultLocale: 'en' }) watch(api.settings.obs.get('patchwork.lang'), currentLocale => { currentLocale = currentLocale || navigator.language var locales = i18nL.g...
javascript
{ "resource": "" }
q20911
quitIfAlreadyRunning
train
function quitIfAlreadyRunning () { if (!electron.app.requestSingleInstanceLock()) { return electron.app.quit() } electron.app.on('second-instance', (event, commandLine, workingDirectory) => { // Someone tried to run a second instance, we should focus our window. if (windows.main) { if (windows.m...
javascript
{ "resource": "" }
q20912
Sustained
train
function Sustained (obs, timeThreshold, checkUpdateImmediately) { var outputValue = Value(obs()) var lastValue = null var timer = null return computed(outputValue, v => v, { onListen: () => watch(obs, onChange) }) function onChange (value) { if (checkUpdateImmediately && checkUpdateImmediately(val...
javascript
{ "resource": "" }
q20913
buildPluginEntry
train
function buildPluginEntry(plugins) { const result = {}; plugins.forEach( plugin => (result[path.basename(plugin, '.js')] = path.join( pluginSrcDir, plugin )) ); return result; }
javascript
{ "resource": "" }
q20914
train
function() { var xDeg = parseInt(slider.value); var x = Math.sin(xDeg * (Math.PI / 180)); wavesurfer.panner.setPosition(x, 0, 0); }
javascript
{ "resource": "" }
q20915
train
function( aSampleRate, aSequenceMS, aSeekWindowMS, aOverlapMS ) { // accept only positive parameter values - if zero or negative, use old values instead if (aSampleRate > 0) { this.sampleRate = aSampleRate; } ...
javascript
{ "resource": "" }
q20916
train
function(overlapInMsec) { var newOvl; // TODO assert(overlapInMsec >= 0); newOvl = (this.sampleRate * overlapInMsec) / 1000; if (newOvl < 16) newOvl = 16; // must be divisible by 8 newOvl -= newOvl % 8; this.overlapLength = newOvl; ...
javascript
{ "resource": "" }
q20917
train
function() { var seq; var seek; if (this.bAutoSeqSetting) { seq = AUTOSEQ_C + AUTOSEQ_K * this._tempo; seq = this.checkLimits(seq, AUTOSEQ_AT_MAX, AUTOSEQ_AT_MIN); this.sequenceMs = Math.floor(seq + 0.5); } if ...
javascript
{ "resource": "" }
q20918
train
function() { var i, cnt2, temp; for (i = 0; i < this.overlapLength; i++) { temp = i * (this.overlapLength - i); cnt2 = i * 2; this.pRefMidBuffer[cnt2] = this.pMidBuffer[cnt2] * temp; this.pRefMidBuffer[cnt2 + 1] = this.pMidBuffer[c...
javascript
{ "resource": "" }
q20919
train
function(pInputPos) { var pInput = this._inputBuffer.vector; pInputPos += this._inputBuffer.startIndex; var pOutput = this._outputBuffer.vector, pOutputPos = this._outputBuffer.endIndex, i, cnt2, fTemp, ...
javascript
{ "resource": "" }
q20920
formatTimeCallback
train
function formatTimeCallback(seconds, pxPerSec) { seconds = Number(seconds); var minutes = Math.floor(seconds / 60); seconds = seconds % 60; // fill up seconds with zeroes var secondsStr = Math.round(seconds).toString(); if (pxPerSec >= 25 * 10) { secondsStr = seconds.toFixed(2); } e...
javascript
{ "resource": "" }
q20921
timeInterval
train
function timeInterval(pxPerSec) { var retval = 1; if (pxPerSec >= 25 * 100) { retval = 0.01; } else if (pxPerSec >= 25 * 40) { retval = 0.025; } else if (pxPerSec >= 25 * 10) { retval = 0.1; } else if (pxPerSec >= 25 * 4) { retval = 0.25; } else if (pxPerSec >= 25...
javascript
{ "resource": "" }
q20922
primaryLabelInterval
train
function primaryLabelInterval(pxPerSec) { var retval = 1; if (pxPerSec >= 25 * 100) { retval = 10; } else if (pxPerSec >= 25 * 40) { retval = 4; } else if (pxPerSec >= 25 * 10) { retval = 10; } else if (pxPerSec >= 25 * 4) { retval = 4; } else if (pxPerSec >= 25) ...
javascript
{ "resource": "" }
q20923
train
function(index) { links[currentTrack].classList.remove('active'); currentTrack = index; links[currentTrack].classList.add('active'); wavesurfer.load(links[currentTrack].href); }
javascript
{ "resource": "" }
q20924
saveRegions
train
function saveRegions() { localStorage.regions = JSON.stringify( Object.keys(wavesurfer.regions.list).map(function(id) { var region = wavesurfer.regions.list[id]; return { start: region.start, end: region.end, attributes: region.attribut...
javascript
{ "resource": "" }
q20925
loadRegions
train
function loadRegions(regions) { regions.forEach(function(region) { region.color = randomColor(0.1); wavesurfer.addRegion(region); }); }
javascript
{ "resource": "" }
q20926
extractRegions
train
function extractRegions(peaks, duration) { // Silence params var minValue = 0.0015; var minSeconds = 0.25; var length = peaks.length; var coef = duration / length; var minLen = minSeconds / coef; // Gather silence indeces var silences = []; Array.prototype.forEach.call(peaks, funct...
javascript
{ "resource": "" }
q20927
editAnnotation
train
function editAnnotation(region) { var form = document.forms.edit; form.style.opacity = 1; (form.elements.start.value = Math.round(region.start * 10) / 10), (form.elements.end.value = Math.round(region.end * 10) / 10); form.elements.note.value = region.data.note || ''; form.onsubmit = functio...
javascript
{ "resource": "" }
q20928
mockPlugin
train
function mockPlugin(name, deferInit = false) { class MockPlugin { constructor(params, ws) { this.ws = ws; // using the instance factory unfortunately makes it // difficult to use the spyOn function, so we use this // instead ...
javascript
{ "resource": "" }
q20929
__createWaveform
train
function __createWaveform(options = {}) { waveformDiv = document.createElement('div'); document.getElementsByTagName('body')[0].appendChild(waveformDiv); wavesurfer = WaveSurfer.create( Object.assign( { container: waveformDiv }, ...
javascript
{ "resource": "" }
q20930
train
function(name, description, action) { if (!action) { [action, description] = [description, action]; } return tasks[name] = {name, description, action}; }
javascript
{ "resource": "" }
q20931
freezeOptions
train
function freezeOptions(options) { // Freeze each property objects Object.getOwnPropertyNames(options).forEach(optionName => { if (optionName === 'valuesToStrings') { const vsProps = Object.getOwnPropertyNames(options.valuesToStrings); vsProps.forEach(valuesToStringObjectName => {...
javascript
{ "resource": "" }
q20932
InvalidDerefInputError
train
function InvalidDerefInputError() { var instance = new Error("Deref can only be used with a non-primitive object from get, set, or call."); instance.name = "InvalidDerefInputError"; if (Object.setPrototypeOf) { Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); } if (Error.capt...
javascript
{ "resource": "" }
q20933
train
function(scheduler, requestQueue) { this.sent = false; this.scheduled = false; this.requestQueue = requestQueue; this.id = ++REQUEST_ID; this.type = GetRequestType; this._scheduler = scheduler; this._pathMap = {}; this._optimizedPaths = []; this._requestedPaths = []; this._callb...
javascript
{ "resource": "" }
q20934
train
function(requestedPaths, optimizedPaths, callback) { var self = this; var oPaths = self._optimizedPaths; var rPaths = self._requestedPaths; var callbacks = self._callbacks; var idx = oPaths.length; // If its not sent, simply add it to the requested paths // and c...
javascript
{ "resource": "" }
q20935
train
function(requested, optimized, callback) { // uses the length tree complement calculator. var self = this; var complementResult = complement(requested, optimized, self._pathMap); var inserted = false; var disposable = false; // If we found an intersection, then just add...
javascript
{ "resource": "" }
q20936
train
function(requested, err, data, mergeContext) { var self = this; var model = self.requestQueue.model; var modelRoot = model._root; var errorSelector = modelRoot.errorSelector; var comparator = modelRoot.comparator; var boundPath = model._path; model._path = emptyA...
javascript
{ "resource": "" }
q20937
createDisposable
train
function createDisposable(request, idx) { var disposed = false; return function() { if (disposed || request._disposed) { return; } disposed = true; request._callbacks[idx] = null; request._optimizedPaths[idx] = []; request._requestedPaths[idx] = []; ...
javascript
{ "resource": "" }
q20938
dispose
train
function dispose() { if (this.disposed || !this.currentDisposable) { return; } this.disposed = true; // If the current disposable fulfills the disposable interface or just // a disposable function. var currentDisposable = this.currentDisposable; if (c...
javascript
{ "resource": "" }
q20939
SetResponse
train
function SetResponse(model, args, isJSONGraph, isProgressive) { // The response properties. this._model = model; this._isJSONGraph = isJSONGraph || false; this._isProgressive = isProgressive || false; this._initialArgs = args; this._value = [{}]; var ...
javascript
{ "resource": "" }
q20940
BoundJSONGraphModelError
train
function BoundJSONGraphModelError() { var instance = new Error("It is not legal to use the JSON Graph " + "format from a bound Model. JSON Graph format" + " can only be used from a root model."); instance.name = "BoundJSONGraphModelError"; if (Object.setPrototypeOf) { Object.setPrototypeOf...
javascript
{ "resource": "" }
q20941
InvalidModelError
train
function InvalidModelError(boundPath, shortedPath) { var instance = new Error("The boundPath of the model is not valid since a value or error was found before the path end."); instance.name = "InvalidModelError"; instance.boundPath = boundPath; instance.shortedPath = shortedPath; if (Object.setPro...
javascript
{ "resource": "" }
q20942
train
function(action) { var self = this; // The subscribe function runs when the Observable is observed. return Rx.Observable.create(function subscribe(observer) { var id = self.id++, handler = function(e) { var response = e.data, ...
javascript
{ "resource": "" }
q20943
Model
train
function Model(o) { var options = o || {}; this._root = options._root || new ModelRoot(options); this._path = options.path || options._path || []; this._scheduler = options.scheduler || options._scheduler || new ImmediateScheduler(); this._source = options.source || options._source; this._reque...
javascript
{ "resource": "" }
q20944
allUnique
train
function allUnique(arr) { var hash = {}, index, len; for (index = 0, len = arr.length; index < len; index++) { if (hash[arr[index]]) { return false; } hash[arr[index]] = true; } return true; }
javascript
{ "resource": "" }
q20945
MaxRetryExceededError
train
function MaxRetryExceededError(missingOptimizedPaths) { var instance = new Error("The allowed number of retries have been exceeded."); instance.name = "MaxRetryExceededError"; instance.missingOptimizedPaths = missingOptimizedPaths || []; if (Object.setPrototypeOf) { Object.setPrototypeOf(insta...
javascript
{ "resource": "" }
q20946
NullInPathError
train
function NullInPathError() { var instance = new Error("`null` and `undefined` are not allowed in branch key positions"); instance.name = "NullInPathError"; if (Object.setPrototypeOf) { Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); } if (Error.captureStackTrace) { E...
javascript
{ "resource": "" }
q20947
GetResponse
train
function GetResponse(model, paths, isJSONGraph, isProgressive, forceCollect) { this.model = model; this.currentRemainingPaths = paths; this.isJSONGraph = isJSONGraph || false; this.isProgressive = isProgressive || false; this.forceCollect = forceCollect || fals...
javascript
{ "resource": "" }
q20948
linkToWithTarget
train
function linkToWithTarget(doc, linkText) { var linkTag = linkto(doc.longname, linkText || doc.name); return linkTag.slice(0, linkTag.indexOf('>')) + ' data-target="#' + escapeDocId(doc.id) + '"' + linkTag.slice(linkTag.indexOf('>')); }
javascript
{ "resource": "" }
q20949
primitiveHasOwnProperty
train
function primitiveHasOwnProperty (primitive, propName) { return ( primitive != null && typeof primitive !== 'object' && primitive.hasOwnProperty && primitive.hasOwnProperty(propName) ); }
javascript
{ "resource": "" }
q20950
bufferFromArrayBuffer
train
function bufferFromArrayBuffer(arrayBuffer) { const buffer = Buffer.alloc(arrayBuffer.byteLength); const view = new Uint8Array(arrayBuffer); for (let i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; }
javascript
{ "resource": "" }
q20951
minify
train
function minify(code) { console.error('Compressing...'); return UglifyJS.minify(code, { warnings: false }).code; }
javascript
{ "resource": "" }
q20952
dither
train
function dither(cb) { const rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6]; this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function( x, y, idx ) { const thresholdId = ((y & 3) << 2) + (x % 4); const dither = rgb565Matrix[thresholdId]; this.bitmap.data[i...
javascript
{ "resource": "" }
q20953
flipFn
train
function flipFn(horizontal, vertical, cb) { if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean') return throwError.call( this, 'horizontal and vertical must be Booleans', cb ); if (horizontal && vertical) { // shortcut return this.rotate(180, true, cb); } con...
javascript
{ "resource": "" }
q20954
histogram
train
function histogram() { const histogram = { r: new Array(256).fill(0), g: new Array(256).fill(0), b: new Array(256).fill(0) }; this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function( x, y, index ) { histogram.r[this.bitmap.data[index + 0]]++; histogram.g[this.bitmap...
javascript
{ "resource": "" }
q20955
buildDropdown
train
function buildDropdown(items, trumbowyg) { var dropdown = []; $.each(items, function (i, item) { var btn = 'mention-' + i, btnDef = { hasIcon: false, text: trumbowyg.o.plugins.mention.formatDropdownItem(item), fn: f...
javascript
{ "resource": "" }
q20956
templateSelector
train
function templateSelector(trumbowyg) { var available = trumbowyg.o.plugins.templates; var templates = []; $.each(available, function (index, template) { trumbowyg.addBtnDef('template_' + index, { fn: function () { trumbowyg.html(template.html); ...
javascript
{ "resource": "" }
q20957
buildDropdown
train
function buildDropdown(trumbowyg) { var dropdown = []; $.each(trumbowyg.o.plugins.lineheight.sizeList, function(index, size) { trumbowyg.addBtnDef('lineheight_' + size, { text: trumbowyg.lang.lineheights[size] || size, hasIcon: false, fn: func...
javascript
{ "resource": "" }
q20958
train
function () { var t = this; t.$ed.removeClass('autogrow-on-enter'); var oldHeight = t.$ed[0].clientHeight; t.$ed.height('auto'); var totalHeight = t.$ed[0].scrollHeight; t.$ed.addClass('autogrow-on-enter'); if (oldHeight !== totalHeight...
javascript
{ "resource": "" }
q20959
train
function () { var t = this, prefix = t.o.prefix; var $btnPane = t.$btnPane = $('<div/>', { class: prefix + 'button-pane' }); $.each(t.o.btns, function (i, btnGrp) { if (!$.isArray(btnGrp)) { btnGrp = [b...
javascript
{ "resource": "" }
q20960
train
function (btnName) { var t = this, prefix = t.o.prefix, btn = t.btnsDef[btnName], hasIcon = btn.hasIcon != null ? btn.hasIcon : true; if (btn.key) { t.keys[btn.key] = { fn: btn.fn || btnName, ...
javascript
{ "resource": "" }
q20961
train
function () { var t = this, fixedFullWidth = t.o.fixedFullWidth, $box = t.$box; if (!t.o.fixedBtnPane) { return; } t.isFixed = false; $(window) .on('scroll.' + t.eventNamespace + ' resize.' + t...
javascript
{ "resource": "" }
q20962
train
function () { var t = this, prefix = t.o.prefix; if (t.isTextarea) { t.$box.after( t.$ta .css({height: ''}) .val(t.html()) .removeClass(prefix + 'textarea') ...
javascript
{ "resource": "" }
q20963
train
function () { var t = this, prefix = t.o.prefix; if (t.o.autogrowOnEnter) { t.autogrowOnEnterDontClose = !t.$box.hasClass(prefix + 'editor-hidden'); } t.semanticCode(false, true); setTimeout(function () { t.do...
javascript
{ "resource": "" }
q20964
train
function (name) { var t = this, d = t.doc, prefix = t.o.prefix, $dropdown = $('[data-' + prefix + 'dropdown=' + name + ']', t.$box), $btn = $('.' + prefix + name + '-button', t.$btnPane), show = $dropdown.is(':hidden'); ...
javascript
{ "resource": "" }
q20965
train
function (html) { var t = this; if (html != null) { t.$ta.val(html); t.syncCode(true); t.$c.trigger('tbwchange'); return t; } return t.$ta.val(); }
javascript
{ "resource": "" }
q20966
train
function (force, full, keepRange) { var t = this; t.saveRange(); t.syncCode(force); if (t.o.semantic) { t.semanticTag('b', t.o.semanticKeepAttributes); t.semanticTag('i', t.o.semanticKeepAttributes); t.semanticTag('s', t.o....
javascript
{ "resource": "" }
q20967
train
function () { var t = this, documentSelection = t.doc.getSelection(), node = documentSelection.focusNode, text = new XMLSerializer().serializeToString(documentSelection.getRangeAt(0).cloneContents()), url, title, ...
javascript
{ "resource": "" }
q20968
train
function (title, content) { var t = this, prefix = t.o.prefix; // No open a modal box when exist other modal box if ($('.' + prefix + 'modal-box', t.$box).length > 0) { return false; } if (t.o.autogrowOnEnter) { ...
javascript
{ "resource": "" }
q20969
train
function () { var t = this, prefix = t.o.prefix; t.$btnPane.removeClass(prefix + 'disable'); t.$overlay.off(); // Find the modal box var $modalBox = $('.' + prefix + 'modal-box', $(t.doc.body)); $modalBox.animate({ ...
javascript
{ "resource": "" }
q20970
train
function (title, fields, cmd) { var t = this, prefix = t.o.prefix, lg = t.lang, html = ''; $.each(fields, function (fieldName, field) { var l = field.label || fieldName, n = field.name || fieldName, ...
javascript
{ "resource": "" }
q20971
buildButtonDef
train
function buildButtonDef(trumbowyg) { return { fn: function () { var $modal = trumbowyg.openModal('Code', [ '<div class="' + trumbowyg.o.prefix + 'highlight-form-group">', ' <select class="' + trumbowyg.o.prefix + 'highlight-form-control langu...
javascript
{ "resource": "" }
q20972
CalculateCircleCenter
train
function CalculateCircleCenter (A, B, C) { const aSlope = (B.y - A.y) / (B.x - A.x); const bSlope = (C.y - B.y) / (C.x - B.x); if (aSlope === 0 || bSlope === 0) { // rotate the points about origin to retry and then rotate the answer back. // this should avoid div by zero. // we could pick any acute a...
javascript
{ "resource": "" }
q20973
checkObject
train
function checkObject (obj) { if (util.isArray(obj)) { obj.forEach(function (o) { checkObject(o); }); } if (typeof obj === 'object' && obj !== null) { Object.keys(obj).forEach(function (k) { checkKey(k, obj[k]); checkObject(obj[k]); }); } }
javascript
{ "resource": "" }
q20974
isPrimitiveType
train
function isPrimitiveType (obj) { return ( typeof obj === 'boolean' || typeof obj === 'number' || typeof obj === 'string' || obj === null || util.isDate(obj) || util.isArray(obj)); }
javascript
{ "resource": "" }
q20975
createModifierFunction
train
function createModifierFunction (modifier) { return function (obj, field, value) { var fieldParts = typeof field === 'string' ? field.split('.') : field; if (fieldParts.length === 1) { lastStepModifierFunctions[modifier](obj, field, value); } else { if (obj[fieldParts[0]] === undefined) { ...
javascript
{ "resource": "" }
q20976
areComparable
train
function areComparable (a, b) { if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) && typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) { return false; } if (typeof a !== typeof b) { return false; } return true; }
javascript
{ "resource": "" }
q20977
getRandomArray
train
function getRandomArray (n) { var res = [] , i, j, temp ; for (i = 0; i < n; i += 1) { res[i] = i; } for (i = n - 1; i >= 1; i -= 1) { j = Math.floor((i + 1) * Math.random()); temp = res[i]; res[i] = res[j]; res[j] = temp; } return res; }
javascript
{ "resource": "" }
q20978
Cursor
train
function Cursor (db, query, execFn) { this.db = db; this.query = query || {}; if (execFn) { this.execFn = execFn; } }
javascript
{ "resource": "" }
q20979
_AVLTree
train
function _AVLTree (options) { options = options || {}; this.left = null; this.right = null; this.parent = options.parent !== undefined ? options.parent : null; if (options.hasOwnProperty('key')) { this.key = options.key; } this.data = options.hasOwnProperty('value') ? [options.value] : []; this.unique = ...
javascript
{ "resource": "" }
q20980
append
train
function append (array, toAppend) { var i; for (i = 0; i < toAppend.length; i += 1) { array.push(toAppend[i]); } }
javascript
{ "resource": "" }
q20981
getRandomArray
train
function getRandomArray (n) { var res, next; if (n === 0) { return []; } if (n === 1) { return [0]; } res = getRandomArray(n - 1); next = Math.floor(Math.random() * n); res.splice(next, 0, n - 1); // Add n-1 at a random position in the array return res; }
javascript
{ "resource": "" }
q20982
Promise
train
function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, t...
javascript
{ "resource": "" }
q20983
KafkaConsumerStream
train
function KafkaConsumerStream(consumer, options) { if (!(this instanceof KafkaConsumerStream)) { return new KafkaConsumerStream(consumer, options); } if (options === undefined) { options = { waitInterval: 1000 }; } else if (typeof options === 'number') { options = { waitInterval: options }; } else...
javascript
{ "resource": "" }
q20984
retry
train
function retry() { if (!self.waitInterval) { setImmediate(function() { self._read(size); }); } else { setTimeout(function() { self._read(size); }, self.waitInterval * Math.random()).unref(); } }
javascript
{ "resource": "" }
q20985
RefCounter
train
function RefCounter(onActive, onPassive) { this.context = {}; this.onActive = onActive; this.onPassive = onPassive; this.currentValue = 0; this.isRunning = false; }
javascript
{ "resource": "" }
q20986
Client
train
function Client(globalConf, SubClientType, topicConf) { if (!(this instanceof Client)) { return new Client(globalConf, SubClientType, topicConf); } Emitter.call(this); // This superclass must be initialized with the Kafka.{Producer,Consumer} // @example var client = new Client({}, Kafka.Producer); // ...
javascript
{ "resource": "" }
q20987
TopicPartition
train
function TopicPartition(topic, partition, offset) { if (!(this instanceof TopicPartition)) { return new TopicPartition(topic, partition, offset); } // Validate that the elements we are iterating over are actual topic partition // js objects. They do not need an offset, but they do need partition if (!top...
javascript
{ "resource": "" }
q20988
KafkaConsumer
train
function KafkaConsumer(conf, topicConf) { if (!(this instanceof KafkaConsumer)) { return new KafkaConsumer(conf, topicConf); } conf = shallowCopy(conf); topicConf = shallowCopy(topicConf); var onRebalance = conf.rebalance_cb; var self = this; // If rebalance is undefined we don't want any part of ...
javascript
{ "resource": "" }
q20989
createSerializer
train
function createSerializer(serializer) { var applyFn = function serializationWrapper(v, cb) { try { return cb ? serializer(v, cb) : serializer(v); } catch (e) { var modifiedError = new Error('Could not serialize value: ' + e.message); modifiedError.value = v; modifiedError.serializer = ...
javascript
{ "resource": "" }
q20990
HighLevelProducer
train
function HighLevelProducer(conf, topicConf) { if (!(this instanceof HighLevelProducer)) { return new HighLevelProducer(conf, topicConf); } // Force this to be true for the high level producer conf = shallowCopy(conf); conf.dr_cb = true; // producer is an initialized consumer object // @see NodeKafka...
javascript
{ "resource": "" }
q20991
doProduce
train
function doProduce(v, k) { try { var r = self._oldProduce(topic, partition, v, k, timestamp, opaque); self._hl.deliveryEmitter.once(opaque.__message_id, function(err, offset) { self._hl.pollingRef.decrement(); setImmediate(function() { // Offset must be greater...
javascript
{ "resource": "" }
q20992
LibrdKafkaError
train
function LibrdKafkaError(e) { if (!(this instanceof LibrdKafkaError)) { return new LibrdKafkaError(e); } if (typeof e === 'number') { this.message = librdkafka.err2str(e); this.code = e; this.errno = e; if (e >= LibrdKafkaError.codes.ERR__END) { this.origin = 'local'; } else { ...
javascript
{ "resource": "" }
q20993
Producer
train
function Producer(conf, topicConf) { if (!(this instanceof Producer)) { return new Producer(conf, topicConf); } conf = shallowCopy(conf); topicConf = shallowCopy(topicConf); /** * Producer message. This is sent to the wrapper, not received from it * * @typedef {object} Producer~Message * @pr...
javascript
{ "resource": "" }
q20994
ProducerStream
train
function ProducerStream(producer, options) { if (!(this instanceof ProducerStream)) { return new ProducerStream(producer, options); } if (options === undefined) { options = {}; } else if (typeof options === 'string') { options = { encoding: options }; } else if (options === null || typeof options...
javascript
{ "resource": "" }
q20995
createAdminClient
train
function createAdminClient(conf) { var client = new AdminClient(conf); // Wrap the error so we throw if it failed with some context LibrdKafkaError.wrap(client.connect(), true); // Return the client if we succeeded return client; }
javascript
{ "resource": "" }
q20996
AdminClient
train
function AdminClient(conf) { if (!(this instanceof AdminClient)) { return new AdminClient(conf); } conf = shallowCopy(conf); /** * NewTopic model. * * This is the representation of a new message that is requested to be made * using the Admin client. * * @typedef {object} AdminClient~NewT...
javascript
{ "resource": "" }
q20997
train
function(ev) { var gridEvent; if (this.isLocked) { ev.preventDefault(); return; } gridEvent = keyEvent.generate(ev); if (!gridEvent) { return; } this._lock(); if (shouldPreventDefault(gridEvent)) { ev.p...
javascript
{ "resource": "" }
q20998
train
function(ev) { var clipboardData = (ev.originalEvent || ev).clipboardData || window.clipboardData; if (!isEdge && !supportWindowClipboardData) { ev.preventDefault(); this._pasteInOtherBrowsers(clipboardData); } else { this._pasteInMSBrowsers(clipboardData); ...
javascript
{ "resource": "" }
q20999
flattenMessageMap
train
function flattenMessageMap(data) { var obj = {}; var newKey; _.each(data, function(groupMessages, key) { _.each(groupMessages, function(message, subKey) { newKey = [key, subKey].join('.'); obj[newKey] = message; }); }, this); return obj; }
javascript
{ "resource": "" }