_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q17600
|
fixAcornEsmImport
|
train
|
function fixAcornEsmImport() {
return {
name: 'fix-acorn-esm-import',
renderChunk(code, chunk, options) {
if (/esm?/.test(options.format)) {
let found = false;
const fixedCode = code.replace(expectedAcornImport, () => {
found = true;
return newAcornImport;
});
if (!found) {
this.error(
'Could not find expected acorn import, please deactive this plugin and examine generated code.'
);
}
return fixedCode;
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q17601
|
parseIpfsPath
|
train
|
function parseIpfsPath (ipfsPath) {
const invalidPathErr = new Error('invalid ipfs ref path')
ipfsPath = ipfsPath.replace(/^\/ipfs\//, '')
const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/)
if (!matched) {
throw invalidPathErr
}
const [hash, ...links] = matched[1].split('/')
// check that a CID can be constructed with the hash
if (isIpfs.cid(hash)) {
return { hash, links }
} else {
throw invalidPathErr
}
}
|
javascript
|
{
"resource": ""
}
|
q17602
|
follow
|
train
|
function follow (cid, links, err, obj) {
if (err) {
return cb(err)
}
if (!links.length) {
// done tracing, obj is the target node
return cb(null, cid.buffer)
}
const linkName = links[0]
const nextObj = obj.links.find(link => link.name === linkName)
if (!nextObj) {
return cb(new Error(
`no link named "${linkName}" under ${cid.toBaseEncodedString()}`
))
}
objectAPI.get(nextObj.cid, follow.bind(null, nextObj.cid, links.slice(1)))
}
|
javascript
|
{
"resource": ""
}
|
q17603
|
parseRabinString
|
train
|
function parseRabinString (chunker) {
const options = {}
const parts = chunker.split('-')
switch (parts.length) {
case 1:
options.avgChunkSize = 262144
break
case 2:
options.avgChunkSize = parseChunkSize(parts[1], 'avg')
break
case 4:
options.minChunkSize = parseChunkSize(parts[1], 'min')
options.avgChunkSize = parseChunkSize(parts[2], 'avg')
options.maxChunkSize = parseChunkSize(parts[3], 'max')
break
default:
throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"')
}
return options
}
|
javascript
|
{
"resource": ""
}
|
q17604
|
resolve
|
train
|
function resolve (cid, path, callback) {
let value, remainderPath
doUntil(
(cb) => {
self.block.get(cid, (err, block) => {
if (err) return cb(err)
const r = self._ipld.resolvers[cid.codec]
if (!r) {
return cb(new Error(`No resolver found for codec "${cid.codec}"`))
}
r.resolver.resolve(block.data, path, (err, result) => {
if (err) return cb(err)
value = result.value
remainderPath = result.remainderPath
cb()
})
})
},
() => {
if (value && value['/']) {
// If we've hit a CID, replace the current CID.
cid = new CID(value['/'])
path = remainderPath
} else if (CID.isCID(value)) {
// If we've hit a CID, replace the current CID.
cid = value
path = remainderPath
} else {
// We've hit a value. Return the current CID and the remaining path.
return true
}
// Continue resolving unless the path is empty.
return !path || path === '/'
},
(err) => {
if (err) return callback(err)
callback(null, { cid, remainderPath: path })
}
)
}
|
javascript
|
{
"resource": ""
}
|
q17605
|
train
|
function(doc) {
// Heuristic for the custom docs in the lib/selenium-webdriver/ folder.
if (doc.name && doc.name.startsWith('webdriver')) {
return;
}
var template = _.template('https://github.com/angular/protractor/blob/' +
'<%= linksHash %>/lib/<%= fileName %>.ts');
doc.sourceLink = template({
linksHash: linksHash,
fileName: doc.fileName
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17606
|
train
|
function(str, doc) {
var oldStr = null;
while (str != oldStr) {
oldStr = str;
var matches = /{\s*@link[plain]*\s+([^]+?)\s*}/.exec(str);
if (matches) {
var str = str.replace(
new RegExp('{\\s*@link[plain]*\\s+' +
matches[1].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\\s*}'),
toMarkdownLinkFormat(matches[1], doc,
matches[0].indexOf('linkplain') == -1)
);
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
|
q17607
|
train
|
function(param) {
var str = param.typeExpression;
var type = param.type;
if (!type) {
return escape(str);
}
var replaceWithLinkIfPresent = function(type) {
if (type.name) {
str = str.replace(type.name, toMarkdownLinkFormat(type.name));
}
};
if (type.type === 'FunctionType') {
_.each(type.params, replaceWithLinkIfPresent);
} else if (type.type === 'TypeApplication') {
// Is this an Array.<type>?
var match = str.match(/Array\.<(.*)>/);
if (match) {
var typeInsideArray = match[1];
str = str.replace(typeInsideArray, toMarkdownLinkFormat(typeInsideArray));
}
} else if (type.type === 'NameExpression') {
replaceWithLinkIfPresent(type);
}
return escape(str);
}
|
javascript
|
{
"resource": ""
}
|
|
q17608
|
train
|
function(item) {
var parts = item.displayName.split('.');
for (var i = parts.length - 1; i > 0; i--) {
var name = parts.slice(0, i).join('.');
if (itemsByName[name]) {
return itemsByName[name];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17609
|
train
|
function(doc) {
// Skip if the function has a name.
if (doc.name) {
return doc.name;
}
try {
var node = doc.codeNode;
// Is this a simple declaration? "var element = function() {".
if (node.declarations && node.declarations.length) {
return node.declarations[0].id.name;
}
// Is this an expression? "elementFinder.find = function() {".
if (node.expression) {
var parts = [];
/**
* Recursively create the function name by examining the object property.
* @param obj Parsed object.
* @return {string} The name of the function.
*/
function buildName(obj) {
if (!obj) {
return parts.join('.');
}
if (obj.property && obj.property.name) {
parts.unshift(obj.property.name);
}
if (obj.object && obj.object.name) {
parts.unshift(obj.object.name);
}
return buildName(obj.object);
}
return buildName(node.expression.left);
}
} catch (e) {
console.log('Could not find document name', doc.file, doc.endingLine);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17610
|
buildName
|
train
|
function buildName(obj) {
if (!obj) {
return parts.join('.');
}
if (obj.property && obj.property.name) {
parts.unshift(obj.property.name);
}
if (obj.object && obj.object.name) {
parts.unshift(obj.object.name);
}
return buildName(obj.object);
}
|
javascript
|
{
"resource": ""
}
|
q17611
|
train
|
function(doc) {
if (doc.params) {
_.each(doc.params, function(param) {
replaceNewLines(param, 'description');
});
}
// Replace new lines in the return and params descriptions.
var returns = doc.returns;
if (returns) {
replaceNewLines(returns, 'description');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17612
|
train
|
function(callback) {
if (window.angular) {
var hooks = getNg1Hooks(rootSelector);
if (!hooks){
callback(); // not an angular1 app
}
else{
if (hooks.$$testability) {
hooks.$$testability.whenStable(callback);
} else if (hooks.$injector) {
hooks.$injector.get('$browser')
.notifyWhenNoOutstandingRequests(callback);
} else if (!rootSelector) {
throw new Error(
'Could not automatically find injector on page: "' +
window.location.toString() + '". Consider using config.rootEl');
} else {
throw new Error(
'root element (' + rootSelector + ') has no injector.' +
' this may mean it is not inside ng-app.');
}
}
}
else {callback();} // not an angular1 app
}
|
javascript
|
{
"resource": ""
}
|
|
q17613
|
train
|
function() {
if (window.getAngularTestability) {
if (rootSelector) {
var testability = null;
var el = document.querySelector(rootSelector);
try{
testability = window.getAngularTestability(el);
}
catch(e){}
if (testability) {
testability.whenStable(testCallback);
return;
}
}
// Didn't specify root element or testability could not be found
// by rootSelector. This may happen in a hybrid app, which could have
// more than one root.
var testabilities = window.getAllAngularTestabilities();
var count = testabilities.length;
// No angular2 testability, this happens when
// going to a hybrid page and going back to a pure angular1 page
if (count === 0) {
testCallback();
return;
}
var decrement = function() {
count--;
if (count === 0) {
testCallback();
}
};
testabilities.forEach(function(testability) {
testability.whenStable(decrement);
});
}
else {testCallback();} // not an angular2 app
}
|
javascript
|
{
"resource": ""
}
|
|
q17614
|
findRepeaterRows
|
train
|
function findRepeaterRows(repeater, exact, index, using) {
using = using || document;
var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:'];
var rows = [];
for (var p = 0; p < prefixes.length; ++p) {
var attr = prefixes[p] + 'repeat';
var repeatElems = using.querySelectorAll('[' + attr + ']');
attr = attr.replace(/\\/g, '');
for (var i = 0; i < repeatElems.length; ++i) {
if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) {
rows.push(repeatElems[i]);
}
}
}
/* multiRows is an array of arrays, where each inner array contains
one row of elements. */
var multiRows = [];
for (var p = 0; p < prefixes.length; ++p) {
var attr = prefixes[p] + 'repeat-start';
var repeatElems = using.querySelectorAll('[' + attr + ']');
attr = attr.replace(/\\/g, '');
for (var i = 0; i < repeatElems.length; ++i) {
if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) {
var elem = repeatElems[i];
var row = [];
while (elem.nodeType != 8 ||
!repeaterMatch(elem.nodeValue, repeater)) {
if (elem.nodeType == 1) {
row.push(elem);
}
elem = elem.nextSibling;
}
multiRows.push(row);
}
}
}
var row = rows[index] || [], multiRow = multiRows[index] || [];
return [].concat(row, multiRow);
}
|
javascript
|
{
"resource": ""
}
|
q17615
|
findAllRepeaterRows
|
train
|
function findAllRepeaterRows(repeater, exact, using) {
using = using || document;
var rows = [];
var prefixes = ['ng-', 'ng_', 'data-ng-', 'x-ng-', 'ng\\:'];
for (var p = 0; p < prefixes.length; ++p) {
var attr = prefixes[p] + 'repeat';
var repeatElems = using.querySelectorAll('[' + attr + ']');
attr = attr.replace(/\\/g, '');
for (var i = 0; i < repeatElems.length; ++i) {
if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) {
rows.push(repeatElems[i]);
}
}
}
for (var p = 0; p < prefixes.length; ++p) {
var attr = prefixes[p] + 'repeat-start';
var repeatElems = using.querySelectorAll('[' + attr + ']');
attr = attr.replace(/\\/g, '');
for (var i = 0; i < repeatElems.length; ++i) {
if (repeaterMatch(repeatElems[i].getAttribute(attr), repeater, exact)) {
var elem = repeatElems[i];
while (elem.nodeType != 8 ||
!repeaterMatch(elem.nodeValue, repeater)) {
if (elem.nodeType == 1) {
rows.push(elem);
}
elem = elem.nextSibling;
}
}
}
}
return rows;
}
|
javascript
|
{
"resource": ""
}
|
q17616
|
_convertUnicode
|
train
|
function _convertUnicode(originalStr) {
let m;
let c;
let cStr;
let lastI = 0;
// Matches \u#### but not \\u####
const unicodeRegex = /\\u[0-9a-fA-F]{4}/g;
let convertedStr = '';
while ((m = unicodeRegex.exec(originalStr))) {
// Don't convert if the backslash itself is escaped
if (originalStr[m.index - 1] === '\\') {
continue;
}
try {
cStr = m[0].slice(2); // Trim off start
c = String.fromCharCode(parseInt(cStr, 16));
if (c === '"') {
// Escape it if it's double quotes
c = `\\${c}`;
}
// + 1 to account for first matched (non-backslash) character
convertedStr += originalStr.slice(lastI, m.index) + c;
lastI = m.index + m[0].length;
} catch (err) {
// Some reason we couldn't convert a char. Should never actually happen
console.warn('Failed to convert unicode char', m[0], err);
}
}
// Finally, add the rest of the string to the end.
convertedStr += originalStr.slice(lastI, originalStr.length);
return convertedStr;
}
|
javascript
|
{
"resource": ""
}
|
q17617
|
parseEndpoints
|
train
|
function parseEndpoints(document) {
const defaultParent = WORKSPACE_ID;
const paths = Object.keys(document.paths);
const endpointsSchemas = paths
.map(path => {
const schemasPerMethod = document.paths[path];
const methods = Object.keys(schemasPerMethod);
return methods
.filter(method => method !== 'parameters')
.map(method => Object.assign({}, schemasPerMethod[method], { path, method }));
})
.reduce((flat, arr) => flat.concat(arr), []); //flat single array
const tags = document.tags || [];
const folders = tags.map(tag => {
return importFolderItem(tag, defaultParent);
});
const folderLookup = {};
folders.forEach(folder => (folderLookup[folder.name] = folder._id));
const requests = [];
endpointsSchemas.map(endpointSchema => {
let { tags } = endpointSchema;
if (!tags || tags.length == 0) tags = [''];
tags.forEach((tag, index) => {
let id = endpointSchema.operationId
? `${endpointSchema.operationId}${index > 0 ? index : ''}`
: `__REQUEST_${requestCount++}__`;
let parentId = folderLookup[tag] || defaultParent;
requests.push(importRequest(endpointSchema, id, parentId));
});
});
return [...folders, ...requests];
}
|
javascript
|
{
"resource": ""
}
|
q17618
|
importRequest
|
train
|
function importRequest(endpointSchema, id, parentId) {
const name = endpointSchema.summary || `${endpointSchema.method} ${endpointSchema.path}`;
return {
_type: 'request',
_id: id,
parentId: parentId,
name,
method: endpointSchema.method.toUpperCase(),
url: '{{ base_url }}' + pathWithParamsAsVariables(endpointSchema.path),
body: prepareBody(endpointSchema),
headers: prepareHeaders(endpointSchema),
parameters: prepareQueryParams(endpointSchema),
};
}
|
javascript
|
{
"resource": ""
}
|
q17619
|
prepareQueryParams
|
train
|
function prepareQueryParams(endpointSchema) {
const isSendInQuery = p => p.in === 'query';
const parameters = endpointSchema.parameters || [];
const queryParameters = parameters.filter(isSendInQuery);
return convertParameters(queryParameters);
}
|
javascript
|
{
"resource": ""
}
|
q17620
|
prepareHeaders
|
train
|
function prepareHeaders(endpointSchema) {
const isSendInHeader = p => p.in === 'header';
const parameters = endpointSchema.parameters || [];
const headerParameters = parameters.filter(isSendInHeader);
return convertParameters(headerParameters);
}
|
javascript
|
{
"resource": ""
}
|
q17621
|
convertParameters
|
train
|
function convertParameters(parameters) {
return parameters.map(parameter => {
const { required, name } = parameter;
return {
name,
disabled: required !== true,
value: `${generateParameterExample(parameter)}`,
};
});
}
|
javascript
|
{
"resource": ""
}
|
q17622
|
replaceHintMatch
|
train
|
function replaceHintMatch(cm, self, data) {
const cur = cm.getCursor();
const from = CodeMirror.Pos(cur.line, cur.ch - data.segment.length);
const to = CodeMirror.Pos(cur.line, cur.ch);
const prevStart = CodeMirror.Pos(from.line, from.ch - 10);
const prevChars = cm.getRange(prevStart, from);
const nextEnd = CodeMirror.Pos(to.line, to.ch + 10);
const nextChars = cm.getRange(to, nextEnd);
let prefix = '';
let suffix = '';
if (data.type === TYPE_VARIABLE && !prevChars.match(/{{[^}]*$/)) {
prefix = '{{ '; // If no closer before
} else if (data.type === TYPE_VARIABLE && prevChars.match(/{{$/)) {
prefix = ' '; // If no space after opener
} else if (data.type === TYPE_TAG && prevChars.match(/{%$/)) {
prefix = ' '; // If no space after opener
} else if (data.type === TYPE_TAG && !prevChars.match(/{%[^%]*$/)) {
prefix = '{% '; // If no closer before
}
if (data.type === TYPE_VARIABLE && !nextChars.match(/^\s*}}/)) {
suffix = ' }}'; // If no closer after
} else if (data.type === TYPE_VARIABLE && nextChars.match(/^}}/)) {
suffix = ' '; // If no space before closer
} else if (data.type === TYPE_TAG && nextChars.match(/^%}/)) {
suffix = ' '; // If no space before closer
} else if (data.type === TYPE_TAG && nextChars.match(/^\s*}/)) {
// Edge case because "%" doesn't auto-close tags so sometimes you end
// up in the scenario of {% foo}
suffix = ' %';
} else if (data.type === TYPE_TAG && !nextChars.match(/^\s*%}/)) {
suffix = ' %}'; // If no closer after
}
cm.replaceRange(`${prefix}${data.text}${suffix}`, from, to);
}
|
javascript
|
{
"resource": ""
}
|
q17623
|
matchSegments
|
train
|
function matchSegments(listOfThings, segment, type, limit = -1) {
if (!Array.isArray(listOfThings)) {
console.warn('Autocomplete received items in non-list form', listOfThings);
return [];
}
const matches = [];
for (const t of listOfThings) {
const name = typeof t === 'string' ? t : t.name;
const value = typeof t === 'string' ? '' : t.value;
const displayName = t.displayName || name;
const defaultFill = typeof t === 'string' ? name : getDefaultFill(t.name, t.args);
const matchSegment = segment.toLowerCase();
const matchName = displayName.toLowerCase();
// Throw away things that don't match
if (!matchName.includes(matchSegment)) {
continue;
}
matches.push({
// Custom Insomnia keys
type,
segment,
comment: value,
displayValue: value ? JSON.stringify(value) : '',
score: name.length, // In case we want to sort by this
// CodeMirror
text: defaultFill,
displayText: displayName,
render: renderHintMatch,
hint: replaceHintMatch,
});
}
if (limit >= 0) {
return matches.slice(0, limit);
} else {
return matches;
}
}
|
javascript
|
{
"resource": ""
}
|
q17624
|
replaceWithSurround
|
train
|
function replaceWithSurround(text, find, prefix, suffix) {
const escapedString = escapeRegex(find);
const re = new RegExp(escapedString, 'gi');
return text.replace(re, matched => prefix + matched + suffix);
}
|
javascript
|
{
"resource": ""
}
|
q17625
|
renderHintMatch
|
train
|
function renderHintMatch(li, self, data) {
// Bold the matched text
const { displayText, segment } = data;
const markedName = replaceWithSurround(displayText, segment, '<strong>', '</strong>');
const { char, title } = ICONS[data.type];
const safeValue = escapeHTML(data.displayValue);
li.className += ` fancy-hint type--${data.type}`;
li.innerHTML = `
<label class="label" title="${title}">${char}</label>
<div class="name">${markedName}</div>
<div class="value" title=${safeValue}>
${safeValue}
</div>
`;
}
|
javascript
|
{
"resource": ""
}
|
q17626
|
_getResourceGroupSymmetricKey
|
train
|
async function _getResourceGroupSymmetricKey(resourceGroupId) {
let key = resourceGroupSymmetricKeysCache[resourceGroupId];
if (!key) {
const resourceGroup = await fetchResourceGroup(resourceGroupId);
const accountPrivateKey = await session.getPrivateKey();
const symmetricKeyStr = crypt.decryptRSAWithJWK(
accountPrivateKey,
resourceGroup.encSymmetricKey,
);
key = JSON.parse(symmetricKeyStr);
// Update cache
resourceGroupSymmetricKeysCache[resourceGroupId] = key;
}
return key;
}
|
javascript
|
{
"resource": ""
}
|
q17627
|
_pbkdf2Passphrase
|
train
|
async function _pbkdf2Passphrase(passphrase, salt) {
if (window.crypto && window.crypto.subtle) {
console.log('[crypt] Using native PBKDF2');
const k = await window.crypto.subtle.importKey(
'raw',
Buffer.from(passphrase, 'utf8'),
{ name: 'PBKDF2' },
false,
['deriveBits'],
);
const algo = {
name: 'PBKDF2',
salt: Buffer.from(salt, 'hex'),
iterations: DEFAULT_PBKDF2_ITERATIONS,
hash: 'SHA-256',
};
const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8);
return Buffer.from(derivedKeyRaw).toString('hex');
} else {
console.log('[crypt] Using Forge PBKDF2');
const derivedKeyRaw = forge.pkcs5.pbkdf2(
passphrase,
forge.util.hexToBytes(salt),
DEFAULT_PBKDF2_ITERATIONS,
DEFAULT_BYTE_LENGTH,
forge.md.sha256.create(),
);
return forge.util.bytesToHex(derivedKeyRaw);
}
}
|
javascript
|
{
"resource": ""
}
|
q17628
|
getAllDocs
|
train
|
async function getAllDocs() {
// Restore docs in parent->child->grandchild order
const allDocs = [
...(await models.settings.all()),
...(await models.workspace.all()),
...(await models.workspaceMeta.all()),
...(await models.environment.all()),
...(await models.cookieJar.all()),
...(await models.requestGroup.all()),
...(await models.requestGroupMeta.all()),
...(await models.request.all()),
...(await models.requestMeta.all()),
...(await models.response.all()),
...(await models.oAuth2Token.all()),
...(await models.clientCertificate.all()),
];
return allDocs;
}
|
javascript
|
{
"resource": ""
}
|
q17629
|
addNativeNodeListener
|
train
|
function addNativeNodeListener (node, eventName, handler) {
if (isNullOrUndefined(node.data.on)) {
node.data.on = {};
}
mergeVNodeListeners(node.data.on, eventName, handler);
}
|
javascript
|
{
"resource": ""
}
|
q17630
|
addComponentNodeListener
|
train
|
function addComponentNodeListener (node, eventName, handler) {
/* istanbul ignore next */
if (!node.componentOptions.listeners) {
node.componentOptions.listeners = {};
}
mergeVNodeListeners(node.componentOptions.listeners, eventName, handler);
}
|
javascript
|
{
"resource": ""
}
|
q17631
|
shouldValidate
|
train
|
function shouldValidate (ctx, model) {
// when an immediate/initial validation is needed and wasn't done before.
if (!ctx._ignoreImmediate && ctx.immediate) {
return true;
}
// when the value changes for whatever reason.
if (ctx.value !== model.value) {
return true;
}
// when it needs validation due to props/cross-fields changes.
if (ctx._needsValidation) {
return true;
}
// when the initial value is undefined and the field wasn't rendered yet.
if (!ctx.initialized && model.value === undefined) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q17632
|
addListeners
|
train
|
function addListeners (node) {
const model = findModel(node);
// cache the input eventName.
this._inputEventName = this._inputEventName || getInputEventName(node, model);
onRenderUpdate.call(this, model);
const { onInput, onBlur, onValidate } = createCommonHandlers(this);
addVNodeListener(node, this._inputEventName, onInput);
addVNodeListener(node, 'blur', onBlur);
// add the validation listeners.
this.normalizedEvents.forEach(evt => {
addVNodeListener(node, evt, onValidate);
});
this.initialized = true;
}
|
javascript
|
{
"resource": ""
}
|
q17633
|
train
|
function() {
// UI initialized, it is OK to cancel last operation.
self.initialized_ = true;
// retrieve is only called if auto sign-in is enabled. Otherwise, it will
// get skipped.
var retrieveCredential = Promise.resolve(null);
if (!autoSignInDisabled) {
retrieveCredential =
self.googleyolo_.retrieve(
/** @type {!SmartLockRequestOptions} */ (config))
.catch(function(error) {
// For user cancellation or concurrent request pass down.
// Otherwise suppress and run hint.
if (error.type ===
firebaseui.auth.GoogleYolo.Error.USER_CANCELED ||
error.type ===
firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) {
throw error;
}
// Ignore all other errors to give hint a chance to run next.
return null;
});
}
// Check if a credential is already available (previously signed in with).
return retrieveCredential
.then(function(credential) {
if (!credential) {
// Auto sign-in not complete.
// Show account selector.
return self.googleyolo_.hint(
/** @type {!SmartLockHintOptions} */ (config));
}
// Credential already available from the retrieve call. Pass it
// through.
return credential;
})
.catch(function(error) {
// When user cancels the flow, reset the lastCancel promise and
// resolve with false.
if (error.type === firebaseui.auth.GoogleYolo.Error.USER_CANCELED) {
self.lastCancel_ = Promise.resolve();
} else if (error.type ===
firebaseui.auth.GoogleYolo.Error.CONCURRENT_REQUEST) {
// Only one UI can be rendered at a time, cancel existing UI
// and try again.
self.cancel();
return self.show(config, autoSignInDisabled);
}
// Return null as no credential is available.
return null;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17634
|
train
|
function(resp, opt_error) {
if (resp && resp['account'] && opt_onAccountSelected) {
opt_onAccountSelected(
firebaseui.auth.Account.fromPlainObject(resp['account']));
} else if (opt_onAddAccount) {
// Check if accountchooser.com is available and pass to add account.
var isUnavailable = firebaseui.auth.acClient.isUnavailable_(opt_error);
// Either an error happened or user clicked the add account button.
opt_onAddAccount(!isUnavailable);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17635
|
train
|
function(done, fail, tries) {
// The default retrial policy.
if (typeof tries === 'undefined') {
tries = FLAKY_TEST_RETRIAL;
}
// executeScript runs the passed method in the "window" context of
// the current test. JSUnit exposes hooks into the test's status through
// the "G_testRunner" global object.
browser.executeScript(function() {
if (window['G_testRunner'] && window['G_testRunner']['isFinished']()) {
return {
isFinished: true,
isSuccess: window['G_testRunner']['isSuccess'](),
report: window['G_testRunner']['getReport']()
};
} else {
return {'isFinished': false};
}
}).then(function(status) {
// Tests completed on the page but something failed. Retry a certain
// number of times in case of flakiness.
if (status && status.isFinished && !status.isSuccess && tries > 1) {
// Try again in a few ms.
setTimeout(waitForTest.bind(undefined, done, fail, tries - 1), 300);
} else if (status && status.isFinished) {
done(status);
} else {
// Try again in a few ms.
setTimeout(waitForTest.bind(undefined, done, fail, tries), 300);
}
}, function(err) {
// This can happen if the webdriver had an issue executing the script.
fail(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17636
|
train
|
function(isAvailable) {
var app = getApp();
if (!app) {
return;
}
firebaseui.auth.widget.handler.common.handleAcAddAccountResponse_(
isAvailable, app, container, uiShownCallback);
}
|
javascript
|
{
"resource": ""
}
|
|
q17637
|
train
|
function(error) {
// Ignore error if cancelled by the client.
if (error['name'] && error['name'] == 'cancel') {
return;
}
// Check if the error was due to an expired credential.
// This may happen in the email mismatch case where the user waits more
// than an hour and then proceeds to sign in with the expired credential.
// Display the relevant error message in this case and return the user to
// the sign-in start page.
if (firebaseui.auth.widget.handler.common.isCredentialExpired(error)) {
var container = component.getContainer();
// Dispose any existing component.
component.dispose();
// Call widget sign-in start handler with the expired credential error.
firebaseui.auth.widget.handler.common.handleSignInStart(
app,
container,
undefined,
firebaseui.auth.soy2.strings.errorExpiredCredential().toString());
} else {
var errorMessage = (error && error['message']) || '';
if (error['code']) {
// Firebase Auth error.
// Errors thrown by anonymous upgrade should not be displayed in
// info bar.
if (error['code'] == 'auth/email-already-in-use' ||
error['code'] == 'auth/credential-already-in-use') {
return;
}
errorMessage =
firebaseui.auth.widget.handler.common.getErrorMessage(error);
}
// Show error message in the info bar.
component.showInfoBar(errorMessage);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17638
|
train
|
function(error) {
// Clear pending redirect status if redirect on Cordova fails.
firebaseui.auth.storage.removePendingRedirectStatus(app.getAppId());
// Ignore error if cancelled by the client.
if (error['name'] && error['name'] == 'cancel') {
return;
}
switch (error['code']) {
case 'auth/popup-blocked':
// Popup blocked, switch to redirect flow as fallback.
processRedirect();
break;
case 'auth/popup-closed-by-user':
case 'auth/cancelled-popup-request':
// When popup is closed or when the user clicks another button,
// do nothing.
break;
case 'auth/credential-already-in-use':
// Do nothing when anonymous user is getting updated.
// Developer should handle this in signInFailure callback.
break;
case 'auth/network-request-failed':
case 'auth/too-many-requests':
case 'auth/user-cancelled':
// For no action errors like network error, just display in info
// bar in current component. A second attempt could still work.
component.showInfoBar(
firebaseui.auth.widget.handler.common.getErrorMessage(error));
break;
default:
// Either linking required errors or errors that are
// unrecoverable.
component.dispose();
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.CALLBACK,
app,
container,
goog.Promise.reject(error));
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17639
|
train
|
function() {
firebaseui.auth.storage.setPendingRedirectStatus(app.getAppId());
app.registerPending(component.executePromiseRequest(
/** @type {function (): !goog.Promise} */ (
goog.bind(app.startSignInWithRedirect, app)),
[provider],
function() {
// Only run below logic if the environment is potentially a Cordova
// environment. This check is not required but will minimize the
// need to change existing tests that assertSignInWithRedirect.
if (firebaseui.auth.util.getScheme() !== 'file:') {
return;
}
// This will resolve in a Cordova environment. Result should be
// obtained from getRedirectResult and then treated like a
// signInWithPopup operation.
return app.registerPending(app.getRedirectResult()
.then(function(result) {
// Pass result in promise to callback handler.
component.dispose();
// Removes pending redirect status if sign-in with redirect
// resolves in Cordova environment.
firebaseui.auth.storage.removePendingRedirectStatus(
app.getAppId());
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.CALLBACK,
app,
container,
goog.Promise.resolve(result));
}, signInResultErrorCallback));
},
providerSigninFailedCallback));
}
|
javascript
|
{
"resource": ""
}
|
|
q17640
|
train
|
function(firebaseCredential) {
var status = false;
var p = component.executePromiseRequest(
/** @type {function (): !goog.Promise} */ (
goog.bind(app.startSignInWithCredential, app)),
[firebaseCredential],
function(result) {
var container = component.getContainer();
component.dispose();
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.CALLBACK,
app,
container,
goog.Promise.resolve(result));
status = true;
},
function(error) {
if (error['name'] && error['name'] == 'cancel') {
return;
} else if (error &&
error['code'] == 'auth/credential-already-in-use') {
// Do nothing when anonymous user is getting updated.
// Developer should handle this in signInFailure callback.
return;
} else if (error &&
error['code'] == 'auth/email-already-in-use' &&
error['email'] && error['credential']) {
// Email already in use error should trigger account linking flow.
// Pass error to callback handler to trigger that flow.
var container = component.getContainer();
component.dispose();
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.CALLBACK,
app,
container,
goog.Promise.reject(error));
return;
}
var errorMessage =
firebaseui.auth.widget.handler.common.getErrorMessage(error);
// Show error message in the info bar.
component.showInfoBar(errorMessage);
});
app.registerPending(p);
return p.then(function() {
// Status needs to be returned.
return status;
}, function(error) {
return false;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17641
|
train
|
function(providerId, opt_email) {
// If popup flow enabled, this will fail and fallback to redirect.
// TODO: Optimize to force redirect mode only.
// For non-Google providers (not supported yet). This may end up signing the
// user with a provider using different email. Even for Google, a user can
// override the login_hint, but that should be fine as it is the user's
// choice.
firebaseui.auth.widget.handler.common.federatedSignIn(
app, component, providerId, opt_email);
return goog.Promise.resolve(true);
}
|
javascript
|
{
"resource": ""
}
|
|
q17642
|
compile
|
train
|
function compile(srcs, out, args) {
// Get the compiler arguments, using the defaults if not specified.
const combinedArgs = Object.assign({}, COMPILER_DEFAULT_ARGS, args);
return gulp
.src(srcs)
.pipe(closureCompiler({
compilerPath: COMPILER_PATH,
fileName: path.basename(out),
compilerFlags: combinedArgs
}))
.pipe(gulp.dest(path.dirname(out)));
}
|
javascript
|
{
"resource": ""
}
|
q17643
|
repeatTaskForAllLocales
|
train
|
function repeatTaskForAllLocales(taskName, dependencies, operation) {
return ALL_LOCALES.map((locale) => {
// Convert build-js-$ to build-js-fr, for example.
const replaceTokens = (name) => name.replace(/\$/g, locale);
const localeTaskName = replaceTokens(taskName);
const localeDependencies = dependencies.map(replaceTokens);
gulp.task(localeTaskName, gulp.series(
gulp.parallel.apply(null, localeDependencies),
() => operation(locale)
));
return localeTaskName;
});
}
|
javascript
|
{
"resource": ""
}
|
q17644
|
buildFirebaseUiJs
|
train
|
function buildFirebaseUiJs(locale) {
const flags = {
closure_entry_point: 'firebaseui.auth.exports',
define: `goog.LOCALE='${locale}'`,
externs: [
'node_modules/firebase/externs/firebase-app-externs.js',
'node_modules/firebase/externs/firebase-auth-externs.js',
'node_modules/firebase/externs/firebase-client-auth-externs.js'
],
only_closure_dependencies: true,
output_wrapper: OUTPUT_WRAPPER,
// This is required to match XTB IDs to the JS/Soy messages.
translations_project: 'FirebaseUI'
};
if (locale !== DEFAULT_LOCALE) {
flags.translations_file = `translations/${locale}.xtb`;
}
return compile([
'node_modules/google-closure-templates/javascript/soyutils_usegoog.js',
'node_modules/google-closure-library/closure/goog/**/*.js',
'node_modules/google-closure-library/third_party/closure/goog/**/*.js',
`${TMP_DIR}/**/*.js`,
'javascript/**/*.js'
], getTmpJsPath(locale), flags);
}
|
javascript
|
{
"resource": ""
}
|
q17645
|
concatWithDeps
|
train
|
function concatWithDeps(locale, outBaseName, outputWrapper) {
const localeForFileName = getLocaleForFileName(locale);
// Get a list of the FirebaseUI JS and its dependencies.
const srcs = JS_DEPS.concat([getTmpJsPath(locale)]);
const outputPath = `${DEST_DIR}/${outBaseName}__${localeForFileName}.js`;
return compile(srcs, outputPath, {
compilation_level: 'WHITESPACE_ONLY',
output_wrapper: outputWrapper
});
}
|
javascript
|
{
"resource": ""
}
|
q17646
|
buildCss
|
train
|
function buildCss(isRtl) {
const mdlSrcs = gulp.src('stylesheet/mdl.scss')
.pipe(sass.sync().on('error', sass.logError))
.pipe(cssInlineImages({
webRoot: 'node_modules/material-design-lite/src',
}));
const dialogPolyfillSrcs = gulp.src(
'node_modules/dialog-polyfill/dialog-polyfill.css');
let firebaseSrcs = gulp.src('stylesheet/*.css');
// Flip left/right, ltr/rtl for RTL languages.
if (isRtl) {
firebaseSrcs = firebaseSrcs.pipe(flip.gulp());
}
const outFile = isRtl ? 'firebaseui-rtl.css' : 'firebaseui.css';
return streamqueue({objectMode: true},
mdlSrcs, dialogPolyfillSrcs, firebaseSrcs)
.pipe(concatCSS(outFile))
.pipe(cleanCSS())
.pipe(gulp.dest(DEST_DIR));
}
|
javascript
|
{
"resource": ""
}
|
q17647
|
loadRecaptcha
|
train
|
function loadRecaptcha(container) {
var root = goog.dom.getElement(container);
var recaptchaContainer =
goog.dom.getElementByClass('firebaseui-recaptcha-container', root);
recaptchaContainer.style.display = 'block';
var img = goog.dom.createElement('img');
img.src = '../image/test/recaptcha-widget.png';
recaptchaContainer.appendChild(img);
}
|
javascript
|
{
"resource": ""
}
|
q17648
|
train
|
function() {
firebaseui.auth.widget.handler.common.sendEmailLinkForSignIn(
app,
component,
email,
onCancelClick,
function(error) {
// The email provided could be an invalid one or some other error
// could occur.
var errorMessage =
firebaseui.auth.widget.handler.common.getErrorMessage(error);
component.showInfoBar(errorMessage);
},
opt_pendingCredential);
}
|
javascript
|
{
"resource": ""
}
|
|
q17649
|
assertIsDirectory
|
train
|
function assertIsDirectory(path) {
try {
if (!fs.lstatSync(path).isDirectory()) {
console.log('Path "' + path + '" is not a directory.');
process.exit();
}
} catch (e) {
console.log('Directory "' + path + '" could not be found.');
process.exit();
}
}
|
javascript
|
{
"resource": ""
}
|
q17650
|
train
|
function() {
var errorMessage =
firebaseui.auth.widget.handler.common.getErrorMessage(emailExistsError);
firebaseui.auth.ui.element.setValid(component.getEmailElement(), false);
firebaseui.auth.ui.element.show(
component.getEmailErrorElement(), errorMessage);
component.getEmailElement().focus();
}
|
javascript
|
{
"resource": ""
}
|
|
q17651
|
train
|
function(phoneAuthResult) {
// Display the dialog that the code was sent.
var container = component.getContainer();
component.showProgressDialog(
firebaseui.auth.ui.element.progressDialog.State.DONE,
firebaseui.auth.soy2.strings.dialogCodeSent().toString());
// Keep the dialog long enough to be seen before redirecting to code
// entry page.
var codeVerificationTimer = setTimeout(function() {
component.dismissDialog();
// Handle sign in with phone number code verification.
component.dispose();
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_FINISH,
app,
container,
phoneNumberValue,
firebaseui.auth.widget.handler.RESEND_DELAY_SECONDS,
phoneAuthResult);
}, firebaseui.auth.widget.handler.SENDING_SUCCESS_DIALOG_DELAY);
// On reset, clear timeout.
app.registerPending(function() {
// Dismiss dialog if still visible.
if (component) {
component.dismissDialog();
}
clearTimeout(codeVerificationTimer);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17652
|
getUiConfig
|
train
|
function getUiConfig() {
return {
'callbacks': {
// Called when the user has been successfully signed in.
'signInSuccessWithAuthResult': function(authResult, redirectUrl) {
if (authResult.user) {
handleSignedInUser(authResult.user);
}
if (authResult.additionalUserInfo) {
document.getElementById('is-new-user').textContent =
authResult.additionalUserInfo.isNewUser ?
'New User' : 'Existing User';
}
// Do not redirect.
return false;
}
},
// Opens IDP Providers sign-in flow in a popup.
'signInFlow': 'popup',
'signInOptions': [
// TODO(developer): Remove the providers you don't need for your app.
{
provider: firebase.auth.GoogleAuthProvider.PROVIDER_ID,
// Required to enable this provider in One-Tap Sign-up.
authMethod: 'https://accounts.google.com',
// Required to enable ID token credentials for this provider.
clientId: CLIENT_ID
},
{
provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID,
scopes :[
'public_profile',
'email',
'user_likes',
'user_friends'
]
},
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID,
{
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
// Whether the display name should be displayed in Sign Up page.
requireDisplayName: true,
signInMethod: getEmailSignInMethod()
},
{
provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
recaptchaParameters: {
size: getRecaptchaMode()
}
},
{
provider: 'microsoft.com',
providerName: 'Microsoft',
buttonColor: '#2F2F2F',
iconUrl: 'https://docs.microsoft.com/en-us/azure/active-directory/develop/media/howto-add-branding-in-azure-ad-apps/ms-symbollockup_mssymbol_19.png',
loginHintKey: 'login_hint'
},
firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
// Terms of service url.
'tosUrl': 'https://www.google.com',
// Privacy policy url.
'privacyPolicyUrl': 'https://www.google.com',
'credentialHelper': CLIENT_ID && CLIENT_ID != 'YOUR_OAUTH_CLIENT_ID' ?
firebaseui.auth.CredentialHelper.GOOGLE_YOLO :
firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM
};
}
|
javascript
|
{
"resource": ""
}
|
q17653
|
train
|
function(authResult, redirectUrl) {
if (authResult.user) {
handleSignedInUser(authResult.user);
}
if (authResult.additionalUserInfo) {
document.getElementById('is-new-user').textContent =
authResult.additionalUserInfo.isNewUser ?
'New User' : 'Existing User';
}
// Do not redirect.
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q17654
|
train
|
function(user) {
document.getElementById('user-signed-in').style.display = 'block';
document.getElementById('user-signed-out').style.display = 'none';
document.getElementById('name').textContent = user.displayName;
document.getElementById('email').textContent = user.email;
document.getElementById('phone').textContent = user.phoneNumber;
if (user.photoURL){
var photoURL = user.photoURL;
// Append size to the photo URL for Google hosted images to avoid requesting
// the image with its original resolution (using more bandwidth than needed)
// when it is going to be presented in smaller size.
if ((photoURL.indexOf('googleusercontent.com') != -1) ||
(photoURL.indexOf('ggpht.com') != -1)) {
photoURL = photoURL + '?sz=' +
document.getElementById('photo').clientHeight;
}
document.getElementById('photo').src = photoURL;
document.getElementById('photo').style.display = 'block';
} else {
document.getElementById('photo').style.display = 'none';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17655
|
train
|
function() {
document.getElementById('user-signed-in').style.display = 'none';
document.getElementById('user-signed-out').style.display = 'block';
ui.start('#firebaseui-container', getUiConfig());
}
|
javascript
|
{
"resource": ""
}
|
|
q17656
|
train
|
function() {
firebase.auth().currentUser.delete().catch(function(error) {
if (error.code == 'auth/requires-recent-login') {
// The user's credential is too old. She needs to sign in again.
firebase.auth().signOut().then(function() {
// The timeout allows the message to be displayed after the UI has
// changed to the signed out state.
setTimeout(function() {
alert('Please sign in again to delete your account.');
}, 1);
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17657
|
handleConfigChange
|
train
|
function handleConfigChange() {
var newRecaptchaValue = document.querySelector(
'input[name="recaptcha"]:checked').value;
var newEmailSignInMethodValue = document.querySelector(
'input[name="emailSignInMethod"]:checked').value;
location.replace(
location.pathname + '#recaptcha=' + newRecaptchaValue +
'&emailSignInMethod=' + newEmailSignInMethodValue);
// Reset the inline widget so the config changes are reflected.
ui.reset();
ui.start('#firebaseui-container', getUiConfig());
}
|
javascript
|
{
"resource": ""
}
|
q17658
|
train
|
function() {
document.getElementById('sign-in-with-redirect').addEventListener(
'click', signInWithRedirect);
document.getElementById('sign-in-with-popup').addEventListener(
'click', signInWithPopup);
document.getElementById('sign-out').addEventListener('click', function() {
firebase.auth().signOut();
});
document.getElementById('delete-account').addEventListener(
'click', function() {
deleteAccount();
});
document.getElementById('recaptcha-normal').addEventListener(
'change', handleConfigChange);
document.getElementById('recaptcha-invisible').addEventListener(
'change', handleConfigChange);
// Check the selected reCAPTCHA mode.
document.querySelector(
'input[name="recaptcha"][value="' + getRecaptchaMode() + '"]')
.checked = true;
document.getElementById('email-signInMethod-password').addEventListener(
'change', handleConfigChange);
document.getElementById('email-signInMethod-emailLink').addEventListener(
'change', handleConfigChange);
// Check the selected email signInMethod mode.
document.querySelector(
'input[name="emailSignInMethod"][value="' + getEmailSignInMethod() + '"]')
.checked = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q17659
|
train
|
function() {
var email = component.checkAndGetEmail();
if (!email) {
component.getEmailElement().focus();
return;
}
component.dispose();
onContinue(app, container, email, link);
}
|
javascript
|
{
"resource": ""
}
|
|
q17660
|
train
|
function() {
component.dispose();
// Render previous phone sign in start page.
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app,
container, phoneNumberValue);
}
|
javascript
|
{
"resource": ""
}
|
|
q17661
|
train
|
function(userCredential) {
component.dismissDialog();
// Show code verified dialog.
component.showProgressDialog(
firebaseui.auth.ui.element.progressDialog.State.DONE,
firebaseui.auth.soy2.strings.dialogCodeVerified().toString());
// Keep on display for long enough to be seen.
var codeVerifiedTimer = setTimeout(function() {
// Dismiss dialog and dispose of component before completing sign-in.
component.dismissDialog();
component.dispose();
var authResult = /** @type {!firebaseui.auth.AuthResult} */ ({
// User already signed on external instance.
'user': app.getExternalAuth().currentUser,
// Phone Auth operations do not return a credential.
'credential': null,
'operationType': userCredential['operationType'],
'additionalUserInfo': userCredential['additionalUserInfo']
});
firebaseui.auth.widget.handler.common.setLoggedInWithAuthResult(
app, component, authResult, true);
}, firebaseui.auth.widget.handler.CODE_SUCCESS_DIALOG_DELAY);
// On reset, clear timeout.
app.registerPending(function() {
// Dismiss dialog if still visible.
if (component) {
component.dismissDialog();
}
clearTimeout(codeVerifiedTimer);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17662
|
train
|
function(error) {
if (error['name'] && error['name'] == 'cancel') {
// Close dialog.
component.dismissDialog();
return;
}
// Get error message.
var errorMessage =
firebaseui.auth.widget.handler.common.getErrorMessage(error);
// Some errors are recoverable while others require resending the code.
switch (error['code']) {
case 'auth/credential-already-in-use':
// Do nothing when anonymous user is getting upgraded.
// Developer should handle this in signInFailure callback.
component.dismissDialog();
break;
case 'auth/code-expired':
// Expired code requires sending another request.
// Render previous phone sign in start page and display error in
// the info bar.
var container = component.getContainer();
// Close dialog.
component.dismissDialog();
component.dispose();
firebaseui.auth.widget.handler.handle(
firebaseui.auth.widget.HandlerName.PHONE_SIGN_IN_START, app,
container, phoneNumberValue, errorMessage);
break;
case 'auth/missing-verification-code':
case 'auth/invalid-verification-code':
// Close dialog.
component.dismissDialog();
// As these errors are related to the code provided, it is better
// to display inline.
showInvalidCode(errorMessage);
break;
default:
// Close dialog.
component.dismissDialog();
// Stay on the same page for all other errors and display error in
// info bar.
component.showInfoBar(errorMessage);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17663
|
markChangesSweep
|
train
|
function markChangesSweep(drafts) {
// The natural order of drafts in the `scope` array is based on when they
// were accessed. By processing drafts in reverse natural order, we have a
// better chance of processing leaf nodes first. When a leaf node is known to
// have changed, we can avoid any traversal of its ancestor nodes.
for (let i = drafts.length - 1; i >= 0; i--) {
const state = drafts[i][DRAFT_STATE]
if (!state.modified) {
if (Array.isArray(state.base)) {
if (hasArrayChanges(state)) markChanged(state)
} else if (hasObjectChanges(state)) markChanged(state)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17664
|
clone
|
train
|
function clone (obj, parent) {
let cloned = new obj.constructor()
for (let i of Object.keys(obj || {})) {
let value = obj[i]
if (i === 'parent' && typeof value === 'object') {
if (parent) {
cloned[i] = parent
}
} else if (i === 'source' || i === null) {
cloned[i] = value
} else if (value instanceof Array) {
cloned[i] = value.map(x => clone(x, cloned))
} else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') {
if (typeof value === 'object' && value !== null) {
value = clone(value, cloned)
}
cloned[i] = value
}
}
return cloned
}
|
javascript
|
{
"resource": ""
}
|
q17665
|
f
|
train
|
function f (data, opts, callback) {
data = unpack(data)
if (!callback) {
[callback, opts] = [opts, {}]
}
let match = opts.match || /\sx($|\s)/
let need = []
for (let browser in data.stats) {
let versions = data.stats[browser]
for (let version in versions) {
let support = versions[version]
if (support.match(match)) {
need.push(browser + ' ' + version)
}
}
}
callback(need.sort(browsersSort))
}
|
javascript
|
{
"resource": ""
}
|
q17666
|
getMSDecls
|
train
|
function getMSDecls (area, addRowSpan = false, addColumnSpan = false) {
return [].concat(
{
prop: '-ms-grid-row',
value: String(area.row.start)
},
(area.row.span > 1 || addRowSpan) ? {
prop: '-ms-grid-row-span',
value: String(area.row.span)
} : [],
{
prop: '-ms-grid-column',
value: String(area.column.start)
},
(area.column.span > 1 || addColumnSpan) ? {
prop: '-ms-grid-column-span',
value: String(area.column.span)
} : []
)
}
|
javascript
|
{
"resource": ""
}
|
q17667
|
changeDuplicateAreaSelectors
|
train
|
function changeDuplicateAreaSelectors (ruleSelectors, templateSelectors) {
ruleSelectors = ruleSelectors.map(selector => {
let selectorBySpace = list.space(selector)
let selectorByComma = list.comma(selector)
if (selectorBySpace.length > selectorByComma.length) {
selector = selectorBySpace.slice(-1).join('')
}
return selector
})
return ruleSelectors.map(ruleSelector => {
let newSelector = templateSelectors.map((tplSelector, index) => {
let space = index === 0 ? '' : ' '
return `${ space }${ tplSelector } > ${ ruleSelector }`
})
return newSelector
})
}
|
javascript
|
{
"resource": ""
}
|
q17668
|
selectorsEqual
|
train
|
function selectorsEqual (ruleA, ruleB) {
return ruleA.selectors.some(sel => {
return ruleB.selectors.some(s => s === sel)
})
}
|
javascript
|
{
"resource": ""
}
|
q17669
|
warnMissedAreas
|
train
|
function warnMissedAreas (areas, decl, result) {
let missed = Object.keys(areas)
decl.root().walkDecls('grid-area', gridArea => {
missed = missed.filter(e => e !== gridArea.value)
})
if (missed.length > 0) {
decl.warn(result, 'Can not find grid areas: ' + missed.join(', '))
}
return undefined
}
|
javascript
|
{
"resource": ""
}
|
q17670
|
shouldInheritGap
|
train
|
function shouldInheritGap (selA, selB) {
let result
// get arrays of selector split in 3-deep array
let splitSelectorArrA = splitSelector(selA)
let splitSelectorArrB = splitSelector(selB)
if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) {
// abort if selectorA has lower descendant specificity then selectorB
// (e.g '.grid' and '.hello .world .grid')
return false
} else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) {
// if selectorA has higher descendant specificity then selectorB
// (e.g '.foo .bar .grid' and '.grid')
let idx = splitSelectorArrA[0].reduce((res, [item], index) => {
let firstSelectorPart = splitSelectorArrB[0][0][0]
if (item === firstSelectorPart) {
return index
}
return false
}, false)
if (idx) {
result = splitSelectorArrB[0].every((arr, index) => {
return arr.every((part, innerIndex) =>
// because selectorA has more space elements, we need to slice
// selectorA array by 'idx' number to compare them
splitSelectorArrA[0].slice(idx)[index][innerIndex] === part)
})
}
} else {
// if selectorA has the same descendant specificity as selectorB
// this condition covers cases such as: '.grid.foo.bar' and '.grid'
result = splitSelectorArrB.some(byCommaArr => {
return byCommaArr.every((bySpaceArr, index) => {
return bySpaceArr.every(
(part, innerIndex) => splitSelectorArrA[0][index][innerIndex] === part
)
})
})
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q17671
|
inheritGridGap
|
train
|
function inheritGridGap (decl, gap) {
let rule = decl.parent
let mediaRule = getParentMedia(rule)
let root = rule.root()
// get an array of selector split in 3-deep array
let splitSelectorArr = splitSelector(rule.selector)
// abort if the rule already has gaps
if (Object.keys(gap).length > 0) {
return false
}
// e.g ['min-width']
let [prop] = parseMediaParams(mediaRule.params)
let lastBySpace = splitSelectorArr[0]
// get escaped value from the selector
// if we have '.grid-2.foo.bar' selector, will be '\.grid\-2'
let escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0])
let regexp = new RegExp(`(${ escaped }$)|(${ escaped }[,.])`)
// find the closest rule with the same selector
let closestRuleGap
root.walkRules(regexp, r => {
let gridGap
// abort if are checking the same rule
if (rule.toString() === r.toString()) {
return false
}
// find grid-gap values
r.walkDecls('grid-gap', d => (gridGap = getGridGap(d)))
// skip rule without gaps
if (!gridGap || Object.keys(gridGap).length === 0) {
return true
}
// skip rules that should not be inherited from
if (!shouldInheritGap(rule.selector, r.selector)) {
return true
}
let media = getParentMedia(r)
if (media) {
// if we are inside media, we need to check that media props match
// e.g ('min-width' === 'min-width')
let propToCompare = parseMediaParams(media.params)[0]
if (propToCompare === prop) {
closestRuleGap = gridGap
return true
}
} else {
closestRuleGap = gridGap
return true
}
return undefined
})
// if we find the closest gap object
if (closestRuleGap && Object.keys(closestRuleGap).length > 0) {
return closestRuleGap
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q17672
|
autoplaceGridItems
|
train
|
function autoplaceGridItems (decl, result, gap, autoflowValue = 'row') {
let { parent } = decl
let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows')
let rows = normalizeRowColumn(rowDecl.value)
let columns = normalizeRowColumn(decl.value)
// Build array of area names with dummy values. If we have 3 columns and
// 2 rows, filledRows will be equal to ['1 2 3', '4 5 6']
let filledRows = rows.map((_, rowIndex) => {
return Array.from({ length: columns.length }, (v, k) =>
k + (rowIndex * columns.length) + 1).join(' ')
})
let areas = parseGridAreas({ rows: filledRows, gap })
let keys = Object.keys(areas)
let items = keys.map(i => areas[i])
// Change the order of cells if grid-auto-flow value is 'column'
if (autoflowValue.includes('column')) {
items = items.sort((a, b) => a.column.start - b.column.start)
}
// Insert new rules
items.reverse().forEach((item, index) => {
let { column, row } = item
let nodeSelector = parent.selectors.map(sel =>
sel + ` > *:nth-child(${ keys.length - index })`).join(', ')
// create new rule
let node = parent.clone().removeAll()
// change rule selector
node.selector = nodeSelector
// insert prefixed row/column values
node.append({ prop: '-ms-grid-row', value: row.start })
node.append({ prop: '-ms-grid-column', value: column.start })
// insert rule
parent.after(node)
})
return undefined
}
|
javascript
|
{
"resource": ""
}
|
q17673
|
substitutePreCodeTags
|
train
|
function substitutePreCodeTags (doc) {
var pres = doc.querySelectorAll('pre'),
presPH = [];
for (var i = 0; i < pres.length; ++i) {
if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {
var content = pres[i].firstChild.innerHTML.trim(),
language = pres[i].firstChild.getAttribute('data-language') || '';
// if data-language attribute is not defined, then we look for class language-*
if (language === '') {
var classes = pres[i].firstChild.className.split(' ');
for (var c = 0; c < classes.length; ++c) {
var matches = classes[c].match(/^language-(.+)$/);
if (matches !== null) {
language = matches[1];
break;
}
}
}
// unescape html entities in content
content = showdown.helper.unescapeHTMLEntities(content);
presPH.push(content);
pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>';
} else {
presPH.push(pres[i].innerHTML);
pres[i].innerHTML = '';
pres[i].setAttribute('prenum', i.toString());
}
}
return presPH;
}
|
javascript
|
{
"resource": ""
}
|
q17674
|
train
|
function() {
return new Promise(function(resolve, reject) {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken().then(function(idToken) {
resolve(idToken);
}, function(error) {
resolve(null);
});
} else {
resolve(null);
}
});
}).catch(function(error) {
console.log(error);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17675
|
runTypedoc
|
train
|
function runTypedoc() {
const typeSource = apiType === 'node' ? tempNodeSourcePath : sourceFile;
const command = `${repoPath}/node_modules/.bin/typedoc ${typeSource} \
--out ${docPath} \
--readme ${tempHomePath} \
--options ${__dirname}/typedoc.js \
--theme ${__dirname}/theme`;
console.log('Running command:\n', command);
return exec(command);
}
|
javascript
|
{
"resource": ""
}
|
q17676
|
moveFilesToRoot
|
train
|
function moveFilesToRoot(subdir) {
return exec(`mv ${docPath}/${subdir}/* ${docPath}`)
.then(() => {
exec(`rmdir ${docPath}/${subdir}`);
})
.catch(e => console.error(e));
}
|
javascript
|
{
"resource": ""
}
|
q17677
|
fixLinks
|
train
|
function fixLinks(file) {
return fs.readFile(file, 'utf8').then(data => {
const flattenedLinks = data
.replace(/\.\.\//g, '')
.replace(/(modules|interfaces|classes)\//g, '');
let caseFixedLinks = flattenedLinks;
for (const lower in lowerToUpperLookup) {
const re = new RegExp(lower, 'g');
caseFixedLinks = caseFixedLinks.replace(re, lowerToUpperLookup[lower]);
}
return fs.writeFile(file, caseFixedLinks);
});
}
|
javascript
|
{
"resource": ""
}
|
q17678
|
generateTempHomeMdFile
|
train
|
function generateTempHomeMdFile(tocRaw, homeRaw) {
const { toc } = yaml.safeLoad(tocRaw);
let tocPageLines = [homeRaw, '# API Reference'];
toc.forEach(group => {
tocPageLines.push(`\n## [${group.title}](${stripPath(group.path)}.html)`);
group.section.forEach(item => {
tocPageLines.push(`- [${item.title}](${stripPath(item.path)}.html)`);
});
});
return fs.writeFile(tempHomePath, tocPageLines.join('\n'));
}
|
javascript
|
{
"resource": ""
}
|
q17679
|
checkForMissingFilesAndFixFilenameCase
|
train
|
function checkForMissingFilesAndFixFilenameCase() {
// Get filenames from toc.yaml.
const filenames = tocText
.split('\n')
.filter(line => line.includes('path:'))
.map(line => line.split(devsitePath)[1]);
// Logs warning to console if a file from TOC is not found.
const fileCheckPromises = filenames.map(filename => {
// Warns if file does not exist, fixes filename case if it does.
// Preferred filename for devsite should be capitalized and taken from
// toc.yaml.
const tocFilePath = `${docPath}/${filename}.html`;
// Generated filename from Typedoc will be lowercase.
const generatedFilePath = `${docPath}/${filename.toLowerCase()}.html`;
return fs.exists(generatedFilePath).then(exists => {
if (exists) {
// Store in a lookup table for link fixing.
lowerToUpperLookup[
`${filename.toLowerCase()}.html`
] = `${filename}.html`;
return fs.rename(generatedFilePath, tocFilePath);
} else {
console.warn(
`Missing file: ${filename}.html requested ` +
`in toc.yaml but not found in ${docPath}`
);
}
});
});
return Promise.all(fileCheckPromises).then(() => filenames);
}
|
javascript
|
{
"resource": ""
}
|
q17680
|
writeGeneratedFileList
|
train
|
function writeGeneratedFileList(htmlFiles) {
const fileList = htmlFiles.map(filename => {
return {
title: filename,
path: `${devsitePath}${filename}`
};
});
const generatedTocYAML = yaml.safeDump({ toc: fileList });
return fs
.writeFile(`${docPath}/_toc_autogenerated.yaml`, generatedTocYAML)
.then(() => htmlFiles);
}
|
javascript
|
{
"resource": ""
}
|
q17681
|
fixAllLinks
|
train
|
function fixAllLinks(htmlFiles) {
const writePromises = [];
htmlFiles.forEach(file => {
// Update links in each html file to match flattened file structure.
writePromises.push(fixLinks(`${docPath}/${file}.html`));
});
return Promise.all(writePromises);
}
|
javascript
|
{
"resource": ""
}
|
q17682
|
generateNodeSource
|
train
|
async function generateNodeSource() {
const sourceText = await fs.readFile(sourceFile, 'utf8');
// Parse index.d.ts. A dummy filename is required but it doesn't create a
// file.
let typescriptSourceFile = typescript.createSourceFile(
'temp.d.ts',
sourceText,
typescript.ScriptTarget.ES2015,
/*setParentNodes */ false
);
/**
* Typescript transformer function. Removes nodes tagged with @webonly.
*/
const removeWebOnlyNodes = context => rootNode => {
function visit(node) {
if (
node.jsDoc &&
node.jsDoc.some(
item =>
item.tags &&
item.tags.some(tag => tag.tagName.escapedText === 'webonly')
)
) {
return null;
}
return typescript.visitEachChild(node, visit, context);
}
return typescript.visitNode(rootNode, visit);
};
// Use above transformer on source AST to remove nodes tagged with @webonly.
const result = typescript.transform(typescriptSourceFile, [
removeWebOnlyNodes
]);
// Convert transformed AST to text and write to file.
const printer = typescript.createPrinter();
return fs.writeFile(
tempNodeSourcePath,
printer.printFile(result.transformed[0])
);
}
|
javascript
|
{
"resource": ""
}
|
q17683
|
train
|
function() {
// Remove current resume listener.
if (onResume) {
doc.removeEventListener('resume', onResume, false);
}
// Remove visibility change listener.
if (onVisibilityChange) {
doc.removeEventListener('visibilitychange', onVisibilityChange, false);
}
// Cancel onClose promise if not already cancelled.
if (onClose) {
onClose.cancel();
}
// Remove Auth event callback.
if (authEventCallback) {
self.removeAuthEventListener(authEventCallback);
}
// Clear any pending redirect now that it is completed.
self.pendingRedirect_ = null;
}
|
javascript
|
{
"resource": ""
}
|
|
q17684
|
train
|
function(eventData) {
initialResolve = true;
// Cancel no event timer.
if (noEventTimer) {
noEventTimer.cancel();
}
// Incoming link detected.
// Check for any stored partial event.
self.getPartialStoredEvent_().then(function(event) {
// Initialize to an unknown event.
var authEvent = noEvent;
// Confirm OAuth response included.
if (event && eventData && eventData['url']) {
// Construct complete event. Default to unknown event if none found.
authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) ||
noEvent;
}
// Dispatch Auth event.
self.dispatchEvent_(authEvent);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q17685
|
train
|
function() {
// Get time until expiration minus the refresh offset.
var waitInterval =
self.stsTokenManager_.getExpirationTime() - goog.now() -
fireauth.TokenRefreshTime.OFFSET_DURATION;
// Set to zero if wait interval is negative.
return waitInterval > 0 ? waitInterval : 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q17686
|
logAtLevel_
|
train
|
function logAtLevel_(message, level) {
if (message != null) {
var messageDiv = $('<div></div>');
messageDiv.addClass(level);
if (typeof message === 'object') {
messageDiv.text(JSON.stringify(message, null, ' '));
} else {
messageDiv.text(message);
}
$('.logs').append(messageDiv);
}
console[level](message);
}
|
javascript
|
{
"resource": ""
}
|
q17687
|
alertMessage_
|
train
|
function alertMessage_(message, cssClass) {
var alertBox = $('<div></div>')
.addClass(cssClass)
.css('display', 'none')
.text(message);
$('#alert-messages').prepend(alertBox);
alertBox.fadeIn({
complete: function() {
setTimeout(function() {
alertBox.slideUp();
}, 3000);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q17688
|
refreshUserData
|
train
|
function refreshUserData() {
if (activeUser()) {
var user = activeUser();
$('.profile').show();
$('body').addClass('user-info-displayed');
$('div.profile-email,span.profile-email').text(user.email || 'No Email');
$('div.profile-phone,span.profile-phone')
.text(user.phoneNumber || 'No Phone');
$('div.profile-uid,span.profile-uid').text(user.uid);
$('div.profile-name,span.profile-name').text(user.displayName || 'No Name');
$('input.profile-name').val(user.displayName);
$('input.photo-url').val(user.photoURL);
if (user.photoURL != null) {
var photoURL = user.photoURL;
// Append size to the photo URL for Google hosted images to avoid requesting
// the image with its original resolution (using more bandwidth than needed)
// when it is going to be presented in smaller size.
if ((photoURL.indexOf('googleusercontent.com') != -1) ||
(photoURL.indexOf('ggpht.com') != -1)) {
photoURL = photoURL + '?sz=' + $('img.profile-image').height();
}
$('img.profile-image').attr('src', photoURL).show();
} else {
$('img.profile-image').hide();
}
$('.profile-email-verified').toggle(user.emailVerified);
$('.profile-email-not-verified').toggle(!user.emailVerified);
$('.profile-anonymous').toggle(user.isAnonymous);
// Display/Hide providers icons.
$('.profile-providers').empty();
if (user['providerData'] && user['providerData'].length) {
var providersCount = user['providerData'].length;
for (var i = 0; i < providersCount; i++) {
addProviderIcon(user['providerData'][i]['providerId']);
}
}
// Change color.
if (user == auth.currentUser) {
$('#user-info').removeClass('last-user');
$('#user-info').addClass('current-user');
} else {
$('#user-info').removeClass('current-user');
$('#user-info').addClass('last-user');
}
} else {
$('.profile').slideUp();
$('body').removeClass('user-info-displayed');
$('input.profile-data').val('');
}
}
|
javascript
|
{
"resource": ""
}
|
q17689
|
addProviderIcon
|
train
|
function addProviderIcon(providerId) {
var pElt = $('<i>').addClass('fa ' + providersIcons[providerId])
.attr('title', providerId)
.data({
'toggle': 'tooltip',
'placement': 'bottom'
});
$('.profile-providers').append(pElt);
pElt.tooltip();
}
|
javascript
|
{
"resource": ""
}
|
q17690
|
onSetLanguageCode
|
train
|
function onSetLanguageCode() {
var languageCode = $('#language-code').val() || null;
try {
auth.languageCode = languageCode;
alertSuccess('Language code changed to "' + languageCode + '".');
} catch (error) {
alertError('Error: ' + error.code);
}
}
|
javascript
|
{
"resource": ""
}
|
q17691
|
onSetPersistence
|
train
|
function onSetPersistence() {
var type = $('#persistence-type').val();
try {
auth.setPersistence(type).then(function() {
log('Persistence state change to "' + type + '".');
alertSuccess('Persistence state change to "' + type + '".');
}, function(error) {
alertError('Error: ' + error.code);
});
} catch (error) {
alertError('Error: ' + error.code);
}
}
|
javascript
|
{
"resource": ""
}
|
q17692
|
onSignUp
|
train
|
function onSignUp() {
var email = $('#signup-email').val();
var password = $('#signup-password').val();
auth.createUserWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17693
|
onSignInWithEmailAndPassword
|
train
|
function onSignInWithEmailAndPassword() {
var email = $('#signin-email').val();
var password = $('#signin-password').val();
auth.signInWithEmailAndPassword(email, password)
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17694
|
onSignInWithEmailLink
|
train
|
function onSignInWithEmailLink() {
var email = $('#sign-in-with-email-link-email').val();
var link = $('#sign-in-with-email-link-link').val() || undefined;
if (auth.isSignInWithEmailLink(link)) {
auth.signInWithEmailLink(email, link).then(onAuthSuccess, onAuthError);
} else {
alertError('Sign in link is invalid');
}
}
|
javascript
|
{
"resource": ""
}
|
q17695
|
onLinkWithEmailLink
|
train
|
function onLinkWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().linkWithCredential(credential)
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17696
|
onReauthenticateWithEmailLink
|
train
|
function onReauthenticateWithEmailLink() {
var email = $('#link-with-email-link-email').val();
var link = $('#link-with-email-link-link').val() || undefined;
var credential = firebase.auth.EmailAuthProvider
.credentialWithLink(email, link);
activeUser().reauthenticateWithCredential(credential)
.then(function(result) {
logAdditionalUserInfo(result);
refreshUserData();
alertSuccess('User reauthenticated!');
}, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17697
|
onSignInWithCustomToken
|
train
|
function onSignInWithCustomToken(event) {
// The token can be directly specified on the html element.
var token = $('#user-custom-token').val();
auth.signInWithCustomToken(token)
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17698
|
onSignInWithGenericIdPCredential
|
train
|
function onSignInWithGenericIdPCredential() {
var providerId = $('#signin-generic-idp-provider-id').val();
var idToken = $('#signin-generic-idp-id-token').val();
var accessToken = $('#signin-generic-idp-access-token').val();
var provider = new firebase.auth.OAuthProvider(providerId);
auth.signInWithCredential(
provider.credential(idToken, accessToken))
.then(onAuthUserCredentialSuccess, onAuthError);
}
|
javascript
|
{
"resource": ""
}
|
q17699
|
makeApplicationVerifier
|
train
|
function makeApplicationVerifier(submitButtonId) {
var container = recaptchaSize === 'invisible' ?
submitButtonId :
'recaptcha-container';
applicationVerifier = new firebase.auth.RecaptchaVerifier(container,
{'size': recaptchaSize});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.