_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q59000
initProcessor
validation
function initProcessor(options = {}, defaultBabelProcessorName) { let {js, css, tpl, wxs} = options; if (tpl !== false) { initTplProcessor(tpl); } if (css !== false) { initStyleProcessor(css); } if (js !== false) { initJsProcessor(js, defaultBabelProcessorName); } if (wxs !== false) { initWxsProcessor(js, defaultBabelProcessorName); } }
javascript
{ "resource": "" }
q59001
process
validation
function process(file, options) { let content = file.content.toString(); let {config: rules, logger} = options; let result = content; try { result = doReplacement(content, rules || [], file); } catch (ex) { let tip; if (ex === 'devServer') { tip = ', please execute `npm run dev:server` script or start with `--server` option'; } logger.error('unknown replacement variable:', ex + (tip || '')); } return { content: result }; }
javascript
{ "resource": "" }
q59002
convertMediaQueryToJSExpression
validation
function convertMediaQueryToJSExpression(tokens, allAppTypes, appType) { let result = []; tokens.forEach(item => { item = item.trim(); if (allAppTypes.includes(item)) { result.push(`('${item}' === '${appType}')`); } else if (item === 'and') { result.push('&&'); } else if (item === ',' || item === 'or') { result.push('||'); } else if (item === 'not') { result.push('!'); } else if (item === '(' || item === ')') { result.push(item); } }); let lastItem = result[result.length - 1]; if (lastItem === '&&' || lastItem === '||') { result.pop(); } // remove no use leading brace if has let braceStack = []; result.forEach((item, index) => { if (item === '(') { braceStack.push(index); } else if (item === ')') { braceStack.pop(); } }); for (let i = braceStack.length - 1; i >= 0; i--) { result.splice(braceStack[i], 1); } return result.join(''); }
javascript
{ "resource": "" }
q59003
isAppMediaMatch
validation
function isAppMediaMatch(params, tokens, allAppTypes, appType) { let expression = convertMediaQueryToJSExpression(tokens, allAppTypes, appType); try { return { /* eslint-disable fecs-no-eval */ value: eval(expression), expression }; } catch (ex) { throw new Error('illegal style env media rule:' + params); } }
javascript
{ "resource": "" }
q59004
normalizeAppMediaQueryTokens
validation
function normalizeAppMediaQueryTokens(tokens) { for (let i = tokens.length - 1; i >= 0; i--) { let item = tokens[i].trim(); if (item && item !== '(') { break; } tokens.pop(); } }
javascript
{ "resource": "" }
q59005
initAppMediaTargetInfo
validation
function initAppMediaTargetInfo(ctx, currToken) { let {allAppTypes, hasAppMediaType} = ctx; let isAppMediaTarget = allAppTypes.includes(currToken); hasAppMediaType || (ctx.hasAppMediaType = isAppMediaTarget); if (!isAppMediaTarget && !MEDIA_QUERY_OPERATORS.includes(currToken)) { return true; } return false; }
javascript
{ "resource": "" }
q59006
initAppMediaQueryToken
validation
function initAppMediaQueryToken(ctx, buffer, separator) { let currToken = buffer.trim(); let {tokens} = ctx; if (currToken) { if (initAppMediaTargetInfo(ctx, currToken)) { return true; } tokens.push(buffer); tokens.push(separator); return ''; } buffer += separator; if (buffer.trim()) { tokens.push(buffer); return ''; } return buffer; }
javascript
{ "resource": "" }
q59007
parseAppMediaQueryParam
validation
function parseAppMediaQueryParam(allAppTypes, params) { let ctx = { allAppTypes, hasAppMediaType: false, tokens: [] }; let buffer = ''; for (let i = 0, len = params.length; i < len; i++) { let c = params[i]; if (QUERY_PARAMS_SEPARATORS.includes(c)) { buffer = initAppMediaQueryToken(ctx, buffer, c); if (buffer === true) { buffer = ''; break; } } else { buffer += c; } } if (buffer) { let result = initAppMediaTargetInfo(ctx, buffer.trim()); result || (ctx.tokens.push(buffer)); } return ctx; }
javascript
{ "resource": "" }
q59008
compilePug
validation
function compilePug(file, options) { let content = file.content.toString(); // 取出用于pug模板的配置项,包括渲染所需的数据(data字段) let config = options.config || {}; // 考虑到给之后的处理器传递数据,所以这里强制 pretty 为true config.pretty = true; let data = config.data; delete config.data; let fn = pug.compile(content, config); content = fn(data); return { content }; }
javascript
{ "resource": "" }
q59009
initJsProcessor
validation
function initJsProcessor(opts, defaultBabelProcessorName) { let plugins = (opts && opts.plugins) || [adapterPlugin]; registerProcessor({ name: (opts && opts.processor) || defaultBabelProcessorName, // override existed processor hook: { before(file, options) { if (file.isAntCompScript && !adapterPlugin.isAdapterModule(file.path)) { options.plugins || (options.plugins = []); options.plugins.push.apply(options.plugins, plugins); } } } }); }
javascript
{ "resource": "" }
q59010
initProcessor
validation
function initProcessor(options = {}, defaultBabelProcessorName) { let {js} = options; if (js !== false) { initJsProcessor(js, defaultBabelProcessorName); } }
javascript
{ "resource": "" }
q59011
confirm
validation
function confirm(params) { params = _.extend({ text: 'Are you sure?', yesText: 'Yes', yesClass: 'btn-danger', noText: 'Cancel', escapedHtml: false, msgConfirmation: false, additionalText: '', name: '' }, params); $('#g-dialog-container').html(ConfirmDialogTemplate({ params: params })).girderModal(false).one('hidden.bs.modal', function () { $('#g-confirm-button').off('click'); }); const el = $('#g-dialog-container').find('.modal-body>p:first-child'); if (params.escapedHtml) { el.html(params.text); } else { el.text(params.text); } if (params['msgConfirmation']) { if (params.escapedHtml) { $('.g-additional-text').html(params.additionalText); } else { $('.g-additional-text').text(params.additionalText); } } $('#g-confirm-button').off('click').click(function () { if (params['msgConfirmation']) { const key = `${params.yesText.toUpperCase()} ${params.name}`; const msg = $('#g-confirm-text').val(); if (msg.toUpperCase() === key.toUpperCase()) { $('#g-dialog-container').modal('hide'); params.confirmCallback(); } else if (msg.toUpperCase() === '') { $('.g-msg-error').html(`Error: You need to enter <b>'${key}'</b>.`); $('.g-msg-error').css('color', 'red'); } else { $('.g-msg-error').html(`Error: <b>'${msg}'</b> isn't <b>'${key}'</b>`); $('.g-msg-error').css('color', 'red'); } } else { $('#g-dialog-container').modal('hide'); params.confirmCallback(); } }); }
javascript
{ "resource": "" }
q59012
wrap
validation
function wrap(obj, funcName, wrapper) { obj.prototype[funcName] = _.wrap(obj.prototype[funcName], wrapper); }
javascript
{ "resource": "" }
q59013
validation
function (opts) { opts = opts || {}; const defaults = { // the default 'method' is 'GET', as set by 'jquery.ajax' girderToken: getCurrentToken() || cookie.find('girderToken'), error: (error, status) => { let info; if (error.status === 401) { events.trigger('g:loginUi'); info = { text: 'You must log in to view this resource', type: 'warning', timeout: 4000, icon: 'info' }; } else if (error.status === 403) { info = { text: 'Access denied. See the console for more details.', type: 'danger', timeout: 5000, icon: 'attention' }; } else if (error.status === 0 && error.statusText === 'abort') { /* We expected this abort, so do nothing. */ return; } else if (error.status === 500 && error.responseJSON && error.responseJSON.type === 'girder') { info = { text: error.responseJSON.message, type: 'warning', timeout: 5000, icon: 'info' }; } else if (status === 'parsererror') { info = { text: 'A parser error occurred while communicating with the ' + 'server (did you use the correct value for `dataType`?). ' + 'Details have been logged in the console.', type: 'danger', timeout: 5000, icon: 'attention' }; } else { info = { text: 'An error occurred while communicating with the ' + 'server. Details have been logged in the console.', type: 'danger', timeout: 5000, icon: 'attention' }; } events.trigger('g:alert', info); console.error(error.status + ' ' + error.statusText, error.responseText); } }; // Overwrite defaults with passed opts, but do not mutate opts const args = _.extend({}, defaults, opts); if (!args.url) { throw new Error('restRequest requires a "url" argument'); } args.url = `${getApiRoot()}${args.url.substring(0, 1) === '/' ? '' : '/'}${args.url}`; if (args.girderToken) { args.headers = args.headers || {}; args.headers['Girder-Token'] = args.girderToken; delete args.girderToken; } return Backbone.$.ajax(args); }
javascript
{ "resource": "" }
q59014
sortOperations
validation
function sortOperations(op1, op2) { var pathCmp = op1.path.localeCompare(op2.path); if (pathCmp !== 0) { return pathCmp; } var index1 = methodOrder.indexOf(op1.method); var index2 = methodOrder.indexOf(op2.method); if (index1 > -1 && index2 > -1) { return index1 > index2 ? 1 : (index1 < index2 ? -1 : 0); } if (index1 > -1) { return -1; } if (index2 > -1) { return 1; } return op1.method.localeCompare(op2.method); }
javascript
{ "resource": "" }
q59015
formatDate
validation
function formatDate(datestr, resolution) { datestr = datestr.replace(' ', 'T'); // Cross-browser accepted date format var date = new Date(datestr); var output = MONTHS[date.getMonth()]; resolution = resolution || DATE_MONTH; if (resolution >= DATE_DAY) { output += ' ' + date.getDate() + ','; } output += ' ' + date.getFullYear(); if (resolution >= DATE_MINUTE) { output += ' at ' + date.getHours() + ':' + ('0' + date.getMinutes()).slice(-2); } if (resolution >= DATE_SECOND) { output += ':' + ('0' + date.getSeconds()).slice(-2); } return output; }
javascript
{ "resource": "" }
q59016
formatSize
validation
function formatSize(sizeBytes) { if (sizeBytes < 1024) { return sizeBytes + ' B'; } var i, sizeVal = sizeBytes, precision = 1; for (i = 0; sizeVal >= 1024; i += 1) { sizeVal /= 1024; } // If we are just reporting a low number, no need for decimal places. if (sizeVal < 10) { precision = 3; } else if (sizeVal < 100) { precision = 2; } return sizeVal.toFixed(precision) + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][Math.min(i, 4)]; }
javascript
{ "resource": "" }
q59017
formatCount
validation
function formatCount(n, opts) { n = n || 0; opts = opts || {}; var i = 0, base = opts.base || 1000, sep = opts.sep || '', maxLen = opts.maxLen || 3, precision = maxLen - 1; for (; n > base; i += 1) { n /= base; } if (!i) { precision = 0; } else if (n > 100) { precision -= 2; } else if (n > 10) { precision -= 1; } return n.toFixed(Math.max(0, precision)) + sep + ['', 'k', 'M', 'G', 'T'][Math.min(i, 4)]; }
javascript
{ "resource": "" }
q59018
localeComparator
validation
function localeComparator(model1, model2) { var a1 = model1.get(this.sortField), a2 = model2.get(this.sortField); if (a1 !== undefined && a1.localeCompare) { var result = a1.localeCompare(a2) * this.sortDir; if (result || !this.secondarySortField) { return result; } a1 = model1.get(this.secondarySortField); a2 = model2.get(this.secondarySortField); return a1.localeCompare(a2) * this.sortDir; } return a1 > a2 ? this.sortDir : (a1 < a2 ? -this.sortDir : 0); }
javascript
{ "resource": "" }
q59019
localeSort
validation
function localeSort(a1, a2) { if (a1 !== undefined && a1.localeCompare) { return a1.localeCompare(a2); } return a1 > a2 ? 1 : (a1 < a2 ? -1 : 0); }
javascript
{ "resource": "" }
q59020
addFile
validation
function addFile(filename) { var file = zip.addFile(filename); var sha = new SHAWriteStream(manifest, filename, file); return sha; }
javascript
{ "resource": "" }
q59021
signManifest
validation
function signManifest(template, manifest, callback) { var identifier = template.passTypeIdentifier().replace(/^pass./, ""); var args = [ "smime", "-sign", "-binary", "-signer", Path.resolve(template.keysPath, identifier + ".pem"), "-certfile", Path.resolve(template.keysPath, "wwdr.pem"), "-passin", "pass:" + template.password ]; var sign = execFile("openssl", args, { stdio: "pipe" }, function(error, stdout, stderr) { var trimmedStderr = stderr.trim(); // Windows outputs some unhelpful error messages, but still produces a valid signature if (error || (trimmedStderr && trimmedStderr.indexOf('- done') < 0)) { callback(new Error(stderr)); } else { var signature = stdout.split(/(\r\n|\n\n)/)[3]; callback(null, Buffer.from(signature, "base64")); } }); sign.stdin.write(manifest); sign.stdin.end(); }
javascript
{ "resource": "" }
q59022
cloneObject
validation
function cloneObject(object) { var clone = {}; if (object) { for (var key in object) clone[key] = object[key]; } return clone; }
javascript
{ "resource": "" }
q59023
nanoRemainder
validation
function nanoRemainder(msFloat) { var modulo = 1e6; var remainder = (msFloat * 1e6) % modulo; var positiveRemainder = remainder < 0 ? remainder + modulo : remainder; return Math.floor(positiveRemainder); }
javascript
{ "resource": "" }
q59024
getEpoch
validation
function getEpoch(epoch) { if (!epoch) { return 0; } if (typeof epoch.getTime === "function") { return epoch.getTime(); } if (typeof epoch === "number") { return epoch; } throw new TypeError("now should be milliseconds since UNIX epoch"); }
javascript
{ "resource": "" }
q59025
tryShutdown
validation
async function tryShutdown () { if (jobsToComplete === 0) { await new Promise((resolve) => { setTimeout(resolve, 500) }) await worker.end() process.exit() } }
javascript
{ "resource": "" }
q59026
validation
function (itemData) { var newItems = this.items.concat(itemData), // Calculate aspect ratios for items only; exclude spacing rowWidthWithoutSpacing = this.width - (newItems.length - 1) * this.spacing, newAspectRatio = newItems.reduce(function (sum, item) { return sum + item.aspectRatio; }, 0), targetAspectRatio = rowWidthWithoutSpacing / this.targetRowHeight, previousRowWidthWithoutSpacing, previousAspectRatio, previousTargetAspectRatio; // Handle big full-width breakout photos if we're doing them if (this.isBreakoutRow) { // Only do it if there's no other items in this row if (this.items.length === 0) { // Only go full width if this photo is a square or landscape if (itemData.aspectRatio >= 1) { // Close out the row with a full width photo this.items.push(itemData); this.completeLayout(rowWidthWithoutSpacing / itemData.aspectRatio, 'justify'); return true; } } } if (newAspectRatio < this.minAspectRatio) { // New aspect ratio is too narrow / scaled row height is too tall. // Accept this item and leave row open for more items. this.items.push(merge(itemData)); return true; } else if (newAspectRatio > this.maxAspectRatio) { // New aspect ratio is too wide / scaled row height will be too short. // Accept item if the resulting aspect ratio is closer to target than it would be without the item. // NOTE: Any row that falls into this block will require cropping/padding on individual items. if (this.items.length === 0) { // When there are no existing items, force acceptance of the new item and complete the layout. // This is the pano special case. this.items.push(merge(itemData)); this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify'); return true; } // Calculate width/aspect ratio for row before adding new item previousRowWidthWithoutSpacing = this.width - (this.items.length - 1) * this.spacing; previousAspectRatio = this.items.reduce(function (sum, item) { return sum + item.aspectRatio; }, 0); previousTargetAspectRatio = previousRowWidthWithoutSpacing / this.targetRowHeight; if (Math.abs(newAspectRatio - targetAspectRatio) > Math.abs(previousAspectRatio - previousTargetAspectRatio)) { // Row with new item is us farther away from target than row without; complete layout and reject item. this.completeLayout(previousRowWidthWithoutSpacing / previousAspectRatio, 'justify'); return false; } else { // Row with new item is us closer to target than row without; // accept the new item and complete the row layout. this.items.push(merge(itemData)); this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify'); return true; } } else { // New aspect ratio / scaled row height is within tolerance; // accept the new item and complete the row layout. this.items.push(merge(itemData)); this.completeLayout(rowWidthWithoutSpacing / newAspectRatio, 'justify'); return true; } }
javascript
{ "resource": "" }
q59027
validation
function (newHeight, widowLayoutStyle) { var itemWidthSum = this.left, rowWidthWithoutSpacing = this.width - (this.items.length - 1) * this.spacing, clampedToNativeRatio, clampedHeight, errorWidthPerItem, roundedCumulativeErrors, singleItemGeometry, centerOffset; // Justify unless explicitly specified otherwise. if (typeof widowLayoutStyle === 'undefined' || ['justify', 'center', 'left'].indexOf(widowLayoutStyle) < 0) { widowLayoutStyle = 'left'; } // Clamp row height to edge case minimum/maximum. clampedHeight = Math.max(this.edgeCaseMinRowHeight, Math.min(newHeight, this.edgeCaseMaxRowHeight)); if (newHeight !== clampedHeight) { // If row height was clamped, the resulting row/item aspect ratio will be off, // so force it to fit the width (recalculate aspectRatio to match clamped height). // NOTE: this will result in cropping/padding commensurate to the amount of clamping. this.height = clampedHeight; clampedToNativeRatio = (rowWidthWithoutSpacing / clampedHeight) / (rowWidthWithoutSpacing / newHeight); } else { // If not clamped, leave ratio at 1.0. this.height = newHeight; clampedToNativeRatio = 1.0; } // Compute item geometry based on newHeight. this.items.forEach(function (item) { item.top = this.top; item.width = item.aspectRatio * this.height * clampedToNativeRatio; item.height = this.height; // Left-to-right. // TODO right to left // item.left = this.width - itemWidthSum - item.width; item.left = itemWidthSum; // Increment width. itemWidthSum += item.width + this.spacing; }, this); // If specified, ensure items fill row and distribute error // caused by rounding width and height across all items. if (widowLayoutStyle === 'justify') { itemWidthSum -= (this.spacing + this.left); errorWidthPerItem = (itemWidthSum - this.width) / this.items.length; roundedCumulativeErrors = this.items.map(function (item, i) { return Math.round((i + 1) * errorWidthPerItem); }); if (this.items.length === 1) { // For rows with only one item, adjust item width to fill row. singleItemGeometry = this.items[0]; singleItemGeometry.width -= Math.round(errorWidthPerItem); } else { // For rows with multiple items, adjust item width and shift items to fill the row, // while maintaining equal spacing between items in the row. this.items.forEach(function (item, i) { if (i > 0) { item.left -= roundedCumulativeErrors[i - 1]; item.width -= (roundedCumulativeErrors[i] - roundedCumulativeErrors[i - 1]); } else { item.width -= roundedCumulativeErrors[i]; } }); } } else if (widowLayoutStyle === 'center') { // Center widows centerOffset = (this.width - itemWidthSum) / 2; this.items.forEach(function (item) { item.left += centerOffset + this.spacing; }, this); } }
javascript
{ "resource": "" }
q59028
createNewRow
validation
function createNewRow(layoutConfig, layoutData) { var isBreakoutRow; // Work out if this is a full width breakout row if (layoutConfig.fullWidthBreakoutRowCadence !== false) { if (((layoutData._rows.length + 1) % layoutConfig.fullWidthBreakoutRowCadence) === 0) { isBreakoutRow = true; } } return new Row({ top: layoutData._containerHeight, left: layoutConfig.containerPadding.left, width: layoutConfig.containerWidth - layoutConfig.containerPadding.left - layoutConfig.containerPadding.right, spacing: layoutConfig.boxSpacing.horizontal, targetRowHeight: layoutConfig.targetRowHeight, targetRowHeightTolerance: layoutConfig.targetRowHeightTolerance, edgeCaseMinRowHeight: 0.5 * layoutConfig.targetRowHeight, edgeCaseMaxRowHeight: 2 * layoutConfig.targetRowHeight, rightToLeft: false, isBreakoutRow: isBreakoutRow, widowLayoutStyle: layoutConfig.widowLayoutStyle }); }
javascript
{ "resource": "" }
q59029
validation
function (path, strategy) { if (typeof path !== 'string') { throw new Error('path should be a string'); } if (!util.isFolder(path)) { throw new Error('path should be a folder'); } if (this._remoteStorage && this._remoteStorage.access && !this._remoteStorage.access.checkPathPermission(path, 'r')) { throw new Error('No access to path "'+path+'". You have to claim access to it first.'); } if (!strategy.match(/^(FLUSH|SEEN|ALL)$/)) { throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'"); } this._rootPaths[path] = strategy; if (strategy === 'ALL') { if (this.activateHandler) { this.activateHandler(path); } else { this.pendingActivations.push(path); } } }
javascript
{ "resource": "" }
q59030
validation
function (cb) { var i; log('[Caching] Setting activate handler', cb, this.pendingActivations); this.activateHandler = cb; for (i=0; i<this.pendingActivations.length; i++) { cb(this.pendingActivations[i]); } delete this.pendingActivations; }
javascript
{ "resource": "" }
q59031
validation
function (path) { if (this._rootPaths[path] !== undefined) { return this._rootPaths[path]; } else if (path === '/') { return 'SEEN'; } else { return this.checkPath(containingFolder(path)); } }
javascript
{ "resource": "" }
q59032
validation
function(scope, mode) { if (typeof(scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) { throw new Error('Scope should be a non-empty string without forward slashes'); } if (!mode.match(/^rw?$/)) { throw new Error('Mode should be either \'r\' or \'rw\''); } this._adjustRootPaths(scope); this.scopeModeMap[scope] = mode; }
javascript
{ "resource": "" }
q59033
validation
function(scope) { var savedMap = {}; var name; for (name in this.scopeModeMap) { savedMap[name] = this.scopeModeMap[name]; } this.reset(); delete savedMap[scope]; for (name in savedMap) { this.set(name, savedMap[name]); } }
javascript
{ "resource": "" }
q59034
metaTitleFromFileName
validation
function metaTitleFromFileName (filename) { if (filename.substr(-1) === '/') { filename = filename.substr(0, filename.length - 1); } return decodeURIComponent(filename); }
javascript
{ "resource": "" }
q59035
baseName
validation
function baseName (path) { const parts = path.split('/'); if (path.substr(-1) === '/') { return parts[parts.length-2]+'/'; } else { return parts[parts.length-1]; } }
javascript
{ "resource": "" }
q59036
validation
function () { this.rs.setBackend('googledrive'); this.rs.authorize({ authURL: AUTH_URL, scope: AUTH_SCOPE, clientId: this.clientId }); }
javascript
{ "resource": "" }
q59037
validation
function (path, body, contentType, options) { const fullPath = googleDrivePath(path); function putDone(response) { if (response.status >= 200 && response.status < 300) { const meta = JSON.parse(response.responseText); const etagWithoutQuotes = removeQuotes(meta.etag); return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes}); } else if (response.status === 412) { return Promise.resolve({statusCode: 412, revision: 'conflict'}); } else { return Promise.reject("PUT failed with status " + response.status + " (" + response.responseText + ")"); } } return this._getFileId(fullPath).then((id) => { if (id) { if (options && (options.ifNoneMatch === '*')) { return putDone({ status: 412 }); } return this._updateFile(id, fullPath, body, contentType, options).then(putDone); } else { return this._createFile(fullPath, body, contentType, options).then(putDone); } }); }
javascript
{ "resource": "" }
q59038
validation
function (path, options) { const fullPath = googleDrivePath(path); return this._getFileId(fullPath).then((id) => { if (!id) { // File doesn't exist. Ignore. return Promise.resolve({statusCode: 200}); } return this._getMeta(id).then((meta) => { let etagWithoutQuotes; if ((typeof meta === 'object') && (typeof meta.etag === 'string')) { etagWithoutQuotes = removeQuotes(meta.etag); } if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) { return {statusCode: 412, revision: etagWithoutQuotes}; } return this._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then((response) => { if (response.status === 200 || response.status === 204) { return {statusCode: 200}; } else { return Promise.reject("Delete failed: " + response.status + " (" + response.responseText + ")"); } }); }); }); }
javascript
{ "resource": "" }
q59039
validation
function () { const url = BASE_URL + '/drive/v2/about?fields=user'; // requesting user info(mainly for userAdress) return this._request('GET', url, {}).then(function (resp){ try { const info = JSON.parse(resp.responseText); return Promise.resolve(info); } catch (e) { return Promise.reject(e); } }); }
javascript
{ "resource": "" }
q59040
validation
function (id, path, body, contentType, options) { const metadata = { mimeType: contentType }; const headers = { 'Content-Type': 'application/json; charset=UTF-8' }; if (options && options.ifMatch) { headers['If-Match'] = '"' + options.ifMatch + '"'; } return this._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', { body: JSON.stringify(metadata), headers: headers }).then((response) => { if (response.status === 412) { return (response); } else { return this._request('PUT', response.getResponseHeader('Location'), { body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body }); } }); }
javascript
{ "resource": "" }
q59041
validation
function (path, body, contentType/*, options*/) { return this._getParentId(path).then((parentId) => { const fileName = baseName(path); const metadata = { title: metaTitleFromFileName(fileName), mimeType: contentType, parents: [{ kind: "drive#fileLink", id: parentId }] }; return this._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', { body: JSON.stringify(metadata), headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).then((response) => { return this._request('POST', response.getResponseHeader('Location'), { body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body }); }); }); }
javascript
{ "resource": "" }
q59042
validation
function (path, options) { return this._getFileId(path).then((id) => { return this._getMeta(id).then((meta) => { let etagWithoutQuotes; if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') { etagWithoutQuotes = removeQuotes(meta.etag); } if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) { return Promise.resolve({statusCode: 304}); } if (!meta.downloadUrl) { if (meta.exportLinks && meta.exportLinks['text/html']) { // Documents that were generated inside GoogleDocs have no // downloadUrl, but you can export them to text/html instead: meta.mimeType += ';export=text/html'; meta.downloadUrl = meta.exportLinks['text/html']; } else { // empty file return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes}); } } var params = { responseType: 'arraybuffer' }; return this._request('GET', meta.downloadUrl, params).then((response) => { //first encode the response as text, and later check if //text appears to actually be binary data return getTextFromArrayBuffer(response.response, 'UTF-8').then(function (responseText) { let body = responseText; if (meta.mimeType.match(/^application\/json/)) { try { body = JSON.parse(body); } catch(e) { // body couldn't be parsed as JSON, so we'll just return it as is } } else { if (shouldBeTreatedAsBinary(responseText, meta.mimeType)) { //return unprocessed response body = response.response; } } return {statusCode: 200, body: body, contentType: meta.mimeType, revision: etagWithoutQuotes}; }); }); }); }); }
javascript
{ "resource": "" }
q59043
validation
function (path/*, options*/) { return this._getFileId(path).then((id) => { let query, fields, data, etagWithoutQuotes, itemsMap; if (! id) { return Promise.resolve({statusCode: 404}); } query = '\'' + id + '\' in parents'; fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title)'; return this._request('GET', BASE_URL + '/drive/v2/files?' + 'q=' + encodeURIComponent(query) + '&fields=' + encodeURIComponent(fields) + '&maxResults=1000', {}) .then((response) => { if (response.status !== 200) { return Promise.reject('request failed or something: ' + response.status); } try { data = JSON.parse(response.responseText); } catch(e) { return Promise.reject('non-JSON response from GoogleDrive'); } itemsMap = {}; for (const item of data.items) { etagWithoutQuotes = removeQuotes(item.etag); if (item.mimeType === GD_DIR_MIME_TYPE) { this._fileIdCache.set(path + item.title + '/', item.id); itemsMap[item.title + '/'] = { ETag: etagWithoutQuotes }; } else { this._fileIdCache.set(path + item.title, item.id); itemsMap[item.title] = { ETag: etagWithoutQuotes, 'Content-Type': item.mimeType, 'Content-Length': item.fileSize }; } } // FIXME: add revision of folder! return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined}); }); }); }
javascript
{ "resource": "" }
q59044
validation
function (path) { const foldername = parentPath(path); return this._getFileId(foldername).then((parentId) => { if (parentId) { return Promise.resolve(parentId); } else { return this._createFolder(foldername); } }); }
javascript
{ "resource": "" }
q59045
validation
function (path) { return this._getParentId(path).then((parentId) => { return this._request('POST', BASE_URL + '/drive/v2/files', { body: JSON.stringify({ title: metaTitleFromFileName(baseName(path)), mimeType: GD_DIR_MIME_TYPE, parents: [{ id: parentId }] }), headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).then((response) => { const meta = JSON.parse(response.responseText); return Promise.resolve(meta.id); }); }); }
javascript
{ "resource": "" }
q59046
validation
function (path) { let id; if (path === '/') { // "root" is a special alias for the fileId of the root folder return Promise.resolve('root'); } else if ((id = this._fileIdCache.get(path))) { // id is cached. return Promise.resolve(id); } // id is not cached (or file doesn't exist). // load parent folder listing to propagate / update id cache. return this._getFolder(parentPath(path)).then(() => { id = this._fileIdCache.get(path); if (!id) { if (path.substr(-1) === '/') { return this._createFolder(path).then(() => { return this._getFileId(path); }); } else { return Promise.resolve(); } } return Promise.resolve(id); }); }
javascript
{ "resource": "" }
q59047
validation
function (id) { return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) { if (response.status === 200) { return Promise.resolve(JSON.parse(response.responseText)); } else { return Promise.reject("request (getting metadata for " + id + ") failed with status: " + response.status); } }); }
javascript
{ "resource": "" }
q59048
unHookGetItemURL
validation
function unHookGetItemURL (rs) { if (!rs._origBaseClientGetItemURL) { return; } BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL; delete rs._origBaseClientGetItemURL; }
javascript
{ "resource": "" }
q59049
validation
function (eventName, handler) { if (typeof(eventName) !== 'string') { throw new Error('Argument eventName should be a string'); } if (typeof(handler) !== 'function') { throw new Error('Argument handler should be a function'); } log('[Eventhandling] Adding event listener', eventName); this._validateEvent(eventName); this._handlers[eventName].push(handler); }
javascript
{ "resource": "" }
q59050
validation
function (eventName, handler) { this._validateEvent(eventName); var hl = this._handlers[eventName].length; for (var i=0;i<hl;i++) { if (this._handlers[eventName][i] === handler) { this._handlers[eventName].splice(i, 1); return; } } }
javascript
{ "resource": "" }
q59051
Discover
validation
function Discover(userAddress) { return new Promise((resolve, reject) => { if (userAddress in cachedInfo) { return resolve(cachedInfo[userAddress]); } var webFinger = new WebFinger({ tls_only: false, uri_fallback: true, request_timeout: 5000 }); return webFinger.lookup(userAddress, function (err, response) { if (err) { return reject(err); } else if ((typeof response.idx.links.remotestorage !== 'object') || (typeof response.idx.links.remotestorage.length !== 'number') || (response.idx.links.remotestorage.length <= 0)) { log("[Discover] WebFinger record for " + userAddress + " does not have remotestorage defined in the links section ", JSON.stringify(response.json)); return reject("WebFinger record for " + userAddress + " does not have remotestorage defined in the links section."); } var rs = response.idx.links.remotestorage[0]; var authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] || rs.properties['auth-endpoint']; var storageApi = rs.properties['http://remotestorage.io/spec/version'] || rs.type; // cache fetched data cachedInfo[userAddress] = { href: rs.href, storageApi: storageApi, authURL: authURL, properties: rs.properties }; if (hasLocalStorage) { localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo }); } return resolve(cachedInfo[userAddress]); }); }); }
javascript
{ "resource": "" }
q59052
validation
function () { // TODO handling when token is already present this.rs.setBackend('dropbox'); if (this.token){ hookIt(this.rs); } else { this.rs.authorize({ authURL: AUTH_URL, scope: '', clientId: this.clientId }); } }
javascript
{ "resource": "" }
q59053
validation
function (path) { var url = 'https://api.dropboxapi.com/2/files/list_folder'; var revCache = this._revCache; var self = this; var processResponse = function (resp) { var body, listing; if (resp.status !== 200 && resp.status !== 409) { return Promise.reject('Unexpected response status: ' + resp.status); } try { body = JSON.parse(resp.responseText); } catch (e) { return Promise.reject(e); } if (resp.status === 409) { if (compareApiError(body, ['path', 'not_found'])) { // if the folder is not found, handle it as an empty folder return Promise.resolve({}); } return Promise.reject(new Error('API returned an error: ' + body.error_summary)); } listing = body.entries.reduce(function (map, item) { var isDir = item['.tag'] === 'folder'; var itemName = item.path_lower.split('/').slice(-1)[0] + (isDir ? '/' : ''); if (isDir){ map[itemName] = { ETag: revCache.get(path+itemName) }; } else { map[itemName] = { ETag: item.rev }; self._revCache.set(path+itemName, item.rev); } return map; }, {}); if (body.has_more) { return loadNext(body.cursor).then(function (nextListing) { return Object.assign(listing, nextListing); }); } return Promise.resolve(listing); }; const loadNext = function (cursor) { const continueURL = 'https://api.dropboxapi.com/2/files/list_folder/continue'; const params = { body: { cursor: cursor } }; return self._request('POST', continueURL, params).then(processResponse); }; return this._request('POST', url, { body: { path: getDropboxPath(path) } }).then(processResponse).then(function (listing) { return Promise.resolve({ statusCode: 200, body: listing, contentType: 'application/json; charset=UTF-8', revision: revCache.get(path) }); }); }
javascript
{ "resource": "" }
q59054
validation
function (path, options) { if (! this.connected) { return Promise.reject("not connected (path: " + path + ")"); } var url = 'https://content.dropboxapi.com/2/files/download'; var self = this; var savedRev = this._revCache.get(path); if (savedRev === null) { // file was deleted server side return Promise.resolve({statusCode: 404}); } if (options && options.ifNoneMatch) { // We must wait for local revision cache to be initialized before // checking if local revision is outdated if (! this._initialFetchDone) { return this.fetchDelta().then(() => { return this.get(path, options); }); } if (savedRev && (savedRev === options.ifNoneMatch)) { // nothing changed. return Promise.resolve({statusCode: 304}); } } //use _getFolder for folders if (path.substr(-1) === '/') { return this._getFolder(path, options); } var params = { headers: { 'Dropbox-API-Arg': JSON.stringify({path: getDropboxPath(path)}), }, responseType: 'arraybuffer' }; if (options && options.ifNoneMatch) { params.headers['If-None-Match'] = options.ifNoneMatch; } return this._request('GET', url, params).then(function (resp) { var status = resp.status; var meta, body, mime, rev; if (status !== 200 && status !== 409) { return Promise.resolve({statusCode: status}); } meta = resp.getResponseHeader('Dropbox-API-Result'); //first encode the response as text, and later check if //text appears to actually be binary data return getTextFromArrayBuffer(resp.response, 'UTF-8').then(function (responseText) { body = responseText; if (status === 409) { meta = body; } try { meta = JSON.parse(meta); } catch(e) { return Promise.reject(e); } if (status === 409) { if (compareApiError(meta, ['path', 'not_found'])) { return {statusCode: 404}; } return Promise.reject(new Error('API error while downloading file ("' + path + '"): ' + meta.error_summary)); } mime = resp.getResponseHeader('Content-Type'); rev = meta.rev; self._revCache.set(path, rev); self._shareIfNeeded(path); if (shouldBeTreatedAsBinary(responseText, mime)) { //return unprocessed response body = resp.response; } else { // handling json (always try) try { body = JSON.parse(body); mime = 'application/json; charset=UTF-8'; } catch(e) { //Failed parsing Json, assume it is something else then } } return { statusCode: status, body: body, contentType: mime, revision: rev }; }); }); }
javascript
{ "resource": "" }
q59055
validation
function (path) { var url = 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings'; var options = { body: {path: getDropboxPath(path)} }; return this._request('POST', url, options).then((response) => { if (response.status !== 200 && response.status !== 409) { return Promise.reject(new Error('Invalid response status:' + response.status)); } var body; try { body = JSON.parse(response.responseText); } catch (e) { return Promise.reject(new Error('Invalid response body: ' + response.responseText)); } if (response.status === 409) { if (compareApiError(body, ['shared_link_already_exists'])) { return this._getSharedLink(path); } return Promise.reject(new Error('API error: ' + body.error_summary)); } return Promise.resolve(body.url); }).then((link) => { this._itemRefs[path] = link; if (hasLocalStorage) { localStorage.setItem(SETTINGS_KEY+':shares', JSON.stringify(this._itemRefs)); } return Promise.resolve(link); }, (error) => { error.message = 'Sharing Dropbox file or folder ("' + path + '") failed: ' + error.message; return Promise.reject(error); }); }
javascript
{ "resource": "" }
q59056
validation
function () { var url = 'https://api.dropboxapi.com/2/users/get_current_account'; return this._request('POST', url, {}).then(function (response) { var info = response.responseText; try { info = JSON.parse(info); } catch (e) { return Promise.reject(new Error('Could not query current account info: Invalid API response: ' + info)); } return Promise.resolve({ email: info.email }); }); }
javascript
{ "resource": "" }
q59057
validation
function (path) { const url = 'https://api.dropboxapi.com/2/files/delete'; const requestBody = { path: getDropboxPath(path) }; return this._request('POST', url, { body: requestBody }).then((response) => { if (response.status !== 200 && response.status !== 409) { return Promise.resolve({statusCode: response.status}); } var responseBody = response.responseText; try { responseBody = JSON.parse(responseBody); } catch (e) { return Promise.reject(new Error('Invalid response body: ' + responseBody)); } if (response.status === 409) { if (compareApiError(responseBody, ['path_lookup', 'not_found'])) { return Promise.resolve({statusCode: 404}); } return Promise.reject(new Error('API error: ' + responseBody.error_summary)); } return Promise.resolve({statusCode: 200}); }).then((result) => { if (result.statusCode === 200 || result.statusCode === 404) { this._revCache.delete(path); delete this._itemRefs[path]; } return Promise.resolve(result); }, (error) => { error.message = 'Could not delete Dropbox file or folder ("' + path + '"): ' + error.message; return Promise.reject(error); }); }
javascript
{ "resource": "" }
q59058
validation
function (path) { var url = 'https://api.dropbox.com/2/sharing/list_shared_links'; var options = { body: { path: getDropboxPath(path), direct_only: true } }; return this._request('POST', url, options).then((response) => { if (response.status !== 200 && response.status !== 409) { return Promise.reject(new Error('Invalid response status: ' + response.status)); } var body; try { body = JSON.parse(response.responseText); } catch (e) { return Promise.reject(new Error('Invalid response body: ' + response.responseText)); } if (response.status === 409) { return Promise.reject(new Error('API error: ' + response.error_summary)); } if (!body.links.length) { return Promise.reject(new Error('No links returned')); } return Promise.resolve(body.links[0].url); }, (error) => { error.message = 'Could not get link to a shared file or folder ("' + path + '"): ' + error.message; return Promise.reject(error); }); }
javascript
{ "resource": "" }
q59059
hookSync
validation
function hookSync(rs) { if (rs._dropboxOrigSync) { return; } // already hooked rs._dropboxOrigSync = rs.sync.sync.bind(rs.sync); rs.sync.sync = function () { return this.dropbox.fetchDelta.apply(this.dropbox, arguments). then(rs._dropboxOrigSync, function (err) { rs._emit('error', new Sync.SyncError(err)); rs._emit('sync-done'); }); }.bind(rs); }
javascript
{ "resource": "" }
q59060
unHookSync
validation
function unHookSync(rs) { if (! rs._dropboxOrigSync) { return; } // not hooked rs.sync.sync = rs._dropboxOrigSync; delete rs._dropboxOrigSync; }
javascript
{ "resource": "" }
q59061
hookSyncCycle
validation
function hookSyncCycle(rs) { if (rs._dropboxOrigSyncCycle) { return; } // already hooked rs._dropboxOrigSyncCycle = rs.syncCycle; rs.syncCycle = () => { if (rs.sync) { hookSync(rs); rs._dropboxOrigSyncCycle(arguments); unHookSyncCycle(rs); } else { throw new Error('expected sync to be initialized by now'); } }; }
javascript
{ "resource": "" }
q59062
unHookSyncCycle
validation
function unHookSyncCycle(rs) { if (!rs._dropboxOrigSyncCycle) { return; } // not hooked rs.syncCycle = rs._dropboxOrigSyncCycle; delete rs._dropboxOrigSyncCycle; }
javascript
{ "resource": "" }
q59063
hookGetItemURL
validation
function hookGetItemURL (rs) { if (rs._origBaseClientGetItemURL) { return; } rs._origBaseClientGetItemURL = BaseClient.prototype.getItemURL; BaseClient.prototype.getItemURL = function (/*path*/) { throw new Error('getItemURL is not implemented for Dropbox yet'); }; }
javascript
{ "resource": "" }
q59064
extractFeatures
validation
function extractFeatures(chunk) { //make it a F32A for efficiency var frame = arrayToTyped(chunk); //run the extraction of selected features var fset = Meyda.extract(featuresToExtract, frame); for (let j = 0; j < featuresToExtract.length; j++) { var feature = fset[featuresToExtract[j]]; features[featuresToExtract[j]].push(feature); } }
javascript
{ "resource": "" }
q59065
getIdFromURL
validation
function getIdFromURL (url) { var id = url.replace(youtubeRegexp, '$1'); if (id.includes(';')) { var pieces = id.split(';'); if (pieces[1].includes('%')) { var uriComponent = decodeURIComponent(pieces[1]); id = ("http://youtube.com" + uriComponent).replace(youtubeRegexp, '$1'); } else { id = pieces[0]; } } else if (id.includes('#')) { id = id.split('#')[0]; } return id }
javascript
{ "resource": "" }
q59066
getTimeFromURL
validation
function getTimeFromURL (url) { if ( url === void 0 ) url = ''; var times = url.match(timeRegexp); if (!times) { return 0 } var full = times[0]; var minutes = times[1]; var seconds = times[2]; if (typeof seconds !== 'undefined') { seconds = parseInt(seconds, 10); minutes = parseInt(minutes, 10); } else if (full.includes('m')) { minutes = parseInt(minutes, 10); seconds = 0; } else { seconds = parseInt(minutes, 10); minutes = 0; } return seconds + (minutes * 60) }
javascript
{ "resource": "" }
q59067
onTablesSelected
validation
function onTablesSelected(tables) { // Assign partialed functions to make the code slightly more readable steps.collect = mapValues(steps.collect, function(method) { return partial(method, adapter, { tables: tables }); }); // Collect the data in parallel async.parallel(steps.collect, onTableDataCollected); }
javascript
{ "resource": "" }
q59068
onTableDataCollected
validation
function onTableDataCollected(err, data) { bailOnError(err); var tableName, models = {}, model; for (tableName in data.tableStructure) { model = steps.tableToObject({ name: tableName, columns: data.tableStructure[tableName], comment: data.tableComments[tableName] }, opts); models[model.name] = model; } data.models = steps.findReferences(models); // Note: This mutates the models - sorry. PRs are welcome. steps.findOneToManyReferences(adapter, data.models, function(refErr) { if (refErr) { throw refErr; } data.types = steps.generateTypes(data, opts); adapter.close(); steps.outputData(data, opts, onDataOutput); }); }
javascript
{ "resource": "" }
q59069
getOffset
validation
function getOffset(cursor, defaultOffset) { if (typeof cursor === 'undefined' || cursor === null) { return defaultOffset; } let offset = cursorToOffset(cursor); if (isNaN(offset)) { return defaultOffset; } return offset; }
javascript
{ "resource": "" }
q59070
importSpecifier
validation
function importSpecifier(name, def) { return { type: def === true ? 'ImportDefaultSpecifier' : 'ImportSpecifier', id: { type: 'Identifier', name: name }, name: null }; }
javascript
{ "resource": "" }
q59071
ruleCodes
validation
function ruleCodes(flags, value) { var flag = flags.FLAG var result = [] var length var index if (!value) { return result } if (flag === 'long') { index = 0 length = value.length while (index < length) { result.push(value.substr(index, 2)) index += 2 } return result } return value.split(flag === 'num' ? ',' : '') }
javascript
{ "resource": "" }
q59072
add
validation
function add(buf) { var self = this var flags = self.flags var lines = buf.toString('utf8').split('\n') var length = lines.length var index = -1 var line var forbidden var word var model var flag // Ensure there’s a key for `FORBIDDENWORD`: `false` cannot be set through an // affix file so its safe to use as a magic constant. flag = flags.FORBIDDENWORD || false flags.FORBIDDENWORD = flag while (++index < length) { line = trim(lines[index]) if (!line) { continue } line = line.split('/') word = line[0] model = line[1] forbidden = word.charAt(0) === '*' if (forbidden) { word = word.slice(1) } self.add(word, model) if (forbidden) { self.data[word].push(flag) } } return self }
javascript
{ "resource": "" }
q59073
generate
validation
function generate(context, memory, words, edits) { var characters = context.flags.TRY var characterLength = characters.length var data = context.data var flags = context.flags var result = [] var upper var length var index var word var position var count var before var after var nextAfter var nextNextAfter var character var nextCharacter var inject var offset // Check the pre-generated edits. length = edits && edits.length index = -1 while (++index < length) { check(edits[index], true) } // Iterate over given word. length = words.length index = -1 while (++index < length) { word = words[index] before = '' character = '' nextAfter = word nextNextAfter = word.slice(1) nextCharacter = word.charAt(0) position = -1 count = word.length + 1 // Iterate over every character (including the end). while (++position < count) { before += character after = nextAfter nextAfter = nextNextAfter nextNextAfter = nextAfter.slice(1) character = nextCharacter nextCharacter = word.charAt(position + 1) upper = character.toLowerCase() !== character // Remove. check(before + nextAfter) // Switch. if (nextAfter) { check(before + nextCharacter + character + nextNextAfter) } // Iterate over all possible letters. offset = -1 while (++offset < characterLength) { inject = characters[offset] // Add and replace. check(before + inject + after) check(before + inject + nextAfter) // Try upper-case if the original character was upper-cased. if (upper) { inject = inject.toUpperCase() check(before + inject + after) check(before + inject + nextAfter) } } } } // Return the list of generated words. return result // Check and handle a generated value. function check(value, double) { var state = memory.state[value] var corrected if (state !== Boolean(state)) { result.push(value) corrected = form(context, value) state = corrected && !flag(flags, noSuggestType, data[corrected]) memory.state[value] = state if (state) { memory.weighted[value] = double ? 10 : 0 memory.suggestions.push(value) } } if (state) { memory.weighted[value]++ } } }
javascript
{ "resource": "" }
q59074
check
validation
function check(value, double) { var state = memory.state[value] var corrected if (state !== Boolean(state)) { result.push(value) corrected = form(context, value) state = corrected && !flag(flags, noSuggestType, data[corrected]) memory.state[value] = state if (state) { memory.weighted[value] = double ? 10 : 0 memory.suggestions.push(value) } } if (state) { memory.weighted[value]++ } }
javascript
{ "resource": "" }
q59075
add
validation
function add(word, rules) { // Some dictionaries will list the same word multiple times with different // rule sets. var curr = (own.call(dict, word) && dict[word]) || [] dict[word] = curr.concat(rules || []) }
javascript
{ "resource": "" }
q59076
flag
validation
function flag(values, value, flags) { return flags && own.call(values, value) && flags.indexOf(values[value]) !== -1 }
javascript
{ "resource": "" }
q59077
normalize
validation
function normalize(value, patterns) { var length = patterns.length var index = -1 var pattern while (++index < length) { pattern = patterns[index] value = value.replace(pattern[0], pattern[1]) } return value }
javascript
{ "resource": "" }
q59078
form
validation
function form(context, value, all) { var dict = context.data var flags = context.flags var alternative value = trim(value) if (!value) { return null } value = normalize(value, context.conversion.in) if (exact(context, value)) { if (!all && flag(flags, 'FORBIDDENWORD', dict[value])) { return null } return value } // Try sentence-case if the value is upper-case. if (value.toUpperCase() === value) { alternative = value.charAt(0) + value.slice(1).toLowerCase() if (ignore(flags, dict[alternative], all)) { return null } if (exact(context, alternative)) { return alternative } } // Try lower-case. alternative = value.toLowerCase() if (alternative !== value) { if (ignore(flags, dict[alternative], all)) { return null } if (exact(context, alternative)) { return alternative } } return null }
javascript
{ "resource": "" }
q59079
NSpell
validation
function NSpell(aff, dic) { var length var index var dictionaries if (!(this instanceof NSpell)) { return new NSpell(aff, dic) } if (typeof aff === 'string' || buffer(aff)) { if (typeof dic === 'string' || buffer(dic)) { dictionaries = [{dic: dic}] } } else if (aff) { if ('length' in aff) { dictionaries = aff aff = aff[0] && aff[0].aff } else { if (aff.dic) { dictionaries = [aff] } aff = aff.aff } } if (!aff) { throw new Error('Missing `aff` in dictionary') } aff = affix(aff) this.data = {} this.compoundRuleCodes = aff.compoundRuleCodes this.replacementTable = aff.replacementTable this.conversion = aff.conversion this.compoundRules = aff.compoundRules this.rules = aff.rules this.flags = aff.flags length = dictionaries ? dictionaries.length : 0 index = -1 while (++index < length) { dic = dictionaries[index] if (dic && dic.dic) { this.dictionary(dic.dic) } } }
javascript
{ "resource": "" }
q59080
add
validation
function add(value, model) { var self = this var dict = self.data var codes = model && own.call(dict, model) ? dict[model].concat() : [] push(dict, value, codes, self) return self }
javascript
{ "resource": "" }
q59081
parse
validation
function parse(buf, options, dict) { var index var last var value // Parse as lines. value = buf.toString(UTF8) last = value.indexOf(linefeed) + 1 index = value.indexOf(linefeed, last) while (index !== -1) { if (value.charCodeAt(last) !== tab) { parseLine(value.slice(last, index), options, dict) } last = index + 1 index = value.indexOf(linefeed, last) } parseLine(value.slice(last), options, dict) }
javascript
{ "resource": "" }
q59082
parseLine
validation
function parseLine(line, options, dict) { var word var codes var result var hashOffset var slashOffset // Find offsets. slashOffset = line.indexOf(slash) while (slashOffset !== -1 && line.charAt(slashOffset - 1) === backslash) { line = line.slice(0, slashOffset - 1) + line.slice(slashOffset) slashOffset = line.indexOf(slash, slashOffset) } hashOffset = line.indexOf(numberSign) // Handle hash and slash offsets. Note that hash can be a valid flag, so we // should not just discard all string after it. if (hashOffset >= 0) { if (slashOffset >= 0 && slashOffset < hashOffset) { word = line.slice(0, slashOffset) whiteSpaceExpression.lastIndex = slashOffset + 1 result = whiteSpaceExpression.exec(line) codes = line.slice(slashOffset + 1, result ? result.index : undefined) } else { word = line.slice(0, hashOffset) } } else if (slashOffset >= 0) { word = line.slice(0, slashOffset) codes = line.slice(slashOffset + 1) } else { word = line } word = trim(word) if (word) { codes = parseCodes(options.flags, codes && trim(codes)) add(dict, word, codes, options) } }
javascript
{ "resource": "" }
q59083
casing
validation
function casing(value) { var head = exact(value.charAt(0)) var rest = value.slice(1) if (!rest) { return head } rest = exact(rest) if (head === rest) { return head } if (head === 'u' && rest === 'l') { return 's' } return null }
javascript
{ "resource": "" }
q59084
apply
validation
function apply(value, rule, rules) { var entries = rule.entries var words = [] var index = -1 var length = entries.length var entry var next var continuationRule var continuation var position var count while (++index < length) { entry = entries[index] if (!entry.match || value.match(entry.match)) { next = value if (entry.remove) { next = next.replace(entry.remove, '') } if (rule.type === 'SFX') { next += entry.add } else { next = entry.add + next } words.push(next) continuation = entry.continuation if (continuation && continuation.length !== 0) { position = -1 count = continuation.length while (++position < count) { continuationRule = rules[continuation[position]] if (continuationRule) { words = words.concat(apply(next, continuationRule, rules)) } } } } } return words }
javascript
{ "resource": "" }
q59085
spell
validation
function spell(word) { var self = this var dict = self.data var flags = self.flags var value = form(self, word, true) // Hunspell also provides `root` (root word of the input word), and `compound` // (whether `word` was compound). return { correct: self.correct(word), forbidden: Boolean(value && flag(flags, 'FORBIDDENWORD', dict[value])), warn: Boolean(value && flag(flags, 'WARN', dict[value])) } }
javascript
{ "resource": "" }
q59086
add
validation
function add(buf) { var self = this var compound = self.compoundRules var compoundCodes = self.compoundRuleCodes var index = -1 var length = compound.length var rule var source var character var offset var count parse(buf, self, self.data) // Regenerate compound expressions. while (++index < length) { rule = compound[index] source = '' offset = -1 count = rule.length while (++offset < count) { character = rule.charAt(offset) if (compoundCodes[character].length === 0) { source += character } else { source += '(?:' + compoundCodes[character].join('|') + ')' } } compound[index] = new RegExp(source, 'i') } return self }
javascript
{ "resource": "" }
q59087
exact
validation
function exact(context, value) { var data = context.data var flags = context.flags var codes = own.call(data, value) ? data[value] : null var compound var index var length if (codes) { return !flag(flags, 'ONLYINCOMPOUND', codes) } compound = context.compoundRules length = compound.length index = -1 // Check if this might be a compound word. if (value.length >= flags.COMPOUNDMIN) { while (++index < length) { if (value.match(compound[index])) { return true } } } return false }
javascript
{ "resource": "" }
q59088
validation
function() { var retVal, parsedOptions; if (this.model) { retVal = this.model.toJSON(); } else if (this.collection) { retVal = { models: this.collection.toJSON(), meta: this.collection.meta, params: this.collection.params }; } // Remove options that are duplicates in the templates parsedOptions = _.omit(this.options, ['model', 'collection', 'app']); return _.extend({}, retVal, parsedOptions); }
javascript
{ "resource": "" }
q59089
validation
function(data) { if (this.app) { data._app = this.app; } if (this.model) { data._model = this.model; } if (this.collection) { data._collection = this.collection; } data._view = this; return data; }
javascript
{ "resource": "" }
q59090
validation
function() { var attributes = {}, fetchSummary = {}, modelUtils = this.app.modelUtils, nonAttributeOptions = this.nonAttributeOptions; if (this.attributes) { _.extend(attributes, _.result(this, 'attributes')); } if (this.id) { attributes.id = _.result(this, "id"); } if (this.className) { attributes['class'] = _.result(this, "className"); } // Add `data-view` attribute with view key. // For now, view key is same as template. attributes['data-view'] = this.name; // Add model & collection meta data from options, // as well as any non-object option values. _.each(this.options, function(value, key) { if (!_.isObject(value) && !_.include(nonAttributeOptions, key)) { attributes["data-" + key] = value; } }); fetchSummary = BaseView.extractFetchSummary(modelUtils, this.options); if (!_.isEmpty(fetchSummary)) { attributes['data-fetch_summary'] = JSON.stringify(fetchSummary); } return attributes; }
javascript
{ "resource": "" }
q59091
validation
function() { var template = this.getTemplate(), data; this._preRender(); data = this.getTemplateData(); data = this.decorateTemplateData(data); if (template == null) { throw new Error(this.name + ": template \"" + this.getTemplateName() + "\" not found."); } return template(data); }
javascript
{ "resource": "" }
q59092
validation
function() { var html = this.getInnerHtml(), attributes = this.getAttributes(), tagName = _.result(this, "tagName"), attrString; attrString = _.inject(attributes, function(memo, value, key) { return memo += " " + key + "=\"" + _.escape(value) + "\""; }, ''); return "<" + tagName + attrString + ">" + html + "</" + tagName + ">"; }
javascript
{ "resource": "" }
q59093
validation
function() { var params = {}, fetchOptions, fetchSpec; if (this.options.fetch_params) { if (!_.isObject(this.options.fetch_params)) { throw new Error('fetch_params must be an object for lazy loaded views'); } params = this.options.fetch_params; } else if (this.options.param_name) { params[this.options.param_name] = this.options.param_value; } if (this.options.fetch_options) { if (!_.isObject(this.options.fetch_options)) { throw new Error('fetch_options must be an object for lazy loaded views'); } fetchOptions = this.options.fetch_options; } if (this.options.model_id != null) { params.id = this.options.model_id; } if (this.options.model_name != null) { fetchSpec = { model: { model: this.options.model_name, params: params } }; } else if (this.options.collection_name != null) { fetchSpec = { collection: { collection: this.options.collection_name, params: params } }; } // Allow ability to just pass the full "spec" to a lazy loaded view if (this.options.fetch_spec) { if (!_.isObject(this.options.fetch_spec)) { throw new Error('fetch_spec must be an object for lazy loaded views'); } fetchSpec = this.options.fetch_spec; } this.setLoading(true); this._preRender(); this.app.fetch(fetchSpec, fetchOptions, this._fetchLazyCallback.bind(this)); }
javascript
{ "resource": "" }
q59094
getAppAttributes
validation
function getAppAttributes(attrs, req, res) { if (typeof attrs === 'function') { attrs = attrs(req, res); } return attrs || {}; }
javascript
{ "resource": "" }
q59095
actionCall
validation
function actionCall(action, params) { action.call(router, params, router.getRenderCallback(route)); }
javascript
{ "resource": "" }
q59096
validation
function(pattern, controller, options) { var realAction, action, handler, route, routeObj, routerContext = this; route = parseRouteDefinitions([controller, options]); realAction = this.getAction(route); if (isServer) { action = realAction; } else { action = function(params, callback) { var self = this; var myLoadNumber = ++loadNumber; function next() { // To prevent race conditions we ensure that no future requests have been processed in the mean time. if (myLoadNumber === loadNumber) { callback.apply(self, arguments); } } // in AMD environment realAction is the string containing path to the controller // which will be loaded async (might be preloaded) // Only used in AMD environment if (typeof realAction === 'string') { routerContext._requireAMD([realAction], function(controller) { // check we have everything we need if (typeof controller[route.action] != 'function') { throw new Error("Missing action \"" + route.action + "\" for controller \"" + route.controller + "\""); } controller[route.action].call(self, params, next); }); } else { realAction.call(self, params, next); } } } if (!(pattern instanceof RegExp) && pattern.slice(0, 1) !== '/') { pattern = "/" + pattern; } handler = this.getHandler(action, pattern, route); routeObj = [pattern, route, handler]; this._routes.push(routeObj); this.trigger('route:add', routeObj); return routeObj; }
javascript
{ "resource": "" }
q59097
unmarshalPublicKey
validation
function unmarshalPublicKey (curve, key) { const byteLen = curveLengths[curve] if (!key.slice(0, 1).equals(Buffer.from([4]))) { throw new Error('Invalid key format') } const x = new BN(key.slice(1, byteLen + 1)) const y = new BN(key.slice(1 + byteLen)) return { kty: 'EC', crv: curve, x: toBase64(x, byteLen), y: toBase64(y, byteLen), ext: true } }
javascript
{ "resource": "" }
q59098
pbkdf2
validation
function pbkdf2 (password, salt, iterations, keySize, hash) { const hasher = hashName[hash] if (!hasher) { throw new Error(`Hash '${hash}' is unknown or not supported`) } const dek = forgePbkdf2( password, salt, iterations, keySize, hasher) return forgeUtil.encode64(dek) }
javascript
{ "resource": "" }
q59099
getRawHeader
validation
function getRawHeader(_block) { if (typeof _block.difficulty !== 'string') { _block.difficulty = '0x' + _block.difficulty.toString(16) } const block = new EthereumBlock(_block) return block.header }
javascript
{ "resource": "" }