_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q29100
getCzechForm
train
function getCzechForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) { return 2 } else { return 3 } }
javascript
{ "resource": "" }
q29101
getPolishForm
train
function getPolishForm (c) { if (c === 1) { return 0 } else if (Math.floor(c) !== c) { return 1 } else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2 } else { return 3 } }
javascript
{ "resource": "" }
q29102
getSlavicForm
train
function getSlavicForm (c) { if (Math.floor(c) !== c) { return 2 } else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) { return 0 } else if (c % 10 === 1) { return 1 } else if (c > 1) { return 2 } else { return 0 } }
javascript
{ "resource": "" }
q29103
getLithuanianForm
train
function getLithuanianForm (c) { if (c === 1 || (c % 10 === 1 && c % 100 > 20)) { return 0 } else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) { return 1 } else { return 2 } }
javascript
{ "resource": "" }
q29104
makeDateFromString
train
function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } }
javascript
{ "resource": "" }
q29105
train
function (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = moment.localeData(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } }
javascript
{ "resource": "" }
q29106
train
function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }
javascript
{ "resource": "" }
q29107
weight
train
function weight(kernel, bandwidth, x_0, x_i) { const arg = (x_i - x_0) / bandwidth; return kernel(arg); }
javascript
{ "resource": "" }
q29108
copy
train
function copy(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; }
javascript
{ "resource": "" }
q29109
fromValues
train
function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) { var out = new glMatrix.ARRAY_TYPE(9); out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; return out; }
javascript
{ "resource": "" }
q29110
set
train
function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; return out; }
javascript
{ "resource": "" }
q29111
identity
train
function identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; }
javascript
{ "resource": "" }
q29112
transpose
train
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a01 = a[1], a02 = a[2], a12 = a[5]; out[1] = a[3]; out[2] = a[6]; out[3] = a01; out[5] = a[7]; out[6] = a02; out[7] = a12; } else { out[0] = a[0]; out[1] = a[3]; out[2] = a[6]; out[3] = a[1]; out[4] = a[4]; out[5] = a[7]; out[6] = a[2]; out[7] = a[5]; out[8] = a[8]; } return out; }
javascript
{ "resource": "" }
q29113
multiply
train
function multiply(out, a, b) { var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; var b00 = b[0], b01 = b[1], b02 = b[2]; var b10 = b[3], b11 = b[4], b12 = b[5]; var b20 = b[6], b21 = b[7], b22 = b[8]; out[0] = b00 * a00 + b01 * a10 + b02 * a20; out[1] = b00 * a01 + b01 * a11 + b02 * a21; out[2] = b00 * a02 + b01 * a12 + b02 * a22; out[3] = b10 * a00 + b11 * a10 + b12 * a20; out[4] = b10 * a01 + b11 * a11 + b12 * a21; out[5] = b10 * a02 + b11 * a12 + b12 * a22; out[6] = b20 * a00 + b21 * a10 + b22 * a20; out[7] = b20 * a01 + b21 * a11 + b22 * a21; out[8] = b20 * a02 + b21 * a12 + b22 * a22; return out; }
javascript
{ "resource": "" }
q29114
rotate
train
function rotate(out, a, rad) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], s = Math.sin(rad), c = Math.cos(rad); out[0] = c * a00 + s * a10; out[1] = c * a01 + s * a11; out[2] = c * a02 + s * a12; out[3] = c * a10 - s * a00; out[4] = c * a11 - s * a01; out[5] = c * a12 - s * a02; out[6] = a20; out[7] = a21; out[8] = a22; return out; }
javascript
{ "resource": "" }
q29115
scale
train
function scale(out, a, v) { var x = v[0], y = v[1]; out[0] = x * a[0]; out[1] = x * a[1]; out[2] = x * a[2]; out[3] = y * a[3]; out[4] = y * a[4]; out[5] = y * a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; }
javascript
{ "resource": "" }
q29116
fromMat2d
train
function fromMat2d(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = 0; out[3] = a[2]; out[4] = a[3]; out[5] = 0; out[6] = a[4]; out[7] = a[5]; out[8] = 1; return out; }
javascript
{ "resource": "" }
q29117
projection
train
function projection(out, width, height) { out[0] = 2 / width; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = -2 / height; out[5] = 0; out[6] = -1; out[7] = 1; out[8] = 1; return out; }
javascript
{ "resource": "" }
q29118
str
train
function str(a) { return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')'; }
javascript
{ "resource": "" }
q29119
add
train
function add(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; out[3] = a[3] + b[3]; out[4] = a[4] + b[4]; out[5] = a[5] + b[5]; out[6] = a[6] + b[6]; out[7] = a[7] + b[7]; out[8] = a[8] + b[8]; return out; }
javascript
{ "resource": "" }
q29120
subtract
train
function subtract(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; out[3] = a[3] - b[3]; out[4] = a[4] - b[4]; out[5] = a[5] - b[5]; out[6] = a[6] - b[6]; out[7] = a[7] - b[7]; out[8] = a[8] - b[8]; return out; }
javascript
{ "resource": "" }
q29121
multiplyScalar
train
function multiplyScalar(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; out[3] = a[3] * b; out[4] = a[4] * b; out[5] = a[5] * b; out[6] = a[6] * b; out[7] = a[7] * b; out[8] = a[8] * b; return out; }
javascript
{ "resource": "" }
q29122
multiplyScalarAndAdd
train
function multiplyScalarAndAdd(out, a, b, scale) { out[0] = a[0] + b[0] * scale; out[1] = a[1] + b[1] * scale; out[2] = a[2] + b[2] * scale; out[3] = a[3] + b[3] * scale; out[4] = a[4] + b[4] * scale; out[5] = a[5] + b[5] * scale; out[6] = a[6] + b[6] * scale; out[7] = a[7] + b[7] * scale; out[8] = a[8] + b[8] * scale; return out; }
javascript
{ "resource": "" }
q29123
equals
train
function equals(a, b) { var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7], a8 = a[8]; var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8]; return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); }
javascript
{ "resource": "" }
q29124
add
train
function add(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; return out; }
javascript
{ "resource": "" }
q29125
subtract
train
function subtract(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; return out; }
javascript
{ "resource": "" }
q29126
multiply
train
function multiply(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; out[2] = a[2] * b[2]; return out; }
javascript
{ "resource": "" }
q29127
ceil
train
function ceil(out, a) { out[0] = Math.ceil(a[0]); out[1] = Math.ceil(a[1]); out[2] = Math.ceil(a[2]); return out; }
javascript
{ "resource": "" }
q29128
floor
train
function floor(out, a) { out[0] = Math.floor(a[0]); out[1] = Math.floor(a[1]); out[2] = Math.floor(a[2]); return out; }
javascript
{ "resource": "" }
q29129
round
train
function round(out, a) { out[0] = Math.round(a[0]); out[1] = Math.round(a[1]); out[2] = Math.round(a[2]); return out; }
javascript
{ "resource": "" }
q29130
scale
train
function scale(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; return out; }
javascript
{ "resource": "" }
q29131
hermite
train
function hermite(out, a, b, c, d, t) { var factorTimes2 = t * t; var factor1 = factorTimes2 * (2 * t - 3) + 1; var factor2 = factorTimes2 * (t - 2) + t; var factor3 = factorTimes2 * (t - 1); var factor4 = factorTimes2 * (3 - 2 * t); out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; return out; }
javascript
{ "resource": "" }
q29132
rotate
train
function rotate(out, a, b, c) { //Translate point to the origin var p0 = a[0] - b[0], p1 = a[1] - b[1], sinC = Math.sin(c), cosC = Math.cos(c); //perform rotation and translate to correct position out[0] = p0 * cosC - p1 * sinC + b[0]; out[1] = p0 * sinC + p1 * cosC + b[1]; return out; }
javascript
{ "resource": "" }
q29133
angle
train
function angle(a, b) { var x1 = a[0], y1 = a[1], x2 = b[0], y2 = b[1]; var len1 = x1 * x1 + y1 * y1; if (len1 > 0) { //TODO: evaluate use of glm_invsqrt here? len1 = 1 / Math.sqrt(len1); } var len2 = x2 * x2 + y2 * y2; if (len2 > 0) { //TODO: evaluate use of glm_invsqrt here? len2 = 1 / Math.sqrt(len2); } var cosine = (x1 * x2 + y1 * y2) * len1 * len2; if (cosine > 1.0) { return 0; } else if (cosine < -1.0) { return Math.PI; } else { return Math.acos(cosine); } }
javascript
{ "resource": "" }
q29134
flatten
train
function flatten(arr) { if (!isArray(arr)) { return arr; } var result = []; each(arr, function (item) { if (isArray(item)) { each(item, function (subItem) { result.push(subItem); }); } else { result.push(item); } }); return result; }
javascript
{ "resource": "" }
q29135
pick
train
function pick(object, keys) { if (object === null || !isPlaineObject(object)) { return {}; } var result = {}; each(keys, function (key) { if (hasOwnProperty.call(object, key)) { result[key] = object[key]; } }); return result; }
javascript
{ "resource": "" }
q29136
getPath
train
function getPath(cfg, smooth) { var path = void 0; var points = cfg.points; var isInCircle = cfg.isInCircle; var first = points[0]; if (Util.isArray(first.y)) { path = getRangePath(points, smooth, isInCircle, cfg); } else { path = getSinglePath(points, smooth, isInCircle, cfg); } return path; }
javascript
{ "resource": "" }
q29137
hrtimer
train
function hrtimer() { const start = process.hrtime(); return () => { const durationComponents = process.hrtime(start); const seconds = durationComponents[0]; const nanoseconds = durationComponents[1]; const duration = (seconds * 1000) + (nanoseconds / 1E6); return duration; }; }
javascript
{ "resource": "" }
q29138
sanitizeTags
train
function sanitizeTags(value, telegraf) { const blacklist = telegraf ? /:|\|/g : /:|\||@|,/g; // Replace reserved chars with underscores. return String(value).replace(blacklist, '_'); }
javascript
{ "resource": "" }
q29139
formatTags
train
function formatTags(tags, telegraf) { if (Array.isArray(tags)) { return tags; } else { return Object.keys(tags).map(key => { return `${sanitizeTags(key, telegraf)}:${sanitizeTags(tags[key], telegraf)}`; }); } }
javascript
{ "resource": "" }
q29140
formatDate
train
function formatDate(date) { let timestamp; if (date instanceof Date) { // Datadog expects seconds. timestamp = Math.round(date.getTime() / 1000); } else if (date instanceof Number) { // Make sure it is an integer, not a float. timestamp = Math.round(date); } return timestamp; }
javascript
{ "resource": "" }
q29141
intToIP
train
function intToIP(int) { const part1 = int & 255; const part2 = ((int >> 8) & 255); const part3 = ((int >> 16) & 255); const part4 = ((int >> 24) & 255); return `${part4}.${part3}.${part2}.${part1}`; }
javascript
{ "resource": "" }
q29142
getDefaultRoute
train
function getDefaultRoute() { try { const fileContents = fs.readFileSync('/proc/net/route', 'utf8'); // eslint-disable-line no-sync const routes = fileContents.split('\n'); for (const routeIdx in routes) { const fields = routes[routeIdx].trim().split('\t'); if (fields[1] === '00000000') { const address = fields[2]; // Convert to little endian by splitting every 2 digits and reversing that list const littleEndianAddress = address.match(/.{2}/g).reverse().join(''); return intToIP(parseInt(littleEndianAddress, 16)); } } } catch (e) { console.error('Could not get default route from /proc/net/route'); } return null; }
javascript
{ "resource": "" }
q29143
onSend
train
function onSend(error, bytes) { completed += 1; if (calledback) { return; } if (error) { if (typeof callback === 'function') { calledback = true; callback(error); } else if (self.errorHandler) { calledback = true; self.errorHandler(error); } return; } if (bytes) { sentBytes += bytes; } if (completed === stat.length && typeof callback === 'function') { callback(null, sentBytes); } }
javascript
{ "resource": "" }
q29144
getBuildGradlePath
train
function getBuildGradlePath() { var target = path.join("platforms", "android", "app", "build.gradle"); if (fs.existsSync(target)) { return target; } return path.join("platforms", "android", "build.gradle"); }
javascript
{ "resource": "" }
q29145
train
function(platform) { var platformConfigPath = path.join("..", "..", "..", platform + ".json"); var platformConfig = require(platformConfigPath); var pluginId = this.getPluginId(); var apiKey = platformConfig.installed_plugins[pluginId].FABRIC_API_KEY; var apiSecret = platformConfig.installed_plugins[pluginId].FABRIC_API_SECRET; var config = { apiKey: apiKey, apiSecret: apiSecret }; return config; }
javascript
{ "resource": "" }
q29146
json2html
train
function json2html(json, options) { var html = ''; if (typeof json === 'string') { // Escape tags json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); if (options.withLinks && isUrl(json)) { html += '<a href="' + json + '" class="json-string" target="_blank">' + json + '</a>'; } else { html += '<span class="json-string">"' + json + '"</span>'; } } else if (typeof json === 'number') { html += '<span class="json-literal">' + json + '</span>'; } else if (typeof json === 'boolean') { html += '<span class="json-literal">' + json + '</span>'; } else if (json === null) { html += '<span class="json-literal">null</span>'; } else if (json instanceof Array) { if (json.length > 0) { html += '[<ol class="json-array">'; for (var i = 0; i < json.length; ++i) { html += '<li>'; // Add toggle button if item is collapsable if (isCollapsable(json[i])) { html += '<a href class="json-toggle"></a>'; } html += json2html(json[i], options); // Add comma if item is not last if (i < json.length - 1) { html += ','; } html += '</li>'; } html += '</ol>]'; } else { html += '[]'; } } else if (typeof json === 'object') { var key_count = Object.keys(json).length; if (key_count > 0) { html += '{<ul class="json-dict">'; for (var key in json) { if (json.hasOwnProperty(key)) { html += '<li>'; var keyRepr = options.withQuotes ? '<span class="json-string">"' + key + '"</span>' : key; // Add toggle button if item is collapsable if (isCollapsable(json[key])) { html += '<a href class="json-toggle">' + keyRepr + '</a>'; } else { html += keyRepr; } html += ': ' + json2html(json[key], options); // Add comma if item is not last if (--key_count > 0) { html += ','; } html += '</li>'; } } html += '</ul>}'; } else { html += '{}'; } } return html; }
javascript
{ "resource": "" }
q29147
train
function () { return _.map([].concat(this.pkgs, this.devPkgs), function (pkg) { return path.join(pkg.path, "node_modules/.bin"); }); }
javascript
{ "resource": "" }
q29148
train
function () { var pkgs = this.pkgs; var configNames = _.chain(pkgs) .map(function (pkg) { return _.keys(pkg.config); }) .flatten() .uniq() .value(); // Take "first" config value in arrays as "winning" value. return _.chain(configNames) .map(function (name) { return [name, _.find(pkgs, function (pkg) { return _.has(pkg.config, name); }).config[name]]; }) // Object. .reduce(function (memo, pair) { memo[pair[0]] = pair[1]; return memo; }, {}) .value(); }
javascript
{ "resource": "" }
q29149
train
function (flagKey) { var flags = _.isUndefined(flagKey) ? FLAGS.general : FLAGS[flagKey]; return !flags ? "" : _.map(flags, function (val, key) { return chalk.cyan("--" + key) + ": " + val.desc; }).join("\n\n "); }
javascript
{ "resource": "" }
q29150
train
function(url, org, space) { var targetObject = { 'Url': url }; if (org) targetObject.Org = org; if (space) targetObject.Space = space; return this._xhrV1("POST", require.toUrl("cfapi/target"), targetObject); }
javascript
{ "resource": "" }
q29151
train
function(target, name, contentLocation, manifest, packager, instrumentation) { var pushReq = {}; if (name) pushReq.Name = name; if (contentLocation) pushReq.ContentLocation = contentLocation; if (target) pushReq.Target = target; if(manifest) pushReq.Manifest = manifest; if(packager) pushReq.Packager = packager; if(instrumentation) pushReq.Instrumentation = instrumentation; return this._xhrV1("PUT", require.toUrl("cfapi/apps"), pushReq); }
javascript
{ "resource": "" }
q29152
TextModel
train
function TextModel(text, lineDelimiter) { this._lastLineIndex = -1; this._text = [""]; this._lineOffsets = [0]; this.setText(text); this.setLineDelimiter(lineDelimiter); }
javascript
{ "resource": "" }
q29153
train
function() { var count = 0; for (var i = 0; i<this._text.length; i++) { count += this._text[i].length; } return count; }
javascript
{ "resource": "" }
q29154
getBundles
train
function getBundles(buildObj) { var _self = self; var bundles = (buildObj.bundles || []); return bundles.map(function(bundle) { bundle = project.replaceProperties(bundle); var dir = project.resolveFile(bundle + Packages.java.io.File.separator + "web"); if (!dir.exists() || !dir.isDirectory()) { _self.log("Bundle folder " + dir.getPath() + " does not exist", Project.MSG_WARN); return null; } _self.log("Found bundle web folder: " + dir.getPath()); return { bundle: bundle, web: dir }; }).filter(function(b) { return !!b; }); }
javascript
{ "resource": "" }
q29155
train
function() { if (this.textView) { this.textView.removeEventListener("ModelChanging", this.listener.onModelChanging); this.textView.removeEventListener("ModelChanged", this.listener.onModelChanged); this.textView.removeEventListener("Destroy", this.listener.onDestroy); this.textView.removeEventListener("LineStyle", this.listener.onLineStyle); this.textView = null; } if (this.services) { for (var i = 0; i < this.services.length; i++) { this.removeServiceListener(this.services[i]); } this.services = null; } if (this.serviceRegistry) { this.serviceRegistry.removeEventListener("registered", this.listener.onServiceAdded); this.serviceRegistry.removeEventListener("unregistering", this.listener.onServiceRemoved); this.serviceRegistry = null; } this.listener = null; this.lineStyles = null; }
javascript
{ "resource": "" }
q29156
sendStatus
train
function sendStatus(code, res){ try{ if (httpCodeMapping) { code = mapHttpStatusCode(code); } addStrictTransportHeaders(res); setResponseNoCache(res); return res.sendStatus(code); }catch(err){ logger.error(res.req.originalUrl , err.message); throw err; } }
javascript
{ "resource": "" }
q29157
writeResponse
train
function writeResponse(code, res, headers, body, needEncodeLocation, noCachedStringRes) { try{ if (res.headerSent) { logger.error("header Sent:", res.req.method, res.req.originalUrl); } if (typeof code === 'number') { if (httpCodeMapping) { code = mapHttpStatusCode(code); } res.status(code); } if (headers && typeof headers === 'object') { Object.keys(headers).forEach(function(header) { var value = headers[header]; res.setHeader( header.replace(REGEX_CRLF, ""), typeof value === "string" ? value.replace(REGEX_CRLF, "") : value ); }); } addStrictTransportHeaders(res); if (typeof body !== 'undefined') { if (typeof body === 'object') { needEncodeLocation && encodeLocation(body); setResponseNoCache(res); return res.json(body); } if (noCachedStringRes){ setResponseNoCache(res); } res.send(body); } else { setResponseNoCache(res); res.end(); } } catch(err) { logger.error(res.req.originalUrl, err.message); throw err; } }
javascript
{ "resource": "" }
q29158
writeError
train
function writeError(code, res, msg) { try{ if (res.headerSent) { logger.error("header Sent:", res.req.method, res.req.originalUrl); } if (httpCodeMapping) { code = mapHttpStatusCode(code); } msg = msg instanceof Error ? msg.message : msg; addStrictTransportHeaders(res); setResponseNoCache(res); if (typeof msg === 'string') { var err = JSON.stringify({Severity: "Error", Message: msg}); res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Length', err.length); res.writeHead(code); res.end(err); } else { res.writeHead(code); res.end(); } }catch(err){ logger.error(res.req.originalUrl , err.message); throw err; } }
javascript
{ "resource": "" }
q29159
train
function(annotationModel, start, end) { var iter = annotationModel.getAnnotations(start, end); var annotation, annotations = []; while (iter.hasNext()) { annotation = iter.next(); if (!this.isAnnotationTypeVisible(annotation.type)) { continue; } annotations.push(annotation); } var self = this; annotations.sort(function(a, b) { return self.getAnnotationTypePriority(a.type) - self.getAnnotationTypePriority(b.type); }); return annotations; }
javascript
{ "resource": "" }
q29160
train
function(type) { if (this.getAnnotationTypePriority(type) === 0) return false; return !this._visibleAnnotationTypes || this._visibleAnnotationTypes[type] === undefined || this._visibleAnnotationTypes[type] === true; }
javascript
{ "resource": "" }
q29161
train
function(type, visible) { if (typeof type === "object") { this._visibleAnnotationTypes = type; } else { if (!this._visibleAnnotationTypes) this._visibleAnnotationTypes = {}; this._visibleAnnotationTypes[type] = visible; } }
javascript
{ "resource": "" }
q29162
AnnotationModel
train
function AnnotationModel(textModel) { this._annotations = []; var self = this; this._listener = { onChanged: function(modelChangedEvent) { self._onChanged(modelChangedEvent); } }; this.setTextModel(textModel); }
javascript
{ "resource": "" }
q29163
train
function(textModel) { if (this._model) { this._model.removeEventListener("Changed", this._listener.onChanged); //$NON-NLS-0$ } this._model = textModel; if (this._model) { this._model.addEventListener("Changed", this._listener.onChanged); //$NON-NLS-0$ } }
javascript
{ "resource": "" }
q29164
AnnotationStyler
train
function AnnotationStyler (view, annotationModel) { this._view = view; this._annotationModel = annotationModel; var self = this; this._listener = { onDestroy: function(e) { self._onDestroy(e); }, onLineStyle: function(e) { self._onLineStyle(e); }, onChanged: function(e) { self._onAnnotationModelChanged(e); } }; view.addEventListener("Destroy", this._listener.onDestroy); //$NON-NLS-0$ view.addEventListener("postLineStyle", this._listener.onLineStyle); //$NON-NLS-0$ annotationModel.addEventListener("Changed", this._listener.onChanged); //$NON-NLS-0$ }
javascript
{ "resource": "" }
q29165
train
function(name, color, location, displayedLocation, editing) { this.name = name; this.color = color; // Remove trailing "/" if(location.substr(-1) === '/') { location = location.substr(0, location.length - 1); } this.location = location; this.displayedLocation = displayedLocation || location; this.editing = editing; }
javascript
{ "resource": "" }
q29166
train
function(model, callback) { var self = this; model.getRoot(function(root) { // Find the existing ID reversely var location = self.location; while (location.length > 0) { // Create a fake item // NOTE: it's a hack because we don't have any efficient // way to get the actual file node. Instead, we have // to do it recursively starting from the root. If // you find anything wierd happens, change it to the // actual item object. var item = { Location: location }; var id = model.getId(item); // Test if this element exists var exists = !!document.getElementById(id); if (exists) { callback(id); return; } // Not found. This probably means this item is collapsed. // Try to find one level upper. // Here I assume every url starts from "/" location = location.substr(0, location.lastIndexOf('/')); } // Nothing found callback(''); }); }
javascript
{ "resource": "" }
q29167
train
function() { var element = document.createElement('div'); element.innerHTML = mUIUtils.getNameInitial(this.name); element.style.backgroundColor = this.color; element.classList.add('collabAnnotation'); if (this.editing) { element.classList.add('collabEditing'); } return element; }
javascript
{ "resource": "" }
q29168
train
function(kb) { if (!kb) { return false; } if (this.keyCode !== kb.keyCode) { return false; } if (this.mod1 !== kb.mod1) { return false; } if (this.mod2 !== kb.mod2) { return false; } if (this.mod3 !== kb.mod3) { return false; } if (this.mod4 !== kb.mod4) { return false; } if (this.type !== kb.type) { return false; } return true; }
javascript
{ "resource": "" }
q29169
train
function(kb) { if (!kb.keys) { return false; } if (kb.keys.length !== this.keys.length) { return false; } for (var i=0; i<kb.keys.length; i++) { if (!kb.keys[i].equals(this.keys[i])) { return false; } } return true; }
javascript
{ "resource": "" }
q29170
train
function(category) { var settingsMap = this.settingsMap; var pids = typeof category === 'string' ? this.categories[category] : Object.keys(settingsMap); //$NON-NLS-0$ if (!pids) { return []; } return pids.map(function(pid) { return settingsMap[pid]; }); }
javascript
{ "resource": "" }
q29171
train
function(category) { var settings = this.getSettings(category); for (var i = 0; i < settings.length; i++){ var label = settings[i].getCategoryLabel(); if (label) { return label; } } return null; }
javascript
{ "resource": "" }
q29172
train
function(client, socket) { OrionSocketAdapter.call(this, client); var self = this; this.socket = socket; this.authenticated = false; // Register incoming message handler this.socket.addEventListener('message', function(e) { self._onMessage(JSON.parse(e.data)); }); }
javascript
{ "resource": "" }
q29173
Reference
train
function Reference(ident, scope, flag,writeExpr, maybeImplicitGlobal, partial, init) { /** * Identifier syntax node. * @member {esprima#Identifier} Reference#identifier */ this.identifier = ident; /** * Reference to the enclosing Scope. * @member {Scope} Reference#from */ this.from = scope; /** * Whether the reference comes from a dynamic scope (such as 'eval', * 'with', etc.), and may be trapped by dynamic scopes. * @member {boolean} Reference#tainted */ this.tainted = false; /** * The variable this reference is resolved with. * @member {Variable} Reference#resolved */ this.resolved = null; /** * The read-write mode of the reference. (Value is one of {@link * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). * @member {number} Reference#flag * @private */ this.flag = flag; if (this.isWrite()) { /** * If reference is writeable, this is the tree being written to it. * @member {esprima#Node} Reference#writeExpr */ this.writeExpr = writeExpr; /** * Whether the Reference might refer to a partial value of writeExpr. * @member {boolean} Reference#partial */ this.partial = partial; /** * Whether the Reference is to write of initialization. * @member {boolean} Reference#init */ this.init = init; } this.__maybeImplicitGlobal = maybeImplicitGlobal; }
javascript
{ "resource": "" }
q29174
analyze
train
function analyze(tree, providedOptions) { var scopeManager, referencer, options; options = updateDeeply(defaultOptions(), providedOptions); scopeManager = new ScopeManager(options); referencer = new Referencer(options, scopeManager); referencer.visit(tree); if(scopeManager.__currentScope !== null) { throw new Error('currentScope should be null.'); } return scopeManager; }
javascript
{ "resource": "" }
q29175
addProject
train
function addProject(project) { var hub = generateUniqueHubId(); //TODO Also add name of project owner? Replace by projectJSON all over the file. var query = sharedProject.findOne({location: project}); return query.exec() .then(function(doc) { return doc ? Promise.resolve(doc) : sharedProject.create({location: project, hubid: hub}); }); }
javascript
{ "resource": "" }
q29176
removeProject
train
function removeProject(project) { return sharedProject.findOne({'location': project}).exec() .then(function(doc) { if (doc.users.length > 0) { return userProjectsCollection.removeProjectReferences(doc.users, project).exec(); } }) .then(function() { return sharedProject.remove({location: project}).exec(); }); }
javascript
{ "resource": "" }
q29177
generateUniqueHubId
train
function generateUniqueHubId() { //TODO ensure generated hub id is unique (not in db) // do { var length = 10; var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV0123456789'; var s = ''; for (var i=0; i<length; i++) { s += letters.charAt(Math.floor(Math.random() * letters.length)); } // } while (s == 0); //TODO actually check in db for value existence return s; }
javascript
{ "resource": "" }
q29178
getUsersInProject
train
function getUsersInProject(project) { return sharedProject.findOne({'location': project}).exec() .then(function(doc) { return doc ? doc.users : undefined; }); }
javascript
{ "resource": "" }
q29179
addUserToProject
train
function addUserToProject(user, project) { return addProject(project) .then(function(doc) { if (doc.users.indexOf(user) === -1) { return sharedProject.findOneAndUpdate({'location': project}, {$addToSet: {'users': user} }, { safe: true, w: 'majority' }).exec(); } }); // return sharedProject.findOne({'location': project}).exec() // .then(function(doc) { // if (!doc) { // return addProject(project); // } else { // return Promise.resolve(doc); // } // }).then(function(doc) { // if (doc.users.indexOf(user) === -1) { // return sharedProject.findOneAndUpdate({'location': project}, {$addToSet: {'users': user} }, { // safe: true, // w: 'majority' // }).exec(); // } // }); }
javascript
{ "resource": "" }
q29180
removeUserFromProject
train
function removeUserFromProject(user, project) { return sharedProject.findOne({'location': project}).exec() .then(function(doc) { return sharedProject.findOneAndUpdate({'location': project}, {$pull: {'users': { $in: [user]}} }, { safe: true, w: 'majority' }).exec(); }); }
javascript
{ "resource": "" }
q29181
EditorView
train
function EditorView(options) { this._parent = options.parent; if(typeof this._parent === "string") { this._parent = document.getElementById(options.parent); } this.id = options.id || ""; this.activateContext = options.activateContext; this.renderToolbars = options.renderToolbars; this.serviceRegistry = options.serviceRegistry; this.contentTypeRegistry = options.contentTypeRegistry; this.commandRegistry = options.commandRegistry; this.progress = options.progress; this.statusService = options.statusService; this.editorCommands = options.editorCommands; this.fileClient = options.fileService; this.inputManager = options.inputManager; this.preferences = options.preferences; this.readonly = options.readonly; this.singleMode = options.singleMode; this.searcher = options.searcher; this.statusReporter = options.statusReporter; this.model = options.model; this.undoStack = options.undoStack; this.problemsServiceID = options.problemsServiceID || "orion.core.marker"; //$NON-NLS-0$ this.editContextServiceID = options.editContextServiceID || "orion.edit.context"; //$NON-NLS-0$ this.syntaxHighlighter = new Highlight.SyntaxHighlighter(this.serviceRegistry); var keyAssist = mGlobalCommands.getKeyAssist ? mGlobalCommands.getKeyAssist() : null; if(keyAssist) { keyAssist.addProvider(this.editorCommands); } var mainSplitter = mGlobalCommands.getMainSplitter ? mGlobalCommands.getMainSplitter() : null; if(mainSplitter) { mainSplitter.splitter.addEventListener("resize", function (evt) { if (this.editor && evt.node === mainSplitter.main) { this.editor.resize(); } }.bind(this)); } if(mGlobalCommands.getGlobalEventTarget) { mGlobalCommands.getGlobalEventTarget().addEventListener("toggleTrim", function() { if (this.editor) { this.editor.resize(); } }.bind(this)); } this.settings = {}; this._editorConfig = options.editorConfig; this._init(); }
javascript
{ "resource": "" }
q29182
train
function(node) { var lhs = node.left, affectsProto; if (lhs.type !== "MemberExpression" || lhs.object.type !== "MemberExpression") { return; } affectsProto = lhs.object.computed ? lhs.object.property.type === "Literal" && lhs.object.property.value === "prototype" : lhs.object.property.name === "prototype"; if (!affectsProto) { return; } modifiedBuiltins.forEach(function(builtin) { if (lhs.object.object.name === builtin) { context.report(node, ProblemMessages.noExtendNative, {builtin: builtin}); } }); }
javascript
{ "resource": "" }
q29183
isValidExpression
train
function isValidExpression(node) { if (allowTernary) { // Recursive check for ternary and logical expressions if (node.type === "ConditionalExpression") { return isValidExpression(node.consequent) && isValidExpression(node.alternate); } } if (allowShortCircuit) { if (node.type === "LogicalExpression") { return isValidExpression(node.right); } } return /^(?:Assignment|Call|New|Update|Yield)Expression$/.test(node.type) || (node.type === "UnaryExpression" && ["delete", "void"].indexOf(node.operator) >= 0); }
javascript
{ "resource": "" }
q29184
OutputTerminal
train
function OutputTerminal(options, components) { this.element = components.element; this.requisition = components.requisition; this.requisition.commandOutputManager.onOutput.add(this.outputted, this); var document = components.element.ownerDocument; if (outputViewCss != null) { this.style = util.importCss(outputViewCss, document, 'gcli-output-view'); } this.template = util.toDom(document, outputViewHtml); this.templateOptions = { allowEval: true, stack: 'output_terminal.html' }; }
javascript
{ "resource": "" }
q29185
OutputView
train
function OutputView(outputData, outputTerminal) { this.outputData = outputData; this.outputTerminal = outputTerminal; this.url = util.createUrlLookup(module); // Elements attached to this by template(). this.elems = { rowin: null, rowout: null, hide: null, show: null, duration: null, throb: null, prompt: null }; var template = this.outputTerminal.template.cloneNode(true); domtemplate.template(template, this, this.outputTerminal.templateOptions); this.outputTerminal.element.appendChild(this.elems.rowin); this.outputTerminal.element.appendChild(this.elems.rowout); this.outputData.onClose.add(this.closed, this); this.outputData.onChange.add(this.changed, this); }
javascript
{ "resource": "" }
q29186
getOptions
train
function getOptions(serviceRegistry, serviceID) { var options = Object.create(null); getReferences(serviceRegistry, serviceID).forEach(function(serviceRef) { serviceRef.getPropertyKeys().forEach(function(key) { if (key !== "service.id" && key !== "service.names" && key !== "objectClass") //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$ options[key] = serviceRef.getProperty(key); }); }); return options; }
javascript
{ "resource": "" }
q29187
Display
train
function Display(options) { var doc = options.document || document; this.displayStyle = undefined; if (displayCss != null) { this.displayStyle = util.importCss(displayCss, doc, 'gcli-css-display'); } // Configuring the document is complex because on the web side, there is an // active desire to have nothing to configure, where as when embedded in // Firefox there could be up to 4 documents, some of which can/should be // derived from some root element. // When a component uses a document to create elements for use under a known // root element, then we pass in the element (if we have looked it up // already) or an id/document this.commandOutputManager = options.commandOutputManager; if (this.commandOutputManager == null) { this.commandOutputManager = new CommandOutputManager(); } this.requisition = new Requisition(options.environment || {}, doc, this.commandOutputManager); this.focusManager = new FocusManager(options, { document: doc, requisition: this.requisition }); this.inputElement = find(doc, options.inputElement || null, 'gcli-input'); this.inputter = new Inputter(options, { requisition: this.requisition, focusManager: this.focusManager, element: this.inputElement }); // autoResize logic: we want Completer to keep the elements at the same // position if we created the completion element, but if someone else created // it, then it's their job. this.completeElement = insert(this.inputElement, options.completeElement || null, 'gcli-row-complete'); this.completer = new Completer(options, { requisition: this.requisition, inputter: this.inputter, autoResize: this.completeElement.gcliCreated, element: this.completeElement }); this.prompt = new Prompt(options, { inputter: this.inputter, element: insert(this.inputElement, options.promptElement || null, 'gcli-prompt') }); this.element = find(doc, options.displayElement || null, 'gcli-display'); this.element.classList.add('gcli-display'); this.template = util.toDom(doc, displayHtml); this.elements = {}; domtemplate.template(this.template, this.elements, { stack: 'display.html' }); this.element.appendChild(this.template); this.tooltip = new Tooltip(options, { requisition: this.requisition, inputter: this.inputter, focusManager: this.focusManager, element: this.elements.tooltip, panelElement: this.elements.panel }); this.inputter.tooltip = this.tooltip; this.outputElement = util.createElement(doc, 'div'); this.outputElement.classList.add('gcli-output'); this.outputList = new OutputTerminal(options, { requisition: this.requisition, element: this.outputElement }); this.element.appendChild(this.outputElement); intro.maybeShowIntro(this.commandOutputManager, this.requisition); }
javascript
{ "resource": "" }
q29188
find
train
function find(doc, element, id) { if (!element) { element = doc.getElementById(id); if (!element) { throw new Error('Missing element, id=' + id); } } return element; }
javascript
{ "resource": "" }
q29189
insert
train
function insert(sibling, element, id) { var doc = sibling.ownerDocument; if (!element) { element = doc.getElementById('gcli-row-complete'); if (!element) { element = util.createElement(doc, 'div'); sibling.parentNode.insertBefore(element, sibling.nextSibling); element.gcliCreated = true; } } return element; }
javascript
{ "resource": "" }
q29190
train
function(node) { this.currentNode = node; // Updates the code path due to node's position in its parent node. if (node.parent) { preprocess(this, node); } // Updates the code path. // And emits onCodePathStart/onCodePathSegmentStart events. processCodePathToEnter(this, node); // Emits node events. this.original.enterNode(node); this.currentNode = null; }
javascript
{ "resource": "" }
q29191
train
function(node) { this.currentNode = node;// Updates the code path. // And emits onCodePathStart/onCodePathSegmentStart events. processCodePathToExit(this, node); // Emits node events. this.original.leaveNode(node); // Emits the last onCodePathStart/onCodePathSegmentStart events. postprocess(this, node); this.currentNode = null; }
javascript
{ "resource": "" }
q29192
train
function(fromSegment, toSegment) { if (fromSegment.reachable && toSegment.reachable) { this.emitter.emit( "onCodePathSegmentLoop", fromSegment, toSegment, this.currentNode ); } }
javascript
{ "resource": "" }
q29193
isAdmin
train
function isAdmin(options, username) { return (options.configParams.get("orion.auth.user.creation") || "").split(",").some(function(user) { return user === username; }); }
javascript
{ "resource": "" }
q29194
userJSON
train
function userJSON(user, options) { return { FullName: user.fullname, UserName: user.username, Location: api.join(options.usersRoot, user.username), Email: user.email, EmailConfirmed: emailConfirmed(user), HasPassword: true, OAuth: user.oauth || undefined, LastLoginTimestamp: user.login_timestamp ? user.login_timestamp.getTime() : 0, DiskUsageTimestamp: user.disk_usage_timestamp ? user.disk_usage_timestamp.getTime() : 0, DiskUsage: user.disk_usage || 0 , jwt: user.jwt }; }
javascript
{ "resource": "" }
q29195
oauth
train
function oauth(id, username, email, req, done) { if (req.params["0"] === "/link") { return done(null, { __linkUser: true, email: email, username: username, id: id }); } fileUtil.getMetastoreSafe(req).then(function(store) { store.getUserByOAuth(id, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, { __newUser: true, email: email, username: username, id: id }); } done(null, user); }, function noMetastore(err) { done(err); }); }); }
javascript
{ "resource": "" }
q29196
configureGithubOAuth
train
function configureGithubOAuth(app, options) { if (options.configParams.get("orion.oauth.github.client")) { const GithubStrategy = require('passport-github2').Strategy; passport.use(new GithubStrategy({ clientID: options.configParams.get("orion.oauth.github.client"), clientSecret: options.configParams.get("orion.oauth.github.secret"), passReqToCallback: true, callbackURL: (options.configParams.get("orion.auth.host") || "") + "/auth/github/callback", scope: "user:email" }, /* @callback */ function(req, accessToken, refreshToken, profile, done) { const email = profile.emails[0].value; oauth(profile.provider + "/" + profile.id, profile.username, email, req, done); })); app.get('/login/oauth/github', options.basicMiddleware, passport.authenticate('github')); app.get('/mixlogin/manageoauth/oauth/github', options.basicMiddleware, passport.authenticate('github', {callbackURL: (options.configParams.get("orion.auth.host") || "") + "/auth/github/callback/link"})); app.get('/auth/github/callback*', options.basicMiddleware, function(req, res) { return passport.authenticate('github', {callbackURL: (options.configParams.get("orion.auth.host") || "") + "/auth/github/callback" + (req.params["0"] || "")}, /* @callback */ function(err, user, info){ createNewUser(req,res,err,user, options); })(req,res); }); } }
javascript
{ "resource": "" }
q29197
checkUserAccess
train
function checkUserAccess(req, res, next) { const isadmin = isAdmin(options, req.user.username); if (!req.user || !(req.params.id === req.user.username || isadmin)) { return api.writeResponse(403, res); } const contextPath = options.configParams.get("orion.context.path") || "", listenContextPath = options.configParams.get("orion.context.listenPath") || false, uri = url.parse(req.originalUrl.substring(listenContextPath ? contextPath.length : 0)).pathname; if(isadmin) { return next(); } checkRights(req.user.username, uri, req, res, next); }
javascript
{ "resource": "" }
q29198
train
function() { var combined = Status.VALID; for (var i = 0; i < arguments.length; i++) { var status = arguments[i]; if (Array.isArray(status)) { status = Status.combine.apply(null, status); } if (status > combined) { combined = status; } } return combined; }
javascript
{ "resource": "" }
q29199
train
function(options, callback) { if (typeof options === "function") { callback = options; options = null; } options = options || {}; var startSegment = options.first || this.internal.initialSegment; var lastSegment = options.last; var item = null; var index = 0; var end = 0; var segment = null; var visited = Object.create(null); var stack = [ [startSegment, 0] ]; var skippedSegment = null; var broken = false; var controller = { skip: function() { if (stack.length <= 1) { broken = true; } else { skippedSegment = stack[stack.length - 2][0]; } }, break: function() { broken = true; } }; /** * Checks a given previous segment has been visited. * @param {CodePathSegment} prevSegment - A previous segment to check. * @returns {boolean} `true` if the segment has been visited. */ function isVisited(prevSegment) { return visited[prevSegment.id] || segment.isLoopedPrevSegment(prevSegment); } while (stack.length > 0) { item = stack[stack.length - 1]; segment = item[0]; index = item[1]; if (index === 0) { // Skip if this segment has been visited already. if (visited[segment.id]) { stack.pop(); continue; } // Skip if all previous segments have not been visited. if (segment !== startSegment && segment.prevSegments.length > 0 && !segment.prevSegments.every(isVisited) ) { stack.pop(); continue; } // Reset the flag of skipping if all branches have been skipped. if (skippedSegment && segment.prevSegments.indexOf(skippedSegment) !== -1) { skippedSegment = null; } visited[segment.id] = true; // Call the callback when the first time. if (!skippedSegment) { callback.call(this, segment, controller); // eslint-disable-line callback-return if (segment === lastSegment) { controller.skip(); } if (broken) { break; } } } // Update the stack. end = segment.nextSegments.length - 1; if (index < end) { item[1] += 1; stack.push([segment.nextSegments[index], 0]); } else if (index === end) { item[0] = segment.nextSegments[index]; item[1] = 0; } else { stack.pop(); } } }
javascript
{ "resource": "" }