_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(); img.close(); // Return (w h) var expr = []; expr.push(new nodes.Unit(size[0], 'px')); expr.push(new nodes.Unit(size[1], 'px')); return expr; }
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 node; } } // Avoid overflows from importing the same file over again if (~importStack.indexOf(file)) throw new Error('import loop has been found'); var str = fs.readFileSync(file, 'utf8'); // shortcut for empty files if (!str.trim()) return nodes.null; // Expose imports node.path = file; node.dirname = dirname(file); // Store the modified time stat = fs.statSync(file); node.mtime = stat.mtime; this.paths.push(node.dirname); if (this.options._imports) this.options._imports.push(node.clone()); // Parse the file importStack.push(file); nodes.filename = file; if (literal) { literal = new nodes.Literal(str.replace(/\r\n?/g, '\n')); literal.lineno = literal.column = 1; if (!this.resolveURL) return literal; } // parse var block = new nodes.Block , parser = new Parser(str, utils.merge({ root: block }, this.options)); try { block = parser.parse(); } catch (err) { var line = parser.lexer.lineno , column = parser.lexer.column; if (literal && this.includeCSS && this.resolveURL) { this.warn('ParseError: ' + file + ':' + line + ':' + column + '. This file included as-is'); return literal; } else { err.filename = file; err.lineno = line; err.column = column; err.input = str; throw err; } } // Evaluate imported "root" block = block.clone(this.currentBlock); block.parent = this.currentBlock; block.scope = false; var ret = this.visit(block); importStack.pop(); if (!this.resolveURL || this.resolveURL.nocheck) this.paths.pop(); return ret; }
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.getLocales() // Try BCP47 codes, otherwise load family language if exist if (locales.indexOf(currentLocale) !== -1) { i18nL.setLocale(currentLocale) } else { i18nL.setLocale(getSimilar(locales, currentLocale)) } // Only refresh if the language has already been selected once. // This will prevent the update loop if (_locale) { electron.remote.getCurrentWebContents().reloadIgnoringCache() } }) _locale = true }
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.main.isMinimized()) windows.main.restore() windows.main.focus() } }) }
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(value)) { clearTimeout(timer) update() } else if (value !== lastValue) { clearTimeout(timer) var delay = typeof timeThreshold === 'function' ? timeThreshold(value, outputValue()) : timeThreshold timer = setTimeout(update, delay) } lastValue = value } function update () { var value = obs() if (value !== outputValue()) { outputValue.set(value) } } }
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; } if (aOverlapMS > 0) { this.overlapMs = aOverlapMS; } if (aSequenceMS > 0) { this.sequenceMs = aSequenceMS; this.bAutoSeqSetting = false; } else { // zero or below, use automatic setting this.bAutoSeqSetting = true; } if (aSeekWindowMS > 0) { this.seekWindowMs = aSeekWindowMS; this.bAutoSeekSetting = false; } else { // zero or below, use automatic setting this.bAutoSeekSetting = true; } this.calcSeqParameters(); this.calculateOverlapLength(this.overlapMs); // set tempo to recalculate 'sampleReq' this.tempo = this._tempo; }
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; this.pRefMidBuffer = new Float32Array(this.overlapLength * 2); this.pMidBuffer = new Float32Array(this.overlapLength * 2); }
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 (this.bAutoSeekSetting) { seek = AUTOSEEK_C + AUTOSEEK_K * this._tempo; seek = this.checkLimits(seek, AUTOSEEK_AT_MAX, AUTOSEEK_AT_MIN); this.seekWindowMs = Math.floor(seek + 0.5); } // Update seek window lengths this.seekWindowLength = Math.floor( (this.sampleRate * this.sequenceMs) / 1000 ); this.seekLength = Math.floor( (this.sampleRate * this.seekWindowMs) / 1000 ); }
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[cnt2 + 1] * temp; } }
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, fScale, fi, pInputOffset, pOutputOffset; fScale = 1 / this.overlapLength; for (i = 0; i < this.overlapLength; i++) { fTemp = (this.overlapLength - i) * fScale; fi = i * fScale; cnt2 = 2 * i; pInputOffset = cnt2 + pInputPos; pOutputOffset = cnt2 + pOutputPos; pOutput[pOutputOffset + 0] = pInput[pInputOffset + 0] * fi + this.pMidBuffer[cnt2 + 0] * fTemp; pOutput[pOutputOffset + 1] = pInput[pInputOffset + 1] * fi + this.pMidBuffer[cnt2 + 1] * 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); } else if (pxPerSec >= 25 * 1) { secondsStr = seconds.toFixed(1); } if (minutes > 0) { if (seconds < 10) { secondsStr = '0' + secondsStr; } return `${minutes}:${secondsStr}`; } return secondsStr; }
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) { retval = 1; } else if (pxPerSec * 5 >= 25) { retval = 5; } else if (pxPerSec * 15 >= 25) { retval = 15; } else { retval = Math.ceil(0.5 / pxPerSec) * 60; } return retval; }
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) { retval = 1; } else if (pxPerSec * 5 >= 25) { retval = 5; } else if (pxPerSec * 15 >= 25) { retval = 15; } else { retval = Math.ceil(0.5 / pxPerSec) * 60; } return retval; }
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.attributes, data: region.data }; }) ); }
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, function(val, index) { if (Math.abs(val) <= minValue) { silences.push(index); } }); // Cluster silence values var clusters = []; silences.forEach(function(val, index) { if (clusters.length && val == silences[index - 1] + 1) { clusters[clusters.length - 1].push(val); } else { clusters.push([val]); } }); // Filter silence clusters by minimum length var fClusters = clusters.filter(function(cluster) { return cluster.length >= minLen; }); // Create regions on the edges of silences var regions = fClusters.map(function(cluster, index) { var next = fClusters[index + 1]; return { start: cluster[cluster.length - 1], end: next ? next[0] : length - 1 }; }); // Add an initial region if the audio doesn't start with silence var firstCluster = fClusters[0]; if (firstCluster && firstCluster[0] != 0) { regions.unshift({ start: 0, end: firstCluster[firstCluster.length - 1] }); } // Filter regions by minimum length var fRegions = regions.filter(function(reg) { return reg.end - reg.start >= minLen; }); // Return time-based regions return fRegions.map(function(reg) { return { start: Math.round(reg.start * coef * 10) / 10, end: Math.round(reg.end * coef * 10) / 10 }; }); }
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 = function(e) { e.preventDefault(); region.update({ start: form.elements.start.value, end: form.elements.end.value, data: { note: form.elements.note.value } }); form.style.opacity = 0; }; form.onreset = function() { form.style.opacity = 0; form.dataset.region = null; }; form.dataset.region = region.id; }
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 this.isInitialised = false; } init() { this.isInitialised = true; } destroy() {} } return { name, deferInit, staticProps: { [`${name}Static`]: 'static property value' }, instance: MockPlugin }; }
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 }, options ) ); wavesurfer.load(TestHelpers.EXAMPLE_FILE_PATH); }
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 => { if (!AutoNumericHelper.isIE11() && options.valuesToStrings[valuesToStringObjectName] !== null) { Object.freeze(options.valuesToStrings[valuesToStringObjectName]); } }); } else if (optionName !== 'styleRules') { if (!AutoNumericHelper.isIE11() && options[optionName] !== null) { Object.freeze(options[optionName]); } } }); // Then freeze the options object globally return Object.freeze(options); }
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.captureStackTrace) { Error.captureStackTrace(instance, InvalidDerefInputError); } return instance; }
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._callbacks = []; this._count = 0; this._disposable = null; this._collapsed = null; this._disposed = false; }
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 callbacks. oPaths[idx] = optimizedPaths; rPaths[idx] = requestedPaths; callbacks[idx] = callback; ++self._count; // If it has not been scheduled, then schedule the action if (!self.scheduled) { self.scheduled = true; var flushedDisposable; var scheduleDisposable = self._scheduler.schedule(function() { flushedDisposable = flushGetRequest(self, oPaths, function(err, data) { var i, fn, len; var model = self.requestQueue.model; self.requestQueue.removeRequest(self); self._disposed = true; if (model._treatDataSourceErrorsAsJSONGraphErrors ? err instanceof InvalidSourceError : !!err) { for (i = 0, len = callbacks.length; i < len; ++i) { fn = callbacks[i]; if (fn) { fn(err); } } return; } // If there is at least one callback remaining, then // callback the callbacks. if (self._count) { // currentVersion will get added to each inserted // node as node.$_version inside of self._merge. // // atom values just downloaded with $expires: 0 // (now-expired) will get assigned $_version equal // to currentVersion, and checkCacheAndReport will // later consider those nodes to not have expired // for the duration of current event loop tick // // we unset currentCacheVersion after all callbacks // have been called, to ensure that only these // particular callbacks and any synchronous model.get // callbacks inside of these, get the now-expired // values var currentVersion = incrementVersion.getCurrentVersion(); currentCacheVersion.setVersion(currentVersion); var mergeContext = { hasInvalidatedResult: false }; var pathsErr = model._useServerPaths && data && data.paths === undefined ? new Error("Server responses must include a 'paths' field when Model._useServerPaths === true") : undefined; if (!pathsErr) { self._merge(rPaths, err, data, mergeContext); } // Call the callbacks. The first one inserts all // the data so that the rest do not have consider // if their data is present or not. for (i = 0, len = callbacks.length; i < len; ++i) { fn = callbacks[i]; if (fn) { fn(pathsErr || err, data, mergeContext.hasInvalidatedResult); } } currentCacheVersion.setVersion(null); } }); self._disposable = flushedDisposable; }); // If the scheduler is sync then `flushedDisposable` will be // defined, and we want to use it, because that's what aborts an // in-flight XHR request, for example. // But if the scheduler is async, then `flushedDisposable` won't be // defined yet, and so we must use the scheduler's disposable until // `flushedDisposable` is defined. Since we want to still use // `flushedDisposable` once it is defined (to be able to abort in- // flight XHR requests), hence the reassignment of `_disposable` // above. self._disposable = flushedDisposable || scheduleDisposable; } // Disposes this batched request. This does not mean that the // entire request has been disposed, but just the local one, if all // requests are disposed, then the outer disposable will be removed. return createDisposable(self, idx); }
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 new callback // as one of the dependents of that request if (complementResult.intersection.length) { inserted = true; var idx = self._callbacks.length; self._callbacks[idx] = callback; self._requestedPaths[idx] = complementResult.intersection; self._optimizedPaths[idx] = []; ++self._count; disposable = createDisposable(self, idx); } return [inserted, complementResult.requestedComplement, complementResult.optimizedComplement, disposable]; }
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 = emptyArray; // flatten all the requested paths, adds them to the var nextPaths = model._useServerPaths ? data.paths : flattenRequestedPaths(requested); // Insert errors in every requested position. if (err && model._treatDataSourceErrorsAsJSONGraphErrors) { var error = err; // Converts errors to objects, a more friendly storage // of errors. if (error instanceof Error) { error = { message: error.message }; } // Not all errors are value $types. if (!error.$type) { error = { $type: $error, value: error }; } var pathValues = nextPaths.map(function(x) { return { path: x, value: error }; }); setPathValues(model, pathValues, null, errorSelector, comparator, mergeContext); } // Insert the jsonGraph from the dataSource. else { setJSONGraphs(model, [{ paths: nextPaths, jsonGraph: data.jsonGraph }], null, errorSelector, comparator, mergeContext); } // return the model"s boundPath model._path = boundPath; }
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] = []; // If there are no more requests, then dispose all of the request. var count = --request._count; var disposable = request._disposable; if (count === 0) { // looking for unsubscribe here to support more data sources (Rx) if (disposable.unsubscribe) { disposable.unsubscribe(); } else { disposable.dispose(); } request.requestQueue.removeRequest(request); } }; }
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 (currentDisposable.dispose) { currentDisposable.dispose(); } else { currentDisposable(); } }
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 groups = []; var group, groupType; var argIndex = -1; var argCount = args.length; // Validation of arguments have been moved out of this function. while (++argIndex < argCount) { var arg = args[argIndex]; var argType; if (isArray(arg) || typeof arg === "string") { arg = pathSyntax.fromPath(arg); argType = "PathValues"; } else if (isPathValue(arg)) { arg.path = pathSyntax.fromPath(arg.path); argType = "PathValues"; } else if (isJSONGraphEnvelope(arg)) { argType = "JSONGs"; } else if (isJSONEnvelope(arg)) { argType = "PathMaps"; } if (groupType !== argType) { groupType = argType; group = { inputType: argType, arguments: [] }; groups.push(group); } group.arguments.push(arg); } this._groups = groups; }
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(instance, Object.getPrototypeOf(this)); } if (Error.captureStackTrace) { Error.captureStackTrace(instance, BoundJSONGraphModelError); } return instance; }
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.setPrototypeOf) { Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); } if (Error.captureStackTrace) { Error.captureStackTrace(instance, InvalidModelError); } return instance; }
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, error, value; // The response is an array like this [id, error, data] if (response[0] === id) { error = response[1]; if (error) { observer.onError(error); } else { value = response[2]; observer.onNext(value); observer.onCompleted(); } } }; // Add the identifier to the front of the message action.unshift(id); self._worker.postMessage(action); self._worker.addEventListener('message', handler); // This is the action to perform if the consumer unsubscribes from the observable return function() { self._worker.removeEventListener('message', handler); }; }); }
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._request = options.request || options._request || new RequestQueue(this, this._scheduler); this._ID = ID++; if (typeof options.maxSize === "number") { this._maxSize = options.maxSize; } else { this._maxSize = options._maxSize || Model.prototype._maxSize; } if (typeof options.maxRetries === "number") { this._maxRetries = options.maxRetries; } else { this._maxRetries = options._maxRetries || Model.prototype._maxRetries; } if (typeof options.collectRatio === "number") { this._collectRatio = options.collectRatio; } else { this._collectRatio = options._collectRatio || Model.prototype._collectRatio; } if (options.boxed || options.hasOwnProperty("_boxed")) { this._boxed = options.boxed || options._boxed; } if (options.materialized || options.hasOwnProperty("_materialized")) { this._materialized = options.materialized || options._materialized; } if (typeof options.treatErrorsAsValues === "boolean") { this._treatErrorsAsValues = options.treatErrorsAsValues; } else if (options.hasOwnProperty("_treatErrorsAsValues")) { this._treatErrorsAsValues = options._treatErrorsAsValues; } this._useServerPaths = options._useServerPaths || false; this._allowFromWhenceYouCame = options.allowFromWhenceYouCame || options._allowFromWhenceYouCame || false; this._treatDataSourceErrorsAsJSONGraphErrors = options._treatDataSourceErrorsAsJSONGraphErrors || false; if (options.cache) { this.setCache(options.cache); } }
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(instance, Object.getPrototypeOf(this)); } if (Error.captureStackTrace) { Error.captureStackTrace(instance, MaxRetryExceededError); } return instance; }
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) { Error.captureStackTrace(instance, NullInPathError); } return instance; }
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 || false; }
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[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff); this.bitmap.data[idx + 1] = Math.min( this.bitmap.data[idx + 1] + dither, 0xff ); this.bitmap.data[idx + 2] = Math.min( this.bitmap.data[idx + 2] + dither, 0xff ); }); if (isNodePattern(cb)) { cb.call(this, null, this); } return this; }
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); } const bitmap = Buffer.alloc(this.bitmap.data.length); this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function( x, y, idx ) { const _x = horizontal ? this.bitmap.width - 1 - x : x; const _y = vertical ? this.bitmap.height - 1 - y : y; const _idx = (this.bitmap.width * _y + _x) << 2; const data = this.bitmap.data.readUInt32BE(idx); bitmap.writeUInt32BE(data, _idx); }); this.bitmap.data = Buffer.from(bitmap); if (isNodePattern(cb)) { cb.call(this, null, this); } return this; }
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.data[index + 1]]++; histogram.b[this.bitmap.data[index + 2]]++; }); return histogram; }
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: function () { trumbowyg.execCmd('insertHTML', trumbowyg.o.plugins.mention.formatResult(item)); return true; } }; trumbowyg.addBtnDef(btn, btnDef); dropdown.push(btn); }); return dropdown; }
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); }, hasIcon: false, title: template.name }); templates.push('template_' + index); }); return templates; }
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: function(){ trumbowyg.saveRange(); var text = trumbowyg.getRangeText(); if (text.replace(/\s/g, '') !== '') { try { var parent = getSelectionParentElement(); $(parent).css('lineHeight', size); } catch (e) { } } } }); dropdown.push('lineheight_' + size); }); return dropdown; }
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) { t.$ed.height(oldHeight); setTimeout(function () { t.$ed.css({height: totalHeight}); t.$c.trigger('tbwresize'); }, 0); } }
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 = [btnGrp]; } var $btnGroup = $('<div/>', { class: prefix + 'button-group ' + ((btnGrp.indexOf('fullscreen') >= 0) ? prefix + 'right' : '') }); $.each(btnGrp, function (i, btn) { try { // Prevent buildBtn error if (t.isSupportedBtn(btn)) { // It's a supported button $btnGroup.append(t.buildBtn(btn)); } } catch (c) { } }); if ($btnGroup.html().trim().length > 0) { $btnPane.append($btnGroup); } }); t.$box.prepend($btnPane); }
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, param: btn.param || btnName }; } t.tagToButton[(btn.tag || btnName).toLowerCase()] = btnName; return $('<button/>', { type: 'button', class: prefix + btnName + '-dropdown-button ' + (btn.class || '') + (btn.ico ? ' ' + prefix + btn.ico + '-button' : ''), html: t.hasSvg && hasIcon ? '<svg><use xlink:href="' + t.svgPath + '#' + prefix + (btn.ico || btnName).replace(/([A-Z]+)/g, '-$1').toLowerCase() + '"/></svg>' + (btn.text || btn.title || t.lang[btnName] || btnName) : (btn.text || btn.title || t.lang[btnName] || btnName), title: (btn.key ? '(' + (t.isMac ? 'Cmd' : 'Ctrl') + ' + ' + btn.key + ')' : null), style: btn.style || null, mousedown: function () { $('body', t.doc).trigger('mousedown'); t.execCmd(btn.fn || btnName, btn.param || btnName, btn.forceCss); return false; } }); }
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.eventNamespace, function () { if (!$box) { return; } t.syncCode(); var scrollTop = $(window).scrollTop(), offset = $box.offset().top + 1, bp = t.$btnPane, oh = bp.outerHeight() - 2; if ((scrollTop - offset > 0) && ((scrollTop - offset - t.height) < 0)) { if (!t.isFixed) { t.isFixed = true; bp.css({ position: 'fixed', top: 0, left: fixedFullWidth ? '0' : 'auto', zIndex: 7 }); $([t.$ta, t.$ed]).css({marginTop: bp.height()}); } bp.css({ width: fixedFullWidth ? '100%' : (($box.width() - 1) + 'px') }); $('.' + t.o.prefix + 'fixed-top', $box).css({ position: fixedFullWidth ? 'fixed' : 'absolute', top: fixedFullWidth ? oh : oh + (scrollTop - offset) + 'px', zIndex: 15 }); } else if (t.isFixed) { t.isFixed = false; bp.removeAttr('style'); $([t.$ta, t.$ed]).css({marginTop: 0}); $('.' + t.o.prefix + 'fixed-top', $box).css({ position: 'absolute', top: oh }); } }); }
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') .show() ); } else { t.$box.after( t.$ed .css({height: ''}) .removeClass(prefix + 'editor') .removeAttr('contenteditable') .removeAttr('dir') .html(t.html()) .show() ); } t.$ed.off('dblclick', 'img'); t.destroyPlugins(); t.$box.remove(); t.$c.removeData('trumbowyg'); $('body').removeClass(prefix + 'body-fullscreen'); t.$c.trigger('tbwclose'); $(window).off('scroll.' + t.eventNamespace + ' resize.' + t.eventNamespace); }
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.doc.activeElement.blur(); t.$box.toggleClass(prefix + 'editor-hidden ' + prefix + 'editor-visible'); t.$btnPane.toggleClass(prefix + 'disable'); $('.' + prefix + 'viewHTML-button', t.$btnPane).toggleClass(prefix + 'active'); if (t.$box.hasClass(prefix + 'editor-visible')) { t.$ta.attr('tabindex', -1); } else { t.$ta.removeAttr('tabindex'); } if (t.o.autogrowOnEnter && !t.autogrowOnEnterDontClose) { t.autogrowEditorOnEnter(); } }, 0); }
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'); $('body', d).trigger('mousedown'); if (show) { var o = $btn.offset().left; $btn.addClass(prefix + 'active'); $dropdown.css({ position: 'absolute', top: $btn.offset().top - t.$btnPane.offset().top + $btn.outerHeight(), left: (t.o.fixedFullWidth && t.isFixed) ? o + 'px' : (o - t.$btnPane.offset().left) + 'px' }).show(); $(window).trigger('scroll'); $('body', d).on('mousedown.' + t.eventNamespace, function (e) { if (!$dropdown.is(e.target)) { $('.' + prefix + 'dropdown', t.$box).hide(); $('.' + prefix + 'active', t.$btnPane).removeClass(prefix + 'active'); $('body', d).off('mousedown.' + t.eventNamespace); } }); } }
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.semanticKeepAttributes); t.semanticTag('strike', t.o.semanticKeepAttributes); if (full) { var inlineElementsSelector = t.o.inlineElementsSelector, blockElementsSelector = ':not(' + inlineElementsSelector + ')'; // Wrap text nodes in span for easier processing t.$ed.contents().filter(function () { return this.nodeType === 3 && this.nodeValue.trim().length > 0; }).wrap('<span data-tbw/>'); // Wrap groups of inline elements in paragraphs (recursive) var wrapInlinesInParagraphsFrom = function ($from) { if ($from.length !== 0) { var $finalParagraph = $from.nextUntil(blockElementsSelector).addBack().wrapAll('<p/>').parent(), $nextElement = $finalParagraph.nextAll(inlineElementsSelector).first(); $finalParagraph.next('br').remove(); wrapInlinesInParagraphsFrom($nextElement); } }; wrapInlinesInParagraphsFrom(t.$ed.children(inlineElementsSelector).first()); t.semanticTag('div', true); // Unwrap paragraphs content, containing nothing useful t.$ed.find('p').filter(function () { // Don't remove currently being edited element if (t.range && this === t.range.startContainer) { return false; } return $(this).text().trim().length === 0 && $(this).children().not('br,span').length === 0; }).contents().unwrap(); // Get rid of temporary span's $('[data-tbw]', t.$ed).contents().unwrap(); // Remove empty <p> t.$ed.find('p:empty').remove(); } if (!keepRange) { t.restoreRange(); } t.syncTextarea(); } }
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, target; while (['A', 'DIV'].indexOf(node.nodeName) < 0) { node = node.parentNode; } if (node && node.nodeName === 'A') { var $a = $(node); text = $a.text(); url = $a.attr('href'); if (!t.o.minimalLinks) { title = $a.attr('title'); target = $a.attr('target'); } var range = t.doc.createRange(); range.selectNode(node); documentSelection.removeAllRanges(); documentSelection.addRange(range); } t.saveRange(); var options = { url: { label: 'URL', required: true, value: url }, text: { label: t.lang.text, value: text } }; if (!t.o.minimalLinks) { Object.assign(options, { title: { label: t.lang.title, value: title }, target: { label: t.lang.target, value: target } }); } t.openModalInsert(t.lang.createLink, options, function (v) { // v is value var url = t.prependUrlPrefix(v.url); if (!url.length) { return false; } var link = $(['<a href="', url, '">', v.text || v.url, '</a>'].join('')); if (!t.o.minimalLinks) { if (v.title.length > 0) { link.attr('title', v.title); } if (v.target.length > 0) { link.attr('target', v.target); } } t.range.deleteContents(); t.range.insertNode(link[0]); t.syncCode(); t.$c.trigger('tbwchange'); return true; }); }
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) { t.autogrowOnEnterDontClose = true; } t.saveRange(); t.showOverlay(); // Disable all btnPane btns t.$btnPane.addClass(prefix + 'disable'); // Build out of ModalBox, it's the mask for animations var $modal = $('<div/>', { class: prefix + 'modal ' + prefix + 'fixed-top' }).css({ top: t.$box.offset().top + t.$btnPane.height(), zIndex: 99999 }).appendTo($(t.doc.body)); // Click on overlay close modal by cancelling them t.$overlay.one('click', function () { $modal.trigger(CANCEL_EVENT); return false; }); // Build the form var $form = $('<form/>', { action: '', html: content }) .on('submit', function () { $modal.trigger(CONFIRM_EVENT); return false; }) .on('reset', function () { $modal.trigger(CANCEL_EVENT); return false; }) .on('submit reset', function () { if (t.o.autogrowOnEnter) { t.autogrowOnEnterDontClose = false; } }); // Build ModalBox and animate to show them var $box = $('<div/>', { class: prefix + 'modal-box', html: $form }) .css({ top: '-' + t.$btnPane.outerHeight() + 'px', opacity: 0 }) .appendTo($modal) .animate({ top: 0, opacity: 1 }, 100); // Append title $('<span/>', { text: title, class: prefix + 'modal-title' }).prependTo($box); $modal.height($box.outerHeight() + 10); // Focus in modal box $('input:first', $box).focus(); // Append Confirm and Cancel buttons t.buildModalBtn('submit', $box); t.buildModalBtn('reset', $box); $(window).trigger('scroll'); return $modal; }
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({ top: '-' + $modalBox.height() }, 100, function () { $modalBox.parent().remove(); t.hideOverlay(); }); t.restoreRange(); }
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, a = field.attributes || {}; var attr = Object.keys(a).map(function (prop) { return prop + '="' + a[prop] + '"'; }).join(' '); html += '<label><input type="' + (field.type || 'text') + '" name="' + n + '"' + (field.type === 'checkbox' && field.value ? ' checked="checked"' : ' value="' + (field.value || '').replace(/"/g, '&quot;')) + '"' + attr + '><span class="' + prefix + 'input-infos"><span>' + (lg[l] ? lg[l] : l) + '</span></span></label>'; }); return t.openModal(title, html) .on(CONFIRM_EVENT, function () { var $form = $('form', $(this)), valid = true, values = {}; $.each(fields, function (fieldName, field) { var n = field.name || fieldName; var $field = $('input[name="' + n + '"]', $form), inputType = $field.attr('type'); switch (inputType.toLowerCase()) { case 'checkbox': values[n] = $field.is(':checked'); break; case 'radio': values[n] = $field.filter(':checked').val(); break; default: values[n] = $.trim($field.val()); break; } // Validate value if (field.required && values[n] === '') { valid = false; t.addErrorOnModalField($field, t.lang.required); } else if (field.pattern && !field.pattern.test(values[n])) { valid = false; t.addErrorOnModalField($field, field.patternError); } }); if (valid) { t.restoreRange(); if (cmd(values, fields)) { t.syncCode(); t.$c.trigger('tbwchange'); t.closeModal(); $(this).off(CONFIRM_EVENT); } } }) .one(CANCEL_EVENT, function () { $(this).off(CONFIRM_EVENT); t.closeModal(); }); }
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 language">', (function () { var options = ''; for (var lang in Prism.languages) { if (Prism.languages.hasOwnProperty(lang)) { options += '<option value="' + lang + '">' + lang + '</option>'; } } return options; })(), ' </select>', '</div>', '<div class="' + trumbowyg.o.prefix + 'highlight-form-group">', ' <textarea class="' + trumbowyg.o.prefix + 'highlight-form-control code"></textarea>', '</div>', ].join('\n')), $language = $modal.find('.language'), $code = $modal.find('.code'); // Listen clicks on modal box buttons $modal.on('tbwconfirm', function () { trumbowyg.restoreRange(); trumbowyg.execCmd('insertHTML', highlightIt($code.val(), $language.val())); trumbowyg.execCmd('insertHTML', '<p><br></p>'); trumbowyg.closeModal(); }); $modal.on('tbwcancel', function () { trumbowyg.closeModal(); }); } }; }
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 angle here and be garuanteed this will take less than three tries. // i've discovered a clever proof for this, but I don't have room in the margin. const angle = Math.PI / 3; return rotate(CalculateCircleCenter(rotate(A, angle), rotate(B, angle), rotate(C, angle)), -1 * angle); } const center = {}; center.x = (aSlope * bSlope * (A.y - C.y) + bSlope * (A.x + B.x) - aSlope * (B.x + C.x)) / (2 * (bSlope - aSlope)); center.y = -1 * (center.x - (A.x + B.x) / 2) / aSlope + (A.y + B.y) / 2; return center; }
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) { if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented obj[fieldParts[0]] = {}; } modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value); } }; }
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 = options.unique || false; this.compareKeys = options.compareKeys || customUtils.defaultCompareKeysFunction; this.checkValueEquality = options.checkValueEquality || customUtils.defaultCheckValueEquality; }
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, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); }
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 if (options === null || typeof options !== 'object') { throw new TypeError('"options" argument must be a number or an object'); } var topics = options.topics; if (typeof topics === 'function') { // Just ignore the rest of the checks here } else if (!Array.isArray(topics)) { if (typeof topics !== 'string' && !(topics instanceof RegExp)) { throw new TypeError('"topics" argument must be a string, regex, or an array'); } else { topics = [topics]; } } options = Object.create(options); var fetchSize = options.fetchSize || 1; // Run in object mode by default. if (options.objectMode === null || options.objectMode === undefined) { options.objectMode = true; // If they did not explicitly set high water mark, and we are running // in object mode, set it to the fetch size + 2 to ensure there is room // for a standard fetch if (!options.highWaterMark) { options.highWaterMark = fetchSize + 2; } } if (options.objectMode !== true) { this._read = this._read_buffer; } else { this._read = this._read_message; } Readable.call(this, options); this.consumer = consumer; this.topics = topics; this.autoClose = options.autoClose === undefined ? true : !!options.autoClose; this.waitInterval = options.waitInterval === undefined ? 1000 : options.waitInterval; this.fetchSize = fetchSize; this.connectOptions = options.connectOptions || {}; this.streamAsBatch = options.streamAsBatch || false; // Hold the messages in here this.messages = []; var self = this; this.consumer .on('unsubscribed', function() { // Invalidate the stream when we unsubscribe self.push(null); }); // Call connect. Handles potentially being connected already this.connect(this.connectOptions); this.once('end', function() { if (this.autoClose) { this.destroy(); } }); }
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); // remember this is a superclass so this will get taken care of in // the producer and consumer main wrappers var no_event_cb = globalConf.event_cb === false; topicConf = topicConf || {}; // delete this because librdkafka will complain since this particular // key is a real conf value delete globalConf.event_cb; this._client = new SubClientType(globalConf, topicConf); // primitive callbacks from c++ wrapper // need binds on them if we want to broadcast the event via the emitter // However, the C++ wrapper lazy processes callbacks. // If we want to improve performance, removing this line is a good way to do it. // we need to do this on creation of the object // thats why we did some processing on config // Self required because we are inside an async callback function scope if (!no_event_cb) { this._client.onEvent(function eventHandler(eventType, eventData) { switch (eventType) { case 'error': self.emit('event.error', LibrdKafkaError.create(eventData)); break; case 'stats': self.emit('event.stats', eventData); break; case 'log': self.emit('event.log', eventData); break; default: self.emit('event.event', eventData); self.emit('event.' + eventType, eventData); } }); } this.metrics = {}; this._isConnected = false; this.errorCounter = 0; /** * Metadata object. Starts out empty but will be filled with information after * the initial connect. * * @type {Client~Metadata} */ this._metadata = {}; var self = this; this.on('ready', function(info) { self.metrics.connectionOpened = Date.now(); self.name = info.name; }) .on('disconnected', function() { // reset metrics self.metrics = {}; self._isConnected = false; // keep the metadata. it still may be useful }) .on('event.error', function(err) { self.lastError = err; ++self.errorCounter; }); }
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 (!topic) { throw new TypeError('"topic" must be a string and must be set'); } if (partition === null || partition === undefined) { throw new TypeError('"partition" must be a number and must set'); } // We can just set topic and partition as they stand. this.topic = topic; this.partition = partition; if (offset === undefined || offset === null) { this.offset = Topic.OFFSET_STORED; } else if (typeof offset === 'string') { switch (offset.toLowerCase()) { case 'earliest': case 'beginning': this.offset = Topic.OFFSET_BEGINNING; break; case 'latest': case 'end': this.offset = Topic.OFFSET_END; break; case 'stored': this.offset = Topic.OFFSET_STORED; break; default: throw new TypeError('"offset", if provided as a string, must be beginning, end, or stored.'); } } else if (typeof offset === 'number') { this.offset = offset; } else { throw new TypeError('"offset" must be a special string or number if it is set'); } }
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 this if (onRebalance && typeof onRebalance === 'boolean') { conf.rebalance_cb = function(err, assignment) { // Create the librdkafka error err = LibrdKafkaError.create(err); // Emit the event self.emit('rebalance', err, assignment); // That's it try { if (err.code === -175 /*ERR__ASSIGN_PARTITIONS*/) { self.assign(assignment); } else if (err.code === -174 /*ERR__REVOKE_PARTITIONS*/) { self.unassign(); } } catch (e) { // Ignore exceptions if we are not connected if (self.isConnected()) { self.emit('rebalance.error', e); } } }; } else if (onRebalance && typeof onRebalance === 'function') { /* * Once this is opted in to, that's it. It's going to manually rebalance * forever. There is no way to unset config values in librdkafka, just * a way to override them. */ conf.rebalance_cb = function(err, assignment) { // Create the librdkafka error err = err ? LibrdKafkaError.create(err) : undefined; self.emit('rebalance', err, assignment); onRebalance.call(self, err, assignment); }; } // Same treatment for offset_commit_cb var onOffsetCommit = conf.offset_commit_cb; if (onOffsetCommit && typeof onOffsetCommit === 'boolean') { conf.offset_commit_cb = function(err, offsets) { // Emit the event self.emit('offset.commit', offsets); }; } else if (onOffsetCommit && typeof onOffsetCommit === 'function') { conf.offset_commit_cb = function(err, offsets) { // Emit the event self.emit('offset.commit', offsets); onOffsetCommit.call(self, err, offsets); }; } /** * KafkaConsumer message. * * This is the representation of a message read from Kafka. * * @typedef {object} KafkaConsumer~Message * @property {buffer} value - the message buffer from Kafka. * @property {string} topic - the topic name * @property {number} partition - the partition on the topic the * message was on * @property {number} offset - the offset of the message * @property {string} key - the message key * @property {number} size - message size, in bytes. * @property {number} timestamp - message timestamp */ Client.call(this, conf, Kafka.KafkaConsumer, topicConf); this.globalConfig = conf; this.topicConfig = topicConf; this._consumeTimeout = 1000; }
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 = serializer; throw modifiedError; } }; // We can check how many parameters the function has and activate the asynchronous // operation if the number of parameters the function accepts is > 1 return { apply: applyFn, async: serializer.length > 1 }; }
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::Producer::Init Producer.call(this, conf, topicConf); var self = this; // Add a delivery emitter to the producer this._hl = { deliveryEmitter: new EventEmitter(), messageId: 0, // Special logic for polling. We use a reference counter to know when we need // to be doing it and when we can stop. This means when we go into fast polling // mode we don't need to do multiple calls to poll since they all will yield // the same result pollingRefTimeout: null, }; // Add the polling ref counter to the class which ensures we poll when we go active this._hl.pollingRef = new RefCounter(function() { self._hl.pollingRefTimeout = setInterval(function() { try { self.poll(); } catch (e) { if (!self._isConnected) { // If we got disconnected for some reason there is no point // in polling anymore clearInterval(self._hl.pollingRefTimeout); } } }, 1); }, function() { clearInterval(self._hl.pollingRefTimeout); }); // Default poll interval. More sophisticated polling is also done in create rule method this.setPollInterval(1000); // Listen to all delivery reports to propagate elements with a _message_id to the emitter this.on('delivery-report', function(err, report) { if (report.opaque && report.opaque.__message_id !== undefined) { self._hl.deliveryEmitter.emit(report.opaque.__message_id, err, report.offset); } }); // Save old produce here since we are making some modifications for it this._oldProduce = this.produce; this.produce = this._modifiedProduce; // Serializer information this.keySerializer = noopSerializer; this.valueSerializer = noopSerializer; }
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 than or equal to 0 otherwise it is a null offset // Possibly because we have acks off callback(err, offset >= 0 ? offset : null); }); }); return r; } catch (e) { callback(e); } }
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 { this.origin = 'kafka'; } Error.captureStackTrace(this, this.constructor); } else if (!util.isError(e)) { // This is the better way this.message = e.message; this.code = e.code; this.errno = e.code; if (e.code >= LibrdKafkaError.codes.ERR__END) { this.origin = 'local'; } else { this.origin = 'kafka'; } Error.captureStackTrace(this, this.constructor); } else { var message = e.message; var parsedMessage = message.split(': '); var origin, msg; if (parsedMessage.length > 1) { origin = parsedMessage[0].toLowerCase(); msg = parsedMessage[1].toLowerCase(); } else { origin = 'unknown'; msg = message.toLowerCase(); } // special cases if (msg === 'consumer is disconnected' || msg === 'producer is disconnected') { this.origin = 'local'; this.code = LibrdKafkaError.codes.ERR__STATE; this.errno = this.code; this.message = msg; } else { this.origin = origin; this.message = msg; this.code = typeof e.code === 'number' ? e.code : -1; this.errno = this.code; this.stack = e.stack; } } }
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 * @property {string|buffer} message - The buffer to send to Kafka. * @property {Topic} topic - The Kafka topic to produce to. * @property {number} partition - The partition to produce to. Defaults to * the partitioner * @property {string} key - The key string to use for the message. * @see Consumer~Message */ var gTopic = conf.topic || false; var gPart = conf.partition || null; var dr_cb = conf.dr_cb || null; var dr_msg_cb = conf.dr_msg_cb || null; // delete keys we don't want to pass on delete conf.topic; delete conf.partition; delete conf.dr_cb; delete conf.dr_msg_cb; // client is an initialized consumer object // @see NodeKafka::Producer::Init Client.call(this, conf, Kafka.Producer, topicConf); var self = this; // Delete these keys after saving them in vars this.globalConfig = conf; this.topicConfig = topicConf; this.defaultTopic = gTopic || null; this.defaultPartition = gPart == null ? -1 : gPart; this.sentMessages = 0; this.pollInterval = undefined; if (dr_msg_cb || dr_cb) { this._client.onDeliveryReport(function onDeliveryReport(err, report) { if (err) { err = LibrdKafkaError.create(err); } self.emit('delivery-report', err, report); }, !!dr_msg_cb); if (typeof dr_cb === 'function') { self.on('delivery-report', dr_cb); } } }
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 !== 'object') { throw new TypeError('"streamOptions" argument must be a string or an object'); } if (!options.objectMode && !options.topic) { throw new TypeError('ProducerStreams not using objectMode must provide a topic to produce to.'); } if (options.objectMode !== true) { this._write = this._write_buffer; } else { this._write = this._write_message; } Writable.call(this, options); this.producer = producer; this.topicName = options.topic; this.autoClose = options.autoClose === undefined ? true : !!options.autoClose; this.connectOptions = options.connectOptions || {}; this.producer.setPollInterval(options.pollInterval || 1000); if (options.encoding) { this.setDefaultEncoding(options.encoding); } // Connect to the producer. Unless we are already connected if (!this.producer.isConnected()) { this.connect(this.connectOptions); } var self = this; this.once('finish', function() { if (this.autoClose) { this.close(); } }); }
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~NewTopic * @property {string} topic - the topic name to create * @property {number} num_partitions - the number of partitions to give the topic * @property {number} replication_factor - the replication factor of the topic * @property {object} config - a list of key values to be passed as configuration * for the topic. */ this._client = new Kafka.AdminClient(conf); this._isConnected = false; this.globalConfig = conf; }
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.preventDefault(); } if (!isPasteEvent(gridEvent)) { this.domEventBus.trigger(gridEvent.type, gridEvent); } }
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": "" }