_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q45600
|
contains
|
train
|
function contains(arr, v) {
var nIndex,
nLen = arr.length;
for (nIndex = 0; nIndex < nLen; nIndex++) {
if (arr[nIndex][1] === v) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q45601
|
unique
|
train
|
function unique(oldArray) {
var nIndex,
nLen = oldArray.length,
aArr = [];
for (nIndex = 0; nIndex < nLen; nIndex++) {
if (!contains(aArr, oldArray[nIndex][1])) {
aArr.push(oldArray[nIndex]);
}
}
return aArr;
}
|
javascript
|
{
"resource": ""
}
|
q45602
|
_biDimensionalArrayToObject
|
train
|
function _biDimensionalArrayToObject(aArr) {
var obj = {},
nIndex,
nLen = aArr.length,
oItem;
for (nIndex = 0; nIndex < nLen; nIndex++) {
oItem = aArr[nIndex];
obj[oItem[0]] = oItem[1];
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q45603
|
_getKeys
|
train
|
function _getKeys(json, aKeys) {
var aKey,
sKey,
oItem;
for (sKey in json) {
if (json.hasOwnProperty(sKey)) {
oItem = json[sKey];
if (_isObject(oItem) || _isArray(oItem)) {
aKeys = aKeys.concat(unique(_getKeys(oItem, aKeys)));
}
if (isNaN(Number(sKey))) {
if (!contains(aKeys, sKey)) {
_nCode += 1;
aKey = [];
aKey.push(_getSpecialKey(_numberToKey(_nCode)), sKey);
aKeys.push(aKey);
}
}
}
}
return aKeys;
}
|
javascript
|
{
"resource": ""
}
|
q45604
|
_compressArray
|
train
|
function _compressArray(json, aKeys) {
var nIndex,
nLenKeys;
for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) {
json[nIndex] = JSONC.compress(json[nIndex], aKeys);
}
}
|
javascript
|
{
"resource": ""
}
|
q45605
|
_compressOther
|
train
|
function _compressOther(json, aKeys) {
var oKeys,
aKey,
str,
nLenKeys,
nIndex,
obj;
aKeys = _getKeys(json, aKeys);
aKeys = unique(aKeys);
oKeys = _biDimensionalArrayToObject(aKeys);
str = JSON.stringify(json);
nLenKeys = aKeys.length;
for (nIndex = 0; nIndex < nLenKeys; nIndex++) {
aKey = aKeys[nIndex];
str = str.replace(new RegExp(escapeRegExp('"' + aKey[1] + '"'), 'g'), '"' + aKey[0] + '"');
}
obj = JSON.parse(str);
obj._ = oKeys;
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q45606
|
_decompressArray
|
train
|
function _decompressArray(json) {
var nIndex, nLenKeys;
for (nIndex = 0, nLenKeys = json.length; nIndex < nLenKeys; nIndex++) {
json[nIndex] = JSONC.decompress(json[nIndex]);
}
}
|
javascript
|
{
"resource": ""
}
|
q45607
|
_decompressOther
|
train
|
function _decompressOther(jsonCopy) {
var oKeys, str, sKey;
oKeys = JSON.parse(JSON.stringify(jsonCopy._));
delete jsonCopy._;
str = JSON.stringify(jsonCopy);
for (sKey in oKeys) {
if (oKeys.hasOwnProperty(sKey)) {
str = str.replace(new RegExp('"' + sKey + '"', 'g'), '"' + oKeys[sKey] + '"');
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q45608
|
attr
|
train
|
function attr(loc, reference, attrName, value) {
if (plainAttributes.indexOf(attrName) != -1) {
return sourceNode(loc, [reference, '.', attrName, ' = ', value, ';']);
} else {
return sourceNode(loc, [reference, '.setAttribute(', esc(attrName), ', ', value, ');']);
}
}
|
javascript
|
{
"resource": ""
}
|
q45609
|
transformArray
|
train
|
function transformArray(array, keys, i, options) {
if (options) {
var t = {__index__: i};
t[options.value] = array[i];
if (options.key) {
t[options.key] = i;
}
return t;
} else {
return array[i];
}
}
|
javascript
|
{
"resource": ""
}
|
q45610
|
unsafe
|
train
|
function unsafe(root, nodes, html) {
var node, j, i = nodes.length, element = document.createElement('div');
element.innerHTML = html;
while (i --> 0)
nodes[i].parentNode.removeChild(nodes.pop());
for (i = j = element.childNodes.length - 1; j >= 0; j--)
nodes.push(element.childNodes[j]);
++i;
if (root.nodeType == 8)
if (root.parentNode)
while (i --> 0)
root.parentNode.insertBefore(nodes[i], root);
else
throw "Can not insert child view into parent node. You need append your view first and then update.";
else
while (i --> 0)
root.appendChild(nodes[i]);
}
|
javascript
|
{
"resource": ""
}
|
q45611
|
task
|
train
|
function task(callback) {
// spawn phantomas process
var child = phantomas(url, options, function(err, data, results) {
callback(
null, // pass null even in case of an error to continue async.series processing (issue #380)
[err, results]
);
});
child.on('progress', function(progress, inc) {
if (bar) {
bar.tick(inc);
}
});
// pipe --verbose messages to stderr
child.stderr.pipe(process.stderr);
}
|
javascript
|
{
"resource": ""
}
|
q45612
|
train
|
function(node, callback, depth) {
if (this.isSkipped(node)) {
return;
}
var childNode,
childNodes = node && node.childNodes || [];
depth = (depth || 1);
for (var n = 0, len = childNodes.length; n < len; n++) {
childNode = childNodes[n];
// callback can return false to stop recursive
if (callback(childNode, depth) !== false) {
this.walk(childNode, callback, depth + 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45613
|
spyGlobalVar
|
train
|
function spyGlobalVar(varName, callback) {
phantomas.log('spy: attaching to %s global variable', varName);
window.__defineSetter__(varName, function(val) {
phantomas.log('spy: %s global variable has been defined', varName);
spiedGlobals[varName] = val;
callback(val);
});
window.__defineGetter__(varName, function() {
return spiedGlobals[varName] || undefined;
});
}
|
javascript
|
{
"resource": ""
}
|
q45614
|
pushToStack
|
train
|
function pushToStack(type, entry, check) {
// no entry of given type
if (typeof stack[type] === 'undefined') {
stack[type] = entry;
}
// apply check function
else if (check(stack[type], entry) === true) {
stack[type] = entry;
}
}
|
javascript
|
{
"resource": ""
}
|
q45615
|
train
|
function(name, value) {
if (typeof metricsAvgStorage[name] === 'undefined') {
metricsAvgStorage[name] = [];
}
metricsAvgStorage[name].push(value);
this.setMetric(name, getAverage(metricsAvgStorage[name]));
}
|
javascript
|
{
"resource": ""
}
|
|
q45616
|
createHAR
|
train
|
function createHAR(page, creator) {
// @see: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HAR/Overview.html
var address = page.address;
var title = page.title;
var startTime = page.startTime;
var resources = page.resources;
var entries = [];
resources.forEach(function(resource) {
var request = resource.request;
var response = resource.response;
if (!request || !response) {
return;
}
// Exclude data URIs from the HAR because they aren't
// included in the spec.
if (request.url.substring(0, 5).toLowerCase() === 'data:') {
return;
}
entries.push({
cache: {},
pageref: address,
request: {
// Accurate bodySize blocked on https://github.com/ariya/phantomjs/pull/11484
bodySize: -1,
cookies: [],
headers: request.headers,
// Accurate headersSize blocked on https://github.com/ariya/phantomjs/pull/11484
headersSize: -1,
httpVersion: 'HTTP/1.1',
method: request.method,
queryString: [],
url: request.url,
},
response: {
bodySize: response.bodySize,
cookies: [],
headers: response.headers,
headersSize: response.headersSize,
httpVersion: 'HTTP/1.1',
redirectURL: '',
status: response.status,
statusText: response.statusText,
content: {
mimeType: response.contentType || '',
size: response.bodySize, // uncompressed
text: ''
}
},
startedDateTime: resource.startTime && resource.startTime.toISOString(),
time: response.timeToLastByte,
timings: {
blocked: 0,
dns: -1,
connect: -1,
send: 0,
wait: 0, // response.timeToFirstByte || 0,
receive: 0, // response.receiveTime,
ssl: -1
}
});
});
return {
log: {
creator: creator,
entries: entries,
pages: [
{
startedDateTime: startTime.toISOString(),
id: address,
title: title,
pageTimings: {
onLoad: page.onLoad || -1,
onContentLoad: page.onContentLoad || -1
}
}
],
version: '1.2',
}
};
}
|
javascript
|
{
"resource": ""
}
|
q45617
|
lowerCaseHeaders
|
train
|
function lowerCaseHeaders(headers) {
var res = {};
Object.keys(headers).forEach(headerName => {
res[headerName.toLowerCase()] = headers[headerName];
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
q45618
|
parseEntryUrl
|
train
|
function parseEntryUrl(entry) {
const parseUrl = require('url').parse;
var parsed;
// asset type
entry.type = 'other';
if (entry.url.indexOf('data:') !== 0) {
// @see http://nodejs.org/api/url.html#url_url
parsed = parseUrl(entry.url) || {};
entry.protocol = parsed.protocol.replace(':', '');
entry.domain = parsed.hostname;
entry.query = parsed.query;
if (entry.protocol === 'https') {
entry.isSSL = true;
}
}
else {
// base64 encoded data
entry.domain = false;
entry.protocol = false;
entry.isBase64 = true;
}
return entry;
}
|
javascript
|
{
"resource": ""
}
|
q45619
|
addContentType
|
train
|
function addContentType(headerValue, entry) {
var value = headerValue.split(';').shift().toLowerCase();
entry.contentType = value;
switch(value) {
case 'text/html':
entry.type = 'html';
entry.isHTML = true;
break;
case 'text/xml':
entry.type = 'xml';
entry.isXML = true;
break;
case 'text/css':
entry.type = 'css';
entry.isCSS = true;
break;
case 'application/x-javascript':
case 'application/javascript':
case 'text/javascript':
entry.type = 'js';
entry.isJS = true;
break;
case 'application/json':
entry.type = 'json';
entry.isJSON = true;
break;
case 'image/png':
case 'image/jpeg':
case 'image/gif':
case 'image/svg+xml':
case 'image/webp':
entry.type = 'image';
entry.isImage = true;
if (value === 'image/svg+xml') {
entry.isSVG = true;
}
break;
case 'video/webm':
entry.type = 'video';
entry.isVideo = true;
break;
// @see http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts
case 'application/font-wof':
case 'application/font-woff':
case 'application/vnd.ms-fontobject':
case 'application/x-font-opentype':
case 'application/x-font-truetype':
case 'application/x-font-ttf':
case 'application/x-font-woff':
case 'font/opentype':
case 'font/ttf':
case 'font/woff':
entry.type = 'webfont';
entry.isWebFont = true;
if (/ttf|truetype$/.test(value)) {
entry.isTTF = true;
}
break;
case 'application/octet-stream':
var ext = (entry.url || '').split('.').pop();
switch(ext) {
// @see http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts#comment-8077637
case 'otf':
entry.type = 'webfont';
entry.isWebFont = true;
break;
}
break;
case 'image/x-icon':
case 'image/vnd.microsoft.icon':
entry.type = 'favicon';
entry.isFavicon = true;
break;
default:
debug('Unknown content type found: ' + value + ' for <' + entry.url + '>');
}
return entry;
}
|
javascript
|
{
"resource": ""
}
|
q45620
|
hasConfigSetting
|
train
|
function hasConfigSetting(pkg, setting) {
return pkg.config && pkg.config[appName] && pkg.config[appName][setting];
}
|
javascript
|
{
"resource": ""
}
|
q45621
|
getConfigSetting
|
train
|
function getConfigSetting(pkg, setting, ensureArray) {
if (!hasConfigSetting(pkg, setting)) {
return null;
}
const value = pkg.config[appName][setting];
if (ensureArray && !Array.isArray(value)) {
return [value];
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q45622
|
getConfigSettings
|
train
|
function getConfigSettings(packageJsonFile) {
// Locate and read package.json
const pkg = JSON.parse(fs.readFileSync(packageJsonFile));
return {
searchDir:
getConfigSetting(pkg, 'searchDir', true) || getDefaultValue('searchDir'),
outputFile:
getConfigSetting(pkg, 'outputFile') || getDefaultValue('outputFile'),
pattern: getConfigSetting(pkg, 'pattern') || getDefaultValue('pattern'),
};
}
|
javascript
|
{
"resource": ""
}
|
q45623
|
train
|
function (template, templateUrl) {
var deferred = $q.defer();
if (template) {
deferred.resolve(template);
} else if (templateUrl) {
$templateRequest(templateUrl, true)
.then(function (template) {
deferred.resolve(template);
}, function (error) {
deferred.reject(error);
});
} else {
deferred.reject("No template or templateUrl has been specified.");
}
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q45624
|
train
|
function(ev) {
if (!ev) { ev = w.event; }
if (!ev) { ev = { name: "load" }; }
if(impl.onloadfired) {
return this;
}
impl.fireEvent("page_ready", ev);
impl.onloadfired = true;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45625
|
train
|
function() {
var res, k, urls, url, startTime, data;
function trimTiming(time, st) {
// strip from microseconds to milliseconds only
var timeMs = Math.round(time ? time : 0),
startTimeMs = Math.round(st ? st : 0);
timeMs = (timeMs === 0 ? 0 : (timeMs - startTimeMs));
return timeMs ? timeMs : "";
}
if(BOOMR.t_start) {
// How long does it take Boomerang to load up and execute (fb to lb)?
BOOMR.plugins.RT.startTimer("boomerang", BOOMR.t_start);
BOOMR.plugins.RT.endTimer("boomerang", BOOMR.t_end); // t_end === null defaults to current time
// How long did it take from page request to boomerang fb?
BOOMR.plugins.RT.endTimer("boomr_fb", BOOMR.t_start);
if(BOOMR.t_lstart) {
// when did the boomerang loader start loading boomerang on the page?
BOOMR.plugins.RT.endTimer("boomr_ld", BOOMR.t_lstart);
// What was the network latency for boomerang (request to first byte)?
BOOMR.plugins.RT.setTimer("boomr_lat", BOOMR.t_start - BOOMR.t_lstart);
}
}
// use window and not w because we want the inner iframe
try
{
if (window.performance && window.performance.getEntriesByName) {
urls = { "rt.bmr": BOOMR.url };
for(url in urls) {
if(urls.hasOwnProperty(url) && urls[url]) {
res = window.performance.getEntriesByName(urls[url]);
if(!res || res.length === 0) {
continue;
}
res = res[0];
startTime = trimTiming(res.startTime, 0);
data = [
startTime,
trimTiming(res.responseEnd, startTime),
trimTiming(res.responseStart, startTime),
trimTiming(res.requestStart, startTime),
trimTiming(res.connectEnd, startTime),
trimTiming(res.secureConnectionStart, startTime),
trimTiming(res.connectStart, startTime),
trimTiming(res.domainLookupEnd, startTime),
trimTiming(res.domainLookupStart, startTime),
trimTiming(res.redirectEnd, startTime),
trimTiming(res.redirectStart, startTime)
].join(",").replace(/,+$/, "");
BOOMR.addVar(url, data);
impl.addedVars.push(url);
}
}
}
}
catch(e)
{
BOOMR.addError(e, "rt.getBoomerangTimings");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45626
|
train
|
function() {
var ti, p, source;
if(this.navigationStart) {
return;
}
// Get start time from WebTiming API see:
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html
// http://blogs.msdn.com/b/ie/archive/2010/06/28/measuring-web-page-performance.aspx
// http://blog.chromium.org/2010/07/do-you-know-how-slow-your-web-page-is.html
p = w.performance || w.msPerformance || w.webkitPerformance || w.mozPerformance;
if(p && p.navigation) {
this.navigationType = p.navigation.type;
}
if(p && p.timing) {
ti = p.timing;
}
else if(w.chrome && w.chrome.csi && w.chrome.csi().startE) {
// Older versions of chrome also have a timing API that's sort of documented here:
// http://ecmanaut.blogspot.com/2010/06/google-bom-feature-ms-since-pageload.html
// source here:
// http://src.chromium.org/viewvc/chrome/trunk/src/chrome/renderer/loadtimes_extension_bindings.cc?view=markup
ti = {
navigationStart: w.chrome.csi().startE
};
source = "csi";
}
else if(w.gtbExternal && w.gtbExternal.startE()) {
// The Google Toolbar exposes navigation start time similar to old versions of chrome
// This would work for any browser that has the google toolbar installed
ti = {
navigationStart: w.gtbExternal.startE()
};
source = "gtb";
}
if(ti) {
// Always use navigationStart since it falls back to fetchStart (not with redirects)
// If not set, we leave t_start alone so that timers that depend
// on it don't get sent back. Never use requestStart since if
// the first request fails and the browser retries, it will contain
// the value for the new request.
BOOMR.addVar("rt.start", source || "navigation");
this.navigationStart = ti.navigationStart || ti.fetchStart || undefined;
this.responseStart = ti.responseStart || undefined;
// bug in Firefox 7 & 8 https://bugzilla.mozilla.org/show_bug.cgi?id=691547
if(navigator.userAgent.match(/Firefox\/[78]\./)) {
this.navigationStart = ti.unloadEventStart || ti.fetchStart || undefined;
}
}
else {
BOOMR.warn("This browser doesn't support the WebTiming API", "rt");
}
return;
}
|
javascript
|
{
"resource": ""
}
|
|
q45627
|
train
|
function(t_now, data) {
var t_done = t_now;
// xhr beacon with detailed timing information
if (data && data.timing && data.timing.loadEventEnd) {
t_done = data.timing.loadEventEnd;
}
// Boomerang loaded late and...
else if (BOOMR.loadedLate) {
// We have navigation timing,
if(w.performance && w.performance.timing) {
// and boomerang loaded after onload fired
if(w.performance.timing.loadEventStart && w.performance.timing.loadEventStart < BOOMR.t_end) {
t_done = w.performance.timing.loadEventStart;
}
}
// We don't have navigation timing,
else {
// So we'll just use the time when boomerang was added to the page
// Assuming that this means boomerang was added in onload
t_done = BOOMR.t_lstart || BOOMR.t_start || t_now;
}
}
return t_done;
}
|
javascript
|
{
"resource": ""
}
|
|
q45628
|
train
|
function(ename, data) {
var t_start;
if(ename==="xhr") {
if(data && data.name && impl.timers[data.name]) {
// For xhr timers, t_start is stored in impl.timers.xhr_{page group name}
// and xhr.pg is set to {page group name}
t_start = impl.timers[data.name].start;
}
else if(data && data.timing && data.timing.requestStart) {
// For automatically instrumented xhr timers, we have detailed timing information
t_start = data.timing.requestStart;
}
BOOMR.addVar("rt.start", "manual");
}
else if(impl.navigationStart) {
t_start = impl.navigationStart;
}
else if(impl.t_start && impl.navigationType !== 2) {
t_start = impl.t_start; // 2 is TYPE_BACK_FORWARD but the constant may not be defined across browsers
BOOMR.addVar("rt.start", "cookie"); // if the user hit the back button, referrer will match, and cookie will match
} // but will have time of previous page start, so t_done will be wrong
else if(impl.cached_t_start) {
t_start = impl.cached_t_start;
}
else {
BOOMR.addVar("rt.start", "none");
t_start = undefined; // force all timers to NaN state
}
BOOMR.debug("Got start time: " + t_start, "rt");
impl.cached_t_start = t_start;
return t_start;
}
|
javascript
|
{
"resource": ""
}
|
|
q45629
|
intersection
|
train
|
function intersection(sets) {
let source = sets[0];
let rest = sets.slice(1);
let keys = Object.keys(source);
let keysLength = keys.length;
let restLength = rest.length;
let result = [];
for (let keyIndex = 0; keyIndex < keysLength; keyIndex++) {
let key = keys[keyIndex];
let matched = true;
for (let restIndex = 0; restIndex < restLength; restIndex++) {
if (!rest[restIndex].hasOwnProperty(key)) {
matched = false;
break;
}
}
if (matched) {
result.push(source[key]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q45630
|
publicAnimationContext
|
train
|
function publicAnimationContext(rt, versions) {
let c = {};
addPublicVersion(c, 'new', versions[0]);
if (versions[1]) {
addPublicVersion(c, 'old', versions[1]);
}
c.older = versions.slice(2).map((v) => {
let context = {};
addPublicVersion(context, null, v);
return context;
});
// Animations are allowed to look each other up.
c.lookup = function(name) {
return rt.transitionMap.lookup(name);
};
return c;
}
|
javascript
|
{
"resource": ""
}
|
q45631
|
train
|
function( index, callback ) {
var scope = this;
var shot = scope.shots[ index|0 ];
if( ! shot ) {
throw new Error(
"Shot number " + index + " not found"
);
return;
}
return shot;
}
|
javascript
|
{
"resource": ""
}
|
|
q45632
|
train
|
function( shot, callback ) {
var scope = this;
if( typeof( shot ) === "number" ) {
shot = scope.getShot( shot );
}
if( shot.location ) {
FS.readFile( shot.location, function( err, data ) {
callback( err, data );
});
} else if( ! shot.data ) {
callback(
new Error( "Shot not valid" )
);
} else {
callback( null, shot.data );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45633
|
train
|
function( shot, callback ) {
var scope = this;
scope.getShotBuffer( shot, function( err, data ) {
if( err ) {
callback( err );
return;
}
var base64 = scope.getBase64FromBuffer( data );
callback( null, base64 );
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45634
|
train
|
function( shotBuffer ) {
var scope = this;
var image = "data:image/"
+ scope.opts.output
+ ";base64,"
+ new Buffer( shotBuffer ).toString( "base64" );
return image;
}
|
javascript
|
{
"resource": ""
}
|
|
q45635
|
train
|
function( callback ) {
var scope = this;
if( ! scope.shots.length ) {
callback && callback( new Error( "Camera has no last shot" ) );
}
scope.getBase64( scope.shots.length - 1, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q45636
|
train
|
function(code, callback) {
if (typeof code == 'function') {
callback = code;
this.promises.push(function onGenericStatusCode(done, utils) {
done(null, callback(this.scraper.getStatusCode(), utils));
});
} else {
this.promises.push(function onStatusCode(done, utils) {
if (code === this.scraper.getStatusCode()) {
done(null, callback(utils));
} else {
done(null, utils.lastReturn);
}
});
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45637
|
train
|
function(scrapeFn, callback) {
var stackTrace = new Error().stack;
var extraArguments = Array.prototype.slice.call(arguments, 2);
callback = callback || function(result) {
return result;
};
this.promises.push(function scrape(done, utils) {
this.scraper.scrape(scrapeFn, function(err, result) {
if (err) {
done(err, undefined);
} else {
done(null, callback(result, utils));
}
}, extraArguments, stackTrace);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45638
|
train
|
function(time, callback) {
callback = callback || function() {};
this.promises.push(function delay(done, utils) {
setTimeout(function() {
done(null, callback(utils));
}, time);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45639
|
train
|
function(callback) {
this.promises.push(function then(done, utils) {
done(null, callback(utils.lastReturn, utils));
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45640
|
train
|
function(callback) {
this.promises.push(function async(done, utils) {
callback(utils.lastReturn, done, utils);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45641
|
train
|
function(error) {
var that = this,
param = this.chainParameter,
stopPointer = {},
utils = {
stop: null,
url: this.scraper.url,
scraper: this,
params: param,
lastReturn: undefined
},
keep = true;
this.chainParameter = null;
if (error) {
this.errorCallback(error, utils);
this.doneCallback(utils);
return;
}
async.eachSeries(this.promises, function dispatcher(fn, callback) {
var done = function(err, lastReturn) {
utils.lastReturn = lastReturn;
if (err === stopPointer) {
keep = false;
callback(err);
} else if (err) {
callback(err);
} else if (keep) {
callback();
}
};
utils.stop = function() {
done(stopPointer, null);
};
try {
fn.call(that, done, utils);
} catch (err) {
done(err, null);
}
}, function(err) {
utils.stop = null;
if (err && err !== stopPointer) {
that.errorCallback(err, utils);
}
that.doneCallback(utils.lastReturn, utils);
that.scraper.close();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45642
|
train
|
function() {
var instance = this.scraper.clone(),
promise = new ScraperPromise(instance);
promise._setPromises(this.promises);
promise.done(this.doneCallback);
promise.catch(this.errorCallback);
return promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q45643
|
train
|
function(path) {
var callback;
if (typeof path === 'function') {
callback = path;
}
this.promises.push({
callback: callback ? function(url) {
return callback(url);
} : Router.pathMatcher(path),
scraper: null,
rqMethod: null
});
return this.get();
}
|
javascript
|
{
"resource": ""
}
|
|
q45644
|
train
|
function(url, callback) {
var that = this,
atLeastOne = false,
stopFlag = {},
lastReturn;
callback = callback || function() {};
async.eachSeries(this.promises, function(promiseObj, done) {
var matcher = promiseObj.callback,
scraper,
reqMethod = promiseObj.rqMethod;
var result = matcher(url);
if (!!result) {
scraper = promiseObj.scraper.clone();
atLeastOne = true;
scraper._setChainParameter(result);
scraper.done(function(lr, utils) {
lastReturn = lr;
done(that.firstMatchStop ? stopFlag : undefined);
});
reqMethod(scraper, url);
} else {
done();
}
}, function() {
if (!atLeastOne) {
that.otherwiseFn(url);
}
callback(atLeastOne, lastReturn);
});
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45645
|
train
|
function() {
/**
* The real PhantomJS instance.
*
* @type {?}
* @private
*/
this.instance = null;
/**
* The PhantomJS instance is being created.
*
* @type {!boolean}
* @private
*/
this.creating = false;
/**
* PhantomJS flags.
*
* @type {!string}
* @private
*/
this.flags = '';
/**
* PhantomJS options.
*
* @type {!Object}
* @private
*/
this.options = {
onStdout: function() {},
onStderr: function() {}
};
/**
* List of functions waiting to be called after the PhantomJS
* instance is created.
*
* @type {!Array.<!function(?)>}
* @private
*/
this.waiting = [];
this._createInstance();
}
|
javascript
|
{
"resource": ""
}
|
|
q45646
|
train
|
function(callback) {
if (this.instance) {
this.instance.createPage(function(page) {
callback(page);
});
} else {
var that = this;
this._createInstance(function() {
that.createPage(callback);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45647
|
train
|
function(callback) {
if (this.creating && callback) {
this.waiting.push(callback);
} else {
var that = this;
this.creating = true;
phantom.create(this.flags, this.options, function(ph) {
that.instance = ph;
that.creating = false;
that.waiting.forEach(function(callback) {
callback(ph);
});
that.waiting = [];
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45648
|
sendAll
|
train
|
function sendAll(requests, fnName, concurrency, callback) {
if (typeof concurrency === 'function') {
callback = concurrency;
concurrency = 1;
}
var q = queue(concurrency);
requests.forEach(function(req) {
q.defer(function(next) {
if (!req) return next();
req.on('complete', function(response) {
next(null, response);
}).send();
});
});
q.awaitAll(function(err, responses) {
if (err) return callback(err);
var errors = [];
var data = [];
var unprocessed = [];
responses.forEach(function(response) {
if (!response) response = { error: null, data: null };
errors.push(response.error);
data.push(response.data);
if (!response.data) return unprocessed.push(null);
var newParams = {
RequestItems: response.data.UnprocessedItems || response.data.UnprocessedKeys
};
if (newParams.RequestItems && !Object.keys(newParams.RequestItems).length)
return unprocessed.push(null);
unprocessed.push(newParams.RequestItems ? newParams : null);
});
unprocessed = unprocessed.map(function(params) {
if (params) return client[fnName].bind(client)(params);
else return null;
});
var unprocessedCount = unprocessed.filter(function(req) { return !!req; }).length;
if (unprocessedCount) unprocessed.sendAll = sendAll.bind(null, unprocessed, fnName);
var errorCount = errors.filter(function(err) { return !!err; }).length;
callback(
errorCount ? errors : null,
data,
unprocessedCount ? unprocessed : null
);
});
}
|
javascript
|
{
"resource": ""
}
|
q45649
|
Stringifier
|
train
|
function Stringifier() {
var stringifier = new stream.Transform({ highWaterMark: 100 });
stringifier._writableState.objectMode = true;
stringifier._readableState.objectMode = false;
stringifier._transform = function(record, enc, callback) {
var str = Dyno.serialize(record);
this.push(str + '\n');
setImmediate(callback);
};
return stringifier;
}
|
javascript
|
{
"resource": ""
}
|
q45650
|
Parser
|
train
|
function Parser() {
var parser = new stream.Transform({ highWaterMark: 100 });
parser._writableState.objectMode = false;
parser._readableState.objectMode = true;
var firstline = true;
parser._transform = function(record, enc, callback) {
if (!record || record.length === 0) return;
if (firstline) {
firstline = false;
var parsed = Dyno.deserialize(record);
if (!Object.keys(parsed).every(function(key) {
return !!parsed[key];
})) return this.push(JSON.parse(record.toString()));
}
record = Dyno.deserialize(record);
this.push(record);
setImmediate(callback);
};
return parser;
}
|
javascript
|
{
"resource": ""
}
|
q45651
|
cleanDescription
|
train
|
function cleanDescription(desc) {
var deleteAttributes = [
'CreationDateTime',
'IndexSizeBytes',
'IndexStatus',
'ItemCount',
'NumberOfDecreasesToday',
'TableSizeBytes',
'TableStatus',
'LastDecreaseDateTime',
'LastIncreaseDateTime'
];
return JSON.stringify(desc.Table, function(key, value) {
if (deleteAttributes.indexOf(key) !== -1) {
return undefined;
}
return value;
});
}
|
javascript
|
{
"resource": ""
}
|
q45652
|
Aggregator
|
train
|
function Aggregator(withTable) {
var firstline = !!withTable;
var aggregator = new stream.Transform({ objectMode: true, highWaterMark: 100 });
aggregator.records = [];
aggregator._transform = function(record, enc, callback) {
if (!record) return;
if (firstline) {
firstline = false;
this.push(record);
} else if (aggregator.records.length === 25) {
this.push(aggregator.records);
aggregator.records = [record];
} else {
aggregator.records.push(record);
}
callback();
};
aggregator._flush = function(callback) {
if (aggregator.records.length) this.push(aggregator.records);
callback();
};
return aggregator;
}
|
javascript
|
{
"resource": ""
}
|
q45653
|
rpcDialogShift
|
train
|
function rpcDialogShift() {
if (rpcDialogQueue.length === 0) {
$dialogRpc.dialog('close');
return;
}
rpcDialogPending = true;
const {daemon, cmd, params, callback} = rpcDialogQueue.shift();
const paramText = JSON.stringify(JSON.parse(JSON.stringify(params).replace(/{"explicitDouble":([0-9.]+)}/g, '$1')), null, ' ');
$('#rpc-command').html(cmd + ' ' + paramText);
$('#rpc-message').html('');
$dialogRpc.dialog('open');
$('#rpc-progress').show();
ipcRpc.send('rpc', [daemon, cmd, params], (err, res) => {
$('#rpc-progress').hide();
if (err) {
$dialogRpc.parent().children().children('.ui-dialog-titlebar-close').show();
$('#rpc-message').html('<span style="color: red; font-weight: bold;">' + (err.faultString ? err.faultString : JSON.stringify(err)) + '</span>');
} else if (res && res.faultCode) {
$dialogRpc.parent().children().children('.ui-dialog-titlebar-close').show();
$('#rpc-message').html('<span style="color: orange; font-weight: bold;">' + res.faultString + ' (' + res.faultCode + ')</span>');
} else {
$dialogRpc.parent().children().children('.ui-dialog-titlebar-close').hide();
const resText = res ? ('<br>' + (typeof res === 'string' ? res : JSON.stringify(res, null, ' '))) : '';
$('#rpc-message').html('<span style="color: green;">success</span><br>' + resText);
}
setTimeout(() => {
rpcDialogPending = false;
rpcDialogShift();
if (typeof callback === 'function') {
callback(err, res);
}
}, config.rpcDelay);
});
}
|
javascript
|
{
"resource": ""
}
|
q45654
|
create_extract_css_plugin
|
train
|
function create_extract_css_plugin(css_bundle_filename, useMiniCssExtractPlugin)
{
if (useMiniCssExtractPlugin)
{
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
return new MiniCssExtractPlugin
({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename : css_bundle_filename
})
}
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// "allChunks: true" option means that the styles from all chunks
// (think "entry points") will be extracted into a single big CSS file.
//
return new ExtractTextPlugin
({
filename : css_bundle_filename,
allChunks : true
})
}
|
javascript
|
{
"resource": ""
}
|
q45655
|
generate_extract_css_loaders
|
train
|
function generate_extract_css_loaders(after_style_loader, development, extract_css_plugin, useMiniCssExtractPlugin)
{
let extract_css_loaders
if (useMiniCssExtractPlugin)
{
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
return [{
loader: MiniCssExtractPlugin.loader
},
...after_style_loader]
}
// The first argument to the .extract() function is the name of the loader
// ("style-loader" in this case) to be applied to non-top-level-chunks in case of "allChunks: false" option.
// since in this configuration "allChunks: true" option is used, this first argument is irrelevant.
//
// `remove: false` ensures that the styles being extracted
// aren't erased from the chunk javascript file.
//
const extract_css_loader = extract_css_plugin.extract
({
remove : development ? false : true,
// `fallback` option is not really being used
// because `allChunks: true` option is used.
// fallback : before_style_loader,
use : after_style_loader
})
// Workaround for an old bug, may be obsolete now.
// https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/368
if (Array.isArray(extract_css_loader))
{
extract_css_loaders = extract_css_loader
}
else
{
extract_css_loaders =
[{
loader: extract_css_loader
}]
}
// I'm also prepending another `style-loader` here
// to re-enable adding these styles to the <head/> of the page on-the-fly.
if (development)
{
return [{
loader: 'style-loader'
},
...extract_css_loaders]
}
return extract_css_loaders
}
|
javascript
|
{
"resource": ""
}
|
q45656
|
fill
|
train
|
function fill() {
if (self.pgrid.filteredDataSource != null && self.dimensionsCount > 0) {
var datasource = self.pgrid.filteredDataSource;
if (datasource != null && utils.isArray(datasource) && datasource.length > 0) {
for (var rowIndex = 0, dataLength = datasource.length; rowIndex < dataLength; rowIndex++) {
var row = datasource[rowIndex];
var dim = self.root;
for (var findex = 0; findex < self.dimensionsCount; findex++) {
var depth = self.dimensionsCount - findex;
var subfield = self.fields[findex];
var subvalue = row[subfield.name];
var subdimvals = dim.subdimvals;
if (subdimvals[subvalue] !== undefined) {
dim = subdimvals[subvalue];
} else {
dim.values.push(subvalue);
dim = new Dimension(++dimid, dim, subvalue, subfield, depth, false, findex == self.dimensionsCount - 1);
subdimvals[subvalue] = dim;
dim.rowIndexes = [];
self.dimensionsByDepth[depth].push(dim);
}
dim.rowIndexes.push(rowIndex);
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q45657
|
getUiInfo
|
train
|
function getUiInfo(depth, headers) {
var infos = headers[headers.length - 1];
var parents = self.axe.root.depth === depth ? [null] :
headers[self.axe.root.depth - depth - 1].filter(function(p) {
return p.type !== uiheaders.HeaderType.SUB_TOTAL;
});
for (var pi = 0; pi < parents.length; pi++) {
var parent = parents[pi];
var parentDim = parent == null ? self.axe.root : parent.dim;
for (var di = 0; di < parentDim.values.length; di++) {
var subvalue = parentDim.values[di];
var subdim = parentDim.subdimvals[subvalue];
var subtotalHeader;
if (!subdim.isLeaf && subdim.field.subTotal.visible) {
subtotalHeader = new uiheaders.header(axe.Type.COLUMNS, uiheaders.HeaderType.SUB_TOTAL, subdim, parent, self.dataFieldsCount());
} else {
subtotalHeader = null;
}
var header = new uiheaders.header(axe.Type.COLUMNS, null, subdim, parent, self.dataFieldsCount(), subtotalHeader);
infos.push(header);
if (!subdim.isLeaf && subdim.field.subTotal.visible) {
infos.push(subtotalHeader);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q45658
|
train
|
function(identifier, parent) {
var parts = identifier.split('.');
var i = 0;
parent = parent || window;
while (i < parts.length) {
parent[parts[i]] = parent[parts[i]] || {};
parent = parent[parts[i]];
i++;
}
return parent;
}
|
javascript
|
{
"resource": ""
}
|
|
q45659
|
train
|
function(obj) {
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
arr.push(prop);
}
}
return arr;
}
|
javascript
|
{
"resource": ""
}
|
|
q45660
|
train
|
function(array, predicate) {
if (this.isArray(array) && predicate) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (predicate(item)) {
return item;
}
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q45661
|
train
|
function(obj, censorKeywords) {
function censor(key, value) {
return censorKeywords && censorKeywords.indexOf(key) > -1 ? undefined : value;
}
return JSON.stringify(obj, censor, 2);
}
|
javascript
|
{
"resource": ""
}
|
|
q45662
|
getUiInfo
|
train
|
function getUiInfo(infos, dimension) {
if (dimension.values.length > 0) {
var infosMaxIndex = infos.length - 1;
var lastInfosArray = infos[infosMaxIndex];
var parent = lastInfosArray.length > 0 ? lastInfosArray[lastInfosArray.length - 1] : null;
for (var valIndex = 0; valIndex < dimension.values.length; valIndex++) {
var subvalue = dimension.values[valIndex];
var subdim = dimension.subdimvals[subvalue];
var subTotalHeader;
if (!subdim.isLeaf && subdim.field.subTotal.visible) {
subTotalHeader = new uiheaders.header(axe.Type.ROWS, uiheaders.HeaderType.SUB_TOTAL, subdim, parent, self.dataFieldsCount());
} else {
subTotalHeader = null;
}
var newHeader = new uiheaders.header(axe.Type.ROWS, null, subdim, parent, self.dataFieldsCount(), subTotalHeader);
if (valIndex > 0) {
infos.push((lastInfosArray = []));
}
lastInfosArray.push(newHeader);
if (!subdim.isLeaf) {
getUiInfo(infos, subdim);
if (subdim.field.subTotal.visible) {
infos.push([subTotalHeader]);
// add sub-total data headers if more than 1 data field and they will be the leaf headers
addDataHeaders(infos, subTotalHeader);
}
} else {
// add data headers if more than 1 data field and they will be the leaf headers
addDataHeaders(infos, newHeader);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q45663
|
setTableWidths
|
train
|
function setTableWidths(tblObject, newWidthArray) {
if (tblObject && tblObject.node) {
// reset table width
(tblObject.size = (tblObject.size || {})).width = 0;
var tbl = tblObject.node;
// for each row, set its cells width
for (var rowIndex = 0; rowIndex < tbl.rows.length; rowIndex++) {
// current row
var currRow = tbl.rows[rowIndex];
// index in newWidthArray
var arrayIndex = 0;
var currWidth = null;
// set width of each cell
for (var cellIndex = 0; cellIndex < currRow.cells.length; cellIndex++) {
// current cell
var currCell = currRow.cells[cellIndex];
if (currCell.__orb._visible) {
// cell width
var newCellWidth = 0;
// whether current cell spans vertically more than 1 row
var rowsSpan = currCell.__orb._rowSpan > 1 && rowIndex < tbl.rows.length - 1;
// current cell width is the sum of (its) "colspan" items in newWidthArray starting at 'arrayIndex'
// 'arrayIndex' should be incremented by an amount equal to current cell 'colspan' but should also skip 'inhibited' cells
for (var cspan = 0; cspan < currCell.__orb._colSpan; cspan++) {
currWidth = newWidthArray[arrayIndex];
// skip inhibited widths (width that belongs to an upper cell than spans vertically to current row)
while (currWidth && currWidth.inhibit > 0) {
currWidth.inhibit--;
arrayIndex++;
currWidth = newWidthArray[arrayIndex];
}
if (currWidth) {
// add width of cells participating in the span
newCellWidth += currWidth.width;
// if current cell spans vertically more than 1 row, mark its width as inhibited for all cells participating in this span
if (rowsSpan) {
currWidth.inhibit = currCell.__orb._rowSpan - 1;
}
// advance newWidthArray index
arrayIndex++;
}
}
currCell.children[0].style.width = newCellWidth + 'px';
// set table width (only in first iteration)
if (rowIndex === 0) {
var outerCellWidth = 0;
if (currCell.__orb) {
outerCellWidth = currCell.__orb._colSpan * (Math.ceil(currCell.__orb._paddingLeft + currCell.__orb._paddingRight + currCell.__orb._borderLeftWidth + currCell.__orb._borderRightWidth));
}
tblObject.size.width += newCellWidth + outerCellWidth;
}
}
}
// decrement inhibited state of all widths unsed in newWidthArray (not reached by current row cells)
currWidth = newWidthArray[arrayIndex];
while (currWidth) {
if (currWidth.inhibit > 0) {
currWidth.inhibit--;
}
arrayIndex++;
currWidth = newWidthArray[arrayIndex];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q45664
|
train
|
function(name, title, url, setupTemplate, setup, showDevTools){
// Check if the window already exists
if(windowManager.windows[name]){
console.log('Window ' + name + ' already exists!');
// Move the focus on it
windowManager.focusOn(name);
return;
}
// The window unique name, if omitted a serialized name will be used instead; window_1 ~> window_2 ~> ...
this.name = name || ( 'window_' + ( Object.keys(windowManager.windows).length + 1 ) );
// The BrowserWindow module instance
this.object = null;
this.setup = {
'show': false,
'setupTemplate': setupTemplate
};
if(title) this.setup.title = title;
if(url) this.setup.url = url;
if(showDevTools) this.setup.showDevTools = showDevTools;
// If the setup is just the window dimensions, like '500x350'
if(isString(setup) && setup.indexOf('x') >= 0){
const dimensions = setup.split('x');
setup = {
'width': parseInt(dimensions[0], 10),
'height': parseInt(dimensions[1], 10)
};
}
// Overwrite the default setup
if(isObject(setup)){
this.setup = Object.assign(this.setup, setup);
}
// Register the window on the window manager
windowManager.windows[this.name] = this;
}
|
javascript
|
{
"resource": ""
}
|
|
q45665
|
train
|
function(name, setup){
if(!isObject(setup) || this.templates[name]) return false;
this.templates[name] = setup;
}
|
javascript
|
{
"resource": ""
}
|
|
q45666
|
train
|
function(setup){
const screen = Electron.screen;
const screenSize = screen.getPrimaryDisplay().workAreaSize;
const position = setup.position;
let x = 0;
let y = 0;
const positionMargin = 0;
let windowWidth = setup.width;
let windowHeight = setup.height;
// If the window dimensions are not set
if(!windowWidth || !windowHeight){
console.log('Cannot position a window with the width/height not defined!');
// Put in in the center
setup.center = true;
return false;
}
// If the position name is incorrect
if(['center', 'top', 'right', 'bottom', 'left', 'topLeft', 'leftTop', 'topRight',
'rightTop', 'bottomRight', 'rightBottom', 'bottomLeft', 'leftBottom'].indexOf(position) < 0){
console.log('The specified position "' + position + '" is\'not correct! Check the docs.');
return false;
}
// It's center by default, no need to carry on
if(position === 'center'){
return false;
}
// Compensate for the frames
if (setup.frame === true) {
switch (position) {
case 'left':
break;
case 'right':
windowWidth += 8;
break;
case 'top':
windowWidth += 13;
break;
case 'bottom':
windowHeight += 50;
windowWidth += 13;
break;
case 'leftTop':
case 'topLeft':
windowWidth += 0;
windowHeight += 50;
break;
case 'rightTop':
case 'topRight':
windowWidth += 8;
windowHeight += 50;
break;
case 'leftBottom':
case 'bottomLeft':
windowWidth -= 0;
windowHeight += 50;
break;
case 'rightBottom':
case 'bottomRight':
windowWidth += 8;
windowHeight += 50;
break;
}
}
switch (position) {
case 'left':
y = Math.floor((screenSize.height - windowHeight) / 2);
x = positionMargin - 8;
break;
case 'right':
y = Math.floor((screenSize.height - windowHeight) / 2);
x = (screenSize.width - windowWidth) - positionMargin;
break;
case 'top':
y = positionMargin;
x = Math.floor((screenSize.width - windowWidth) / 2);
break;
case 'bottom':
y = (screenSize.height - windowHeight) - positionMargin;
x = Math.floor((screenSize.width - windowWidth) / 2);
break;
case 'leftTop':
case 'topLeft':
y = positionMargin;
x = positionMargin - 8;
break;
case 'rightTop':
case 'topRight':
y = positionMargin;
x = (screenSize.width - windowWidth) - positionMargin;
break;
case 'leftBottom':
case 'bottomLeft':
y = (screenSize.height - windowHeight) - positionMargin;
x = positionMargin - 8;
break;
case 'rightBottom':
case 'bottomRight':
y = (screenSize.height - windowHeight) - positionMargin;
x = (screenSize.width - windowWidth) - positionMargin;
break;
}
return [x, y];
}
|
javascript
|
{
"resource": ""
}
|
|
q45667
|
train
|
function(config){
if(isString(config)){
this.config.appBase = config;
}else if(isObject(config)){// If the config object is provided
this.config = Object.assign(this.config, config);
}
// If the app base isn't provided
if(!this.config.appBase){
this.config.appBase = utils.getAppLocalPath();
}else if(this.config.appBase.length && this.config.appBase[this.config.appBase.length-1] !== '/'){
this.config.appBase += '/';
}
// If the layouts list was passed in the config
if(this.config.layouts && isObject(this.config.layouts)){
Object.keys(this.config.layouts).forEach(key => {
layouts.add(key, this.config.layouts[key]);
});
}
// If the dev mode is on
if(this.config.devMode === true){
// Attach some shortcuts
Application.on('ready', function(){
// Ctrl+F12 to toggle the dev tools
Shortcuts.register('CmdOrCtrl+F12', function(){
const window = windowManager.getCurrent();
if(window) window.toggleDevTools();
});
// Ctrl+R to reload the page
Shortcuts.register('CmdOrCtrl+R', function(){
const window = windowManager.getCurrent();
if(window) window.reload();
});
});
}
// If a default setup is provided
if(this.config.defaultSetup){
this.setDefaultSetup(this.config.defaultSetup);
delete this.config.defaultSetup;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45668
|
train
|
function(file){
const list = require(utils.getAppLocalPath() + file);
if(!isObject(list)) return false;
Object.keys(list).forEach(key => {
let window = list[key];
this.createNew(key, window.title, window.url, window.setupTemplate, window.setup);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45669
|
train
|
function(name, title, url, setupTemplate, setup, showDevTools){
// Create the window instance
const window = new Window(name, title, url, setupTemplate, setup, showDevTools);
// If the window was created
return (window == null || Object.keys(window).length === 0) ?false :window;
}
|
javascript
|
{
"resource": ""
}
|
|
q45670
|
train
|
function(name, title, content, setupTemplate, setup, showDevTools){
const window = this.createNew(name, title, content, setupTemplate, setup, showDevTools);
if(window) window.open();
return window;
}
|
javascript
|
{
"resource": ""
}
|
|
q45671
|
train
|
function(name){
const window = this.get(name);
if(!window) return;
return this.createNew(false, false, false, false, this.setup);
}
|
javascript
|
{
"resource": ""
}
|
|
q45672
|
train
|
function(id) {
let instance;
Object.keys(this.windows).forEach(key => {
let window = this.windows[key];
if(window.object.id === id){
instance = window;
}
});
return instance;
}
|
javascript
|
{
"resource": ""
}
|
|
q45673
|
train
|
function(){
Object.keys(this.windows).forEach(key => {
let window = this.windows[key];
window.close();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q45674
|
train
|
function(name){
// Get all the windows
const windows = BrowserWindow.getAllWindows();
// Get the window through the name
const windowID = this.get(name).object.id;
if(!windows.length || !windowID) return false;
// Loop through the windows, close all of them and focus on the targeted one
Object.keys(windows).forEach(key => {
let window = windows[key];
if(window.id !== windowID){
window.close();
}
});
this.get(name).focus();
}
|
javascript
|
{
"resource": ""
}
|
|
q45675
|
train
|
function(event, callback){
let id = windowManager.eventEmitter.listenerCount(event);
windowManager.eventEmitter.addListener(event, function(event){
callback.call(null, event.data, event.target, event.emittedBy);
});
return windowManager.eventEmitter.listeners(event)[id];
}
|
javascript
|
{
"resource": ""
}
|
|
q45676
|
getBrowserInformation
|
train
|
function getBrowserInformation(userAgent) {
var browserInfo = _bowser2.default._detect(userAgent);
for (var browser in prefixByBrowser) {
if (browserInfo.hasOwnProperty(browser)) {
var prefix = prefixByBrowser[browser];
browserInfo.jsPrefix = prefix;
browserInfo.cssPrefix = '-' + prefix.toLowerCase() + '-';
break;
}
}
browserInfo.browserName = getBrowserName(browserInfo);
// For cordova IOS 8 the version is missing, set truncated osversion to prevent NaN
if (browserInfo.version) {
browserInfo.browserVersion = parseFloat(browserInfo.version);
} else {
browserInfo.browserVersion = parseInt(parseFloat(browserInfo.osversion), 10);
}
browserInfo.osVersion = parseFloat(browserInfo.osversion);
// iOS forces all browsers to use Safari under the hood
// as the Safari version seems to match the iOS version
// we just explicitely use the osversion instead
// https://github.com/rofrischmann/inline-style-prefixer/issues/72
if (browserInfo.browserName === 'ios_saf' && browserInfo.browserVersion > browserInfo.osVersion) {
browserInfo.browserVersion = browserInfo.osVersion;
}
// seperate native android chrome
// https://github.com/rofrischmann/inline-style-prefixer/issues/45
if (browserInfo.browserName === 'android' && browserInfo.chrome && browserInfo.browserVersion > 37) {
browserInfo.browserName = 'and_chr';
}
// For android < 4.4 we want to check the osversion
// not the chrome version, see issue #26
// https://github.com/rofrischmann/inline-style-prefixer/issues/26
if (browserInfo.browserName === 'android' && browserInfo.osVersion < 5) {
browserInfo.browserVersion = browserInfo.osVersion;
}
// Samsung browser are basically build on Chrome > 44
// https://github.com/rofrischmann/inline-style-prefixer/issues/102
if (browserInfo.browserName === 'android' && browserInfo.samsungBrowser) {
browserInfo.browserName = 'and_chr';
browserInfo.browserVersion = 44;
}
return browserInfo;
}
|
javascript
|
{
"resource": ""
}
|
q45677
|
train
|
function(name) {
var cookie = this.cookies[name]
if (cookie && this.checkNotExpired(name)) {
return this.cookies[name].value
}
return null
}
|
javascript
|
{
"resource": ""
}
|
|
q45678
|
train
|
function(name, value, options) {
var cookie = typeof options == 'object'
? {value: value, expires: options.expires, secure: options.secure || false, new: options.new || false}
: {value: value}
if (this.checkNotExpired(name, cookie)) {
this.cookies[name] = cookie
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45679
|
train
|
function(headers) {
var cookies = headers['set-cookie']
if (cookies) {
cookies.forEach(function(c) {
var cookiesParams = c.split(';')
var cookiePair = cookiesParams.shift().split('=')
var options = {}
cookiesParams.forEach(function(param) {
param = param.trim()
if (param.toLowerCase().indexOf('expires') == 0) {
var date = param.split('=')[1].trim()
options.expires = new Date(date)
}
})
this.set(cookiePair[0].trim(), cookiePair[1].trim(), options)
}.bind(this))
}
}
|
javascript
|
{
"resource": ""
}
|
|
q45680
|
Server
|
train
|
function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.parse(options)
options.host = options.hostname
options.path = options.pathname
}
function handleMethodCall(request, response) {
var deserializer = new Deserializer()
deserializer.deserializeMethodCall(request, function(error, methodName, params) {
if (Object.prototype.hasOwnProperty.call(that._events, methodName)) {
that.emit(methodName, null, params, function(error, value) {
var xml = null
if (error !== null) {
xml = Serializer.serializeFault(error)
}
else {
xml = Serializer.serializeMethodResponse(value)
}
response.writeHead(200, {'Content-Type': 'text/xml'})
response.end(xml)
})
}
else {
that.emit('NotFound', methodName, params)
response.writeHead(404)
response.end()
}
})
}
this.httpServer = isSecure ? https.createServer(options, handleMethodCall)
: http.createServer(handleMethodCall)
process.nextTick(function() {
this.httpServer.listen(options.port, options.host, onListening)
}.bind(this))
this.close = function(callback) {
this.httpServer.once('close', callback)
this.httpServer.close()
}.bind(this)
}
|
javascript
|
{
"resource": ""
}
|
q45681
|
Client
|
train
|
function Client(options, isSecure) {
// Invokes with new if called without
if (false === (this instanceof Client)) {
return new Client(options, isSecure)
}
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.parse(options)
options.host = options.hostname
options.path = options.pathname
}
if (typeof options.url !== 'undefined') {
var parsedUrl = url.parse(options.url);
options.host = parsedUrl.hostname;
options.path = parsedUrl.pathname;
options.port = parsedUrl.port;
}
// Set the HTTP request headers
var headers = {
'User-Agent' : 'NodeJS XML-RPC Client'
, 'Content-Type' : 'text/xml'
, 'Accept' : 'text/xml'
, 'Accept-Charset' : 'UTF8'
, 'Connection' : 'Keep-Alive'
}
options.headers = options.headers || {}
if (options.headers.Authorization == null &&
options.basic_auth != null &&
options.basic_auth.user != null &&
options.basic_auth.pass != null)
{
var auth = options.basic_auth.user + ':' + options.basic_auth.pass
options.headers['Authorization'] = 'Basic ' + new Buffer(auth).toString('base64')
}
for (var attribute in headers) {
if (options.headers[attribute] === undefined) {
options.headers[attribute] = headers[attribute]
}
}
options.method = 'POST'
this.options = options
this.isSecure = isSecure
this.headersProcessors = {
processors: [],
composeRequest: function(headers) {
this.processors.forEach(function(p) {p.composeRequest(headers);})
},
parseResponse: function(headers) {
this.processors.forEach(function(p) {p.parseResponse(headers);})
}
};
if (options.cookies) {
this.cookies = new Cookies();
this.headersProcessors.processors.unshift(this.cookies);
}
}
|
javascript
|
{
"resource": ""
}
|
q45682
|
getNamespace
|
train
|
async function getNamespace(namespaceName) {
const cacheName = '_console_namespace_promise_cache_';
if (!window[cacheName]) {
window[cacheName] = {};
}
const cache = window[cacheName];
if (!cache[namespaceName]) {
cache[namespaceName] = fetchFromKyma(
`${k8sServerUrl}/api/v1/namespaces/${namespaceName}`
);
}
return await cache[namespaceName];
}
|
javascript
|
{
"resource": ""
}
|
q45683
|
train
|
function(scope, element, attrs, ngModel) {
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
if (ngModel.$viewValue !== element.html()) {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
}
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
}
|
javascript
|
{
"resource": ""
}
|
|
q45684
|
MetadataStore
|
train
|
function MetadataStore(config) {
config = config || { };
assertConfig(config)
.whereParam("namingConvention").isOptional().isInstanceOf(NamingConvention).withDefault(NamingConvention.defaultInstance)
.whereParam("localQueryComparisonOptions").isOptional().isInstanceOf(LocalQueryComparisonOptions).withDefault(LocalQueryComparisonOptions.defaultInstance)
.whereParam("serializerFn").isOptional().isFunction()
.applyAll(this);
this.dataServices = []; // array of dataServices;
this._resourceEntityTypeMap = {}; // key is resource name - value is qualified entityType name
this._structuralTypeMap = {}; // key is qualified structuraltype name - value is structuralType. ( structural = entityType or complexType).
this._shortNameMap = {}; // key is shortName, value is qualified name - does not need to be serialized.
this._ctorRegistry = {}; // key is either short or qual type name - value is ctor;
this._incompleteTypeMap = {}; // key is entityTypeName; value is array of nav props
this._incompleteComplexTypeMap = {}; // key is complexTypeName; value is array of complexType props
this._id = __id++;
this.metadataFetched = new Event("metadataFetched", this);
}
|
javascript
|
{
"resource": ""
}
|
q45685
|
parseTypeNameWithSchema
|
train
|
function parseTypeNameWithSchema(entityTypeName, schema) {
var result = parseTypeName(entityTypeName);
if (schema && schema.cSpaceOSpaceMapping) {
var ns = getNamespaceFor(result.shortTypeName, schema);
if (ns) {
result = makeTypeHash(result.shortTypeName, ns);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q45686
|
ComplexType
|
train
|
function ComplexType(config) {
if (arguments.length > 1) {
throw new Error("The ComplexType ctor has a single argument that is a configuration object.");
}
assertConfig(config)
.whereParam("shortName").isNonEmptyString()
.whereParam("namespace").isString().isOptional().withDefault("")
.whereParam("dataProperties").isOptional()
.whereParam("isComplexType").isOptional().isBoolean() // needed because this ctor can get called from the addEntityType method which needs the isComplexType prop
.whereParam("custom").isOptional()
.applyAll(this);
this.name = qualifyTypeName(this.shortName, this.namespace);
this.isComplexType = true;
this.dataProperties = [];
this.complexProperties = [];
this.validators = [];
this.concurrencyProperties = [];
this.unmappedProperties = [];
this.navigationProperties = []; // not yet supported
this.keyProperties = []; // may be used later to enforce uniqueness on arrays of complextypes.
addProperties(this, config.dataProperties, DataProperty);
}
|
javascript
|
{
"resource": ""
}
|
q45687
|
parseTypeName
|
train
|
function parseTypeName(entityTypeName) {
if (!entityTypeName) {
return null;
}
var typeParts = entityTypeName.split(":#");
if (typeParts.length > 1) {
return makeTypeHash(typeParts[0], typeParts[1]);
}
if (__stringStartsWith(entityTypeName, MetadataStore.ANONTYPE_PREFIX)) {
var typeHash = makeTypeHash(entityTypeName);
typeHash.isAnonymous = true
return typeHash;
}
var entityTypeNameNoAssembly = entityTypeName.split(",")[0];
var typeParts = entityTypeNameNoAssembly.split(".");
if (typeParts.length > 1) {
var shortName = typeParts[typeParts.length - 1];
var namespaceParts = typeParts.slice(0, typeParts.length - 1);
var ns = namespaceParts.join(".");
return makeTypeHash(shortName, ns);
} else {
return makeTypeHash(entityTypeName);
}
}
|
javascript
|
{
"resource": ""
}
|
q45688
|
addProperties
|
train
|
function addProperties(entityType, propObj, ctor) {
if (!propObj) return;
if (Array.isArray(propObj)) {
propObj.forEach(entityType._addPropertyCore.bind(entityType));
} else if (typeof (propObj) === 'object') {
for (var key in propObj) {
if (__hasOwnProperty(propObj, key)) {
var value = propObj[key];
value.name = key;
var prop = new ctor(value);
entityType._addPropertyCore(prop);
}
}
} else {
throw new Error("The 'dataProperties' or 'navigationProperties' values must be either an array of data/nav properties or an object where each property defines a data/nav property");
}
}
|
javascript
|
{
"resource": ""
}
|
q45689
|
__getOwnPropertyValues
|
train
|
function __getOwnPropertyValues(source) {
var result = [];
for (var name in source) {
if (__hasOwnProperty(source, name)) {
result.push(source[name]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q45690
|
__toJSONSafe
|
train
|
function __toJSONSafe(obj, replacer) {
if (obj !== Object(obj)) return obj; // primitive value
if (obj._$visited) return undefined;
replacer = replacer || __safeReplacer;
if (obj.toJSON) {
var newObj = obj.toJSON();
if (newObj !== Object(newObj)) return newObj; // primitive value
if (newObj !== obj) return __toJSONSafe(newObj, replacer);
// toJSON returned the object unchanged.
obj = newObj;
}
obj._$visited = true;
var result;
if (obj instanceof Array) {
result = obj.map(function (o) {
return __toJSONSafe(o, replacer);
});
} else if (typeof (obj) === "function") {
result = undefined;
} else {
result = {};
for (var prop in obj) {
if (prop === "_$visited") continue;
var val = obj[prop];
if (replacer) {
val = replacer(prop, val);
if (val === undefined) continue;
}
val = __toJSONSafe(val, replacer);
if (val === undefined) continue;
result[prop] = val;
}
}
delete obj._$visited;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q45691
|
__resolveProperties
|
train
|
function __resolveProperties(sources, propertyNames) {
var r = {};
var length = sources.length;
propertyNames.forEach(function (pn) {
for (var i = 0; i < length; i++) {
var src = sources[i];
if (src) {
var val = src[pn];
if (val !== undefined) {
r[pn] = val;
break;
}
}
}
});
return r;
}
|
javascript
|
{
"resource": ""
}
|
q45692
|
__map
|
train
|
function __map(items, fn, includeNull) {
// whether to return nulls in array of results; default = true;
includeNull = includeNull == null ? true : includeNull;
if (items == null) return items;
var result;
if (Array.isArray(items)) {
result = [];
items.forEach(function (v, ix) {
var r = fn(v, ix);
if (r != null || includeNull) {
result[ix] = r;
}
});
} else {
result = fn(items);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q45693
|
__getArray
|
train
|
function __getArray(source, propName) {
var arr = source[propName];
if (!arr) {
arr = [];
source[propName] = arr;
}
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q45694
|
__requireLibCore
|
train
|
function __requireLibCore(libName) {
var window = global.window;
if (!window) return; // Must run in a browser. Todo: add commonjs support
// get library from browser globals if we can
var lib = window[libName];
if (lib) return lib;
// if require exists, maybe require can get it.
// This method is synchronous so it can't load modules with AMD.
// It can only obtain modules from require that have already been loaded.
// Developer should bootstrap such that the breeze module
// loads after all other libraries that breeze should find with this method
// See documentation
var r = window.require;
if (r) { // if require exists
if (r.defined) { // require.defined is not standard and may not exist
// require.defined returns true if module has been loaded
return r.defined(libName) ? r(libName) : undefined;
} else {
// require.defined does not exist so we have to call require('libName') directly.
// The require('libName') overload is synchronous and does not load modules.
// It throws an exception if the module isn't already loaded.
try {
return r(libName);
} catch (e) {
// require('libName') threw because module not loaded
return;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q45695
|
__isPrimitive
|
train
|
function __isPrimitive(obj) {
if (obj == null) return false;
// true for numbers, strings, booleans and null, false for objects
if (obj != Object(obj)) return true;
return __isDate(obj);
}
|
javascript
|
{
"resource": ""
}
|
q45696
|
__stringStartsWith
|
train
|
function __stringStartsWith(str, prefix) {
// returns true for empty string or null prefix
if ((!str)) return false;
if (prefix == "" || prefix == null) return true;
return str.indexOf(prefix, 0) === 0;
}
|
javascript
|
{
"resource": ""
}
|
q45697
|
Enum
|
train
|
function Enum(name, methodObj) {
this.name = name;
var prototype = new EnumSymbol(methodObj);
prototype.parentEnum = this;
this._symbolPrototype = prototype;
if (methodObj) {
Object.keys(methodObj).forEach(function (key) {
prototype[key] = methodObj[key];
});
}
}
|
javascript
|
{
"resource": ""
}
|
q45698
|
EntityAspect
|
train
|
function EntityAspect(entity) {
if (entity === null) {
var nullInstance = EntityAspect._nullInstance;
if (nullInstance) return nullInstance;
EntityAspect._nullInstance = this;
} else if (entity === undefined) {
throw new Error("The EntityAspect ctor requires an entity as its only argument.");
} else if (entity.entityAspect) {
return entity.entityAspect;
}
// if called without new
if (!(this instanceof EntityAspect)) {
return new EntityAspect(entity);
}
this.entity = entity;
// TODO: keep public or not?
this.entityGroup = null;
this.entityManager = null;
this.entityState = EntityState.Detached;
this.isBeingSaved = false;
this.originalValues = {};
this.hasValidationErrors = false;
this._validationErrors = {};
// Uncomment when we implement entityAspect.isNavigationPropertyLoaded method
// this._loadedNavPropMap = {};
this.validationErrorsChanged = new Event("validationErrorsChanged", this);
this.propertyChanged = new Event("propertyChanged", this);
// in case this is the NULL entityAspect. - used with ComplexAspects that have no parent.
if (entity != null) {
entity.entityAspect = this;
// entityType should already be on the entity from 'watch'
var entityType = entity.entityType || entity._$entityType;
if (!entityType) {
var typeName = entity.prototype._$typeName;
if (!typeName) {
throw new Error("This entity is not registered as a valid EntityType");
} else {
throw new Error("Metadata for this entityType has not yet been resolved: " + typeName);
}
}
var entityCtor = entityType.getEntityCtor();
__modelLibraryDef.getDefaultInstance().startTracking(entity, entityCtor.prototype);
}
}
|
javascript
|
{
"resource": ""
}
|
q45699
|
validateTarget
|
train
|
function validateTarget(target, coIndex) {
var ok = true;
var stype = target.entityType || target.complexType;
var aspect = target.entityAspect || target.complexAspect;
var entityAspect = target.entityAspect || target.complexAspect.getEntityAspect();
var context = { entity: entityAspect.entity };
if (coIndex !== undefined) {
context.index = coIndex;
}
stype.getProperties().forEach(function (p) {
var value = target.getProperty(p.name);
var validators = p.getAllValidators();
if (validators.length > 0) {
context.property = p;
context.propertyName = aspect.getPropertyPath(p.name);
ok = entityAspect._validateProperty(value, context) && ok;
}
if (p.isComplexProperty) {
if (p.isScalar) {
ok = validateTarget(value) && ok;
} else {
ok = value.reduce(function (pv, cv, ix) {
return validateTarget(cv, ix) && pv;
}, ok);
}
}
});
// then target level
stype.getAllValidators().forEach(function (validator) {
ok = validate(entityAspect, validator, target) && ok;
});
return ok;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.