_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q21300
|
train
|
function (cb) {
var self = this;
var dirs = ['classes', 'modules', 'files'];
if (self.options.dumpview) {
dirs.push('json');
}
var writeRedirect = function (dir, file, cb) {
Y.Files.exists(file, function (x) {
if (x) {
var out = path.join(dir, 'index.html');
fs.createReadStream(file).pipe(fs.createWriteStream(out));
}
cb();
});
};
var defaultIndex = path.join(themeDir, 'assets', 'index.html');
var stack = new Y.Parallel();
Y.log('Making default directories: ' + dirs.join(','), 'info', 'builder');
dirs.forEach(function (d) {
var dir = path.join(self.options.outdir, d);
Y.Files.exists(dir, stack.add(function (x) {
if (!x) {
fs.mkdir(dir, 0777, stack.add(function () {
writeRedirect(dir, defaultIndex, stack.add(noop));
}));
} else {
writeRedirect(dir, defaultIndex, stack.add(noop));
}
}));
});
stack.done(function () {
if (cb) {
cb();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21301
|
train
|
function (cb) {
var self = this;
Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function (err, opts) {
opts.meta.title = self.data.project.name;
opts.meta.projectRoot = './';
opts.meta.projectAssets = './assets';
opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
opts = self.populateClasses(opts);
opts = self.populateModules(opts);
var view = new Y.DocView(opts.meta);
self.render('{{>index}}', view, opts.layouts.main, opts.partials, function (err, html) {
self.files++;
cb(html, view);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21302
|
train
|
function (cb) {
var self = this,
stack = new Y.Parallel();
Y.log('Preparing index.html', 'info', 'builder');
self.renderIndex(stack.add(function (html, view) {
stack.html = html;
stack.view = view;
if (self.options.dumpview) {
Y.Files.writeFile(path.join(self.options.outdir, 'json', 'index.json'), JSON.stringify(view), stack.add(noop));
}
Y.Files.writeFile(path.join(self.options.outdir, 'index.html'), html, stack.add(noop));
}));
stack.done(function ( /* html, view */ ) {
Y.log('Writing index.html', 'info', 'builder');
cb(stack.html, stack.view);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21303
|
train
|
function (info, classItems, first) {
var self = this;
self._mergeCounter = (first) ? 0 : (self._mergeCounter + 1);
if (self._mergeCounter === 100) {
throw ('YUIDoc detected a loop extending class ' + info.name);
}
if (info.extends || info.uses) {
var hasItems = {};
hasItems[info.extends] = 1;
if (info.uses) {
info.uses.forEach(function (v) {
hasItems[v] = 1;
});
}
self.data.classitems.forEach(function (v) {
//console.error(v.class, '==', info.extends);
if (hasItems[v.class]) {
if (!v.static) {
var q,
override = self.hasProperty(classItems, v);
if (override === false) {
//This method was extended from the parent class but not over written
//console.error('Merging extends from', v.class, 'onto', info.name);
q = Y.merge({}, v);
q.extended_from = v.class;
classItems.push(q);
} else {
//This method was extended from the parent and overwritten in this class
q = Y.merge({}, v);
q = self.augmentData(q);
classItems[override].overwritten_from = q;
}
}
}
});
if (self.data.classes[info.extends]) {
if (self.data.classes[info.extends].extends || self.data.classes[info.extends].uses) {
//console.error('Stepping down to:', self.data.classes[info.extends]);
classItems = self.mergeExtends(self.data.classes[info.extends], classItems);
}
}
}
return classItems;
}
|
javascript
|
{
"resource": ""
}
|
|
q21304
|
train
|
function (cb, data, layout) {
var self = this;
Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function (err, opts) {
if (err) {
console.log(err);
}
if (!data.name) {
return;
}
opts.meta = Y.merge(opts.meta, data);
opts.meta.title = self.data.project.name;
opts.meta.moduleName = data.name;
opts.meta.projectRoot = '../';
opts.meta.projectAssets = '../assets';
opts.meta.projectLogo = self._resolveUrl(self.data.project.logo, opts);
opts = self.populateClasses(opts);
opts = self.populateModules(opts);
opts = self.populateFiles(opts);
opts.meta.fileName = data.name;
fs.readFile(opts.meta.fileName, Y.charset, Y.rbind(function (err, str, opts, data) {
if (err) {
Y.log(err, 'error', 'builder');
cb(err);
return;
}
if (typeof self.options.tabspace === 'string') {
str = str.replace(/\t/g, self.options.tabspace);
}
opts.meta.fileData = str;
var view = new Y.DocView(opts.meta, 'index');
var mainLayout = opts.layouts[layout];
self.render('{{>files}}', view, mainLayout, opts.partials, function (err, html) {
self.files++;
cb(html, view, data);
});
}, this, opts, data));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21305
|
train
|
function (cb) {
Y.log('Writing API Meta Data', 'info', 'builder');
var self = this;
this.renderAPIMeta(function (js) {
fs.writeFile(path.join(self.options.outdir, 'api.js'), js, Y.charset, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21306
|
train
|
function (cb) {
var opts = {
meta: {}
};
opts = this.populateClasses(opts);
opts = this.populateModules(opts);
['classes', 'modules'].forEach(function (id) {
opts.meta[id].forEach(function (v, k) {
opts.meta[id][k] = v.name;
if (v.submodules) {
v.submodules.forEach(function (s) {
opts.meta[id].push(s.displayName);
});
}
});
opts.meta[id].sort();
});
var apijs = 'YUI.add("yuidoc-meta", function(Y) {\n' +
' Y.YUIDoc = { meta: ' + JSON.stringify(opts.meta, null, 4) + ' };\n' +
'});';
cb(apijs);
}
|
javascript
|
{
"resource": ""
}
|
|
q21307
|
train
|
function (cb) {
var self = this;
var starttime = (new Date()).getTime();
Y.log('Compiling Templates', 'info', 'builder');
this.mixExternal(function () {
self.makeDirs(function () {
Y.log('Copying Assets', 'info', 'builder');
if (!Y.Files.isDirectory(path.join(self.options.outdir, 'assets'))) {
fs.mkdirSync(path.join(self.options.outdir, 'assets'), 0777);
}
Y.Files.copyAssets([
path.join(DEFAULT_THEME, 'assets'),
path.join(themeDir, 'assets')
],
path.join(self.options.outdir, 'assets'),
false,
function () {
var cstack = new Y.Parallel();
self.writeModules(cstack.add(function () {
self.writeClasses(cstack.add(function () {
if (!self.options.nocode) {
self.writeFiles(cstack.add(noop));
}
}));
}));
/*
self.writeModules(cstack.add(noop));
self.writeClasses(cstack.add(noop));
if (!self.options.nocode) {
self.writeFiles(cstack.add(noop));
}
*/
self.writeIndex(cstack.add(noop));
self.writeAPIMeta(cstack.add(noop));
cstack.done(function () {
var endtime = (new Date()).getTime();
var timer = ((endtime - starttime) / 1000) + ' seconds';
Y.log('Finished writing ' + self.files + ' files in ' + timer, 'info', 'builder');
if (cb) {
cb();
}
});
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q21308
|
parseMulti
|
train
|
function parseMulti(str, compare, arr) {
// TODO: add logic to deal with "0" values? Troublesome because the browser automatically appends a unit for some 0 values.
do {
// pull out the next value (ex. "20px", "12.4rad"):
var result = s.TRANSFORM_VALUE_RE.exec(str);
if (!result) { return arr; }
if (!arr) { arr = []; }
arr.push(+result[1], result[2]);
// check that the units match (ex. "px" vs "em"):
if (compare && (compare[arr.length-1] !== result[2])) { console.log("transform units don't match: ",arr[0], compare[arr.length-1], result[2]); compare=null; } // unit doesn't match
} while(true);
}
|
javascript
|
{
"resource": ""
}
|
q21309
|
TweenGroup
|
train
|
function TweenGroup(paused, timeScale) {
this._tweens = [];
this.paused = paused;
this.timeScale = timeScale;
this.__onComplete = this._onComplete.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q21310
|
extractOriginHeaders_
|
train
|
function extractOriginHeaders_(headers) {
const result = {
isSameOrigin: false,
};
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
const normalizedKey = key.toLowerCase();
// for same-origin requests where the Origin header is missing, AMP sets the amp-same-origin header
if (normalizedKey === 'amp-same-origin') {
result.isSameOrigin = true;
return result;
}
// use the origin header otherwise
if (normalizedKey === 'origin') {
result.origin = headers[key];
return result;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q21311
|
isValidOrigin
|
train
|
async function isValidOrigin(origin, sourceOrigin) {
// This will fetch the caches from https://cdn.ampproject.org/caches.json the first time it's
// called. Subsequent calls will receive a cached version.
const officialCacheList = await caches.list();
// Calculate the cache specific origin
const cacheSubdomain = `https://${await createCacheSubdomain(sourceOrigin)}.`;
// Check all caches listed on ampproject.org
for (const cache of officialCacheList) {
const cachedOrigin = cacheSubdomain + cache.cacheDomain;
if (origin === cachedOrigin) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q21312
|
findMetaViewport
|
train
|
function findMetaViewport(head) {
for (let node = head.firstChild; node !== null; node = node.nextSibling) {
if (node.tagName === 'meta' && node.attribs.name === 'viewport') {
return node;
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q21313
|
oneBehindFetch
|
train
|
async function oneBehindFetch(input, init) {
let cachedResponse = cache.get(input);
if (!cachedResponse) {
cachedResponse = {
maxAge: Promise.resolve(MaxAge.zero()),
};
cache.set(input, cachedResponse);
}
const maxAge = await cachedResponse.maxAge;
if (!maxAge.isExpired()) {
// we have to clone the response to enable multiple reads
const response = await cachedResponse.responsePromise;
return response.clone();
}
const staleResponsePromise = cachedResponse.responsePromise;
const newResponsePromise = fetch(input, init);
cachedResponse = {
responsePromise: newResponsePromise,
maxAge: newResponsePromise.then(
(response) => MaxAge.parse(response.headers.get('cache-control'))
),
};
cache.set(input, cachedResponse);
const result = staleResponsePromise || newResponsePromise;
// we have to clone the response to enable multiple reads
const response = await result;
return response.clone();
}
|
javascript
|
{
"resource": ""
}
|
q21314
|
copyAndTransform
|
train
|
async function copyAndTransform(file, ampRuntimeVersion) {
const originalHtml = await readFile(file);
const ampFile = file.substring(1, file.length)
.replace('.html', '.amp.html');
const allTransformationsFile = file.substring(1, file.length)
.replace('.html', '.all.html');
const validTransformationsFile = file.substring(1, file.length)
.replace('.html', '.valid.html');
// Transform into valid optimized AMP
ampOptimizer.setConfig({
validAmp: true,
verbose: true,
});
const validOptimizedHtml = await ampOptimizer.transformHtml(originalHtml);
// Run all optimizations including versioned AMP runtime URLs
ampOptimizer.setConfig({
validAmp: false,
verbose: true,
});
// The transformer needs the path to the original AMP document
// to correctly setup AMP to canonical linking
const optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {
ampUrl: ampFile,
ampRuntimeVersion: ampRuntimeVersion,
});
writeFile(allTransformationsFile, optimizedHtml);
writeFile(validTransformationsFile, validOptimizedHtml);
// We change the path of the original AMP file to match the new
// amphtml link and make the canonical link point to the transformed version.
writeFile(ampFile, originalHtml);
}
|
javascript
|
{
"resource": ""
}
|
q21315
|
collectInputFiles
|
train
|
function collectInputFiles(pattern) {
return new Promise((resolve, reject) => {
glob(pattern, {root: SRC_DIR, nomount: true}, (err, files) => {
if (err) {
return reject(err);
}
resolve(files);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21316
|
setFSEventsListener
|
train
|
function setFSEventsListener(path, realPath, listener, rawEmitter) {
let watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;
const parentPath = sysPath.dirname(watchPath);
let cont = FSEventsWatchers.get(watchPath);
// If we've accumulated a substantial number of paths that
// could have been consolidated by watching one directory
// above the current one, create a watcher on the parent
// path instead, so that we do consolidate going forward.
if (couldConsolidate(parentPath)) {
watchPath = parentPath;
}
const resolvedPath = sysPath.resolve(path);
const hasSymlink = resolvedPath !== realPath;
const filteredListener = (fullPath, flags, info) => {
if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
if (
fullPath === resolvedPath ||
!fullPath.indexOf(resolvedPath + sysPath.sep)
) listener(fullPath, flags, info);
};
// check if there is already a watcher on a parent path
// modifies `watchPath` to the parent path when it finds a match
const watchedParent = () => {
for (const watchedPath of FSEventsWatchers.keys()) {
if (realPath.indexOf(sysPath.resolve(watchedPath) + sysPath.sep) === 0) {
watchPath = watchedPath;
cont = FSEventsWatchers.get(watchPath);
return true;
}
}
};
if (cont || watchedParent()) {
cont.listeners.add(filteredListener);
} else {
cont = {
listeners: new Set([filteredListener]),
rawEmitter: rawEmitter,
watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
const info = fsevents.getInfo(fullPath, flags);
cont.listeners.forEach(list => {
list(fullPath, flags, info);
});
cont.rawEmitter(info.event, fullPath, info);
})
};
FSEventsWatchers.set(watchPath, cont);
}
// removes this instance's listeners and closes the underlying fsevents
// instance if there are no more listeners left
return () => {
const wl = cont.listeners;
wl.delete(filteredListener);
if (!wl.size) {
FSEventsWatchers.delete(watchPath);
cont.watcher.stop();
cont.rawEmitter = cont.watcher = null;
Object.freeze(cont);
Object.freeze(cont.listeners);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q21317
|
createFsWatchInstance
|
train
|
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path);
emitRaw(rawEvent, evPath, {watchedPath: path});
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (and rely on throttling to de-dupe)
if (evPath && path !== evPath) {
fsWatchBroadcast(
sysPath.resolve(path, evPath), 'listeners', sysPath.join(path, evPath)
);
}
};
try {
return fs.watch(path, options, handleEvent);
} catch (error) {
errHandler(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q21318
|
abbr
|
train
|
function abbr(str) {
if (/total|overall/i.test(str)) return str.trim();
return str.replace(/\w+\s?/g, a => a[0]);
}
|
javascript
|
{
"resource": ""
}
|
q21319
|
validateMessageFormat
|
train
|
function validateMessageFormat(message) {
function validateTypeStructure(message) {
const typeParts = message.type.split('.'),
baseType = typeParts[0],
typeDepth = typeParts.length;
if (typeDepth > 2)
throw new Error(
'Message type has too many dot separated sections: ' + message.type
);
const previousDepth = messageTypeDepths[baseType];
if (previousDepth && previousDepth !== typeDepth) {
throw new Error(
`All messages of type ${baseType} must have the same structure. ` +
`${
message.type
} has ${typeDepth} part(s), but earlier messages had ${previousDepth} part(s).`
);
}
messageTypeDepths[baseType] = typeDepth;
}
function validatePageSummary(message) {
const type = message.type;
if (!type.endsWith('.pageSummary')) return;
if (!message.url)
throw new Error(`Page summary message (${type}) didn't specify a url`);
if (!message.group)
throw new Error(`Page summary message (${type}) didn't specify a group.`);
}
function validateSummaryMessage(message) {
const type = message.type;
if (!type.endsWith('.summary')) return;
if (message.url)
throw new Error(
`Summary message (${type}) shouldn't be url specific, use .pageSummary instead.`
);
if (!message.group)
throw new Error(`Summary message (${type}) didn't specify a group.`);
const groups = groupsPerSummaryType[type] || [];
if (groups.includes(message.group)) {
throw new Error(
`Multiple summary messages of type ${type} and group ${message.group}`
);
}
groupsPerSummaryType[type] = groups.concat(message.group);
}
validateTypeStructure(message);
validatePageSummary(message);
validateSummaryMessage(message);
}
|
javascript
|
{
"resource": ""
}
|
q21320
|
write
|
train
|
function write(file, data) {
writeFileSync(file, data);
console.log(
`✓ ${relative(__dirname + "/../", file)} (${bytes(statSync(file).size)})`
);
}
|
javascript
|
{
"resource": ""
}
|
q21321
|
build
|
train
|
async function build(file) {
const { code, map, assets } = await ncc(file, options);
if (Object.keys(assets).length)
console.error("New unexpected assets are being emitted for", file);
const name = basename(file, ".js");
await mkdirp(resolve(DIST_DIR, name));
write(resolve(DIST_DIR, name, "index.js"), code);
write(resolve(DIST_DIR, name, "index.map.js"), map);
}
|
javascript
|
{
"resource": ""
}
|
q21322
|
runSample
|
train
|
async function runSample(projectId = 'your-project-id') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
}
|
javascript
|
{
"resource": ""
}
|
q21323
|
train
|
function() {
var self = this,
val = $.map(self.items(), function(item) {
return self.options.itemValue(item).toString();
});
self.$element.val(val, true);
if (self.options.triggerChange)
self.$element.trigger('change');
}
|
javascript
|
{
"resource": ""
}
|
|
q21324
|
makeOptionItemFunction
|
train
|
function makeOptionItemFunction(options, key) {
if (typeof options[key] !== 'function') {
var propertyName = options[key];
options[key] = function(item) { return item[propertyName]; };
}
}
|
javascript
|
{
"resource": ""
}
|
q21325
|
keyCombinationInList
|
train
|
function keyCombinationInList(keyPressEvent, lookupList) {
var found = false;
$.each(lookupList, function (index, keyCombination) {
if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
found = true;
return false;
}
if (keyPressEvent.which === keyCombination.which) {
var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey,
shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey,
ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey;
if (alt && shift && ctrl) {
found = true;
return false;
}
}
});
return found;
}
|
javascript
|
{
"resource": ""
}
|
q21326
|
createClassComponent
|
train
|
function createClassComponent(ctor, displayName, opts) {
var cdu = createComponentDidUpdate(displayName, opts);
// the wrapper class extends the original class,
// and overwrites its `componentDidUpdate` method,
// to allow why-did-you-update to listen for updates.
// If the component had its own `componentDidUpdate`,
// we call it afterwards.`
var WDYUClassComponent = function (_ctor) {
_inherits(WDYUClassComponent, _ctor);
function WDYUClassComponent() {
_classCallCheck(this, WDYUClassComponent);
return _possibleConstructorReturn(this, _ctor.apply(this, arguments));
}
WDYUClassComponent.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState, snapshot) {
cdu.call(this, prevProps, prevState);
if (typeof ctor.prototype.componentDidUpdate === 'function') {
ctor.prototype.componentDidUpdate.call(this, prevProps, prevState, snapshot);
}
};
return WDYUClassComponent;
}(ctor);
// our wrapper component needs an explicit display name
// based on the original constructor.
WDYUClassComponent.displayName = displayName;
return WDYUClassComponent;
}
|
javascript
|
{
"resource": ""
}
|
q21327
|
createFunctionalComponent
|
train
|
function createFunctionalComponent(ctor, displayName, opts, ReactComponent) {
var cdu = createComponentDidUpdate(displayName, opts);
// We call the original function in the render() method,
// and implement `componentDidUpdate` for `why-did-you-update`
var WDYUFunctionalComponent = function (_ReactComponent) {
_inherits(WDYUFunctionalComponent, _ReactComponent);
function WDYUFunctionalComponent() {
_classCallCheck(this, WDYUFunctionalComponent);
return _possibleConstructorReturn(this, _ReactComponent.apply(this, arguments));
}
WDYUFunctionalComponent.prototype.render = function render() {
return ctor(this.props, this.context);
};
WDYUFunctionalComponent.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState, snapshot) {
cdu.call(this, prevProps, prevState, snapshot);
};
return WDYUFunctionalComponent;
}(ReactComponent);
// copy all statics from the functional component to the class
// to support proptypes and context apis
Object.assign(WDYUFunctionalComponent, ctor, {
// our wrapper component needs an explicit display name
// based on the original constructor.
displayName: displayName
});
return WDYUFunctionalComponent;
}
|
javascript
|
{
"resource": ""
}
|
q21328
|
bindFunc
|
train
|
function bindFunc(obj, method, observer) {
const oldFn = obj[method]
obj[method] = function(target) {
if (observer) {
observer.call(this, target, {
[method]: true,
})
}
if (oldFn) {
oldFn.call(this, target)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q21329
|
search
|
train
|
function search (query) {
if (!allowSearch) {
console.error('Assets for search still loading');
return;
}
var resultDocuments = [];
var results = index.search(query + '~2'); // fuzzy
for (var i=0; i < results.length; i++){
var result = results[i];
doc = documents[result.ref];
doc.summary = doc.text.substring(0, 200);
resultDocuments.push(doc);
}
return resultDocuments;
}
|
javascript
|
{
"resource": ""
}
|
q21330
|
isEqual
|
train
|
function isEqual (array1, array2) {
return array1.length === array2.length && array1.every(function (element, index) {
return element === array2[index];
});
}
|
javascript
|
{
"resource": ""
}
|
q21331
|
readCertificateDataFromFile
|
train
|
function readCertificateDataFromFile ({ keyFile, certFile, caFile }) {
let key, cert, ca;
if (keyFile) {
key = fs.readFileSync(keyFile);
}
if (certFile) {
cert = fs.readFileSync(certFile);
}
if (caFile) {
ca = fs.readFileSync(caFile);
}
return { key, cert, ca };
}
|
javascript
|
{
"resource": ""
}
|
q21332
|
walk
|
train
|
function walk(arr, key, fn) {
var l = arr.length,
children;
while (l--) {
children = arr[l][key];
if (children) {
walk(children, key, fn);
}
fn(arr[l]);
}
}
|
javascript
|
{
"resource": ""
}
|
q21333
|
run_table_cases
|
train
|
async function* run_table_cases(worker, data, test) {
console.log(`Benchmarking \`${test}\``);
try {
for (let x = 0; x < ITERATIONS + TOSS_ITERATIONS; x++) {
const start = performance.now();
const table = worker.table(data.slice ? data.slice() : data);
await table.size();
if (x >= TOSS_ITERATIONS) {
yield {
test,
time: performance.now() - start,
method: test,
row_pivots: "n/a",
column_pivots: "n/a",
aggregate: "n/a"
};
}
await table.delete();
}
} catch (e) {
console.error(`Benchmark ${test} failed`, e);
}
}
|
javascript
|
{
"resource": ""
}
|
q21334
|
convert
|
train
|
async function convert(filename, options) {
let file;
if (filename) {
file = fs.readFileSync(filename).toString();
} else {
file = await read_stdin();
}
try {
file = JSON.parse(file);
} catch {}
let tbl = table(file);
let view = tbl.view();
let out;
options.format = options.format || "arrow";
if (options.format === "csv") {
out = await view.to_csv();
} else if (options.format === "columns") {
out = JSON.stringify(await view.to_columns());
} else if (options.format === "json") {
out = JSON.stringify(await view.to_json());
} else {
out = await view.to_arrow();
}
if (options.format === "arrow") {
if (options.output) {
fs.writeFileSync(options.output, new Buffer(out), "binary");
} else {
console.log(new Buffer(out).toString());
}
} else {
if (options.output) {
fs.writeFileSync(options.output, out);
} else {
console.log(out);
}
}
view.delete();
tbl.delete();
}
|
javascript
|
{
"resource": ""
}
|
q21335
|
host
|
train
|
async function host(filename, options) {
let files = [path.join(__dirname, "html")];
if (options.assets) {
files = [options.assets, ...files];
}
const server = new WebSocketHost({assets: files, port: options.port});
let file;
if (filename) {
file = fs.readFileSync(filename).toString();
} else {
file = await read_stdin();
}
server.host_table("data_source_one", table(file));
if (options.open) {
open_browser(options.port);
}
}
|
javascript
|
{
"resource": ""
}
|
q21336
|
train
|
async function(row, col, event) {
if (this.isTreeCol(col)) {
let isShift = false;
if (event.primitiveEvent.detail.primitiveEvent) {
isShift = !!event.primitiveEvent.detail.primitiveEvent.shiftKey; // typecast to boolean
}
let is_expanded = await this._view.get_row_expanded(row);
if (isShift) {
if (is_expanded) {
if (this.data[row][col].rowPath.length === 1) {
this._view.collapse(row);
} else {
this._view.set_depth(this.data[row][col].rowPath.length - 2);
}
} else {
this._view.set_depth(this.data[row][col].rowPath.length - 1);
}
} else {
if (is_expanded) {
this._view.collapse(row);
} else {
this._view.expand(row);
}
}
let nrows = await this._view.num_rows();
this.setDirty(nrows);
this.grid.canvas.paintNow();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21337
|
copyValues
|
train
|
function copyValues(origin, clone, elementSelector) {
var $originalElements = origin.find(elementSelector);
clone.find(elementSelector).each(function(index, item) {
$(item).val($originalElements.eq(index).val());
});
}
|
javascript
|
{
"resource": ""
}
|
q21338
|
setDocType
|
train
|
function setDocType($iframe, doctype){
var win, doc;
win = $iframe.get(0);
win = win.contentWindow || win.contentDocument || win;
doc = win.document || win.contentDocument || win;
doc.open();
doc.write(doctype);
doc.close();
}
|
javascript
|
{
"resource": ""
}
|
q21339
|
attachOnBeforePrintEvent
|
train
|
function attachOnBeforePrintEvent($iframe, beforePrintHandler) {
var win = $iframe.get(0);
win = win.contentWindow || win.contentDocument || win;
if (typeof beforePrintHandler === "function") {
if ('matchMedia' in win) {
win.matchMedia('print').addListener(function(mql) {
if(mql.matches) beforePrintHandler();
});
} else {
win.onbeforeprint = beforePrintHandler;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q21340
|
isSatisfiable
|
train
|
function isSatisfiable (comparators, options) {
var result = true
var remainingComparators = comparators.slice()
var testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every(function (otherComparator) {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q21341
|
resizeImageBase64
|
train
|
function resizeImageBase64 (successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = 'data:' + file.contentType + ';base64,' + strBase64;
var image = new Image(); /* eslint no-undef : 0 */
image.src = imageData;
image.onload = function () {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(file.contentType);
// Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
var arr = finalFile.split(',');
var newStr = finalFile.substr(arr[0].length + 1);
successCallback(newStr);
};
}, function (err) { errorCallback(err); });
}
|
javascript
|
{
"resource": ""
}
|
q21342
|
orientationToRotation
|
train
|
function orientationToRotation (orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx
switch (orientation) {
// portrait
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.none;
// portrait-flipped (not supported by WinPhone Apps)
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape-flipped
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
// faceup & facedown
default:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
}
}
|
javascript
|
{
"resource": ""
}
|
q21343
|
train
|
function (picture) {
if (options.destinationType === Camera.DestinationType.FILE_URI || options.destinationType === Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
} else {
// CB-11714: check if target content-type is PNG to just rename as *.jpg since camera is captured as JPEG
if (options.encodingType === Camera.EncodingType.PNG) {
picture.name = picture.name.replace(/\.png$/, '.jpg');
}
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
successCallback('ms-appdata:///local/' + copiedFile.name);
}, errorCallback);
}
} else {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
} else {
fileIO.readBufferAsync(picture).done(function (buffer) {
var strBase64 = encodeToBase64String(buffer);
picture.deleteAsync().done(function () {
successCallback(strBase64);
}, function (err) {
errorCallback(err);
});
}, errorCallback);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21344
|
getProps
|
train
|
function getProps(componentProps, properties, indexes, suppressQuotes) {
// Make indexes ordered by ascending.
indexes.sort(function(a, b) {
return a - b;
});
const propertiesKeys = Object.keys(properties);
return indexes.map(i => {
const name = propertiesKeys[i];
const value = getPropValue(properties[name]);
return PropRep({
...componentProps,
mode: MODE.TINY,
name,
object: value,
equal: ": ",
defaultRep: Grip,
title: null,
suppressQuotes
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21345
|
getPropIndexes
|
train
|
function getPropIndexes(properties, max, filter) {
const indexes = [];
try {
let i = 0;
for (const name in properties) {
if (indexes.length >= max) {
return indexes;
}
// Type is specified in grip's "class" field and for primitive
// values use typeof.
const value = getPropValue(properties[name]);
let type = value.class || typeof value;
type = type.toLowerCase();
if (filter(type, value, name)) {
indexes.push(i);
}
i++;
}
} catch (err) {
console.error(err);
}
return indexes;
}
|
javascript
|
{
"resource": ""
}
|
q21346
|
getPropValue
|
train
|
function getPropValue(property) {
let value = property;
if (typeof property === "object") {
const keys = Object.keys(property);
if (keys.includes("value")) {
value = property.value;
} else if (keys.includes("getterValue")) {
value = property.getterValue;
}
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q21347
|
oncePerAnimationFrame
|
train
|
function oncePerAnimationFrame(fn) {
let animationId = null;
let argsToPass = null;
return function(...args) {
argsToPass = args;
if (animationId !== null) {
return;
}
animationId = requestAnimationFrame(() => {
fn.call(this, ...argsToPass);
animationId = null;
argsToPass = null;
});
};
}
|
javascript
|
{
"resource": ""
}
|
q21348
|
escapeString
|
train
|
function escapeString(str, escapeWhitespace) {
return `"${str.replace(escapeRegexp, (match, offset) => {
const c = match.charCodeAt(0);
if (c in escapeMap) {
if (!escapeWhitespace && (c === 9 || c === 0xa || c === 0xd)) {
return match[0];
}
return escapeMap[c];
}
if (c >= 0xd800 && c <= 0xdfff) {
// Find the full code point containing the surrogate, with a
// special case for a trailing surrogate at the start of the
// string.
if (c >= 0xdc00 && offset > 0) {
--offset;
}
const codePoint = str.codePointAt(offset);
if (codePoint >= 0xd800 && codePoint <= 0xdfff) {
// Unpaired surrogate.
return `\\u${codePoint.toString(16)}`;
} else if (codePoint >= 0xf0000 && codePoint <= 0x10fffd) {
// Private use area. Because we visit each pair of a such a
// character, return the empty string for one half and the
// real result for the other, to avoid duplication.
if (c <= 0xdbff) {
return `\\u{${codePoint.toString(16)}}`;
}
return "";
}
// Other surrogate characters are passed through.
return match;
}
return `\\u${`0000${c.toString(16)}`.substr(-4)}`;
})}"`;
}
|
javascript
|
{
"resource": ""
}
|
q21349
|
getGripPreviewItems
|
train
|
function getGripPreviewItems(grip) {
if (!grip) {
return [];
}
// Promise resolved value Grip
if (grip.promiseState && grip.promiseState.value) {
return [grip.promiseState.value];
}
// Array Grip
if (grip.preview && grip.preview.items) {
return grip.preview.items;
}
// Node Grip
if (grip.preview && grip.preview.childNodes) {
return grip.preview.childNodes;
}
// Set or Map Grip
if (grip.preview && grip.preview.entries) {
return grip.preview.entries.reduce((res, entry) => res.concat(entry), []);
}
// Event Grip
if (grip.preview && grip.preview.target) {
const keys = Object.keys(grip.preview.properties);
const values = Object.values(grip.preview.properties);
return [grip.preview.target, ...keys, ...values];
}
// RegEx Grip
if (grip.displayString) {
return [grip.displayString];
}
// Generic Grip
if (grip.preview && grip.preview.ownProperties) {
let propertiesValues = Object.values(grip.preview.ownProperties).map(
property => property.value || property
);
const propertyKeys = Object.keys(grip.preview.ownProperties);
propertiesValues = propertiesValues.concat(propertyKeys);
// ArrayBuffer Grip
if (grip.preview.safeGetterValues) {
propertiesValues = propertiesValues.concat(
Object.values(grip.preview.safeGetterValues).map(
property => property.getterValue || property
)
);
}
return propertiesValues;
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q21350
|
getGripType
|
train
|
function getGripType(object, noGrip) {
if (noGrip || Object(object) !== object) {
return typeof object;
}
if (object.type === "object") {
return object.class;
}
return object.type;
}
|
javascript
|
{
"resource": ""
}
|
q21351
|
isURL
|
train
|
function isURL(token) {
try {
if (!validProtocols.test(token)) {
return false;
}
new URL(token);
return true;
} catch (e) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q21352
|
interleave
|
train
|
function interleave(items, char) {
return items.reduce((res, item, index) => {
if (index !== items.length - 1) {
return res.concat(item, char);
}
return res.concat(item);
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q21353
|
getBabelFrameIndexes
|
train
|
function getBabelFrameIndexes(frames) {
const startIndexes = frames.reduce((accumulator, frame, index) => {
if (
getFrameUrl(frame).match(/regenerator-runtime/i) &&
frame.displayName === "tryCatch"
) {
return [...accumulator, index];
}
return accumulator;
}, []);
const endIndexes = frames.reduce((accumulator, frame, index) => {
if (
getFrameUrl(frame).match(/_microtask/i) &&
frame.displayName === "flush"
) {
return [...accumulator, index];
}
if (frame.displayName === "_asyncToGenerator/<") {
return [...accumulator, index + 1];
}
return accumulator;
}, []);
if (startIndexes.length != endIndexes.length || startIndexes.length === 0) {
return frames;
}
// Receives an array of start and end index tuples and returns
// an array of async call stack index ranges.
// e.g. [[1,3], [5,7]] => [[1,2,3], [5,6,7]]
// $FlowIgnore
return flatMap(zip(startIndexes, endIndexes), ([startIndex, endIndex]) =>
range(startIndex, endIndex + 1)
);
}
|
javascript
|
{
"resource": ""
}
|
q21354
|
parseStackString
|
train
|
function parseStackString(stack) {
const res = [];
if (!stack) {
return res;
}
const isStacktraceALongString = isLongString(stack);
const stackString = isStacktraceALongString ? stack.initial : stack;
stackString.split("\n").forEach((frame, index, frames) => {
if (!frame) {
// Skip any blank lines
return;
}
// If the stacktrace is a longString, don't include the last frame in the
// array, since it is certainly incomplete.
// Can be removed when https://bugzilla.mozilla.org/show_bug.cgi?id=1448833
// is fixed.
if (isStacktraceALongString && index === frames.length - 1) {
return;
}
let functionName;
let location;
// Given the input: "functionName@scriptLocation:2:100"
// Result: [
// "functionName@scriptLocation:2:100",
// "functionName",
// "scriptLocation:2:100"
// ]
const result = frame.match(/^(.*)@(.*)$/);
if (result && result.length === 3) {
functionName = result[1];
// If the resource was loaded by base-loader.js, the location looks like:
// resource://devtools/shared/base-loader.js -> resource://path/to/file.js .
// What's needed is only the last part after " -> ".
location = result[2].split(" -> ").pop();
}
if (!functionName) {
functionName = "<anonymous>";
}
// Given the input: "scriptLocation:2:100"
// Result:
// ["scriptLocation:2:100", "scriptLocation", "2", "100"]
const locationParts = location.match(/^(.*):(\d+):(\d+)$/);
if (location && locationParts) {
const [, filename, line, column] = locationParts;
res.push({
filename,
functionName,
location,
columnNumber: Number(column),
lineNumber: Number(line)
});
}
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
q21355
|
hasOwnProperty
|
train
|
function hasOwnProperty(value, key) {
if (value.hasOwnProperty && isFunction(value.hasOwnProperty)) {
return value.hasOwnProperty(key);
}
if (value.prototype && value.prototype.hasOwnProperty) {
return value.prototype.hasOwnProperty(key);
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q21356
|
addGroupToList
|
train
|
function addGroupToList(group, list) {
if (!group) {
return list;
}
if (group.length > 1) {
list.push(group);
} else {
list = list.concat(group);
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q21357
|
getEntries
|
train
|
function getEntries(props, entries, indexes) {
const { onDOMNodeMouseOver, onDOMNodeMouseOut, onInspectIconClick } = props;
// Make indexes ordered by ascending.
indexes.sort(function(a, b) {
return a - b;
});
return indexes.map((index, i) => {
const [key, entryValue] = entries[index];
const value =
entryValue.value !== undefined ? entryValue.value : entryValue;
return PropRep({
name: key,
equal: " \u2192 ",
object: value,
mode: MODE.TINY,
onDOMNodeMouseOver,
onDOMNodeMouseOut,
onInspectIconClick
});
});
}
|
javascript
|
{
"resource": ""
}
|
q21358
|
getEntriesIndexes
|
train
|
function getEntriesIndexes(entries, max, filter) {
return entries.reduce((indexes, [key, entry], i) => {
if (indexes.length < max) {
const value = entry && entry.value !== undefined ? entry.value : entry;
// Type is specified in grip's "class" field and for primitive
// values use typeof.
const type = (value && value.class
? value.class
: typeof value
).toLowerCase();
if (filter(type, value, key)) {
indexes.push(i);
}
}
return indexes;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q21359
|
createMozBuildFiles
|
train
|
function createMozBuildFiles() {
const builds = {};
getFiles()
.filter(file => file.match(/.js$/))
.filter(file => {
if (file.match(/\/workers\.js/)) {
return true;
}
// We exclude worker files because they are bundled and we include
// worker/index.js files because are required by the debugger app in order
// to communicate with the worker.
if (file.match(/\/workers/)) {
return file.match(/workers\/(\w|-)*\/index.js/);
}
return !file.match(/(test|types|packages)/)
})
.forEach(file => {
// console.log(file)
let dir = path.dirname(file);
builds[dir] = builds[dir] || { files: [], dirs: [] };
// Add the current file to its parent dir moz.build
builds[dir].files.push(path.basename(file));
// There should be a moz.build in every folder between the root and this
// file. Climb up the folder hierarchy and make sure a each folder of the
// chain is listing in its parent dir moz.build.
while (path.dirname(dir) != ".") {
const parentDir = path.dirname(dir);
const dirName = path.basename(dir);
builds[parentDir] = builds[parentDir] || { files: [], dirs: [] };
if (!builds[parentDir].dirs.includes(dirName)) {
builds[parentDir].dirs.push(dirName);
}
dir = parentDir;
}
});
Object.keys(builds).forEach(build => {
const { files, dirs } = builds[build];
const buildPath = path.join(mcDebuggerPath, build);
shell.mkdir("-p", buildPath);
// Files and folders should be alphabetically sorted in moz.build
const fileStr = files
.sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
.map(file => ` '${file}',`)
.join("\n");
const dirStr = dirs
.sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
.map(dir => ` '${dir}',`)
.join("\n");
const src = MOZ_BUILD_TEMPLATE.replace("__DIRS__", dirStr).replace(
"__FILES__",
fileStr
);
fs.writeFileSync(path.join(buildPath, "moz.build"), src);
});
}
|
javascript
|
{
"resource": ""
}
|
q21360
|
getLinkifiedElements
|
train
|
function getLinkifiedElements(text, cropLimit, openLink, isInContentPage) {
const halfLimit = Math.ceil((cropLimit - ELLIPSIS.length) / 2);
const startCropIndex = cropLimit ? halfLimit : null;
const endCropIndex = cropLimit ? text.length - halfLimit : null;
const items = [];
let currentIndex = 0;
let contentStart;
while (true) {
const url = urlRegex.exec(text);
// Pick the regexp with the earlier content; index will always be zero.
if (!url) {
break;
}
contentStart = url.index + url[1].length;
if (contentStart > 0) {
const nonUrlText = text.substring(0, contentStart);
items.push(
getCroppedString(nonUrlText, currentIndex, startCropIndex, endCropIndex)
);
}
// There are some final characters for a URL that are much more likely
// to have been part of the enclosing text rather than the end of the
// URL.
let useUrl = url[2];
const uneat = uneatLastUrlCharsRegex.exec(useUrl);
if (uneat) {
useUrl = useUrl.substring(0, uneat.index);
}
currentIndex = currentIndex + contentStart;
const linkText = getCroppedString(
useUrl,
currentIndex,
startCropIndex,
endCropIndex
);
if (linkText) {
items.push(
a(
{
className: "url",
title: useUrl,
draggable: false,
// Because we don't want the link to be open in the current
// panel's frame, we only render the href attribute if `openLink`
// exists (so we can preventDefault) or if the reps will be
// displayed in content page (e.g. in the JSONViewer).
href: openLink || isInContentPage ? useUrl : null,
onClick: openLink
? e => {
e.preventDefault();
openLink(useUrl, e);
}
: null
},
linkText
)
);
}
currentIndex = currentIndex + useUrl.length;
text = text.substring(url.index + url[1].length + useUrl.length);
}
// Clean up any non-URL text at the end of the source string,
// i.e. not handled in the loop.
if (text.length > 0) {
if (currentIndex < endCropIndex) {
text = getCroppedString(text, currentIndex, startCropIndex, endCropIndex);
}
items.push(text);
}
return items;
}
|
javascript
|
{
"resource": ""
}
|
q21361
|
getCroppedString
|
train
|
function getCroppedString(text, offset = 0, startCropIndex, endCropIndex) {
if (!startCropIndex) {
return text;
}
const start = offset;
const end = offset + text.length;
const shouldBeVisible = !(start >= startCropIndex && end <= endCropIndex);
if (!shouldBeVisible) {
return null;
}
const shouldCropEnd = start < startCropIndex && end > startCropIndex;
const shouldCropStart = start < endCropIndex && end > endCropIndex;
if (shouldCropEnd) {
const cutIndex = startCropIndex - start;
return (
text.substring(0, cutIndex) +
ELLIPSIS +
(shouldCropStart ? text.substring(endCropIndex - start) : "")
);
}
if (shouldCropStart) {
// The string should be cropped at the beginning.
const cutIndex = endCropIndex - start;
return text.substring(cutIndex);
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
q21362
|
globalizeDeclaration
|
train
|
function globalizeDeclaration(node, bindings) {
return node.declarations.map(declaration =>
t.expressionStatement(
t.assignmentExpression(
"=",
getAssignmentTarget(declaration.id, bindings),
declaration.init || t.unaryExpression("void", t.numericLiteral(0))
)
)
);
}
|
javascript
|
{
"resource": ""
}
|
q21363
|
globalizeAssignment
|
train
|
function globalizeAssignment(node, bindings) {
return t.assignmentExpression(
node.operator,
getAssignmentTarget(node.left, bindings),
node.right
);
}
|
javascript
|
{
"resource": ""
}
|
q21364
|
findExistingBreakpoint
|
train
|
function findExistingBreakpoint(state, generatedLocation) {
const breakpoints = getBreakpointsList(state);
return breakpoints.find(bp => {
return (
bp.generatedLocation.sourceUrl == generatedLocation.sourceUrl &&
bp.generatedLocation.line == generatedLocation.line &&
bp.generatedLocation.column == generatedLocation.column
);
});
}
|
javascript
|
{
"resource": ""
}
|
q21365
|
getFunctionName
|
train
|
function getFunctionName(grip, props = {}) {
let { functionName } = props;
let name;
if (functionName) {
const end = functionName.length - 1;
functionName =
functionName.startsWith('"') && functionName.endsWith('"')
? functionName.substring(1, end)
: functionName;
}
if (
grip.displayName != undefined &&
functionName != undefined &&
grip.displayName != functionName
) {
name = `${functionName}:${grip.displayName}`;
} else {
name = cleanFunctionName(
grip.userDisplayName ||
grip.displayName ||
grip.name ||
props.functionName ||
""
);
}
return cropString(name, 100);
}
|
javascript
|
{
"resource": ""
}
|
q21366
|
getLocation
|
train
|
function getLocation(func) {
const location = { ...func.location };
// if the function has an identifier, start the block after it so the
// identifier is included in the "scope" of its parent
const identifierEnd = get(func, "identifier.loc.end");
if (identifierEnd) {
location.start = identifierEnd;
}
return location;
}
|
javascript
|
{
"resource": ""
}
|
q21367
|
train
|
function(props) {
const { object, defaultRep } = props;
const rep = getRep(object, defaultRep, props.noGrip);
return rep(props);
}
|
javascript
|
{
"resource": ""
}
|
|
q21368
|
getRep
|
train
|
function getRep(object, defaultRep = Grip, noGrip = false) {
for (let i = 0; i < reps.length; i++) {
const rep = reps[i];
try {
// supportsObject could return weight (not only true/false
// but a number), which would allow to priorities templates and
// support better extensibility.
if (rep.supportsObject(object, noGrip)) {
return rep.rep;
}
} catch (err) {
console.error(err);
}
}
return defaultRep.rep;
}
|
javascript
|
{
"resource": ""
}
|
q21369
|
lastRelease
|
train
|
function lastRelease() {
const {stdout: branches} = exec(`git branch -a | grep 'origin/release'`)
const releases = branches.
split("\n")
.map(b => b.replace(/remotes\/origin\//, '').trim())
.filter(b => b.match(/^release-(\d+)$/))
const ordered = sortBy(releases, r => parseInt(/\d+/.exec(r)[0], 10) )
return ordered[ordered.length -1];
}
|
javascript
|
{
"resource": ""
}
|
q21370
|
updateManifest
|
train
|
function updateManifest() {
const {stdout: branch} = exec(`git rev-parse --abbrev-ref HEAD`)
if (!branch.includes("release")) {
return;
}
console.log("[copy-assets] update assets manifest");
const last = lastRelease();
exec(`git cat-file -p ${last}:assets/module-manifest.json > assets/module-manifest.json`);
}
|
javascript
|
{
"resource": ""
}
|
q21371
|
getRecordUpdateData
|
train
|
function getRecordUpdateData (msg) {
let data
try {
data = JSON.parse(msg.data[2])
} catch (error) {
return error
}
return data
}
|
javascript
|
{
"resource": ""
}
|
q21372
|
setGlobalConfigDirectory
|
train
|
function setGlobalConfigDirectory (argv, filePath) {
const customConfigPath =
argv.c ||
argv.config ||
filePath ||
process.env.DEEPSTREAM_CONFIG_DIRECTORY
const configPath = customConfigPath
? verifyCustomConfigPath(customConfigPath)
: getDefaultConfigPath()
global.deepstreamConfDir = path.dirname(configPath)
return configPath
}
|
javascript
|
{
"resource": ""
}
|
q21373
|
setGlobalLibDirectory
|
train
|
function setGlobalLibDirectory (argv, config) {
const libDir =
argv.l ||
argv.libDir ||
(config.libDir && fileUtils.lookupConfRequirePath(config.libDir)) ||
process.env.DEEPSTREAM_LIBRARY_DIRECTORY
global.deepstreamLibDir = libDir
}
|
javascript
|
{
"resource": ""
}
|
q21374
|
extendConfig
|
train
|
function extendConfig (config, argv) {
const cliArgs = {}
let key
for (key in defaultOptions.get()) {
cliArgs[key] = argv[key]
}
if (argv.port) {
overrideEndpointOption('port', argv.port, 'websocket', config)
}
if (argv.host) {
overrideEndpointOption('host', argv.host, 'websocket', config)
}
if (argv.httpPort) {
overrideEndpointOption('port', argv.httpPort, 'http', config)
}
if (argv.httpHost) {
overrideEndpointOption('host', argv.httpHost, 'http', config)
}
return utils.merge({ plugins: {} }, defaultOptions.get(), config, cliArgs)
}
|
javascript
|
{
"resource": ""
}
|
q21375
|
getDefaultConfigPath
|
train
|
function getDefaultConfigPath () {
let filePath
let i
let k
for (k = 0; k < DEFAULT_CONFIG_DIRS.length; k++) {
for (i = 0; i < SUPPORTED_EXTENSIONS.length; i++) {
filePath = DEFAULT_CONFIG_DIRS[k] + SUPPORTED_EXTENSIONS[i]
if (fileUtils.fileExistsSync(filePath)) {
return filePath
}
}
}
throw new Error('No config file found')
}
|
javascript
|
{
"resource": ""
}
|
q21376
|
replaceEnvironmentVariables
|
train
|
function replaceEnvironmentVariables (fileContent) {
const environmentVariable = new RegExp(/\${([^}]+)}/g)
// eslint-disable-next-line
fileContent = fileContent.replace(environmentVariable, (a, b) => process.env[b] || '')
return fileContent
}
|
javascript
|
{
"resource": ""
}
|
q21377
|
parseLogLevel
|
train
|
function parseLogLevel (logLevel) {
if (!/debug|info|warn|error|off/i.test(logLevel)) {
console.error('Log level must be one of the following (debug|info|warn|error|off)')
process.exit(1)
}
return logLevel.toUpperCase()
}
|
javascript
|
{
"resource": ""
}
|
q21378
|
parseInteger
|
train
|
function parseInteger (name, port) {
const portNumber = Number(port)
if (!portNumber) {
console.error(`Provided ${name} must be an integer`)
process.exit(1)
}
return portNumber
}
|
javascript
|
{
"resource": ""
}
|
q21379
|
parseBoolean
|
train
|
function parseBoolean (name, enabled) {
let isEnabled
if (typeof enabled === 'undefined' || enabled === 'true') {
isEnabled = true
} else if (typeof enabled !== 'undefined' && enabled === 'false') {
isEnabled = false
} else {
console.error(`Invalid argument for ${name}, please provide true or false`)
process.exit(1)
}
return isEnabled
}
|
javascript
|
{
"resource": ""
}
|
q21380
|
handleForceWriteAcknowledgement
|
train
|
function handleForceWriteAcknowledgement (
socketWrapper, message, cacheResponse, storageResponse, error
) {
if (storageResponse && cacheResponse) {
socketWrapper.sendMessage(RECORD, C.ACTIONS.WRITE_ACKNOWLEDGEMENT, [
message.data[0],
[message.data[1]],
messageBuilder.typed(error)
], true)
}
}
|
javascript
|
{
"resource": ""
}
|
q21381
|
sendRecord
|
train
|
function sendRecord (recordName, record, socketWrapper) {
socketWrapper.sendMessage(RECORD, C.ACTIONS.READ, [recordName, record._v, record._d])
}
|
javascript
|
{
"resource": ""
}
|
q21382
|
validateSubscriptionMessage
|
train
|
function validateSubscriptionMessage (socket, message) {
if (message.data && message.data.length === 1 && typeof message.data[0] === 'string') {
return true
}
socket.sendError(C.TOPIC.EVENT, C.EVENT.INVALID_MESSAGE_DATA, message.raw)
return false
}
|
javascript
|
{
"resource": ""
}
|
q21383
|
compileRuleset
|
train
|
function compileRuleset (path, rules) {
const ruleset = pathParser.parse(path)
ruleset.rules = {}
for (const ruleType in rules) {
ruleset.rules[ruleType] = ruleParser.parse(
rules[ruleType], ruleset.variables
)
}
return ruleset
}
|
javascript
|
{
"resource": ""
}
|
q21384
|
sendError
|
train
|
function sendError (
event, message, recordName, socketWrapper, onError, options, context, metaData
) {
options.logger.error(event, message, metaData)
if (socketWrapper) {
socketWrapper.sendError(C.TOPIC.RECORD, event, message)
}
if (onError) {
onError.call(context, event, message, recordName, socketWrapper)
}
}
|
javascript
|
{
"resource": ""
}
|
q21385
|
onStorageResponse
|
train
|
function onStorageResponse (
error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData
) {
if (error) {
sendError(
C.EVENT.RECORD_LOAD_ERROR,
`error while loading ${recordName} from storage:${error.toString()}`,
recordName,
socketWrapper,
onError,
options,
context,
metaData
)
} else {
onComplete.call(context, record || null, recordName, socketWrapper)
if (record) {
options.cache.set(recordName, record, () => {}, metaData)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q21386
|
onCacheResponse
|
train
|
function onCacheResponse (
error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData
) {
if (error) {
sendError(
C.EVENT.RECORD_LOAD_ERROR,
`error while loading ${recordName} from cache:${error.toString()}`,
recordName,
socketWrapper,
onError,
options,
context,
metaData
)
} else if (record) {
onComplete.call(context, record, recordName, socketWrapper)
} else if (
!options.storageExclusion ||
!options.storageExclusion.test(recordName)
) {
let storageTimedOut = false
const storageTimeout = setTimeout(() => {
storageTimedOut = true
sendError(
C.EVENT.STORAGE_RETRIEVAL_TIMEOUT,
recordName, recordName, socketWrapper,
onError, options, context, metaData
)
}, options.storageRetrievalTimeout)
options.storage.get(recordName, (storageError, recordData) => {
if (!storageTimedOut) {
clearTimeout(storageTimeout)
onStorageResponse(
storageError,
recordData,
recordName,
socketWrapper,
onComplete,
onError,
options,
context,
metaData
)
}
}, metaData)
} else {
onComplete.call(context, null, recordName, socketWrapper)
}
}
|
javascript
|
{
"resource": ""
}
|
q21387
|
setValue
|
train
|
function setValue (root, path, value) {
const tokens = tokenize(path)
let node = root
let i
for (i = 0; i < tokens.length - 1; i++) {
const token = tokens[i]
if (node[token] !== undefined && typeof node[token] === 'object') {
node = node[token]
} else if (typeof tokens[i + 1] === 'number') {
node = node[token] = []
} else {
node = node[token] = {}
}
}
node[tokens[i]] = value
}
|
javascript
|
{
"resource": ""
}
|
q21388
|
tokenize
|
train
|
function tokenize (path) {
const tokens = []
const parts = path.split('.')
for (let i = 0; i < parts.length; i++) {
const part = parts[i].trim()
if (part.length === 0) {
continue
}
const arrayIndexes = part.split(SPLIT_REG_EXP)
tokens.push(arrayIndexes[0])
for (let j = 1; j < arrayIndexes.length; j++) {
if (arrayIndexes[j].length === 0) {
continue
}
tokens.push(Number(arrayIndexes[j]))
}
}
return tokens
}
|
javascript
|
{
"resource": ""
}
|
q21389
|
handleSSLProperties
|
train
|
function handleSSLProperties (config) {
const sslFiles = ['sslKey', 'sslCert', 'sslDHParams']
let key
let resolvedFilePath
let filePath
for (let i = 0; i < sslFiles.length; i++) {
key = sslFiles[i]
filePath = config[key]
if (!filePath) {
continue
}
resolvedFilePath = fileUtils.lookupConfRequirePath(filePath)
try {
config[key] = fs.readFileSync(resolvedFilePath, 'utf8')
} catch (e) {
throw new Error(`The file path "${resolvedFilePath}" provided by "${key}" does not exist.`)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q21390
|
handleLogger
|
train
|
function handleLogger (config) {
const configOptions = (config.logger || {}).options
let Logger
if (config.logger == null || config.logger.name === 'default') {
Logger = DefaultLogger
} else {
Logger = resolvePluginClass(config.logger, 'logger')
}
if (configOptions instanceof Array) {
// Note: This will not work on options without filename, and
// is biased against for the winston logger
let options
for (let i = 0; i < configOptions.length; i++) {
options = configOptions[i].options
if (options && options.filename) {
options.filename = fileUtils.lookupConfRequirePath(options.filename)
}
}
}
config.logger = new Logger(configOptions)
if (!config.logger.info) {
config.logger.debug = config.logger.log.bind(config.logger, C.LOG_LEVEL.DEBUG)
config.logger.info = config.logger.log.bind(config.logger, C.LOG_LEVEL.INFO)
config.logger.warn = config.logger.log.bind(config.logger, C.LOG_LEVEL.WARN)
config.logger.error = config.logger.log.bind(config.logger, C.LOG_LEVEL.ERROR)
}
if (LOG_LEVEL_KEYS.indexOf(config.logLevel) !== -1) {
// NOTE: config.logLevel has highest priority, compare to the level defined
// in the nested logger object
config.logLevel = C.LOG_LEVEL[config.logLevel]
config.logger.setLogLevel(config.logLevel)
}
}
|
javascript
|
{
"resource": ""
}
|
q21391
|
resolvePluginClass
|
train
|
function resolvePluginClass (plugin, type) {
// alias require to trick nexe from bundling it
const req = require
let requirePath
let pluginConstructor
if (plugin.path != null) {
requirePath = fileUtils.lookupLibRequirePath(plugin.path)
pluginConstructor = req(requirePath)
} else if (plugin.name != null && type) {
requirePath = `deepstream.io-${type}-${plugin.name}`
requirePath = fileUtils.lookupLibRequirePath(requirePath)
pluginConstructor = req(requirePath)
} else if (plugin.name != null) {
requirePath = fileUtils.lookupLibRequirePath(plugin.name)
pluginConstructor = req(requirePath)
} else {
throw new Error(`Neither name nor path property found for ${type}`)
}
return pluginConstructor
}
|
javascript
|
{
"resource": ""
}
|
q21392
|
train
|
function (urlPath, outStream, callback) {
needle.get(`https://github.com${urlPath}`, {
follow_max: 5,
headers: { 'User-Agent': 'nodejs-client' }
}, (error, response) => {
if (error) {
return callback(error)
}
outStream.write(response.body)
outStream.end()
if (process.env.VERBOSE) {
process.stdout.clearLine()
process.stdout.cursorTo(0)
process.stdout.write('Download complete' + '\n')
}
return callback()
})
}
|
javascript
|
{
"resource": ""
}
|
|
q21393
|
train
|
function (directory) {
try {
const content = fs.readFileSync(path.join(directory, CONFIG_EXAMPLE_FILE), 'utf8')
if (process.env.VERBOSE) {
console.log('You need to configure the connector in your deepstream configuration file')
}
if (!process.env.QUIET) {
console.log(`Example configuration:\n${colors.grey(content)}`)
}
} catch (err) {
if (!process.env.QUIET) {
console.log('Example configuration not found')
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21394
|
resolvePrefixAndFile
|
train
|
function resolvePrefixAndFile (nonAbsoluteFilePath, prefix) {
// prefix is not absolute
if (path.parse(prefix).root === '') {
return path.resolve(process.cwd(), prefix, nonAbsoluteFilePath)
}
// prefix is absolute
return path.resolve(prefix, nonAbsoluteFilePath)
}
|
javascript
|
{
"resource": ""
}
|
q21395
|
getInvalidPackages
|
train
|
async function getInvalidPackages() {
const packages = (await new Project(__dirname).getPackages())
.filter(p => p.scripts.build) // Only packages that have a build target
.filter(p => isPf3
? p.location.indexOf('patternfly-3') !== -1 || commonPackages.indexOf(p.name) !== -1
: true) // Based off argv
.filter(p => isPf4
? p.location.indexOf('patternfly-4') !== -1 || commonPackages.indexOf(p.name) !== -1
: true) // Based off argv
for (let p of packages) {
const watchDir = getDir(p.name);
p.hash = (await hashElement(`${p.location}/${watchDir}`)).hash;
p.valid = cache && cache[p.name] === p.hash;
if (p.valid) {
console.info('Skipping', p.name, '(already built).');
}
}
return packages.filter(p => !p.valid);
}
|
javascript
|
{
"resource": ""
}
|
q21396
|
train
|
function() {
if(!mfp.isOpen) return;
_mfpTrigger(BEFORE_CLOSE_EVENT);
mfp.isOpen = false;
// for CSS3 animation
if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) {
mfp._addClassToMFP(REMOVING_CLASS);
setTimeout(function() {
mfp._close();
}, mfp.st.removalDelay);
} else {
mfp._close();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q21397
|
train
|
function() {
var item = mfp.items[mfp.index];
// Detach and perform modifications
mfp.contentContainer.detach();
if(mfp.content)
mfp.content.detach();
if(!item.parsed) {
item = mfp.parseEl( mfp.index );
}
var type = item.type;
_mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
// BeforeChange event works like so:
// _mfpOn('BeforeChange', function(e, prevType, newType) { });
mfp.currItem = item;
if(!mfp.currTemplate[type]) {
var markup = mfp.st[type] ? mfp.st[type].markup : false;
// allows to modify markup
_mfpTrigger('FirstMarkupParse', markup);
if(markup) {
mfp.currTemplate[type] = $(markup);
} else {
// if there is no markup found we just define that template is parsed
mfp.currTemplate[type] = true;
}
}
if(_prevContentType && _prevContentType !== item.type) {
mfp.container.removeClass('mfp-'+_prevContentType+'-holder');
}
var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
mfp.appendContent(newContent, type);
item.preloaded = true;
_mfpTrigger(CHANGE_EVENT, item);
_prevContentType = item.type;
// Append container back after its content changed
mfp.container.prepend(mfp.contentContainer);
_mfpTrigger('AfterChange');
}
|
javascript
|
{
"resource": ""
}
|
|
q21398
|
train
|
function(newContent, type) {
mfp.content = newContent;
if(newContent) {
if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
mfp.currTemplate[type] === true) {
// if there is no markup, we just append close button element inside
if(!mfp.content.find('.mfp-close').length) {
mfp.content.append(_getCloseBtn());
}
} else {
mfp.content = newContent;
}
} else {
mfp.content = '';
}
_mfpTrigger(BEFORE_APPEND_EVENT);
mfp.container.addClass('mfp-'+type+'-holder');
mfp.contentContainer.append(mfp.content);
}
|
javascript
|
{
"resource": ""
}
|
|
q21399
|
train
|
function(index) {
var item = mfp.items[index],
type;
if(item.tagName) {
item = { el: $(item) };
} else {
type = item.type;
item = { data: item, src: item.src };
}
if(item.el) {
var types = mfp.types;
// check for 'mfp-TYPE' class
for(var i = 0; i < types.length; i++) {
if( item.el.hasClass('mfp-'+types[i]) ) {
type = types[i];
break;
}
}
item.src = item.el.attr('data-mfp-src');
if(!item.src) {
item.src = item.el.attr('href');
}
}
item.type = type || mfp.st.type || 'inline';
item.index = index;
item.parsed = true;
mfp.items[index] = item;
_mfpTrigger('ElementParse', item);
return mfp.items[index];
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.