language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | _getDocument() {
return Promise.all(METADATA_ENDPOINTS.map((path) => { // eslint-disable-line arrow-body-style
return promisify((done) => this._metadata.request(path, done));
}));
} | _getDocument() {
return Promise.all(METADATA_ENDPOINTS.map((path) => { // eslint-disable-line arrow-body-style
return promisify((done) => this._metadata.request(path, done));
}));
} |
JavaScript | function _addToZip( zip, obj ) {
if ( _ieExcel === undefined ) {
// Detect if we are dealing with IE's _awful_ serialiser by seeing if it
// drop attributes
_ieExcel = _serialiser
.serializeToString(
( new window.DOMParser() ).parseFromString( excelStrings['xl/worksheets/sheet1.xml'], 'text/xml' )
)
.indexOf( 'xmlns:r' ) === -1;
}
$.each( obj, function ( name, val ) {
if ( $.isPlainObject( val ) ) {
var newDir = zip.folder( name );
_addToZip( newDir, val );
}
else {
if ( _ieExcel ) {
// IE's XML serialiser will drop some name space attributes from
// from the root node, so we need to save them. Do this by
// replacing the namespace nodes with a regular attribute that
// we convert back when serialised. Edge does not have this
// issue
var worksheet = val.childNodes[0];
var i, ien;
var attrs = [];
for ( i=worksheet.attributes.length-1 ; i>=0 ; i-- ) {
var attrName = worksheet.attributes[i].nodeName;
var attrValue = worksheet.attributes[i].nodeValue;
if ( attrName.indexOf( ':' ) !== -1 ) {
attrs.push( { name: attrName, value: attrValue } );
worksheet.removeAttribute( attrName );
}
}
for ( i=0, ien=attrs.length ; i<ien ; i++ ) {
var attr = val.createAttribute( attrs[i].name.replace( ':', '_dt_b_namespace_token_' ) );
attr.value = attrs[i].value;
worksheet.setAttributeNode( attr );
}
}
var str = _serialiser.serializeToString(val);
// Fix IE's XML
if ( _ieExcel ) {
// IE doesn't include the XML declaration
if ( str.indexOf( '<?xml' ) === -1 ) {
str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+str;
}
// Return namespace attributes to being as such
str = str.replace( /_dt_b_namespace_token_/g, ':' );
// Remove testing name space that IE puts into the space preserve attr
str = str.replace( /xmlns:NS[\d]+="" NS[\d]+:/g, '' );
}
// Safari, IE and Edge will put empty name space attributes onto
// various elements making them useless. This strips them out
str = str.replace( /<([^<>]*?) xmlns=""([^<>]*?)>/g, '<$1 $2>' );
zip.file( name, str );
}
} );
} | function _addToZip( zip, obj ) {
if ( _ieExcel === undefined ) {
// Detect if we are dealing with IE's _awful_ serialiser by seeing if it
// drop attributes
_ieExcel = _serialiser
.serializeToString(
( new window.DOMParser() ).parseFromString( excelStrings['xl/worksheets/sheet1.xml'], 'text/xml' )
)
.indexOf( 'xmlns:r' ) === -1;
}
$.each( obj, function ( name, val ) {
if ( $.isPlainObject( val ) ) {
var newDir = zip.folder( name );
_addToZip( newDir, val );
}
else {
if ( _ieExcel ) {
// IE's XML serialiser will drop some name space attributes from
// from the root node, so we need to save them. Do this by
// replacing the namespace nodes with a regular attribute that
// we convert back when serialised. Edge does not have this
// issue
var worksheet = val.childNodes[0];
var i, ien;
var attrs = [];
for ( i=worksheet.attributes.length-1 ; i>=0 ; i-- ) {
var attrName = worksheet.attributes[i].nodeName;
var attrValue = worksheet.attributes[i].nodeValue;
if ( attrName.indexOf( ':' ) !== -1 ) {
attrs.push( { name: attrName, value: attrValue } );
worksheet.removeAttribute( attrName );
}
}
for ( i=0, ien=attrs.length ; i<ien ; i++ ) {
var attr = val.createAttribute( attrs[i].name.replace( ':', '_dt_b_namespace_token_' ) );
attr.value = attrs[i].value;
worksheet.setAttributeNode( attr );
}
}
var str = _serialiser.serializeToString(val);
// Fix IE's XML
if ( _ieExcel ) {
// IE doesn't include the XML declaration
if ( str.indexOf( '<?xml' ) === -1 ) {
str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+str;
}
// Return namespace attributes to being as such
str = str.replace( /_dt_b_namespace_token_/g, ':' );
// Remove testing name space that IE puts into the space preserve attr
str = str.replace( /xmlns:NS[\d]+="" NS[\d]+:/g, '' );
}
// Safari, IE and Edge will put empty name space attributes onto
// various elements making them useless. This strips them out
str = str.replace( /<([^<>]*?) xmlns=""([^<>]*?)>/g, '<$1 $2>' );
zip.file( name, str );
}
} );
} |
JavaScript | function _createNode( doc, nodeName, opts ) {
var tempNode = doc.createElement( nodeName );
if ( opts ) {
if ( opts.attr ) {
$(tempNode).attr( opts.attr );
}
if ( opts.children ) {
$.each( opts.children, function ( key, value ) {
tempNode.appendChild( value );
} );
}
if ( opts.text !== null && opts.text !== undefined ) {
tempNode.appendChild( doc.createTextNode( opts.text ) );
}
}
return tempNode;
} | function _createNode( doc, nodeName, opts ) {
var tempNode = doc.createElement( nodeName );
if ( opts ) {
if ( opts.attr ) {
$(tempNode).attr( opts.attr );
}
if ( opts.children ) {
$.each( opts.children, function ( key, value ) {
tempNode.appendChild( value );
} );
}
if ( opts.text !== null && opts.text !== undefined ) {
tempNode.appendChild( doc.createTextNode( opts.text ) );
}
}
return tempNode;
} |
JavaScript | function _excelColWidth( data, col ) {
var max = data.header[col].length;
var len, lineSplit, str;
if ( data.footer && data.footer[col].length > max ) {
max = data.footer[col].length;
}
for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
var point = data.body[i][col];
str = point !== null && point !== undefined ?
point.toString() :
'';
// If there is a newline character, workout the width of the column
// based on the longest line in the string
if ( str.indexOf('\n') !== -1 ) {
lineSplit = str.split('\n');
lineSplit.sort( function (a, b) {
return b.length - a.length;
} );
len = lineSplit[0].length;
}
else {
len = str.length;
}
if ( len > max ) {
max = len;
}
// Max width rather than having potentially massive column widths
if ( max > 40 ) {
return 54; // 40 * 1.35
}
}
max *= 1.35;
// And a min width
return max > 6 ? max : 6;
} | function _excelColWidth( data, col ) {
var max = data.header[col].length;
var len, lineSplit, str;
if ( data.footer && data.footer[col].length > max ) {
max = data.footer[col].length;
}
for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
var point = data.body[i][col];
str = point !== null && point !== undefined ?
point.toString() :
'';
// If there is a newline character, workout the width of the column
// based on the longest line in the string
if ( str.indexOf('\n') !== -1 ) {
lineSplit = str.split('\n');
lineSplit.sort( function (a, b) {
return b.length - a.length;
} );
len = lineSplit[0].length;
}
else {
len = str.length;
}
if ( len > max ) {
max = len;
}
// Max width rather than having potentially massive column widths
if ( max > 40 ) {
return 54; // 40 * 1.35
}
}
max *= 1.35;
// And a min width
return max > 6 ? max : 6;
} |
JavaScript | function validate(newValue) {
if (newValue !== undefined) {
if (newValue) {
target.hasError(false);
$control.removeClass("input-validation-error");
} else {
target.hasError(true);
$control.addClass("input-validation-error");
}
}
} | function validate(newValue) {
if (newValue !== undefined) {
if (newValue) {
target.hasError(false);
$control.removeClass("input-validation-error");
} else {
target.hasError(true);
$control.addClass("input-validation-error");
}
}
} |
JavaScript | function _createToast(){var toast=document.createElement('div');toast.classList.add('toast');// Add custom classes onto toast
if(!!this.options.classes.length){$(toast).addClass(this.options.classes);}// Set content
if(typeof HTMLElement==='object'?this.message instanceof HTMLElement:this.message&&typeof this.message==='object'&&this.message!==null&&this.message.nodeType===1&&typeof this.message.nodeName==='string'){toast.appendChild(this.message);// Check if it is jQuery object
}else if(!!this.message.jquery){$(toast).append(this.message[0]);// Insert as html;
}else{toast.innerHTML=this.message;}// Append toasft
Toast._container.appendChild(toast);return toast;}/**
* Animate in toast
*/ | function _createToast(){var toast=document.createElement('div');toast.classList.add('toast');// Add custom classes onto toast
if(!!this.options.classes.length){$(toast).addClass(this.options.classes);}// Set content
if(typeof HTMLElement==='object'?this.message instanceof HTMLElement:this.message&&typeof this.message==='object'&&this.message!==null&&this.message.nodeType===1&&typeof this.message.nodeName==='string'){toast.appendChild(this.message);// Check if it is jQuery object
}else if(!!this.message.jquery){$(toast).append(this.message[0]);// Insert as html;
}else{toast.innerHTML=this.message;}// Append toasft
Toast._container.appendChild(toast);return toast;}/**
* Animate in toast
*/ |
JavaScript | static socketpair(callback) {
assert(callback, "Asynchronous SocketPair.socketpair() method called with no callback.");
if(!SocketPair._requestCount) {
SocketPair._requestCount = 1;
} else {
SocketPair._requestCount += 1;
}
// Start socket acceptor server if not yet started.
SocketPair._startListener((pipeSrv, error) => {
if(!pipeSrv) {
callback(undefined, error);
return;
}
let localSock = new net.Socket()
.on('error', (error) => {
debuglog('Local socket connect: %s', error);
callback(undefined, error);
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.once('close', () => {
debuglog('Local socket closed.');
SocketPair._dequeueLocalSocket(localSock);
callback(undefined, new Error('Premature local socket closure.'));
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.once('paired', (sp) => {
assert(sp != undefined);
assert(sp.localSock === localSock);
localSock.removeAllListeners('error');
localSock.removeAllListeners('close');
debuglog('Completed socket pair allocation: %d/%d', localSock._handle.fd, sp._remoteSock._handle.fd);
callback(sp, undefined);
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.connect(SocketPair.listenerPathname, () => {
let fd = SocketPair._enqueueLocalSocket(localSock);
debuglog('Connected local sock with fd: %d.', fd);
let b = Buffer.alloc(8);
b.writeInt32LE(fd);
b.writeInt32LE(pipeSrv._pipeCookie, 4);
localSock.write(b);
});
});
} | static socketpair(callback) {
assert(callback, "Asynchronous SocketPair.socketpair() method called with no callback.");
if(!SocketPair._requestCount) {
SocketPair._requestCount = 1;
} else {
SocketPair._requestCount += 1;
}
// Start socket acceptor server if not yet started.
SocketPair._startListener((pipeSrv, error) => {
if(!pipeSrv) {
callback(undefined, error);
return;
}
let localSock = new net.Socket()
.on('error', (error) => {
debuglog('Local socket connect: %s', error);
callback(undefined, error);
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.once('close', () => {
debuglog('Local socket closed.');
SocketPair._dequeueLocalSocket(localSock);
callback(undefined, new Error('Premature local socket closure.'));
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.once('paired', (sp) => {
assert(sp != undefined);
assert(sp.localSock === localSock);
localSock.removeAllListeners('error');
localSock.removeAllListeners('close');
debuglog('Completed socket pair allocation: %d/%d', localSock._handle.fd, sp._remoteSock._handle.fd);
callback(sp, undefined);
SocketPair._stopIfPossibleAndNeededOnRequestCompleted();
})
.connect(SocketPair.listenerPathname, () => {
let fd = SocketPair._enqueueLocalSocket(localSock);
debuglog('Connected local sock with fd: %d.', fd);
let b = Buffer.alloc(8);
b.writeInt32LE(fd);
b.writeInt32LE(pipeSrv._pipeCookie, 4);
localSock.write(b);
});
});
} |
JavaScript | static stopListener(force, callback) {
if(callback === undefined) {
if(typeof force == 'function') {
callback = force;
force = true;
}
} else if(force === undefined) {
force = false;
}
if(SocketPair._listener == undefined) {
if(callback) {
callback();
}
return;
}
if(!force && SocketPair._requestCount)
{
debuglog('Queued local socket listener termination.');
SocketPair._stopRequested = true;
SocketPair._listener.once('close', callback);
return;
}
debuglog('Stopping local socket listener.');
SocketPair._listener.close((err) => {
debuglog('Local socket listener is stopped.');
if(callback) {
callback();
}
});
if(force) {
let q = SocketPair._socketQueue;
if(q && q.size) {
debuglog('Closing local sockets, being paired: %s', q);
q.forEach((sock, fd) => {
sock.destroy('SocketPair: Listener stopped');
});
delete SocketPair._socketQueue;
}
}
delete SocketPair._listener;
} | static stopListener(force, callback) {
if(callback === undefined) {
if(typeof force == 'function') {
callback = force;
force = true;
}
} else if(force === undefined) {
force = false;
}
if(SocketPair._listener == undefined) {
if(callback) {
callback();
}
return;
}
if(!force && SocketPair._requestCount)
{
debuglog('Queued local socket listener termination.');
SocketPair._stopRequested = true;
SocketPair._listener.once('close', callback);
return;
}
debuglog('Stopping local socket listener.');
SocketPair._listener.close((err) => {
debuglog('Local socket listener is stopped.');
if(callback) {
callback();
}
});
if(force) {
let q = SocketPair._socketQueue;
if(q && q.size) {
debuglog('Closing local sockets, being paired: %s', q);
q.forEach((sock, fd) => {
sock.destroy('SocketPair: Listener stopped');
});
delete SocketPair._socketQueue;
}
}
delete SocketPair._listener;
} |
JavaScript | static get listenerPathname() {
if(SocketPair._listenerPathname === undefined) {
if( process.platform == 'win32' ) {
SocketPair._listenerPathname = path.join('\\\\?\\pipe', process.cwd(), 'SocketPair-' + process.pid);
debuglog('Will use Win32 named pipe family with pathname: %s', SocketPair._listenerPathname);
} else {
SocketPair._listenerPathname = path.join('/tmp', path.basename(process.execPath) + '-SocketPair-' + process.pid + '.sock');
debuglog('Will use UNIX socket family with pathname: %s', SocketPair._listenerPathname);
}
}
return SocketPair._listenerPathname;
} | static get listenerPathname() {
if(SocketPair._listenerPathname === undefined) {
if( process.platform == 'win32' ) {
SocketPair._listenerPathname = path.join('\\\\?\\pipe', process.cwd(), 'SocketPair-' + process.pid);
debuglog('Will use Win32 named pipe family with pathname: %s', SocketPair._listenerPathname);
} else {
SocketPair._listenerPathname = path.join('/tmp', path.basename(process.execPath) + '-SocketPair-' + process.pid + '.sock');
debuglog('Will use UNIX socket family with pathname: %s', SocketPair._listenerPathname);
}
}
return SocketPair._listenerPathname;
} |
JavaScript | static _startListener(callback) {
if(SocketPair._listener === undefined) {
SocketPair._unlinkListenerSocket();
debuglog('Starting local socket listener.');
const pipeSrv = net.createServer()
.on('listening', () => {
debuglog('Local socket listener is ready.');
})
.on('error', (err) => {
debuglog('Local socket listener: %s', err);
let p = SocketPair._listener;
delete SocketPair._listener;
p.close();
})
.on('close', () => {
debuglog('Local socket listener closed.');
SocketPair._unlinkListenerSocket();
})
.on('connection', (pipeSock) => {
let sp = new SocketPair();
sp._pipeCookie = pipeSrv._pipeCookie;
pipeSock.pause()
.once('error', (err) => {
debuglog('Remote socket error: %s', err);
pipeSock.destroy();
pipeSock = undefined;
})
.once('close', () => {
debuglog('Remote socket closed.');
pipeSock.destroy();
pipeSock = undefined;
})
.on('readable', () => {
// Read local socket handle (file descriptor) value over the connection.
let localFd = sp._consumeLocalSockFdHandleVal(pipeSock);
if(localFd === undefined) {
return;
}
pipeSock.setTimeout(0);
debuglog('Reported local sock fd is: %d.', localFd);
pipeSock.removeAllListeners('readable');
pipeSock.removeAllListeners('error');
pipeSock.removeAllListeners('close');
// Use peer socket handle to couple a socket pair.
SocketPair._dequeueLocalSocket(localFd, (localSock) => {
if(localSock === undefined) {
debuglog('No local sock fd in the pending coupling queue: ' + localFd);
pipeSock.destroy();
return;
}
localSock.pause();
debuglog('Paired local/remote: %d/%d', localFd, pipeSock._handle.fd);
sp._localSock = localSock;
sp._remoteSock = pipeSock;
localSock.emit('paired', sp);
});
})
.setTimeout(exports.pairingTimeout, () => {
debuglog('Timed out, waiting for local socket introduce itself.');
pipeSock.destroy();
pipeSock = undefined;
});
});
pipeSrv._pipeCookie = parseInt(Math.random().toString(10).slice(2, 10));
SocketPair._listener = pipeSrv;
pipeSrv.listen(SocketPair.listenerPathname, 256);
}
if(!callback) {
return;
}
if(SocketPair._listener.listening) {
callback(SocketPair._listener, undefined);
} else {
SocketPair._listener
.once('listening', () => { callback(SocketPair._listener, undefined); })
.once('error', (e) => { callback(undefined, e); });
}
return SocketPair._listener;
} | static _startListener(callback) {
if(SocketPair._listener === undefined) {
SocketPair._unlinkListenerSocket();
debuglog('Starting local socket listener.');
const pipeSrv = net.createServer()
.on('listening', () => {
debuglog('Local socket listener is ready.');
})
.on('error', (err) => {
debuglog('Local socket listener: %s', err);
let p = SocketPair._listener;
delete SocketPair._listener;
p.close();
})
.on('close', () => {
debuglog('Local socket listener closed.');
SocketPair._unlinkListenerSocket();
})
.on('connection', (pipeSock) => {
let sp = new SocketPair();
sp._pipeCookie = pipeSrv._pipeCookie;
pipeSock.pause()
.once('error', (err) => {
debuglog('Remote socket error: %s', err);
pipeSock.destroy();
pipeSock = undefined;
})
.once('close', () => {
debuglog('Remote socket closed.');
pipeSock.destroy();
pipeSock = undefined;
})
.on('readable', () => {
// Read local socket handle (file descriptor) value over the connection.
let localFd = sp._consumeLocalSockFdHandleVal(pipeSock);
if(localFd === undefined) {
return;
}
pipeSock.setTimeout(0);
debuglog('Reported local sock fd is: %d.', localFd);
pipeSock.removeAllListeners('readable');
pipeSock.removeAllListeners('error');
pipeSock.removeAllListeners('close');
// Use peer socket handle to couple a socket pair.
SocketPair._dequeueLocalSocket(localFd, (localSock) => {
if(localSock === undefined) {
debuglog('No local sock fd in the pending coupling queue: ' + localFd);
pipeSock.destroy();
return;
}
localSock.pause();
debuglog('Paired local/remote: %d/%d', localFd, pipeSock._handle.fd);
sp._localSock = localSock;
sp._remoteSock = pipeSock;
localSock.emit('paired', sp);
});
})
.setTimeout(exports.pairingTimeout, () => {
debuglog('Timed out, waiting for local socket introduce itself.');
pipeSock.destroy();
pipeSock = undefined;
});
});
pipeSrv._pipeCookie = parseInt(Math.random().toString(10).slice(2, 10));
SocketPair._listener = pipeSrv;
pipeSrv.listen(SocketPair.listenerPathname, 256);
}
if(!callback) {
return;
}
if(SocketPair._listener.listening) {
callback(SocketPair._listener, undefined);
} else {
SocketPair._listener
.once('listening', () => { callback(SocketPair._listener, undefined); })
.once('error', (e) => { callback(undefined, e); });
}
return SocketPair._listener;
} |
JavaScript | static _stopIfPossibleAndNeededOnRequestCompleted() {
if(SocketPair._requestCount) {
SocketPair._requestCount -= 1;
}
if(!SocketPair._stopRequested || SocketPair._requestCount)
{
return;
}
SocketPair.stopListener(false);
} | static _stopIfPossibleAndNeededOnRequestCompleted() {
if(SocketPair._requestCount) {
SocketPair._requestCount -= 1;
}
if(!SocketPair._stopRequested || SocketPair._requestCount)
{
return;
}
SocketPair.stopListener(false);
} |
JavaScript | static _unlinkListenerSocket() {
if(process.platform != 'win32')
{
try {
let pathname = SocketPair.listenerPathname;
fs.accessSync(pathname, fs.constants.F_OK);
fs.unlinkSync(pathname);
debuglog('Unlinked listener socket at: %s', pathname);
} catch(e) {
}
}
} | static _unlinkListenerSocket() {
if(process.platform != 'win32')
{
try {
let pathname = SocketPair.listenerPathname;
fs.accessSync(pathname, fs.constants.F_OK);
fs.unlinkSync(pathname);
debuglog('Unlinked listener socket at: %s', pathname);
} catch(e) {
}
}
} |
JavaScript | static _enqueueLocalSocket(sock) {
assert(sock != undefined && sock._handle);
let fd = sock._handle.fd;
if(fd != undefined) {
if(SocketPair._socketQueue === undefined) {
SocketPair._socketQueue = new Map();
}
assert(SocketPair._socketQueue.get(fd) === undefined, 'Already enqueued handle: ' + fd);
SocketPair._socketQueue.set(fd, sock);
}
return fd;
} | static _enqueueLocalSocket(sock) {
assert(sock != undefined && sock._handle);
let fd = sock._handle.fd;
if(fd != undefined) {
if(SocketPair._socketQueue === undefined) {
SocketPair._socketQueue = new Map();
}
assert(SocketPair._socketQueue.get(fd) === undefined, 'Already enqueued handle: ' + fd);
SocketPair._socketQueue.set(fd, sock);
}
return fd;
} |
JavaScript | static _dequeueLocalSocket(fd, callback) {
assert(fd != undefined);
if(SocketPair._socketQueue === undefined) {
if(callback) {
callback(undefined);
}
return;
}
if(typeof fd == 'object') {
let realFd = fd._handle ? fd._handle.fd : undefined;
if(!realFd) {
// Wortht case - there is no socket handle and a sequential lookup is necessary.
for( var [key, value] of SocketPair._socketQueue) {
if(value === fd) {
SocketPair._socketQueue.delete(key);
if(callback) {
callback(sock);
}
return;
}
}
}
if(callback) {
callback(undefined);
}
return;
}
let sock = SocketPair._socketQueue.get(fd);
SocketPair._socketQueue.delete(fd);
if(callback) {
callback(sock);
}
} | static _dequeueLocalSocket(fd, callback) {
assert(fd != undefined);
if(SocketPair._socketQueue === undefined) {
if(callback) {
callback(undefined);
}
return;
}
if(typeof fd == 'object') {
let realFd = fd._handle ? fd._handle.fd : undefined;
if(!realFd) {
// Wortht case - there is no socket handle and a sequential lookup is necessary.
for( var [key, value] of SocketPair._socketQueue) {
if(value === fd) {
SocketPair._socketQueue.delete(key);
if(callback) {
callback(sock);
}
return;
}
}
}
if(callback) {
callback(undefined);
}
return;
}
let sock = SocketPair._socketQueue.get(fd);
SocketPair._socketQueue.delete(fd);
if(callback) {
callback(sock);
}
} |
JavaScript | _consumeLocalSockFdHandleVal(sock) {
let data = sock.read(8);
if(data === null) {
return undefined;
}
if(data.length < 8) {
return undefined;
}
let cookie = data.readInt32LE(4);
assert(this._pipeCookie);
if(cookie != this._pipeCookie) {
debuglog('Incoming connection havn\'t provided valid cookie: %d, expected: %d.', cookie, this._pipeCookie);
sock.end();
return undefined;
}
let fd = data.readInt32LE(0);
return fd;
} | _consumeLocalSockFdHandleVal(sock) {
let data = sock.read(8);
if(data === null) {
return undefined;
}
if(data.length < 8) {
return undefined;
}
let cookie = data.readInt32LE(4);
assert(this._pipeCookie);
if(cookie != this._pipeCookie) {
debuglog('Incoming connection havn\'t provided valid cookie: %d, expected: %d.', cookie, this._pipeCookie);
sock.end();
return undefined;
}
let fd = data.readInt32LE(0);
return fd;
} |
JavaScript | function gameOver(winOrLose) {
// display table again, without click events
grid.innerHTML = "<table>" + game.displayMineField(true) + "</table>";
let tiles = Array.from(grid.querySelectorAll("td"));
tiles.forEach((tile) => {
let value = Number(tile.innerText);
// place icons
if (value >= 1000) {
tile.innerHTML = `<i class="fas fa-bomb"></i>`;
} else if (value === 0) {
tile.innerText = "";
tile.classList.add("emptyTile");
}
});
// display game over
showMessage(winOrLose);
// end timer
clearInterval(startCounting);
} | function gameOver(winOrLose) {
// display table again, without click events
grid.innerHTML = "<table>" + game.displayMineField(true) + "</table>";
let tiles = Array.from(grid.querySelectorAll("td"));
tiles.forEach((tile) => {
let value = Number(tile.innerText);
// place icons
if (value >= 1000) {
tile.innerHTML = `<i class="fas fa-bomb"></i>`;
} else if (value === 0) {
tile.innerText = "";
tile.classList.add("emptyTile");
}
});
// display game over
showMessage(winOrLose);
// end timer
clearInterval(startCounting);
} |
JavaScript | toJSON() {
let json;
const state = this._state;
if (state.type === 'text') {
json = {
type: 'text',
body: '' + state.body
};
} else if (state.type === 'is-typing') {
json = {
type: 'is-typing',
isTyping: !!state.isTyping
};
} else if (state.type === 'read-receipt') {
json = {
type: 'read-receipt',
messageIds: state.messageIds
};
} else {
if (state.type === 'picture') {
json = {
type: 'picture',
picUrl: '' + state.picUrl
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
} else if (state.type === 'link') {
json = {
type: 'link',
url: '' + state.url
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
} else if (state.type === 'video') {
json = {
type: 'video',
videoUrl: '' + state.videoUrl,
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
if (!util.isUndefined(state.loop)) {
json.loop = !!state.loop;
}
if (!util.isUndefined(state.muted)) {
json.muted = !!state.muted;
}
if (!util.isUndefined(state.autoplay)) {
json.autoplay = !!state.autoplay;
}
}
if (util.isString(state.picUrl)) {
json.picUrl = '' + state.picUrl;
}
if (util.isString(state.title)) {
json.title = '' + state.title;
}
if (util.isString(state.text)) {
json.text = '' + state.text;
}
if (!util.isUndefined(state.noSave)) {
json.noSave = !!state.noSave;
}
if (!util.isUndefined(state.kikJsData)) {
json.kikJsData = state.kikJsData;
}
if (!util.isUndefined(state.noForward)) {
json.noForward = !!state.noForward;
}
}
if (!util.isUndefined(state.typeTime)) {
json.typeTime = +state.typeTime;
}
if (!util.isUndefined(state.delay)) {
json.delay = +state.delay;
}
if (state.keyboards && state.keyboards.length !== 0) {
json.keyboards = state.keyboards;
}
return json;
} | toJSON() {
let json;
const state = this._state;
if (state.type === 'text') {
json = {
type: 'text',
body: '' + state.body
};
} else if (state.type === 'is-typing') {
json = {
type: 'is-typing',
isTyping: !!state.isTyping
};
} else if (state.type === 'read-receipt') {
json = {
type: 'read-receipt',
messageIds: state.messageIds
};
} else {
if (state.type === 'picture') {
json = {
type: 'picture',
picUrl: '' + state.picUrl
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
} else if (state.type === 'link') {
json = {
type: 'link',
url: '' + state.url
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
} else if (state.type === 'video') {
json = {
type: 'video',
videoUrl: '' + state.videoUrl,
};
if (!util.isUndefined(state.attribution)) {
json.attribution = {
name: '' + state.attribution.name,
iconUrl: '' + state.attribution.iconUrl
};
}
if (!util.isUndefined(state.loop)) {
json.loop = !!state.loop;
}
if (!util.isUndefined(state.muted)) {
json.muted = !!state.muted;
}
if (!util.isUndefined(state.autoplay)) {
json.autoplay = !!state.autoplay;
}
}
if (util.isString(state.picUrl)) {
json.picUrl = '' + state.picUrl;
}
if (util.isString(state.title)) {
json.title = '' + state.title;
}
if (util.isString(state.text)) {
json.text = '' + state.text;
}
if (!util.isUndefined(state.noSave)) {
json.noSave = !!state.noSave;
}
if (!util.isUndefined(state.kikJsData)) {
json.kikJsData = state.kikJsData;
}
if (!util.isUndefined(state.noForward)) {
json.noForward = !!state.noForward;
}
}
if (!util.isUndefined(state.typeTime)) {
json.typeTime = +state.typeTime;
}
if (!util.isUndefined(state.delay)) {
json.delay = +state.delay;
}
if (state.keyboards && state.keyboards.length !== 0) {
json.keyboards = state.keyboards;
}
return json;
} |
JavaScript | update(state_update) {
if (!state_update || state_update.type === undefined)
return;
switch (state_update.type) {
case "BOARD":
this._board = {
width: state_update.object.width,
height: state_update.object.height,
blocks: state_update.object.blocks
};
if (state_update.object.new_level)
this._newLevel();
break;
case "SNAKE":
this._snake = {
snake: state_update.object.snake,
direction: state_update.object.direction
};
if (state_update.object.new_fruits)
state_update.object.new_fruits.forEach(fruit => this._newFruit(fruit));
if (state_update.object.expired_fruits)
state_update.object.expired_fruits.forEach(fruit => this._expiredFruit(fruit));
break;
}
} | update(state_update) {
if (!state_update || state_update.type === undefined)
return;
switch (state_update.type) {
case "BOARD":
this._board = {
width: state_update.object.width,
height: state_update.object.height,
blocks: state_update.object.blocks
};
if (state_update.object.new_level)
this._newLevel();
break;
case "SNAKE":
this._snake = {
snake: state_update.object.snake,
direction: state_update.object.direction
};
if (state_update.object.new_fruits)
state_update.object.new_fruits.forEach(fruit => this._newFruit(fruit));
if (state_update.object.expired_fruits)
state_update.object.expired_fruits.forEach(fruit => this._expiredFruit(fruit));
break;
}
} |
JavaScript | run() {
while (true) {
// board
this.readAndUpdate();
// snake
this.readAndUpdate();
this.execute();
this.doAction(this._action);
this.sendAction();
// reset current action
this._action = "IDLE";
}
} | run() {
while (true) {
// board
this.readAndUpdate();
// snake
this.readAndUpdate();
this.execute();
this.doAction(this._action);
this.sendAction();
// reset current action
this._action = "IDLE";
}
} |
JavaScript | update(state_update) {
if (state_update === undefined || state_update.type === undefined)
return;
switch (state_update.type) {
case 'HIT':
if (!state_update.object)
quit(-2);
let pos = state_update.object.split('\\s+');
this.bullseyeX = pos[0];
this.bullseyeY = pos[1];
break;
}
} | update(state_update) {
if (state_update === undefined || state_update.type === undefined)
return;
switch (state_update.type) {
case 'HIT':
if (!state_update.object)
quit(-2);
let pos = state_update.object.split('\\s+');
this.bullseyeX = pos[0];
this.bullseyeY = pos[1];
break;
}
} |
JavaScript | run() {
// game flow
while (true) {
this.readAndUpdate();
this.execute();
this.sendAction();
}
} | run() {
// game flow
while (true) {
this.readAndUpdate();
this.execute();
this.sendAction();
}
} |
JavaScript | function play(movie) {
var header = movie.header;
if(header === undefined)
throw "header missing in movie";
logger = document.getElementById("logArea");
canvas = document.getElementById("movieCanvas");
canvas.width = header.width;
canvas.height = header.height;
context = canvas.getContext("2d");
waitingFor = 0;
if (header.background) {
waitingFor++;
background = new Image();
background.onload = function() { startPlaying(); };
background.src = header.background;
}
if(header.sprites === undefined)
throw "spites missing in movie header";
for(var id in header.sprites) {
var image = new Image();
waitingFor++;
image.onload = function() { startPlaying(); };
image.src = header.sprites[id];
sprites[id] = image;
}
if(movie.frames === undefined)
throw "frames missing in movie";
frames = movie.frames;
if(movie.header.fps === undefined)
framesPerSecond = 1;
else
framesPerSecond = header.fps;
anchor_point = header.anchor_point;
} | function play(movie) {
var header = movie.header;
if(header === undefined)
throw "header missing in movie";
logger = document.getElementById("logArea");
canvas = document.getElementById("movieCanvas");
canvas.width = header.width;
canvas.height = header.height;
context = canvas.getContext("2d");
waitingFor = 0;
if (header.background) {
waitingFor++;
background = new Image();
background.onload = function() { startPlaying(); };
background.src = header.background;
}
if(header.sprites === undefined)
throw "spites missing in movie header";
for(var id in header.sprites) {
var image = new Image();
waitingFor++;
image.onload = function() { startPlaying(); };
image.src = header.sprites[id];
sprites[id] = image;
}
if(movie.frames === undefined)
throw "frames missing in movie";
frames = movie.frames;
if(movie.header.fps === undefined)
framesPerSecond = 1;
else
framesPerSecond = header.fps;
anchor_point = header.anchor_point;
} |
JavaScript | function startPlaying() {
if(--waitingFor === 0) {
startTime = new Date().getTime();
lastFrameIndex = -1;
continuePlaying();
}
} | function startPlaying() {
if(--waitingFor === 0) {
startTime = new Date().getTime();
lastFrameIndex = -1;
continuePlaying();
}
} |
JavaScript | function continuePlaying() {
var currentTime = new Date().getTime();
var frameIndex = Math.floor((
currentTime - startTime) * framesPerSecond / 1000);
if(frameIndex > lastFrameIndex) {
lastFrameIndex = frameIndex;
if(frameIndex < frames.length)
showFrame(frames[frameIndex]);
}
if(frameIndex < frames.length-1)
window.requestAnimationFrame(continuePlaying);
} | function continuePlaying() {
var currentTime = new Date().getTime();
var frameIndex = Math.floor((
currentTime - startTime) * framesPerSecond / 1000);
if(frameIndex > lastFrameIndex) {
lastFrameIndex = frameIndex;
if(frameIndex < frames.length)
showFrame(frames[frameIndex]);
}
if(frameIndex < frames.length-1)
window.requestAnimationFrame(continuePlaying);
} |
JavaScript | function showFrame(frame) {
context.clearRect(0,0,canvas.width,canvas.height);
if (background)
context.drawImage(background,0,0);
if(frame.items === undefined)
throw "missing item in frame:"+lastFrameIndex;
var messages = frame.messages[player];
if(messages !== undefined) {
logger.value += frame.messages[player];
logger.scrollTop = logger.scrollHeight;
}
var ratio = 1; // here ratio is always the same
for(var i in frame.items) {
var item = frame.items[i];
var sprite = sprites[item.sprite];
var msg = item.message;
var posX = item.x;
var posY = item.y;
var relX, relY;
if(sprite === undefined && msg === undefined)
throw "unknown sprite with id:"+item.sprite;
var spriteWidth = sprite.width;
var spriteHeight = sprite.height;
if (item.view_window) {
spriteWidth = !item.view_window.width ?
spriteWidth - item.view_window.start_x : item.view_window.width;
spriteHeight = !item.view_window.height ?
spriteHeight - item.view_window.start_y : item.view_window.height;
}
var spriteRatio = ratio;
if (item.scale)
spriteRatio = item.scale * ratio;
context.save();
context.translate(item.x * ratio, item.y * ratio);
context.scale(spriteRatio, spriteRatio);
if (item.rotate)
context.rotate(item.rotate);
if(sprite)
{
switch(anchor_point) {
case "TOP":
relX = -spriteWidth/2;
relY = 0;
break;
case "TOP_LEFT":
relX = 0;
relY = 0;
break;
case "TOP_RIGHT":
relX = -spriteWidth;
relY = 0;
break;
case "LEFT":
relX = 0;
relY = -spriteHeight/2;
break;
case "RIGHT":
relX = -spriteWidth;
relY = -spriteHeight/2;
break;
case "BOTTOM":
relX = -spriteWidth/2;
relY = -spriteHeight;
break;
case "BOTTOM_LEFT":
relX = 0;
relY = -spriteHeight;
break;
case "BOTTOM_RIGHT":
relX = -spriteWidth;
relY = -spriteHeight;
break;
case "CENTER":
default:
relX = -spriteWidth/2;
relY = -spriteHeight/2;
break;
}
if (!item.view_window)
context.drawImage(sprite,relX,relY);
else {
var startX = item.view_window.start_x;
var startY = item.view_window.start_y;
context.drawImage(sprite, startX, startY,
spriteWidth, spriteHeight,
relX, relY,
spriteWidth, spriteHeight);
}
}
if(msg)
{
context.font="40px Verdana";
context.fillStyle = 'white';
context.fillText(msg, posX, posY);
}
context.restore();
}
} | function showFrame(frame) {
context.clearRect(0,0,canvas.width,canvas.height);
if (background)
context.drawImage(background,0,0);
if(frame.items === undefined)
throw "missing item in frame:"+lastFrameIndex;
var messages = frame.messages[player];
if(messages !== undefined) {
logger.value += frame.messages[player];
logger.scrollTop = logger.scrollHeight;
}
var ratio = 1; // here ratio is always the same
for(var i in frame.items) {
var item = frame.items[i];
var sprite = sprites[item.sprite];
var msg = item.message;
var posX = item.x;
var posY = item.y;
var relX, relY;
if(sprite === undefined && msg === undefined)
throw "unknown sprite with id:"+item.sprite;
var spriteWidth = sprite.width;
var spriteHeight = sprite.height;
if (item.view_window) {
spriteWidth = !item.view_window.width ?
spriteWidth - item.view_window.start_x : item.view_window.width;
spriteHeight = !item.view_window.height ?
spriteHeight - item.view_window.start_y : item.view_window.height;
}
var spriteRatio = ratio;
if (item.scale)
spriteRatio = item.scale * ratio;
context.save();
context.translate(item.x * ratio, item.y * ratio);
context.scale(spriteRatio, spriteRatio);
if (item.rotate)
context.rotate(item.rotate);
if(sprite)
{
switch(anchor_point) {
case "TOP":
relX = -spriteWidth/2;
relY = 0;
break;
case "TOP_LEFT":
relX = 0;
relY = 0;
break;
case "TOP_RIGHT":
relX = -spriteWidth;
relY = 0;
break;
case "LEFT":
relX = 0;
relY = -spriteHeight/2;
break;
case "RIGHT":
relX = -spriteWidth;
relY = -spriteHeight/2;
break;
case "BOTTOM":
relX = -spriteWidth/2;
relY = -spriteHeight;
break;
case "BOTTOM_LEFT":
relX = 0;
relY = -spriteHeight;
break;
case "BOTTOM_RIGHT":
relX = -spriteWidth;
relY = -spriteHeight;
break;
case "CENTER":
default:
relX = -spriteWidth/2;
relY = -spriteHeight/2;
break;
}
if (!item.view_window)
context.drawImage(sprite,relX,relY);
else {
var startX = item.view_window.start_x;
var startY = item.view_window.start_y;
context.drawImage(sprite, startX, startY,
spriteWidth, spriteHeight,
relX, relY,
spriteWidth, spriteHeight);
}
}
if(msg)
{
context.font="40px Verdana";
context.fillStyle = 'white';
context.fillText(msg, posX, posY);
}
context.restore();
}
} |
JavaScript | shooting (state) {
this.fire()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
} | shooting (state) {
this.fire()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
} |
JavaScript | rejected(reason) {
if (reason === 'FAILURE_RECHARGING'){
if (this.direction === 'up') {
this.down()
.then((state) => this.goDown(state))
.catch((reason) => this.rejected(reason));
this.direction = 'down';
} else {
this.up()
.then((state) => this.goUp(state))
.catch((reason) => this.rejected(reason));
this.direction = 'up';
}
}
else if (reason === 'FAILURE_OUT_OF_BOUNDS')
this.fire()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
else
this.idle()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
} | rejected(reason) {
if (reason === 'FAILURE_RECHARGING'){
if (this.direction === 'up') {
this.down()
.then((state) => this.goDown(state))
.catch((reason) => this.rejected(reason));
this.direction = 'down';
} else {
this.up()
.then((state) => this.goUp(state))
.catch((reason) => this.rejected(reason));
this.direction = 'up';
}
}
else if (reason === 'FAILURE_OUT_OF_BOUNDS')
this.fire()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
else
this.idle()
.then((state) => this.move(state))
.catch((reason => this.rejected(reason)));
} |
JavaScript | update (state_update) {
if (!state_update || state_update.type === undefined)
return;
switch (state_update.type) {
case "PONG":
this._state = Object.assign({}, state_update.object.board);
this._promise_succeeded = state_update.object.result === 'SUCCESS';
if (!this._promise_succeeded)
this._promise_failure_reason = state_update.object.result;
break;
}
} | update (state_update) {
if (!state_update || state_update.type === undefined)
return;
switch (state_update.type) {
case "PONG":
this._state = Object.assign({}, state_update.object.board);
this._promise_succeeded = state_update.object.result === 'SUCCESS';
if (!this._promise_succeeded)
this._promise_failure_reason = state_update.object.result;
break;
}
} |
JavaScript | run () {
this.readAndUpdate();
this.start(this._state);
this.doAction("PADDLE", this._current_action);
this.sendAction();
while (true) {
this.readAndUpdate();
if (!this._next_command)
return;
if (this._promise_succeeded) {
this._next_command.resolve(this._state);
} else {
this._next_command.reject(this._promise_failure_reason);
}
this.doAction("PADDLE", this._current_action);
this.sendAction();
// reset current action
this._current_action = [0, 0, false];
// reset promise results
this._promise_succeeded = undefined;
this._promise_failure_reason = undefined;
}
} | run () {
this.readAndUpdate();
this.start(this._state);
this.doAction("PADDLE", this._current_action);
this.sendAction();
while (true) {
this.readAndUpdate();
if (!this._next_command)
return;
if (this._promise_succeeded) {
this._next_command.resolve(this._state);
} else {
this._next_command.reject(this._promise_failure_reason);
}
this.doAction("PADDLE", this._current_action);
this.sendAction();
// reset current action
this._current_action = [0, 0, false];
// reset promise results
this._promise_succeeded = undefined;
this._promise_failure_reason = undefined;
}
} |
JavaScript | resolved(state) {
return this.up()
.then((state) => this.resolved(state))
.catch((err) => this.rejected(err));
} | resolved(state) {
return this.up()
.then((state) => this.resolved(state))
.catch((err) => this.rejected(err));
} |
JavaScript | rejected(err) {
return this.down()
.then((state) => this.resolved(state))
.catch((err) => this.rejected(err));
} | rejected(err) {
return this.down()
.then((state) => this.resolved(state))
.catch((err) => this.rejected(err));
} |
JavaScript | function adjustPlayerHeights(){
if( Foundation.MediaQuery.atLeast('medium') ) {
$('#amplitude-right').css('max-height', $('#amplitude-left').height()+'px');
}else{
$('#amplitude-right').css('max-height', 'initial' );
}
} | function adjustPlayerHeights(){
if( Foundation.MediaQuery.atLeast('medium') ) {
$('#amplitude-right').css('max-height', $('#amplitude-left').height()+'px');
}else{
$('#amplitude-right').css('max-height', 'initial' );
}
} |
JavaScript | check () {
const response = {
agentsAvailable: false,
};
return this._checkWorkingTime()
.then(() => {
return SDKLoader.load();
})
.then(this._areAvailableAgents.bind(this))
.then(() => {
response.agentsAvailable = true;
return response;
})
.catch((err) => {
response.agentsAvailable = false;
response.reason = 'no-agents';
return response;
});
} | check () {
const response = {
agentsAvailable: false,
};
return this._checkWorkingTime()
.then(() => {
return SDKLoader.load();
})
.then(this._areAvailableAgents.bind(this))
.then(() => {
response.agentsAvailable = true;
return response;
})
.catch((err) => {
response.agentsAvailable = false;
response.reason = 'no-agents';
return response;
});
} |
JavaScript | _areAvailableAgents () {
const getRoom = Conf.get('room');
const getLanguage = Conf.get('lang');
if (!isFunction(getRoom) || !isFunction(getLanguage)) {
throw new Error('Room and language configurations must be callable functions');
}
const roomId = getRoom();
const lang = getLanguage();
const params = { roomIds: roomId };
// set lang if specified
if (lang) {
params.langs = lang;
}
return ICF.Api.request('/agents/available', 'GET', params)
.then((res) => {
if (!isEmpty(res.data) && !isEmpty(res.data.agents)) {
return (res.data.agents[roomId] >= 1);
}
return false;
})
.then((areAvailable) => {
if (!areAvailable) {
throw new Error('No available agents');
}
});
} | _areAvailableAgents () {
const getRoom = Conf.get('room');
const getLanguage = Conf.get('lang');
if (!isFunction(getRoom) || !isFunction(getLanguage)) {
throw new Error('Room and language configurations must be callable functions');
}
const roomId = getRoom();
const lang = getLanguage();
const params = { roomIds: roomId };
// set lang if specified
if (lang) {
params.langs = lang;
}
return ICF.Api.request('/agents/available', 'GET', params)
.then((res) => {
if (!isEmpty(res.data) && !isEmpty(res.data.agents)) {
return (res.data.agents[roomId] >= 1);
}
return false;
})
.then((areAvailable) => {
if (!areAvailable) {
throw new Error('No available agents');
}
});
} |
JavaScript | validate (conf) {
if (
!isPlainObject(conf) ||
(!conf.appId || !isString(conf.appId)) ||
(
(!conf.region || !isString(conf.region)) &&
(!conf.server || !isString(conf.server))
) ||
(!conf.room || !isFunction(conf.room))
) {
throw new Error('Invalid or missing configuration value');
}
return true;
} | validate (conf) {
if (
!isPlainObject(conf) ||
(!conf.appId || !isString(conf.appId)) ||
(
(!conf.region || !isString(conf.region)) &&
(!conf.server || !isString(conf.server))
) ||
(!conf.room || !isFunction(conf.room))
) {
throw new Error('Invalid or missing configuration value');
}
return true;
} |
JavaScript | assignDefaults (conf) {
const defaultSource = () => {
return '3';
};
const defaultLang = () => {
return '';
};
conf.sdkVersion = conf.sdkVersion || '1';
conf.source = isFunction(conf.source) ? conf.source : defaultSource;
conf.lang = isFunction(conf.lang) ? conf.lang : defaultLang;
conf.importBotHistory = isBoolean(conf.importBotHistory) ? conf.importBotHistory : false;
conf.fileUploadsActive = isBoolean(conf.fileUploadsActive) ? conf.fileUploadsActive : false;
return conf;
} | assignDefaults (conf) {
const defaultSource = () => {
return '3';
};
const defaultLang = () => {
return '';
};
conf.sdkVersion = conf.sdkVersion || '1';
conf.source = isFunction(conf.source) ? conf.source : defaultSource;
conf.lang = isFunction(conf.lang) ? conf.lang : defaultLang;
conf.importBotHistory = isBoolean(conf.importBotHistory) ? conf.importBotHistory : false;
conf.fileUploadsActive = isBoolean(conf.fileUploadsActive) ? conf.fileUploadsActive : false;
return conf;
} |
JavaScript | load () {
// don't load if it's already loaded
if (!isUndefined(window.ICF) && ICF.isInit) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this.once('icf-ready', resolve);
this.once('icf-failed', reject);
this._loadAndInitSDK();
});
} | load () {
// don't load if it's already loaded
if (!isUndefined(window.ICF) && ICF.isInit) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this.once('icf-ready', resolve);
this.once('icf-failed', reject);
this._loadAndInitSDK();
});
} |
JavaScript | _loadAndInitSDK () {
const v = Conf.get('sdkVersion');
const d = document;
const s = 'script';
const id = 'inbenta-jssdk';
let js, ijs = d.getElementsByTagName(s)[0];
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = 'https://sdk.inbenta.chat/'+v+'/icf.sdk.js';
js.onload = this._initICF.bind(this);
ijs.parentNode.insertBefore(js, ijs);
} else {
this._initICF();
}
} | _loadAndInitSDK () {
const v = Conf.get('sdkVersion');
const d = document;
const s = 'script';
const id = 'inbenta-jssdk';
let js, ijs = d.getElementsByTagName(s)[0];
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = 'https://sdk.inbenta.chat/'+v+'/icf.sdk.js';
js.onload = this._initICF.bind(this);
ijs.parentNode.insertBefore(js, ijs);
} else {
this._initICF();
}
} |
JavaScript | _initICF () {
const initData = {
appId: Conf.get('appId'),
setCookieOnDomain: Conf.get('setCookieOnDomain'),
port: Conf.get('port') || defaultPort
};
if (Conf.get('region')) {
initData.region = Conf.get('region');
} else if (Conf.get('server')) {
initData.server = Conf.get('server');
}
ICF.init(initData)
.then(() => {
if (ICF.isInit) {
window.ICF = ICF;
this.emit('icf-ready');
}
})
.catch(() => {
this.emit('icf-failed');
});
} | _initICF () {
const initData = {
appId: Conf.get('appId'),
setCookieOnDomain: Conf.get('setCookieOnDomain'),
port: Conf.get('port') || defaultPort
};
if (Conf.get('region')) {
initData.region = Conf.get('region');
} else if (Conf.get('server')) {
initData.server = Conf.get('server');
}
ICF.init(initData)
.then(() => {
if (ICF.isInit) {
window.ICF = ICF;
this.emit('icf-ready');
}
})
.catch(() => {
this.emit('icf-failed');
});
} |
JavaScript | function client(srv, nsp, opts) {
if ("object" == typeof nsp) {
opts = nsp;
nsp = null;
}
let addr = srv.address();
if (!addr) addr = srv.listen().address();
const url = "ws://localhost:" + addr.port + (nsp || "");
return ioc(url, opts);
} | function client(srv, nsp, opts) {
if ("object" == typeof nsp) {
opts = nsp;
nsp = null;
}
let addr = srv.address();
if (!addr) addr = srv.listen().address();
const url = "ws://localhost:" + addr.port + (nsp || "");
return ioc(url, opts);
} |
JavaScript | function encode(latLon, precision) {
var lat = latLon[0],
lon = latLon[1],
hash = "",
hashVal = 0,
bits = 0,
even = 1,
latRange = { "min": -90, "max": 90 },
lonRange = { "min": -180, "max": 180 },
val, range, mid;
precision = Math.min(precision || 12, 22);
if (lat < latRange["min"] || lat > latRange["max"])
throw "Invalid latitude specified! (" + lat + ")";
if (lon < lonRange["min"] || lon > lonRange["max"])
throw "Invalid longitude specified! (" + lon + ")";
while (hash.length < precision) {
val = (even) ? lon : lat;
range = (even) ? lonRange : latRange;
mid = (range["min"] + range["max"]) / 2;
if (val > mid) {
hashVal = (hashVal << 1) + 1;
range["min"] = mid;
} else {
hashVal = (hashVal << 1) + 0;
range["max"] = mid;
}
even = !even;
if (bits < 4) {
bits++;
} else {
bits = 0;
hash += BASE32[hashVal].toString();
hashVal = 0;
}
}
return hash;
} | function encode(latLon, precision) {
var lat = latLon[0],
lon = latLon[1],
hash = "",
hashVal = 0,
bits = 0,
even = 1,
latRange = { "min": -90, "max": 90 },
lonRange = { "min": -180, "max": 180 },
val, range, mid;
precision = Math.min(precision || 12, 22);
if (lat < latRange["min"] || lat > latRange["max"])
throw "Invalid latitude specified! (" + lat + ")";
if (lon < lonRange["min"] || lon > lonRange["max"])
throw "Invalid longitude specified! (" + lon + ")";
while (hash.length < precision) {
val = (even) ? lon : lat;
range = (even) ? lonRange : latRange;
mid = (range["min"] + range["max"]) / 2;
if (val > mid) {
hashVal = (hashVal << 1) + 1;
range["min"] = mid;
} else {
hashVal = (hashVal << 1) + 0;
range["max"] = mid;
}
even = !even;
if (bits < 4) {
bits++;
} else {
bits = 0;
hash += BASE32[hashVal].toString();
hashVal = 0;
}
}
return hash;
} |
JavaScript | function decode(hash) {
var latRange = { "min": -90, "max": 90 },
lonRange = { "min": -180, "max": 180 },
even = 1,
lat, lon, decimal, mask, interval;
for (var i = 0; i < hash.length; i++) {
decimal = BASE32.indexOf(hash[i]);
for (var j = 0; j < 5; j++) {
interval = (even) ? lonRange : latRange;
mask = BITS[j];
halve_interval(interval, decimal, mask);
even = !even;
}
}
lat = (latRange["min"] + latRange["max"]) / 2;
lon = (lonRange["min"] + lonRange["max"]) / 2;
return [lat, lon];
} | function decode(hash) {
var latRange = { "min": -90, "max": 90 },
lonRange = { "min": -180, "max": 180 },
even = 1,
lat, lon, decimal, mask, interval;
for (var i = 0; i < hash.length; i++) {
decimal = BASE32.indexOf(hash[i]);
for (var j = 0; j < 5; j++) {
interval = (even) ? lonRange : latRange;
mask = BITS[j];
halve_interval(interval, decimal, mask);
even = !even;
}
}
lat = (latRange["min"] + latRange["max"]) / 2;
lon = (lonRange["min"] + lonRange["max"]) / 2;
return [lat, lon];
} |
JavaScript | function dist(lat1, lon1, lat2, lon2) {
var radius = 6371, // km
dlat = deg2rad(lat2 - lat1),
dlon = deg2rad(lon2 - lon1),
a, c;
a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dlon / 2) * Math.sin(dlon / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return radius * c;
} | function dist(lat1, lon1, lat2, lon2) {
var radius = 6371, // km
dlat = deg2rad(lat2 - lat1),
dlon = deg2rad(lon2 - lon1),
a, c;
a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dlon / 2) * Math.sin(dlon / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return radius * c;
} |
JavaScript | function distByHash(hash1, hash2) {
var loc1 = decode(hash1);
var loc2 = decode(hash2);
return dist(loc1[0], loc1[1], loc2[0], loc2[1]);
} | function distByHash(hash1, hash2) {
var loc1 = decode(hash1);
var loc2 = decode(hash2);
return dist(loc1[0], loc1[1], loc2[0], loc2[1]);
} |
JavaScript | function dimensions(hash) {
var length = hash.length,
parity = (length % 2) ? 1 : 0,
a = 5 * length - parity;
return {
"height" : deg2km(180 / Math.pow(2, a / 2)),
"width" : deg2km(180 / Math.pow(2, (a - 1) / 2))
};
} | function dimensions(hash) {
var length = hash.length,
parity = (length % 2) ? 1 : 0,
a = 5 * length - parity;
return {
"height" : deg2km(180 / Math.pow(2, a / 2)),
"width" : deg2km(180 / Math.pow(2, (a - 1) / 2))
};
} |
JavaScript | function neighbor(hash, dir) {
hash = hash.toLowerCase();
var lastChar = hash.charAt(hash.length - 1),
type = (hash.length % 2) ? "odd" : "even",
base = hash.substring(0, hash.length-1);
if (BORDERS[dir][type].indexOf(lastChar) != -1) {
if (base.length <= 0)
return "";
base = neighbor(base, dir);
}
return base + BASE32[NEIGHBORS[dir][type].indexOf(lastChar)];
} | function neighbor(hash, dir) {
hash = hash.toLowerCase();
var lastChar = hash.charAt(hash.length - 1),
type = (hash.length % 2) ? "odd" : "even",
base = hash.substring(0, hash.length-1);
if (BORDERS[dir][type].indexOf(lastChar) != -1) {
if (base.length <= 0)
return "";
base = neighbor(base, dir);
}
return base + BASE32[NEIGHBORS[dir][type].indexOf(lastChar)];
} |
JavaScript | function neighbors(hash) {
var neighbors = [];
neighbors.push(neighbor(hash, "north"));
neighbors.push(neighbor(hash, "south"));
neighbors.push(neighbor(hash, "east"));
neighbors.push(neighbor(hash, "west"));
neighbors.push(neighbor(neighbors[0], "east"));
neighbors.push(neighbor(neighbors[0], "west"));
neighbors.push(neighbor(neighbors[1], "east"));
neighbors.push(neighbor(neighbors[1], "west"));
return neighbors;
} | function neighbors(hash) {
var neighbors = [];
neighbors.push(neighbor(hash, "north"));
neighbors.push(neighbor(hash, "south"));
neighbors.push(neighbor(hash, "east"));
neighbors.push(neighbor(hash, "west"));
neighbors.push(neighbor(neighbors[0], "east"));
neighbors.push(neighbor(neighbors[0], "west"));
neighbors.push(neighbor(neighbors[1], "east"));
neighbors.push(neighbor(neighbors[1], "west"));
return neighbors;
} |
JavaScript | function validate_boat_params(req) {
return !(req.body === null || req.body === undefined || req.body.name === null ||
req.body.name === undefined || req.body.type === null || req.body.type ===
undefined || req.body.length === null || req.body.length === undefined ||
isNaN(req.body.length));
} | function validate_boat_params(req) {
return !(req.body === null || req.body === undefined || req.body.name === null ||
req.body.name === undefined || req.body.type === null || req.body.type ===
undefined || req.body.length === null || req.body.length === undefined ||
isNaN(req.body.length));
} |
JavaScript | function validate_all_provided_boat_params_valid(req, sub) {
var minimumParamsPresent = false;
if (req.body !== null && req.body !== undefined) {
if (req.body.name !== null && req.body.name !== undefined) {
minimumParamsPresent = true;
}
if (req.body.type !== null && req.body.type !== undefined) {
minimumParamsPresent = true;
}
if (req.body.length !== null && req.body.length !== undefined) {
//Invalidate flag if length is NaN
minimumParamsPresent = !isNaN(req.body.length);
}
if (req.body.owner !== null && req.body.owner !== undefined) {
minimumParamsPresent = req.body.owner === sub;
}
}
return minimumParamsPresent;
} | function validate_all_provided_boat_params_valid(req, sub) {
var minimumParamsPresent = false;
if (req.body !== null && req.body !== undefined) {
if (req.body.name !== null && req.body.name !== undefined) {
minimumParamsPresent = true;
}
if (req.body.type !== null && req.body.type !== undefined) {
minimumParamsPresent = true;
}
if (req.body.length !== null && req.body.length !== undefined) {
//Invalidate flag if length is NaN
minimumParamsPresent = !isNaN(req.body.length);
}
if (req.body.owner !== null && req.body.owner !== undefined) {
minimumParamsPresent = req.body.owner === sub;
}
}
return minimumParamsPresent;
} |
JavaScript | function put_boat(id, name, type, length, sub) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const modified_boat = {
"name": `${name}`,
"type": `${type}`,
"length": Number(length),
"owner": `${sub}`
};
return datastore.save({"key": key, "data": modified_boat}).then(() => key);
} | function put_boat(id, name, type, length, sub) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const modified_boat = {
"name": `${name}`,
"type": `${type}`,
"length": Number(length),
"owner": `${sub}`
};
return datastore.save({"key": key, "data": modified_boat}).then(() => key);
} |
JavaScript | function patch_boat(id, name, type, length, boat) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const modified_boat = {
"name": name !== null && name !== undefined ? `${name}` : boat.name,
"type": type !== null && type !== undefined ? `${type}` : boat.type,
"length": length !== null && length !== undefined ? Number(length) : boat.length,
"owner": boat.owner
};
return datastore.save({"key": key, "data": modified_boat}).then(() => key);
} | function patch_boat(id, name, type, length, boat) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const modified_boat = {
"name": name !== null && name !== undefined ? `${name}` : boat.name,
"type": type !== null && type !== undefined ? `${type}` : boat.type,
"length": length !== null && length !== undefined ? Number(length) : boat.length,
"owner": boat.owner
};
return datastore.save({"key": key, "data": modified_boat}).then(() => key);
} |
JavaScript | async function delete_boat(id) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const q = datastore.createQuery(LOADS).filter('current_boat', '=', id);
await datastore.runQuery(q).then(entities => {
for (var load of entities[0]) {
remove_load_from_boat(fromLoadDatastore((load)));
}
});
return datastore.delete(key);
} | async function delete_boat(id) {
const key = datastore.key([BOATS, parseInt(id, 10)]);
const q = datastore.createQuery(LOADS).filter('current_boat', '=', id);
await datastore.runQuery(q).then(entities => {
for (var load of entities[0]) {
remove_load_from_boat(fromLoadDatastore((load)));
}
});
return datastore.delete(key);
} |
JavaScript | async function fromBoatDatastore(item) {
if (item === null || item === undefined) return item;
item.id = item[Datastore.KEY].id;
item.self = `${BASE_URL}${BOATS}/${item.id}`;
let query = datastore.createQuery(LOADS).filter('current_boat', '=', item.id);
let results = await datastore.runQuery(query);
item.loads = [];
if (results !== undefined && results !== null && results[0] !== null && results[0] !==
undefined && results[0].length !== 0) {
for (let result of results[0]) {
let load = fromLoadDatastore(result);
item.loads.push({"id": load.id, "self": load.self});
}
}
return item;
} | async function fromBoatDatastore(item) {
if (item === null || item === undefined) return item;
item.id = item[Datastore.KEY].id;
item.self = `${BASE_URL}${BOATS}/${item.id}`;
let query = datastore.createQuery(LOADS).filter('current_boat', '=', item.id);
let results = await datastore.runQuery(query);
item.loads = [];
if (results !== undefined && results !== null && results[0] !== null && results[0] !==
undefined && results[0].length !== 0) {
for (let result of results[0]) {
let load = fromLoadDatastore(result);
item.loads.push({"id": load.id, "self": load.self});
}
}
return item;
} |
JavaScript | registerRegistrationEventListeners() {
Container.get(EVENT_DISPATCHER).on(USER_REGISTERED, async (data) => {
//log here
logger.info("User Registered", data);
});
} | registerRegistrationEventListeners() {
Container.get(EVENT_DISPATCHER).on(USER_REGISTERED, async (data) => {
//log here
logger.info("User Registered", data);
});
} |
JavaScript | registerLoginEventListeners() {
Container.get(EVENT_DISPATCHER).on(USER_LOGGED_IN, async (data) => {
//log here
logger.info("User logged in", data);
});
} | registerLoginEventListeners() {
Container.get(EVENT_DISPATCHER).on(USER_LOGGED_IN, async (data) => {
//log here
logger.info("User logged in", data);
});
} |
JavaScript | async allHotels(request, response) {
const hotel = await this.HotelService.GetAllHotels();
response.ok({ hotel });
} | async allHotels(request, response) {
const hotel = await this.HotelService.GetAllHotels();
response.ok({ hotel });
} |
JavaScript | function watchAndRestartConnection() {
if (!playerObject.socketCurrentlyConnected) {
// Clear last sent data to make sure we send it all again
playerObject.lastSentPlayerDataObject = {};
// Reconnect
connect();
}
setTimeout(watchAndRestartConnection, connectionCheckInterval);
} | function watchAndRestartConnection() {
if (!playerObject.socketCurrentlyConnected) {
// Clear last sent data to make sure we send it all again
playerObject.lastSentPlayerDataObject = {};
// Reconnect
connect();
}
setTimeout(watchAndRestartConnection, connectionCheckInterval);
} |
JavaScript | async function startGame({ phaserDebug }) {
phaserConfigObject.physics.arcade.debug = phaserDebug;
socketCommunications();
await waitForConnectionAndInitialPlayerPosition();
// Set last DOM updates before game starts.
document.getElementById('pre_load_info').hidden = true;
document.getElementsByTagName('body')[0].style.background = 'black';
touchInput();
playerObject.scrollingTextBox = new ScrollingTextBox();
// Start Phaser
phaserConfigObject.game = new Phaser.Game(phaserConfigObject);
// grab handle to canvas element
playerObject.domElements.canvas = document.getElementsByTagName('canvas')[0];
} | async function startGame({ phaserDebug }) {
phaserConfigObject.physics.arcade.debug = phaserDebug;
socketCommunications();
await waitForConnectionAndInitialPlayerPosition();
// Set last DOM updates before game starts.
document.getElementById('pre_load_info').hidden = true;
document.getElementsByTagName('body')[0].style.background = 'black';
touchInput();
playerObject.scrollingTextBox = new ScrollingTextBox();
// Start Phaser
phaserConfigObject.game = new Phaser.Game(phaserConfigObject);
// grab handle to canvas element
playerObject.domElements.canvas = document.getElementsByTagName('canvas')[0];
} |
JavaScript | function updateDomSettingsForGame() {
// Set viewport requirements for game, such as no scrolling
const metaTag = document.createElement('meta');
metaTag.name = 'viewport';
metaTag.content =
'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
document.getElementsByTagName('head')[0].appendChild(metaTag);
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
// Set up some initial values.
document.getElementById('canvas_overlay_elements').style.display = 'flex';
playerObject.domElements.chatInputDiv.style.display = 'none';
playerObject.domElements.chatInputDiv.style.display = 'none';
playerObject.domElements.Scrolling.hidden = true;
playerObject.domElements.chatInputCaret.innerHTML = '💬';
} | function updateDomSettingsForGame() {
// Set viewport requirements for game, such as no scrolling
const metaTag = document.createElement('meta');
metaTag.name = 'viewport';
metaTag.content =
'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';
document.getElementsByTagName('head')[0].appendChild(metaTag);
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
// Set up some initial values.
document.getElementById('canvas_overlay_elements').style.display = 'flex';
playerObject.domElements.chatInputDiv.style.display = 'none';
playerObject.domElements.chatInputDiv.style.display = 'none';
playerObject.domElements.Scrolling.hidden = true;
playerObject.domElements.chatInputCaret.innerHTML = '💬';
} |
JavaScript | get image() {
if (!this.download.target.path) {
// Old history downloads may not have a target path.
return "moz-icon://.unknown?size=32";
}
// When a download that was previously in progress finishes successfully, it
// means that the target file now exists and we can extract its specific
// icon, for example from a Windows executable. To ensure that the icon is
// reloaded, however, we must change the URI used by the XUL image element,
// for example by adding a query parameter. This only works if we add one of
// the parameters explicitly supported by the nsIMozIconURI interface.
return "moz-icon://" + this.download.target.path + "?size=32" +
(this.download.succeeded ? "&state=normal" : "");
} | get image() {
if (!this.download.target.path) {
// Old history downloads may not have a target path.
return "moz-icon://.unknown?size=32";
}
// When a download that was previously in progress finishes successfully, it
// means that the target file now exists and we can extract its specific
// icon, for example from a Windows executable. To ensure that the icon is
// reloaded, however, we must change the URI used by the XUL image element,
// for example by adding a query parameter. This only works if we add one of
// the parameters explicitly supported by the nsIMozIconURI interface.
return "moz-icon://" + this.download.target.path + "?size=32" +
(this.download.succeeded ? "&state=normal" : "");
} |
JavaScript | get displayName() {
if (!this.download.target.path) {
return this.download.source.url;
}
return OS.Path.basename(this.download.target.path);
} | get displayName() {
if (!this.download.target.path) {
return this.download.source.url;
}
return OS.Path.basename(this.download.target.path);
} |
JavaScript | get _progressElement() {
if (!this.__progressElement) {
// If the element is not available now, we will try again the next time.
this.__progressElement =
this.element.ownerDocument.getAnonymousElementByAttribute(
this.element, "anonid",
"progressmeter");
}
return this.__progressElement;
} | get _progressElement() {
if (!this.__progressElement) {
// If the element is not available now, we will try again the next time.
this.__progressElement =
this.element.ownerDocument.getAnonymousElementByAttribute(
this.element, "anonid",
"progressmeter");
}
return this.__progressElement;
} |
JavaScript | _updateState() {
this.element.setAttribute("displayName", this.displayName);
this.element.setAttribute("extendedDisplayName", this.extendedDisplayName);
this.element.setAttribute("extendedDisplayNameTip", this.extendedDisplayNameTip);
this.element.setAttribute("image", this.image);
this.element.setAttribute("state",
DownloadsCommon.stateOfDownload(this.download));
// Since state changed, reset the time left estimation.
this.lastEstimatedSecondsLeft = Infinity;
this._updateProgress();
} | _updateState() {
this.element.setAttribute("displayName", this.displayName);
this.element.setAttribute("extendedDisplayName", this.extendedDisplayName);
this.element.setAttribute("extendedDisplayNameTip", this.extendedDisplayNameTip);
this.element.setAttribute("image", this.image);
this.element.setAttribute("state",
DownloadsCommon.stateOfDownload(this.download));
// Since state changed, reset the time left estimation.
this.lastEstimatedSecondsLeft = Infinity;
this._updateProgress();
} |
JavaScript | _updateProgress() {
if (this.download.succeeded) {
// We only need to add or remove this attribute for succeeded downloads.
if (this.download.target.exists) {
this.element.setAttribute("exists", "true");
} else {
this.element.removeAttribute("exists");
}
}
// The progress bar is only displayed for in-progress downloads.
if (this.download.hasProgress) {
this.element.setAttribute("progressmode", "normal");
this.element.setAttribute("progress", this.download.progress);
} else {
this.element.setAttribute("progressmode", "undetermined");
}
// Dispatch the ValueChange event for accessibility, if possible.
if (this._progressElement) {
let event = this.element.ownerDocument.createEvent("Events");
event.initEvent("ValueChange", true, true);
this._progressElement.dispatchEvent(event);
}
let status = this.statusTextAndTip;
this.element.setAttribute("status", status.text);
this.element.setAttribute("statusTip", status.tip);
} | _updateProgress() {
if (this.download.succeeded) {
// We only need to add or remove this attribute for succeeded downloads.
if (this.download.target.exists) {
this.element.setAttribute("exists", "true");
} else {
this.element.removeAttribute("exists");
}
}
// The progress bar is only displayed for in-progress downloads.
if (this.download.hasProgress) {
this.element.setAttribute("progressmode", "normal");
this.element.setAttribute("progress", this.download.progress);
} else {
this.element.setAttribute("progressmode", "undetermined");
}
// Dispatch the ValueChange event for accessibility, if possible.
if (this._progressElement) {
let event = this.element.ownerDocument.createEvent("Events");
event.initEvent("ValueChange", true, true);
this._progressElement.dispatchEvent(event);
}
let status = this.statusTextAndTip;
this.element.setAttribute("status", status.text);
this.element.setAttribute("statusTip", status.tip);
} |
JavaScript | get rawStatusTextAndTip() {
const nsIDM = Ci.nsIDownloadManager;
let s = DownloadsCommon.strings;
let text = "";
let tip = "";
if (!this.download.stopped) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
// By default, extended status information including the individual
// download rate is displayed in the tooltip. The history view overrides
// the getter and displays the datails in the main area instead.
[text] = DownloadUtils.getDownloadStatusNoRate(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
let newEstimatedSecondsLeft;
[tip, newEstimatedSecondsLeft] = DownloadUtils.getDownloadStatus(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
this.lastEstimatedSecondsLeft = newEstimatedSecondsLeft;
} else if (this.download.canceled && this.download.hasPartialData) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
let transfer = DownloadUtils.getTransferTotal(this.download.currentBytes,
totalBytes);
// We use the same XUL label to display both the state and the amount
// transferred, for example "Paused - 1.1 MB".
text = s.statusSeparatorBeforeNumber(s.statePaused, transfer);
} else if (!this.download.succeeded && !this.download.canceled &&
!this.download.error) {
text = s.stateStarting;
} else {
let stateLabel;
if (this.download.succeeded) {
// For completed downloads, show the file size (e.g. "1.5 MB").
if (this.download.target.size !== undefined) {
let [size, unit] =
DownloadUtils.convertByteUnits(this.download.target.size);
stateLabel = s.sizeWithUnits(size, unit);
} else {
// History downloads may not have a size defined.
stateLabel = s.sizeUnknown;
}
} else if (this.download.canceled) {
stateLabel = s.stateCanceled;
} else if (this.download.error.becauseBlockedByParentalControls) {
stateLabel = s.stateBlockedParentalControls;
} else if (this.download.error.becauseBlockedByReputationCheck) {
stateLabel = s.stateDirty;
} else {
stateLabel = s.stateFailed;
}
let referrer = this.download.source.referrer || this.download.source.url;
let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer);
let date = new Date(this.download.endTime);
let [displayDate, fullDate] = DownloadUtils.getReadableDates(date);
let firstPart = s.statusSeparator(stateLabel, displayHost);
text = s.statusSeparator(firstPart, displayDate);
tip = s.statusSeparator(fullHost, fullDate);
}
return { text, tip: tip || text };
} | get rawStatusTextAndTip() {
const nsIDM = Ci.nsIDownloadManager;
let s = DownloadsCommon.strings;
let text = "";
let tip = "";
if (!this.download.stopped) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
// By default, extended status information including the individual
// download rate is displayed in the tooltip. The history view overrides
// the getter and displays the datails in the main area instead.
[text] = DownloadUtils.getDownloadStatusNoRate(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
let newEstimatedSecondsLeft;
[tip, newEstimatedSecondsLeft] = DownloadUtils.getDownloadStatus(
this.download.currentBytes,
totalBytes,
this.download.speed,
this.lastEstimatedSecondsLeft);
this.lastEstimatedSecondsLeft = newEstimatedSecondsLeft;
} else if (this.download.canceled && this.download.hasPartialData) {
let totalBytes = this.download.hasProgress ? this.download.totalBytes
: -1;
let transfer = DownloadUtils.getTransferTotal(this.download.currentBytes,
totalBytes);
// We use the same XUL label to display both the state and the amount
// transferred, for example "Paused - 1.1 MB".
text = s.statusSeparatorBeforeNumber(s.statePaused, transfer);
} else if (!this.download.succeeded && !this.download.canceled &&
!this.download.error) {
text = s.stateStarting;
} else {
let stateLabel;
if (this.download.succeeded) {
// For completed downloads, show the file size (e.g. "1.5 MB").
if (this.download.target.size !== undefined) {
let [size, unit] =
DownloadUtils.convertByteUnits(this.download.target.size);
stateLabel = s.sizeWithUnits(size, unit);
} else {
// History downloads may not have a size defined.
stateLabel = s.sizeUnknown;
}
} else if (this.download.canceled) {
stateLabel = s.stateCanceled;
} else if (this.download.error.becauseBlockedByParentalControls) {
stateLabel = s.stateBlockedParentalControls;
} else if (this.download.error.becauseBlockedByReputationCheck) {
stateLabel = s.stateDirty;
} else {
stateLabel = s.stateFailed;
}
let referrer = this.download.source.referrer || this.download.source.url;
let [displayHost, fullHost] = DownloadUtils.getURIHost(referrer);
let date = new Date(this.download.endTime);
let [displayDate, fullDate] = DownloadUtils.getReadableDates(date);
let firstPart = s.statusSeparator(stateLabel, displayHost);
text = s.statusSeparator(firstPart, displayDate);
tip = s.statusSeparator(fullHost, fullDate);
}
return { text, tip: tip || text };
} |
JavaScript | function removeNotificationOnEnd(notification, installs) {
let count = installs.length;
function maybeRemove(install) {
install.removeListener(this);
if (--count == 0) {
// Check that the notification is still showing
let current = PopupNotifications.getNotification(notification.id, notification.browser);
if (current === notification)
notification.remove();
}
}
for (let install of installs) {
install.addListener({
onDownloadCancelled: maybeRemove,
onDownloadFailed: maybeRemove,
onInstallFailed: maybeRemove,
onInstallEnded: maybeRemove
});
}
} | function removeNotificationOnEnd(notification, installs) {
let count = installs.length;
function maybeRemove(install) {
install.removeListener(this);
if (--count == 0) {
// Check that the notification is still showing
let current = PopupNotifications.getNotification(notification.id, notification.browser);
if (current === notification)
notification.remove();
}
}
for (let install of installs) {
install.addListener({
onDownloadCancelled: maybeRemove,
onDownloadFailed: maybeRemove,
onInstallFailed: maybeRemove,
onInstallEnded: maybeRemove
});
}
} |
JavaScript | registerIndicator(aBrowserWindow) {
if (!this._taskbarProgress) {
if (gMacTaskbarProgress) {
// On Mac OS X, we have to register the global indicator only once.
this._taskbarProgress = gMacTaskbarProgress;
// Free the XPCOM reference on shutdown, to prevent detecting a leak.
Services.obs.addObserver(() => {
this._taskbarProgress = null;
gMacTaskbarProgress = null;
}, "quit-application-granted", false);
} else if (gWinTaskbar) {
// On Windows, the indicator is currently hidden because we have no
// previous browser window, thus we should attach the indicator now.
this._attachIndicator(aBrowserWindow);
} else {
// The taskbar indicator is not available on this platform.
return;
}
}
// Ensure that the DownloadSummary object will be created asynchronously.
if (!this._summary) {
Downloads.getSummary(Downloads.ALL).then(summary => {
// In case the method is re-entered, we simply ignore redundant
// invocations of the callback, instead of keeping separate state.
if (this._summary) {
return;
}
this._summary = summary;
return this._summary.addView(this);
}).then(null, Cu.reportError);
}
} | registerIndicator(aBrowserWindow) {
if (!this._taskbarProgress) {
if (gMacTaskbarProgress) {
// On Mac OS X, we have to register the global indicator only once.
this._taskbarProgress = gMacTaskbarProgress;
// Free the XPCOM reference on shutdown, to prevent detecting a leak.
Services.obs.addObserver(() => {
this._taskbarProgress = null;
gMacTaskbarProgress = null;
}, "quit-application-granted", false);
} else if (gWinTaskbar) {
// On Windows, the indicator is currently hidden because we have no
// previous browser window, thus we should attach the indicator now.
this._attachIndicator(aBrowserWindow);
} else {
// The taskbar indicator is not available on this platform.
return;
}
}
// Ensure that the DownloadSummary object will be created asynchronously.
if (!this._summary) {
Downloads.getSummary(Downloads.ALL).then(summary => {
// In case the method is re-entered, we simply ignore redundant
// invocations of the callback, instead of keeping separate state.
if (this._summary) {
return;
}
this._summary = summary;
return this._summary.addView(this);
}).then(null, Cu.reportError);
}
} |
JavaScript | _attachIndicator(aWindow) {
// Activate the indicator on the specified window.
let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIXULWindow).docShell;
this._taskbarProgress = gWinTaskbar.getTaskbarProgress(docShell);
// If the DownloadSummary object has already been created, we should update
// the state of the new indicator, otherwise it will be updated as soon as
// the DownloadSummary view is registered.
if (this._summary) {
this.onSummaryChanged();
}
aWindow.addEventListener("unload", () => {
// Locate another browser window, excluding the one being closed.
let browserWindow = RecentWindow.getMostRecentBrowserWindow();
if (browserWindow) {
// Move the progress indicator to the other browser window.
this._attachIndicator(browserWindow);
} else {
// The last browser window has been closed. We remove the reference to
// the taskbar progress object so that the indicator will be registered
// again on the next browser window that is opened.
this._taskbarProgress = null;
}
}, false);
} | _attachIndicator(aWindow) {
// Activate the indicator on the specified window.
let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIXULWindow).docShell;
this._taskbarProgress = gWinTaskbar.getTaskbarProgress(docShell);
// If the DownloadSummary object has already been created, we should update
// the state of the new indicator, otherwise it will be updated as soon as
// the DownloadSummary view is registered.
if (this._summary) {
this.onSummaryChanged();
}
aWindow.addEventListener("unload", () => {
// Locate another browser window, excluding the one being closed.
let browserWindow = RecentWindow.getMostRecentBrowserWindow();
if (browserWindow) {
// Move the progress indicator to the other browser window.
this._attachIndicator(browserWindow);
} else {
// The last browser window has been closed. We remove the reference to
// the taskbar progress object so that the indicator will be registered
// again on the next browser window that is opened.
this._taskbarProgress = null;
}
}, false);
} |
JavaScript | set rotation(aVal) {
this._currentRotation = aVal % 360;
if (this._currentRotation < 0) {
this._currentRotation += 360;
}
return this._currentRotation;
} | set rotation(aVal) {
this._currentRotation = aVal % 360;
if (this._currentRotation < 0) {
this._currentRotation += 360;
}
return this._currentRotation;
} |
JavaScript | handleEnter(aIsPopupSelection) {
if (this.openedPopup) {
this.sendMessageToBrowser("FormAutoComplete:HandleEnter", {
selectedIndex: this.openedPopup.selectedIndex,
isPopupSelection: aIsPopupSelection,
});
}
} | handleEnter(aIsPopupSelection) {
if (this.openedPopup) {
this.sendMessageToBrowser("FormAutoComplete:HandleEnter", {
selectedIndex: this.openedPopup.selectedIndex,
isPopupSelection: aIsPopupSelection,
});
}
} |
JavaScript | sendMessageToBrowser(msgName, data) {
let browser = this.weakBrowser ? this.weakBrowser.get()
: null;
if (browser) {
browser.messageManager.sendAsyncMessage(msgName, data);
}
} | sendMessageToBrowser(msgName, data) {
let browser = this.weakBrowser ? this.weakBrowser.get()
: null;
if (browser) {
browser.messageManager.sendAsyncMessage(msgName, data);
}
} |
JavaScript | get logins() {
try {
let logins = Services.logins.findLogins({},
this.principal.originNoSuffix, "", "");
return logins;
} catch (e) {
if (!e.message.includes(MASTER_PASSWORD_MESSAGE)) {
Cu.reportError("AboutPermissions: " + e);
}
return [];
}
} | get logins() {
try {
let logins = Services.logins.findLogins({},
this.principal.originNoSuffix, "", "");
return logins;
} catch (e) {
if (!e.message.includes(MASTER_PASSWORD_MESSAGE)) {
Cu.reportError("AboutPermissions: " + e);
}
return [];
}
} |
JavaScript | get cookies() {
let cookies = [];
let enumerator = Services.cookies.enumerator;
while (enumerator.hasMoreElements()) {
let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
if (cookie.host.hasRootDomain(
AboutPermissions.domainFromHost(this.principal.URI.host))) {
cookies.push(cookie);
}
}
return cookies;
} | get cookies() {
let cookies = [];
let enumerator = Services.cookies.enumerator;
while (enumerator.hasMoreElements()) {
let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
if (cookie.host.hasRootDomain(
AboutPermissions.domainFromHost(this.principal.URI.host))) {
cookies.push(cookie);
}
}
return cookies;
} |
JavaScript | function InsertionPoint(aItemId, aIndex, aOrientation, aIsTag,
aDropNearItemId) {
this.itemId = aItemId;
this._index = aIndex;
this.orientation = aOrientation;
this.isTag = aIsTag;
this.dropNearItemId = aDropNearItemId;
} | function InsertionPoint(aItemId, aIndex, aOrientation, aIsTag,
aDropNearItemId) {
this.itemId = aItemId;
this._index = aIndex;
this.orientation = aOrientation;
this.isTag = aIsTag;
this.dropNearItemId = aDropNearItemId;
} |
JavaScript | _hasRemovableSelection() {
var ranges = this._view.removableSelectionRanges;
if (!ranges.length)
return false;
var root = this._view.result.root;
for (var j = 0; j < ranges.length; j++) {
var nodes = ranges[j];
for (var i = 0; i < nodes.length; ++i) {
// Disallow removing the view's root node
if (nodes[i] == root)
return false;
if (!PlacesUIUtils.canUserRemove(nodes[i]))
return false;
}
}
return true;
} | _hasRemovableSelection() {
var ranges = this._view.removableSelectionRanges;
if (!ranges.length)
return false;
var root = this._view.result.root;
for (var j = 0; j < ranges.length; j++) {
var nodes = ranges[j];
for (var i = 0; i < nodes.length; ++i) {
// Disallow removing the view's root node
if (nodes[i] == root)
return false;
if (!PlacesUIUtils.canUserRemove(nodes[i]))
return false;
}
}
return true;
} |
JavaScript | function findNodes(node) {
var foundOne = false;
// See if node matches an ID we wanted; add to results.
// For simple folder queries, check both itemId and the concrete
// item id.
var index = ids.indexOf(node.itemId);
if (index == -1 &&
node.type == Components.interfaces.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
index = ids.indexOf(PlacesUtils.asQuery(node).folderItemId); //xxx Bug 556739 3.7a5pre
}
if (index != -1) {
nodes.push(node);
foundOne = true;
ids.splice(index, 1);
}
if (ids.length == 0 || !PlacesUtils.nodeIsContainer(node) ||
nodesURIChecked.indexOf(node.uri) != -1)
return foundOne;
nodesURIChecked.push(node.uri);
PlacesUtils.asContainer(node); // xxx Bug 556739 3.7a6pre
// Remember the beginning state so that we can re-close
// this node if we don't find any additional results here.
var previousOpenness = node.containerOpen;
node.containerOpen = true;
for (var child = 0; child < node.childCount && ids.length > 0;
child++) {
var childNode = node.getChild(child);
var found = findNodes(childNode);
if (!foundOne)
foundOne = found;
}
// If we didn't find any additional matches in this node's
// subtree, revert the node to its previous openness.
if (foundOne)
nodesToOpen.unshift(node);
node.containerOpen = previousOpenness;
return foundOne;
} // findNodes | function findNodes(node) {
var foundOne = false;
// See if node matches an ID we wanted; add to results.
// For simple folder queries, check both itemId and the concrete
// item id.
var index = ids.indexOf(node.itemId);
if (index == -1 &&
node.type == Components.interfaces.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
index = ids.indexOf(PlacesUtils.asQuery(node).folderItemId); //xxx Bug 556739 3.7a5pre
}
if (index != -1) {
nodes.push(node);
foundOne = true;
ids.splice(index, 1);
}
if (ids.length == 0 || !PlacesUtils.nodeIsContainer(node) ||
nodesURIChecked.indexOf(node.uri) != -1)
return foundOne;
nodesURIChecked.push(node.uri);
PlacesUtils.asContainer(node); // xxx Bug 556739 3.7a6pre
// Remember the beginning state so that we can re-close
// this node if we don't find any additional results here.
var previousOpenness = node.containerOpen;
node.containerOpen = true;
for (var child = 0; child < node.childCount && ids.length > 0;
child++) {
var childNode = node.getChild(child);
var found = findNodes(childNode);
if (!foundOne)
foundOne = found;
}
// If we didn't find any additional matches in this node's
// subtree, revert the node to its previous openness.
if (foundOne)
nodesToOpen.unshift(node);
node.containerOpen = previousOpenness;
return foundOne;
} // findNodes |
JavaScript | function findNodes(node) {
var foundOne = false;
// See if node matches an ID we wanted; add to results.
// For simple folder queries, check both itemId and the concrete
// item id.
var index = ids.indexOf(node.itemId);
if (index == -1 &&
node.type == Components.interfaces.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
index = ids.indexOf(PlacesUtils.asQuery(node).folderItemId); // xxx Bug 556739 3.7a5pre
}
if (index != -1) {
nodes.push(node);
foundOne = true;
ids.splice(index, 1);
}
if (ids.length == 0 || !PlacesUtils.nodeIsContainer(node) ||
nodesURIChecked.indexOf(node.uri) != -1)
return foundOne;
nodesURIChecked.push(node.uri);
PlacesUtils.asContainer(node); // xxx Bug 556739 3.7a6pre
// Remember the beginning state so that we can re-close
// this node if we don't find any additional results here.
var previousOpenness = node.containerOpen;
node.containerOpen = true;
for (var child = 0; child < node.childCount && ids.length > 0;
child++) {
var childNode = node.getChild(child);
if (PlacesUtils.nodeIsQuery(childNode))
continue;
var found = findNodes(childNode);
if (!foundOne)
foundOne = found;
}
// If we didn't find any additional matches in this node's
// subtree, revert the node to its previous openness.
if (foundOne)
nodesToOpen.unshift(node);
node.containerOpen = previousOpenness;
return foundOne;
} // findNodes | function findNodes(node) {
var foundOne = false;
// See if node matches an ID we wanted; add to results.
// For simple folder queries, check both itemId and the concrete
// item id.
var index = ids.indexOf(node.itemId);
if (index == -1 &&
node.type == Components.interfaces.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
index = ids.indexOf(PlacesUtils.asQuery(node).folderItemId); // xxx Bug 556739 3.7a5pre
}
if (index != -1) {
nodes.push(node);
foundOne = true;
ids.splice(index, 1);
}
if (ids.length == 0 || !PlacesUtils.nodeIsContainer(node) ||
nodesURIChecked.indexOf(node.uri) != -1)
return foundOne;
nodesURIChecked.push(node.uri);
PlacesUtils.asContainer(node); // xxx Bug 556739 3.7a6pre
// Remember the beginning state so that we can re-close
// this node if we don't find any additional results here.
var previousOpenness = node.containerOpen;
node.containerOpen = true;
for (var child = 0; child < node.childCount && ids.length > 0;
child++) {
var childNode = node.getChild(child);
if (PlacesUtils.nodeIsQuery(childNode))
continue;
var found = findNodes(childNode);
if (!foundOne)
foundOne = found;
}
// If we didn't find any additional matches in this node's
// subtree, revert the node to its previous openness.
if (foundOne)
nodesToOpen.unshift(node);
node.containerOpen = previousOpenness;
return foundOne;
} // findNodes |
JavaScript | function isContainedBy(node, parent) {
var cursor = node.parent;
while (cursor) {
if (cursor == parent)
return true;
cursor = cursor.parent;
}
return false;
} | function isContainedBy(node, parent) {
var cursor = node.parent;
while (cursor) {
if (cursor == parent)
return true;
cursor = cursor.parent;
}
return false;
} |
JavaScript | function snapRectAtScale(r, scale) {
let x = Math.floor(r.x * scale);
let y = Math.floor(r.y * scale);
let width = Math.ceil((r.x + r.width) * scale) - x;
let height = Math.ceil((r.y + r.height) * scale) - y;
r.x = x / scale;
r.y = y / scale;
r.width = width / scale;
r.height = height / scale;
} | function snapRectAtScale(r, scale) {
let x = Math.floor(r.x * scale);
let y = Math.floor(r.y * scale);
let width = Math.ceil((r.x + r.width) * scale) - x;
let height = Math.ceil((r.y + r.height) * scale) - y;
r.x = x / scale;
r.y = y / scale;
r.width = width / scale;
r.height = height / scale;
} |
JavaScript | function PreviewController(win, tab) {
this.win = win;
this.tab = tab;
this.linkedBrowser = tab.linkedBrowser;
this.preview = this.win.createTabPreview(this);
this.tab.addEventListener("TabAttrModified", this, false);
XPCOMUtils.defineLazyGetter(this, "canvasPreview", function () {
let canvas = PageThumbs.createCanvas();
canvas.mozOpaque = true;
return canvas;
});
} | function PreviewController(win, tab) {
this.win = win;
this.tab = tab;
this.linkedBrowser = tab.linkedBrowser;
this.preview = this.win.createTabPreview(this);
this.tab.addEventListener("TabAttrModified", this, false);
XPCOMUtils.defineLazyGetter(this, "canvasPreview", function () {
let canvas = PageThumbs.createCanvas();
canvas.mozOpaque = true;
return canvas;
});
} |
JavaScript | function TabWindow(win) {
this.win = win;
this.tabbrowser = win.gBrowser;
this.previews = new Map();
for (let i = 0; i < this.tabEvents.length; i++) {
this.tabbrowser.tabContainer.addEventListener(this.tabEvents[i], this, false);
}
for (let i = 0; i < this.winEvents.length; i++) {
this.win.addEventListener(this.winEvents[i], this, false);
}
this.tabbrowser.addTabsProgressListener(this);
AeroPeek.windows.push(this);
let tabs = this.tabbrowser.tabs;
for (let i = 0; i < tabs.length; i++) {
this.newTab(tabs[i]);
}
this.updateTabOrdering();
AeroPeek.checkPreviewCount();
} | function TabWindow(win) {
this.win = win;
this.tabbrowser = win.gBrowser;
this.previews = new Map();
for (let i = 0; i < this.tabEvents.length; i++) {
this.tabbrowser.tabContainer.addEventListener(this.tabEvents[i], this, false);
}
for (let i = 0; i < this.winEvents.length; i++) {
this.win.addEventListener(this.winEvents[i], this, false);
}
this.tabbrowser.addTabsProgressListener(this);
AeroPeek.windows.push(this);
let tabs = this.tabbrowser.tabs;
for (let i = 0; i < tabs.length; i++) {
this.newTab(tabs[i]);
}
this.updateTabOrdering();
AeroPeek.checkPreviewCount();
} |
JavaScript | update(reason = "") {
// Update immediately if we're visible.
if (!document.hidden) {
// Ignore updates where reason=links-changed as those signal that the
// provider's set of links changed. We don't want to update visible pages
// in that case, it is ok to wait until the user opens the next tab.
if (reason != "links-changed" && gGrid.ready) {
gGrid.refresh();
}
return;
}
// Bail out if we scheduled before.
if (this._scheduleUpdateTimeout) {
return;
}
this._scheduleUpdateTimeout = setTimeout(() => {
// Refresh if the grid is ready.
if (gGrid.ready) {
gGrid.refresh();
}
this._scheduleUpdateTimeout = null;
}, SCHEDULE_UPDATE_TIMEOUT_MS);
} | update(reason = "") {
// Update immediately if we're visible.
if (!document.hidden) {
// Ignore updates where reason=links-changed as those signal that the
// provider's set of links changed. We don't want to update visible pages
// in that case, it is ok to wait until the user opens the next tab.
if (reason != "links-changed" && gGrid.ready) {
gGrid.refresh();
}
return;
}
// Bail out if we scheduled before.
if (this._scheduleUpdateTimeout) {
return;
}
this._scheduleUpdateTimeout = setTimeout(() => {
// Refresh if the grid is ready.
if (gGrid.ready) {
gGrid.refresh();
}
this._scheduleUpdateTimeout = null;
}, SCHEDULE_UPDATE_TIMEOUT_MS);
} |
JavaScript | get uniqueCurrentPages() {
let uniquePages = {};
let URIs = [];
gBrowser.visibleTabs.forEach(function(tab) {
let spec = tab.linkedBrowser.currentURI.spec;
if (!tab.pinned && !(spec in uniquePages)) {
uniquePages[spec] = null;
URIs.push(tab.linkedBrowser.currentURI);
}
});
return URIs;
} | get uniqueCurrentPages() {
let uniquePages = {};
let URIs = [];
gBrowser.visibleTabs.forEach(function(tab) {
let spec = tab.linkedBrowser.currentURI.spec;
if (!tab.pinned && !(spec in uniquePages)) {
uniquePages[spec] = null;
URIs.push(tab.linkedBrowser.currentURI);
}
});
return URIs;
} |
JavaScript | function HistoryMenu(aPopupShowingEvent) {
// Workaround for Bug 610187. The sidebar does not include all the Places
// views definitions, and we don't need them there.
// Defining the prototype inheritance in the prototype itself would cause
// browser.js to halt on "PlacesMenu is not defined" error.
this.__proto__.__proto__ = PlacesMenu.prototype;
XPCOMUtils.defineLazyServiceGetter(this, "_ss",
"@mozilla.org/browser/sessionstore;1",
"nsISessionStore");
PlacesMenu.call(this, aPopupShowingEvent,
"place:sort=4&maxResults=15");
} | function HistoryMenu(aPopupShowingEvent) {
// Workaround for Bug 610187. The sidebar does not include all the Places
// views definitions, and we don't need them there.
// Defining the prototype inheritance in the prototype itself would cause
// browser.js to halt on "PlacesMenu is not defined" error.
this.__proto__.__proto__ = PlacesMenu.prototype;
XPCOMUtils.defineLazyServiceGetter(this, "_ss",
"@mozilla.org/browser/sessionstore;1",
"nsISessionStore");
PlacesMenu.call(this, aPopupShowingEvent,
"place:sort=4&maxResults=15");
} |
JavaScript | get defaultSearchEngine() {
let defaultEngine = Services.search.defaultEngine;
let submission = defaultEngine.getSubmission("_searchTerms_", null, "homepage");
return Object.freeze({
name: defaultEngine.name,
searchURL: submission.uri.spec,
postDataString: submission.postDataString
});
} | get defaultSearchEngine() {
let defaultEngine = Services.search.defaultEngine;
let submission = defaultEngine.getSubmission("_searchTerms_", null, "homepage");
return Object.freeze({
name: defaultEngine.name,
searchURL: submission.uri.spec,
postDataString: submission.postDataString
});
} |
JavaScript | _getFolderCopyTransaction(aData, aContainer, aIndex) {
function getChildItemsTransactions(aRoot) {
let transactions = [];
let index = aIndex;
for (let i = 0; i < aRoot.childCount; ++i) {
let child = aRoot.getChild(i);
// Temporary hacks until we switch to PlacesTransactions.jsm.
let isLivemark =
PlacesUtils.annotations.itemHasAnnotation(child.itemId,
PlacesUtils.LMANNO_FEEDURI);
let [node] = PlacesUtils.unwrapNodes(
PlacesUtils.wrapNode(child, PlacesUtils.TYPE_X_MOZ_PLACE, isLivemark),
PlacesUtils.TYPE_X_MOZ_PLACE
);
// Make sure that items are given the correct index, this will be
// passed by the transaction manager to the backend for the insertion.
// Insertion behaves differently for DEFAULT_INDEX (append).
if (aIndex != PlacesUtils.bookmarks.DEFAULT_INDEX) {
index = i;
}
if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER) {
if (node.livemark && node.annos) {
transactions.push(
PlacesUIUtils._getLivemarkCopyTransaction(node, aContainer, index)
);
}
else {
transactions.push(
PlacesUIUtils._getFolderCopyTransaction(node, aContainer, index)
);
}
}
else if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR) {
transactions.push(new PlacesCreateSeparatorTransaction(-1, index));
}
else if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE) {
transactions.push(
PlacesUIUtils._getURIItemCopyTransaction(node, -1, index)
);
}
else {
throw new Error("Unexpected item under a bookmarks folder");
}
}
return transactions;
}
if (aContainer == PlacesUtils.tagsFolderId) { // Copying into a tag folder.
let transactions = [];
if (!aData.livemark && aData.type == PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER) {
let {root} = PlacesUtils.getFolderContents(aData.id, false, false);
let urls = PlacesUtils.getURLsForContainerNode(root);
root.containerOpen = false;
for (let { uri } of urls) {
transactions.push(
new PlacesTagURITransaction(NetUtil.newURI(uri), [aData.title])
);
}
}
return new PlacesAggregatedTransaction("addTags", transactions);
}
if (aData.livemark && aData.annos) { // Copying a livemark.
return this._getLivemarkCopyTransaction(aData, aContainer, aIndex);
}
let {root} = PlacesUtils.getFolderContents(aData.id, false, false);
let transactions = getChildItemsTransactions(root);
root.containerOpen = false;
if (aData.dateAdded) {
transactions.push(
new PlacesEditItemDateAddedTransaction(null, aData.dateAdded)
);
}
if (aData.lastModified) {
transactions.push(
new PlacesEditItemLastModifiedTransaction(null, aData.lastModified)
);
}
let annos = [];
if (aData.annos) {
annos = aData.annos.filter(function(aAnno) {
return this._copyableAnnotations.indexOf(aAnno.name) != -1;
}, this);
}
return new PlacesCreateFolderTransaction(aData.title, aContainer, aIndex,
annos, transactions);
} | _getFolderCopyTransaction(aData, aContainer, aIndex) {
function getChildItemsTransactions(aRoot) {
let transactions = [];
let index = aIndex;
for (let i = 0; i < aRoot.childCount; ++i) {
let child = aRoot.getChild(i);
// Temporary hacks until we switch to PlacesTransactions.jsm.
let isLivemark =
PlacesUtils.annotations.itemHasAnnotation(child.itemId,
PlacesUtils.LMANNO_FEEDURI);
let [node] = PlacesUtils.unwrapNodes(
PlacesUtils.wrapNode(child, PlacesUtils.TYPE_X_MOZ_PLACE, isLivemark),
PlacesUtils.TYPE_X_MOZ_PLACE
);
// Make sure that items are given the correct index, this will be
// passed by the transaction manager to the backend for the insertion.
// Insertion behaves differently for DEFAULT_INDEX (append).
if (aIndex != PlacesUtils.bookmarks.DEFAULT_INDEX) {
index = i;
}
if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER) {
if (node.livemark && node.annos) {
transactions.push(
PlacesUIUtils._getLivemarkCopyTransaction(node, aContainer, index)
);
}
else {
transactions.push(
PlacesUIUtils._getFolderCopyTransaction(node, aContainer, index)
);
}
}
else if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR) {
transactions.push(new PlacesCreateSeparatorTransaction(-1, index));
}
else if (node.type == PlacesUtils.TYPE_X_MOZ_PLACE) {
transactions.push(
PlacesUIUtils._getURIItemCopyTransaction(node, -1, index)
);
}
else {
throw new Error("Unexpected item under a bookmarks folder");
}
}
return transactions;
}
if (aContainer == PlacesUtils.tagsFolderId) { // Copying into a tag folder.
let transactions = [];
if (!aData.livemark && aData.type == PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER) {
let {root} = PlacesUtils.getFolderContents(aData.id, false, false);
let urls = PlacesUtils.getURLsForContainerNode(root);
root.containerOpen = false;
for (let { uri } of urls) {
transactions.push(
new PlacesTagURITransaction(NetUtil.newURI(uri), [aData.title])
);
}
}
return new PlacesAggregatedTransaction("addTags", transactions);
}
if (aData.livemark && aData.annos) { // Copying a livemark.
return this._getLivemarkCopyTransaction(aData, aContainer, aIndex);
}
let {root} = PlacesUtils.getFolderContents(aData.id, false, false);
let transactions = getChildItemsTransactions(root);
root.containerOpen = false;
if (aData.dateAdded) {
transactions.push(
new PlacesEditItemDateAddedTransaction(null, aData.dateAdded)
);
}
if (aData.lastModified) {
transactions.push(
new PlacesEditItemLastModifiedTransaction(null, aData.lastModified)
);
}
let annos = [];
if (aData.annos) {
annos = aData.annos.filter(function(aAnno) {
return this._copyableAnnotations.indexOf(aAnno.name) != -1;
}, this);
}
return new PlacesCreateFolderTransaction(aData.title, aContainer, aIndex,
annos, transactions);
} |
JavaScript | get restoreOnDemand() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restoreOnDemand", definition);
return value;
}
const PREF = "browser.sessionstore.restore_on_demand";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} | get restoreOnDemand() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restoreOnDemand", definition);
return value;
}
const PREF = "browser.sessionstore.restore_on_demand";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} |
JavaScript | get restorePinnedTabsOnDemand() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restorePinnedTabsOnDemand", definition);
return value;
}
const PREF = "browser.sessionstore.restore_pinned_tabs_on_demand";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} | get restorePinnedTabsOnDemand() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restorePinnedTabsOnDemand", definition);
return value;
}
const PREF = "browser.sessionstore.restore_pinned_tabs_on_demand";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} |
JavaScript | get restoreHiddenTabs() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restoreHiddenTabs", definition);
return value;
}
const PREF = "browser.sessionstore.restore_hidden_tabs";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} | get restoreHiddenTabs() {
let updateValue = () => {
let value = Services.prefs.getBoolPref(PREF);
let definition = {value: value, configurable: true};
Object.defineProperty(this, "restoreHiddenTabs", definition);
return value;
}
const PREF = "browser.sessionstore.restore_hidden_tabs";
Services.prefs.addObserver(PREF, updateValue, false);
return updateValue();
} |
JavaScript | get panel()
{
// If the downloads panel overlay hasn't loaded yet, just return null
// without resetting this.panel.
let downloadsPanel = document.getElementById("downloadsPanel");
if (!downloadsPanel)
return null;
delete this.panel;
return this.panel = downloadsPanel;
} | get panel()
{
// If the downloads panel overlay hasn't loaded yet, just return null
// without resetting this.panel.
let downloadsPanel = document.getElementById("downloadsPanel");
if (!downloadsPanel)
return null;
delete this.panel;
return this.panel = downloadsPanel;
} |
JavaScript | get isPanelShowing()
{
return this._state == this.kStateWaitingData ||
this._state == this.kStateWaitingAnchor ||
this._state == this.kStateShown;
} | get isPanelShowing()
{
return this._state == this.kStateWaitingData ||
this._state == this.kStateWaitingAnchor ||
this._state == this.kStateShown;
} |
JavaScript | set keyFocusing(aValue)
{
if (aValue) {
this.panel.setAttribute("keyfocus", "true");
this.panel.addEventListener("mousemove", this);
} else {
this.panel.removeAttribute("keyfocus");
this.panel.removeEventListener("mousemove", this);
}
return aValue;
} | set keyFocusing(aValue)
{
if (aValue) {
this.panel.setAttribute("keyfocus", "true");
this.panel.addEventListener("mousemove", this);
} else {
this.panel.removeAttribute("keyfocus");
this.panel.removeEventListener("mousemove", this);
}
return aValue;
} |
JavaScript | onDownloadAdded(download, aNewest) {
DownloadsCommon.log("A new download data item was added - aNewest =",
aNewest);
if (aNewest) {
this._downloads.unshift(download);
} else {
this._downloads.push(download);
}
let itemsNowOverflow = this._downloads.length > this.kItemCountLimit;
if (aNewest || !itemsNowOverflow) {
// The newly added item is visible in the panel and we must add the
// corresponding element. This is either because it is the first item, or
// because it was added at the bottom but the list still doesn't overflow.
this._addViewItem(download, aNewest);
}
if (aNewest && itemsNowOverflow) {
// If the list overflows, remove the last item from the panel to make room
// for the new one that we just added at the top.
this._removeViewItem(this._downloads[this.kItemCountLimit]);
}
// For better performance during batch loads, don't update the count for
// every item, because the interface won't be visible until load finishes.
if (!this.loading) {
this._itemCountChanged();
}
} | onDownloadAdded(download, aNewest) {
DownloadsCommon.log("A new download data item was added - aNewest =",
aNewest);
if (aNewest) {
this._downloads.unshift(download);
} else {
this._downloads.push(download);
}
let itemsNowOverflow = this._downloads.length > this.kItemCountLimit;
if (aNewest || !itemsNowOverflow) {
// The newly added item is visible in the panel and we must add the
// corresponding element. This is either because it is the first item, or
// because it was added at the bottom but the list still doesn't overflow.
this._addViewItem(download, aNewest);
}
if (aNewest && itemsNowOverflow) {
// If the list overflows, remove the last item from the panel to make room
// for the new one that we just added at the top.
this._removeViewItem(this._downloads[this.kItemCountLimit]);
}
// For better performance during batch loads, don't update the count for
// every item, because the interface won't be visible until load finishes.
if (!this.loading) {
this._itemCountChanged();
}
} |
JavaScript | onDownloadRemoved(download) {
DownloadsCommon.log("A download data item was removed.");
let itemIndex = this._downloads.indexOf(download);
this._downloads.splice(itemIndex, 1);
if (itemIndex < this.kItemCountLimit) {
// The item to remove is visible in the panel.
this._removeViewItem(download);
if (this._downloads.length >= this.kItemCountLimit) {
// Reinsert the next item into the panel.
this._addViewItem(this._downloads[this.kItemCountLimit - 1], false);
}
}
this._itemCountChanged();
} | onDownloadRemoved(download) {
DownloadsCommon.log("A download data item was removed.");
let itemIndex = this._downloads.indexOf(download);
this._downloads.splice(itemIndex, 1);
if (itemIndex < this.kItemCountLimit) {
// The item to remove is visible in the panel.
this._removeViewItem(download);
if (this._downloads.length >= this.kItemCountLimit) {
// Reinsert the next item into the panel.
this._addViewItem(this._downloads[this.kItemCountLimit - 1], false);
}
}
this._itemCountChanged();
} |
JavaScript | _addViewItem(download, aNewest)
{
DownloadsCommon.log("Adding a new DownloadsViewItem to the downloads list.",
"aNewest =", aNewest);
let element = document.createElement("richlistitem");
let viewItem = new DownloadsViewItem(download, element);
this._visibleViewItems.set(download, viewItem);
let viewItemController = new DownloadsViewItemController(download);
this._controllersForElements.set(element, viewItemController);
if (aNewest) {
this.richListBox.insertBefore(element, this.richListBox.firstChild);
} else {
this.richListBox.appendChild(element);
}
} | _addViewItem(download, aNewest)
{
DownloadsCommon.log("Adding a new DownloadsViewItem to the downloads list.",
"aNewest =", aNewest);
let element = document.createElement("richlistitem");
let viewItem = new DownloadsViewItem(download, element);
this._visibleViewItems.set(download, viewItem);
let viewItemController = new DownloadsViewItemController(download);
this._controllersForElements.set(element, viewItemController);
if (aNewest) {
this.richListBox.insertBefore(element, this.richListBox.firstChild);
} else {
this.richListBox.appendChild(element);
}
} |
JavaScript | _removeViewItem(download) {
DownloadsCommon.log("Removing a DownloadsViewItem from the downloads list.");
let element = this._visibleViewItems.get(download).element;
let previousSelectedIndex = this.richListBox.selectedIndex;
this.richListBox.removeChild(element);
if (previousSelectedIndex != -1) {
this.richListBox.selectedIndex = Math.min(previousSelectedIndex,
this.richListBox.itemCount - 1);
}
this._visibleViewItems.delete(download);
this._controllersForElements.delete(element);
} | _removeViewItem(download) {
DownloadsCommon.log("Removing a DownloadsViewItem from the downloads list.");
let element = this._visibleViewItems.get(download).element;
let previousSelectedIndex = this.richListBox.selectedIndex;
this.richListBox.removeChild(element);
if (previousSelectedIndex != -1) {
this.richListBox.selectedIndex = Math.min(previousSelectedIndex,
this.richListBox.itemCount - 1);
}
this._visibleViewItems.delete(download);
this._controllersForElements.delete(element);
} |
JavaScript | function DownloadsViewItem(download, aElement) {
this.download = download;
this.element = aElement;
this.element._shell = this;
this.element.setAttribute("type", "download");
this.element.classList.add("download-state");
this._updateState();
} | function DownloadsViewItem(download, aElement) {
this.download = download;
this.element = aElement;
this.element._shell = this;
this.element.setAttribute("type", "download");
this.element.classList.add("download-state");
this._updateState();
} |
JavaScript | set active(aActive)
{
if (aActive == this._active || !this._summaryNode) {
return this._active;
}
if (aActive) {
DownloadsCommon.getSummary(window, DownloadsView.kItemCountLimit)
.refreshView(this);
} else {
DownloadsFooter.showingSummary = false;
}
return this._active = aActive;
} | set active(aActive)
{
if (aActive == this._active || !this._summaryNode) {
return this._active;
}
if (aActive) {
DownloadsCommon.getSummary(window, DownloadsView.kItemCountLimit)
.refreshView(this);
} else {
DownloadsFooter.showingSummary = false;
}
return this._active = aActive;
} |
JavaScript | set showingProgress(aShowingProgress)
{
if (aShowingProgress) {
this._summaryNode.setAttribute("inprogress", "true");
} else {
this._summaryNode.removeAttribute("inprogress");
}
// If progress isn't being shown, then we simply do not show the summary.
return DownloadsFooter.showingSummary = aShowingProgress;
} | set showingProgress(aShowingProgress)
{
if (aShowingProgress) {
this._summaryNode.setAttribute("inprogress", "true");
} else {
this._summaryNode.removeAttribute("inprogress");
}
// If progress isn't being shown, then we simply do not show the summary.
return DownloadsFooter.showingSummary = aShowingProgress;
} |
JavaScript | set percentComplete(aValue)
{
if (this._progressNode) {
this._progressNode.setAttribute("value", aValue);
}
return aValue;
} | set percentComplete(aValue)
{
if (this._progressNode) {
this._progressNode.setAttribute("value", aValue);
}
return aValue;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.