_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q1600
trimTrailingWhitespacesForRemainingRange
train
function trimTrailingWhitespacesForRemainingRange() { var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); }
javascript
{ "resource": "" }
q1601
getCompletionEntryDisplayNameForSymbol
train
function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, location) { var displayName = ts.getDeclaredName(program.getTypeChecker(), symbol, location); if (displayName) { var firstCharCode = displayName.charCodeAt(0); // First check of the displayName is not external module; if it is an external module, it is not valid entry if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); }
javascript
{ "resource": "" }
q1602
getCompletionEntryDisplayName
train
function getCompletionEntryDisplayName(name, target, performCharacterChecks) { if (!name) { return undefined; } name = ts.stripQuotes(name); if (!name) { return undefined; } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. if (performCharacterChecks) { if (!ts.isIdentifier(name, target)) { return undefined; } } return name; }
javascript
{ "resource": "" }
q1603
tryGetObjectLikeCompletionSymbols
train
function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. isMemberCompletion = true; var typeForObject; var existingMembers; if (objectLikeContainer.kind === 171 /* ObjectLiteralExpression */) { // We are completing on contextual types, but may also include properties // other than those within the declared type. isNewIdentifierLocation = true; // If the object literal is being assigned to something of type 'null | { hello: string }', // it clearly isn't trying to satisfy the 'null' type. So we grab the non-nullable type if possible. typeForObject = typeChecker.getContextualType(objectLikeContainer); typeForObject = typeForObject && typeForObject.getNonNullableType(); existingMembers = objectLikeContainer.properties; } else if (objectLikeContainer.kind === 167 /* ObjectBindingPattern */) { // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); if (ts.isVariableLike(rootDeclaration)) { // We don't want to complete using the type acquired by the shape // of the binding pattern; we are only interested in types acquired // through type declaration or inference. // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - // type of parameter will flow in from the contextual type of the function var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); if (!canGetType && rootDeclaration.kind === 142 /* Parameter */) { if (ts.isExpression(rootDeclaration.parent)) { canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } else if (rootDeclaration.parent.kind === 147 /* MethodDeclaration */ || rootDeclaration.parent.kind === 150 /* SetAccessor */) { canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } if (canGetType) { typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); existingMembers = objectLikeContainer.elements; } } else { ts.Debug.fail("Root declaration is not variable-like."); } } else { ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); } if (!typeForObject) { return false; } var typeMembers = typeChecker.getPropertiesOfType(typeForObject); if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); } return true; }
javascript
{ "resource": "" }
q1604
tryGetObjectLikeCompletionContainer
train
function tryGetObjectLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // const x = { | case 24 /* CommaToken */: var parent_19 = contextToken.parent; if (parent_19 && (parent_19.kind === 171 /* ObjectLiteralExpression */ || parent_19.kind === 167 /* ObjectBindingPattern */)) { return parent_19; } break; } } return undefined; }
javascript
{ "resource": "" }
q1605
tryGetNamedImportsOrExportsForCompletion
train
function tryGetNamedImportsOrExportsForCompletion(contextToken) { if (contextToken) { switch (contextToken.kind) { case 15 /* OpenBraceToken */: // import { | case 24 /* CommaToken */: switch (contextToken.parent.kind) { case 233 /* NamedImports */: case 237 /* NamedExports */: return contextToken.parent; } } } return undefined; }
javascript
{ "resource": "" }
q1606
filterNamedImportOrExportCompletionItems
train
function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var existingImportsOrExports = ts.createMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; } var name_41 = element.propertyName || element.name; existingImportsOrExports[name_41.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); } return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports[e.name]; }); }
javascript
{ "resource": "" }
q1607
getBaseDirectoriesFromRootDirs
train
function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory; for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { var rootDirectory = rootDirs_1[_i]; if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { relativeDirectory = scriptPath.substr(rootDirectory.length); break; } } // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); }
javascript
{ "resource": "" }
q1608
getDirectoryFragmentTextSpan
train
function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); var offset = index !== -1 ? index + 1 : 0; return { start: textStart + offset, length: text.length - offset }; }
javascript
{ "resource": "" }
q1609
getSymbolScope
train
function getSymbolScope(symbol) { // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var valueDeclaration = symbol.valueDeclaration; if (valueDeclaration && (valueDeclaration.kind === 179 /* FunctionExpression */ || valueDeclaration.kind === 192 /* ClassExpression */)) { return valueDeclaration; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 8 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 221 /* ClassDeclaration */); } } // If the symbol is an import we would like to find it if we are looking for what it imports. // So consider it visible outside its declaration scope. if (symbol.flags & 8388608 /* Alias */) { return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { return undefined; } var scope; var declarations = symbol.getDeclarations(); if (declarations) { for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { var declaration = declarations_9[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; } if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } if (container.kind === 256 /* SourceFile */ && !ts.isExternalModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; } // The search scope is the container node scope = container; } } return scope; }
javascript
{ "resource": "" }
q1610
tryClassifyNode
train
function tryClassifyNode(node) { if (ts.isJSDocTag(node)) { return true; } if (ts.nodeIsMissing(node)) { return true; } var classifiedElementName = tryClassifyJsxElementName(node); if (!ts.isToken(node) && node.kind !== 244 /* JsxText */ && classifiedElementName === undefined) { return false; } var tokenStart = node.kind === 244 /* JsxText */ ? node.pos : classifyLeadingTriviaAndGetTokenStart(node); var tokenWidth = node.end - tokenStart; ts.Debug.assert(tokenWidth >= 0); if (tokenWidth > 0) { var type = classifiedElementName || classifyTokenType(node.kind, node); if (type) { pushClassification(tokenStart, tokenWidth, type); } } return true; }
javascript
{ "resource": "" }
q1611
canFollow
train
function canFollow(keyword1, keyword2) { if (ts.isAccessibilityModifier(keyword1)) { if (keyword2 === 123 /* GetKeyword */ || keyword2 === 131 /* SetKeyword */ || keyword2 === 121 /* ConstructorKeyword */ || keyword2 === 113 /* StaticKeyword */) { // Allow things like "public get", "public constructor" and "public static". // These are all legal. return true; } // Any other keyword following "public" is actually an identifier an not a real // keyword. return false; } // Assume any other keyword combination is legal. This can be refined in the future // if there are more cases we want the classifier to be better at. return true; }
javascript
{ "resource": "" }
q1612
chainStepsNoError
train
function chainStepsNoError() { var steps = slice.call(arguments).map(function(step) { return notHandlingError(step); }); return chainSteps.apply(null, steps); }
javascript
{ "resource": "" }
q1613
chainAndCall
train
function chainAndCall(chainer) { return function(/*step1, step2, ...*/) { var steps = slice.call(arguments); var callback = steps.pop(); chainer.apply(null, steps)(callback); }; }
javascript
{ "resource": "" }
q1614
route
train
function route (message, cb) { assert(message, 'route requries a valid message') assert(cb && (typeof cb === 'function'), 'route requires a valid callback handler') if (message.pattern) { return pattern(message, cb) } if (message.response) { return response(message, cb) } malformed(message, cb) }
javascript
{ "resource": "" }
q1615
get
train
function get(attr) { var val = dotty.get(attrs, attr); if (val === undefined) { this.emit('undefined', 'WARNING: Undefined environment variable: ' + attr, attr); } return val; }
javascript
{ "resource": "" }
q1616
processZtagOutput
train
function processZtagOutput(output) { return output.split('\n').reduce(function(memo, line) { var match, key, value; match = ztagRegex.exec(line); if(match) { key = match[1]; value = match[2]; memo[key] = value; } return memo; }, {}); }
javascript
{ "resource": "" }
q1617
jsnox
train
function jsnox(React) { var client = function jsnoxClient(componentType, props, children) { // Special $renderIf prop allows you to conditionally render an element: //if (props && typeof props.$renderIf !== 'undefined') { if (props && typeof props === 'object' && props.hasOwnProperty('$renderIf')) { if (props.$renderIf) delete props.$renderIf // Don't pass down to components else return null } // Handle case where an array of children is given as the second argument: if (Array.isArray(props) || typeof props !== 'object') { children = props props = null } // Handle case where props object (second arg) is omitted var arg2IsReactElement = props && React.isValidElement(props) var finalProps = props if (typeof componentType === 'string' || !componentType) { // Parse the provided string into a hash of props // If componentType is invalid (undefined, empty string, etc), // parseTagSpec should throw. var spec = parseTagSpec(componentType) componentType = spec.tagName finalProps = arg2IsReactElement ? spec.props : extend(spec.props, props) } // If more than three args are given, assume args 3..n are ReactElement // children. You can also pass an array of children as the 3rd argument, // but in that case each child should have a unique key to avoid warnings. var args = protoSlice.call(arguments) if (args.length > 3 || arg2IsReactElement) { args[0] = componentType if (arg2IsReactElement) { args.splice(1, 0, finalProps || null) } else { args[1] = finalProps } return React.createElement.apply(React, args) } else { return React.createElement(componentType, finalProps, children) } } client.ParseError = ParseError return client }
javascript
{ "resource": "" }
q1618
train
function(file, lint, isError, isWarning, errorLocation) { var lintId = (isError) ? colors.bgRed(colors.white(lint.id)) : colors.bgYellow(colors.white(lint.id)); var message = ''; if (errorLocation) { message = file.path + ':' + (errorLocation.line + 1) + ':' + (errorLocation.column + 1) + ' ' + lintId + ' ' + lint.message; } else { message = file.path + ': ' + lintId + ' ' + lint.message; } if (isError) { log.error(message); } else { log.warning(message); } }
javascript
{ "resource": "" }
q1619
train
function(file, errorCount, warningCount) { if (errorCount > 0 || warningCount > 0) { var message = ''; if (errorCount > 0) { message += colors.red(errorCount + ' lint ' + (errorCount === 1 ? 'error' : 'errors')); } if (warningCount > 0) { if (errorCount > 0) { message += ' and '; } message += colors.yellow(warningCount + ' lint ' + (warningCount === 1 ? 'warning' : 'warnings')); } message += ' found in file ' + file.path; log.notice(message); } else { log.info(colors.green(file.path + ' is lint free!')); } }
javascript
{ "resource": "" }
q1620
shuffle
train
function shuffle(v) { for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); return v; }
javascript
{ "resource": "" }
q1621
_assign
train
function _assign (target, source) { var s, from, key; var to = Object(target); for (s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (key in from) { if (own(from, key)) { to[key] = from[key]; } } } return to }
javascript
{ "resource": "" }
q1622
splitSelector
train
function splitSelector (sel, splitter, inBracket) { if (sel.indexOf(splitter) < 0) return [sel] for (var c, i = 0, n = 0, instr = '', prev = 0, d = []; c = sel.charAt(i); i++) { if (instr) { if (c == instr && sel.charAt(i-1)!='\\') instr = ''; continue } if (c == '"' || c == '\'') instr = c; /* istanbul ignore if */ if(!inBracket){ if (c == '(' || c == '[') n++; if (c == ')' || c == ']') n--; } if (!n && c == splitter) d.push(sel.substring(prev, i)), prev = i + 1; } return d.concat(sel.substring(prev)) }
javascript
{ "resource": "" }
q1623
isIterable
train
function isIterable (v) { return type.call(v) == OBJECT || type.call(v) == ARRAY }
javascript
{ "resource": "" }
q1624
createDOM
train
function createDOM (rootDoc, id, option) { var el = rootDoc.getElementById(id); var head = rootDoc.getElementsByTagName('head')[0]; if(el) { if(option.append) return el el.parentNode && el.parentNode.removeChild(el); } el = rootDoc.createElement('style'); head.appendChild(el); el.setAttribute('id', id); if (option.attrs) for (var i in option.attrs) { el.setAttribute(i, option.attrs[i]); } return el }
javascript
{ "resource": "" }
q1625
prefixProp
train
function prefixProp (name, inCSS) { // $prop will skip if(name[0]=='$') return '' // find name and cache the name for next time use var retName = cssProps[ name ] || ( cssProps[ name ] = vendorPropName( name ) || name); return inCSS // if hasPrefix in prop ? dashify(cssPrefixesReg.test(retName) ? capitalize(retName) : name=='float' && name || retName) // fix float in CSS, avoid return cssFloat : retName }
javascript
{ "resource": "" }
q1626
setCSSProperty
train
function setCSSProperty (styleObj, prop, val) { var value; var important = /^(.*)!(important)\s*$/i.exec(val); var propCamel = prefixProp(prop); var propDash = prefixProp(prop, true); if(important) { value = important[1]; important = important[2]; if(styleObj.setProperty) styleObj.setProperty(propDash, value, important); else { // for old IE, cssText is writable, and below is valid for contain !important // don't use styleObj.setAttribute since it's not set important // should do: delete styleObj[propCamel], but not affect result // only work on <= IE8: s.style['FONT-SIZE'] = '12px!important' styleObj[propDash.toUpperCase()] = val; // refresh cssText, the whole rule! styleObj.cssText = styleObj.cssText; } } else { styleObj[propCamel] = val; } }
javascript
{ "resource": "" }
q1627
train
function (node, selText, cssText) { if(!cssText) return // get parent to add var parent = getParent(node); var parentRule = node.parentRule; if (validParent(node)) return node.omRule = addCSSRule(parent, selText, cssText, node) else if (parentRule) { // for old IE not support @media, check mediaEnabled, add child nodes if (parentRule.mediaEnabled) { [].concat(node.omRule).forEach(removeOneRule); return node.omRule = addCSSRule(parent, selText, cssText, node) } else if (node.omRule) { node.omRule.forEach(removeOneRule); delete node.omRule; } } }
javascript
{ "resource": "" }
q1628
cssobj$1
train
function cssobj$1 (obj, config, state) { config = config || {}; var local = config.local; config.local = !local ? {space: ''} : local && typeof local === 'object' ? local : {}; config.plugins = [].concat( config.plugins || [], cssobj_plugin_selector_localize(config.local), cssobj_plugin_post_cssom(config.cssom) ); return cssobj(config)(obj, state) }
javascript
{ "resource": "" }
q1629
wrap
train
function wrap(fn, before, after, advisor) { var ignoredKeys = { prototype: 1 }; function wrapper() { var _before = wrapper[BEFORE], bLen = _before.length, _after = wrapper[AFTER], aLen = _after.length, _fn = wrapper[ORIGIN], ret, r; // Invoke before, if it returns { $skip: true } then skip fn() and after() and returns $data while (bLen--) { r = _before[bLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return r.$data; } } // Invoke fn, save return value ret = _fn.apply(this, arguments); while (aLen--) { r = _after[aLen].apply(this, arguments); if (mapOrNil(r) && r.$skip === true) { return ret; } } return ret; } // wrapper exists? reuse it if (fn[WRAPPER] === fn) { fn[BEFORE].push(before); fn[AFTER].push(after); fn[ADVISOR].push(advisor); return fn; } // create a reusable wrapper structure extend(wrapper, fn, 0, true); if (classOrNil(fn)) { wrapper.prototype = fn.prototype; // this destroys the origin of wrapper[ORIGIN], in theory, prototype.constructor should point // to the class constructor itself, but it's no harm to not let that happen // wrapper.prototype.constructor = wrapper; } wrapper[BEFORE] = [ before ]; wrapper[AFTER] = [ after ]; wrapper[ORIGIN] = fn; wrapper[ADVISOR] = [ advisor ]; wrapper[WRAPPER] = wrapper; wrapper.$super = fn.$super; wrapper.$superp = fn.$superp; return wrapper; }
javascript
{ "resource": "" }
q1630
restore
train
function restore(fn, advisor) { var origin, index, len; if (fn && fn === fn[WRAPPER]) { if ( !advisor) { origin = fn[ORIGIN]; delete fn[ORIGIN]; delete fn[ADVISOR]; delete fn[BEFORE]; delete fn[AFTER]; delete fn[WRAPPER]; } else { index = len = fn[ADVISOR].length; while (index--) { if (fn[ADVISOR][index] === advisor) { break; } } if (index >= 0) { if (len === 1) { return restore(fn); } fn[ADVISOR].splice(index, 1); fn[BEFORE].splice(index, 1); fn[AFTER].splice(index, 1); } } } return origin; }
javascript
{ "resource": "" }
q1631
deepFreeze
train
function deepFreeze(object) { var prop, propKey; Object.freeze(object); // first freeze the object for (propKey in object) { prop = object[propKey]; if (!object.hasOwnProperty(propKey) || (typeof prop !== 'object') || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // recursively call deepFreeze } }
javascript
{ "resource": "" }
q1632
getAuth
train
function getAuth (auth, url) { if (auth && auth.user && auth.pass) { return auth.user + ':' + auth.pass } return url.auth }
javascript
{ "resource": "" }
q1633
getPath
train
function getPath (path, name, profiles, label) { const profilesStr = buildProfilesString(profiles) return (path.endsWith('/') ? path : path + '/') + encodeURIComponent(name) + '/' + encodeURIComponent(profilesStr) + (label ? '/' + encodeURIComponent(label) : '') }
javascript
{ "resource": "" }
q1634
loadWithCallback
train
function loadWithCallback (options, callback) { const endpoint = options.endpoint ? URL.parse(options.endpoint) : DEFAULT_URL const name = options.name || options.application const context = options.context const client = endpoint.protocol === 'https:' ? https : http client.request({ protocol: endpoint.protocol, hostname: endpoint.hostname, port: endpoint.port, path: getPath(endpoint.path, name, options.profiles, options.label), auth: getAuth(options.auth, endpoint), rejectUnauthorized: options.rejectUnauthorized !== false, agent: options.agent }, (res) => { if (res.statusCode !== 200) { // OK res.resume() // it consumes response return callback(new Error('Invalid response: ' + res.statusCode)) } let response = '' res.setEncoding('utf8') res.on('data', (data) => { response += data }) res.on('end', () => { try { const body = JSON.parse(response) callback(null, new Config(body, context)) } catch (e) { callback(e) } }) }).on('error', callback).end() }
javascript
{ "resource": "" }
q1635
loadWithPromise
train
function loadWithPromise (options) { return new Promise((resolve, reject) => { loadWithCallback(options, (error, config) => { if (error) { reject(error) } else { resolve(config) } }) }) }
javascript
{ "resource": "" }
q1636
_MinHeap
train
function _MinHeap(elements) { var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultComparator; _classCallCheck(this, _MinHeap); __assertArray(elements); __assertFunction(comparator); // we do not wrap elements here since the heapify function does that the moment it encounters elements this.__elements = elements; // create comparator that works on heap elements (it also ensures equal elements remain in original order) this.__comparator = function (a, b) { var res = comparator(a.__value, b.__value); if (res !== 0) { return res; } return defaultComparator(a.__index, b.__index); }; // create heap ordering this.__createHeap(this.__elements, this.__comparator); }
javascript
{ "resource": "" }
q1637
assert
train
function assert(value, schema, message, vars) { return assertion(value, schema, message, vars, (internals.debug ? null : assert)); }
javascript
{ "resource": "" }
q1638
tolerancesToString
train
function tolerancesToString(values, tolerances) { let str = '{'; const props = []; if (typeof values !== 'object' && typeof values !== 'undefined') { if (typeof tolerances === 'undefined') { return values; } else if (typeof tolerances !== 'object') { const tolerance = Math.abs(tolerances); return `[${Math.max(values - tolerance, 0)}, ${Math.max(values + tolerance, 0)}]`; } } else { for (const p in values) { if (values.hasOwnProperty(p)) { const value = values[p]; let valueStr = ''; if (tolerances && typeof tolerances[p] !== 'undefined' && tolerances[p] !== 0) { const tolerance = Math.abs(tolerances[p]); valueStr = `[${Math.max(value - tolerance, 0)}, ${Math.max(value + tolerance, 0)}]`; } else { valueStr = `${value}`; } props.push(`${p}: ${valueStr}`); } } } str += props.join(', '); return `${str}}`; }
javascript
{ "resource": "" }
q1639
isKeyComparator
train
function isKeyComparator(arg) { let result = __getParameterCount(arg) === 2; const first = self.first(); try { const key = keySelector(first); // if this is a key comparator, it must return truthy values for equal values and falsy ones if they're different result = result && arg(key, key) && !arg(key, {}); } catch (err) { // if the function throws an error for values, it can't be a keyComparator result = false; } return result; }
javascript
{ "resource": "" }
q1640
processThunkArgs
train
function processThunkArgs( args ) { let length = args.length | 0; if( length >= 3 ) { let res = new Array( --length ); for( let i = 0; i < length; ) { res[i] = args[++i]; //It's a good thing this isn't undefined behavior in JavaScript } return res; } return args[1]; }
javascript
{ "resource": "" }
q1641
ccw
train
function ccw(c) { var n = c.length var area = [0] for(var j=0; j<n; ++j) { var a = positions[c[j]] var b = positions[c[(j+1)%n]] var t00 = twoProduct(-a[0], a[1]) var t01 = twoProduct(-a[0], b[1]) var t10 = twoProduct( b[0], a[1]) var t11 = twoProduct( b[0], b[1]) area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11))) } return area[area.length-1] > 0 }
javascript
{ "resource": "" }
q1642
syncToTmp
train
function syncToTmp(tmpfd, msgnumber, cb) { // Pass the last msg if (msgnumber > messages.offsets.length) cb(); // Skip deleted messages else if (messages.offsets[msgnumber] === undefined) syncToTmp(tmpfd, msgnumber + 1, cb); else { var buffer = new Buffer(omessages.sizes[msgnumber]); fs.read(fd, buffer, 0, omessages.sizes[msgnumber], messages.offsets[msgnumber], function(err, bytesRead, buffer) { fs.write(tmpfd, buffer, 0, bytesRead, null, function(err, written, buffer) { syncToTmp(tmpfd, msgnumber + 1, cb); }); }); } }
javascript
{ "resource": "" }
q1643
isIElementNode
train
function isIElementNode(node) { return typeof node['getText'] === 'function' && typeof node.currently['hasText'] === 'function' && typeof node.currently['hasAnyText'] === 'function' && typeof node.currently['containsText'] === 'function' && typeof node.wait['hasText'] === 'function' && typeof node.wait['hasAnyText'] === 'function' && typeof node.wait['containsText'] === 'function' && typeof node.eventually['hasText'] === 'function' && typeof node.eventually['hasAnyText'] === 'function' && typeof node.eventually['containsText'] === 'function' && typeof node['getDirectText'] === 'function' && typeof node.currently['hasDirectText'] === 'function' && typeof node.currently['hasAnyDirectText'] === 'function' && typeof node.currently['containsDirectText'] === 'function' && typeof node.wait['hasDirectText'] === 'function' && typeof node.wait['hasAnyDirectText'] === 'function' && typeof node.wait['containsDirectText'] === 'function' && typeof node.eventually['hasDirectText'] === 'function' && typeof node.eventually['hasAnyDirectText'] === 'function' && typeof node.eventually['containsDirectText'] === 'function'; }
javascript
{ "resource": "" }
q1644
updateFormatting
train
function updateFormatting(outNode, profile) { const node = outNode.node; if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
{ "resource": "" }
q1645
train
function (commandName, args, result, error) { if (error) { if ( error.type ) { errorType = error.type } else if ( error.toString().indexOf("Error: An element could not be located on the page using the given search parameters") > -1 ) { errorType = true } try { const screenshot = browser.saveScreenshot() // returns base64 string buffer const screenshotFolder = path.join(process.env.WDIO_WORKFLO_RUN_PATH, 'allure-results') const screenshotFilename = `${screenshotFolder}/${global.screenshotId}.png` global.errorScreenshotFilename = screenshotFilename fs.writeFileSync(screenshotFilename, screenshot) } catch (err) { console.log(`Failed to take screenshot: ${err.message}`) console.log(err.stack) } } if (typeof workfloConf.afterCommand === 'function') { return workfloConf.afterCommand(commandName, args, result, error) } }
javascript
{ "resource": "" }
q1646
extend
train
function extend(a, b){ var p, type; for(p in b) { type = typeof b[p]; if(type !== "object" && type !== "function") { a[p] = b[p]; } } return a; }
javascript
{ "resource": "" }
q1647
completeSpecFiles
train
function completeSpecFiles(argv, _filters) { // if user manually defined an empty specFiles array, do not add specFiles from folder if (Object.keys(_filters.specFiles).length === 0 && !argv.specFiles) { io_1.getAllFiles(specsDir, '.spec.ts').forEach(specFile => _filters.specFiles[specFile] = true); return true; } else { let removeOnly = true; const removeSpecFiles = {}; for (const specFile in _filters.specFiles) { let remove = false; let matchStr = specFile; if (specFile.substr(0, 1) === '-') { remove = true; matchStr = specFile.substr(1, specFile.length - 1); } else { removeOnly = false; } if (remove) { delete _filters.specFiles[specFile]; removeSpecFiles[matchStr] = true; } } if (removeOnly) { io_1.getAllFiles(specsDir, '.spec.ts') .filter(specFile => !(specFile in removeSpecFiles)) .forEach(specFile => _filters.specFiles[specFile] = true); } } return false; }
javascript
{ "resource": "" }
q1648
mergeLists
train
function mergeLists(list, _filters) { if (list.specFiles) { list.specFiles.forEach(value => _filters.specFiles[value] = true); } if (list.testcaseFiles) { list.testcaseFiles.forEach(value => _filters.testcaseFiles[value] = true); } if (list.features) { list.features.forEach(value => _filters.features[value] = true); } if (list.specs) { list.specs.forEach(value => _filters.specs[value] = true); } if (list.testcases) { list.testcases.forEach(value => _filters.testcases[value] = true); } if (list.listFiles) { for (const listFile of list.listFiles) { // complete cli listFiles paths const listFilePath = path.join(listsDir, `${listFile}.list.ts`); if (!fs.existsSync(listFilePath)) { throw new Error(`List file could not be found: ${listFilePath}`); } else { const sublist = require(listFilePath).default; // recursively traverse sub list files mergeLists(sublist, _filters); } } } }
javascript
{ "resource": "" }
q1649
addFeatures
train
function addFeatures() { const features = {}; for (const spec in filters.specs) { features[parseResults.specs.specTable[spec].feature] = true; } filters.features = features; }
javascript
{ "resource": "" }
q1650
addSpecFiles
train
function addSpecFiles() { const specFiles = {}; for (const spec in filters.specs) { specFiles[parseResults.specs.specTable[spec].specFile] = true; } filters.specFiles = specFiles; }
javascript
{ "resource": "" }
q1651
cleanResultsStatus
train
function cleanResultsStatus() { // remove criterias and spec if no criteria in spec for (const spec in mergedResults.specs) { if (!(spec in parseResults.specs.specTable) || Object.keys(parseResults.specs.specTable[spec].criteria).length === 0) { delete mergedResults.specs[spec]; } else { const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in resultsCriteria) { if (!(criteria in parsedCriteria)) { delete mergedResults.specs[spec][criteria]; } } } } for (const testcase in mergedResults.testcases) { if (!(testcase in parseResults.testcases.testcaseTable)) { delete mergedResults.testcases[testcase]; } } // add criteria for (const spec in parseResults.specs.specTable) { if (!(spec in mergedResults.specs)) { mergedResults.specs[spec] = {}; } const parsedCriteria = parseResults.specs.specTable[spec].criteria; const resultsCriteria = mergedResults.specs[spec]; for (const criteria in parsedCriteria) { if (!(criteria in resultsCriteria)) { mergedResults.specs[spec][criteria] = { dateTime, status: 'unknown', resultsFolder: undefined, }; if (criteria in criteriaAnalysis.specs[spec].manual) { mergedResults.specs[spec][criteria].manual = true; } } } } for (const testcase in parseResults.testcases.testcaseTable) { if (!(testcase in mergedResults.testcases)) { mergedResults.testcases[testcase] = { dateTime, status: 'unknown', resultsFolder: undefined, }; } } fs.writeFileSync(mergedResultsPath, JSON.stringify(mergedResults), { encoding: 'utf8' }); }
javascript
{ "resource": "" }
q1652
splitToObj
train
function splitToObj(str, delim) { if (!(_.isString(str))) { throw new Error(`Input must be a string: ${str}`); } else { return util_1.convertToObject(str.split(delim), () => true); } }
javascript
{ "resource": "" }
q1653
assertion
train
function assertion(value, schema, message, vars, ssf) { return Joi.validate(value, schema, function(err, value) { // fast way if (!err) { return value; } // assemble message var msg = ''; // process message (if any) var mtype = typeof message; if (mtype === 'string') { if (vars && typeof vars === 'object') { // mini template message = message.replace(/\{([\w]+)\}/gi, function (match, key) { if (hasOwnProp.call(vars, key)) { return vars[key]; } }); } msg += message + ': '; } // append schema label msg += getLabel(schema.describe(), err); // append some of the errors var maxDetails = 4; msg += err.details.slice(0, maxDetails).map(function(det) { if (/^\w+\.\w/.test(det.path)) { return '[' + det.path + '] ' + det.message; } return det.message; }).join(', '); if (err.details.length > maxDetails) { var hidden = (err.details.length - maxDetails); msg += '... (showing ' + (err.details.length - hidden) + ' of ' + err.details.length + ')'; } // booya throw new AssertionError(msg, { details: err.details, value: value }, ssf); }); }
javascript
{ "resource": "" }
q1654
setFormatting
train
function setFormatting(outNode, profile) { const node = outNode.node; if (shouldFormatNode(node, profile)) { outNode.indent = profile.indent(getIndentLevel(node, profile)); outNode.newline = '\n'; const prefix = outNode.newline + outNode.indent; // do not format the very first node in output if (!isRoot(node.parent) || !isFirstChild(node)) { outNode.beforeOpen = prefix; if (node.isTextOnly) { outNode.beforeText = prefix; } } if (hasInnerFormatting(node, profile)) { if (!node.isTextOnly) { outNode.beforeText = prefix + profile.indent(1); } outNode.beforeClose = prefix; } } return outNode; }
javascript
{ "resource": "" }
q1655
shouldFormatNode
train
function shouldFormatNode(node, profile) { if (!profile.get('format')) { return false; } if (node.parent.isTextOnly && node.parent.children.length === 1 && parseFields(node.parent.value).fields.length) { // Edge case: do not format the only child of text-only node, // but only if parent contains fields return false; } return isInline(node, profile) ? shouldFormatInline(node, profile) : true; }
javascript
{ "resource": "" }
q1656
formatAttributes
train
function formatAttributes(outNode, profile) { const node = outNode.node; return node.attributes.map(attr => { if (attr.options.implied && attr.value == null) { return null; } const attrName = profile.attribute(attr.name); let attrValue = null; // handle boolean attributes if (attr.options.boolean || profile.get('booleanAttributes').indexOf(attrName.toLowerCase()) !== -1) { if (profile.get('compactBooleanAttributes') && attr.value == null) { return ` ${attrName}`; } else if (attr.value == null) { attrValue = attrName; } } if (attrValue == null) { attrValue = outNode.renderFields(attr.value); } return attr.options.before && attr.options.after ? ` ${attrName}=${attr.options.before+attrValue+attr.options.after}` : ` ${attrName}=${profile.quote(attrValue)}`; }).join(''); }
javascript
{ "resource": "" }
q1657
getIndentLevel
train
function getIndentLevel(node, profile) { // Increase indent level IF NOT: // * parent is text-only node // * there’s a parent node with a name that is explicitly set to decrease level const skip = profile.get('formatSkip') || []; let level = node.parent.isTextOnly ? -2 : -1; let ctx = node; while (ctx = ctx.parent) { if (skip.indexOf( (ctx.name || '').toLowerCase() ) === -1) { level++; } } return level < 0 ? 0 : level; }
javascript
{ "resource": "" }
q1658
commentNode
train
function commentNode(outNode, options) { const node = outNode.node; if (!options.enabled || !options.trigger || !node.name) { return; } const attrs = outNode.node.attributes.reduce((out, attr) => { if (attr.name && attr.value != null) { out[attr.name.toUpperCase().replace(/-/g, '_')] = attr.value; } return out; }, {}); // add comment only if attribute trigger is present for (let i = 0, il = options.trigger.length; i < il; i++) { if (options.trigger[i].toUpperCase() in attrs) { outNode.open = template(options.before, attrs) + outNode.open; if (outNode.close) { outNode.close += template(options.after, attrs); } break; } } }
javascript
{ "resource": "" }
q1659
isIValueElementNode
train
function isIValueElementNode(node) { return typeof node['getValue'] === 'function' && typeof node['setValue'] === 'function' && typeof node.currently['getValue'] === 'function' && typeof node.currently['hasValue'] === 'function' && typeof node.currently['hasAnyValue'] === 'function' && typeof node.currently['containsValue'] === 'function' && typeof node.wait['hasValue'] === 'function' && typeof node.wait['hasAnyValue'] === 'function' && typeof node.wait['containsValue'] === 'function' && typeof node.eventually['hasValue'] === 'function' && typeof node.eventually['hasAnyValue'] === 'function' && typeof node.eventually['containsValue'] === 'function'; }
javascript
{ "resource": "" }
q1660
prettifyDiffObj
train
function prettifyDiffObj(diff) { const obj = { kind: undefined, path: undefined, expect: undefined, actual: undefined, index: undefined, item: undefined, }; if (diff.kind) { switch (diff.kind) { case 'N': obj.kind = 'New'; break; case 'D': obj.kind = 'Missing'; break; case 'E': obj.kind = 'Changed'; break; case 'A': obj.kind = 'Array Canged'; break; } } if (diff.path) { let path = diff.path[0]; for (let i = 1; i < diff.path.length; i++) { path += `/${diff.path[i]}`; } obj.path = path; } if (typeof diff.lhs !== 'undefined') { obj.expect = diff.lhs; } if (typeof diff.rhs !== 'undefined') { obj.actual = diff.rhs; } if (diff.index) { obj.index = diff.index; } if (diff.item) { obj.item = prettifyDiffObj(diff.item); } return obj; }
javascript
{ "resource": "" }
q1661
prettifyDiffOutput
train
function prettifyDiffOutput(diffArr) { const res = []; for (const diff of diffArr) { res.push(prettifyDiffObj(diff)); } return res; }
javascript
{ "resource": "" }
q1662
cleanup
train
function cleanup() { if(chan.timer) clearTimeout(chan.timer); chan.timer = setTimeout(function(){ chan.state = "gone"; // in case an app has a reference x.channels[chan.id] = {state:"gone"}; // remove our reference for gc }, chan.timeout); }
javascript
{ "resource": "" }
q1663
proxifySteps
train
function proxifySteps(stepDefinitions) { return new Proxy(stepDefinitions, { get: (target, name, receiver) => stepsGetter(target, name, receiver), set: (target, name, value) => stepsSetter(target, name, value), }); }
javascript
{ "resource": "" }
q1664
mapToObject
train
function mapToObject(input, mapFunc) { const obj = {}; for (const element of input) { obj[element] = mapFunc(element); } return obj; }
javascript
{ "resource": "" }
q1665
train
function(args, callback) { if (!config.i18n.spreadsheet_id) { return callback('Missing config.i18n.spreadsheet_id'); } const path = 'https://spreadsheets.google.com/feeds/list/' + config.i18n.spreadsheet_id + '/default/public/values?alt=json'; // request json data request(path, (err, res, body) => { if (err) { return callback(err); } const json = JSON.parse(body); //console.dir(json); const translations = {}; // parse json.feed.entry.forEach(entry => { // const key = _.get(entry, 'gsx$key.$t'); config.i18n.whitelist.forEach((lang) => { const value = _.get(entry, 'gsx$' + lang + '.$t'); if (value) { _.setWith(translations, lang + '.' + key, value, Object); } }); }); // write translation files config.i18n.whitelist.forEach((lang) => { const dir = `./locales/${lang}`; if (!fs.existsSync(dir)) { console.warn('Missing directory: ' + dir); return; } translations[lang]._meta = { generated_at: new Date(), lang }; const data = JSON.stringify(translations[lang], null, 2); const filename = `${dir}/translation.json`; console.log('Writing ' + filename); fs.writeFileSync(filename, data ); }); callback(); }); }
javascript
{ "resource": "" }
q1666
convertDiffToMessages
train
function convertDiffToMessages(diff, actualOnly = false, includeTimeouts = false, timeout = undefined, comparisonLines = [], paths = []) { if (diff.tree && Object.keys(diff.tree).length > 0) { const keys = Object.keys(diff.tree); keys.forEach(key => { const _paths = [...paths]; _paths.push(key); convertDiffToMessages(diff.tree[key], actualOnly, includeTimeouts, timeout, comparisonLines, _paths); }); } else { let _paths = paths.join(''); if (_paths.charAt(0) === '.') { _paths = _paths.substring(1); } const _actual = printValue(diff.actual); const _expected = printValue(diff.expected); let compareStr = ''; if (actualOnly) { compareStr = (typeof diff.actual === 'undefined') ? '' : `{actual: <${_actual}>}\n`; } else { compareStr = (typeof diff.actual === 'undefined' && typeof diff.expected === 'undefined') ? '' : `{actual: <${_actual}>, expected: <${_expected}>}\n`; } const timeoutStr = (includeTimeouts) ? ` within ${timeout || diff.timeout}ms` : ''; comparisonLines.push(`${diff.constructorName} at path '${_paths}'${timeoutStr}\n${compareStr}( ${diff.selector} )`); } return comparisonLines; }
javascript
{ "resource": "" }
q1667
convertToObject
train
function convertToObject(unknownTypedInput, valueFunc = undefined) { let obj = {}; if (typeof unknownTypedInput !== 'undefined') { if (typeof unknownTypedInput === 'string') { unknownTypedInput = [unknownTypedInput]; } if (_.isArray(unknownTypedInput)) { for (const element of unknownTypedInput) { let value; if (typeof valueFunc !== 'undefined') { value = valueFunc(element); } else { value = undefined; } obj[element] = value; } } else { obj = _.cloneDeep(unknownTypedInput); } } return obj; }
javascript
{ "resource": "" }
q1668
compare
train
function compare(var1, var2, operator) { switch (operator) { case Workflo.Comparator.equalTo || Workflo.Comparator.eq: return var1 === var2; case Workflo.Comparator.notEqualTo || Workflo.Comparator.ne: return var1 !== var2; case Workflo.Comparator.greaterThan || Workflo.Comparator.gt: return var1 > var2; case Workflo.Comparator.lessThan || Workflo.Comparator.lt: return var1 < var2; } }
javascript
{ "resource": "" }
q1669
Types
train
function Types() { this.binary = specs.ABinary; this.string = specs.AString; this.bool = specs.ABoolean; this.byte = specs.AByte; this.i16 = specs.AInt16; this.i32 = specs.AInt32; this.i64 = specs.AInt64; this.double = specs.ADouble; }
javascript
{ "resource": "" }
q1670
get
train
function get(values, index, initiatedOnce, rtn) { /** * add the named mixin and all un-added dependencies to the return array * @param the mixin name */ function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } } // if the mixin has a "mixins" attribute, clone and add those dependencies first function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } } function handleMixin(mixin) { if (mixin) { if (Array.isArray(mixin)) { // flatten it out get(mixin, index, initiatedOnce, rtn); } else if (typeof mixin === 'string') { // add the named mixin and all of it's dependencies addTo(mixin); } else { checkForInlineMixins(mixin, rtn); // just add the mixin normally rtn.push(mixin); } } } if (Array.isArray(values)) { for (var i = 0; i < values.length; i++) { handleMixin(values[i]); } } else { handleMixin(values); } }
javascript
{ "resource": "" }
q1671
addTo
train
function addTo(name) { var indexName = name, match = name.match(/^([^\(]*)\s*\(([^\)]*)\)\s*/), params = match && match[2]; name = match && match[1] || name; if (!index[indexName]) { if (params) { // there can be no function calls here because of the regex match /*jshint evil: true */ params = eval('[' + params + ']'); } var mixin = _mixins[name], checkAgain = false, skip = false; if (mixin) { if (typeof mixin === 'function') { if (_initiatedOnce[name]) { if (!initiatedOnce[name]) { initiatedOnce[name] = []; // add the placeholder so the mixin ends up in the right place // we will replace all names with the appropriate mixins at the end // (so we have all of the appropriate arguments) mixin = name; } else { // but we only want to add it a single time skip = true; } if (params) { initiatedOnce[name].push(params); } } else { mixin = mixin.apply(this, params || []); checkAgain = true; } } else if (params) { throw new Error('the mixin "' + name + '" does not support parameters'); } get(_dependsOn[name], index, initiatedOnce, rtn); get(_dependsInjected[name], index, initiatedOnce, rtn); index[indexName] = true; if (checkAgain) { get([mixin], index, initiatedOnce, rtn); } else if (!skip) { checkForInlineMixins(mixin, rtn); rtn.push(mixin); } } else { throw new Error('invalid mixin "' + name + '"'); } } }
javascript
{ "resource": "" }
q1672
checkForInlineMixins
train
function checkForInlineMixins(mixin, rtn) { if (mixin.mixins) { get(mixin.mixins, index, initiatedOnce, rtn); } }
javascript
{ "resource": "" }
q1673
applyInitiatedOnceArgs
train
function applyInitiatedOnceArgs(mixins, rtn) { /** * added once initiated mixins to return array */ function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); } for (var m in mixins) { if (mixins.hasOwnProperty(m)) { addInitiatedOnce(m, _mixins[m], mixins[m]); } } }
javascript
{ "resource": "" }
q1674
addInitiatedOnce
train
function addInitiatedOnce(name, mixin, params) { mixin = mixin.call(this, params || []); // find the name placeholder in the return arr and replace it with the mixin var index = rtn.indexOf(name); rtn.splice(index, 1, mixin); }
javascript
{ "resource": "" }
q1675
train
function(name) { var l = _dependsInjected[name]; if (!l) { l = _dependsInjected[name] = []; } l.push(Array.prototype.slice.call(arguments, 1)); }
javascript
{ "resource": "" }
q1676
train
function(err, req, res) { console.log('handle error:'); console.dir(err); // uri error if (err instanceof URIError) { return res.status(404).render('errors/404'); } logger.error(req.method + ' ' + getURL(req) + ' : ' + err); logger.error(err.stack); if (!res._headerSent) { // show error if (config.showerrstack) { // const stacktrace = [ '<h1>', req.originalUrl, '</h1>', '<pre>', err.stack, '</pre>' ].join(''); res.status(500).send(stacktrace); } else { res.status(500).render('errors/500'); } } if (config.mailcrashto) { mailer.send('crash', { to: config.mailcrashto, subject: [ config.appname, 'Crash:', err ].join(' '), body: formatMessage(req, err) }) } }
javascript
{ "resource": "" }
q1677
mapProperties
train
function mapProperties(obj, func) { if (_.isArray(obj)) { throw new Error(`Input must be an object: ${obj}`); } else { const resultObj = Object.create(Object.prototype); for (const key in obj) { if (obj.hasOwnProperty(key)) { resultObj[key] = func(obj[key], key); } } return resultObj; } }
javascript
{ "resource": "" }
q1678
iteratorFactory
train
function iteratorFactory(callback) { return iterator function iterator(parent) { var children = parent && parent.children if (!children) { throw new Error('Missing children in `parent` for `modifier`') } return iterate(children, callback, parent) } }
javascript
{ "resource": "" }
q1679
setIfPresent
train
function setIfPresent(docEl, nodeName){ var node = getBaseElement(docEl, nodeName); if(node) { document[nodeName] = node; } }
javascript
{ "resource": "" }
q1680
updateFormatting
train
function updateFormatting(outNode, profile) { const node = outNode.node; const parent = node.parent; // Edge case: a single inline-level child inside node without text: // allow it to be inlined if (profile.get('inlineBreak') === 0 && isInline(node, profile) && !isRoot(parent) && parent.value == null && parent.children.length === 1) { outNode.beforeOpen = ': '; } if (!node.isTextOnly && node.value) { // node with text: put a space before single-line text outNode.beforeText = reNl.test(node.value) ? outNode.newline + outNode.indent + profile.indent(1) : ' '; } return outNode; }
javascript
{ "resource": "" }
q1681
next
train
function next( ret ) { if( ret.done ) { return resolve( ret.value ); } var value = toPromise.call( ctx, ret.value ); if( value && isPromise( value ) ) { return value.then( onFulfilled, onRejected ); } return onRejected( new TypeError( 'You may only yield a function, promise, generator, array, or object, ' + 'but the following object was passed: "' + String( ret.value ) + '"' ) ); }
javascript
{ "resource": "" }
q1682
toPromise
train
function toPromise( obj ) { if( !obj ) { return obj; } if( isPromise( obj ) ) { return obj; } if( isGeneratorFunction( obj ) || isGenerator( obj ) ) { return co.call( this, obj ); } if( 'function' == typeof obj ) { return thunkToPromise.call( this, obj ); } if( Array.isArray( obj ) ) { return arrayToPromise.call( this, obj ); } if( isObject( obj ) ) { return objectToPromise.call( this, obj ); } return obj; }
javascript
{ "resource": "" }
q1683
getEaseType
train
function getEaseType(type){ switch(type) { case KeyframeInterpolationType.BEZIER: return EASE_TYPE.BEZIER; break; case KeyframeInterpolationType.LINEAR: return EASE_TYPE.LINEAR; break; case KeyframeInterpolationType.HOLD: return EASE_TYPE.HOLD; break; default: throw new Error('unknown ease type'); break; } }
javascript
{ "resource": "" }
q1684
getTypeOf
train
function getTypeOf(item) { var type = null; if(item) { var strValue = item.toString(); var isObject = /\[object/.test(strValue); var isFunction = /function/.test(strValue); var isArray = Array.isArray(item); if(isArray) { type = Array; } else if(isFunction) { type = Function; } else if(isObject) { type = Object; } else { type = null; } } else { type = null; } return type; }
javascript
{ "resource": "" }
q1685
extractSchemaLabel
train
function extractSchemaLabel(schema, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label = ''; if (schema.id) { label = style.accent(schema.id); } if (schema.title) { label += style.accent(label ? ' (' + schema.title + ')' : style.accent(schema.title)); } if (!label) { if (schema.description) { label = style.accent('<no id>') + ' ' + valueStrim(schema.description, limit); } else { label = style.accent('<no id>') + ' ' + valueStrim(schema, limit); } } return label; }
javascript
{ "resource": "" }
q1686
extractCTXLabel
train
function extractCTXLabel(test, limit) { limit = typeof limit === 'undefined' ? strimLimit : limit; var label; if (test.label) { label = style.accent(test.label); } if (!label) { label = style.accent('<no label>') + ' ' + valueStrim(test.value, limit); } return label; }
javascript
{ "resource": "" }
q1687
init
train
function init() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; dayStartsAt = options.dayStartsAt || DEFAULT_DAY_STARTS_AT; nightStartsAt = options.nightStartsAt || DEFAULT_NIGHT_STARTS_AT; }
javascript
{ "resource": "" }
q1688
clientNow
train
function clientNow() { var d = new Date(); var offset = -1 * d.getTimezoneOffset(); d.setUTCMinutes(d.getUTCMinutes() + offset); return d.toISOString().replace('Z', minutesToOffsetString(offset)); }
javascript
{ "resource": "" }
q1689
update
train
function update(instance) { instance.isValid = isValid(instance._date); instance.timeString = instance.toString(); return instance; }
javascript
{ "resource": "" }
q1690
isValid
train
function isValid(date) { return Object.prototype.toString.call(date) == '[object Date]' && !isNaN(date.getTime()); }
javascript
{ "resource": "" }
q1691
isTime
train
function isTime(time) { return time != null && time._manipulate != null && time._date != null; }
javascript
{ "resource": "" }
q1692
pad
train
function pad(value, length) { value = String(value); length = length || 2; while (value.length < length) { value = '0' + value; } return value; }
javascript
{ "resource": "" }
q1693
minutesToOffsetString
train
function minutesToOffsetString(minutes) { var t = String(Math.abs(minutes / 60)).split('.'); var H = pad(t[0]); var m = t[1] ? parseInt(t[1], 10) * 0.6 : 0; var sign = minutes < 0 ? '-' : '+'; return '' + sign + H + ':' + pad(m); }
javascript
{ "resource": "" }
q1694
addSentinels
train
function addSentinels(container, className, stickySelector = STICKY_SELECTOR) { return Array.from(container.querySelectorAll(stickySelector)).map((stickyElement) => { const sentinel = document.createElement('div'); const stickyParent = stickyElement.parentElement; // Apply styles to the sticky element stickyElement.style.cssText = ` position: -webkit-sticky; position: sticky; `; // Apply default sentinel styles sentinel.classList.add(ClassName.SENTINEL, className); Object.assign(sentinel.style,{ left: 0, position: 'absolute', right: 0, visibility: 'hidden', }); switch (className) { case ClassName.SENTINEL_TOP: { stickyParent.insertBefore(sentinel, stickyElement); // Apply styles specific to the top sentinel Object.assign( sentinel.style, getSentinelPosition(stickyElement, sentinel, className), { position: 'relative' }, ); break; } case ClassName.SENTINEL_BOTTOM: { stickyParent.appendChild(sentinel); // Apply styles specific to the bottom sentinel Object.assign(sentinel.style, getSentinelPosition(stickyElement, sentinel, className)); break; } } return sentinel; }); }
javascript
{ "resource": "" }
q1695
getSentinelPosition
train
function getSentinelPosition(stickyElement, sentinel, className) { const stickyStyle = window.getComputedStyle(stickyElement); const parentStyle = window.getComputedStyle(stickyElement.parentElement); switch (className) { case ClassName.SENTINEL_TOP: return { top: `calc(${stickyStyle.getPropertyValue('top')} * -1)`, height: 0, }; case ClassName.SENTINEL_BOTTOM: const parentPadding = parseInt(parentStyle.paddingTop); return { bottom: stickyStyle.top, height: `${stickyElement.getBoundingClientRect().height + parentPadding}px`, }; } }
javascript
{ "resource": "" }
q1696
isSticking
train
function isSticking(stickyElement) { const topSentinel = stickyElement.previousElementSibling; const stickyOffset = stickyElement.getBoundingClientRect().top; const topSentinelOffset = topSentinel.getBoundingClientRect().top; const difference = Math.round(Math.abs(stickyOffset - topSentinelOffset)); const topSentinelTopPosition = Math.abs(parseInt(window.getComputedStyle(topSentinel).getPropertyValue('top'))); return difference !== topSentinelTopPosition; }
javascript
{ "resource": "" }
q1697
computeLcsMatrix
train
function computeLcsMatrix(xs, ys) { var n = xs.size||0; var m = ys.size||0; var a = makeMatrix(n + 1, m + 1, 0); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { if (Immutable.is(xs.get(i), ys.get(j))) { a[i + 1][j + 1] = a[i][j] + 1; } else { a[i + 1][j + 1] = Math.max(a[i + 1][j], a[i][j + 1]); } } } return a; }
javascript
{ "resource": "" }
q1698
train
function(xs, ys, matrix){ var lcs = []; for(var i = xs.size, j = ys.size; i !== 0 && j !== 0;){ if (matrix[i][j] === matrix[i-1][j]){ i--; } else if (matrix[i][j] === matrix[i][j-1]){ j--; } else{ if(Immutable.is(xs.get(i-1), ys.get(j-1))){ lcs.push(xs.get(i-1)); i--; j--; } } } return lcs.reverse(); }
javascript
{ "resource": "" }
q1699
serializeCurrentNode
train
function serializeCurrentNode(currentNode) { var children = currentNode.children; if (!children) { return null; } var len = children.length; var arr = new Array(len); var i = -1; while (++i < len) { arr[i] = serializeCurrentNode(children[i]); } if (currentNode.count) { return [arr, currentNode.count]; } else { return [arr]; } }
javascript
{ "resource": "" }