_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q53100
|
train
|
function () {
var self = this,
options = this.options,
csv = options.csv,
columns = this.columns,
startRow = options.startRow || 0,
endRow = options.endRow || Number.MAX_VALUE,
startColumn = options.startColumn || 0,
endColumn = options.endColumn || Number.MAX_VALUE,
lines,
activeRowNo = 0;
if (csv) {
lines = csv
.replace(/\r\n/g, "\n") // Unix
.replace(/\r/g, "\n") // Mac
.split(options.lineDelimiter || "\n");
each(lines, function (line, rowNo) {
var trimmed = self.trim(line),
isComment = trimmed.indexOf('#') === 0,
isBlank = trimmed === '',
items;
if (rowNo >= startRow && rowNo <= endRow && !isComment && !isBlank) {
items = line.split(options.itemDelimiter || ',');
each(items, function (item, colNo) {
if (colNo >= startColumn && colNo <= endColumn) {
if (!columns[colNo - startColumn]) {
columns[colNo - startColumn] = [];
}
columns[colNo - startColumn][activeRowNo] = item;
}
});
activeRowNo += 1;
}
});
this.dataFound();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53101
|
train
|
function () {
var options = this.options,
table = options.table,
columns = this.columns,
startRow = options.startRow || 0,
endRow = options.endRow || Number.MAX_VALUE,
startColumn = options.startColumn || 0,
endColumn = options.endColumn || Number.MAX_VALUE,
colNo;
if (table) {
if (typeof table === 'string') {
table = document.getElementById(table);
}
each(table.getElementsByTagName('tr'), function (tr, rowNo) {
colNo = 0;
if (rowNo >= startRow && rowNo <= endRow) {
each(tr.childNodes, function (item) {
if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) {
if (!columns[colNo]) {
columns[colNo] = [];
}
columns[colNo][rowNo - startRow] = item.innerHTML;
colNo += 1;
}
});
}
});
this.dataFound(); // continue
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53102
|
train
|
function (rows) {
var row,
rowsLength,
col,
colsLength,
columns;
if (rows) {
columns = [];
rowsLength = rows.length;
for (row = 0; row < rowsLength; row++) {
colsLength = rows[row].length;
for (col = 0; col < colsLength; col++) {
if (!columns[col]) {
columns[col] = [];
}
columns[col][row] = rows[row][col];
}
}
}
return columns;
}
|
javascript
|
{
"resource": ""
}
|
|
q53103
|
closeness
|
train
|
function closeness(graph, oriented) {
var Q = [];
// list of predecessors on shortest paths from source
// distance from source
var dist = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
return centrality;
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
// Add all distances for node to array, excluding -1s
var distances = Object.keys(dist).map(function(key) {return dist[key]}).filter(function(val){return val !== -1});
// Set number of reachable nodes
var reachableNodesTotal = distances.length;
// Compute sum of all distances for node
var totalDistance = distances.reduce(function(a,b) { return a + b });
if (totalDistance > 0) {
centrality[currentNode] = ((reachableNodesTotal - 1) / totalDistance);
} else {
centrality[currentNode] = 0;
}
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
Q.push(source);
while (Q.length) {
var v = Q.shift();
graph.forEachLinkedNode(v, processNode, oriented);
}
function initNode(node) {
var nodeId = node.id;
dist[nodeId] = -1;
}
function processNode(otherNode) {
var w = otherNode.id
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q53104
|
eccentricity
|
train
|
function eccentricity(graph, oriented) {
var Q = [];
// distance from source
var dist = Object.create(null);
var currentNode;
var centrality = Object.create(null);
graph.forEachNode(setCentralityToZero);
graph.forEachNode(calculateCentrality);
return centrality;
function setCentralityToZero(node) {
centrality[node.id] = 0;
}
function calculateCentrality(node) {
currentNode = node.id;
singleSourceShortestPath(currentNode);
accumulate();
}
function accumulate() {
var maxDist = 0;
Object.keys(dist).forEach(function (key) {
var val = dist[key];
if (maxDist < val) maxDist = val;
});
centrality[currentNode] = maxDist;
}
function singleSourceShortestPath(source) {
graph.forEachNode(initNode);
dist[source] = 0;
Q.push(source);
while (Q.length) {
var v = Q.shift();
graph.forEachLinkedNode(v, processNode, oriented);
}
function initNode(node) {
var nodeId = node.id;
dist[nodeId] = -1;
}
function processNode(otherNode) {
var w = otherNode.id
if (dist[w] === -1) {
// Node w is found for the first time
dist[w] = dist[v] + 1;
Q.push(w);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q53105
|
initPerfMonitor
|
train
|
function initPerfMonitor(options) {
if (!initialized) {
if (options.container) {
container = options.container;
}
initialized = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q53106
|
checkInit
|
train
|
function checkInit() {
if (!container) {
container = document.createElement("div");
container.style.cssText = "position: fixed;" + "opacity: 0.9;" + "right: 0;" + "bottom: 0";
document.body.appendChild(container);
}
initialized = true;
}
|
javascript
|
{
"resource": ""
}
|
q53107
|
scheduleTask
|
train
|
function scheduleTask(task) {
frameTasks.push(task);
if (rafId === -1) {
requestAnimationFrame(function (t) {
rafId = -1;
var tasks = frameTasks;
frameTasks = [];
for (var i = 0; i < tasks.length; i++) {
tasks[i]();
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q53108
|
startFPSMonitor
|
train
|
function startFPSMonitor() {
checkInit();
var data = new Data();
var w = new MonitorWidget("FPS", "", 2 /* HideMax */ | 1 /* HideMin */ | 4 /* HideMean */ | 32 /* RoundValues */);
container.appendChild(w.element);
var samples = [];
var last = 0;
function update(now) {
var elapsed = (now - (last === 0 ? now : last)) / 1000;
var fps = 1 / elapsed;
if (fps !== Infinity) {
if (samples.length === 64) {
samples.shift();
}
samples.push(fps);
var sum = 0;
for (var i = 0; i < samples.length; i++) {
sum += samples[i];
}
var mean = sum / samples.length;
data.addSample(mean);
w.addResult(data.calc());
}
last = now;
requestAnimationFrame(update);
}
requestAnimationFrame(update);
}
|
javascript
|
{
"resource": ""
}
|
q53109
|
startMemMonitor
|
train
|
function startMemMonitor() {
checkInit();
if (performance.memory !== void 0) {
(function () {
var update = function update() {
data.addSample(Math.round(mem.usedJSHeapSize / (1024 * 1024)));
w.addResult(data.calc());
setTimeout(update, 30);
};
var data = new Data();
var w = new MonitorWidget("Memory", "MB", 1 /* HideMin */ | 4 /* HideMean */);
container.appendChild(w.element);
var mem = performance.memory;
update();
})();
}
}
|
javascript
|
{
"resource": ""
}
|
q53110
|
initProfiler
|
train
|
function initProfiler(name) {
checkInit();
var profiler = profilerInstances[name];
if (profiler === void 0) {
profilerInstances[name] = profiler = new Profiler(name, "ms");
container.appendChild(profiler.widget.element);
}
}
|
javascript
|
{
"resource": ""
}
|
q53111
|
train
|
function (evt) {
var threshold = 30;
if (!this.pressed) {
this.pressed = true;
this.emit('touchdown');
var self = this;
this.interval = setInterval(function() {
var delta = performance.now() - self.lastTime;
if (delta > threshold) {
self.pressed = false;
self.lastTime = 0;
self.emit('touchup');
clearInterval(self.interval);
}
}, threshold);
}
this.lastTime = performance.now();
}
|
javascript
|
{
"resource": ""
}
|
|
q53112
|
readDir
|
train
|
function readDir (dir, regex = /^(?:)$/) {
return new Promise((resolve, reject) =>
fs.readdir(dir, (err, files) => err
? reject(err)
: resolve(Promise.all(files.map(checkFileName.bind(null, dir, regex))))))
.then(values =>
[].concat(...values)
.filter(i => i))
}
|
javascript
|
{
"resource": ""
}
|
q53113
|
check
|
train
|
function check(filename) {
this.filename = filename && path.resolve(filename) || '';
this.types = [];
this.valid = null;
}
|
javascript
|
{
"resource": ""
}
|
q53114
|
handler
|
train
|
function handler(req, res) {
var parsedUrl = url.parse(req.url)
var callback = qs.parse(parsedUrl.query).callback
var filename = decodeURI(parsedUrl.path.substr(1).split('?')[0])
var basename = path.basename(filename.split('?')[0])
var extname = path.extname(basename)
var response = reswrap(res);
var notfound = function() {
response.writeHead(404, 'text').end('');
};
if (req.method === 'GET' && parsedUrl.pathname === '/jsonp-request') {
if (!!exitCountdown) {
exitCountdown.restart();
}
response
.writeHead(200, 'js')
.end(callback +'('+ R.get('stamp') +')');
return;
}
var serve;
if (/^\/template/.test(parsedUrl.pathname)) {
serve = check(join(__dirname, '..', filename))
} else if (/^\/node_modules/.test(parsedUrl.pathname)) {
serve = check(join(__dirname, '..', filename))
}
if (serve) {
serve.pass(function(name, type) {
response
.writeHead(200, extname.substr(1))
.pipeWith(fs.createReadStream(
path.resolve(name)
))
}).fail(notfound);
return;
}
if (/^\.(md|mkd|markdown|html)$/.test(extname)) {
check(filename)
.pass(function() {
response
.writeHead(200, 'html')
.end(template.render({
title: basename,
highlight: R.get('highlight') || 'default',
theme: getTheme(R.get('css')),
width: R.get('width'),
body: parser.parse(read(path.resolve(filename)))
}));
}).fail(notfound);
return;
}
// Image or some other resources.
check(filename)
.pass(function(name) {
response
.writeHead(200, name)
.pipeWith(fs.createReadStream(name));
}).fail(notfound)
}
|
javascript
|
{
"resource": ""
}
|
q53115
|
compileFile
|
train
|
function compileFile(module, filename) {
const templateString = fs.readFileSync(filename, 'utf8');
module.exports = handlebars.compile(templateString);
}
|
javascript
|
{
"resource": ""
}
|
q53116
|
cal_arrayPush
|
train
|
function cal_arrayPush(n) {
function toFib(x, y, z) {
x.push((z < 2) ? z : x[z - 1] + x[z - 2])
return x
}
var arr = Array.apply(null, new Array(n)).reduce(toFib, [])
var len = arr.length
return arr[len - 1] + arr[len - 2]
}
|
javascript
|
{
"resource": ""
}
|
q53117
|
convert
|
train
|
function convert(trace, opts) {
opts = opts || {}
this._map = opts.map
this._opts = xtend({ v8gc: true }, opts, { map: this._map ? 'was supplied' : 'was not supplied' })
this.emit('info', 'Options: %j', this._opts)
this._trace = trace
this._traceLen = trace.length
if (!this._traceLen) {
this.emit('warn', 'Trace was empty, quitting')
return
}
try {
this._traceStart = traceUtil.traceStart(this._trace)
this._converterCtr = getConverter(this._trace, this._traceStart, this._opts.type)
this._resolveTraceInfo()
this._tryResolveSymbols()
this._filterInternals()
var converter = this._converterCtr(this._filtered, this._traceStart, this._opts)
this.emit('info', 'Converting trace of length %d', this._filteredLen)
var converted = converter.convert()
this.emit('info', 'Success!')
return converted
} catch (err) {
this.emit('error', err)
}
}
|
javascript
|
{
"resource": ""
}
|
q53118
|
LocalTransport
|
train
|
function LocalTransport(config) {
this.id = config && config.id || null;
this.networkId = this.id || null;
this['default'] = config && config['default'] || false;
this.agents = {};
}
|
javascript
|
{
"resource": ""
}
|
q53119
|
PubNubConnection
|
train
|
function PubNubConnection(transport, id, receive) {
this.id = id;
this.transport = transport;
// ready state
var me = this;
this.ready = new Promise(function (resolve, reject) {
transport.pubnub.subscribe({
channel: id,
message: function (message) {
receive(message.from, message.message);
},
connect: function () {
resolve(me);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q53120
|
PubNubTransport
|
train
|
function PubNubTransport(config) {
this.id = config.id || null;
this.networkId = config.publish_key || null;
this['default'] = config['default'] || false;
this.pubnub = PUBNUB().init(config);
}
|
javascript
|
{
"resource": ""
}
|
q53121
|
DistribusTransport
|
train
|
function DistribusTransport(config) {
this.id = config && config.id || null;
this['default'] = config && config['default'] || false;
this.host = config && config.host || new distribus.Host(config);
this.networkId = this.host.networkId; // FIXME: networkId can change when host connects to another host.
}
|
javascript
|
{
"resource": ""
}
|
q53122
|
PatternModule
|
train
|
function PatternModule(agent, options) {
this.agent = agent;
this.stopPropagation = options && options.stopPropagation || false;
this.receiveOriginal = agent._receive;
this.listeners = [];
}
|
javascript
|
{
"resource": ""
}
|
q53123
|
_getModuleConstructor
|
train
|
function _getModuleConstructor(name) {
var constructor = Agent.modules[name];
if (!constructor) {
throw new Error('Unknown module "' + name + '". ' +
'Choose from: ' + Object.keys(Agent.modules).map(JSON.stringify).join(', '));
}
return constructor;
}
|
javascript
|
{
"resource": ""
}
|
q53124
|
Transport
|
train
|
function Transport(config) {
this.id = config && config.id || null;
this['default'] = config && config['default'] || false;
}
|
javascript
|
{
"resource": ""
}
|
q53125
|
RequestModule
|
train
|
function RequestModule(agent, options) {
this.agent = agent;
this.receiveOriginal = agent._receive;
this.timeout = options && options.timeout || TIMEOUT;
this.queue = [];
}
|
javascript
|
{
"resource": ""
}
|
q53126
|
WebSocketConnection
|
train
|
function WebSocketConnection(transport, url, receive) {
this.transport = transport;
this.url = url ? util.normalizeURL(url) : uuid();
this.receive = receive;
this.sockets = {};
this.closed = false;
this.reconnectTimers = {};
// ready state
this.ready = Promise.resolve(this);
}
|
javascript
|
{
"resource": ""
}
|
q53127
|
BabbleModule
|
train
|
function BabbleModule(agent, options) {
// create a new babbler
var babbler = babble.babbler(agent.id);
babbler.connect({
connect: function (params) {},
disconnect: function(token) {},
send: function (to, message) {
agent.send(to, message);
}
});
this.babbler = babbler;
// create a receive function for the agent
var receiveOriginal = agent._receive;
this._receive = function (from, message) {
babbler._receive(message);
// TODO: only propagate to receiveOriginal if the message is not handled by the babbler
return receiveOriginal.call(agent, from, message);
};
}
|
javascript
|
{
"resource": ""
}
|
q53128
|
WebSocketTransport
|
train
|
function WebSocketTransport(config) {
this.id = config && config.id || null;
this.networkId = this.id || null;
this['default'] = config && config['default'] || false;
this.localShortcut = (config && config.localShortcut === false) ? false : true;
this.reconnectDelay = config && config.reconnectDelay || 10000;
this.httpTransport = config && config.httpTransport;
this.url = config && config.url || null;
this.server = null;
if (this.url != null) {
var urlParts = urlModule.parse(this.url);
if (urlParts.protocol != 'ws:') throw new Error('Invalid protocol, "ws:" expected');
if (this.url.indexOf(':id') == -1) throw new Error('":id" placeholder missing in url');
this.address = urlParts.protocol + '//' + urlParts.host; // the url without path, for example 'ws://localhost:3000'
this.ready = this._initServer(this.url);
}
else {
this.address = null;
this.ready = Promise.resolve(this);
}
this.agents = {}; // WebSocketConnections of all registered agents. The keys are the urls of the agents
}
|
javascript
|
{
"resource": ""
}
|
q53129
|
PlanningAgent
|
train
|
function PlanningAgent(id) {
// execute super constructor
eve.Agent.call(this, id);
// connect to all transports configured by the system
this.connect(eve.system.transports.getAll());
}
|
javascript
|
{
"resource": ""
}
|
q53130
|
AMQPTransport
|
train
|
function AMQPTransport(config) {
this.id = config.id || null;
this.url = config.url || (config.host && "amqp://" + config.host) || null;
this['default'] = config['default'] || false;
this.networkId = this.url;
this.connection = null;
this.config = config;
}
|
javascript
|
{
"resource": ""
}
|
q53131
|
train
|
function(name, data){
var self = this;
var eventCalls = function eventCalls(name, data){
if(events[name] instanceof Array){
events[name].forEach(function(event){
event.call(self, data);
});
}
};
if(typeof name !== 'undefined'){
name = name + '';
var statusPattern = /^([0-9])([0-9x])([0-9x])$/i;
var triggerStatus = name.match(statusPattern);
//HTTP status pattern
if(triggerStatus && triggerStatus.length > 3){
Object.keys(events).forEach(function(eventName){
var listenerStatus = eventName.match(statusPattern);
if(listenerStatus && listenerStatus.length > 3 && //an listener on status
triggerStatus[1] === listenerStatus[1] && //hundreds match exactly
(listenerStatus[2] === 'x' || triggerStatus[2] === listenerStatus[2]) && //tens matches
(listenerStatus[3] === 'x' || triggerStatus[3] === listenerStatus[3])){ //ones matches
eventCalls(eventName, data);
}
});
//or exact matching
} else if(events[name]){
eventCalls(name, data);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53132
|
train
|
function(){
var type = data.type || (data.into ? 'html' : 'json');
var url = _buildQuery();
//delegates to ajaGo
if(typeof ajaGo[type] === 'function'){
return ajaGo[type].call(this, url);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53133
|
train
|
function(url){
var self = this;
ajaGo._xhr.call(this, url, function processRes(res){
if(res){
try {
res = JSON.parse(res);
} catch(e){
self.trigger('error', e);
return null;
}
}
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53134
|
train
|
function(url){
ajaGo._xhr.call(this, url, function processRes(res){
if(data.into && data.into.length){
[].forEach.call(data.into, function(elt){
elt.innerHTML = res;
});
}
return res;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53135
|
train
|
function(url, processRes){
var self = this;
//iterators
var key, header;
var method = data.method || 'get';
var async = data.sync !== true;
var request = new XMLHttpRequest();
var _data = data.data;
var body = data.body;
var contentType = this.header('Content-Type');
var timeout = data.timeout;
var timeoutId;
var isUrlEncoded;
var openParams;
//guess content type
if(!contentType && _data && _dataInBody()){
this.header('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
contentType = this.header('Content-Type');
}
//if data is used in body, it needs some modifications regarding the content type
if(_data && _dataInBody()){
if(typeof body !== 'string'){
body = '';
}
if(contentType.indexOf('json') > -1){
try {
body = JSON.stringify(_data);
} catch(e){
throw new TypeError('Unable to stringify body\'s content : ' + e.name);
}
} else {
isUrlEncoded = contentType && contentType.indexOf('x-www-form-urlencoded') > 1;
for(key in _data){
if(isUrlEncoded){
body += encodeURIComponent(key) + '=' + encodeURIComponent(_data[key]) + '&';
} else {
body += key + '=' + _data[key] + '\n\r';
}
}
}
}
//open the XHR request
openParams = [method, url, async];
if(data.auth){
openParams.push(data.auth.user);
openParams.push(data.auth.passwd);
}
request.open.apply(request, openParams);
//set the headers
for(header in data.headers){
request.setRequestHeader(header, data.headers[header]);
}
//bind events
request.onprogress = function(e){
if (e.lengthComputable) {
self.trigger('progress', e.loaded / e.total);
}
};
request.onload = function onRequestLoad(){
var response = request.responseText;
if (timeoutId) {
clearTimeout(timeoutId);
}
if(this.status >= 200 && this.status < 300){
if(typeof processRes === 'function'){
response = processRes(response);
}
self.trigger('success', response);
}
self.trigger(this.status, response);
self.trigger('end', response);
};
request.onerror = function onRequestError (err){
if (timeoutId) {
clearTimeout(timeoutId);
}
self.trigger('error', err, arguments);
};
//sets the timeout
if (timeout) {
timeoutId = setTimeout(function() {
self.trigger('timeout', {
type: 'timeout',
expiredAfter: timeout
}, request, arguments);
request.abort();
}, timeout);
}
//send the request
request.send(body);
}
|
javascript
|
{
"resource": ""
}
|
|
q53136
|
train
|
function(url){
var self = this;
var head = document.querySelector('head') || document.querySelector('body');
var async = data.sync !== true;
var script;
if(!head){
throw new Error('Ok, wait a second, you want to load a script, but you don\'t have at least a head or body tag...');
}
script = document.createElement('script');
script.async = async;
script.src = url;
script.onerror = function onScriptError(){
self.trigger('error', arguments);
head.removeChild(script);
};
script.onload = function onScriptLoad(){
self.trigger('success', arguments);
};
head.appendChild(script);
}
|
javascript
|
{
"resource": ""
}
|
|
q53137
|
_buildQuery
|
train
|
function _buildQuery(){
var url = data.url;
var cache = typeof data.cache !== 'undefined' ? !!data.cache : true;
var queryString = data.queryString || '';
var _data = data.data;
//add a cache buster
if(cache === false){
queryString += '&ajabuster=' + new Date().getTime();
}
url = appendQueryString(url, queryString);
if(_data && !_dataInBody()){
url = appendQueryString(url, _data);
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q53138
|
train
|
function(params){
var object = {};
if(typeof params === 'string'){
params.replace('?', '').split('&').forEach(function(kv){
var pair = kv.split('=');
if(pair.length === 2){
object[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
});
} else {
object = params;
}
return this.plainObject(object);
}
|
javascript
|
{
"resource": ""
}
|
|
q53139
|
train
|
function(functionName){
functionName = this.string(functionName);
if(!/^([a-zA-Z_])([a-zA-Z0-9_\-])+$/.test(functionName)){
throw new TypeError('a valid function name is expected, ' + functionName + ' [' + (typeof functionName) + '] given');
}
return functionName;
}
|
javascript
|
{
"resource": ""
}
|
|
q53140
|
train
|
function(req, res, next) {
if (/aja\.js$/.test(req.url)) {
return res.end(grunt.file.read(coverageDir + '/instrument/src/aja.js'));
}
return next();
}
|
javascript
|
{
"resource": ""
}
|
|
q53141
|
get
|
train
|
function get (url, callback) {
// https://nodejs.org/dist/latest-v8.x/docs/api/http.html#http_http_get_options_callback
http.get(url, (result) => {
const contentType = result.headers['content-type']
const statusCode = result.statusCode
let error
if (statusCode !== 200) {
error = new Error(`Unable to send request for definitions. Status code: '${statusCode}'`)
error.code = 'ERR_REQUEST_SEND'
} else if (contentType.indexOf('application/json') === -1) {
error = new Error(`Content retrieved isn't JSON. Content type: '${contentType}'`)
error.code = 'ERR_RESPONSE_NOT_JSON'
}
if (error) {
// Removes response data to clear up memory.
result.resume()
callback(error)
return
}
result.setEncoding('utf8')
let rawData = ''
result.on('data', (buffer) => {
rawData += buffer
})
result.on('end', () => {
let data = null
let error = null
try {
data = JSON.parse(rawData)
} catch (unusedError) {
// In case somehow the data got set to not null. This is more of a failsafe.
data = null
error = new Error('Failed to parse retrieved Urban Dictionary JSON.')
error.code = 'ERR_JSON_PARSE'
}
callback(error, data)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q53142
|
difference
|
train
|
function difference(a, b) {
var oldHashes = {};
var errors = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = b.errors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var error = _step.value;
var hash = JSON.stringify(error.message);
oldHashes[hash] = error;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = a.errors[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _error = _step2.value;
var _hash = JSON.stringify(_error.message);
if (oldHashes[_hash] !== undefined) {
continue;
}
errors.push(JSON.parse(JSON.stringify(_error)));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return {
passed: errors.length === 0,
errors: errors,
flowVersion: a.flowVersion
};
}
|
javascript
|
{
"resource": ""
}
|
q53143
|
train
|
function(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier, redOffset, greenOffset, blueOffset, alphaOffset) {
this.initialize(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier, redOffset, greenOffset, blueOffset, alphaOffset);
}
|
javascript
|
{
"resource": ""
}
|
|
q53144
|
resolveClient
|
train
|
function resolveClient(c,arg)
{
if(typeof c.y === "function")
{
try {
var yret = c.y.call(_undefined,arg);
c.p.resolve(yret);
}
catch(err) { c.p.reject(err) }
}
else
c.p.resolve(arg); // pass this along...
}
|
javascript
|
{
"resource": ""
}
|
q53145
|
rp
|
train
|
function rp(p,i)
{
if(!p || typeof p.then !== "function")
p = Zousan.resolve(p);
p.then(
function(yv) { results[i] = yv; rc++; if(rc == pa.length) retP.resolve(results); },
function(nv) { retP.reject(nv); }
);
}
|
javascript
|
{
"resource": ""
}
|
q53146
|
train
|
function(workingDir, elmPackage){
elmPackage['native-modules'] = true;
var sources = elmPackage['source-directories'].map(function(dir){
return path.join(workingDir, dir);
});
sources.push('.');
elmPackage['source-directories'] = sources;
elmPackage['dependencies']["eeue56/elm-html-in-elm"] = "2.0.0 <= v < 3.0.0";
return elmPackage;
}
|
javascript
|
{
"resource": ""
}
|
|
q53147
|
has
|
train
|
function has(obj, val) {
val = arrayify(val);
var len = val.length;
if (isObject(obj)) {
for (var key in obj) {
if (val.indexOf(key) > -1) {
return true;
}
}
var keys = nativeKeys(obj);
return has(keys, val);
}
if (Array.isArray(obj)) {
var arr = obj;
while (len--) {
if (arr.indexOf(val[len]) > -1) {
return true;
}
}
return false;
}
throw new TypeError('expected an array or object.');
}
|
javascript
|
{
"resource": ""
}
|
q53148
|
setupTempDir
|
train
|
function setupTempDir(tmpDir) {
var rpmStructure = ['BUILD', 'BUILDROOT', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'];
// If the tmpDir exists (probably from previous build), delete it first
if (fsx.existsSync(tmpDir)) {
logger(chalk.cyan('Removing old temporary directory.'));
fsx.removeSync(tmpDir);
}
// Create RPM folder structure
logger(chalk.cyan('Creating RPM directory structure at:'), tmpDir);
_.forEach(rpmStructure, function(dirName) {
fsx.mkdirpSync(path.join(tmpDir, dirName));
});
}
|
javascript
|
{
"resource": ""
}
|
q53149
|
buildRpm
|
train
|
function buildRpm(buildRoot, specFile, rpmDest, execOpts, cb) {
// Build the RPM package.
var cmd = [
'rpmbuild',
'-bb',
'-vv',
'--buildroot',
buildRoot,
specFile
].join(' ');
logger(chalk.cyan('Executing:'), cmd);
execOpts = execOpts || {};
exec(cmd, execOpts, function rpmbuild(err, stdout) {
if (err) {
return cb(err);
}
if (stdout) {
var rpm = stdout.match(/(\/.+\..+\.rpm)/);
if (rpm && rpm.length > 0) {
var rpmDestination = rpm[0];
if (rpmDest) {
rpmDestination = path.join(rpmDest, path.basename(rpmDestination));
logger(chalk.cyan('Copying RPM package to:'), rpmDestination);
fsx.copySync(rpm[0], rpmDestination);
}
return cb(null, rpmDestination);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q53150
|
parseIgnoreFile
|
train
|
function parseIgnoreFile(ignoreFile) {
// At first we'll try to determine line endings for ignore file.
// For this we will count \n and \r\n occurrences and choose the one
// which dominates. If we don't have line endings at all we will keep
// default OS line endings.
var lfCount = countOccurrences('\n', ignoreFile.content),
crlfCount = countOccurrences('\r\n', ignoreFile.content);
if (lfCount > 0 || crlfCount > 0)
ignoreFile.eol = lfCount > crlfCount ? '\n' : '\r\n';
ignoreFile.patterns = ignoreFile.content
// Normalize new lines
.replace(/\r\n?/g, '\n')
// Then split content by new line
.split('\n')
// Trim items
.map(function (str) {
return str.trim();
})
// Skip empty strings and comments
.filter(function (str) {
return str && str.indexOf('#') !== 0;
});
}
|
javascript
|
{
"resource": ""
}
|
q53151
|
getCleanTargets
|
train
|
function getCleanTargets() {
var directDeps = targets.map(function (pattern) {
return '*/' + pattern;
}),
indirectDeps = targets.map(function (pattern) {
return '**/node_modules/*/' + pattern;
});
return directDeps.concat(indirectDeps);
}
|
javascript
|
{
"resource": ""
}
|
q53152
|
logFatal
|
train
|
function logFatal(message) {
console.log(os.EOL + chalk.red.bold('Fatal error : ' + message));
process.exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q53153
|
logDebug
|
train
|
function logDebug(message) {
if (!debug) {
return;
}
if (!enabled) return;
console.log(os.EOL + chalk.cyan(message));
}
|
javascript
|
{
"resource": ""
}
|
q53154
|
countTrailingZeros
|
train
|
function countTrailingZeros(v) {
var c = 32;
v &= -v;
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
return c;
}
|
javascript
|
{
"resource": ""
}
|
q53155
|
generate
|
train
|
function generate(options) {
options = options || {};
if (typeof options === 'string') options = { type: options };
var type = paramDefault(options.type, 'base64');
var additional = paramDefault(options.additional, 0);
var count = paramDefault(options.countNumber, parseInt(Math.random() * 10000 % 1024));
var rawBuffer = generator.generate(count, additional);
if (type === 'base64') {
// NOTE: this is URL-safe Base64Url format. not pure base64.
// + since UUID is fixed 64bit we don't have to worry about padding(=)
return unLittleEndian(rawBuffer)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
} else if (type === 'hash' || type == 'hex') {
return unLittleEndian(rawBuffer).toString('hex');
} else if (type === 'decimal' || type == 'number') {
return toLong(rawBuffer).toString();
} else if (type === 'long') {
return toLong(rawBuffer);
} else if (type == 'buffer') {
return rawBuffer;
} else if (type == 'buffer_be') {
// to big endian
return unLittleEndian(rawBuffer);
} else if (type == 'raw') {
// OMG, R u serious?
return rawBuffer.toString();
} else throw new TypeError("Unknown encoding: " + type);
}
|
javascript
|
{
"resource": ""
}
|
q53156
|
Message
|
train
|
function Message(messageId) {
if (util.isNullOrUndefined(messageId) || "string" !== typeof(messageId)) {
throw new IllegalArgumentException();
}
/**
* This parameter uniquely identifies a message in an XMPP connection.
*/
this.mMessageId = messageId;
this.mCollapseKey = null;
this.mDelayWhileIdle = null;
this.mTimeToLive = null;
this.mData = null; //Object
this.mDryRun = null;
this.mDeliveryReceiptRequested = false;
this.mPriority = null;
this.mNotification = null;
this.mContentAvailable = false;
this.mMutableContent = false;
this.mBuilded = false;
}
|
javascript
|
{
"resource": ""
}
|
q53157
|
getTagLength
|
train
|
function getTagLength(tag) {
var lenTag = 4;
while(lenTag > 1) {
var tmpTag = tag >>> ((lenTag - 1) * 8);
if ((tmpTag & 0xFF) != 0x00) {
break;
}
lenTag--;
}
return lenTag;
}
|
javascript
|
{
"resource": ""
}
|
q53158
|
getValueLength
|
train
|
function getValueLength(value, constructed) {
var lenValue = 0;
if (constructed) {
for (var i = 0; i < value.length; i++) {
lenValue = lenValue + value[i].byteLength;
}
} else {
lenValue = value.length;
}
return lenValue;
}
|
javascript
|
{
"resource": ""
}
|
q53159
|
getLengthOfLength
|
train
|
function getLengthOfLength(lenValue, indefiniteLength) {
var lenOfLen;
if (indefiniteLength) {
lenOfLen = 3;
} else if (lenValue > 0x00FFFFFF) {
lenOfLen = 5;
} else if (lenValue > 0x0000FFFF) {
lenOfLen = 4;
} else if (lenValue > 0x000000FF) {
lenOfLen = 3;
} else if (lenValue > 0x0000007F) {
lenOfLen = 2;
} else {
lenOfLen = 1;
}
return lenOfLen
}
|
javascript
|
{
"resource": ""
}
|
q53160
|
encodeNumber
|
train
|
function encodeNumber(buf, value, len) {
var index = 0;
while (len > 0) {
var tmpValue = value >>> ((len - 1) * 8);
buf[index++] = tmpValue & 0xFF;
len--;
}
}
|
javascript
|
{
"resource": ""
}
|
q53161
|
parseTag
|
train
|
function parseTag(buf) {
var index = 0;
var tag = buf[index++];
var constructed = (tag & 0x20) == 0x20;
if ((tag & 0x1F) == 0x1F) {
do {
tag = tag << 8;
tag = tag | buf[index++];
} while((tag & 0x80) == 0x80);
if (index > 4) {
throw new RangeError("The length of the tag cannot be more than 4 bytes in this implementation");
}
}
return { tag: tag, length: index, constructed: constructed };
}
|
javascript
|
{
"resource": ""
}
|
q53162
|
parseAllTags
|
train
|
function parseAllTags(buf) {
var result = [];
var element;
while (buf.length > 0) {
element = parseTag(buf);
buf = buf.slice(element.length);
result.push(element.tag);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q53163
|
encodeTags
|
train
|
function encodeTags(tags) {
var bufLength = 0;
var tagLengths = []
for (var i = 0; i < tags.length; i++) {
var tagLength = getTagLength(tags[i]);
tagLengths.push(tagLength);
bufLength += tagLength;
}
var buf = new Buffer(bufLength);
var slicedBuf = buf;
for (var i = 0; i < tags.length; i++) {
encodeNumber(slicedBuf, tags[i], tagLengths[i]);
slicedBuf = slicedBuf.slice(tagLengths[i]);
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q53164
|
Notification
|
train
|
function Notification(icon) {
if (util.isNullOrUndefined(icon)) {
throw new IllegalArgumentException();
}
this.mTitle = null;
this.mBody = null;
this.mIcon = icon;
this.mSound = "default"; // the only currently supported value
this.mBadge = null;
this.mTag = null;
this.mColor = null;
this.mClickAction = null;
this.mBodyLocKey = null;
this.mBodyLocArgs = null; // array
this.mTitleLocKey = null;
this.mTitleLocArgs = null; // array
this.mBuilded = false;
}
|
javascript
|
{
"resource": ""
}
|
q53165
|
run
|
train
|
function run (answers) {
ls(['LICENSE', 'package.json', 'README.md', 'index.js', 'index.html', 'examples/basic/index.html', 'tests/index.test.js']).forEach(function (file) {
answers.aframeVersion = aframeVersion;
answers.npmName = `aframe-${answers.shortName}-component`;
fs.writeFileSync(file, nunjucks.render(file, answers));
});
}
|
javascript
|
{
"resource": ""
}
|
q53166
|
loadFileData
|
train
|
function loadFileData(fileName) {
var testConfig = this.testConfig;
if (!testConfig) {
throw new Error('No test configuration found.\n' +
'You can add one by adding a property called `testConfig` to the word object.');
}
var testDataRoot = testConfig.testDataRoot;
if (!testDataRoot) {
throw new Error('No test data root path found.\n' +
'You can add one by adding a property called `testDataRoot` to the test configuration.');
}
var filePath = path.join(testDataRoot, fileName);
this._log.trace({ path: filePath }, 'Loading file.');
//Don't use `require` because that caches the returned object.
var value = require('fs').createReadStream(filePath);
this._log.trace({ loadedData: value }, 'File loaded.');
return value;
}
|
javascript
|
{
"resource": ""
}
|
q53167
|
TimeStamp
|
train
|
function TimeStamp(timestamp) {
tr.b.u.Scalar.call(this, timestamp, tr.b.u.Units.timeStampInMs);
}
|
javascript
|
{
"resource": ""
}
|
q53168
|
train
|
function(slice, flowEvents) {
var fromOtherInputs = false;
slice.iterateEntireHierarchy(function(subsequentSlice) {
if (fromOtherInputs)
return;
subsequentSlice.inFlowEvents.forEach(function(inflow) {
if (fromOtherInputs)
return;
if (inflow.category.indexOf('input') > -1) {
if (flowEvents.indexOf(inflow) === -1)
fromOtherInputs = true;
}
}, this);
}, this);
return fromOtherInputs;
}
|
javascript
|
{
"resource": ""
}
|
|
q53169
|
train
|
function(event, flowEvents) {
if (event.outFlowEvents === undefined ||
event.outFlowEvents.length === 0)
return false;
// Once we fix the bug of flow event binding, there should exist one and
// only one outgoing flow (PostTask) from ScheduleBeginImplFrameDeadline
// and PostComposite.
var flow = event.outFlowEvents[0];
if (flow.category !== POSTTASK_FLOW_EVENT ||
!flow.endSlice)
return false;
var endSlice = flow.endSlice;
if (this.belongToOtherInputs(endSlice.mostTopLevelSlice, flowEvents))
return true;
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q53170
|
train
|
function(event, queue, visited, flowEvents) {
var stopFollowing = false;
var inputAck = false;
event.iterateAllSubsequentSlices(function(slice) {
if (stopFollowing)
return;
// Do not follow TaskQueueManager::RunTask because it causes
// many false events to be included.
if (slice.title === 'TaskQueueManager::RunTask')
return;
// Do not follow ScheduledActionSendBeginMainFrame because the real
// main thread BeginMainFrame is already traced by LatencyInfo flow.
if (slice.title === 'ThreadProxy::ScheduledActionSendBeginMainFrame')
return;
// Do not follow ScheduleBeginImplFrameDeadline that triggers an
// OnBeginImplFrameDeadline that is tracked by another LatencyInfo.
if (slice.title === 'Scheduler::ScheduleBeginImplFrameDeadline') {
if (this.triggerOtherInputs(slice, flowEvents))
return;
}
// Do not follow PostComposite that triggers CompositeImmediately
// that is tracked by another LatencyInfo.
if (slice.title === 'CompositorImpl::PostComposite') {
if (this.triggerOtherInputs(slice, flowEvents))
return;
}
// Stop following the rest of the current slice hierarchy if
// FilterAndSendWebInputEvent occurs after ProcessInputEventAck.
if (slice.title === 'InputRouterImpl::ProcessInputEventAck')
inputAck = true;
if (inputAck &&
slice.title === 'InputRouterImpl::FilterAndSendWebInputEvent')
stopFollowing = true;
this.followCurrentSlice(slice, queue, visited);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q53171
|
train
|
function(event, queue, visited) {
event.outFlowEvents.forEach(function(outflow) {
if ((outflow.category === POSTTASK_FLOW_EVENT ||
outflow.category === IPC_FLOW_EVENT) &&
outflow.endSlice) {
this.associatedEvents_.push(outflow);
var nextEvent = outflow.endSlice.mostTopLevelSlice;
if (!visited.contains(nextEvent)) {
visited.push(nextEvent);
queue.push(nextEvent);
}
}
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q53172
|
SchedParser
|
train
|
function SchedParser(importer) {
Parser.call(this, importer);
importer.registerEventHandler('sched_switch',
SchedParser.prototype.schedSwitchEvent.bind(this));
importer.registerEventHandler('sched_wakeup',
SchedParser.prototype.schedWakeupEvent.bind(this));
importer.registerEventHandler('sched_blocked_reason',
SchedParser.prototype.schedBlockedEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53173
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
var event = schedSwitchRE.exec(eventBase.details);
if (!event)
return false;
var prevState = event[4];
var nextComm = event[5];
var nextPid = parseInt(event[6]);
var nextPrio = parseInt(event[7]);
var nextThread = this.importer.threadsByLinuxPid[nextPid];
var nextName;
if (nextThread)
nextName = nextThread.userFriendlyName;
else
nextName = nextComm;
var cpu = this.importer.getOrCreateCpu(cpuNumber);
cpu.switchActiveThread(
ts,
{stateWhenDescheduled: prevState},
nextPid,
nextName,
{
comm: nextComm,
tid: nextPid,
prio: nextPrio
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53174
|
train
|
function(array, opt_keyFunc, opt_this) {
if (this.isEmpty_)
return [];
// Binary search. |test| is a function that should return true when we
// need to explore the left branch and false to explore the right branch.
function binSearch(test) {
var i0 = 0;
var i1 = array.length;
while (i0 < i1 - 1) {
var i = Math.trunc((i0 + i1) / 2);
if (test(i))
i1 = i; // Explore the left branch.
else
i0 = i; // Explore the right branch.
}
return i1;
}
var keyFunc = opt_keyFunc || tr.b.identity;
function getValue(index) {
return keyFunc.call(opt_this, array[index]);
}
var first = binSearch(function(i) {
return this.min_ === undefined || this.min_ <= getValue(i);
}.bind(this));
var last = binSearch(function(i) {
return this.max_ !== undefined && this.max_ < getValue(i);
}.bind(this));
return array.slice(first, last);
}
|
javascript
|
{
"resource": ""
}
|
|
q53175
|
binSearch
|
train
|
function binSearch(test) {
var i0 = 0;
var i1 = array.length;
while (i0 < i1 - 1) {
var i = Math.trunc((i0 + i1) / 2);
if (test(i))
i1 = i; // Explore the left branch.
else
i0 = i; // Explore the right branch.
}
return i1;
}
|
javascript
|
{
"resource": ""
}
|
q53176
|
DrmParser
|
train
|
function DrmParser(importer) {
Parser.call(this, importer);
importer.registerEventHandler('drm_vblank_event',
DrmParser.prototype.vblankEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53177
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
var event = /crtc=(\d+), seq=(\d+)/.exec(eventBase.details);
if (!event)
return false;
var crtc = parseInt(event[1]);
var seq = parseInt(event[2]);
this.drmVblankSlice(ts, 'vblank:' + crtc,
{
crtc: crtc,
seq: seq
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53178
|
CpufreqParser
|
train
|
function CpufreqParser(importer) {
Parser.call(this, importer);
importer.registerEventHandler('cpufreq_interactive_up',
CpufreqParser.prototype.cpufreqUpDownEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_down',
CpufreqParser.prototype.cpufreqUpDownEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_already',
CpufreqParser.prototype.cpufreqTargetEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_notyet',
CpufreqParser.prototype.cpufreqTargetEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_setspeed',
CpufreqParser.prototype.cpufreqTargetEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_target',
CpufreqParser.prototype.cpufreqTargetEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_boost',
CpufreqParser.prototype.cpufreqBoostUnboostEvent.bind(this));
importer.registerEventHandler('cpufreq_interactive_unboost',
CpufreqParser.prototype.cpufreqBoostUnboostEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53179
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
var data = splitData(eventBase.details);
this.cpufreqSlice(ts, eventName, data.cpu, data);
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53180
|
PowerParser
|
train
|
function PowerParser(importer) {
Parser.call(this, importer);
// NB: old-style power events, deprecated
importer.registerEventHandler('power_start',
PowerParser.prototype.powerStartEvent.bind(this));
importer.registerEventHandler('power_frequency',
PowerParser.prototype.powerFrequencyEvent.bind(this));
importer.registerEventHandler('cpu_frequency',
PowerParser.prototype.cpuFrequencyEvent.bind(this));
importer.registerEventHandler('cpu_idle',
PowerParser.prototype.cpuIdleEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53181
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
var event = /type=(\d+) state=(\d) cpu_id=(\d+)/.exec(eventBase.details);
if (!event)
return false;
var targetCpuNumber = parseInt(event[3]);
var cpuState = parseInt(event[2]);
this.cpuStateSlice(ts, targetCpuNumber, event[1], cpuState);
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53182
|
DiskParser
|
train
|
function DiskParser(importer) {
Parser.call(this, importer);
importer.registerEventHandler('f2fs_write_begin',
DiskParser.prototype.f2fsWriteBeginEvent.bind(this));
importer.registerEventHandler('f2fs_write_end',
DiskParser.prototype.f2fsWriteEndEvent.bind(this));
importer.registerEventHandler('f2fs_sync_file_enter',
DiskParser.prototype.f2fsSyncFileEnterEvent.bind(this));
importer.registerEventHandler('f2fs_sync_file_exit',
DiskParser.prototype.f2fsSyncFileExitEvent.bind(this));
importer.registerEventHandler('ext4_sync_file_enter',
DiskParser.prototype.ext4SyncFileEnterEvent.bind(this));
importer.registerEventHandler('ext4_sync_file_exit',
DiskParser.prototype.ext4SyncFileExitEvent.bind(this));
importer.registerEventHandler('ext4_da_write_begin',
DiskParser.prototype.ext4WriteBeginEvent.bind(this));
importer.registerEventHandler('ext4_da_write_end',
DiskParser.prototype.ext4WriteEndEvent.bind(this));
importer.registerEventHandler('block_rq_issue',
DiskParser.prototype.blockRqIssueEvent.bind(this));
importer.registerEventHandler('block_rq_complete',
DiskParser.prototype.blockRqCompleteEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53183
|
train
|
function(datum) {
var startPosition = this.beginPositionCb_(datum);
var endPosition = this.endPositionCb_(datum);
var node = new IntervalTreeNode(datum,
startPosition, endPosition);
this.size_++;
this.root_ = this.insertNode_(this.root_, node);
this.root_.colour = Colour.BLACK;
return datum;
}
|
javascript
|
{
"resource": ""
}
|
|
q53184
|
train
|
function(queryLow, queryHigh) {
this.validateFindArguments_(queryLow, queryHigh);
if (this.root_ === undefined)
return [];
var ret = [];
this.root_.appendIntersectionsInto_(ret, queryLow, queryHigh);
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q53185
|
train
|
function() {
this.classList.add('overlay');
this.parentEl_ = this.ownerDocument.body;
this.visible_ = false;
this.userCanClose_ = true;
this.onKeyDown_ = this.onKeyDown_.bind(this);
this.onClick_ = this.onClick_.bind(this);
this.onFocusIn_ = this.onFocusIn_.bind(this);
this.onDocumentClick_ = this.onDocumentClick_.bind(this);
this.onClose_ = this.onClose_.bind(this);
this.addEventListener('visible-change',
tr.ui.b.Overlay.prototype.onVisibleChange_.bind(this), true);
// Setup the shadow root
var createShadowRoot = this.createShadowRoot ||
this.webkitCreateShadowRoot;
this.shadow_ = createShadowRoot.call(this);
this.shadow_.appendChild(tr.ui.b.instantiateTemplate('#overlay-template',
THIS_DOC));
this.closeBtn_ = this.shadow_.querySelector('close-button');
this.closeBtn_.addEventListener('click', this.onClose_);
this.shadow_
.querySelector('overlay-frame')
.addEventListener('click', this.onClick_);
this.observer_ = new WebKitMutationObserver(
this.didButtonBarMutate_.bind(this));
this.observer_.observe(this.shadow_.querySelector('button-bar'),
{ childList: true });
// title is a variable on regular HTMLElements. However, we want to
// use it for something more useful.
Object.defineProperty(
this, 'title', {
get: function() {
return this.shadow_.querySelector('title').textContent;
},
set: function(title) {
this.shadow_.querySelector('title').textContent = title;
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53186
|
userFriendlyRailTypeName
|
train
|
function userFriendlyRailTypeName(railTypeName) {
if (railTypeName.length < 6 || railTypeName.indexOf('rail_') != 0)
return railTypeName;
return railTypeName[5].toUpperCase() + railTypeName.slice(6);
}
|
javascript
|
{
"resource": ""
}
|
q53187
|
railCompare
|
train
|
function railCompare(name1, name2) {
var i1 = RAIL_ORDER.indexOf(name1.toUpperCase());
var i2 = RAIL_ORDER.indexOf(name2.toUpperCase());
if (i1 == -1 && i2 == -1)
return name1.localeCompare(name2);
if (i1 == -1)
return 1; // i2 is a RAIL name but not i1.
if (i2 == -1)
return -1; // i1 is a RAIL name but not i2.
// Two rail names.
return i1 - i2;
}
|
javascript
|
{
"resource": ""
}
|
q53188
|
WorkqueueParser
|
train
|
function WorkqueueParser(importer) {
Parser.call(this, importer);
importer.registerEventHandler('workqueue_execute_start',
WorkqueueParser.prototype.executeStartEvent.bind(this));
importer.registerEventHandler('workqueue_execute_end',
WorkqueueParser.prototype.executeEndEvent.bind(this));
importer.registerEventHandler('workqueue_queue_work',
WorkqueueParser.prototype.executeQueueWork.bind(this));
importer.registerEventHandler('workqueue_activate_work',
WorkqueueParser.prototype.executeActivateWork.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q53189
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
var event = workqueueExecuteStartRE.exec(eventBase.details);
if (!event)
return false;
var kthread = this.importer.getOrCreateKernelThread(eventBase.threadName,
pid, pid);
kthread.openSliceTS = ts;
kthread.openSlice = event[2];
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53190
|
LinuxPerfImporter
|
train
|
function LinuxPerfImporter(model, events) {
this.importPriority = 2;
this.model_ = model;
this.events_ = events;
this.newlyAddedClockSyncRecords_ = [];
this.wakeups_ = [];
this.blocked_reasons_ = [];
this.kernelThreadStates_ = {};
this.buildMapFromLinuxPidsToThreads();
this.lines_ = [];
this.pseudoThreadCounter = 1;
this.parsers_ = [];
this.eventHandlers_ = {};
}
|
javascript
|
{
"resource": ""
}
|
q53191
|
train
|
function() {
this.threadsByLinuxPid = {};
this.model_.getAllThreads().forEach(
function(thread) {
this.threadsByLinuxPid[thread.tid] = thread;
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q53192
|
train
|
function(isSecondaryImport) {
this.parsers_ = this.createParsers_();
this.registerDefaultHandlers_();
this.parseLines();
this.importClockSyncRecords();
var timeShift = this.computeTimeTransform();
if (timeShift === undefined) {
this.model_.importWarning({
type: 'clock_sync',
message: 'Cannot import kernel trace without a clock sync.'
});
return;
}
this.shiftNewlyAddedClockSyncRecords(timeShift);
this.importCpuData(timeShift);
this.buildMapFromLinuxPidsToThreads();
this.buildPerThreadCpuSlicesFromCpuState();
this.computeCpuTimestampsForSlicesAsNeeded();
}
|
javascript
|
{
"resource": ""
}
|
|
q53193
|
train
|
function(state) {
if (wakeup !== undefined) {
midDuration = wakeup.ts - prevSlice.end;
}
if (blocked_reason !== undefined) {
var args = {
'kernel callsite when blocked:' : blocked_reason.caller
};
if (blocked_reason.iowait) {
switch (state) {
case SCHEDULING_STATE.UNINTR_SLEEP:
state = SCHEDULING_STATE.UNINTR_SLEEP_IO;
break;
case SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL:
state = SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL_IO;
break;
case SCHEDULING_STATE.UNINTR_SLEEP_WAKING:
state = SCHEDULING_STATE.UNINTR_SLEEP_WAKE_KILL_IO;
break;
default:
}
}
slices.push(new tr.model.ThreadTimeSlice(
thread,
state, '', prevSlice.end, args, midDuration));
} else {
slices.push(new tr.model.ThreadTimeSlice(
thread,
state, '', prevSlice.end, {}, midDuration));
}
if (wakeup !== undefined) {
var wakeupDuration = nextSlice.start - wakeup.ts;
var args = {'wakeup from tid': wakeup.fromTid};
slices.push(new tr.model.ThreadTimeSlice(
thread, SCHEDULING_STATE.RUNNABLE, '',
wakeup.ts, args, wakeupDuration));
wakeup = undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53194
|
train
|
function() {
var isSecondaryImport = this.model.getClockSyncRecordsNamed(
'ftrace_importer').length !== 0;
var mSyncs = this.model_.getClockSyncRecordsNamed('monotonic');
// If this is a secondary import, and no clock syncing records were
// found, then abort the import. Otherwise, just skip clock alignment.
if (mSyncs.length == 0)
return isSecondaryImport ? undefined : 0;
// Shift all the slice times based on the sync record.
// TODO(skyostil): Compute a scaling factor if we have multiple clock sync
// records.
var sync = mSyncs[0].args;
// NB: parentTS of zero denotes no times-shift; this is
// used when user and kernel event clocks are identical.
if (sync.parentTS == 0 || sync.parentTS == sync.perfTS)
return 0;
return sync.parentTS - sync.perfTS;
}
|
javascript
|
{
"resource": ""
}
|
|
q53195
|
train
|
function(ts, pid, comm, prio, fromPid) {
// The the pids that get passed in to this function are Linux kernel
// pids, which identify threads. The rest of trace-viewer refers to
// these as tids, so the change of nomenclature happens in the following
// construction of the wakeup object.
this.wakeups_.push({ts: ts, tid: pid, fromTid: fromPid});
}
|
javascript
|
{
"resource": ""
}
|
|
q53196
|
train
|
function(ts, pid, iowait, caller) {
// The the pids that get passed in to this function are Linux kernel
// pids, which identify threads. The rest of trace-viewer refers to
// these as tids, so the change of nomenclature happens in the following
// construction of the wakeup object.
this.blocked_reasons_.push({ts: ts, tid: pid, iowait: iowait,
caller: caller});
}
|
javascript
|
{
"resource": ""
}
|
|
q53197
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase) {
// Check for new-style clock sync records.
var event = /name=(\w+?)\s(.+)/.exec(eventBase.details);
if (event) {
var name = event[1];
var pieces = event[2].split(' ');
var args = {
perfTS: ts
};
for (var i = 0; i < pieces.length; i++) {
var parts = pieces[i].split('=');
if (parts.length != 2)
throw new Error('omgbbq');
args[parts[0]] = parts[1];
}
this.addClockSyncRecord(new ClockSyncRecord(name, ts, args));
return true;
}
// Old-style clock sync records from chromium
event = /parent_ts=(\d+\.?\d*)/.exec(eventBase.details);
if (!event)
return false;
this.addClockSyncRecord(new ClockSyncRecord('monotonic', ts, {
perfTS: ts,
parentTS: event[1] * 1000
}));
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53198
|
train
|
function(eventName, cpuNumber, pid, ts, eventBase,
threadName) {
// Some profiles end up with a \n\ on the end of each line. Strip it
// before we do the comparisons.
eventBase.details = eventBase.details.replace(/\\n.*$/, '');
var event = /^\s*(\w+):\s*(.*)$/.exec(eventBase.details);
if (!event) {
// Check if the event matches events traced by the Android framework
var tag = eventBase.details.substring(0, 2);
if (tag == 'B|' || tag == 'E' || tag == 'E|' || tag == 'X|' ||
tag == 'C|' || tag == 'S|' || tag == 'F|') {
eventBase.subEventName = 'android';
} else {
return false;
}
} else {
eventBase.subEventName = event[1];
eventBase.details = event[2];
}
var writeEventName = eventName + ':' + eventBase.subEventName;
var handler = this.eventHandlers_[writeEventName];
if (!handler) {
this.model_.importWarning({
type: 'parse_error',
message: 'Unknown trace_marking_write event ' + writeEventName
});
return true;
}
return handler(writeEventName, cpuNumber, pid, ts, eventBase, threadName);
}
|
javascript
|
{
"resource": ""
}
|
|
q53199
|
train
|
function() {
this.forEachLine(function(text, eventBase, cpuNumber, pid, ts) {
var eventName = eventBase.eventName;
if (eventName !== 'tracing_mark_write' && eventName !== '0')
return;
if (traceEventClockSyncRE.exec(eventBase.details))
this.traceClockSyncEvent(eventName, cpuNumber, pid, ts, eventBase);
if (realTimeClockSyncRE.exec(eventBase.details)) {
// This entry maps realtime to clock_monotonic; store in the model
// so that importers parsing files with realtime timestamps can
// map this back to monotonic.
var match = realTimeClockSyncRE.exec(eventBase.details);
this.model_.realtime_to_monotonic_offset_ms = ts - match[1];
}
if (genericClockSyncRE.exec(eventBase.details))
this.traceClockSyncEvent(eventName, cpuNumber, pid, ts, eventBase);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.