_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| 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;
|
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
|
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.
|
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);
|
javascript
|
{
"resource": ""
}
|
q1604
|
tryGetObjectLikeCompletionContainer
|
train
|
function tryGetObjectLikeCompletionContainer(contextToken) {
if (contextToken) {
switch (contextToken.kind) {
case 15 /* OpenBraceToken */: // const x = { |
case 24 /* CommaToken */:
|
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 */:
|
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;
}
|
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];
|
javascript
|
{
"resource": ""
}
|
q1608
|
getDirectoryFragmentTextSpan
|
train
|
function getDirectoryFragmentTextSpan(text, textStart) {
var index = text.lastIndexOf(ts.directorySeparator);
var offset = index !== -1 ? index + 1 : 0;
|
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
|
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);
|
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;
}
|
javascript
|
{
"resource": ""
}
|
q1612
|
chainStepsNoError
|
train
|
function chainStepsNoError() {
var steps = slice.call(arguments).map(function(step) {
return
|
javascript
|
{
"resource": ""
}
|
q1613
|
chainAndCall
|
train
|
function chainAndCall(chainer) {
return function(/*step1, step2, ...*/) {
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1615
|
get
|
train
|
function get(attr) {
var val = dotty.get(attrs, attr);
if (val === undefined) {
this.emit('undefined',
|
javascript
|
{
"resource": ""
}
|
q1616
|
processZtagOutput
|
train
|
function processZtagOutput(output) {
return output.split('\n').reduce(function(memo, line) {
var match, key, value;
|
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)
}
|
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;
|
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 ';
}
|
javascript
|
{
"resource": ""
}
|
|
q1620
|
shuffle
|
train
|
function shuffle(v) {
for (var j, x, i = v.length; i;
|
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) {
|
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
|
javascript
|
{
"resource": ""
}
|
q1623
|
isIterable
|
train
|
function isIterable (v) {
return
|
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);
|
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 ] ||
|
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
|
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) {
|
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
|
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);
|
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) {
|
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
|
javascript
|
{
"resource": ""
}
|
q1632
|
getAuth
|
train
|
function getAuth (auth, url) {
if (auth && auth.user && auth.pass) {
return auth.user
|
javascript
|
{
"resource": ""
}
|
q1633
|
getPath
|
train
|
function getPath (path, name, profiles, label) {
const profilesStr = buildProfilesString(profiles)
return (path.endsWith('/') ? path : path + '/') +
encodeURIComponent(name) + '/'
|
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),
|
javascript
|
{
"resource": ""
}
|
q1635
|
loadWithPromise
|
train
|
function loadWithPromise (options) {
return new Promise((resolve, reject) => {
loadWithCallback(options, (error, config) => {
if (error) {
|
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
|
javascript
|
{
"resource": ""
}
|
q1637
|
assert
|
train
|
function assert(value, schema, message, vars) {
return
|
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)}]`;
}
|
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
|
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
|
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])
|
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],
|
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' &&
|
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
|
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
|
javascript
|
{
"resource": ""
}
|
|
q1646
|
extend
|
train
|
function extend(a, b){
var p, type;
for(p in b) {
type = typeof b[p];
if(type !== "object" && type !==
|
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 {
|
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);
|
javascript
|
{
"resource": ""
}
|
q1649
|
addFeatures
|
train
|
function addFeatures() {
const features = {};
for (const spec in filters.specs) {
|
javascript
|
{
"resource": ""
}
|
q1650
|
addSpecFiles
|
train
|
function addSpecFiles() {
const specFiles = {};
for (const spec in filters.specs) {
|
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];
}
|
javascript
|
{
"resource": ""
}
|
q1652
|
splitToObj
|
train
|
function splitToObj(str, delim) {
if (!(_.isString(str))) {
throw new Error(`Input must be a string: ${str}`);
}
else {
|
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) {
|
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;
|
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,
//
|
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 =
|
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;
|
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 <
|
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' &&
|
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++) {
|
javascript
|
{
"resource": ""
}
|
q1661
|
prettifyDiffOutput
|
train
|
function prettifyDiffOutput(diffArr) {
const res = [];
for (const diff of diffArr) {
|
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
|
javascript
|
{
"resource": ""
}
|
q1663
|
proxifySteps
|
train
|
function proxifySteps(stepDefinitions) {
return new Proxy(stepDefinitions, {
get: (target, name, receiver) => stepsGetter(target, name, receiver),
|
javascript
|
{
"resource": ""
}
|
q1664
|
mapToObject
|
train
|
function mapToObject(input, mapFunc) {
const obj = {};
for (const element of input) {
|
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 => {
//
|
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 =
|
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') {
|
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;
|
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;
|
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);
}
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1672
|
checkForInlineMixins
|
train
|
function checkForInlineMixins(mixin, rtn) {
if (mixin.mixins) {
get(mixin.mixins,
|
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
|
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
|
javascript
|
{
"resource": ""
}
|
q1675
|
train
|
function(name) {
var l = _dependsInjected[name];
if (!l) {
l = _dependsInjected[name] = [];
}
|
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
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1678
|
iteratorFactory
|
train
|
function iteratorFactory(callback) {
return iterator
function iterator(parent) {
var children = parent && parent.children
if (!children) {
throw new Error('Missing
|
javascript
|
{
"resource": ""
}
|
q1679
|
setIfPresent
|
train
|
function setIfPresent(docEl, nodeName){
var node = getBaseElement(docEl,
|
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)
|
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
|
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 );
|
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;
|
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) {
|
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 ?
|
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) {
|
javascript
|
{
"resource": ""
}
|
q1687
|
init
|
train
|
function init() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
dayStartsAt =
|
javascript
|
{
"resource": ""
}
|
q1688
|
clientNow
|
train
|
function clientNow() {
var d = new Date();
var offset = -1 * d.getTimezoneOffset();
d.setUTCMinutes(d.getUTCMinutes() + offset);
return
|
javascript
|
{
"resource": ""
}
|
q1689
|
update
|
train
|
function update(instance) {
instance.isValid = isValid(instance._date);
instance.timeString =
|
javascript
|
{
"resource": ""
}
|
q1690
|
isValid
|
train
|
function isValid(date) {
return Object.prototype.toString.call(date) == '[object
|
javascript
|
{
"resource": ""
}
|
q1691
|
isTime
|
train
|
function isTime(time) {
return time != null && time._manipulate !=
|
javascript
|
{
"resource": ""
}
|
q1692
|
pad
|
train
|
function pad(value, length) {
value = String(value);
length = length || 2;
while (value.length <
|
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;
|
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);
|
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,
|
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));
|
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] +
|
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{
|
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 <
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.