_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q15300
|
injectGhStars
|
train
|
async function injectGhStars () {
const opts = {}
if ('GITHUB_TOKEN' in process.env) {
opts.auth = process.env.GITHUB_TOKEN
}
const Octokit = require('@octokit/rest')
const octokit = new Octokit(opts)
let { headers, data } = await octokit.repos.get({
owner: 'transloadit',
repo: 'uppy'
})
console.log(`${headers['x-ratelimit-remaining']} requests remaining until we hit GitHub ratelimiter`)
let dstpath = path.join(webRoot, 'themes', 'uppy', 'layout', 'partials', 'generated_stargazers.ejs')
fs.writeFileSync(dstpath, data.stargazers_count, 'utf-8')
console.log(`${data.stargazers_count} stargazers written to '${dstpath}'`)
}
|
javascript
|
{
"resource": ""
}
|
q15301
|
createEventTracker
|
train
|
function createEventTracker (emitter) {
const events = []
return {
on (event, fn) {
events.push([ event, fn ])
return emitter.on(event, fn)
},
remove () {
events.forEach(([ event, fn ]) => {
emitter.off(event, fn)
})
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15302
|
findIndex
|
train
|
function findIndex (array, predicate) {
for (let i = 0; i < array.length; i++) {
if (predicate(array[i])) return i
}
return -1
}
|
javascript
|
{
"resource": ""
}
|
q15303
|
findUppyInstances
|
train
|
function findUppyInstances () {
const instances = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (/^uppyState:/.test(key)) {
instances.push(key.slice('uppyState:'.length))
}
}
return instances
}
|
javascript
|
{
"resource": ""
}
|
q15304
|
openModal
|
train
|
function openModal () {
robodog.pick({
restrictions: {
allowedFileTypes: ['.png']
},
waitForEncoding: true,
params: {
auth: { key: TRANSLOADIT_KEY },
template_id: TEMPLATE_ID
},
providers: [
'webcam'
]
// if providers need custom config
// webcam: {
// option: 'whatever'
// }
}).then(console.log, console.error)
}
|
javascript
|
{
"resource": ""
}
|
q15305
|
getUploadParameters
|
train
|
function getUploadParameters (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const key = config.getKey(req, req.query.filename)
if (typeof key !== 'string') {
return res.status(500).json({ error: 's3: filename returned from `getKey` must be a string' })
}
const fields = {
acl: config.acl,
key: key,
success_action_status: '201',
'content-type': req.query.type
}
client.createPresignedPost({
Bucket: config.bucket,
Expires: ms('5 minutes') / 1000,
Fields: fields,
Conditions: config.conditions
}, (err, data) => {
if (err) {
next(err)
return
}
res.json({
method: 'post',
url: data.url,
fields: data.fields
})
})
}
|
javascript
|
{
"resource": ""
}
|
q15306
|
createMultipartUpload
|
train
|
function createMultipartUpload (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const key = config.getKey(req, req.body.filename)
const { type } = req.body
if (typeof key !== 'string') {
return res.status(500).json({ error: 's3: filename returned from `getKey` must be a string' })
}
if (typeof type !== 'string') {
return res.status(400).json({ error: 's3: content type must be a string' })
}
client.createMultipartUpload({
Bucket: config.bucket,
Key: key,
ACL: config.acl,
ContentType: type,
Expires: ms('5 minutes') / 1000
}, (err, data) => {
if (err) {
next(err)
return
}
res.json({
key: data.Key,
uploadId: data.UploadId
})
})
}
|
javascript
|
{
"resource": ""
}
|
q15307
|
getUploadedParts
|
train
|
function getUploadedParts (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const { uploadId } = req.params
const { key } = req.query
if (typeof key !== 'string') {
return res.status(400).json({ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"' })
}
let parts = []
listPartsPage(0)
function listPartsPage (startAt) {
client.listParts({
Bucket: config.bucket,
Key: key,
UploadId: uploadId,
PartNumberMarker: startAt
}, (err, data) => {
if (err) {
next(err)
return
}
parts = parts.concat(data.Parts)
if (data.IsTruncated) {
// Get the next page.
listPartsPage(data.NextPartNumberMarker)
} else {
done()
}
})
}
function done () {
res.json(parts)
}
}
|
javascript
|
{
"resource": ""
}
|
q15308
|
signPartUpload
|
train
|
function signPartUpload (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const { uploadId, partNumber } = req.params
const { key } = req.query
if (typeof key !== 'string') {
return res.status(400).json({ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"' })
}
if (!parseInt(partNumber, 10)) {
return res.status(400).json({ error: 's3: the part number must be a number between 1 and 10000.' })
}
client.getSignedUrl('uploadPart', {
Bucket: config.bucket,
Key: key,
UploadId: uploadId,
PartNumber: partNumber,
Body: '',
Expires: ms('5 minutes') / 1000
}, (err, url) => {
if (err) {
next(err)
return
}
res.json({ url })
})
}
|
javascript
|
{
"resource": ""
}
|
q15309
|
abortMultipartUpload
|
train
|
function abortMultipartUpload (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const { uploadId } = req.params
const { key } = req.query
if (typeof key !== 'string') {
return res.status(400).json({ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"' })
}
client.abortMultipartUpload({
Bucket: config.bucket,
Key: key,
UploadId: uploadId
}, (err, data) => {
if (err) {
next(err)
return
}
res.json({})
})
}
|
javascript
|
{
"resource": ""
}
|
q15310
|
completeMultipartUpload
|
train
|
function completeMultipartUpload (req, res, next) {
// @ts-ignore The `uppy` property is added by middleware before reaching here.
const client = req.uppy.s3Client
const { uploadId } = req.params
const { key } = req.query
const { parts } = req.body
if (typeof key !== 'string') {
return res.status(400).json({ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"' })
}
if (!Array.isArray(parts) || !parts.every(isValidPart)) {
return res.status(400).json({ error: 's3: `parts` must be an array of {ETag, PartNumber} objects.' })
}
client.completeMultipartUpload({
Bucket: config.bucket,
Key: key,
UploadId: uploadId,
MultipartUpload: {
Parts: parts
}
}, (err, data) => {
if (err) {
next(err)
return
}
res.json({
location: data.Location
})
})
}
|
javascript
|
{
"resource": ""
}
|
q15311
|
assertLoadedUrlEqual
|
train
|
function assertLoadedUrlEqual(controller, targetUrl) {
var locationBar = new elementslib.ID(controller.window.document, "urlbar");
var currentURL = locationBar.getNode().value;
// Load the target URL
controller.open(targetUrl);
controller.waitForPageLoad();
// Check the same web page has been opened
controller.waitForEval("subject.targetURL.value == subject.currentURL", gTimeout, 100,
{targetURL: locationBar.getNode(), currentURL: currentURL});
}
|
javascript
|
{
"resource": ""
}
|
q15312
|
closeContentAreaContextMenu
|
train
|
function closeContentAreaContextMenu(controller) {
var contextMenu = new elementslib.ID(controller.window.document, "contentAreaContextMenu");
controller.keypress(contextMenu, "VK_ESCAPE", {});
}
|
javascript
|
{
"resource": ""
}
|
q15313
|
checkSearchField
|
train
|
function checkSearchField(controller, searchField,
searchTerm, submitButton,
timeout) {
controller.waitThenClick(searchField, timeout);
controller.type(searchField, searchTerm);
if (submitButton != undefined) {
controller.waitThenClick(submitButton, timeout);
}
}
|
javascript
|
{
"resource": ""
}
|
q15314
|
createURI
|
train
|
function createURI(spec, originCharset, baseURI)
{
let iosvc = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
return iosvc.newURI(spec, originCharset, baseURI);
}
|
javascript
|
{
"resource": ""
}
|
q15315
|
formatUrlPref
|
train
|
function formatUrlPref(prefName) {
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
.getService(Ci.nsIURLFormatter);
return formatter.formatURLPref(prefName);
}
|
javascript
|
{
"resource": ""
}
|
q15316
|
getDefaultHomepage
|
train
|
function getDefaultHomepage() {
var preferences = prefs.preferences;
var prefValue = preferences.getPref("browser.startup.homepage", "",
true, Ci.nsIPrefLocalizedString);
return prefValue.data;
}
|
javascript
|
{
"resource": ""
}
|
q15317
|
getEntity
|
train
|
function getEntity(urls, entityId) {
// Add xhtml11.dtd to prevent missing entity errors with XHTML files
urls.push("resource:///res/dtd/xhtml11.dtd");
// Build a string of external entities
var extEntities = "";
for (i = 0; i < urls.length; i++) {
extEntities += '<!ENTITY % dtd' + i + ' SYSTEM "' +
urls[i] + '">%dtd' + i + ';';
}
var parser = Cc["@mozilla.org/xmlextras/domparser;1"]
.createInstance(Ci.nsIDOMParser);
var header = '<?xml version="1.0"?><!DOCTYPE elem [' + extEntities + ']>';
var elem = '<elem id="elementID">&' + entityId + ';</elem>';
var doc = parser.parseFromString(header + elem, 'text/xml');
var elemNode = doc.querySelector('elem[id="elementID"]');
if (elemNode == null)
throw new Error(arguments.callee.name + ": Unknown entity - " + entityId);
return elemNode.textContent;
}
|
javascript
|
{
"resource": ""
}
|
q15318
|
getProperty
|
train
|
function getProperty(url, prefName) {
var sbs = Cc["@mozilla.org/intl/stringbundle;1"]
.getService(Ci.nsIStringBundleService);
var bundle = sbs.createBundle(url);
try {
return bundle.GetStringFromName(prefName);
} catch (ex) {
throw new Error(arguments.callee.name + ": Unknown property - " + prefName);
}
}
|
javascript
|
{
"resource": ""
}
|
q15319
|
handleWindow
|
train
|
function handleWindow(type, text, callback, dontClose) {
// Set the window opener function to use depending on the type
var func_ptr = null;
switch (type) {
case "type":
func_ptr = mozmill.utils.getWindowByType;
break;
case "title":
func_ptr = mozmill.utils.getWindowByTitle;
break;
default:
throw new Error(arguments.callee.name + ": Unknown opener type - " + type);
}
var window = null;
var controller = null;
try {
// Wait until the window has been opened
mozmill.utils.waitFor(function () {
window = func_ptr(text);
return window != null;
}, "Window has been found.");
// XXX: We still have to find a reliable way to wait until the new window
// content has been finished loading. Let's wait for now.
controller = new mozmill.controller.MozMillController(window);
controller.sleep(200);
if (callback) {
callback(controller);
}
// Check if we have to close the window
dontClose = dontClose || false;
if (dontClose == false & window != null) {
controller.window.close();
mozmill.utils.waitFor(function () {
return func_ptr(text) != window;
}, "Window has been closed.");
window = null;
controller = null;
}
return controller;
} catch (ex) {
if (window)
window.close();
throw ex;
}
}
|
javascript
|
{
"resource": ""
}
|
q15320
|
createExecutor
|
train
|
function createExecutor(serverUrl) {
let client = serverUrl.then(url => new http.HttpClient(url));
let executor = new http.Executor(client);
configureExecutor(executor);
return executor;
}
|
javascript
|
{
"resource": ""
}
|
q15321
|
configureExecutor
|
train
|
function configureExecutor(executor) {
executor.defineCommand(
ExtensionCommand.GET_CONTEXT,
'GET',
'/session/:sessionId/moz/context');
executor.defineCommand(
ExtensionCommand.SET_CONTEXT,
'POST',
'/session/:sessionId/moz/context');
executor.defineCommand(
ExtensionCommand.INSTALL_ADDON,
'POST',
'/session/:sessionId/moz/addon/install');
executor.defineCommand(
ExtensionCommand.UNINSTALL_ADDON,
'POST',
'/session/:sessionId/moz/addon/uninstall');
}
|
javascript
|
{
"resource": ""
}
|
q15322
|
tabView_open
|
train
|
function tabView_open() {
var menuitem = new elementslib.Elem(this._controller.menus['view-menu'].menu_tabview);
this._controller.click(menuitem);
this.waitForOpened();
this._tabView = this.getElement({type: "tabView"});
this._tabViewDoc = this._tabView.getNode().webNavigation.document;
}
|
javascript
|
{
"resource": ""
}
|
q15323
|
tabView_waitForOpened
|
train
|
function tabView_waitForOpened() {
// Add event listener to wait until the tabview has been opened
var self = { opened: false };
function checkOpened() { self.opened = true; }
this._controller.window.addEventListener("tabviewshown", checkOpened, false);
try {
mozmill.utils.waitFor(function() {
return self.opened == true;
}, TIMEOUT, 100, "TabView is not open.");
this._tabViewObject = this._controller.window.TabView;
this._groupItemsObject = this._tabViewObject._window.GroupItems;
this._tabItemsObject = this._tabViewObject._window.TabItems;
} finally {
this._controller.window.removeEventListener("tabviewshown", checkOpened, false);
}
}
|
javascript
|
{
"resource": ""
}
|
q15324
|
tabView_close
|
train
|
function tabView_close() {
var menuitem = new elementslib.Elem(this._controller.menus['view-menu'].menu_tabview);
this._controller.click(menuitem);
this.waitForClosed();
this._tabView = null;
this._tabViewDoc = this._controller.window.document;
}
|
javascript
|
{
"resource": ""
}
|
q15325
|
tabView_waitForClosed
|
train
|
function tabView_waitForClosed() {
// Add event listener to wait until the tabview has been closed
var self = { closed: false };
function checkClosed() { self.closed = true; }
this._controller.window.addEventListener("tabviewhidden", checkClosed, false);
try {
mozmill.utils.waitFor(function() {
return self.closed == true;
}, TIMEOUT, 100, "TabView is still open.");
} finally {
this._controller.window.removeEventListener("tabviewhidden", checkClosed, false);
}
this._tabViewObject = null;
this._groupItemsObject = null;
this._tabItemsObject = null;
}
|
javascript
|
{
"resource": ""
}
|
q15326
|
tabView_getGroupTitleBox
|
train
|
function tabView_getGroupTitleBox(aSpec) {
var spec = aSpec || {};
var group = spec.group;
if (!group) {
throw new Error(arguments.callee.name + ": Group not specified.");
}
return this.getElement({
type: "group_titleBox",
parent: spec.group
});
}
|
javascript
|
{
"resource": ""
}
|
q15327
|
tabView_closeGroup
|
train
|
function tabView_closeGroup(aSpec) {
var spec = aSpec || {};
var group = spec.group;
if (!group) {
throw new Error(arguments.callee.name + ": Group not specified.");
}
var button = this.getElement({
type: "group_closeButton",
value: group
});
this._controller.click(button);
this.waitForGroupClosed({group: group});
}
|
javascript
|
{
"resource": ""
}
|
q15328
|
tabView_undoCloseGroup
|
train
|
function tabView_undoCloseGroup(aSpec) {
var spec = aSpec || {};
var group = spec.group;
if (!group) {
throw new Error(arguments.callee.name + ": Group not specified.");
}
var undo = this.getElement({
type: "group_undoButton",
value: group
});
this._controller.click(undo);
this.waitForGroupUndo({group: group});
}
|
javascript
|
{
"resource": ""
}
|
q15329
|
tabView_waitForGroupUndo
|
train
|
function tabView_waitForGroupUndo(aSpec) {
var spec = aSpec || {};
var group = spec.group;
if (!group) {
throw new Error(arguments.callee.name + ": Group not specified.");
}
var element = null;
this._groupItemsObject.groupItems.forEach(function(node) {
if (node.container == group.getNode()) {
element = node;
}
});
mozmill.utils.waitFor(function() {
return element && element.hidden == false;
}, TIMEOUT, 100, "Tab Group has not been reopened.");
// XXX: Ugly but otherwise the events on the button aren't get processed
this._controller.sleep(0);
}
|
javascript
|
{
"resource": ""
}
|
q15330
|
tabView_closeTab
|
train
|
function tabView_closeTab(aSpec) {
var spec = aSpec || {};
var tab = spec.tab;
if (!tab) {
throw new Error(arguments.callee.name + ": Tab not specified.");
}
var button = this.getElement({
type: "tab_closeButton",
value: tab}
);
this._controller.click(button);
}
|
javascript
|
{
"resource": ""
}
|
q15331
|
tabView_getTabTitleBox
|
train
|
function tabView_getTabTitleBox(aSpec) {
var spec = aSpec || {};
var tab = spec.tab;
if (!tab) {
throw new Error(arguments.callee.name + ": Tab not specified.");
}
return this.getElement({
type: "tab_titleBox",
parent: spec.tab
});
}
|
javascript
|
{
"resource": ""
}
|
q15332
|
tabView_openTab
|
train
|
function tabView_openTab(aSpec) {
var spec = aSpec || {};
var group = spec.group;
if (!group) {
throw new Error(arguments.callee.name + ": Group not specified.");
}
var button = this.getElement({
type: "group_newTabButton",
value: group
});
this._controller.click(button);
this.waitForClosed();
}
|
javascript
|
{
"resource": ""
}
|
q15333
|
createNativeTouchList
|
train
|
function createNativeTouchList(touchListArgs) {
var touches = goog.array.map(touchListArgs, function(touchArg) {
return doc.createTouch(view, target, touchArg.identifier,
touchArg.pageX, touchArg.pageY, touchArg.screenX, touchArg.screenY);
});
return doc.createTouchList.apply(doc, touches);
}
|
javascript
|
{
"resource": ""
}
|
q15334
|
createGenericTouchList
|
train
|
function createGenericTouchList(touchListArgs) {
var touches = goog.array.map(touchListArgs, function(touchArg) {
// The target field is not part of the W3C spec, but both android and iOS
// add the target field to each touch.
return {
identifier: touchArg.identifier,
screenX: touchArg.screenX,
screenY: touchArg.screenY,
clientX: touchArg.clientX,
clientY: touchArg.clientY,
pageX: touchArg.pageX,
pageY: touchArg.pageY,
target: target
};
});
touches.item = function(i) {
return touches[i];
};
return touches;
}
|
javascript
|
{
"resource": ""
}
|
q15335
|
train
|
function() {
/**
* Protobuf raw bytes stream parser
* @private {?JsonStreamParser}
*/
this.jsonStreamParser_ = null;
/**
* The current error message, if any.
* @private {?string}
*/
this.errorMessage_ = null;
/**
* The current position in the streamed data.
* @private {number}
*/
this.streamPos_ = 0;
/**
* The current parser state.
* @private {!State}
*/
this.state_ = State.INIT;
/**
* The currently buffered result (parsed JSON objects).
* @private {!Array<!Object>}
*/
this.result_ = [];
/**
* Whether the status has been parsed.
* @private {boolean}
*/
this.statusParsed_ = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q15336
|
readMore
|
train
|
function readMore() {
while (pos < input.length) {
if (!utils.isJsonWhitespace(input[pos])) {
return true;
}
pos++;
parser.streamPos_++;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q15337
|
mdObserver
|
train
|
function mdObserver(aOpener, aCallback) {
this._opener = aOpener;
this._callback = aCallback;
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this.exception = null;
this.finished = false;
}
|
javascript
|
{
"resource": ""
}
|
q15338
|
mdObserver_findWindow
|
train
|
function mdObserver_findWindow() {
// If a window has been opened from content, it has to be unwrapped.
var window = domUtils.unwrapNode(mozmill.wm.getMostRecentWindow(''));
// Get the WebBrowserChrome and check if it's a modal window
var chrome = window.QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIWebNavigation).
QueryInterface(Ci.nsIDocShellTreeItem).
treeOwner.
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIWebBrowserChrome);
if (!chrome.isWindowModal()) {
return null;
}
// Opening a modal dialog from a modal dialog would fail, if we wouldn't
// check for the opener of the modal dialog
var found = false;
if (window.opener) {
// XXX Bug 614757 - an already unwrapped node returns a wrapped node
var opener = domUtils.unwrapNode(window.opener);
found = (mozmill.utils.getChromeWindow(opener) == this._opener);
}
else {
// Also note that it could happen that dialogs don't have an opener
// (i.e. clear recent history). In such a case make sure that the most
// recent window is not the passed in reference opener
found = (window != this._opener);
}
return (found ? window : null);
}
|
javascript
|
{
"resource": ""
}
|
q15339
|
mdObserver_observe
|
train
|
function mdObserver_observe(aSubject, aTopic, aData) {
// Once the window has been found and loaded we can execute the callback
var window = this.findWindow();
if (window && ("documentLoaded" in window)) {
try {
this._callback(new mozmill.controller.MozMillController(window));
}
catch (ex) {
// Store the exception, so it can be forwarded if a modal dialog has
// been opened by another modal dialog
this.exception = ex;
}
if (window) {
window.close();
}
this.finished = true;
this.stop();
}
else {
// otherwise try again in a bit
this._timer.init(this, DELAY_CHECK, Ci.nsITimer.TYPE_ONE_SHOT);
}
}
|
javascript
|
{
"resource": ""
}
|
q15340
|
modalDialog_start
|
train
|
function modalDialog_start(aCallback) {
if (!aCallback)
throw new Error(arguments.callee.name + ": Callback not specified.");
this._observer = new mdObserver(this._window, aCallback);
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._timer.init(this._observer, DELAY_CHECK, Ci.nsITimer.TYPE_ONE_SHOT);
}
|
javascript
|
{
"resource": ""
}
|
q15341
|
modalDialog_waitForDialog
|
train
|
function modalDialog_waitForDialog(aTimeout) {
var timeout = aTimeout || TIMEOUT_MODAL_DIALOG;
if (!this._observer) {
return;
}
try {
mozmill.utils.waitFor(function () {
return this.finished;
}, "Modal dialog has been found and processed", timeout, undefined, this);
// Forward the raised exception so we can detect failures in modal dialogs
if (this._observer.exception) {
throw this._observer.exception;
}
}
finally {
this.stop();
}
}
|
javascript
|
{
"resource": ""
}
|
q15342
|
train
|
function(event, tagName) {
var element = Event.element(event);
while (element.parentNode && (!element.tagName ||
(element.tagName.toUpperCase() != tagName.toUpperCase())))
element = element.parentNode;
return element;
}
|
javascript
|
{
"resource": ""
}
|
|
q15343
|
train
|
function() {
this.deltaX = window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q15344
|
train
|
function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
}
|
javascript
|
{
"resource": ""
}
|
|
q15345
|
UIArgument
|
train
|
function UIArgument(uiArgumentShorthand, localVars)
{
/**
* @param uiArgumentShorthand
*
* @throws UIArgumentException
*/
this.validate = function(uiArgumentShorthand)
{
var msg = "UIArgument validation error:\n"
+ print_r(uiArgumentShorthand);
// try really hard to throw an exception!
if (!uiArgumentShorthand.name) {
throw new UIArgumentException(msg + 'no name specified!');
}
if (!uiArgumentShorthand.description) {
throw new UIArgumentException(msg + 'no description specified!');
}
if (!uiArgumentShorthand.defaultValues &&
!uiArgumentShorthand.getDefaultValues) {
throw new UIArgumentException(msg + 'no default values specified!');
}
};
/**
* @param uiArgumentShorthand
* @param localVars a list of local variables
*/
this.init = function(uiArgumentShorthand, localVars)
{
this.validate(uiArgumentShorthand);
this.name = uiArgumentShorthand.name;
this.description = uiArgumentShorthand.description;
this.required = uiArgumentShorthand.required || false;
if (uiArgumentShorthand.defaultValues) {
var defaultValues = uiArgumentShorthand.defaultValues;
this.getDefaultValues =
function() { return defaultValues; }
}
else {
this.getDefaultValues = uiArgumentShorthand.getDefaultValues;
}
for (var name in localVars) {
this[name] = localVars[name];
}
}
this.init(uiArgumentShorthand, localVars);
}
|
javascript
|
{
"resource": ""
}
|
q15346
|
UISpecifier
|
train
|
function UISpecifier(uiSpecifierStringOrPagesetName, elementName, args)
{
/**
* Initializes this object from a UI specifier string of the form:
*
* pagesetName::elementName(arg1=value1, arg2=value2, ...)
*
* into its component parts, and returns them as an object.
*
* @return an object containing the components of the UI specifier
* @throws UISpecifierException
*/
this._initFromUISpecifierString = function(uiSpecifierString) {
var matches = /^(.*)::([^\(]+)\((.*)\)$/.exec(uiSpecifierString);
if (matches == null) {
throw new UISpecifierException('Error in '
+ 'UISpecifier._initFromUISpecifierString(): "'
+ this.string + '" is not a valid UI specifier string');
}
this.pagesetName = matches[1];
this.elementName = matches[2];
this.args = (matches[3]) ? parse_kwargs(matches[3]) : {};
};
/**
* Override the toString() method to return the UI specifier string when
* evaluated in a string context. Combines the UI specifier components into
* a canonical UI specifier string and returns it.
*
* @return a UI specifier string
*/
this.toString = function() {
// empty string is acceptable for the path, but it must be defined
if (this.pagesetName == undefined) {
throw new UISpecifierException('Error in UISpecifier.toString(): "'
+ this.pagesetName + '" is not a valid UI specifier pageset '
+ 'name');
}
if (!this.elementName) {
throw new UISpecifierException('Error in UISpecifier.unparse(): "'
+ this.elementName + '" is not a valid UI specifier element '
+ 'name');
}
if (!this.args) {
throw new UISpecifierException('Error in UISpecifier.unparse(): "'
+ this.args + '" are not valid UI specifier args');
}
uiElement = UIMap.getInstance()
.getUIElement(this.pagesetName, this.elementName);
if (uiElement != null) {
var kwargs = to_kwargs(this.args, uiElement.argsOrder);
}
else {
// probably under unit test
var kwargs = to_kwargs(this.args);
}
return this.pagesetName + '::' + this.elementName + '(' + kwargs + ')';
};
// construct the object
if (arguments.length < 2) {
this._initFromUISpecifierString(uiSpecifierStringOrPagesetName);
}
else {
this.pagesetName = uiSpecifierStringOrPagesetName;
this.elementName = elementName;
this.args = (args) ? clone(args) : {};
}
}
|
javascript
|
{
"resource": ""
}
|
q15347
|
UIMap
|
train
|
function UIMap()
{
// the singleton pattern, split into two parts so that "new" can still
// be used, in addition to "getInstance()"
UIMap.self = this;
// need to attach variables directly to the Editor object in order for them
// to be in scope for Editor methods
if (is_IDE()) {
Editor.uiMap = this;
Editor.UI_PREFIX = UI_GLOBAL.UI_PREFIX;
}
this.pagesets = new Object();
/**
* pageset[pagesetName]
* regexp
* elements[elementName]
* UIElement
*/
this.addPageset = function(pagesetShorthand)
{
try {
var pageset = new Pageset(pagesetShorthand);
}
catch (e) {
safe_alert("Could not create pageset from shorthand:\n"
+ print_r(pagesetShorthand) + "\n" + e.message);
return false;
}
if (this.pagesets[pageset.name]) {
safe_alert('Could not add pageset "' + pageset.name
+ '": a pageset with that name already exists!');
return false;
}
this.pagesets[pageset.name] = pageset;
return true;
};
/**
* @param pagesetName
* @param uiElementShorthand a representation of a UIElement object in
* shorthand JSON.
*/
this.addElement = function(pagesetName, uiElementShorthand)
{
try {
var uiElement = new UIElement(uiElementShorthand);
}
catch (e) {
safe_alert("Could not create UI element from shorthand:\n"
+ print_r(uiElementShorthand) + "\n" + e.message);
return false;
}
// run the element's unit tests only for the IDE, and only when the
// IDE is starting. Make a rough guess as to the latter condition.
if (is_IDE() && !editor.selDebugger && !uiElement.test()) {
safe_alert('Could not add UI element "' + uiElement.name
+ '": failed testcases!');
return false;
}
try {
this.pagesets[pagesetName].uiElements[uiElement.name] = uiElement;
}
catch (e) {
safe_alert("Could not add UI element '" + uiElement.name
+ "' to pageset '" + pagesetName + "':\n" + e.message);
return false;
}
return true;
};
/**
* Returns the pageset for a given UI specifier string.
*
* @param uiSpecifierString
* @return a pageset object
*/
this.getPageset = function(uiSpecifierString)
{
try {
var uiSpecifier = new UISpecifier(uiSpecifierString);
return this.pagesets[uiSpecifier.pagesetName];
}
catch (e) {
return null;
}
}
/**
* Returns the UIElement that a UISpecifierString or pageset and element
* pair refer to.
*
* @param pagesetNameOrUISpecifierString
* @return a UIElement, or null if none is found associated with
* uiSpecifierString
*/
this.getUIElement = function(pagesetNameOrUISpecifierString, uiElementName)
{
var pagesetName = pagesetNameOrUISpecifierString;
if (arguments.length == 1) {
var uiSpecifierString = pagesetNameOrUISpecifierString;
try {
var uiSpecifier = new UISpecifier(uiSpecifierString);
pagesetName = uiSpecifier.pagesetName;
var uiElementName = uiSpecifier.elementName;
}
catch (e) {
return null;
}
}
try {
return this.pagesets[pagesetName].uiElements[uiElementName];
}
catch (e) {
return null;
}
};
/**
* Returns a list of pagesets that "contains" the provided page,
* represented as a document object. Containership is defined by the
* Pageset object's contain() method.
*
* @param inDocument the page to get pagesets for
* @return a list of pagesets
*/
this.getPagesetsForPage = function(inDocument)
{
var pagesets = [];
for (var pagesetName in this.pagesets) {
var pageset = this.pagesets[pagesetName];
if (pageset.contains(inDocument)) {
pagesets.push(pageset);
}
}
return pagesets;
};
/**
* Returns a list of all pagesets.
*
* @return a list of pagesets
*/
this.getPagesets = function()
{
var pagesets = [];
for (var pagesetName in this.pagesets) {
pagesets.push(this.pagesets[pagesetName]);
}
return pagesets;
};
/**
* Returns a list of elements on a page that a given UI specifier string,
* maps to. If no elements are mapped to, returns an empty list..
*
* @param uiSpecifierString a String that specifies a UI element with
* attendant argument values
* @param inDocument the document object the specified UI element
* appears in
* @return a potentially-empty list of elements
* specified by uiSpecifierString
*/
this.getPageElements = function(uiSpecifierString, inDocument)
{
var locator = this.getLocator(uiSpecifierString);
var results = locator ? eval_locator(locator, inDocument) : [];
return results;
};
/**
* Returns the locator string that a given UI specifier string maps to, or
* null if it cannot be mapped.
*
* @param uiSpecifierString
*/
this.getLocator = function(uiSpecifierString)
{
try {
var uiSpecifier = new UISpecifier(uiSpecifierString);
}
catch (e) {
safe_alert('Could not create UISpecifier for string "'
+ uiSpecifierString + '": ' + e.message);
return null;
}
var uiElement = this.getUIElement(uiSpecifier.pagesetName,
uiSpecifier.elementName);
try {
return uiElement.getLocator(uiSpecifier.args);
}
catch (e) {
return null;
}
}
/**
* Finds and returns a UI specifier string given an element and the page
* that it appears on.
*
* @param pageElement the document element to map to a UI specifier
* @param inDocument the document the element appears in
* @return a UI specifier string, or false if one cannot be
* constructed
*/
this.getUISpecifierString = function(pageElement, inDocument)
{
var is_fuzzy_match =
BrowserBot.prototype.locateElementByUIElement.is_fuzzy_match;
var pagesets = this.getPagesetsForPage(inDocument);
for (var i = 0; i < pagesets.length; ++i) {
var pageset = pagesets[i];
var uiElements = pageset.getUIElements();
for (var j = 0; j < uiElements.length; ++j) {
var uiElement = uiElements[j];
// first test against the generic locator, if there is one.
// This should net some performance benefit when recording on
// more complicated pages.
if (uiElement.getGenericLocator) {
var passedTest = false;
var results =
eval_locator(uiElement.getGenericLocator(), inDocument);
for (var i = 0; i < results.length; ++i) {
if (results[i] == pageElement) {
passedTest = true;
break;
}
}
if (!passedTest) {
continue;
}
}
var defaultLocators;
if (uiElement.isDefaultLocatorConstructionDeferred) {
defaultLocators = uiElement.getDefaultLocators(inDocument);
}
else {
defaultLocators = uiElement.defaultLocators;
}
//safe_alert(print_r(uiElement.defaultLocators));
for (var locator in defaultLocators) {
var locatedElements = eval_locator(locator, inDocument);
if (locatedElements.length) {
var locatedElement = locatedElements[0];
}
else {
continue;
}
// use a heuristic to determine whether the element
// specified is the "same" as the element we're matching
if (is_fuzzy_match) {
if (is_fuzzy_match(locatedElement, pageElement)) {
return UI_GLOBAL.UI_PREFIX + '=' +
new UISpecifier(pageset.name, uiElement.name,
defaultLocators[locator]);
}
}
else {
if (locatedElement == pageElement) {
return UI_GLOBAL.UI_PREFIX + '=' +
new UISpecifier(pageset.name, uiElement.name,
defaultLocators[locator]);
}
}
// ok, matching the element failed. See if an offset
// locator can complete the match.
if (uiElement.getOffsetLocator) {
for (var k = 0; k < locatedElements.length; ++k) {
var offsetLocator = uiElement
.getOffsetLocator(locatedElements[k], pageElement);
if (offsetLocator) {
return UI_GLOBAL.UI_PREFIX + '=' +
new UISpecifier(pageset.name,
uiElement.name,
defaultLocators[locator])
+ '->' + offsetLocator;
}
}
}
}
}
}
return false;
};
/**
* Returns a sorted list of UI specifier string stubs representing possible
* UI elements for all pagesets, paired the their descriptions. Stubs
* contain all required arguments, but leave argument values blank.
*
* @return a list of UI specifier string stubs
*/
this.getUISpecifierStringStubs = function() {
var stubs = [];
var pagesets = this.getPagesets();
for (var i = 0; i < pagesets.length; ++i) {
stubs = stubs.concat(pagesets[i].getUISpecifierStringStubs());
}
stubs.sort(function(a, b) {
if (a[0] < b[0]) {
return -1;
}
return a[0] == b[0] ? 0 : 1;
});
return stubs;
}
}
|
javascript
|
{
"resource": ""
}
|
q15348
|
downloadManager_cancelActiveDownloads
|
train
|
function downloadManager_cancelActiveDownloads() {
// Get a list of all active downloads (nsISimpleEnumerator)
var downloads = this._dms.activeDownloads;
// Iterate through each active download and cancel it
while (downloads.hasMoreElements()) {
var download = downloads.getNext().QueryInterface(Ci.nsIDownload);
this._dms.cancelDownload(download.id);
}
}
|
javascript
|
{
"resource": ""
}
|
q15349
|
downloadManager_cleanAll
|
train
|
function downloadManager_cleanAll(downloads) {
// Cancel any active downloads
this.cancelActiveDownloads();
// If no downloads have been specified retrieve the list from the database
if (downloads === undefined || downloads.length == 0)
downloads = this.getAllDownloads();
else
downloads = downloads.concat(this.getAllDownloads());
// Delete all files referred to in the Download Manager
this.deleteDownloadedFiles(downloads);
// Clean any entries from the Download Manager database
this.cleanUp();
}
|
javascript
|
{
"resource": ""
}
|
q15350
|
downloadManager_close
|
train
|
function downloadManager_close(force) {
var windowCount = mozmill.utils.getWindows().length;
if (this._controller) {
// Check if we should force the closing of the DM window
if (force) {
this._controller.window.close();
} else {
var cmdKey = utils.getEntity(this.getDtds(), "cmd.close.commandKey");
this._controller.keypress(null, cmdKey, {accelKey: true});
}
this._controller.waitForEval("subject.getWindows().length == " + (windowCount - 1),
gTimeout, 100, mozmill.utils);
this._controller = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q15351
|
downloadManager_deleteDownloadedFiles
|
train
|
function downloadManager_deleteDownloadedFiles(downloads) {
downloads.forEach(function(download) {
try {
var file = getLocalFileFromNativePathOrUrl(download.target);
file.remove(false);
} catch (ex) {
}
});
}
|
javascript
|
{
"resource": ""
}
|
q15352
|
downloadManager_getAllDownloads
|
train
|
function downloadManager_getAllDownloads() {
var dbConn = this._dms.DBConnection;
var stmt = null;
if (dbConn.schemaVersion < 3)
return new Array();
// Run a SQL query and iterate through all results which have been found
var downloads = [];
stmt = dbConn.createStatement("SELECT * FROM moz_downloads");
while (stmt.executeStep()) {
downloads.push({
id: stmt.row.id, name: stmt.row.name, target: stmt.row.target,
tempPath: stmt.row.tempPath, startTime: stmt.row.startTime,
endTime: stmt.row.endTime, state: stmt.row.state,
referrer: stmt.row.referrer, entityID: stmt.row.entityID,
currBytes: stmt.row.currBytes, maxBytes: stmt.row.maxBytes,
mimeType : stmt.row.mimeType, autoResume: stmt.row.autoResume,
preferredApplication: stmt.row.preferredApplication,
preferredAction: stmt.row.preferredAction
});
};
stmt.reset();
return downloads;
}
|
javascript
|
{
"resource": ""
}
|
q15353
|
downloadManager_open
|
train
|
function downloadManager_open(controller, shortcut) {
if (shortcut) {
if (mozmill.isLinux) {
var cmdKey = utils.getEntity(this.getDtds(), "downloadsUnix.commandkey");
controller.keypress(null, cmdKey, {ctrlKey: true, shiftKey: true});
} else {
var cmdKey = utils.getEntity(this.getDtds(), "downloads.commandkey");
controller.keypress(null, cmdKey, {accelKey: true});
}
} else {
controller.click(new elementslib.Elem(controller.menus["tools-menu"].menu_openDownloads));
}
controller.sleep(500);
this.waitForOpened(controller);
}
|
javascript
|
{
"resource": ""
}
|
q15354
|
downloadManager_waitForDownloadState
|
train
|
function downloadManager_waitForDownloadState(download, state, timeout) {
this._controller.waitForEval("subject.manager.getDownloadState(subject.download) == subject.state", timeout, 100,
{manager: this, download: download, state: state});
}
|
javascript
|
{
"resource": ""
}
|
q15355
|
train
|
function(controller, url) {
controller.open(url);
// Wait until the unknown content type dialog has been opened
controller.waitForEval("subject.getMostRecentWindow('').document.documentElement.id == 'unknownContentType'",
gTimeout, 100, mozmill.wm);
utils.handleWindow("type", "", function (controller) {
// Select to save the file directly
var saveFile = new elementslib.ID(controller.window.document, "save");
controller.waitThenClick(saveFile, gTimeout);
controller.waitForEval("subject.selected == true", gTimeout, 100,
saveFile.getNode());
// Wait until the OK button has been enabled and click on it
var button = new elementslib.Lookup(controller.window.document,
'/id("unknownContentType")/anon({"anonid":"buttons"})/{"dlgtype":"accept"}');
controller.waitForElement(button, gTimeout);
controller.waitForEval("subject.okButton.hasAttribute('disabled') == false", gTimeout, 100,
{okButton: button.getNode()});
controller.click(button);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q15356
|
getLocalFileFromNativePathOrUrl
|
train
|
function getLocalFileFromNativePathOrUrl(aPathOrUrl) {
if (aPathOrUrl.substring(0,7) == "file://") {
// if this is a URL, get the file from that
let ioSvc = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService);
// XXX it's possible that using a null char-set here is bad
const fileUrl = ioSvc.newURI(aPathOrUrl, null, null)
.QueryInterface(Ci.nsIFileURL);
return fileUrl.file.clone().QueryInterface(Ci.nsILocalFile);
} else {
// if it's a pathname, create the nsILocalFile directly
var f = new nsLocalFile(aPathOrUrl);
return f;
}
}
|
javascript
|
{
"resource": ""
}
|
q15357
|
jsUnitFixTop
|
train
|
function jsUnitFixTop() {
var tempTop = top;
if (!tempTop) {
tempTop = window;
while (tempTop.parent) {
tempTop = tempTop.parent;
if (tempTop.top && tempTop.top.jsUnitTestSuite) {
tempTop = tempTop.top;
break;
}
}
}
try {
window.top = tempTop;
} catch (e) {
}
}
|
javascript
|
{
"resource": ""
}
|
q15358
|
formatHelpMsg
|
train
|
function formatHelpMsg(usage, options) {
var prog = path.basename(
process.argv[0]) + ' ' + path.basename(process.argv[1]);
var help = [
usage.replace(/\$0\b/g, prog),
'',
'Options:',
formatOption('help', 'Show this message and exit')
];
Object.keys(options).sort().forEach(function(key) {
help.push(formatOption(key, options[key].help));
});
help.push('');
return help.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q15359
|
formatOption
|
train
|
function formatOption(name, helpMsg) {
var result = [];
var options = IDENTATION + '--' + name;
if (options.length > MAX_HELP_POSITION) {
result.push(options);
result.push('\n');
result.push(wrapStr(helpMsg, TOTAL_WIDTH,
repeatStr(' ', HELP_TEXT_POSITION)).join('\n'));
} else {
var spaceCount = HELP_TEXT_POSITION - options.length;
options += repeatStr(' ', spaceCount) + helpMsg;
result.push(options.substring(0, TOTAL_WIDTH));
options = options.substring(TOTAL_WIDTH);
if (options) {
result.push('\n');
result.push(wrapStr(options, TOTAL_WIDTH,
repeatStr(' ', HELP_TEXT_POSITION)).join('\n'));
}
}
return result.join('');
}
|
javascript
|
{
"resource": ""
}
|
q15360
|
checkAccessKeysResults
|
train
|
function checkAccessKeysResults(controller, accessKeysSet) {
// Sort the access keys to have them in a A->Z order
var accessKeysList = accessKeysSet.sort();
// List of access keys
var aKeysList = [];
// List of values to identify the access keys
var valueList = [];
// List of rectangles of nodes containing access keys
var rects = [];
// List of rectangles of nodes with broken access keys
var badRects = [];
// Makes lists of all access keys and the values the access keys are in
for (var i = 0; i < accessKeysList.length; i++) {
var accessKey = accessKeysList[i][0];
var node = accessKeysList[i][1];
// Set the id and label to be shown in the console
var id = node.id || "(id is undefined)";
var label = node.label || "(label is undefined)";
var box = node.boxObject;
var innerIds = [];
var innerRects = [];
// if the access key is already in our list, take it out to replace it
// later
if (accessKey == aKeysList[aKeysList.length-1]) {
innerIds = valueList.pop();
innerRects = rects.pop();
} else {
aKeysList.push([accessKey]);
}
innerIds.push("[id: " + id + ", label: " + label + "]");
valueList.push(innerIds);
innerRects.push([box.x, box.y, box.width, box.height]);
rects.push(innerRects);
}
// Go through all access keys and find the duplicated ones
for (var i = 0; i < valueList.length; i++) {
// Only access keys contained in more than one node are the ones we are
// looking for
if (valueList[i].length > 1) {
for (var j = 0; j < rects[i].length; j++) {
badRects.push(rects[i][j]);
}
jumlib.assert(false, 'accessKey: ' + aKeysList[i] +
' found in string\'s: ' + valueList[i].join(", "));
}
}
// If we have found broken access keys, make a screenshot
if (badRects.length > 0) {
screenshot.create(controller, badRects);
}
}
|
javascript
|
{
"resource": ""
}
|
q15361
|
checkDimensions
|
train
|
function checkDimensions(child) {
if (!child.boxObject)
return [];
var childBox = child.boxObject;
var parent = childBox.parentBox;
// toplevel element or hidden elements, like script tags
if (!parent || parent == child.element || !parent.boxObject) {
return [];
}
var parentBox = parent.boxObject;
var badRects = [];
// check width
if (childBox.height && childBox.screenX < parentBox.screenX) {
badRects.push([childBox.x, childBox.y, parentBox.x - childBox.x,
childBox.height]);
jumlib.assert(false, 'Node is cut off at the left: ' +
_reportNode(child) + '. Parent node: ' + _reportNode(parent));
}
if (childBox.height && childBox.screenX + childBox.width >
parentBox.screenX + parentBox.width) {
badRects.push([parentBox.x + parentBox.width, childBox.y,
childBox.x + childBox.width - parentBox.x - parentBox.width,
childBox.height]);
jumlib.assert(false, 'Node is cut off at the right: ' +
_reportNode(child) + '. Parent node: ' + _reportNode(parent));
}
// check height
// We don't want to test menupopup's, as they always report the full height
// of all items in the popup
if (child.nodeName != 'menupopup' && parent.nodeName != 'menupopup') {
if (childBox.width && childBox.screenY < parentBox.screenY) {
badRects.push([childBox.x, childBox.y, parentBox.y - childBox.y,
childBox.width]);
jumlib.assert(false, 'Node is cut off at the top: ' +
_reportNode(child) + '. Parent node: ' + _reportNode(parent));
}
if (childBox.width && childBox.screenY + childBox.height >
parentBox.screenY + parentBox.height) {
badRects.push([childBox.x, parentBox.y + parentBox.height,
childBox.width,
childBox.y + childBox.height - parentBox.y - parentBox.height]);
jumlib.assert(false, 'Node is cut off at the bottom: ' +
_reportNode(child) + '. Parent node: ' + _reportNode(parent));
}
}
return badRects;
}
|
javascript
|
{
"resource": ""
}
|
q15362
|
filterAccessKeys
|
train
|
function filterAccessKeys(node) {
// Menus will need a separate filter set
var notAllowedLocalNames = ["menu", "menubar", "menupopup", "popupset"];
if (!node.disabled && !node.collapsed && !node.hidden &&
notAllowedLocalNames.indexOf(node.localName) == -1) {
// Code specific to the preferences panes to reject out not visible nodes
// in the panes.
if (node.parentNode && (node.parentNode.localName == "prefwindow" &&
node.parentNode.currentPane.id != node.id) ||
((node.parentNode.localName == "tabpanels" ||
node.parentNode.localName == "deck") &&
node.parentNode.selectedPanel.id != node.id)) {
return domUtils.DOMWalker.FILTER_REJECT;
// end of the specific code
} else if (node.accessKey) {
return domUtils.DOMWalker.FILTER_ACCEPT;
} else {
return domUtils.DOMWalker.FILTER_SKIP;
}
} else {
// we don't want to test not visible elements
return domUtils.DOMWalker.FILTER_REJECT;
}
}
|
javascript
|
{
"resource": ""
}
|
q15363
|
filterCroppedNodes
|
train
|
function filterCroppedNodes(node) {
if (!node.boxObject) {
return domUtils.DOMWalker.FILTER_SKIP;
} else {
if (!node.disabled && !node.collapsed && !node.hidden) {
// Code specific to the preferences panes to reject out not visible nodes
// in the panes.
if (node.parentNode && (node.parentNode.localName == "prefwindow" &&
node.parentNode.currentPane.id != node.id) ||
((node.parentNode.localName == "tabpanels" ||
node.parentNode.localName == "deck") &&
node.parentNode.selectedPanel.id != node.id)) {
return domUtils.DOMWalker.FILTER_REJECT;
// end of the specific code
} else {
return domUtils.DOMWalker.FILTER_ACCEPT;
}
} else {
// we don't want to test not visible elements
return domUtils.DOMWalker.FILTER_REJECT;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15364
|
processDimensionsResults
|
train
|
function processDimensionsResults(controller, boxes) {
if (boxes && boxes.length > 0) {
screenshot.create(controller, boxes);
}
}
|
javascript
|
{
"resource": ""
}
|
q15365
|
_reportNode
|
train
|
function _reportNode(node) {
if (node.id) {
return "id: " + node.id;
} else if (node.label) {
return "label: " + node.label;
} else if (node.value) {
return "value: " + node.value;
} else if (node.hasAttributes()) {
var attrs = "node attributes: ";
for (var i = node.attributes.length - 1; i >= 0; i--) {
attrs += node.attributes[i].name + "->" + node.attributes[i].value + ";";
}
return attrs;
} else {
return "anonymous node";
}
}
|
javascript
|
{
"resource": ""
}
|
q15366
|
mapExec
|
train
|
function mapExec(array, func) {
for (var i = 0; i < array.length; ++i) {
func.call(this, array[i], i);
}
}
|
javascript
|
{
"resource": ""
}
|
q15367
|
mapExpr
|
train
|
function mapExpr(array, func) {
var ret = [];
for (var i = 0; i < array.length; ++i) {
ret.push(func(array[i]));
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q15368
|
reverseInplace
|
train
|
function reverseInplace(array) {
for (var i = 0; i < array.length / 2; ++i) {
var h = array[i];
var ii = array.length - i - 1;
array[i] = array[ii];
array[ii] = h;
}
}
|
javascript
|
{
"resource": ""
}
|
q15369
|
copyArray
|
train
|
function copyArray(dst, src) {
if (!src) return;
var dstLength = dst.length;
for (var i = src.length - 1; i >= 0; --i) {
dst[i+dstLength] = src[i];
}
}
|
javascript
|
{
"resource": ""
}
|
q15370
|
copyArrayIgnoringAttributesWithoutValue
|
train
|
function copyArrayIgnoringAttributesWithoutValue(dst, src)
{
if (!src) return;
for (var i = src.length - 1; i >= 0; --i) {
// this test will pass so long as the attribute has a non-empty string
// value, even if that value is "false", "0", "undefined", etc.
if (src[i].nodeValue) {
dst.push(src[i]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15371
|
xmlValue
|
train
|
function xmlValue(node, disallowBrowserSpecificOptimization) {
if (!node) {
return '';
}
var ret = '';
if (node.nodeType == DOM_TEXT_NODE ||
node.nodeType == DOM_CDATA_SECTION_NODE) {
ret += node.nodeValue;
} else if (node.nodeType == DOM_ATTRIBUTE_NODE) {
if (ajaxsltIsIE6) {
ret += xmlValueIE6Hack(node);
} else {
ret += node.nodeValue;
}
} else if (node.nodeType == DOM_ELEMENT_NODE ||
node.nodeType == DOM_DOCUMENT_NODE ||
node.nodeType == DOM_DOCUMENT_FRAGMENT_NODE) {
if (!disallowBrowserSpecificOptimization) {
// IE, Safari, Opera, and friends
var innerText = node.innerText;
if (innerText != undefined) {
return innerText;
}
// Firefox
var textContent = node.textContent;
if (textContent != undefined) {
return textContent;
}
}
// pobrecito!
var len = node.childNodes.length;
for (var i = 0; i < len; ++i) {
ret += arguments.callee(node.childNodes[i]);
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q15372
|
xmlText
|
train
|
function xmlText(node, opt_cdata) {
var buf = [];
xmlTextR(node, buf, opt_cdata);
return buf.join('');
}
|
javascript
|
{
"resource": ""
}
|
q15373
|
predicateExprHasPositionalSelector
|
train
|
function predicateExprHasPositionalSelector(expr, isRecursiveCall) {
if (!expr) {
return false;
}
if (!isRecursiveCall && exprReturnsNumberValue(expr)) {
// this is a "proximity position"-based predicate
return true;
}
if (expr instanceof FunctionCallExpr) {
var value = expr.name.value;
return (value == 'last' || value == 'position');
}
if (expr instanceof BinaryExpr) {
return (
predicateExprHasPositionalSelector(expr.expr1, true) ||
predicateExprHasPositionalSelector(expr.expr2, true));
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q15374
|
lookUpValueWithKeys
|
train
|
function lookUpValueWithKeys(keys) {
var key = goog.array.find(keys, versionMapHasKey);
return versionMap[key] || '';
}
|
javascript
|
{
"resource": ""
}
|
q15375
|
createExecutor
|
train
|
function createExecutor(url) {
let agent = new http.Agent({ keepAlive: true });
let client = url.then(url => new http.HttpClient(url, agent));
let executor = new http.Executor(client);
configureExecutor(executor);
return executor;
}
|
javascript
|
{
"resource": ""
}
|
q15376
|
configureExecutor
|
train
|
function configureExecutor(executor) {
executor.defineCommand(
Command.LAUNCH_APP,
'POST',
'/session/:sessionId/chromium/launch_app');
executor.defineCommand(
Command.GET_NETWORK_CONDITIONS,
'GET',
'/session/:sessionId/chromium/network_conditions');
executor.defineCommand(
Command.SET_NETWORK_CONDITIONS,
'POST',
'/session/:sessionId/chromium/network_conditions');
executor.defineCommand(
Command.SEND_DEVTOOLS_COMMAND,
'POST',
'/session/:sessionId/chromium/send_command');
}
|
javascript
|
{
"resource": ""
}
|
q15377
|
addonsManager_open
|
train
|
function addonsManager_open(aSpec) {
var spec = aSpec || { };
var type = (spec.type == undefined) ? "menu" : spec.type;
var waitFor = (spec.waitFor == undefined) ? true : spec.waitFor;
switch (type) {
case "menu":
var menuItem = new elementslib.Elem(this._controller.
menus["tools-menu"].menu_openAddons);
this._controller.click(menuItem);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.dtds, "addons.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true, shiftKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unknown event type - " +
event.type);
}
return waitFor ? this.waitForOpened() : null;
}
|
javascript
|
{
"resource": ""
}
|
q15378
|
addonsManager_waitforOpened
|
train
|
function addonsManager_waitforOpened(aSpec) {
var spec = aSpec || { };
var timeout = (spec.timeout == undefined) ? TIMEOUT : spec.timeout;
// TODO: restore after 1.5.1 has landed
// var self = this;
//
// mozmill.utils.waitFor(function() {
// return self.isOpen;
// }, timeout, 100, "Add-ons Manager has been opened");
mozmill.utils.waitForEval("subject.isOpen", timeout, 100, this);
// The first tab found will be the selected one
var tab = this.getTabs()[0];
tab.controller.waitForPageLoad();
return tab;
}
|
javascript
|
{
"resource": ""
}
|
q15379
|
addonsManager_handleUtilsButton
|
train
|
function addonsManager_handleUtilsButton(aSpec) {
var spec = aSpec || { };
var item = spec.item;
if (!item)
throw new Error(arguments.callee.name + ": Menu item not specified.");
var button = this.getElement({type: "utilsButton"});
var menu = this.getElement({type: "utilsButton_menu"});
try {
this._controller.click(button);
// Click the button and wait until menu has been opened
// TODO: restore after 1.5.1 has landed
// mozmill.utils.waitFor(function() {
// return menu.getNode() && menu.getNode().state == "open";
// }, TIMEOUT, 100, "Menu of utils button has been opened.");
mozmill.utils.waitForEval("subject && subject.state == 'open'",
TIMEOUT, 100, menu.getNode());
// Click the given menu entry and make sure the
var menuItem = this.getElement({
type: "utilsButton_menuItem",
value: "#utils-" + item
});
this._controller.click(menuItem);
} finally {
// Make sure the menu has been closed
this._controller.keypress(menu, "VK_ESCAPE", {});
// TODO: restore after 1.5.1 has landed
// mozmill.utils.waitFor(function() {
// return menu.getNode() && menu.getNode().state == "closed";
// }, TIMEOUT, 100, "Menu of utils button has been closed.");
mozmill.utils.waitForEval("subject && subject.state == 'closed'",
TIMEOUT, 100, menu.getNode());
}
}
|
javascript
|
{
"resource": ""
}
|
q15380
|
addonsManager_enableAddon
|
train
|
function addonsManager_enableAddon(aSpec) {
var spec = aSpec || { };
spec.button = "enable";
var button = this.getAddonButton(spec);
this._controller.click(button);
}
|
javascript
|
{
"resource": ""
}
|
q15381
|
addonsManager_disableAddon
|
train
|
function addonsManager_disableAddon(aSpec) {
var spec = aSpec || { };
spec.button = "disable";
var button = this.getAddonButton(spec);
this._controller.click(button);
}
|
javascript
|
{
"resource": ""
}
|
q15382
|
addonsManager_installAddon
|
train
|
function addonsManager_installAddon(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var timeout = spec.timeout;
var button = "install";
var waitFor = (spec.waitFor == undefined) ? true : spec.waitFor;
var button = this.getAddonButton({addon: addon, button: button});
this._controller.click(button);
if (waitFor)
this.waitForDownloaded({addon: addon, timeout: timeout});
}
|
javascript
|
{
"resource": ""
}
|
q15383
|
addonsManager_removeAddon
|
train
|
function addonsManager_removeAddon(aSpec) {
var spec = aSpec || { };
spec.button = "remove";
var button = this.getAddonButton(spec);
this._controller.click(button);
}
|
javascript
|
{
"resource": ""
}
|
q15384
|
addonsManager_undo
|
train
|
function addonsManager_undo(aSpec) {
var spec = aSpec || { };
spec.link = "undo";
var link = this.getAddonLink(spec);
this._controller.click(link);
}
|
javascript
|
{
"resource": ""
}
|
q15385
|
addonsManager_addons
|
train
|
function addonsManager_addons(aSpec) {
var spec = aSpec || {};
return this.getElements({
type: "addons",
subtype: spec.attribute,
value: spec.value,
parent: this.selectedView
});
}
|
javascript
|
{
"resource": ""
}
|
q15386
|
addonsManager_getAddonButton
|
train
|
function addonsManager_getAddonButton(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var button = spec.button;
if (!button)
throw new Error(arguments.callee.name + ": Button not specified.");
return this.getAddonChildElement({addon: addon, type: button + "Button"});
}
|
javascript
|
{
"resource": ""
}
|
q15387
|
addonsManager_getAddonLink
|
train
|
function addonsManager_getAddonLink(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var link = spec.link;
if (!link)
throw new Error(arguments.callee.name + ": Link not specified.");
return this.getAddonChildElement({addon: addon, type: link + "Link"});
}
|
javascript
|
{
"resource": ""
}
|
q15388
|
addonsManager_getAddonRadiogroup
|
train
|
function addonsManager_getAddonRadiogroup(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var radiogroup = spec.radiogroup;
if (!radiogroup)
throw new Error(arguments.callee.name + ": Radiogroup not specified.");
return this.getAddonChildElement({addon: addon, type: radiogroup + "Radiogroup"});
}
|
javascript
|
{
"resource": ""
}
|
q15389
|
addonsManager_getAddonChildElement
|
train
|
function addonsManager_getAddonChildElement(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var attribute = spec.attribute;
var value = spec.value;
var type = spec.type;
if (!addon)
throw new Error(arguments.callee.name + ": Add-on not specified.");
// If no type has been set retrieve a general element which needs an
// attribute and value
if (!type) {
type = "element";
if (!attribute)
throw new Error(arguments.callee.name + ": DOM attribute not specified.");
if (!value)
throw new Error(arguments.callee.name + ": Value not specified.");
}
// For the details view the elements don't have anonymous nodes
if (this.selectedView.getNode().id == "detail-view") {
return this.getElement({
type: "detailView_" + type,
subtype: attribute,
value: value
});
} else {
return this.getElement({
type: "listView_" + type,
subtype: attribute,
value: value,
parent: addon
});
}
}
|
javascript
|
{
"resource": ""
}
|
q15390
|
addonsManager_waitForDownloaded
|
train
|
function addonsManager_waitForDownloaded(aSpec) {
var spec = aSpec || { };
var addon = spec.addon;
var timeout = (spec.timeout == undefined) ? TIMEOUT_DOWNLOAD : spec.timeout;
if (!addon)
throw new Error(arguments.callee.name + ": Add-on not specified.");
var self = this;
var node = addon.getNode();
// TODO: restore after 1.5.1 has landed
// mozmill.utils.waitFor(function () {
// return node.getAttribute("pending") == "install" &&
// node.getAttribute("status") != "installing";
// }, timeout, 100, "'" + node.getAttribute("name") + "' has been downloaded");
mozmill.utils.waitForEval("subject.getAttribute('pending') == 'install' &&" +
"subject.getAttribute('status') != 'installing'",
timeout, 100, node);
}
|
javascript
|
{
"resource": ""
}
|
q15391
|
addonsManager_categories
|
train
|
function addonsManager_categories(aSpec) {
var spec = aSpec || { };
var categories = this.getElements({
type: "categories",
subtype: spec.attribute,
value: spec.value
});
if (categories.length == 0)
throw new Error(arguments.callee.name + ": Categories could not be found.");
return categories;
}
|
javascript
|
{
"resource": ""
}
|
q15392
|
addonsManager_getCategoryById
|
train
|
function addonsManager_getCategoryById(aSpec) {
var spec = aSpec || { };
var id = spec.id;
if (!id)
throw new Error(arguments.callee.name + ": Category ID not specified.");
return this.getCategories({
attribute: "id",
value: "category-" + id
})[0];
}
|
javascript
|
{
"resource": ""
}
|
q15393
|
addonsManager_getCategoryId
|
train
|
function addonsManager_getCategoryId(aSpec) {
var spec = aSpec || { };
var category = spec.category;
if (!category)
throw new Error(arguments.callee.name + ": Category not specified.");
return category.getNode().id;
}
|
javascript
|
{
"resource": ""
}
|
q15394
|
addonsManager_setCategory
|
train
|
function addonsManager_setCategory(aSpec) {
var spec = aSpec || { };
var category = spec.category;
var waitFor = (spec.waitFor == undefined) ? true : spec.waitFor;
if (!category)
throw new Error(arguments.callee.name + ": Category not specified.");
this._controller.click(category);
if (waitFor)
this.waitForCategory({category: category});
}
|
javascript
|
{
"resource": ""
}
|
q15395
|
addonsManager_setCategoryById
|
train
|
function addonsManager_setCategoryById(aSpec) {
var spec = aSpec || { };
var id = spec.id;
var waitFor = (spec.waitFor == undefined) ? true : spec.waitFor;
if (!id)
throw new Error(arguments.callee.name + ": Category ID not specified.");
// Retrieve the category and set it as active
var category = this.getCategoryById({id: id});
if (category)
this.setCategory({category: category, waitFor: waitFor});
else
throw new Error(arguments.callee.name + ": Category '" + id + " not found.");
}
|
javascript
|
{
"resource": ""
}
|
q15396
|
addonsManager_waitForCategory
|
train
|
function addonsManager_waitForCategory(aSpec) {
var spec = aSpec || { };
var category = spec.category;
var timeout = (spec.timeout == undefined) ? TIMEOUT : spec.timeout;
if (!category)
throw new Error(arguments.callee.name + ": Category not specified.");
// TODO: restore after 1.5.1 has landed
// var self = this;
// mozmill.utils.waitFor(function () {
// return self.selectedCategory.getNode() == category.getNode();
// }, timeout, 100, "Category '" + category.getNode().id + "' has been set");
mozmill.utils.waitForEval("subject.self.selectedCategory.getNode() == subject.aCategory.getNode()",
timeout, 100,
{self: this, aCategory: category});
}
|
javascript
|
{
"resource": ""
}
|
q15397
|
addonsManager_search
|
train
|
function addonsManager_search(aSpec) {
var spec = aSpec || { };
var value = spec.value;
var timeout = (spec.timeout == undefined) ? TIMEOUT_SEARCH : spec.timeout;
var waitFor = (spec.waitFor == undefined) ? true : spec.waitFor;
if (!value)
throw new Error(arguments.callee.name + ": Search term not specified.");
var textbox = this.getElement({type: "search_textbox"});
this.clearSearchField();
this._controller.type(textbox, value);
this._controller.keypress(textbox, "VK_RETURN", {});
if (waitFor)
this.waitForSearchFinished();
}
|
javascript
|
{
"resource": ""
}
|
q15398
|
addonsManager_getSearchFilter
|
train
|
function addonsManager_getSearchFilter(aSpec) {
var spec = aSpec || { };
return this.getElements({
type: "search_filterRadioButtons",
subtype: spec.attribute,
value: spec.value
});
}
|
javascript
|
{
"resource": ""
}
|
q15399
|
addonsManager_getSearchFilterByValue
|
train
|
function addonsManager_getSearchFilterByValue(aValue) {
if (!aValue)
throw new Error(arguments.callee.name + ": Search filter value not specified.");
return this.getElement({
type: "search_filterRadioGroup",
subtype: "value",
value: aValue
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.