_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q54700
|
train
|
function (column, cb) {
var ret = new Promise();
this.__aggregateDataset()
.select(sql.min(this.stringToIdentifier(column)).as("v1"), sql.max(this.stringToIdentifier(column)).as("v2"))
.first()
.chain(function (r) {
ret.callback(r.v1, r.v2);
}, ret.errback);
return ret.classic(cb).promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q54701
|
train
|
function (includeColumnTitles, cb) {
var n = this.naked();
if (isFunction(includeColumnTitles)) {
cb = includeColumnTitles;
includeColumnTitles = true;
}
includeColumnTitles = isBoolean(includeColumnTitles) ? includeColumnTitles : true;
return n.columns.chain(function (cols) {
var vals = [];
if (includeColumnTitles) {
vals.push(cols.join(", "));
}
return n.forEach(function (r) {
vals.push(cols.map(function (c) {
return r[c] || "";
}).join(", "));
}).chain(function () {
return vals.join("\r\n") + "\r\n";
});
}.bind(this)).classic(cb).promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q54702
|
train
|
function () {
var fc = this.freeCount, def, defQueue = this.__deferredQueue;
while (fc-- >= 0 && defQueue.count) {
def = defQueue.dequeue();
var conn = this.getObject();
if (conn) {
def.callback(conn);
} else {
throw new Error("UNEXPECTED ERROR");
}
fc--;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54703
|
train
|
function () {
var ret = new Promise(), conn;
if (this.count > this.__maxObjects) {
this.__deferredQueue.enqueue(ret);
} else {
//todo override getObject to make async so creating a connetion can execute setup sql
conn = this.getObject();
if (!conn) {
//we need to deffer it
this.__deferredQueue.enqueue(ret);
} else {
ret.callback(conn);
}
}
if (this.count > this.__maxObjects && !conn) {
ret.errback(new Error("Unexpected ConnectionPool error"));
}
return ret.promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q54704
|
train
|
function (obj) {
var self = this;
this.validate(obj).chain(function (valid) {
var index;
if (self.count <= self.__maxObjects && valid && (index = self.__inUseObjects.indexOf(obj)) > -1) {
self.__inUseObjects.splice(index, 1);
self.__freeObjects.enqueue(obj);
self.__checkQueries();
} else {
self.removeObject(obj);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54705
|
train
|
function () {
this.__ending = true;
var conn, fQueue = this.__freeObjects, count = this.count, ps = [];
while ((conn = this.__freeObjects.dequeue()) !== undefined) {
ps.push(this.closeConnection(conn));
}
var inUse = this.__inUseObjects;
for (var i = inUse.length - 1; i >= 0; i--) {
ps.push(this.closeConnection(inUse[i]));
}
this.__inUseObjects.length = 0;
return new PromiseList(ps).promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q54706
|
train
|
function (conn) {
if (!this.__validateConnectionCB) {
var ret = new Promise();
ret.callback(true);
return ret;
} else {
return this.__validateConnectionCB(conn);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54707
|
train
|
function (s) {
var ret, m;
if ((m = s.match(this._static.COLUMN_REF_RE1)) !== null) {
ret = m.slice(1);
}
else if ((m = s.match(this._static.COLUMN_REF_RE2)) !== null) {
ret = [null, m[1], m[2]];
}
else if ((m = s.match(this._static.COLUMN_REF_RE3)) !== null) {
ret = [m[1], m[2], null];
}
else {
ret = [null, s, null];
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q54708
|
train
|
function () {
var model;
try {
model = this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db));
} catch (e) {
model = this["__model__"] = this.patio.getModel(this.name, this.parent.db);
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q54709
|
train
|
function () {
if (!this.__joinTableDataset) {
var ds = this.__joinTableDataset = this.model.dataset.db.from(this.joinTableName), model = this.model, options = this.__opts;
var identifierInputMethod = isUndefined(options.identifierInputMethod) ? model.identifierInputMethod : options.identifierInputMethod,
identifierOutputMethod = isUndefined(options.identifierOutputMethod) ? model.identifierOutputMethod : options.identifierOutputMethod;
if (identifierInputMethod) {
ds.identifierInputMethod = identifierInputMethod;
}
if (identifierOutputMethod) {
ds.identifierOutputMethod = identifierOutputMethod;
}
}
return this.__joinTableDataset;
}
|
javascript
|
{
"resource": ""
}
|
|
q54710
|
train
|
function () {
this.errors = {};
return flatten(this._static.validators.map(function runValidator(validator) {
var col = validator.col, val = this.__values[validator.col], ret = validator.validate(val);
this.errors[col] = ret;
return ret;
}, this));
}
|
javascript
|
{
"resource": ""
}
|
|
q54711
|
train
|
function (name) {
this.__initValidation();
var ret;
if (isFunction(name)) {
name.call(this, this.__getValidator.bind(this));
ret = this;
} else if (isString(name)) {
ret = this.__getValidator(name);
} else {
throw new ModelError("name is must be a string or function when validating");
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q54712
|
train
|
function(httpMethod, xhrURL){
var cookie = headers["cookie"] || "";
// Monkey patch URL onto xhr for cookie origin checking in the send method.
var reqURL = url.parse(xhrURL);
this.__url = reqURL;
if (options.auth && cookie) {
var domainIsApproved = options.auth.domains.reduce(function(prev, domain){
return prev || reqURL.host.indexOf(domain) >= 0;
}, false);
}
// fix: if proxy is specified, use proxy-hostname instead of request-hostname for xhrURL
var args = Array.prototype.slice.call(arguments);
if (
options &&
options.proxy &&
options.proxyTo &&
(xhrURL.indexOf(options.proxyTo) === 0)
) {
args[1] = url.resolve(options.proxy, xhrURL);
}
var res = oldOpen.apply(this, args);
// If on an approved domain copy the jwt from a cookie to the request headers.
if (domainIsApproved) {
var jwtCookie = cookieReg.exec(cookie);
if(jwtCookie && !this.getRequestHeader('authorization')){
this.setRequestHeader('authorization', 'Bearer ' + jwtCookie[1]);
}
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
|
q54713
|
resolveUrl
|
train
|
function resolveUrl(headers, relativeURL) {
var path = headers[":path"] || "";
var baseUri = headers[":scheme"] + "://" + headers[":authority"] + path;
var outURL;
if (relativeURL && !fullUrlExp.test(relativeURL) ) {
outURL = url.resolve(baseUri, relativeURL);
} else {
outURL = relativeURL;
}
return outURL;
}
|
javascript
|
{
"resource": ""
}
|
q54714
|
findLastSeed
|
train
|
function findLastSeed (epoc, cb2) {
if (epoc === 0) {
return cb2(ethUtil.zeros(32), 0)
}
self.cacheDB.get(epoc, self.dbOpts, function (err, data) {
if (!err) {
cb2(data.seed, epoc)
} else {
findLastSeed(epoc - 1, cb2)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q54715
|
listDirectories
|
train
|
function listDirectories(dirPath) {
return fs.readdirSync(dirPath).filter(
/**
* @param {string} file
* @returns {boolean}
* */
file => fs.statSync(path.join(dirPath, file)).isDirectory(),
);
}
|
javascript
|
{
"resource": ""
}
|
q54716
|
findDependencies
|
train
|
function findDependencies(startFile, class2Path, deps) {
// Create a new regex object to reset the readIndex
const depRegEx = /global ([a-zA-Z0-9,\s]+) \*/g;
// Get global variable
const contents = fs.readFileSync(startFile).toString();
/** @type {string[]} */
let fileDeps = [];
let fileDepMatch;
while ((fileDepMatch = depRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
const fileDep = fileDepMatch[1];
fileDeps = fileDeps.concat(fileDep.split(/,\s*/g));
}
fileDeps.forEach(dep => {
// CustomError classes
if (dep.slice(-5) === 'Error') dep = 'errors';
if (dep === 'runKeyguard' || dep === 'loadNimiq') dep = 'common';
if (deps.indexOf(dep) > -1) return;
deps.push(dep);
if (dep === 'Nimiq') return;
const depPath = class2Path.get(dep);
if (!depPath) throw new Error(`Unknown dependency ${dep} referenced from ${startFile}`);
// deps are passed by reference
findDependencies(depPath, class2Path, deps); // recurse
});
return deps;
}
|
javascript
|
{
"resource": ""
}
|
q54717
|
findScripts
|
train
|
function findScripts(indexPath) {
const scriptRegEx = /<script.+src="(.+)".*?>/g;
const contents = fs.readFileSync(indexPath).toString();
/** @type {string[]} */
const scripts = [];
let scriptMatch;
while ((scriptMatch = scriptRegEx.exec(contents)) !== null) { // eslint-disable-line no-cond-assign
const scriptPath = scriptMatch[1];
scripts.push(scriptPath);
}
return scripts;
}
|
javascript
|
{
"resource": ""
}
|
q54718
|
train
|
function(data, eventType) {
switch(eventType) {
case 'progress':
// Update UI loading bar
break;
case 'timeout':
finish(new Error(data));
break;
case 'result':
finish(null, {
value: data,
type: 'result'
});
break;
case 'error':
if(ready) {
return finish(null, {
value: data,
type: 'error'
});
}
return finish(new Error(data));
break
case 'ready':
// We're good to get results and stuff back now
ready = true;
// Eval our code now that the runtime is ready
repl.eval(code);
break;
default:
console.log('Unhandled event =', eventType, 'data =', data);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54719
|
train
|
function($exercise) {
var codeSolution = $exercise.find(".code-solution").text();
var codeValidation = $exercise.find(".code-validation").text();
var codeContext = $exercise.find(".code-context").text();
var editor = ace.edit($exercise.find(".editor").get(0));
editor.setTheme("ace/theme/tomorrow");
editor.getSession().setUseWorker(false);
editor.getSession().setMode("ace/mode/javascript");
editor.commands.addCommand({
name: "submit",
bindKey: "Ctrl-Return|Cmd-Return",
exec: function() {
$exercise.find(".action-submit").click();
}
});
// Submit: test code
$exercise.find(".action-submit").click(function(e) {
e.preventDefault();
gitbook.events.trigger("exercise.submit", {type: "code"});
execute("javascript", editor.getValue(), codeValidation, codeContext, function(err, result) {
$exercise.toggleClass("return-error", err != null);
$exercise.toggleClass("return-success", err == null);
if (err) $exercise.find(".alert-danger").text(err.message || err);
});
});
// Set solution
$exercise.find(".action-solution").click(function(e) {
e.preventDefault();
editor.setValue(codeSolution);
editor.gotoLine(0);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q54720
|
reorderFinderPatterns
|
train
|
function reorderFinderPatterns(pattern1, pattern2, pattern3) {
// Find distances between pattern centers
const oneTwoDistance = distance(pattern1, pattern2);
const twoThreeDistance = distance(pattern2, pattern3);
const oneThreeDistance = distance(pattern1, pattern3);
let bottomLeft;
let topLeft;
let topRight;
// Assume one closest to other two is B; A and C will just be guesses at first
if (twoThreeDistance >= oneTwoDistance && twoThreeDistance >= oneThreeDistance) {
[bottomLeft, topLeft, topRight] = [pattern2, pattern1, pattern3];
}
else if (oneThreeDistance >= twoThreeDistance && oneThreeDistance >= oneTwoDistance) {
[bottomLeft, topLeft, topRight] = [pattern1, pattern2, pattern3];
}
else {
[bottomLeft, topLeft, topRight] = [pattern1, pattern3, pattern2];
}
// Use cross product to figure out whether bottomLeft (A) and topRight (C) are correct or flipped in relation to topLeft (B)
// This asks whether BC x BA has a positive z component, which is the arrangement we want. If it's negative, then
// we've got it flipped around and should swap topRight and bottomLeft.
if (((topRight.x - topLeft.x) * (bottomLeft.y - topLeft.y)) - ((topRight.y - topLeft.y) * (bottomLeft.x - topLeft.x)) < 0) {
[bottomLeft, topRight] = [topRight, bottomLeft];
}
return { bottomLeft, topLeft, topRight };
}
|
javascript
|
{
"resource": ""
}
|
q54721
|
countBlackWhiteRun
|
train
|
function countBlackWhiteRun(origin, end, matrix, length) {
const rise = end.y - origin.y;
const run = end.x - origin.x;
const towardsEnd = countBlackWhiteRunTowardsPoint(origin, end, matrix, Math.ceil(length / 2));
const awayFromEnd = countBlackWhiteRunTowardsPoint(origin, { x: origin.x - run, y: origin.y - rise }, matrix, Math.ceil(length / 2));
const middleValue = towardsEnd.shift() + awayFromEnd.shift() - 1; // Substract one so we don't double count a pixel
return awayFromEnd.concat(middleValue).concat(...towardsEnd);
}
|
javascript
|
{
"resource": ""
}
|
q54722
|
scoreBlackWhiteRun
|
train
|
function scoreBlackWhiteRun(sequence, ratios) {
const averageSize = sum(sequence) / sum(ratios);
let error = 0;
ratios.forEach((ratio, i) => {
error += Math.pow((sequence[i] - ratio * averageSize), 2);
});
return { averageSize, error };
}
|
javascript
|
{
"resource": ""
}
|
q54723
|
RpcTunnel
|
train
|
function RpcTunnel(url, sslSettings) {
var self = this;
if (! (this instanceof RpcTunnel)) {
return new RpcTunnel(url, sslSettings);
}
this.transports = {};
if (!url) {
throw new Error('Missing url parameter, which should be either a URL or client transport.')
}
var transport = null;
if (typeof url === 'string') {
var HttpTransport = require('./transports/http');
transport = new HttpTransport(url, sslSettings);
// As a special case when adding an HTTP transport, set up the WebSocket transport
// It is lazy-loaded, so the WebSocket connection is only created if/when the transport is used
Object.defineProperty(this.transports, 'ws', {
enumerable: true, // JSWS-47 ensure we can discover the ws transport
get: (function () {
var webSocketTransport;
var WebSocketTransport = require('./transports/ws');
return function () {
if (!webSocketTransport) {
webSocketTransport = new WebSocketTransport(url, sslSettings);
webSocketTransport.on('event', function (e) {
self.emit('event', e);
});
}
return webSocketTransport;
};
}())
});
} else {
transport = url;
transport.on('event', function (e) {
self.emit('event', e);
});
}
transport.on('error', function(err) {
self.emit('error', err);
});
this.url = transport.url;
this.transports[transport.name] = transport;
}
|
javascript
|
{
"resource": ""
}
|
q54724
|
train
|
function () {
// Call base class' constructor.
PluginBase.call(this);
this.pluginMetadata = {
name: 'ComponentDisabler',
version: '2.0.0',
configStructure: [
{ name: 'field',
displayName: 'Field',
description: 'Field of root node to add to',
value: null,
valueType: 'string',
readOnly: false },
{ name: 'attribute',
displayName: 'Attribute',
description: 'Attribute to add to field',
value: '',
valueType: 'string',
readOnly: false }
]
};
}
|
javascript
|
{
"resource": ""
}
|
|
q54725
|
getLanguageProxy
|
train
|
function getLanguageProxy(options) {
// Try and find if one is available
const proxyScript = path.resolve(__dirname, '..', 'proxies', options.language + '.ejs');
return new Promise(function(resolve, reject) {
fs.stat(proxyScript, function(err) {
if (err) {
return reject(err);
}
ejs.renderFile(
proxyScript,
{
metadata: options.serviceInstance.metadata,
localName: options.localName || 'Proxy',
_: _,
},
{ _with: false },
function(err, html) {
if (err) {
return reject(err);
}
resolve(html);
}
);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54726
|
checkConfiguration
|
train
|
function checkConfiguration(conf) {
let failedChecks = 0;
for (const path of Object.keys(CHECKS)) {
// @todo avoid try..catch
try {
checkProperty(path, get(conf, path), CHECKS[path]);
} catch (error) {
LusterConfigurationError.ensureError(error).log();
++failedChecks;
}
}
return failedChecks;
}
|
javascript
|
{
"resource": ""
}
|
q54727
|
extendResolvePath
|
train
|
function extendResolvePath(basedir) {
// using module internals isn't good, but restarting with corrected NODE_PATH looks more ugly, IMO
module.paths.push(basedir);
const _basedir = basedir.split('/'),
size = basedir.length;
let i = 0;
while (size > i++) {
const modulesPath = _basedir.slice(0, i).join('/') + '/node_modules';
if (module.paths.indexOf(modulesPath) === -1) {
module.paths.push(modulesPath);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54728
|
Multihashing
|
train
|
async function Multihashing (buf, alg, length) {
const digest = await Multihashing.digest(buf, alg, length)
return multihash.encode(digest, alg, length)
}
|
javascript
|
{
"resource": ""
}
|
q54729
|
applyAxiosDefaults
|
train
|
function applyAxiosDefaults(authenticatedAPIClient) {
/* eslint-disable no-param-reassign */
authenticatedAPIClient.defaults.withCredentials = true;
authenticatedAPIClient.defaults.headers.common['USE-JWT-COOKIE'] = true;
/* eslint-enable no-param-reassign */
}
|
javascript
|
{
"resource": ""
}
|
q54730
|
ensureCsrfToken
|
train
|
function ensureCsrfToken(request) {
const originalRequest = request;
const method = request.method.toUpperCase();
const isCsrfExempt = authenticatedAPIClient.isCsrfExempt(originalRequest.url);
if (!isCsrfExempt && CSRF_PROTECTED_METHODS.includes(method)) {
const url = new Url(request.url);
const { protocol } = url;
const { host } = url;
const csrfToken = csrfTokens[host];
if (csrfToken) {
request.headers[CSRF_HEADER_NAME] = csrfToken;
} else {
if (!queueRequests) {
queueRequests = true;
authenticatedAPIClient.getCsrfToken(protocol, host)
.then((response) => {
queueRequests = false;
PubSub.publishSync(CSRF_TOKEN_REFRESH, response.data.csrfToken);
});
}
return new Promise((resolve) => {
logInfo(`Queuing API request ${originalRequest.url} while CSRF token is retrieved`);
PubSub.subscribeOnce(CSRF_TOKEN_REFRESH, (msg, token) => {
logInfo(`Resolving queued API request ${originalRequest.url}`);
csrfTokens[host] = token;
originalRequest.headers[CSRF_HEADER_NAME] = token;
resolve(originalRequest);
});
});
}
}
return request;
}
|
javascript
|
{
"resource": ""
}
|
q54731
|
ensureValidJWTCookie
|
train
|
function ensureValidJWTCookie(request) {
const originalRequest = request;
const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url);
const accessToken = authenticatedAPIClient.getDecodedAccessToken();
const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken);
if (isAuthUrl || !tokenExpired) {
return request;
}
if (!queueRequests) {
queueRequests = true;
authenticatedAPIClient.refreshAccessToken()
.then(() => {
queueRequests = false;
PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true });
})
.catch((error) => {
// If no callback is supplied frontend-auth will (ultimately) redirect the user to login.
// The user is redirected to logout to ensure authentication clean-up, which in turn
// redirects to login.
if (authenticatedAPIClient.handleRefreshAccessTokenFailure) {
authenticatedAPIClient.handleRefreshAccessTokenFailure(error);
} else {
authenticatedAPIClient.logout();
}
PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false });
});
}
return new Promise((resolve, reject) => {
logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`);
PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => {
if (success) {
logInfo(`Resolving queued API request ${originalRequest.url}`);
resolve(originalRequest);
} else {
reject(originalRequest);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54732
|
handleUnauthorizedAPIResponse
|
train
|
function handleUnauthorizedAPIResponse(error) {
const response = error && error.response;
const errorStatus = response && response.status;
const requestUrl = response && response.config && response.config.url;
const requestIsTokenRefresh = requestUrl === authenticatedAPIClient.refreshAccessTokenEndpoint;
switch (errorStatus) { // eslint-disable-line default-case
case 401:
if (requestIsTokenRefresh) {
logInfo(`Unauthorized token refresh response from ${requestUrl}. This is expected if the user is not yet logged in.`);
} else {
logInfo(`Unauthorized API response from ${requestUrl}`);
}
break;
case 403:
logInfo(`Forbidden API response from ${requestUrl}`);
break;
}
return Promise.reject(error);
}
|
javascript
|
{
"resource": ""
}
|
q54733
|
callServer
|
train
|
function callServer(ctx, config, callback) {
const ip = ctx.ip;
const fullUrl = ctx.fullUrl;
const vid = ctx.vid || '';
const pxhd = ctx.pxhd || '';
const vidSource = ctx.vidSource || '';
const uuid = ctx.uuid || '';
const uri = ctx.uri || '/';
const headers = pxUtil.formatHeaders(ctx.headers, config.SENSITIVE_HEADERS);
const httpVersion = ctx.httpVersion;
const riskMode = config.MODULE_MODE === config.MONITOR_MODE.MONITOR ? 'monitor' : 'active_blocking';
const data = {
request: {
ip: ip,
headers: headers,
url: fullUrl,
uri: uri,
firstParty: config.FIRST_PARTY_ENABLED
},
additional: {
s2s_call_reason: ctx.s2sCallReason,
http_version: httpVersion,
http_method: ctx.httpMethod,
risk_mode: riskMode,
module_version: config.MODULE_VERSION,
cookie_origin: ctx.cookieOrigin,
request_cookie_names: ctx.requestCookieNames
}
};
if (ctx.s2sCallReason === 'cookie_decryption_failed') {
data.additional.px_orig_cookie = ctx.getCookie(); //No need strigify, already a string
}
if (ctx.s2sCallReason === 'cookie_expired' || ctx.s2sCallReason === 'cookie_validation_failed') {
data.additional.px_cookie = JSON.stringify(ctx.decodedCookie);
}
pxUtil.prepareCustomParams(config, data.additional);
const reqHeaders = {
Authorization: 'Bearer ' + config.AUTH_TOKEN,
'Content-Type': 'application/json'
};
if (vid) {
data.vid = vid;
}
if (uuid) {
data.uuid = uuid;
}
if (pxhd) {
data.pxhd = pxhd;
}
if (vidSource) {
data.vid_source = vidSource;
}
if (pxhd && data.additional.s2s_call_reason === 'no_cookie') {
data.additional.s2s_call_reason = 'no_cookie_w_vid';
}
if (ctx.originalUuid) {
data.additional['original_uuid'] = ctx.originalUuid;
}
if (ctx.originalTokenError) {
data.additional['original_token_error'] = ctx.originalTokenError;
}
if (ctx.originalToken) {
data.additional['original_token'] = ctx.originalToken;
}
if (ctx.decodedOriginalToken) {
data.additional['px_decoded_original_token'] = ctx.decodedOriginalToken;
}
if(ctx.hmac) {
data.additional['px_cookie_hmac'] = ctx.hmac;
}
ctx.hasMadeServerCall = true;
return pxHttpc.callServer(data, reqHeaders, config.SERVER_TO_SERVER_API_URI, 'query', config, callback);
}
|
javascript
|
{
"resource": ""
}
|
q54734
|
evalByServerCall
|
train
|
function evalByServerCall(ctx, config, callback) {
if (!ctx.ip || !ctx.headers) {
config.logger.error('perimeterx score evaluation failed. bad parameters.');
return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT);
}
config.logger.debug(`Evaluating Risk API request, call reason: ${ctx.s2sCallReason}`);
callServer(ctx, config, (err, res) => {
if (err) {
if (err === 'timeout') {
ctx.passReason = config.PASS_REASON.S2S_TIMEOUT;
return callback(config.SCORE_EVALUATE_ACTION.S2S_TIMEOUT_PASS);
}
config.logger.error(`Unexpected exception while evaluating Risk API. ${err}`);
ctx.passReason = config.PASS_REASON.REQUEST_FAILED;
return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT);
}
ctx.pxhd = res.pxhd;
const action = isBadRiskScore(res, ctx, config);
/* score response invalid - pass traffic */
if (action === -1) {
config.logger.error('perimeterx server query response is invalid');
return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT);
}
/* score did not cross threshold - pass traffic */
if (action === 1) {
return callback(config.SCORE_EVALUATE_ACTION.GOOD_SCORE);
}
/* score crossed threshold - block traffic */
if (action === 0) {
ctx.uuid = res.uuid || '';
return callback(config.SCORE_EVALUATE_ACTION.BAD_SCORE);
}
/* This shouldn't be called - if it did - we pass the traffic */
return callback(config.SCORE_EVALUATE_ACTION.UNEXPECTED_RESULT);
});
}
|
javascript
|
{
"resource": ""
}
|
q54735
|
isBadRiskScore
|
train
|
function isBadRiskScore(res, ctx, config) {
if (!res || !pxUtil.verifyDefined(res.score) || !res.action) {
ctx.passReason = config.PASS_REASON.INVALID_RESPONSE;
return -1;
}
const score = res.score;
ctx.score = score;
ctx.uuid = res.uuid;
if (score >= config.BLOCKING_SCORE) {
ctx.blockAction = res.action;
if (res.action === 'j' && res.action_data && res.action_data.body) {
ctx.blockActionData = res.action_data.body;
}
return 0;
} else {
ctx.passReason = config.PASS_REASON.S2S;
return 1;
}
}
|
javascript
|
{
"resource": ""
}
|
q54736
|
pxCookieFactory
|
train
|
function pxCookieFactory(ctx, config) {
if (ctx.cookieOrigin === 'cookie') {
return (ctx.cookies['_px3'] ? new CookieV3(ctx, config, config.logger) : new CookieV1(ctx, config, config.logger));
} else {
return (ctx.cookies['_px3'] ? new TokenV3(ctx, config, ctx.cookies['_px3'], config.logger) : new TokenV1(ctx, config, ctx.cookies['_px'], config.logger));
}
}
|
javascript
|
{
"resource": ""
}
|
q54737
|
prepareCustomParams
|
train
|
function prepareCustomParams(config, dict) {
const customParams = {
'custom_param1': '',
'custom_param2': '',
'custom_param3': '',
'custom_param4': '',
'custom_param5': '',
'custom_param6': '',
'custom_param7': '',
'custom_param8': '',
'custom_param9': '',
'custom_param10': ''
};
if (config.ENRICH_CUSTOM_PARAMETERS) {
const enrichedCustomParams = config.ENRICH_CUSTOM_PARAMETERS(customParams);
for (const param in enrichedCustomParams) {
if (param.match(/^custom_param([1-9]|10)$/) && enrichedCustomParams[param] !== '') {
dict[param] = enrichedCustomParams[param];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q54738
|
getCaptcha
|
train
|
function getCaptcha(req, config, ip, reversePrefix, cb) {
let res = {};
if (!config.FIRST_PARTY_ENABLED) {
res = {
status: 200,
header: {key: 'Content-Type', value:'application/javascript'},
body: ''
};
return cb(null, res);
} else {
const searchMask = `/${reversePrefix}${config.FIRST_PARTY_CAPTCHA_PATH}`;
const regEx = new RegExp(searchMask, 'ig');
const pxRequestUri = `/${config.PX_APP_ID}${req.originalUrl.replace(regEx, '')}`;
config.logger.debug(`Forwarding request from ${req.originalUrl} to xhr at ${config.CAPTCHA_HOST}${pxRequestUri}`);
const callData = {
url: `https://${config.CAPTCHA_HOST}${pxRequestUri}`,
headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS),
timeout: config.API_TIMEOUT_MS
};
callData.headers['host'] = config.CAPTCHA_HOST;
callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip;
callData.headers[config.FIRST_PARTY_HEADER] = 1;
request.get(callData, config, (error, response) => {
if (error || !response) {
config.logger.error(`Error while fetching first party captcha: ${error}`);
}
response = response || {statusCode: 200, headers: {}};
res = {
status: response.statusCode,
headers: response.headers,
body: response.body || ''
};
return cb(null, res);
});
}
return;
}
|
javascript
|
{
"resource": ""
}
|
q54739
|
getClient
|
train
|
function getClient(req, config, ip, cb) {
let res = {};
if (!config.FIRST_PARTY_ENABLED) {
res = {
status: 200,
header: {key: 'Content-Type', value:'application/javascript'},
body: ''
};
return cb(null, res);
} else {
const clientRequestUri = `/${config.PX_APP_ID}/main.min.js`;
config.logger.debug(`Forwarding request from ${req.originalUrl.toLowerCase()} to client at ${config.CLIENT_HOST}${clientRequestUri}`);
const callData = {
url: `https://${config.CLIENT_HOST}${clientRequestUri}`,
headers: pxUtil.filterSensitiveHeaders(req.headers, config.SENSITIVE_HEADERS),
timeout: config.API_TIMEOUT_MS
};
callData.headers['host'] = config.CLIENT_HOST;
callData.headers[config.ENFORCER_TRUE_IP_HEADER] = ip;
callData.headers[config.FIRST_PARTY_HEADER] = 1;
request.get(callData, config, (error, response) => {
if (error || !response) {
config.logger.error(`Error while fetching first party client: ${error}`);
}
response = response || {statusCode: 200, headers: {}};
res = {
status: response.statusCode,
headers: response.headers,
body: response.body || ''
};
return cb(null, res);
});
}
return;
}
|
javascript
|
{
"resource": ""
}
|
q54740
|
callServer
|
train
|
function callServer(data, headers, uri, callType, config, callback) {
callback = callback || ((err) => { err && config.logger.debug(`callServer default callback. Error: ${err}`); });
const callData = {
'url': `https://${config.SERVER_HOST}${uri}`,
'data': JSON.stringify(data),
'headers': headers
};
callData.timeout = callType === 'query' ? config.API_TIMEOUT_MS : config.ACTIVITIES_TIMEOUT;
try {
request.post(callData, config, function (err, response) {
let data;
if (err) {
if (err === 'Error: Timeout has been reached.' || err === 'Error: Timeout reached') {
return callback('timeout');
} else {
return callback(`perimeterx server did not return a valid response. Error: ${err}`);
}
}
if (typeof(response.body) !== 'undefined' && response.body !== null) {
data = response.body.toString();
}
if (response && response.statusCode === 200) {
try {
if (typeof data === 'object') {
return callback(null, data);
} else {
return callback(null, JSON.parse(data));
}
} catch (e) {
return callback('could not parse perimeterx api server response');
}
}
if (data) {
try {
return callback(`perimeterx server query failed. ${JSON.parse(data).message}`);
} catch (e) {
}
}
return callback('perimeterx server did not return a valid response');
});
} catch (e) {
return callback('error while calling perimeterx servers');
}
}
|
javascript
|
{
"resource": ""
}
|
q54741
|
npmInstall
|
train
|
function npmInstall(settings) {
const message = logger.promise('Running npm install (can take several minutes)');
const installArgs = {};
if (settings) {
if (settings.path) {
installArgs.cwd = settings.path;
}
if (settings.stdio) {
installArgs.stdio = settings.stdio;
}
}
const npmProcess = spawn('npm', ['install'], installArgs);
return new Promise((resolve, reject) => {
npmProcess.on('exit', (code) => {
if (code !== 0) {
message.fail();
reject('npm install failed.');
return;
}
message.succeed();
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q54742
|
mock
|
train
|
function mock(_module, _exports) {
delete require.cache[require.resolve(_module)];
require(_module);
_exports && (require.cache[require.resolve(_module)].exports = _exports);
return require(_module);
}
|
javascript
|
{
"resource": ""
}
|
q54743
|
later
|
train
|
function later (info) {
process.stdin.resume();
const action = start.bind(null, info);
process.on('SIGINT', action);
process.on('SIGTERM', action);
(function wait () {
if (beenthere) {
return;
}
setTimeout(wait, EVENT_LOOP);
}());
}
|
javascript
|
{
"resource": ""
}
|
q54744
|
start
|
train
|
async function start ({latest, message, name, version}) {
if (beenthere) {
return;
}
beenthere = true;
console.log( // eslint-disable-line no-console
box({
latest,
message,
name,
version,
})
);
const Confirm = require('prompt-confirm');
const confirmed = await new Confirm(
`install ${name.yellow} version ${latest.yellow} globally?`
).run();
if (!confirmed) {
process.exit(); // eslint-disable-line no-process-exit
}
await require('../install-latest')(name);
process.exit(); // eslint-disable-line no-process-exit
}
|
javascript
|
{
"resource": ""
}
|
q54745
|
box
|
train
|
function box ({latest, message, name, version}) {
const lines = [
`You are running ${name.yellow} version ${version.yellow}`,
`The latest version is ${latest.green}`,
];
if (message) {
lines.push(message.bold.italic);
}
return boxt(
lines.join('\n'),
{
'align': 'left',
'theme': 'round',
}
);
}
|
javascript
|
{
"resource": ""
}
|
q54746
|
getStats
|
train
|
function getStats({_: [file]} = {}) {
const route = resolve(process.cwd(), file);
try {
return require(route);
} catch (error) {
console.error(`The file "${route}" could not be properly parsed.`);
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
q54747
|
start
|
train
|
function start(stats, {f, format = 'human'} = {}) {
try {
const result = chunkalyse(stats);
let output;
switch (f || format) {
case 'json':
output = JSON.stringify(result, null, 2);
break;
case 'human':
default:
output = require('../lib/humanise')(result);
}
console.log(output);
} catch (error) {
console.log('I\'ve had trouble finding the chunks\n');
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
q54748
|
create
|
train
|
async function create(sourcedir) {
const target = join(sourcedir, FILENAME);
const exists = await exist(target);
const source = exists
? target
: join(__dirname, FILENAME)
;
const content = await readFile(source);
await writeFile(primed, content.toString());
return exists
? 'Creating a new Dangerfile'
: 'Creating a default Dangerfile'
;
}
|
javascript
|
{
"resource": ""
}
|
q54749
|
run
|
train
|
async function run() {
try {
await execute('./node_modules/.bin/danger ci', { pipe: true });
return false;
} catch (error) {
// don't throw yet
}
await execute('npm i danger --no-save', { pipe: true });
await execute('./node_modules/.bin/danger ci', { pipe: true });
return true;
}
|
javascript
|
{
"resource": ""
}
|
q54750
|
replace
|
train
|
function replace(haystack, needle) {
const replacement = options.resolve ? notate(data, needle.trim()) : data[needle.trim()];
return VALID_RESULT_TYPES.includes(typeof replacement) ? replacement : options.clean ? '' : haystack;
}
|
javascript
|
{
"resource": ""
}
|
q54751
|
getHelpTopic
|
train
|
function getHelpTopic(topic) {
let filename = getFilename(topic);
if (!fs.existsSync(filename)) {
filename = getFilename('help');
}
return fs.readFileSync(filename).toString();
}
|
javascript
|
{
"resource": ""
}
|
q54752
|
getHelp
|
train
|
function getHelp(argv) {
const version = require('./version').getVersion();
logger.info(`
***********************************************************************
* SKY UX App Builder ${version} *
* Usage: skyux [command] [options] *
* Help: skyux help or skyux help [command] *
* https://developer.blackbaud.com/skyux2/learn/reference/cli-commands *
***********************************************************************
`);
logger.info(getHelpTopic(argv._[1]));
}
|
javascript
|
{
"resource": ""
}
|
q54753
|
clean
|
train
|
function clean(route) {
// Resolve module location from given path
const filename = _require.resolve(route);
// Escape if this module is not present in cache
if (!_require.cache[filename]) {
return;
}
// Remove all children from memory, recursively
shidu(filename);
// Remove module from memory as well
delete _require.cache[filename];
}
|
javascript
|
{
"resource": ""
}
|
q54754
|
override
|
train
|
function override(route, thing) {
// Resolve module location from given path
const filename = _require.resolve(route);
// Load it into memory
_require(filename);
// Override exports with new value
_require.cache[filename].exports = thing;
// Return exports value
return _require(filename);
}
|
javascript
|
{
"resource": ""
}
|
q54755
|
reset
|
train
|
function reset(route) {
// Resolve module location from given path
const filename = _require.resolve(route);
// Load it into memory
_require(filename);
// Remove all children from memory, recursively
shidu(filename);
// Remove module from memory as well
delete _require.cache[filename];
// Return exports value
return _require(filename);
}
|
javascript
|
{
"resource": ""
}
|
q54756
|
shidu
|
train
|
function shidu(filename) {
const parent = require.cache[filename];
if (!parent) {
return;
}
// If there are children - iterate over them
parent.children
.map(
({filename}) => filename
)
.forEach(
child => {
// Load child to memory
require(child);
// Remove all of its children from memory, recursively
shidu(child);
// Remove it from memory
delete require.cache[child];
}
);
}
|
javascript
|
{
"resource": ""
}
|
q54757
|
getGlobs
|
train
|
function getGlobs() {
// Look globally and locally for matching glob pattern
const dirs = [
`${process.cwd()}/node_modules/`, // local (where they ran the command from)
`${__dirname}/..`, // global, if scoped package (where this code exists)
`${__dirname}/../..`, // global, if not scoped package
];
let globs = [];
dirs.forEach(dir => {
const legacyPattern = path.join(dir, '*/skyux-builder*/package.json');
const newPattern = path.join(dir, '@skyux-sdk/builder*/package.json');
logger.verbose(`Looking for modules in ${legacyPattern} and ${newPattern}`);
globs = globs.concat([
...glob.sync(legacyPattern),
...glob.sync(newPattern)
]);
});
return globs;
}
|
javascript
|
{
"resource": ""
}
|
q54758
|
getModulesAnswered
|
train
|
function getModulesAnswered(command, argv, globs) {
let modulesCalled = {};
let modulesAnswered = [];
globs.forEach(pkg => {
const dirName = path.dirname(pkg);
let pkgJson = {};
let module;
try {
module = require(dirName);
pkgJson = require(pkg);
} catch (err) {
logger.verbose(`Error loading module: ${pkg}`);
}
if (module && typeof module.runCommand === 'function') {
const pkgName = pkgJson.name || dirName;
if (modulesCalled[pkgName]) {
logger.verbose(`Multiple instances found. Skipping passing command to ${pkgName}`);
} else {
logger.verbose(`Passing command to ${pkgName}`);
modulesCalled[pkgName] = true;
if (module.runCommand(command, argv)) {
modulesAnswered.push(pkgName);
}
}
}
});
return modulesAnswered;
}
|
javascript
|
{
"resource": ""
}
|
q54759
|
invokeCommandError
|
train
|
function invokeCommandError(command, isInternalCommand) {
if (isInternalCommand) {
return;
}
const cwd = process.cwd();
logger.error(`No modules found for ${command}`);
if (cwd.indexOf('skyux-spa') === -1) {
logger.error(`Are you in a SKY UX SPA directory?`);
} else if (!fs.existsSync('./node_modules')) {
logger.error(`Have you ran 'npm install'?`);
}
process.exit(1);
}
|
javascript
|
{
"resource": ""
}
|
q54760
|
invokeCommand
|
train
|
function invokeCommand(command, argv, isInternalCommand) {
const globs = getGlobs();
if (globs.length === 0) {
return invokeCommandError(command, isInternalCommand);
}
const modulesAnswered = getModulesAnswered(command, argv, globs);
const modulesAnsweredLength = modulesAnswered.length;
if (modulesAnsweredLength === 0) {
return invokeCommandError(command, isInternalCommand);
}
const modulesAnsweredPlural = modulesAnsweredLength === 1 ? 'module' : 'modules';
logger.verbose(
`Successfully passed ${command} to ${modulesAnsweredLength} ${modulesAnsweredPlural}:`
);
logger.verbose(modulesAnswered.join(', '));
}
|
javascript
|
{
"resource": ""
}
|
q54761
|
getCommand
|
train
|
function getCommand(argv) {
let command = argv._[0] || 'help';
// Allow shorthand "-v" for version
if (argv.v) {
command = 'version';
}
// Allow shorthand "-h" for help
if (argv.h) {
command = 'help';
}
return command;
}
|
javascript
|
{
"resource": ""
}
|
q54762
|
processArgv
|
train
|
function processArgv(argv) {
let command = getCommand(argv);
let isInternalCommand = true;
logger.info(`SKY UX processing command ${command}`);
switch (command) {
case 'version':
require('./lib/version').logVersion(argv);
break;
case 'new':
require('./lib/new')(argv);
break;
case 'help':
require('./lib/help')(argv);
break;
case 'install':
require('./lib/install')(argv);
break;
default:
isInternalCommand = false;
}
invokeCommand(command, argv, isInternalCommand);
}
|
javascript
|
{
"resource": ""
}
|
q54763
|
getSlot
|
train
|
function getSlot(name) {
const main = document.querySelector('settings-ui').shadowRoot.children.container.children.main;
const settings = findTag(main.shadowRoot.children, 'SETTINGS-BASIC-PAGE');
const advancedPage = settings.shadowRoot.children.advancedPage;
const [page] = [...advancedPage.children].find(i => i.section === 'privacy').children;
const dialog = findTag(page.shadowRoot.children, 'SETTINGS-CLEAR-BROWSING-DATA-DIALOG');
return dialog.shadowRoot.children.clearBrowsingDataDialog.querySelector(`[slot="${name}"]`);
}
|
javascript
|
{
"resource": ""
}
|
q54764
|
update
|
train
|
function update(message) {
clearLine(stdout, 0); // Clear current STDOUT line
cursorTo(stdout, 0); // Place cursor at the start
stdout.write(message.toString());
}
|
javascript
|
{
"resource": ""
}
|
q54765
|
accountGuilds
|
train
|
function accountGuilds (client) {
return client.account().get().then(account => {
if (!account.guild_leader) {
return []
}
let requests = account.guild_leader.map(id => wrap(() => guildData(id)))
return flow.parallel(requests)
})
function guildData (id) {
let requests = {
data: wrap(() => client.guild().get(id)),
members: wrap(() => client.guild(id).members().get()),
ranks: wrap(() => client.guild(id).ranks().get()),
stash: wrap(() => client.guild(id).stash().get()),
teams: wrap(() => Promise.resolve(null)),
treasury: wrap(() => client.guild(id).treasury().get()),
upgrades: wrap(() => client.guild(id).upgrades().get())
}
return flow.parallel(requests)
}
}
|
javascript
|
{
"resource": ""
}
|
q54766
|
filterBetaCharacters
|
train
|
function filterBetaCharacters (characters) {
/* istanbul ignore next */
if (!characters) {
return null
}
return characters.filter(x => !x.flags || !x.flags.includes('Beta'))
}
|
javascript
|
{
"resource": ""
}
|
q54767
|
unflatten
|
train
|
function unflatten (object) {
let result = {}
for (let key in object) {
_set(result, key, object[key])
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q54768
|
adjustTop
|
train
|
function adjustTop(placements, containerPosition, initialHeight, currentHeight) {
if (placements.indexOf('top') !== -1 && initialHeight !== currentHeight) {
return {
top: containerPosition.top - currentHeight
};
}
}
|
javascript
|
{
"resource": ""
}
|
q54769
|
train
|
function (opts) {
if (!(this instanceof Worker)) {
return new Worker(opts);
}
this.opts = opts;
this.port = this.opts.port || 8888;
this.apps = opts.apps;
if (typeof (this.apps) !== 'object') {
this.apps = JSON.parse(this.apps);
}
this.server = http.createServer(this._handleHttp.bind(this));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q54770
|
logCallback
|
train
|
function logCallback(cb, message) {
var wrappedArgs = Array.prototype.slice.call(arguments);
return function (err, data) {
if (err) return cb(err);
wrappedArgs.shift();
console.log.apply(console, wrappedArgs);
cb();
}
}
|
javascript
|
{
"resource": ""
}
|
q54771
|
reqToAppName
|
train
|
function reqToAppName(req) {
var targetName = null;
try {
targetName = req.url.split('/').pop();
} catch (e) {}
return targetName || null;
}
|
javascript
|
{
"resource": ""
}
|
q54772
|
isStaleDailyData
|
train
|
async function isStaleDailyData (endpointInstance) {
const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get()
return new Date(account.last_modified) < resetTime.getLastDailyReset()
}
|
javascript
|
{
"resource": ""
}
|
q54773
|
isStaleWeeklyData
|
train
|
async function isStaleWeeklyData (endpointInstance) {
const account = await new AccountEndpoint(endpointInstance).schema('2019-03-26').get()
return new Date(account.last_modified) < resetTime.getLastWeeklyReset()
}
|
javascript
|
{
"resource": ""
}
|
q54774
|
createViewModel
|
train
|
function createViewModel(initialData, hasDataBinding, bindingState) {
if(bindingState && bindingState.isSettingOnViewModel === true) {
// If we are setting a value like `x:from="y"`,
// we need to make a variable scope.
newScope = tagData.scope.addLetContext(initialData);
return newScope._context;
} else {
// If we are setting the ViewModel itself, we
// stick the value in an observable: `this:from="value"`.
return vm = new SimpleObservable(initialData);
}
}
|
javascript
|
{
"resource": ""
}
|
q54775
|
Spinner
|
train
|
function Spinner(props) {
warnAboutDeprecatedProp(props.mods, 'mods', 'className');
const { className, size } = props;
const mods = props.mods ? props.mods.slice() : [];
mods.push(`size_${size}`);
const classes = classnames(getClassNamesWithMods('ui-spinner', mods), className);
/* eslint-disable max-len */
return (
<div className={classes}>
<svg
version="1.1"
viewBox="0 0 80 80"
x="0px"
xlinkHref="http://www.w3.org/1999/xlink"
xmlSpace="preserve"
xmlns="http://www.w3.org/2000/svg"
y="0px"
>
<g>
<g>
<circle
clipRule="evenodd"
cx="40"
cy="40"
fillRule="evenodd"
r="34.3"
/>
<path
className="ui-spinner_darker"
clipRule="evenodd"
d="M39.9,33.1c0.5-5.4-1.5-10.4-5.2-14.9c6.1-2.1,7.6-1.5,8.6,3.8c0.5,2.9,0.4,6,0.1,9c-0.1,0.9-0.3,1.8-0.7,2.7c-0.8-0.3-1.8-0.6-2.7-0.6H39.9z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M46.6,41.9c5.3,2,10.6,2.1,16-0.3c0.8,5.6-0.3,7-5.4,6.9c-4.6,0-8.5-1.6-12-4.1C45.9,43.7,46.3,42.8,46.6,41.9z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M44.3,45.4c3.1,4.5,7.2,7.7,13.2,8.9c-3.2,5.1-5.1,5.5-9.2,2.1c-3.2-2.6-5.3-5.9-6.5-9.8C42.7,46.4,43.5,46,44.3,45.4z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M40.1,46.9c-0.1,5.6,1.3,10.4,5.3,14.5c-5.6,2.6-7.2,2-8.6-3.3c-0.5-1.8-0.8-3.7-0.6-5.6c0.2-2,0.6-4.1,1.1-6.2c0.8,0.3,1.7,0.5,2.7,0.5H40.1z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M36,45.5c-3.5,4.3-5,9.2-4.7,14.8c-5.7-1.2-6.8-2.7-4.9-7.3c1.1-2.5,2.6-4.8,4.4-6.8c0.9-1,2-1.9,3.3-2.8C34.6,44.3,35.2,45,36,45.5z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M33.5,42.1c-5.6,1.5-9.8,4.5-12.8,9.5c-4-4.2-3.9-6.4,0.6-9.1c1.6-1,3.4-1.9,5.2-2.2c2.2-0.4,4.4-0.6,6.6-0.8l0,0.5C33.1,40.7,33.2,41.5,33.5,42.1z"
fillRule="evenodd"
/>
<path
className="ui-spinner_darker"
clipRule="evenodd"
d="M33.5,37.9c-3.7-1.5-7.1-1.4-16,0c-1-4.9,0.3-6.5,5-6.6c4.7,0,8.8,1.6,12.4,4.1C34.2,36.2,33.8,37,33.5,37.9z"
fillRule="evenodd"
/>
<path
className="ui-spinner_darker"
clipRule="evenodd"
d="M35.8,34.6c-3-4.7-7.3-7.8-13.2-9c3.4-5.2,5.2-5.5,9.5-1.9c3.2,2.6,5.2,5.9,6.5,9.6C37.5,33.5,36.6,34,35.8,34.6z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M48,34.8c-0.5,0.7-1.4,1.1-2.1,1.6c-0.5-0.8-1.1-1.5-1.8-2c3.5-4.4,5.2-9.2,4.6-14.9c5.7,0.8,7.1,2.7,5.1,7.1C52.3,29.6,50,32.2,48,34.8z"
fillRule="evenodd"
/>
<path
className="ui-spinner_dark"
clipRule="evenodd"
d="M46.9,40c0-0.8-0.1-1.5-0.4-2.2c5.8-1.6,10-4.7,13.1-9.6c4.4,6.1,3.2,6.4-1.3,9.5c-1.5,1-3.3,1.7-5,2c-2.1,0.4-4.2,0.6-6.4,0.8L46.9,40z"
fillRule="evenodd"
/>
</g>
<circle
className="ui-spinner_lighter"
clipRule="evenodd"
cx="40"
cy="40"
fillRule="evenodd"
r="36"
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth="8"
/>
</g>
</svg>
</div>
);
/* eslint-enable max-len */
}
|
javascript
|
{
"resource": ""
}
|
q54776
|
Button
|
train
|
function Button(props) {
warnAboutDeprecatedProp(props.mods, 'mods', 'className');
const {
children,
className,
dataAttrs = {},
disabled,
href,
id,
onClick,
onMouseUp,
size,
type,
variation,
} = props;
const restProps = getDataAttributes(dataAttrs);
const mods = props.mods ? props.mods.slice() : [];
/** This props have default values */
mods.push(`size_${size}`);
mods.push(`variation_${variation}`);
if (disabled) {
mods.push(`disabled_true`);
}
const classes = classnames(
getClassNamesWithMods('ui-button', mods),
className
);
if (type === 'link') {
if (!href) {
console.warn('Missing href'); // eslint-disable-line no-console
return null;
}
return (
<a
{...restProps}
className={classes}
href={href}
id={id}
onMouseUp={onMouseUp}
>
{children}
</a>
);
}
if (type === 'submit' || type === 'reset') {
return (
<button
{...restProps}
className={classes}
disabled={disabled}
id={id}
onMouseUp={onMouseUp}
type={type}
>
{children}
</button>
);
}
return (
<button
{...restProps}
className={classes}
disabled={disabled}
id={id}
onClick={onClick}
onMouseUp={onMouseUp}
type="button"
>
{children}
</button>
);
}
|
javascript
|
{
"resource": ""
}
|
q54777
|
getThemeFiles
|
train
|
function getThemeFiles({ brand, affiliate }) {
return [
path.join(__dirname, '/themes/_default.yaml'),
path.join(__dirname, `/themes/${brand}/_default.yaml`),
path.join(__dirname, `/themes/${brand}/${affiliate.toUpperCase()}/_default.yaml`)
].filter(fs.existsSync);
}
|
javascript
|
{
"resource": ""
}
|
q54778
|
processProps
|
train
|
function processProps(props) {
const { initialDates, maxDate, minDate, selectionType, multiplemode } = props;
const maxLimit = maxDate ? normalizeDate(getUTCDate(maxDate), 23, 59, 59, 999) : null;
let renderDate = (initialDates && initialDates.length && initialDates[0]) ? getUTCDate(initialDates[0]) : new Date();
normalizeDate(renderDate);
let minLimit = minDate ? normalizeDate(getUTCDate(minDate)) : null;
let selectedDates = [null, null];
if (initialDates) {
selectedDates = selectedDates.map((item, idx) => {
if (!initialDates[idx]) {
return null;
}
return normalizeDate(getUTCDate(initialDates[idx]));
});
}
/**
* If a minDate or a maxDate is set, let's check if any selectedDates are outside of the boundaries.
* If so, resets the selectedDates.
*/
if (minLimit || maxLimit) {
const isAnyDateOutOfLimit = selectedDates.some(item => (
item && (
(minLimit && (minLimit.getTime() > item.getTime())) ||
(maxLimit && (maxLimit.getTime() < item.getTime()))
)
));
if (isAnyDateOutOfLimit) {
selectedDates = [null, null];
console.warn(`A calendar instance contains a selectedDate outside of the minDate and maxDate boundaries`); // eslint-disable-line
}
}
/** If initialDates is defined and we have a start date, we want to set it as the minLimit */
if (selectedDates[0] && (selectionType === CALENDAR_SELECTION_TYPE_RANGE && !multiplemode)) {
minLimit = selectedDates[0];
}
/** If the renderDate is not between any of the minLimit and/or maxDate, we need to redefine it. */
if (minLimit && (renderDate.getTime() < minLimit.getTime())) {
renderDate = minLimit;
} else if (maxLimit && (renderDate.getTime() > maxLimit.getTime())) {
renderDate = maxLimit;
}
return {
maxLimit,
minLimit,
renderDate,
selectedDates,
};
}
|
javascript
|
{
"resource": ""
}
|
q54779
|
parseExpressions
|
train
|
function parseExpressions(obj, proto) {
const parsedObj = Object.assign(Object.create(proto), obj);
Object.keys(obj).forEach((key) => {
const value = obj[key];
const fn = isObject(value) ? parseExpressions : applyTransforms;
try {
parsedObj[key] = fn(value, parsedObj);
} catch (err) {
throwDescriptiveError({ err, key, value });
}
});
return parsedObj;
}
|
javascript
|
{
"resource": ""
}
|
q54780
|
getDataAttributes
|
train
|
function getDataAttributes(attributes) {
if (!attributes) {
return {};
}
return Object.keys(attributes).reduce((ret, key) => {
ret[`data-${key.toLowerCase()}`] = attributes[key];
return ret;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q54781
|
normalizeDate
|
train
|
function normalizeDate(dateObject, hours = 0, minutes = 0, seconds = 0, milliseconds = 0) {
dateObject.setHours(hours);
dateObject.setMinutes(minutes);
dateObject.setSeconds(seconds);
dateObject.setMilliseconds(milliseconds);
return dateObject;
}
|
javascript
|
{
"resource": ""
}
|
q54782
|
ejectOtherProps
|
train
|
function ejectOtherProps(props, propTypes) {
const propTypesKeys = Object.keys(propTypes);
return Object.keys(props)
.filter(x => propTypesKeys.indexOf(x) === -1)
.reduce((prev, item) => {
return { ...prev, [item]: props[item] };
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q54783
|
warnAboutDeprecatedProp
|
train
|
function warnAboutDeprecatedProp(propValue, oldPropName, newPropName) {
if (propValue !== undefined) {
console.warn(`[DEPRECATED] the property "${oldPropName}" has been deprecated, use "${newPropName}" instead`);
}
}
|
javascript
|
{
"resource": ""
}
|
q54784
|
List
|
train
|
function List(props) {
warnAboutDeprecatedProp(props.mods, 'mods', 'className');
const {
align,
className,
dataAttrs,
hideBullets,
items,
} = props;
const mods = props.mods ? props.mods.slice() : [];
mods.push(`align_${align}`);
if (hideBullets) {
mods.push("no-bullets");
}
const listClasses = classNames(getClassNamesWithMods('ui-list', mods), className);
const itemsBlock = items.filter(Boolean).map((item, index) => (
<li className="ui-list__item" key={index}>
{item}
</li>
));
return (
<ul className={listClasses} {...getDataAttributes(dataAttrs)}>
{itemsBlock}
</ul>
);
}
|
javascript
|
{
"resource": ""
}
|
q54785
|
Checkbox
|
train
|
function Checkbox(props) {
warnAboutDeprecatedProp(props.mods, 'mods', 'className');
const {
checked,
children,
className,
dataAttrs = {},
disabled,
inputDataAttrs = {},
name,
onChange,
} = props;
const dataAttributes = getDataAttributes(dataAttrs);
const inputDataAttributes = getDataAttributes(inputDataAttrs);
const mods = props.mods ? props.mods.slice() : [];
disabled && mods.push('is-disabled');
const classNames = classnames(getClassNamesWithMods('ui-checkbox', mods), className);
return (
<label
{...dataAttributes}
className={classNames}
htmlFor={name}
>
<input
{...inputDataAttributes}
aria-checked={checked}
checked={checked}
disabled={disabled}
id={name}
onChange={onChange}
readOnly={!onChange}
role="radio"
type="checkbox"
/>
<span className="ui-checkbox__text">
{children}
</span>
</label>
);
}
|
javascript
|
{
"resource": ""
}
|
q54786
|
parseExternalLink
|
train
|
function parseExternalLink(elem) {
var path = elem.href;
elem.setAttribute('data-parsed', true);
var rawFile = new XMLHttpRequest();
rawFile.open('GET', path, true);
rawFile.onreadystatechange = function processStylesFile() {
if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) {
var styleEl = document.createElement('style');
document.head.appendChild(styleEl);
styleEl.innerText = window.cssThemeService(rawFile.responseText);
}
};
rawFile.send(null);
}
|
javascript
|
{
"resource": ""
}
|
q54787
|
initializeRealtime
|
train
|
async function initializeRealtime({ getApp, onCreate, onDelete, url, token }) {
const realtimeConfig = { token, url }
try {
realtime
.subscribe(realtimeConfig, APPS_DOCTYPE)
.onCreate(async app => {
// Fetch directly the app to get attributes `related` as well.
let fullApp
try {
fullApp = await getApp(app.slug)
} catch (error) {
throw new Error(`Cannot fetch app ${app.slug}: ${error.message}`)
}
if (typeof onCreate === 'function') {
onCreate(fullApp)
}
})
.onDelete(app => {
if (typeof onDelete === 'function') {
onDelete(app)
}
})
} catch (error) {
console.warn(`Cannot initialize realtime in Cozy-bar: ${error.message}`)
}
}
|
javascript
|
{
"resource": ""
}
|
q54788
|
cozyFetchJSON
|
train
|
function cozyFetchJSON(cozy, method, path, body) {
const requestOptions = Object.assign({}, fetchOptions(), {
method
})
requestOptions.headers['Accept'] = 'application/json'
if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {
if (requestOptions.headers['Content-Type']) {
requestOptions.body = body
} else {
requestOptions.headers['Content-Type'] = 'application/json'
requestOptions.body = JSON.stringify(body)
}
}
return fetchJSON(`${COZY_URL}${path}`, requestOptions).then(json => {
const responseData = Object.assign({}, json.data)
if (responseData.id) responseData._id = responseData.id
return Promise.resolve(responseData)
})
}
|
javascript
|
{
"resource": ""
}
|
q54789
|
train
|
function(attrs) {
if (!attrs.ssl || includes(['NONE', 'UNVALIDATED', 'IFAVAILABLE', 'SYSTEMCA'], attrs.ssl)) {
return;
}
if (attrs.ssl === 'SERVER' && !attrs.ssl_ca) {
throw new TypeError('ssl_ca is required when ssl is SERVER.');
} else if (attrs.ssl === 'ALL') {
if (!attrs.ssl_ca) {
throw new TypeError('ssl_ca is required when ssl is ALL.');
}
if (!attrs.ssl_private_key) {
throw new TypeError('ssl_private_key is required when ssl is ALL.');
}
if (!attrs.ssl_certificate) {
throw new TypeError('ssl_certificate is required when ssl is ALL.');
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54790
|
train
|
function(attrs) {
if (attrs.authentication !== 'KERBEROS') {
if (attrs.kerberos_service_name) {
throw new TypeError(format(
'The kerberos_service_name field does not apply when '
+ 'using %s for authentication.', attrs.authentication));
}
if (attrs.kerberos_principal) {
throw new TypeError(format(
'The kerberos_principal field does not apply when '
+ 'using %s for authentication.', attrs.authentication));
}
if (attrs.kerberos_password) {
throw new TypeError(format(
'The kerberos_password field does not apply when '
+ 'using %s for authentication.', attrs.authentication));
}
}
if (attrs.authentication === 'KERBEROS') {
if (!attrs.kerberos_principal) {
throw new TypeError(format(
'The kerberos_principal field is required when '
+ 'using KERBEROS for authentication.'));
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q54791
|
validateURL
|
train
|
function validateURL(model, done) {
var url = model.driver_url;
parseURL(url, {}, function(err, result) {
// URL parsing errors are just generic `Error` instances
// so overwrite name so mongodb-js-server will know
// the message is safe to display.
if (err) {
err.name = 'MongoError';
}
done(err, result);
});
}
|
javascript
|
{
"resource": ""
}
|
q54792
|
httpsRequest
|
train
|
async function httpsRequest (opts, formData) {
return new Promise
((resolve, reject) => {
let req = https.request (opts, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
resolve ([res, data]);
});
});
if (formData)
req.write (formData);
req.end();
});
}
|
javascript
|
{
"resource": ""
}
|
q54793
|
makeFuncArgTree
|
train
|
function makeFuncArgTree (pt, args, makeSymbolName, forceBraces, allowNakedSymbol) {
var noBraces = !forceBraces && args.length === 1 && (args[0].type === 'func' || args[0].type === 'lookup' || args[0].type === 'alt' || (allowNakedSymbol && isPlainSymExpr(args[0])))
return [noBraces ? '' : leftBraceChar, pt.makeRhsTree (args, makeSymbolName), noBraces ? '' : rightBraceChar]
}
|
javascript
|
{
"resource": ""
}
|
q54794
|
train
|
function (next) { // next can be a function or another thenable
if (typeof(next.then) === 'function') // thenable?
return next
// next is a function, so call it
var nextResult = next.apply (next, result)
if (nextResult && typeof(nextResult.then) !== 'undefined') // thenable?
return nextResult
// create a Promise-like wrapper for the result
return syncPromiseResolve (nextResult)
}
|
javascript
|
{
"resource": ""
}
|
|
q54795
|
makeRhsExpansionPromise
|
train
|
function makeRhsExpansionPromise (config) {
var pt = this
var rhs = config.rhs || this.sampleParseTree (config.parsedRhsText || parseRhs (config.rhsText), config)
var resolve = config.sync ? syncPromiseResolve : Promise.resolve.bind(Promise)
var maxLength = config.maxLength || pt.maxLength
var maxNodes = config.maxNodes || pt.maxNodes
var reduce = config.reduce || textReducer
var makeExpansionPromise = config.makeExpansionPromise || pt.makeExpansionPromise
var init = extend ({ text: '',
vars: config.vars,
tree: [],
nodes: 0 },
config.init)
return rhs.reduce (function (promise, child) {
return promise.then (function (expansion) {
if ((expansion.text && expansion.text.length >= maxLength)
|| (expansion.nodes && expansion.nodes >= maxNodes)) {
return expansion
}
return makeExpansionPromise.call (pt,
extend ({},
config,
{ node: child,
vars: expansion.vars }))
.then (function (childExpansion) {
return reduce.call (pt, expansion, childExpansion, config)
})
})
}, resolve (init))
}
|
javascript
|
{
"resource": ""
}
|
q54796
|
pseudoRotateArray
|
train
|
function pseudoRotateArray (a, rng) {
var halfLen = a.length / 2, insertAfter = Math.ceil(halfLen) + Math.floor (rng() * Math.floor(halfLen))
var result = a.slice(1)
result.splice (insertAfter, 0, a[0])
return result
}
|
javascript
|
{
"resource": ""
}
|
q54797
|
capitalize
|
train
|
function capitalize (text) {
return text
.replace (/^([^A-Za-z]*)([a-z])/, function (m, g1, g2) { return g1 + g2.toUpperCase() })
.replace (/([\.\!\?]\s*)([a-z])/g, function (m, g1, g2) { return g1 + g2.toUpperCase() })
}
|
javascript
|
{
"resource": ""
}
|
q54798
|
textToWords
|
train
|
function textToWords (text) {
return text.toLowerCase()
.replace(/[^a-z\s]/g,'') // these are the phoneme characters we keep
.replace(/\s+/g,' ').replace(/^ /,'').replace(/ $/,'') // collapse all runs of space & remove start/end space
.split(' ');
}
|
javascript
|
{
"resource": ""
}
|
q54799
|
train
|
function(params, sep, eq) {
var query = '',
value,
typeOf,
tmpArray,
i, size, key;
if ( ! params) {
return query;
}
sep || (sep = '&');
eq || (eq = '=');
for (key in params) {
if (hasOwnProp.call(params, key)) {
tmpArray = [].concat(params[key]);
for (i = 0, size = tmpArray.length; i < size; ++i) {
typeOf = typeof tmpArray[i];
if (typeOf === 'object' || typeOf === 'undefined') {
value = '';
} else {
value = encodeURIComponent(tmpArray[i]);
}
query += sep + encodeURIComponent(key) + eq + value;
}
}
}
return query.substr(sep.length);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.