_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q53900
unpublishPage
train
function unpublishPage(uri, user) { const update = { published: false, publishTime: null, url: '', history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }] }; return changeMetaState(uri, update); }
javascript
{ "resource": "" }
q53901
changeMetaState
train
function changeMetaState(uri, update) { return getMeta(uri) .then(old => mergeNewAndOldMeta(old, update)) .then(updatedMeta => putMeta(uri, updatedMeta)); }
javascript
{ "resource": "" }
q53902
putMeta
train
function putMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.putMeta(id, data) .then(pubToBus(id)); }
javascript
{ "resource": "" }
q53903
patchMeta
train
function patchMeta(uri, data) { const id = replaceVersion(uri.replace('/meta', '')); return db.patchMeta(id, data) .then(() => getMeta(uri)) .then(pubToBus(id)); }
javascript
{ "resource": "" }
q53904
checkProps
train
function checkProps(uri, props) { const id = replaceVersion(uri.replace('/meta', '')); return db.getMeta(id) .then(meta => { return Array.isArray(props) ? props.every(prop => meta[prop]) : meta[props] && true; }) .catch(err => { throw new Error(err); }); }
javascript
{ "resource": "" }
q53905
put
train
function put(model, uri, data, locals) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT; return bluebird.try(() => { return bluebird.resolve(model.save(uri, data, locals)) .then(resolvedData => { if (!_.isObject(resolvedData)) { throw new Error(`Unable to save ${uri}: Data from model.save must be an object!`); } return { key: uri, type: 'put', value: JSON.stringify(resolvedData) }; }); }).tap(() => { const ms = timer.getMillisecondsSince(startTime); if (ms > timeoutLimit * 0.5) { log('warn', `slow put ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Module PUT exceeded ${timeoutLimit}ms: ${uri}`); }
javascript
{ "resource": "" }
q53906
get
train
function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */ var promise; if (executeRender) { const startTime = process.hrtime(), timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT; promise = bluebird.try(() => { return db.get(uri) .then(upgrade.init(uri, locals)) // Run an upgrade! .then(data => model.render(uri, data, locals)); }).tap(result => { const ms = timer.getMillisecondsSince(startTime); if (!_.isObject(result)) { throw new Error(`Component model must return object, not ${typeof result}: ${uri}`); } if (ms > timeoutLimit * 0.5) { log('warn', `slow get ${uri} ${ms}ms`); } }).timeout(timeoutLimit, `Model GET exceeded ${timeoutLimit}ms: ${uri}`); } else { promise = db.get(uri).then(upgrade.init(uri, locals)); // Run an upgrade! } if (renderModel && _.isFunction(renderModel)) { promise = promise.then(data => renderModel(uri, data, locals)); } return promise.then(data => { if (!_.isObject(data)) { throw new Error(`Client: Invalid data type for component at ${uri} of ${typeof data}`); } return data; }); }
javascript
{ "resource": "" }
q53907
renameReferenceUniquely
train
function renameReferenceUniquely(uri) { const prefix = uri.substr(0, uri.indexOf('/_components/')); return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`; }
javascript
{ "resource": "" }
q53908
getPageClonePutOperations
train
function getPageClonePutOperations(pageData, locals) { return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => { if (typeof pageValue === 'string' && getComponentName(pageValue)) { // for all strings that are component references promises.push(components.get(pageValue, locals) // only follow the paths of instance references. Don't clone default components .then(refData => composer.resolveComponentReferences(refData, locals, isInstanceReferenceObject)) .then(resolvedData => { // for each instance reference within resolved data _.each(references.listDeepObjects(resolvedData, isInstanceReferenceObject), obj => { obj._ref = renameReferenceUniquely(obj._ref); }); // rename reference in pageData const ref = renameReferenceUniquely(pageValue); pageData[pageKey] = ref; // put new data using cascading PUT at place that page now points return dbOps.getPutOperations(components.cmptPut, ref, resolvedData, locals); })); } else { // for all object-like things (i.e., objects and arrays) promises = promises.concat(getPageClonePutOperations(pageValue, locals)); } return promises; }, [])).then(_.flatten); // only one level of flattening needed }
javascript
{ "resource": "" }
q53909
replacePageReferenceVersions
train
function replacePageReferenceVersions(data, version) { const replace = _.partial(replaceVersion, _, version); return _.mapValues(data, function (value, key) { let result; if (references.isUri(value)) { result = replace(value); } else if (_.isArray(value) && key !== 'urlHistory') { // urlHistory is an array of old page urls. they're not component refs and shouldn't be versioned result = _.map(value, replace); } else { result = value; } return result; }); }
javascript
{ "resource": "" }
q53910
getRecursivePublishedPutOperations
train
function getRecursivePublishedPutOperations(locals) { return rootComponentRef => { /** * 1) Get reference (could be latest, could be other) * 2) Get all references within reference * 3) Replace all references with @published (including root reference) * 4) Get list of put operations needed */ return components.get(rootComponentRef, locals) .then(data => composer.resolveComponentReferences(data, locals)) .then(data => dbOps.getPutOperations(components.cmptPut, replaceVersion(rootComponentRef, 'published'), data, locals)); }; }
javascript
{ "resource": "" }
q53911
getSite
train
function getSite(prefix, locals) { const site = locals && locals.site; return site || siteService.getSiteFromPrefix(prefix); }
javascript
{ "resource": "" }
q53912
publish
train
function publish(uri, data, locals) { const startTime = process.hrtime(), prefix = getPrefix(uri), site = getSite(prefix, locals), timeoutLimit = timeoutConstant * timeoutPublishCoefficient, user = locals && locals.user; var publishedMeta; // We need to store some meta a little later return getPublishData(uri, data) .then(publishService.resolvePublishUrl(uri, locals, site)) .then(({ meta, data: pageData}) => { const published = 'published', dynamicPage = pageData._dynamic, componentList = references.getPageReferences(pageData); if (!references.isUrl(meta.url) && !dynamicPage) { throw new Error('Client: Page must have valid url to publish.'); } return bluebird.map(componentList, getRecursivePublishedPutOperations(locals)) .then(_.flatten) // only one level of flattening needed, because getPutOperations should have flattened its list already .then(ops => { // convert the data to all @published pageData = replacePageReferenceVersions(pageData, published); // Make public unless we're dealing with a `_dynamic` page if (!dynamicPage) { addOpToMakePublic(ops, prefix, meta.url, uri); } // Store the metadata if we're at this point publishedMeta = meta; // add page PUT operation last return addOp(replaceVersion(uri, published), pageData, ops); }); }) .then(applyBatch) .tap(() => { const ms = timer.getMillisecondsSince(startTime); if (ms > timeoutLimit * 0.5) { log('warn', `slow publish ${uri} ${ms}ms`); } else { log('info', `published ${replaceVersion(uri)} ${ms}ms`); } }) .timeout(timeoutLimit, `Page publish exceeded ${timeoutLimit}ms: ${uri}`) .then(publishedData => { return meta.publishPage(uri, publishedMeta, user).then(() => { // Notify the bus bus.publish('publishPage', { uri, data: publishedData, user}); notifications.notify(site, 'published', publishedData); // Update the meta object return publishedData; }); }); }
javascript
{ "resource": "" }
q53913
initPlugins
train
function initPlugins(router, site) { return bluebird.all(module.exports.plugins.map(plugin => { return bluebird.try(() => { if (typeof plugin === 'function') { return plugin(router, pluginDBAdapter, publish, sites, site); } else { log('warn', 'Plugin is not a function'); return bluebird.resolve(); } }); })); }
javascript
{ "resource": "" }
q53914
createDBAdapter
train
function createDBAdapter() { var returnObj = { getMeta, patchMeta }; for (const key in db) { /* istanbul ignore else */ if (db.hasOwnProperty(key) && key.indexOf('Meta') === -1) { returnObj[key] = db[key]; } } return returnObj; }
javascript
{ "resource": "" }
q53915
connect
train
function connect(busModule) { if (busModule) { module.exports.client = busModule.connect(); BUS_MODULE = true; } else { log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`); module.exports.client = new Redis(process.env.CLAY_BUS_HOST); } }
javascript
{ "resource": "" }
q53916
publish
train
function publish(topic, msg) { if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') { throw new Error('A `topic` (string) and `msg` (object) property must be defined'); } if (module.exports.client && BUS_MODULE) { module.exports.client.publish(`${NAMESPACE}:${topic}`, msg); } else if (module.exports.client) { module.exports.client.publish(`${NAMESPACE}:${topic}`, JSON.stringify(msg)); } }
javascript
{ "resource": "" }
q53917
addSiteData
train
function addSiteData(site) { return (req, res, next) => { res.locals.url = uriToUrl(req.hostname + req.originalUrl, site.protocol, site.port); res.locals.site = site; next(); }; }
javascript
{ "resource": "" }
q53918
addQueryParams
train
function addQueryParams(req, res, next) { _assign(res.locals, req.params, req.query); next(); }
javascript
{ "resource": "" }
q53919
addAvailableRoutes
train
function addAvailableRoutes(router) { return (req, res, next) => { const routes = router.stack .filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff) .map((r) => r.route.path); // pull out their paths res.locals.routes = routes; // and add them to the locals next(); }; }
javascript
{ "resource": "" }
q53920
addAvailableComponents
train
function addAvailableComponents(req, res, next) { res.locals.components = files.getComponents(); next(); }
javascript
{ "resource": "" }
q53921
addUser
train
function addUser(req, res, next) { res.locals.user = req.user; next(); }
javascript
{ "resource": "" }
q53922
isPropagatingVersion
train
function isPropagatingVersion(uri) { const version = uri.split('@')[1]; return !!version && _.includes(propagatingVersions, version); }
javascript
{ "resource": "" }
q53923
uriToUrl
train
function uriToUrl(uri, protocol, port) { // just pretend to start with http; it's overwritten two lines down const parts = urlParse.parse('http://' + uri); parts.protocol = protocol || 'http'; parts.port = port || process.env.PORT; delete parts.host; if (parts.port && (parts.protocol === 'http' && parts.port.toString() === '80') || parts.protocol === 'https' && parts.port.toString() === '443' ) { delete parts.port; } return parts.format(); }
javascript
{ "resource": "" }
q53924
urlToUri
train
function urlToUri(url) { let parts; if (!isUrl(url)) { throw new Error('Invalid url ' + url); } parts = urlParse.parse(url); return `${parts.hostname}${decodeURIComponent(parts.path)}`; }
javascript
{ "resource": "" }
q53925
put
train
function put(uri, data, locals) { let model = files.getComponentModule(getComponentName(uri)), callHooks = _.get(locals, 'hooks') !== 'false', result; if (model && _.isFunction(model.save) && callHooks) { result = models.put(model, uri, data, locals); } else { result = dbOps.putDefaultBehavior(uri, data); } return result; }
javascript
{ "resource": "" }
q53926
getExtension
train
function getExtension(req) { return _.get(req, 'params.ext', '') ? req.params.ext.toLowerCase() : renderers.default; }
javascript
{ "resource": "" }
q53927
findRenderer
train
function findRenderer(extension) { var renderer; // Default to HTML if you don't have an extension extension = extension || renderers.default; // Get the renderer renderer = _.get(renderers, `${extension}`, null); if (renderer) { return renderer; } else { return new Error(`Renderer not found for extension ${extension}`); } }
javascript
{ "resource": "" }
q53928
renderComponent
train
function renderComponent(req, res, hrStart) { var extension = getExtension(req), // Get the extension for the request renderer = findRenderer(extension), // Determine which renderer we are using _ref = req.uri, locals = res.locals, options = options || {}; if (renderer instanceof Error) { log('error', renderer); return Promise.reject(renderer); } // Add request route params, request query params // and the request extension to the locals object locals.params = req.params; locals.query = req.query; locals.extension = extension; return components.get(_ref, locals) .then(cmptData => formDataForRenderer(cmptData, { _ref }, locals)) .tap(logTime(hrStart, _ref)) .then(({data, options}) => renderer.render(data, options, res)) .catch(err => log('error', err)); }
javascript
{ "resource": "" }
q53929
renderPage
train
function renderPage(uri, req, res, hrStart) { const locals = res.locals, extension = getExtension(req), renderer = findRenderer(extension); // Add request route params, request query params // and the request extension to the locals object locals.params = req.params; locals.query = req.query; locals.extension = extension; // look up page alias' component instance return getDBObject(uri) .then(formDataFromLayout(locals, uri)) .then(data => { logTime(hrStart, uri); return data; }) .then(({ data, options }) => renderer.render(data, options, res)) .catch(responses.handleError(res)); }
javascript
{ "resource": "" }
q53930
renderDynamicRoute
train
function renderDynamicRoute(pageId) { return (req, res) => { const hrStart = process.hrtime(), site = res.locals.site, pageUri = `${getExpressRoutePrefix(site)}/_pages/${pageId}@published`; return module.exports.renderPage(pageUri, req, res, hrStart); }; }
javascript
{ "resource": "" }
q53931
formDataFromLayout
train
function formDataFromLayout(locals, uri) { return function (result) { const _layoutRef = result.layout, pageData = references.omitPageConfiguration(result); return components.get(_layoutRef, locals) .then(layout => mapLayoutToPageData(pageData, layout)) .then(mappedData => module.exports.formDataForRenderer(mappedData, { _layoutRef, _ref: uri }, locals)); }; }
javascript
{ "resource": "" }
q53932
formDataForRenderer
train
function formDataForRenderer(unresolvedData, { _layoutRef, _ref }, locals) { return composer.resolveComponentReferences(unresolvedData, locals) .then((data) => ({ data, options: { locals, _ref, _layoutRef } })); }
javascript
{ "resource": "" }
q53933
getExpressRoutePrefix
train
function getExpressRoutePrefix(site) { let prefix = site.host; if (site.path.length > 1) { prefix += site.path; } return prefix; }
javascript
{ "resource": "" }
q53934
renderUri
train
function renderUri(uri, req, res, hrStart) { hrStart = hrStart || process.hrtime(); // Check if we actually have a start time return db.get(uri).then(function (result) { const route = _.find(uriRoutes, function (item) { return result.match(item.when); }); if (!route) { throw new Error('Invalid URI: ' + uri + ': ' + result); } if (route.isUri) { let newBase64Uri = _.last(result.split('/')), newUri = buf.decode(newBase64Uri), newPath = url.parse(`${res.req.protocol}://${newUri}`).path, newUrl = `${res.req.protocol}://${res.req.hostname}${newPath}`, queryString = req._parsedUrl.search; if (queryString) newUrl += queryString; log('info', `Redirecting to ${newUrl}`); res.redirect(301, newUrl); } else { return route.default(result, req, res, hrStart); } }); }
javascript
{ "resource": "" }
q53935
logTime
train
function logTime(hrStart, uri) { return () => { const diff = process.hrtime(hrStart), ms = Math.floor((diff[0] * 1e9 + diff[1]) / 1000000); log('info', `composed data for: ${uri} (${ms}ms)`, { composeTime: ms, uri }); }; }
javascript
{ "resource": "" }
q53936
renderExpressRoute
train
function renderExpressRoute(req, res, next) { var hrStart = process.hrtime(), site = res.locals.site, prefix = `${getExpressRoutePrefix(site)}/_uris/`, pageReference = `${prefix}${buf.encode(req.hostname + req.baseUrl + req.path)}`; return module.exports.renderUri(pageReference, req, res, hrStart) .catch((error) => { if (error.name === 'NotFoundError') { log('error', `could not find resource ${req.uri}`, { message: error.message }); next(); } else { next(error); } }); }
javascript
{ "resource": "" }
q53937
assumePublishedUnlessEditing
train
function assumePublishedUnlessEditing(fn) { return function (uri, req, res, hrStart) { // ignore version if they are editing; default to 'published' if (!_.get(res, 'req.query.edit')) { uri = clayUtils.replaceVersion(uri, uri.split('@')[1] || 'published'); } return fn(uri, req, res, hrStart); }; }
javascript
{ "resource": "" }
q53938
resetUriRouteHandlers
train
function resetUriRouteHandlers() { /** * URIs can point to many different things, and this list will probably grow. * @type {[{when: RegExp, html: function, json: function}]} */ uriRoutes = [ // assume published { when: /\/_pages\//, default: assumePublishedUnlessEditing(renderPage), json: assumePublishedUnlessEditing(getDBObject) }, // assume published { when: /\/_components\//, default: assumePublishedUnlessEditing(renderComponent), json: assumePublishedUnlessEditing(components.get) }, // uris are not published, they only exist { when: /\/_uris\//, isUri: true, html: renderUri, json: db.get }]; }
javascript
{ "resource": "" }
q53939
addAuthenticationRoutes
train
function addAuthenticationRoutes(router) { const authRouter = express.Router(); authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' })); authRouter.use(require('body-parser').text({ type: 'text/*' })); amphoraAuth.addRoutes(authRouter); router.use('/_users', authRouter); }
javascript
{ "resource": "" }
q53940
addSiteController
train
function addSiteController(router, site, providers) { if (site.dir) { const controller = files.tryRequire(site.dir); if (controller) { if (Array.isArray(controller.middleware)) { router.use(controller.middleware); } if (Array.isArray(controller.routes)) { attachRoutes(router, controller.routes, site); } else { log('warn', `There is no router for site: ${site.slug}`); } // Providers are the same across all sites, but this is a convenient // place to store it so that it's available everywhere _.set(site, 'providers', providers); // things to remember from controller _.assign(site, _.pick(controller, 'resolvePublishing')); _.assign(site, _.pick(controller, 'resolvePublishUrl')); _.assign(site, _.pick(controller, 'modifyPublishedData')); } } return router; }
javascript
{ "resource": "" }
q53941
loadFromConfig
train
function loadFromConfig(router, providers, sessionStore) { const sitesMap = siteService.sites(), siteHosts = _.uniq(_.map(sitesMap, 'host')); // iterate through the hosts _.each(siteHosts, hostname => { const sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath); addHost({ router, hostname, sites, providers, sessionStore }); }); return router; }
javascript
{ "resource": "" }
q53942
getConfig
train
function getConfig(dir) { dir = path.resolve(dir); if (dir.indexOf('.', 2) > 0) { // remove extension dir = dir.substring(0, dir.indexOf('.', 2)); } if (files.isDirectory(dir)) { // default to bootstrap.yaml or bootstrap.yml dir = path.join(dir, 'bootstrap'); } return files.getYaml(dir); }
javascript
{ "resource": "" }
q53943
saveWithInstances
train
function saveWithInstances(dbPath, list, save) { const promises = []; // load item defaults _.each(list, function (item, itemName) { let obj = _.omit(item, 'instances'); if (_.isObject(item)) { obj = _.omit(item, 'instances'); if (_.size(obj) > 0) { promises.push(save(dbPath + itemName, obj)); } if (item && item.instances) { // load instances _.each(item.instances, function (instance, instanceId) { if (_.size(instance) > 0) { promises.push(save(dbPath + itemName + '/instances/' + instanceId, instance)); } }); } } }); return bluebird.all(promises); }
javascript
{ "resource": "" }
q53944
saveBase64Strings
train
function saveBase64Strings(dbPath, list, save) { return bluebird.all(_.map(list, function (item, itemName) { return save(dbPath + buf.encode(itemName), item); })); }
javascript
{ "resource": "" }
q53945
load
train
function load(data, site) { let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps, prefix = site.prefix, compData = applyPrefix(data, site); promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation); promiseUrisOps = saveBase64Strings(`${prefix}/_uris/`, compData._uris, getPutOperation); _.each(compData._uris, function (page, uri) { log('info', `bootstrapped: ${uri} => ${page}`); }); promiseComponentsOps = saveWithInstances(`${prefix}/_components/`, compData._components, function (name, item) { return bluebird.join( dbOps.getPutOperations(components.cmptPut, name, _.cloneDeep(item), locals.getDefaultLocals(site)) ).then(_.flatten); }); promisePagesOps = saveObjects(`${prefix}/_pages/`, compData._pages, (name, item) => [getPutOperation(name, item)]); promiseUsersOps = saveObjects('', compData._users, (name, item) => [getPutOperation(`/_users/${encode(`${item.username}@${item.provider}`)}`, item)]); /* eslint max-params: ["error", 5] */ return bluebird.join(promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps, function (componentsOps, pagesOps, urisOps, listsOps, userOps) { const flatComponentsOps = _.flatten(componentsOps), ops = flatComponentsOps.concat(_.flattenDeep(pagesOps.concat(urisOps, listsOps, userOps))); return db.batch(ops, { fillCache: false, sync: false }); }); }
javascript
{ "resource": "" }
q53946
bootstrapPath
train
function bootstrapPath(dir, site) { let promise, data = getConfig(dir); if (data) { promise = load(data, site); } else { promise = Promise.reject(new Error(`No bootstrap found at ${dir}`)); } return promise; }
javascript
{ "resource": "" }
q53947
bootstrapError
train
function bootstrapError(component, e) { if (ERRORING_COMPONENTS.indexOf(component) === -1) { ERRORING_COMPONENTS.push(component); log('error', `Error bootstrapping component ${component}: ${e.message}`); } return bluebird.reject(); }
javascript
{ "resource": "" }
q53948
bootrapSitesAndComponents
train
function bootrapSitesAndComponents() { const sites = siteService.sites(), sitesArray = _.map(Object.keys(sites), site => sites[site]); return highland(sitesArray) .flatMap(site => { return highland( bootstrapComponents(site) .then(function () { return site; }) .catch(function () { log('debug', `Errors bootstrapping components for site: ${site.slug}`); return site; }) ); }) .flatMap(site => { return highland( bootstrapPath(site.dir, site) .catch(function () { log('debug', `No bootstrap file found for site: ${site.slug}`); return site; }) ); }) .collect() .toPromise(bluebird); }
javascript
{ "resource": "" }
q53949
replacePropagatingVersions
train
function replacePropagatingVersions(uri, data) { if (references.isPropagatingVersion(uri)) { references.replaceAllVersions(uri.split('@')[1])(data); } return data; }
javascript
{ "resource": "" }
q53950
splitCascadingData
train
function splitCascadingData(uri, data) { let ops, list; // search for _ref with _size greater than 1 list = references.listDeepObjects(data, isReferencedAndReal); ops = _.map(list.reverse(), function (obj) { const ref = obj[referenceProperty], // since children are before parents, no one will see data below them op = {key: ref, value: _.omit(obj, referenceProperty)}; // omit cloned 1 level deep and we clear what omit cloned from obj // so the op gets the first level of data, but it's removed from the main obj clearOwnProperties(obj); obj[referenceProperty] = ref; return op; }); // add the cleaned root object at the end ops.push({key: uri, value: data}); return ops; }
javascript
{ "resource": "" }
q53951
getPutOperations
train
function getPutOperations(putFn, uri, data, locals) { // potentially propagate version throughout object const cmptOrLayout = splitCascadingData(uri, replacePropagatingVersions(uri, data)); // if locals exist and there are more than one component being put, // then we should pass a read-only version to each component so they can't affect each other // this operation isn't needed in the common case of putting a single object if (!!locals && cmptOrLayout.length > 0) { locals = control.setReadOnly(_.cloneDeep(locals)); } // run each through the normal put, which may or may not hit custom component logic return bluebird.map(cmptOrLayout, ({ key, value }) => putFn(key, value, locals)) .then(ops => _.filter(_.flattenDeep(ops), _.identity)); }
javascript
{ "resource": "" }
q53952
train
function(e) { e.preventDefault(); var group = e.group; var toZoom; if (group) { toZoom = e.secondary ? group.parent : group; } else { toZoom = this.get('dataObject'); } this.zoom(toZoom); }
javascript
{ "resource": "" }
q53953
formatProjectPath
train
function formatProjectPath(filePath = '') { let dir = path.relative(process.cwd(), path.dirname(filePath)); return dir + (dir ? path.sep : '') + path.basename(filePath); }
javascript
{ "resource": "" }
q53954
format
train
function format(string) { string = _.toString(string); // Replace all code snippets with a token. var snippets = []; string = string.replace(reCode, function(match) { snippets.push(match); return token; }); return string // Add line breaks. .replace(/:\n(?=[\t ]*\S)/g, ':<br>\n') .replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*') .replace(/^[\t ]*\n/gm, '<br>\n<br>\n') // Normalize whitespace. .replace(/\n +/g, ' ') // Italicize parentheses. .replace(/(^|\s)(\(.+\))/g, '$1*$2*') // Mark numbers as inline code. .replace(/[\t ](-?\d+(?:.\d+)?)(?!\.[^\n])/g, ' `$1`') // Replace all tokens with code snippets. .replace(reToken, function(match) { return snippets.shift(); }) .trim(); }
javascript
{ "resource": "" }
q53955
docdown
train
function docdown(options) { options = _.defaults(options, { 'lang': 'js', 'sort': true, 'style': 'default', 'title': path.basename(options.path) + ' API documentation', 'toc': 'properties' }); if (!options.path || !options.url) { throw new Error('Path and URL must be specified'); } return generator(fs.readFileSync(options.path, 'utf8'), options); }
javascript
{ "resource": "" }
q53956
getTag
train
function getTag(entry, tagName) { var parsed = entry.parsed; return _.find(parsed.tags, ['title', tagName]) || null; }
javascript
{ "resource": "" }
q53957
getValue
train
function getValue(entry, tagName) { var parsed = entry.parsed, result = parsed.description, tag = getTag(entry, tagName); if (tagName == 'alias') { result = _.get(tag, 'name') ; // Doctrine can't parse alias tags containing multiple values so extract // them from the error message. var error = _.first(_.get(tag, 'errors')); if (error) { result += error.replace(/^[^']*'|'[^']*$/g, ''); } } else if (tagName == 'type') { result = _.get(tag, 'type.name'); } else if (tagName != 'description') { result = _.get(tag, 'name') || _.get(tag, 'description'); } return tagName == 'example' ? _.toString(result) : util.format(result); }
javascript
{ "resource": "" }
q53958
getAliases
train
function getAliases(index) { if (this._aliases === undefined) { var owner = this; this._aliases = _(getValue(this, 'alias')) .split(/,\s*/) .compact() .sort(util.compareNatural) .map(function(value) { return new Alias(value, owner); }) .value(); } var result = this._aliases; return index === undefined ? result : result[index]; }
javascript
{ "resource": "" }
q53959
getCall
train
function getCall() { var result = _.trim(_.get(/\*\/\s*(?:function\s+)?([^\s(]+)\s*\(/.exec(this.entry), 1)); if (!result) { result = _.trim(_.get(/\*\/\s*(.*?)[:=,]/.exec(this.entry), 1)); result = /['"]$/.test(result) ? _.trim(result, '"\'') : result.split('.').pop().split(/^(?:const|let|var) /).pop(); } var name = getValue(this, 'name') || result; if (!this.isFunction()) { return name; } var params = this.getParams(); result = _.castArray(result); // Compile the function call syntax. _.each(params, function(param) { var paramValue = param[1], parentParam = _.get(/\w+(?=\.[\w.]+)/.exec(paramValue), 0); var parentIndex = parentParam == null ? -1 : _.findIndex(params, function(param) { return _.trim(param[1], '[]').split(/\s*=/)[0] == parentParam; }); // Skip params that are properties of other params (e.g. `options.leading`). if (_.get(params[parentIndex], 0) != 'Object') { result.push(paramValue); } }); // Format the function call. return name + '(' + result.slice(1).join(', ') + ')'; }
javascript
{ "resource": "" }
q53960
getDesc
train
function getDesc() { var type = this.getType(), result = getValue(this, 'description'); return (!result || type == 'Function' || type == 'unknown') ? result : ('(' + _.trim(type.replace(/\|/g, ', '), '()') + '): ' + result); }
javascript
{ "resource": "" }
q53961
getHash
train
function getHash(style) { var result = _.toString(this.getMembers(0)); if (style == 'github') { if (result) { result += this.isPlugin() ? 'prototype' : ''; } result += this.getCall(); return result .replace(/[\\.=|'"(){}\[\]\t ]/g, '') .replace(/[#,]+/g, '-') .toLowerCase(); } if (result) { result += '-' + (this.isPlugin() ? 'prototype-' : ''); } result += this.isAlias() ? this.getOwner().getName() : this.getName(); return result .replace(/\./g, '-') .replace(/^_-/, ''); }
javascript
{ "resource": "" }
q53962
getLineNumber
train
function getLineNumber() { var lines = this.source .slice(0, this.source.indexOf(this.entry) + this.entry.length) .match(/\n/g) .slice(1); // Offset by 2 because the first line number is before a line break and the // last line doesn't include a line break. return lines.length + 2; }
javascript
{ "resource": "" }
q53963
getMembers
train
function getMembers(index) { if (this._members === undefined) { this._members = _(getValue(this, 'member') || getValue(this, 'memberOf')) .split(/,\s*/) .compact() .sort(util.compareNatural) .value(); } var result = this._members; return index === undefined ? result : result[index]; }
javascript
{ "resource": "" }
q53964
getParams
train
function getParams(index) { if (this._params === undefined) { this._params = _(this.parsed.tags) .filter(['title', 'param']) .filter('name') .map(function(tag) { var defaultValue = tag['default'], desc = util.format(tag.description), name = _.toString(tag.name), type = getParamType(tag.type); if (defaultValue != null) { name += '=' + defaultValue; } if (_.get(tag, 'type.type') == 'OptionalType') { name = '[' + name + ']'; } return [type, name, desc]; }) .value(); } var result = this._params; return index === undefined ? result : result[index]; }
javascript
{ "resource": "" }
q53965
getRelated
train
function getRelated() { var relatedValues = getValue(this, 'see'); if (relatedValues && relatedValues.trim().length > 0) { var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim()); return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')'); } else { return []; } }
javascript
{ "resource": "" }
q53966
getReturns
train
function getReturns() { var tag = getTag(this, 'returns'), desc = _.toString(_.get(tag, 'description')), type = _.toString(_.get(tag, 'type.name')) || '*'; return tag ? [type, desc] : []; }
javascript
{ "resource": "" }
q53967
getType
train
function getType() { var result = getValue(this, 'type'); if (!result) { return this.isFunction() ? 'Function' : 'unknown'; } return /^(?:array|function|object|regexp)$/.test(result) ? _.capitalize(result) : result; }
javascript
{ "resource": "" }
q53968
isFunction
train
function isFunction() { return !!( this.isCtor() || _.size(this.getParams()) || _.size(this.getReturns()) || hasTag(this, 'function') || /\*\/\s*(?:function\s+)?[^\s(]+\s*\(/.test(this.entry) ); }
javascript
{ "resource": "" }
q53969
train
function (buffer) { var element = buffer.element(); var dom = buffer.dom; var container = dom.createElement('div'); container.className = 'ember-list-container'; element.appendChild(container); this._childViewsMorph = dom.appendMorph(container, container, null); return container; }
javascript
{ "resource": "" }
q53970
_getRegistryErrorMessage
train
function _getRegistryErrorMessage(err) { if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) { return err.body.errors[0].message; } else if (err.body && err.body.details) { return err.body.details; } else if (Array.isArray(err.errors) && err.errors[0].message) { return err.errors[0].message; } else if (err.message) { return err.message; } return err.toString(); }
javascript
{ "resource": "" }
q53971
_getRegistryErrMessage
train
function _getRegistryErrMessage(body) { if (!body) { return null; } var obj = body; if (typeof (obj) === 'string' && obj.length <= MAX_REGISTRY_ERROR_LENGTH) { try { obj = JSON.parse(obj); } catch (ex) { // Just return the error as a string. return obj; } } if (typeof (obj) !== 'object' || !obj.hasOwnProperty('errors')) { return null; } if (!Array.isArray(obj.errors)) { return null; } // Example obj: // { // "errors": [ // { // "code": "MANIFEST_INVALID", // "message": "manifest invalid", // "detail": {} // } // ] // } if (obj.errors.length === 1) { return obj.errors[0].message; } else { return obj.errors.map(function (o) { return o.message; }).join(', '); } }
javascript
{ "resource": "" }
q53972
registryError
train
function registryError(err, res, callback) { var body = ''; res.on('data', function onResChunk(chunk) { body += chunk; }); res.on('end', function onResEnd() { // Parse errors in the response body. var message = _getRegistryErrMessage(body); if (message) { err.message = message; } callback(err); }); }
javascript
{ "resource": "" }
q53973
digestFromManifestStr
train
function digestFromManifestStr(manifestStr) { assert.string(manifestStr, 'manifestStr'); var hash = crypto.createHash('sha256'); var digestPrefix = 'sha256:'; var manifest; try { manifest = JSON.parse(manifestStr); } catch (err) { throw new restifyErrors.InvalidContentError(err, fmt( 'could not parse manifest: %s', manifestStr)); } if (manifest.schemaVersion === 1) { try { var manifestBuffer = Buffer(manifestStr); var jws = _jwsFromManifest(manifest, manifestBuffer); hash.update(jws.payload, 'binary'); return digestPrefix + hash.digest('hex'); } catch (verifyErr) { if (!(verifyErr instanceof restifyErrors.InvalidContentError)) { throw verifyErr; } // Couldn't parse (or doesn't have) the signatures section, // fall through. } } hash.update(manifestStr); return digestPrefix + hash.digest('hex'); }
javascript
{ "resource": "" }
q53974
wrappedMapper
train
function wrappedMapper (input, number, callback) { return mapper.call(null, input, function(err, data){ callback(err, data, number) }) }
javascript
{ "resource": "" }
q53975
factory
train
function factory(BaseClass, mapFunction) { function subject(value) { if (typeof mapFunction === 'function') { value = mapFunction.apply(undefined, arguments); } else if (typeof mapFunction !== 'undefined') { value = mapFunction; } subject.onNext(value); return value; } for (var key in BaseClass.prototype) { subject[key] = BaseClass.prototype[key]; } BaseClass.apply(subject, [].slice.call(arguments, 2)); return subject; }
javascript
{ "resource": "" }
q53976
waitUntil
train
function waitUntil(fun) { var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20; var timedOut = false; var ok = false; if (timeout !== 0) (0, _wait2['default'])(timeout).then(function () { return timedOut = true; }); return new Promise(function (resolve, reject) { var runLoop = function runLoop() { if (ok) { resolve(); return; } if (timedOut) { reject(new Error('AsyncTestUtil.waitUntil(): reached timeout of ' + timeout + 'ms')); return; } (0, _wait2['default'])(interval).then(function () { var value = (0, _promisify2['default'])(fun()); value.then(function (val) { ok = val; runLoop(); }); }); }; runLoop(); }); }
javascript
{ "resource": "" }
q53977
resolveValues
train
function resolveValues(obj) { var ret = {}; return Promise.all(Object.keys(obj).map(function (k) { var val = (0, _promisify2['default'])(obj[k]); return val.then(function (v) { return ret[k] = v; }); })).then(function () { return ret; }); }
javascript
{ "resource": "" }
q53978
assertThrows
train
function assertThrows(test) { var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; if (!Array.isArray(contains)) contains = [contains]; var shouldErrorName = typeof error === 'string' ? error : error.name; var nonThrown = new Error('util.assertThrowsAsync(): Missing rejection' + (error ? ' with ' + error.name : '')); var ensureErrorMatches = function ensureErrorMatches(error) { // wrong type if (error.constructor.name != shouldErrorName) { return new Error('\n util.assertThrowsAsync(): Wrong Error-type\n - is : ' + error.constructor.name + '\n - should: ' + shouldErrorName + '\n - error: ' + error.toString() + '\n '); } // check if contains var errorString = error.toString(); if (contains.length > 0 && (0, _utils.oneOfArrayNotInString)(contains, errorString)) { return new Error('\n util.assertThrowsAsync(): Error does not contain\n - should contain: ' + contains + '\n - is string: ' + error.toString() + '\n '); } return false; }; return new Promise(function (res, rej) { var val = void 0; try { val = test(); } catch (err) { var wrong = ensureErrorMatches(err); if (wrong) rej(wrong);else res(err); return; } if ((0, _isPromise2['default'])(val)) { val.then(function () { // has not thrown rej(nonThrown); })['catch'](function (err) { var wrong = ensureErrorMatches(err); if (wrong) rej(wrong);else res(err); }); } else rej(nonThrown); }); }
javascript
{ "resource": "" }
q53979
waitResolveable
train
function waitResolveable() { var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var ret = {}; ret.promise = new Promise(function (res) { ret.resolve = function (x) { return res(x); }; setTimeout(res, ms); }); return ret; }
javascript
{ "resource": "" }
q53980
randomNumber
train
function randomNumber() { var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000; return Math.floor(Math.random() * (max - min + 1)) + min; }
javascript
{ "resource": "" }
q53981
a11yPromise
train
function a11yPromise (url, viewportSize, verbose) { var deferred = Q.defer(); a11y(url, {viewportSize: viewportSize}, function (err, reports) { if (err) { deferred.reject(new Error(err)); } else { deferred.resolve({url: url, reports: reports, verbose: verbose}); } }); return deferred.promise; }
javascript
{ "resource": "" }
q53982
logReports
train
function logReports (url, reports, verbose) { var passes = ''; var failures = ''; grunt.log.writeln(chalk.underline(chalk.cyan('\nReport for ' + url + '\n'))); reports.audit.forEach(function (el) { if (el.result === 'PASS') { passes += logSymbols.success + ' ' + el.heading + '\n'; } if (el.result === 'FAIL') { failures += logSymbols.error + ' ' + el.heading + '\n'; failures += el.elements + '\n\n'; } }); grunt.log.writeln(indent(failures, ' ', 2)); grunt.log.writeln(indent(passes , ' ', 2)); if (verbose) { grunt.log.writeln('VERBOSE OUTPUT\n', reports.audit); } return !failures.length; }
javascript
{ "resource": "" }
q53983
randomString
train
function randomString() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'abcdefghijklmnopqrstuvwxyz'; var text = ''; for (var i = 0; i < length; i++) { text += charset.charAt(Math.floor(Math.random() * charset.length)); }return text; }
javascript
{ "resource": "" }
q53984
_prepSnapshot
train
function _prepSnapshot() { var config = this.constructor.config, copy = (config.snapshotSerializer || config.serializer).serialize(this); // we don't want to store our snapshots in the snapshots because that would make the rollback kind of funny // not to mention using more memory for each snapshot. delete copy.$$snapshots; return copy }
javascript
{ "resource": "" }
q53985
rollback
train
function rollback(numVersions) { var snapshotsLength = this.$$snapshots ? this.$$snapshots.length : 0; numVersions = Math.min(numVersions || 1, snapshotsLength); if (numVersions < 0) { numVersions = snapshotsLength; } if (snapshotsLength) { this.rollbackTo(this.$$snapshots.length - numVersions); } return true; }
javascript
{ "resource": "" }
q53986
unsnappedChanges
train
function unsnappedChanges() { if (!this.$$snapshots) { return true } var copy = this._prepSnapshot(), latestSnap = this.$$snapshots[this.$$snapshots.length - 1] return !angular.equals(copy, latestSnap) }
javascript
{ "resource": "" }
q53987
getService
train
function getService(service) { // strings and functions are not considered objects by angular.isObject() if (angular.isObject(service)) { return service; } else if (service) { return createService(service); } return undefined; }
javascript
{ "resource": "" }
q53988
MongolianGridFileWriteStream
train
function MongolianGridFileWriteStream(file) { if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported") if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize) stream.Stream.call(this) this.file = file this.writable = true this.encoding = 'binary' this._hash = crypto.createHash('md5') this._chunkIndex = 0 file.length = 0 this._chunkSize = file.chunkSize }
javascript
{ "resource": "" }
q53989
MongolianGridFileReadStream
train
function MongolianGridFileReadStream(file) { if (!file._id) throw new Error("Can only read files retrieved from the database") if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported") if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize) stream.Stream.call(this) this.file = file this.readable = true this._chunkCount = file.chunkCount() this._chunkIndex = 0 process.nextTick(this._nextChunk.bind(this)) }
javascript
{ "resource": "" }
q53990
MongolianServer
train
function MongolianServer(mongolian, url) { var self = this this.mongolian = mongolian this.url = url this._callbacks = [] this._callbackCount = 0 this._connection = taxman(function(callback) { var connection = new Connection var connected = false connection.requestId = 0 connection.on('error', function(error) { mongolian.log.error(self+": "+require('util').inspect(error)) if (!connected) callback(error) self.close(error) }) connection.on('close', function() { mongolian.log.debug(self+": Disconnected") self.close() }) connection.on('connect',function() { mongolian.log.debug(self+": Connected") connected = true callback(null, connection) }) connection.on('message', function(message) { var response = new mongo.Response(message) // mongolian.log.debug("<<<--- "+require('util').inspect(response,undefined,5,true).slice(0,5000)) var cb = self._callbacks[response.responseTo] if (cb) { delete self._callbacks[response.responseTo] self._callbackCount-- cb(null,response) } }) connection.connect(url.port, url.host) }) }
javascript
{ "resource": "" }
q53991
fillCollection
train
function fillCollection(collection, max, callback) { collection.count(function(err,count) { console.log(collection+" count = "+count) while (count < max) { var toInsert = [] while (count < max) { toInsert.push({ foo: Math.random(), index: count++ }) if (toInsert.length == 300) { break } } console.log("inserting "+toInsert.length+" document(s) into "+collection) collection.insert(toInsert) } callback() }) }
javascript
{ "resource": "" }
q53992
funBuffer
train
function funBuffer(size) { var buffer = new Buffer(size) for (var i=0; i<size; i++) { if (i%1000 == 0) buffer[i++] = 13 buffer[i] = 97 + (i%26) } return buffer }
javascript
{ "resource": "" }
q53993
safeGet
train
function safeGet (obj, path) { // split ['c:chart'].row[0] into ['c:chart', 'row', 0] var paths = path.replace(/\[/g, '.').replace(/\]/g, '').replace(/'/g, '').split('.') for (var i = 0; i < paths.length; i++) { if (paths[i] === '') { // the first can be empty string if the path starts with ['chart:c'] continue } var objReference = 'obj["' + paths[i] + '"]' // the last must be always array, also if accessor is number, we want to initialize as array var emptySafe = ((i === paths.length - 1) || !isNaN(paths[i + 1])) ? '[]' : '{}' new Function('obj', objReference + ' = ' + objReference + ' || ' + emptySafe)(obj) obj = new Function('obj', 'return ' + objReference)(obj) } return obj }
javascript
{ "resource": "" }
q53994
train
function (name,val) { var cookieVal = $.cookie(this.cookieName); cookieVal = ((cookieVal === null) || (cookieVal === "")) ? name+"~"+val : cookieVal+"|"+name+"~"+val; $.cookie(this.cookieName,cookieVal); }
javascript
{ "resource": "" }
q53995
train
function (name,val) { if (this.findValue(name)) { var updateCookieVals = ""; var cookieVals = $.cookie(this.cookieName).split("|"); for (var i = 0; i < cookieVals.length; i++) { var fieldVals = cookieVals[i].split("~"); if (fieldVals[0] == name) { fieldVals[1] = val; } updateCookieVals += (i > 0) ? "|"+fieldVals[0]+"~"+fieldVals[1] : fieldVals[0]+"~"+fieldVals[1]; } $.cookie(this.cookieName,updateCookieVals); } else { this.addValue(name,val); } }
javascript
{ "resource": "" }
q53996
train
function (name) { var updateCookieVals = ""; var cookieVals = $.cookie(this.cookieName).split("|"); var k = 0; for (var i = 0; i < cookieVals.length; i++) { var fieldVals = cookieVals[i].split("~"); if (fieldVals[0] != name) { updateCookieVals += (k === 0) ? fieldVals[0]+"~"+fieldVals[1] : "|"+fieldVals[0]+"~"+fieldVals[1]; k++; } } $.cookie(this.cookieName,updateCookieVals); }
javascript
{ "resource": "" }
q53997
train
function() { // the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location var oGetVars = new (function (sSearch) { if (sSearch.length > 1) { for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) { aItKey = aCouples[nKeyId].split("="); this[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : ""; } } })(window.location.search); return oGetVars; }
javascript
{ "resource": "" }
q53998
train
function (pattern, givenPath) { var data = { "pattern": pattern }; var fileName = urlHandler.getFileName(pattern); var path = window.location.pathname; path = (window.location.protocol === "file") ? path.replace("/public/index.html","public/") : path.replace(/\/index\.html/,"/"); var expectedPath = window.location.protocol+"//"+window.location.host+path+fileName; if (givenPath != expectedPath) { // make sure to update the iframe because there was a click var obj = JSON.stringify({ "event": "patternLab.updatePath", "path": fileName }); document.getElementById("sg-viewport").contentWindow.postMessage(obj, urlHandler.targetOrigin); } else { // add to the history var addressReplacement = (window.location.protocol == "file:") ? null : window.location.protocol+"//"+window.location.host+window.location.pathname.replace("index.html","")+"?p="+pattern; if (history.pushState !== undefined) { history.pushState(data, null, addressReplacement); } document.getElementById("title").innerHTML = "Pattern Lab - "+pattern; if (document.getElementById("sg-raw") !== null) { document.getElementById("sg-raw").setAttribute("href",urlHandler.getFileName(pattern)); } } }
javascript
{ "resource": "" }
q53999
train
function() { // make sure the modal viewer and other options are off just in case modalViewer.close(); // note it's turned on in the viewer DataSaver.updateValue('modalActive', 'true'); modalViewer.active = true; // add an active class to the button that matches this template $('#sg-t-'+modalViewer.template+' .sg-checkbox').addClass('active'); //Add active class to modal $('#sg-modal-container').addClass('active'); // show the modal modalViewer.show(); }
javascript
{ "resource": "" }