_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20400
_unsqueeze
train
function _unsqueeze (array, dims, dim) { let i, ii if (Array.isArray(array)) { const next = dim + 1 for (i = 0, ii = array.length; i < ii; i++) { array[i] = _unsqueeze(array[i], dims, next) } } else { for (let d = dim; d < dims; d++) { array = [array] } } return array }
javascript
{ "resource": "" }
q20401
getSafeProperty
train
function getSafeProperty (object, prop) { // only allow getting safe properties of a plain object if (isPlainObject(object) && isSafeProperty(object, prop)) { return object[prop] } if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) { throw new Error('Cannot access method "' + prop + ...
javascript
{ "resource": "" }
q20402
setSafeProperty
train
function setSafeProperty (object, prop, value) { // only allow setting safe properties of a plain object if (isPlainObject(object) && isSafeProperty(object, prop)) { object[prop] = value return value } throw new Error('No access to property "' + prop + '"') }
javascript
{ "resource": "" }
q20403
isSafeProperty
train
function isSafeProperty (object, prop) { if (!object || typeof object !== 'object') { return false } // SAFE: whitelisted // e.g length if (hasOwnProperty(safeNativeProperties, prop)) { return true } // UNSAFE: inherited from Object prototype // e.g constructor if (prop in Object.prototype) { ...
javascript
{ "resource": "" }
q20404
_print
train
function _print (template, values, options) { return template.replace(/\$([\w.]+)/g, function (original, key) { const keys = key.split('.') let value = values[keys.shift()] while (keys.length && value !== undefined) { const k = keys.shift() value = k ? value[k] : value + '.' } if (val...
javascript
{ "resource": "" }
q20405
format
train
function format (value) { const math = getMath() return math.format(value, { fn: function (value) { if (typeof value === 'number') { // round numbers return math.format(value, PRECISION) } else { return math.format(value) } } }) }
javascript
{ "resource": "" }
q20406
completer
train
function completer (text) { const math = getMath() let matches = [] let keyword const m = /[a-zA-Z_0-9]+$/.exec(text) if (m) { keyword = m[0] // scope variables for (const def in scope) { if (scope.hasOwnProperty(def)) { if (def.indexOf(keyword) === 0) { matches.push(def) ...
javascript
{ "resource": "" }
q20407
runStream
train
function runStream (input, output, mode, parenthesis) { const readline = require('readline') const rl = readline.createInterface({ input: input || process.stdin, output: output || process.stdout, completer: completer }) if (rl.output.isTTY) { rl.setPrompt('> ') rl.prompt() } // load ma...
javascript
{ "resource": "" }
q20408
findSymbolName
train
function findSymbolName (node) { const math = getMath() let n = node while (n) { if (math.isSymbolNode(n)) { return n.name } n = n.object } return null }
javascript
{ "resource": "" }
q20409
outputVersion
train
function outputVersion () { fs.readFile(path.join(__dirname, '/../package.json'), function (err, data) { if (err) { console.log(err.toString()) } else { const pkg = JSON.parse(data) const version = pkg && pkg.version ? pkg.version : 'unknown' console.log(version) } process.exit...
javascript
{ "resource": "" }
q20410
outputHelp
train
function outputHelp () { console.log('math.js') console.log('https://mathjs.org') console.log() console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ') console.log('real and complex numbers, units, matrices, a large set of mathematical') console.log('functions, and a fle...
javascript
{ "resource": "" }
q20411
compareArrays
train
function compareArrays (x, y) { // compare each value for (let i = 0, ii = Math.min(x.length, y.length); i < ii; i++) { const v = compareNatural(x[i], y[i]) if (v !== 0) { return v } } // compare the size of the arrays if (x.length > y.length) { return 1 } if (x.length...
javascript
{ "resource": "" }
q20412
compareObjects
train
function compareObjects (x, y) { const keysX = Object.keys(x) const keysY = Object.keys(y) // compare keys keysX.sort(naturalSort) keysY.sort(naturalSort) const c = compareArrays(keysX, keysY) if (c !== 0) { return c } // compare values for (let i = 0; i < keysX.length; i...
javascript
{ "resource": "" }
q20413
validateDoc
train
function validateDoc (doc) { let issues = [] function ignore (field) { return IGNORE_WARNINGS[field].indexOf(doc.name) !== -1 } if (!doc.name) { issues.push('name missing in document') } if (!doc.description) { issues.push('function "' + doc.name + '": description missing') } if (!doc.sy...
javascript
{ "resource": "" }
q20414
functionEntry
train
function functionEntry (name) { const fn = functions[name] let syntax = SYNTAX[name] || (fn.doc && fn.doc.syntax && fn.doc.syntax[0]) || name syntax = syntax // .replace(/^math\./, '') .replace(/\s+\/\/.*$/, '') .replace(/;$/, '') if (syntax.length < 40) { syntax ...
javascript
{ "resource": "" }
q20415
integrate
train
function integrate (f, start, end, step) { let total = 0 step = step || 0.01 for (let x = start; x < end; x += step) { total += f(x + step / 2) * step } return total }
javascript
{ "resource": "" }
q20416
mapTransform
train
function mapTransform (args, math, scope) { let x, callback if (args[0]) { x = args[0].compile().evaluate(scope) } if (args[1]) { if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args...
javascript
{ "resource": "" }
q20417
exclude
train
function exclude (object, excludedProperties) { const strippedObject = Object.assign({}, object) excludedProperties.forEach(excludedProperty => { delete strippedObject[excludedProperty] }) return strippedObject }
javascript
{ "resource": "" }
q20418
_getSubstring
train
function _getSubstring (str, index) { if (!isIndex(index)) { // TODO: better error message throw new TypeError('Index expected') } if (index.size().length !== 1) { throw new DimensionError(index.size().length, 1) } // validate whether the range is out of range const strLen = str.length valida...
javascript
{ "resource": "" }
q20419
_setSubstring
train
function _setSubstring (str, index, replacement, defaultValue) { if (!index || index.isIndex !== true) { // TODO: better error message throw new TypeError('Index expected') } if (index.size().length !== 1) { throw new DimensionError(index.size().length, 1) } if (defaultValue !== undefined) { i...
javascript
{ "resource": "" }
q20420
_getObjectProperty
train
function _getObjectProperty (object, index) { if (index.size().length !== 1) { throw new DimensionError(index.size(), 1) } const key = index.dimension(0) if (typeof key !== 'string') { throw new TypeError('String expected as index to retrieve an object property') } return getSafeProperty(object, k...
javascript
{ "resource": "" }
q20421
_setObjectProperty
train
function _setObjectProperty (object, index, replacement) { if (index.size().length !== 1) { throw new DimensionError(index.size(), 1) } const key = index.dimension(0) if (typeof key !== 'string') { throw new TypeError('String expected as index to retrieve an object property') } // clone the object...
javascript
{ "resource": "" }
q20422
_switch
train
function _switch (mat) { const I = mat.length const J = mat[0].length let i, j const ret = [] for (j = 0; j < J; j++) { const tmp = [] for (i = 0; i < I; i++) { tmp.push(mat[i][j]) } ret.push(tmp) } return ret }
javascript
{ "resource": "" }
q20423
_concat
train
function _concat (a, b, concatDim, dim) { if (dim < concatDim) { // recurse into next dimension if (a.length !== b.length) { throw new DimensionError(a.length, b.length) } const c = [] for (let i = 0; i < a.length; i++) { c[i] = _concat(a[i], b[i], concatDim, dim + 1) } return...
javascript
{ "resource": "" }
q20424
filterTransform
train
function filterTransform (args, math, scope) { let x, callback if (args[0]) { x = args[0].compile().evaluate(scope) } if (args[1]) { if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = a...
javascript
{ "resource": "" }
q20425
_filter
train
function _filter (x, callback) { // figure out what number of arguments the callback function expects const args = maxArgumentCount(callback) return filter(x, function (value, index, array) { // invoke the callback function with the right number of arguments if (args === 1) { return callback(value)...
javascript
{ "resource": "" }
q20426
checkEqualDimensions
train
function checkEqualDimensions (x, y) { const xsize = x.size() const ysize = y.size() if (xsize.length !== ysize.length) { throw new DimensionError(xsize.length, ysize.length) } }
javascript
{ "resource": "" }
q20427
camelize
train
function camelize(str) { return str .replace(STRING_CAMELIZE_REGEXP, (_match, _separator, chr) => { return chr ? chr.toUpperCase() : ''; }) .replace(/^([A-Z])/, (match) => match.toLowerCase()); }
javascript
{ "resource": "" }
q20428
interpolate
train
function interpolate(str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); }
javascript
{ "resource": "" }
q20429
replaceWord
train
function replaceWord(replaceMap, keepMap, rules) { return function (word) { // Get the correct token and case restoration functions. var token = word.toLowerCase(); // Check against the keep object map. if (keepMap.hasOwnProperty(token)) { return r...
javascript
{ "resource": "" }
q20430
pluralize
train
function pluralize(word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; }
javascript
{ "resource": "" }
q20431
findNodes
train
function findNodes(node, kind, max = Infinity) { if (!node || max == 0) { return []; } const arr = []; if (node.kind === kind) { arr.push(node); max--; } if (max > 0) { for (const child of node.getChildren()) { findNodes(child, kind, max).forEach(node ...
javascript
{ "resource": "" }
q20432
getSourceNodes
train
function getSourceNodes(sourceFile) { const nodes = [sourceFile]; const result = []; while (nodes.length > 0) { const node = nodes.shift(); if (node) { result.push(node); if (node.getChildCount(sourceFile) >= 0) { nodes.unshift(...node.getChildren()); ...
javascript
{ "resource": "" }
q20433
addImportToModule
train
function addImportToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath); }
javascript
{ "resource": "" }
q20434
addProviderToModule
train
function addProviderToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath); }
javascript
{ "resource": "" }
q20435
addEntryComponentToModule
train
function addEntryComponentToModule(source, modulePath, classifiedName, importPath) { return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath); }
javascript
{ "resource": "" }
q20436
isImported
train
function isImported(source, classifiedName, importPath) { const allNodes = getSourceNodes(source); const matchingNodes = allNodes .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration) .filter((imp) => imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) .filter((imp) => { ...
javascript
{ "resource": "" }
q20437
FfmpegCommand
train
function FfmpegCommand(input, options) { // Make 'new' optional if (!(this instanceof FfmpegCommand)) { return new FfmpegCommand(input, options); } EventEmitter.call(this); if (typeof input === 'object' && !('readable' in input)) { // Options object passed directly options = input; } else { ...
javascript
{ "resource": "" }
q20438
normalizeTimemarks
train
function normalizeTimemarks(next) { config.timemarks = config.timemarks.map(function(mark) { return utils.timemarkToSeconds(mark); }).sort(function(a, b) { return a - b; }); next(); }
javascript
{ "resource": "" }
q20439
fixPattern
train
function fixPattern(next) { var pattern = config.filename || 'tn.png'; if (pattern.indexOf('.') === -1) { pattern += '.png'; } if (config.timemarks.length > 1 && !pattern.match(/%(s|0*i)/)) { var ext = path.extname(pattern); pattern = path.join(path.dirnam...
javascript
{ "resource": "" }
q20440
train
function(ffprobe, cb) { if (ffprobe.length) { return cb(null, ffprobe); } self._getFfmpegPath(function(err, ffmpeg) { if (err) { cb(err); } else if (ffmpeg.length) { var name = utils.isWindows ? 'ffprobe.exe' : 'ffprobe'; var ffp...
javascript
{ "resource": "" }
q20441
train
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvmeta', function(err, flvmeta) { cb(err, flvmeta); }); }
javascript
{ "resource": "" }
q20442
train
function(flvtool, cb) { if (flvtool.length) { return cb(null, flvtool); } utils.which('flvtool2', function(err, flvtool2) { cb(err, flvtool2); }); }
javascript
{ "resource": "" }
q20443
train
function(formats, cb) { var unavailable; // Output format(s) unavailable = self._outputs .reduce(function(fmts, output) { var format = output.options.find('-f', 1); if (format) { if (!(format[0] in formats) || !(formats[format[0]].canMux)) { ...
javascript
{ "resource": "" }
q20444
train
function(encoders, cb) { var unavailable; // Audio codec(s) unavailable = self._outputs.reduce(function(cdcs, output) { var acodec = output.audio.find('-acodec', 1); if (acodec && acodec[0] !== 'copy') { if (!(acodec[0] in encoders) || encoders[acodec[0]].type !=...
javascript
{ "resource": "" }
q20445
parseProgressLine
train
function parseProgressLine(line) { var progress = {}; // Remove all spaces after = and trim line = line.replace(/=\s+/g, '=').trim(); var progressParts = line.split(' '); // Split every progress part by "=" to get key and value for(var i = 0; i < progressParts.length; i++) { var progressSplit = progr...
javascript
{ "resource": "" }
q20446
train
function() { var list = []; // Append argument(s) to the list var argfunc = function() { if (arguments.length === 1 && Array.isArray(arguments[0])) { list = list.concat(arguments[0]); } else { list = list.concat([].slice.call(arguments)); } }; // Clear argument li...
javascript
{ "resource": "" }
q20447
train
function(filters) { return filters.map(function(filterSpec) { if (typeof filterSpec === 'string') { return filterSpec; } var filterString = ''; // Filter string format is: // [input1][input2]...filter[output1][output2]... // The 'filter' part can optionaly have argument...
javascript
{ "resource": "" }
q20448
train
function(name, callback) { if (name in whichCache) { return callback(null, whichCache[name]); } which(name, function(err, result){ if (err) { // Treat errors as not found return callback(null, whichCache[name] = ''); } callback(null, whichCache[name] = result); }...
javascript
{ "resource": "" }
q20449
train
function(command, stderrLine, codecsObject) { var inputPattern = /Input #[0-9]+, ([^ ]+),/; var durPattern = /Duration\: ([^,]+)/; var audioPattern = /Audio\: (.*)/; var videoPattern = /Video\: (.*)/; if (!('inputStack' in codecsObject)) { codecsObject.inputStack = []; codecsObject.inpu...
javascript
{ "resource": "" }
q20450
train
function(command, stderrLine) { var progress = parseProgressLine(stderrLine); if (progress) { // build progress report object var ret = { frames: parseInt(progress.frame, 10), currentFps: parseInt(progress.fps, 10), currentKbps: progress.bitrate ? parseFloat(progress.bitrate...
javascript
{ "resource": "" }
q20451
createSizeFilters
train
function createSizeFilters(output, key, value) { // Store parameters var data = output.sizeData = output.sizeData || {}; data[key] = value; if (!('size' in data)) { // No size requested, keep original size return []; } // Try to match the different size string formats var fixedSize = data.size.m...
javascript
{ "resource": "" }
q20452
train
function(cb) { if (!readMetadata) { return cb(); } self.ffprobe(0, function(err, data) { if (!err) { self._ffprobeData = data; } cb(); }); }
javascript
{ "resource": "" }
q20453
train
function(cb) { var args; try { args = self._getArguments(); } catch(e) { return cb(e); } cb(null, args); }
javascript
{ "resource": "" }
q20454
train
function(args, cb) { self.availableEncoders(function(err, encoders) { for (var i = 0; i < args.length; i++) { if (args[i] === '-acodec' || args[i] === '-vcodec') { i++; if ((args[i] in encoders) && encoders[args[i]].experimental) { args.splice(i...
javascript
{ "resource": "" }
q20455
serverMonitoringCleanup
train
function serverMonitoringCleanup(db, conn){ var exclude = { eventDate: 0, pid: 0, version: 0, uptime: 0, network: 0, connectionName: 0, connections: 0, memory: 0, dataRetrieved: 0, docCounts: 0 }; var retainedRecords = (24 * 60...
javascript
{ "resource": "" }
q20456
train
function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(...
javascript
{ "resource": "" }
q20457
train
function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (succ...
javascript
{ "resource": "" }
q20458
train
function(model, options) { model = this._prepareModel(model, options); this.add(model, _.extend({at: 0}, options)); return model; }
javascript
{ "resource": "" }
q20459
train
function(model, value, context) { value || (value = this.comparator); var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _.sortedIndex(this.models, model, iterator, context); }
javascript
{ "resource": "" }
q20460
train
function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }
javascript
{ "resource": "" }
q20461
train
function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } }
javascript
{ "resource": "" }
q20462
train
function (param, value) { var len = arguments.length, lastSelectedDate = this.lastSelectedDate; if (len == 2) { this.opts[param] = value; } else if (len == 1 && typeof param == 'object') { this.opts = $.extend(true, this.opts, param) ...
javascript
{ "resource": "" }
q20463
train
function (date, type) { var time = date.getTime(), d = datepicker.getParsedDate(date), min = datepicker.getParsedDate(this.minDate), max = datepicker.getParsedDate(this.maxDate), dMinTime = new Date(d.year, d.month, min.date).getTime(), ...
javascript
{ "resource": "" }
q20464
train
function (date) { var totalMonthDays = dp.getDaysCount(date), firstMonthDay = new Date(date.getFullYear(), date.getMonth(), 1).getDay(), lastMonthDay = new Date(date.getFullYear(), date.getMonth(), totalMonthDays).getDay(), daysFromPevMonth = firstMonthDay - t...
javascript
{ "resource": "" }
q20465
train
function (date) { var html = '', d = dp.getParsedDate(date), i = 0; while(i < 12) { html += this._getMonthHtml(new Date(d.year, i)); i++ } return html; }
javascript
{ "resource": "" }
q20466
train
function (date) { this._setDefaultMinMaxTime(); if (date) { if (dp.isSame(date, this.d.opts.minDate)) { this._setMinTimeFromDate(this.d.opts.minDate); } else if (dp.isSame(date, this.d.opts.maxDate)) { this._setMaxTimeFromDa...
javascript
{ "resource": "" }
q20467
train
function (date, ampm) { var d = date, hours = date; if (date instanceof Date) { d = dp.getParsedDate(date); hours = d.hours; } var _ampm = ampm || this.d.ampm, dayPeriod = 'am'; if (_ampm) { ...
javascript
{ "resource": "" }
q20468
toggleEdit
train
function toggleEdit() { document.body.classList.toggle('form-rendered', editing) if (!editing) { $('.build-wrap').formBuilder('setData', $('.render-wrap').formRender('userData')) } else { const formRenderData = $('.build-wrap').formBuilder('getData', dataType) $('.render-wrap').formRender(...
javascript
{ "resource": "" }
q20469
train
function($field, isNew = false) { let field = {} if ($field instanceof jQuery) { // get the default type etc & label for this field field.type = $field[0].dataset.type if (field.type) { // check for a custom type const custom = controls.custom.lookup(field.type) if (cus...
javascript
{ "resource": "" }
q20470
train
function(formData) { formData = h.getData(formData) if (formData && formData.length) { formData.forEach(fieldData => prepFieldVars(trimObj(fieldData))) d.stage.classList.remove('empty') } else if (opts.defaultFields && opts.defaultFields.length) { // Load default fields if none are set ...
javascript
{ "resource": "" }
q20471
userAttrType
train
function userAttrType(attr, attrData) { return ( [ ['array', ({ options }) => !!options], [typeof attrData.value, () => true], // string, number, ].find(typeCondition => typeCondition[1](attrData))[0] || 'string' ) }
javascript
{ "resource": "" }
q20472
inputUserAttrs
train
function inputUserAttrs(name, inputAttrs) { const { class: classname, className, ...attrs } = inputAttrs let textAttrs = { id: name + '-' + data.lastID, title: attrs.description || attrs.label || name.toUpperCase(), name: name, type: attrs.type || 'text', className: [`fld-${name}`,...
javascript
{ "resource": "" }
q20473
selectUserAttrs
train
function selectUserAttrs(name, fieldData) { const { multiple, options, label: labelText, value, class: classname, className, ...restData } = fieldData const optis = Object.keys(options).map(val => { const attrs = { value: val } const optionTextVal = options[val] const optionText = Array.isArra...
javascript
{ "resource": "" }
q20474
train
function(name, optionData, multipleSelect) { const optionInputType = { selected: multipleSelect ? 'checkbox' : 'radio', } const optionDataOrder = ['value', 'label', 'selected'] const optionInputs = [] const optionTemplate = { selected: false, label: '', value: '' } optionData = Object.ass...
javascript
{ "resource": "" }
q20475
isActuallyCombinator
train
function isActuallyCombinator(combinatorNode) { // `.foo /*comment*/, .bar` // ^^ // If include comments, this spaces is a combinator, but it is not combinators. if (!/^\s+$/.test(combinatorNode.value)) { return true; } let next = combinatorNode.next(); while (skipTest(next)) { next = next...
javascript
{ "resource": "" }
q20476
hasInterpolatingAmpersand
train
function hasInterpolatingAmpersand(selector) { for (let i = 0, l = selector.length; i < l; i++) { if (selector[i] !== "&") { continue; } if (!_.isUndefined(selector[i - 1]) && !isCombinator(selector[i - 1])) { return true; } if (!_.isUndefined(selector[i + 1]) && !isCombinator(select...
javascript
{ "resource": "" }
q20477
verifyMathExpressions
train
function verifyMathExpressions(expression, node) { if (expression.type === "MathExpression") { const { operator, left, right } = expression; if (operator === "+" || operator === "-") { if ( expression.source.operator.end.index === right.source.start.index ...
javascript
{ "resource": "" }
q20478
getCommaCheckIndex
train
function getCommaCheckIndex(commaNode, nodeIndex) { let commaBefore = valueNode.before + argumentStrings.slice(0, nodeIndex).join("") + commaNode.before; // 1. Remove comments including preceeding whitespace (when only succeeded by whitespace) // 2. Remove all othe...
javascript
{ "resource": "" }
q20479
isEofNode
train
function isEofNode(document, root) { if (!document || document.constructor.name !== "Document") { return true; } // In the `postcss-html` and `postcss-jsx` syntax, checks that there is text after the given node. let after; if (root === document.last) { after = _.get(document, "raws.afterEnd"); } e...
javascript
{ "resource": "" }
q20480
augmentConfigBasic
train
function augmentConfigBasic( stylelint /*: stylelint$internalApi*/, config /*: stylelint$config*/, configDir /*: string*/, allowOverrides /*:: ?: boolean*/ ) /*: Promise<stylelint$config>*/ { return Promise.resolve() .then(() => { if (!allowOverrides) return config; return _.merge(config, sty...
javascript
{ "resource": "" }
q20481
augmentConfigExtended
train
function augmentConfigExtended( stylelint /*: stylelint$internalApi*/, cosmiconfigResultArg /*: ?{ config: stylelint$config, filepath: string, }*/ ) /*: Promise<?{ config: stylelint$config, filepath: string }>*/ { const cosmiconfigResult = cosmiconfigResultArg; // Lock in for Flow if (!cosmiconfig...
javascript
{ "resource": "" }
q20482
absolutizeProcessors
train
function absolutizeProcessors( processors /*: stylelint$configProcessors*/, configDir /*: string*/ ) /*: stylelint$configProcessors*/ { const normalizedProcessors = Array.isArray(processors) ? processors : [processors]; return normalizedProcessors.map(item => { if (typeof item === "string") { ...
javascript
{ "resource": "" }
q20483
addEmptyLineAfter
train
function addEmptyLineAfter( node /*: postcss$node*/, newline /*: '\n' | '\r\n'*/ ) /*: postcss$node*/ { const after = _.last(node.raws.after.split(";")); if (!/\r?\n/.test(after)) { node.raws.after = node.raws.after + _.repeat(newline, 2); } else { node.raws.after = node.raws.after.replace(/(\r?\n)/,...
javascript
{ "resource": "" }
q20484
addEmptyLineBefore
train
function addEmptyLineBefore( node /*: postcss$node*/, newline /*: '\n' | '\r\n'*/ ) /*: postcss$node*/ { if (!/\r?\n/.test(node.raws.before)) { node.raws.before = _.repeat(newline, 2) + node.raws.before; } else { node.raws.before = node.raws.before.replace(/(\r?\n)/, `${newline}$1`); } return node;...
javascript
{ "resource": "" }
q20485
train
function(invokeId, errType, resultStr) { if (!invoked) return var diffMs = hrTimeMs(process.hrtime(start)) var billedMs = Math.min(100 * (Math.floor(diffMs / 100) + 1), TIMEOUT * 1000) systemLog('END RequestId: ' + invokeId) systemLog([ 'REPORT RequestId: ' + invokeId, 'Duration: ' + dif...
javascript
{ "resource": "" }
q20486
uuid
train
function uuid() { return crypto.randomBytes(4).toString('hex') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(2).toString('hex').replace(/^./, '1') + '-' + crypto.randomBytes(2).toString('hex') + '-' + crypto.randomBytes(6).toString('hex') }
javascript
{ "resource": "" }
q20487
train
function(roomName, appRoomObj, callback) { // Join room. Creates a default connection room object e.app[appName].connection[easyrtcid].room[roomName] = { apiField: {}, enteredOn: Date.now(), gotListOn: Date.now(), ...
javascript
{ "resource": "" }
q20488
train
function (err) { if (err) { try{ pub.util.sendSocketCallbackMsg(easyrtcid, socketCallback, pub.util.getErrorMsg("LOGIN_GEN_FAIL"), appObj); socket.disconnect(); pub.util.logError("["+easyrtcid+"] General authentication error. Socket disconnected.", err...
javascript
{ "resource": "" }
q20489
iceCandidateFilter
train
function iceCandidateFilter( iceCandidate, fromPeer) { var sdp = iceCandidate.candidate; if( sdp.indexOf("typ relay") > 0) { // is turn candidate if( document.getElementById("allowTurn").checked ) { return iceCandidate; } else { return null; } } else if( sdp...
javascript
{ "resource": "" }
q20490
setThumbSizeAspect
train
function setThumbSizeAspect(percentSize, percentLeft, percentTop, parentw, parenth, aspect) { var width, height; if( parentw < parenth*aspectRatio){ width = parentw * percentSize; height = width/aspect; } else { height = parenth * percentSize; width = height*asp...
javascript
{ "resource": "" }
q20491
establishConnection
train
function establishConnection(position) { function callSuccess() { connectCount++; if( connectCount < maxCALLERS && position > 0) { establishConnection(position-1); } } function callFailure(errorCode, errorText) { easyrtc.sho...
javascript
{ "resource": "" }
q20492
getCommonCapabilities
train
function getCommonCapabilities(localCapabilities, remoteCapabilities) { var commonCapabilities = { codecs: [], headerExtensions: [], fecMechanisms: [] }; var findCodecByPayloadType = function(pt, codecs) { pt = parseInt(pt, 10); for (var i = 0; i < codecs.length; i++) { if (codecs[i].pa...
javascript
{ "resource": "" }
q20493
isActionAllowedInSignalingState
train
function isActionAllowedInSignalingState(action, type, signalingState) { return { offer: { setLocalDescription: ['stable', 'have-local-offer'], setRemoteDescription: ['stable', 'have-remote-offer'] }, answer: { setLocalDescription: ['have-remote-offer', 'have-local-pranswer'], setR...
javascript
{ "resource": "" }
q20494
train
function(window) { var URL = window && window.URL; if (!(typeof window === 'object' && window.HTMLMediaElement && 'srcObject' in window.HTMLMediaElement.prototype && URL.createObjectURL && URL.revokeObjectURL)) { // Only shim CreateObjectURL using srcObject if srcObject exists. re...
javascript
{ "resource": "" }
q20495
train
function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { ...
javascript
{ "resource": "" }
q20496
extractVersion
train
function extractVersion(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }
javascript
{ "resource": "" }
q20497
train
function(window) { var navigator = window && window.navigator; // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; ...
javascript
{ "resource": "" }
q20498
addStreamToPeerConnection
train
function addStreamToPeerConnection(stream, peerConnection) { if( peerConnection.addStream ) { var existingStreams = peerConnection.getLocalStreams(); if (existingStreams.indexOf(stream) === -1) { peerConnection.addStream(stream); } } else { v...
javascript
{ "resource": "" }
q20499
isSocketConnected
train
function isSocketConnected(socket) { return socket && ( (socket.socket && socket.socket.connected) || socket.connected ); }
javascript
{ "resource": "" }