code stringlengths 31 2.05k | label_name stringclasses 5 values | label int64 0 4 |
|---|---|---|
export const createBubbleIcon = ({ className, path, target }) => {
let bubbleClassName = `${className} woot-elements--${window.$chatwoot.position}`;
const bubbleIcon = document.createElementNS(
'http://www.w3.org/2000/svg',
'svg'
);
bubbleIcon.setAttributeNS(null, 'id', 'woot-widget-bubble-icon');
bubbleIcon.setAttributeNS(null, 'width', '24');
bubbleIcon.setAttributeNS(null, 'height', '24');
bubbleIcon.setAttributeNS(null, 'viewBox', '0 0 240 240');
bubbleIcon.setAttributeNS(null, 'fill', 'none');
bubbleIcon.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
const bubblePath = document.createElementNS(
'http://www.w3.org/2000/svg',
'path'
);
bubblePath.setAttributeNS(null, 'd', path);
bubblePath.setAttributeNS(null, 'fill', '#FFFFFF');
bubbleIcon.appendChild(bubblePath);
target.appendChild(bubbleIcon);
if (isExpandedView(window.$chatwoot.type)) {
const textNode = document.createElement('div');
textNode.id = 'woot-widget--expanded__text';
textNode.innerHTML = '';
target.appendChild(textNode);
bubbleClassName += ' woot-widget--expanded';
}
target.className = bubbleClassName;
target.title = 'Open chat window';
return target;
}; | Base | 1 |
export const setBubbleText = bubbleText => {
if (isExpandedView(window.$chatwoot.type)) {
const textNode = document.getElementById('woot-widget--expanded__text');
textNode.innerHTML = bubbleText;
}
}; | Base | 1 |
export function defaultRenderTag(tag, params) {
// This file is in lib but it's used as a helper
let siteSettings = helperContext().siteSettings;
params = params || {};
const visibleName = escapeExpression(tag);
tag = visibleName.toLowerCase();
const classes = ["discourse-tag"];
const tagName = params.tagName || "a";
let path;
if (tagName === "a" && !params.noHref) {
if ((params.isPrivateMessage || params.pmOnly) && User.current()) {
const username = params.tagsForUser
? params.tagsForUser
: User.current().username;
path = `/u/${username}/messages/tags/${tag}`;
} else {
path = `/tag/${tag}`;
}
}
const href = path ? ` href='${getURL(path)}' ` : "";
if (siteSettings.tag_style || params.style) {
classes.push(params.style || siteSettings.tag_style);
}
if (params.size) {
classes.push(params.size);
}
let val =
"<" +
tagName +
href +
" data-tag-name=" +
tag +
(params.description ? ' title="' + params.description + '" ' : "") +
" class='" +
classes.join(" ") +
"'>" +
visibleName +
"</" +
tagName +
">";
if (params.count) {
val += " <span class='discourse-tag-count'>x" + params.count + "</span>";
}
return val;
} | Base | 1 |
_saveDraft(channelId, draft) {
const data = { chat_channel_id: channelId };
if (draft) {
data.data = JSON.stringify(draft);
}
ajax("/chat/drafts", { type: "POST", data, ignoreUnsent: false })
.then(() => {
this.markNetworkAsReliable();
})
.catch((error) => {
if (!error.jqXHR?.responseJSON?.errors?.length) {
this.markNetworkAsUnreliable();
}
});
} | Base | 1 |
Auth.prototype.getRolesForUser = async function () {
//Stack all Parse.Role
const results = [];
if (this.config) {
const restWhere = {
users: {
__type: 'Pointer',
className: '_User',
objectId: this.user.id,
},
};
const RestQuery = require('./RestQuery');
await new RestQuery(this.config, master(this.config), '_Role', restWhere, {}).each(result =>
results.push(result)
);
} else {
await new Parse.Query(Parse.Role)
.equalTo('users', this.user)
.each(result => results.push(result.toJSON()), { useMasterKey: true });
}
return results;
}; | Class | 2 |
var getAuthForLegacySessionToken = function ({ config, sessionToken, installationId }) {
var restOptions = {
limit: 1,
};
const RestQuery = require('./RestQuery');
var query = new RestQuery(config, master(config), '_User', { sessionToken }, restOptions);
return query.execute().then(response => {
var results = response.results;
if (results.length !== 1) {
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid legacy session token');
}
const obj = results[0];
obj.className = '_User';
const userObject = Parse.Object.fromJSON(obj);
return new Auth({
config,
isMaster: false,
installationId,
user: userObject,
});
});
}; | Class | 2 |
const getAuthForSessionToken = async function ({
config,
cacheController,
sessionToken,
installationId,
}) {
cacheController = cacheController || (config && config.cacheController);
if (cacheController) {
const userJSON = await cacheController.user.get(sessionToken);
if (userJSON) {
const cachedUser = Parse.Object.fromJSON(userJSON);
return Promise.resolve(
new Auth({
config,
cacheController,
isMaster: false,
installationId,
user: cachedUser,
})
);
}
}
let results;
if (config) {
const restOptions = {
limit: 1,
include: 'user',
};
const RestQuery = require('./RestQuery');
const query = new RestQuery(config, master(config), '_Session', { sessionToken }, restOptions);
results = (await query.execute()).results;
} else {
results = (
await new Parse.Query(Parse.Session)
.limit(1)
.include('user')
.equalTo('sessionToken', sessionToken)
.find({ useMasterKey: true })
).map(obj => obj.toJSON());
}
if (results.length !== 1 || !results[0]['user']) {
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token');
}
const now = new Date(),
expiresAt = results[0].expiresAt ? new Date(results[0].expiresAt.iso) : undefined;
if (expiresAt < now) {
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token is expired.');
}
const obj = results[0]['user'];
delete obj.password;
obj['className'] = '_User';
obj['sessionToken'] = sessionToken;
if (cacheController) {
cacheController.user.put(sessionToken, obj);
}
const userObject = Parse.Object.fromJSON(obj);
return new Auth({
config,
cacheController,
isMaster: false,
installationId,
user: userObject,
});
}; | Class | 2 |
Auth.prototype.getRolesByIds = async function (ins) {
const results = [];
// Build an OR query across all parentRoles
if (!this.config) {
await new Parse.Query(Parse.Role)
.containedIn(
'roles',
ins.map(id => {
const role = new Parse.Object(Parse.Role);
role.id = id;
return role;
})
)
.each(result => results.push(result.toJSON()), { useMasterKey: true });
} else {
const roles = ins.map(id => {
return {
__type: 'Pointer',
className: '_Role',
objectId: id,
};
});
const restWhere = { roles: { $in: roles } };
const RestQuery = require('./RestQuery');
await new RestQuery(this.config, master(this.config), '_Role', restWhere, {}).each(result =>
results.push(result)
);
}
return results;
}; | Class | 2 |
badgeUpdate = () => {
// Build a real RestQuery so we can use it in RestWrite
const restQuery = new RestQuery(config, master(config), '_Installation', updateWhere);
return restQuery.buildRestWhere().then(() => {
const write = new RestWrite(
config,
master(config),
'_Installation',
restQuery.restWhere,
restUpdate
);
write.runOptions.many = true;
return write.execute();
});
}; | Class | 2 |
RestQuery.prototype.getUserAndRoleACL = function () {
if (this.auth.isMaster) {
return Promise.resolve();
}
this.findOptions.acl = ['*'];
if (this.auth.user) {
return this.auth.getUserRoles().then(roles => {
this.findOptions.acl = this.findOptions.acl.concat(roles, [this.auth.user.id]);
return;
});
} else {
return Promise.resolve();
}
}; | Class | 2 |
RestQuery.prototype.denyProtectedFields = async function () {
if (this.auth.isMaster) {
return;
}
const schemaController = await this.config.database.loadSchema();
const protectedFields =
this.config.database.addProtectedFields(
schemaController,
this.className,
this.restWhere,
this.findOptions.acl,
this.auth,
this.findOptions
) || [];
for (const key of protectedFields) {
if (this.restWhere[key]) {
throw new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
`This user is not allowed to query ${key} on class ${this.className}`
);
}
}
}; | Class | 2 |
RestQuery.prototype.handleAuthAdapters = async function () {
if (this.className !== '_User' || this.findOptions.explain) {
return;
}
await Promise.all(
this.response.results.map(result =>
this.config.authDataManager.runAfterFind(
{ config: this.config, auth: this.auth },
result.authData
)
)
);
}; | Class | 2 |
RestQuery.prototype.replaceDontSelect = function () {
var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
if (!dontSelectObject) {
return;
}
// The dontSelect value must have precisely two keys - query and key
var dontSelectValue = dontSelectObject['$dontSelect'];
if (
!dontSelectValue.query ||
!dontSelectValue.key ||
typeof dontSelectValue.query !== 'object' ||
!dontSelectValue.query.className ||
Object.keys(dontSelectValue).length !== 2
) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect');
}
const additionalOptions = {
redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey,
};
if (this.restOptions.subqueryReadPreference) {
additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
} else if (this.restOptions.readPreference) {
additionalOptions.readPreference = this.restOptions.readPreference;
}
var subquery = new RestQuery(
this.config,
this.auth,
dontSelectValue.query.className,
dontSelectValue.query.where,
additionalOptions
);
return subquery.execute().then(response => {
transformDontSelect(dontSelectObject, dontSelectValue.key, response.results);
// Keep replacing $dontSelect clauses
return this.replaceDontSelect();
});
}; | Class | 2 |
RestQuery.prototype.runCount = function () {
if (!this.doCount) {
return;
}
this.findOptions.count = true;
delete this.findOptions.skip;
delete this.findOptions.limit;
return this.config.database.find(this.className, this.restWhere, this.findOptions).then(c => {
this.response.count = c;
});
}; | Class | 2 |
RestQuery.prototype.handleIncludeAll = function () {
if (!this.includeAll) {
return;
}
return this.config.database
.loadSchema()
.then(schemaController => schemaController.getOneSchema(this.className))
.then(schema => {
const includeFields = [];
const keyFields = [];
for (const field in schema.fields) {
if (
(schema.fields[field].type && schema.fields[field].type === 'Pointer') ||
(schema.fields[field].type && schema.fields[field].type === 'Array')
) {
includeFields.push([field]);
keyFields.push(field);
}
}
// Add fields to include, keys, remove dups
this.include = [...new Set([...this.include, ...includeFields])];
// if this.keys not set, then all keys are already included
if (this.keys) {
this.keys = [...new Set([...this.keys, ...keyFields])];
}
});
}; | Class | 2 |
RestQuery.prototype.redirectClassNameForKey = function () {
if (!this.redirectKey) {
return Promise.resolve();
}
// We need to change the class name based on the schema
return this.config.database
.redirectClassNameForKey(this.className, this.redirectKey)
.then(newClassName => {
this.className = newClassName;
this.redirectClassName = newClassName;
});
}; | Class | 2 |
RestQuery.prototype.replaceSelect = function () {
var selectObject = findObjectWithKey(this.restWhere, '$select');
if (!selectObject) {
return;
}
// The select value must have precisely two keys - query and key
var selectValue = selectObject['$select'];
// iOS SDK don't send where if not set, let it pass
if (
!selectValue.query ||
!selectValue.key ||
typeof selectValue.query !== 'object' ||
!selectValue.query.className ||
Object.keys(selectValue).length !== 2
) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select');
}
const additionalOptions = {
redirectClassNameForKey: selectValue.query.redirectClassNameForKey,
};
if (this.restOptions.subqueryReadPreference) {
additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
} else if (this.restOptions.readPreference) {
additionalOptions.readPreference = this.restOptions.readPreference;
}
var subquery = new RestQuery(
this.config,
this.auth,
selectValue.query.className,
selectValue.query.where,
additionalOptions
);
return subquery.execute().then(response => {
transformSelect(selectObject, selectValue.key, response.results);
// Keep replacing $select clauses
return this.replaceSelect();
});
}; | Class | 2 |
RestQuery.prototype.each = function (callback) {
const { config, auth, className, restWhere, restOptions, clientSDK } = this;
// if the limit is set, use it
restOptions.limit = restOptions.limit || 100;
restOptions.order = 'objectId';
let finished = false;
return continueWhile(
() => {
return !finished;
},
async () => {
const query = new RestQuery(
config,
auth,
className,
restWhere,
restOptions,
clientSDK,
this.runAfterFind,
this.context
);
const { results } = await query.execute();
results.forEach(callback);
finished = results.length < restOptions.limit;
if (!finished) {
restWhere.objectId = Object.assign({}, restWhere.objectId, {
$gt: results[results.length - 1].objectId,
});
}
}
);
}; | Class | 2 |
RestQuery.prototype.handleExcludeKeys = function () {
if (!this.excludeKeys) {
return;
}
if (this.keys) {
this.keys = this.keys.filter(k => !this.excludeKeys.includes(k));
return;
}
return this.config.database
.loadSchema()
.then(schemaController => schemaController.getOneSchema(this.className))
.then(schema => {
const fields = Object.keys(schema.fields);
this.keys = fields.filter(k => !this.excludeKeys.includes(k));
});
}; | Class | 2 |
RestQuery.prototype.cleanResultAuthData = function (result) {
delete result.password;
if (result.authData) {
Object.keys(result.authData).forEach(provider => {
if (result.authData[provider] === null) {
delete result.authData[provider];
}
});
if (Object.keys(result.authData).length == 0) {
delete result.authData;
}
}
}; | Class | 2 |
RestQuery.prototype.buildRestWhere = function () {
return Promise.resolve()
.then(() => {
return this.getUserAndRoleACL();
})
.then(() => {
return this.redirectClassNameForKey();
})
.then(() => {
return this.validateClientClassCreation();
})
.then(() => {
return this.replaceSelect();
})
.then(() => {
return this.replaceDontSelect();
})
.then(() => {
return this.replaceInQuery();
})
.then(() => {
return this.replaceNotInQuery();
})
.then(() => {
return this.replaceEquality();
});
}; | Class | 2 |
RestQuery.prototype.runAfterFindTrigger = function () {
if (!this.response) {
return;
}
if (!this.runAfterFind) {
return;
}
// Avoid doing any setup for triggers if there is no 'afterFind' trigger for this class.
const hasAfterFindHook = triggers.triggerExists(
this.className,
triggers.Types.afterFind,
this.config.applicationId
);
if (!hasAfterFindHook) {
return Promise.resolve();
}
// Skip Aggregate and Distinct Queries
if (this.findOptions.pipeline || this.findOptions.distinct) {
return Promise.resolve();
}
const json = Object.assign({}, this.restOptions);
json.where = this.restWhere;
const parseQuery = new Parse.Query(this.className);
parseQuery.withJSON(json);
// Run afterFind trigger and set the new results
return triggers
.maybeRunAfterFindTrigger(
triggers.Types.afterFind,
this.auth,
this.className,
this.response.results,
this.config,
parseQuery,
this.context
)
.then(results => {
// Ensure we properly set the className back
if (this.redirectClassName) {
this.response.results = results.map(object => {
if (object instanceof Parse.Object) {
object = object.toJSON();
}
object.className = this.redirectClassName;
return object;
});
} else {
this.response.results = results;
}
});
}; | Class | 2 |
RestQuery.prototype.handleInclude = function () {
if (this.include.length == 0) {
return;
}
var pathResponse = includePath(
this.config,
this.auth,
this.response,
this.include[0],
this.restOptions
);
if (pathResponse.then) {
return pathResponse.then(newResponse => {
this.response = newResponse;
this.include = this.include.slice(1);
return this.handleInclude();
});
} else if (this.include.length > 0) {
this.include = this.include.slice(1);
return this.handleInclude();
}
return pathResponse;
}; | Class | 2 |
RestQuery.prototype.replaceInQuery = function () {
var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
if (!inQueryObject) {
return;
}
// The inQuery value must have precisely two keys - where and className
var inQueryValue = inQueryObject['$inQuery'];
if (!inQueryValue.where || !inQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery');
}
const additionalOptions = {
redirectClassNameForKey: inQueryValue.redirectClassNameForKey,
};
if (this.restOptions.subqueryReadPreference) {
additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
} else if (this.restOptions.readPreference) {
additionalOptions.readPreference = this.restOptions.readPreference;
}
var subquery = new RestQuery(
this.config,
this.auth,
inQueryValue.className,
inQueryValue.where,
additionalOptions
);
return subquery.execute().then(response => {
transformInQuery(inQueryObject, subquery.className, response.results);
// Recurse to repeat
return this.replaceInQuery();
});
}; | Class | 2 |
RestQuery.prototype.replaceNotInQuery = function () {
var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
if (!notInQueryObject) {
return;
}
// The notInQuery value must have precisely two keys - where and className
var notInQueryValue = notInQueryObject['$notInQuery'];
if (!notInQueryValue.where || !notInQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery');
}
const additionalOptions = {
redirectClassNameForKey: notInQueryValue.redirectClassNameForKey,
};
if (this.restOptions.subqueryReadPreference) {
additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
} else if (this.restOptions.readPreference) {
additionalOptions.readPreference = this.restOptions.readPreference;
}
var subquery = new RestQuery(
this.config,
this.auth,
notInQueryValue.className,
notInQueryValue.where,
additionalOptions
);
return subquery.execute().then(response => {
transformNotInQuery(notInQueryObject, subquery.className, response.results);
// Recurse to repeat
return this.replaceNotInQuery();
});
}; | Class | 2 |
RestQuery.prototype.replaceEquality = function () {
if (typeof this.restWhere !== 'object') {
return;
}
for (const key in this.restWhere) {
this.restWhere[key] = replaceEqualityConstraint(this.restWhere[key]);
}
}; | Class | 2 |
RestQuery.prototype.execute = function (executeOptions) {
return Promise.resolve()
.then(() => {
return this.buildRestWhere();
})
.then(() => {
return this.denyProtectedFields();
})
.then(() => {
return this.handleIncludeAll();
})
.then(() => {
return this.handleExcludeKeys();
})
.then(() => {
return this.runFind(executeOptions);
})
.then(() => {
return this.runCount();
})
.then(() => {
return this.handleInclude();
})
.then(() => {
return this.runAfterFindTrigger();
})
.then(() => {
return this.handleAuthAdapters();
})
.then(() => {
return this.response;
});
}; | Class | 2 |
RestQuery.prototype.validateClientClassCreation = function () {
if (
this.config.allowClientClassCreation === false &&
!this.auth.isMaster &&
SchemaController.systemClasses.indexOf(this.className) === -1
) {
return this.config.database
.loadSchema()
.then(schemaController => schemaController.hasClass(this.className))
.then(hasClass => {
if (hasClass !== true) {
throw new Parse.Error(
Parse.Error.OPERATION_FORBIDDEN,
'This user is not allowed to access ' + 'non-existent class: ' + this.className
);
}
});
} else {
return Promise.resolve();
}
}; | Class | 2 |
RestQuery.prototype.runFind = function (options = {}) {
if (this.findOptions.limit === 0) {
this.response = { results: [] };
return Promise.resolve();
}
const findOptions = Object.assign({}, this.findOptions);
if (this.keys) {
findOptions.keys = this.keys.map(key => {
return key.split('.')[0];
});
}
if (options.op) {
findOptions.op = options.op;
}
return this.config.database
.find(this.className, this.restWhere, findOptions, this.auth)
.then(results => {
if (this.className === '_User' && !findOptions.explain) {
for (var result of results) {
this.cleanResultAuthData(result);
}
}
this.config.filesController.expandFilesInObject(this.config, results);
if (this.redirectClassName) {
for (var r of results) {
r.className = this.redirectClassName;
}
}
this.response = { results: results };
});
}; | Class | 2 |
function enforceRoleSecurity(method, className, auth) {
if (className === '_Installation' && !auth.isMaster && !auth.isMaintenance) {
if (method === 'delete' || method === 'find') {
const error = `Clients aren't allowed to perform the ${method} operation on the installation collection.`;
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
}
}
//all volatileClasses are masterKey only
if (
classesWithMasterOnlyAccess.indexOf(className) >= 0 &&
!auth.isMaster &&
!auth.isMaintenance
) {
const error = `Clients aren't allowed to perform the ${method} operation on the ${className} collection.`;
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
}
// readOnly masterKey is not allowed
if (auth.isReadOnly && (method === 'delete' || method === 'create' || method === 'update')) {
const error = `read-only masterKey isn't allowed to perform the ${method} operation.`;
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
}
} | Class | 2 |
function find(config, auth, className, restWhere, restOptions, clientSDK, context) {
enforceRoleSecurity('find', className, auth);
return triggers
.maybeRunQueryTrigger(
triggers.Types.beforeFind,
className,
restWhere,
restOptions,
config,
auth,
context
)
.then(result => {
restWhere = result.restWhere || restWhere;
restOptions = result.restOptions || restOptions;
const query = new RestQuery(
config,
auth,
className,
restWhere,
restOptions,
clientSDK,
true,
context
);
return query.execute();
});
} | Class | 2 |
const get = (config, auth, className, objectId, restOptions, clientSDK, context) => {
var restWhere = { objectId };
enforceRoleSecurity('get', className, auth);
return triggers
.maybeRunQueryTrigger(
triggers.Types.beforeFind,
className,
restWhere,
restOptions,
config,
auth,
context,
true
)
.then(result => {
restWhere = result.restWhere || restWhere;
restOptions = result.restOptions || restOptions;
const query = new RestQuery(
config,
auth,
className,
restWhere,
restOptions,
clientSDK,
true,
context
);
return query.execute();
});
}; | Class | 2 |
function update(config, auth, className, restWhere, restObject, clientSDK, context) {
enforceRoleSecurity('update', className, auth);
return Promise.resolve()
.then(() => {
const hasTriggers = checkTriggers(className, config, ['beforeSave', 'afterSave']);
const hasLiveQuery = checkLiveQuery(className, config);
if (hasTriggers || hasLiveQuery) {
// Do not use find, as it runs the before finds
return new RestQuery(
config,
auth,
className,
restWhere,
undefined,
undefined,
false,
context
).execute({
op: 'update',
});
}
return Promise.resolve({});
})
.then(({ results }) => {
var originalRestObject;
if (results && results.length) {
originalRestObject = results[0];
}
return new RestWrite(
config,
auth,
className,
restWhere,
restObject,
originalRestObject,
clientSDK,
context,
'update'
).execute();
})
.catch(error => {
handleSessionMissingError(error, className, auth);
});
} | Class | 2 |
onCreate(instance) {
const content = instance.props.content + $("#narrow-hotkey-tooltip-template").html();
instance.setContent(parse_html(content));
}, | Base | 1 |
function isTextSearchable(text, search) {
return text && (search || isNumber(search));
} | Base | 1 |
function TuleapHighlightFilter() {
function isTextSearchable(text, search) {
return text && (search || isNumber(search));
}
return function (text, search) {
if (!isTextSearchable(text, search)) {
return text ? text.toString() : text;
}
const classifier = Classifier(String(search));
const parts = classifier.classify(String(text)).map((highlighted_text) => {
if (!HighlightedText.isHighlight(highlighted_text)) {
return highlighted_text.content;
}
return `<span class="highlight">${highlighted_text.content}</span>`;
});
return parts.join("");
};
} | Base | 1 |
export async function downloadKubectl(version: string): Promise<string> {
let cachedToolpath = toolCache.find(kubectlToolName, version);
let kubectlDownloadPath = '';
const arch = getKubectlArch();
if (!cachedToolpath) {
try {
kubectlDownloadPath = await toolCache.downloadTool(getkubectlDownloadURL(version, arch));
} catch (exception) {
if (exception instanceof toolCache.HTTPError && exception.httpStatusCode === 404) {
throw new Error(util.format("Kubectl '%s' for '%s' arch not found.", version, arch));
} else {
throw new Error('DownloadKubectlFailed');
}
}
cachedToolpath = await toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
}
const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension());
fs.chmodSync(kubectlPath, '777');
return kubectlPath;
}
| Class | 2 |
fastify.addHook('onRequest', async (request, reply) => {
if (request.url === bullBoardPath || request.url.startsWith(bullBoardPath + '/')) {
const token = request.cookies.token;
if (token == null) {
reply.code(401);
throw new Error('login required');
}
const user = await this.usersRepository.findOneBy({ token });
if (user == null) {
reply.code(403);
throw new Error('no such user');
}
const isAdministrator = await this.roleService.isAdministrator(user);
if (!isAdministrator) {
reply.code(403);
throw new Error('access denied');
}
}
}); | Class | 2 |
super(meta, paramDef, async (ps, me) => {
const user = await this.usersRepository.findOneBy({ id: ps.userId });
if (user == null) {
throw new Error('user not found');
}
if (user.avatarId == null) return;
await this.usersRepository.update(user.id, {
avatar: null,
avatarId: null,
avatarUrl: null,
avatarBlurhash: null,
});
this.moderationLogService.log(me, 'unsetUserAvatar', {
userId: user.id,
userUsername: user.username,
userHost: user.host,
fileId: user.avatarId,
});
}); | Class | 2 |
public getChannelService(name: string) {
switch (name) {
case 'main': return this.mainChannelService;
case 'homeTimeline': return this.homeTimelineChannelService;
case 'localTimeline': return this.localTimelineChannelService;
case 'hybridTimeline': return this.hybridTimelineChannelService;
case 'globalTimeline': return this.globalTimelineChannelService;
case 'userList': return this.userListChannelService;
case 'hashtag': return this.hashtagChannelService;
case 'roleTimeline': return this.roleTimelineChannelService;
case 'antenna': return this.antennaChannelService;
case 'channel': return this.channelChannelService;
case 'drive': return this.driveChannelService;
case 'serverStats': return this.serverStatsChannelService;
case 'queueStats': return this.queueStatsChannelService;
case 'admin': return this.adminChannelService;
default:
throw new Error(`no such channel: ${name}`);
}
} | Class | 2 |
export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: string): string;
export function format(sql: string, values: unknown[], timeZone?: string, dialect?: string): string; | Base | 1 |
export function escapeId(val: string, forbidQualified?: boolean): string;
export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: string): string; | Base | 1 |
getTokenFromRequest: (req) => {
if (req.headers['x-csrf-token']) {
return req.headers['x-csrf-token'];
} else if (req.body.csrf_token) {
return req.body.csrf_token;
}
}, | Class | 2 |
export function splitOnFirstEquals(str: string): string[] {
// we use regex instead of "=" to ensure we split at the first
// "=" and return the following substring with it
// important for the hashed-password which looks like this
// $argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY
// 2 means return two items
// Source: https://stackoverflow.com/a/4607799/3015595
// We use the ? to say the the substr after the = is optional
const split = str.split(/=(.+)?/, 2)
return split
} | Class | 2 |
export const wsErrorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
logger.error(`${err.message} ${err.stack}`)
;(req as WebsocketRequest).ws.end()
} | Class | 2 |
function inspectFallback(val) {
const domains = Object.keys(val);
if (domains.length === 0) {
return "{}";
}
let result = "{\n";
Object.keys(val).forEach((domain, i) => {
result += formatDomain(domain, val[domain]);
if (i < domains.length - 1) {
result += ",";
}
result += "\n";
});
result += "}";
return result;
} | Variant | 0 |
removeAllCookies(cb) {
this.idx = {};
return cb(null);
} | Variant | 0 |
function formatPath(pathName, pathValue) {
const indent = " ";
let result = `${indent}'${pathName}': {\n`;
Object.keys(pathValue).forEach((cookieName, i, cookieNames) => {
const cookie = pathValue[cookieName];
result += ` ${cookieName}: ${cookie.inspect()}`;
if (i < cookieNames.length - 1) {
result += ",";
}
result += "\n";
});
result += `${indent}}`;
return result;
} | Variant | 0 |
putCookie(cookie, cb) {
if (!this.idx[cookie.domain]) {
this.idx[cookie.domain] = {};
}
if (!this.idx[cookie.domain][cookie.path]) {
this.idx[cookie.domain][cookie.path] = {};
}
this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
cb(null);
} | Variant | 0 |
constructor() {
super();
this.synchronous = true;
this.idx = {};
const customInspectSymbol = getCustomInspectSymbol();
if (customInspectSymbol) {
this[customInspectSymbol] = this.inspect;
}
} | Variant | 0 |
function formatDomain(domainName, domainValue) {
const indent = " ";
let result = `${indent}'${domainName}': {\n`;
Object.keys(domainValue).forEach((path, i, paths) => {
result += formatPath(path, domainValue[path]);
if (i < paths.length - 1) {
result += ",";
}
result += "\n";
});
result += `${indent}}`;
return result;
} | Variant | 0 |
? element.boundElementIds.map((id) => ({ type: "arrow", id }))
: element.boundElements ?? [],
updated: element.updated ?? getUpdatedTimestamp(),
link: element.link ?? null,
locked: element.locked ?? false,
}; | Base | 1 |
function sameStreams(
directives1: ReadonlyArray<DirectiveNode>,
directives2: ReadonlyArray<DirectiveNode>,
): boolean {
const stream1 = getStreamDirective(directives1);
const stream2 = getStreamDirective(directives2);
if (!stream1 && !stream2) {
// both fields do not have streams
return true;
} else if (stream1 && stream2) {
// check if both fields have equivalent streams
return stringifyArguments(stream1) === stringifyArguments(stream2);
}
// fields have a mix of stream and no stream
return false;
} | Class | 2 |
fields: args.map((argNode) => ({
kind: Kind.OBJECT_FIELD,
name: argNode.name,
value: argNode.value,
})),
}; | Class | 2 |
setCipherKey(val) {
this.cipherKey = val;
return this;
} | Base | 1 |
getVersion() {
return '7.3.3';
} | Base | 1 |
function __processMessage(modules, message) {
const { config, crypto } = modules;
if (!config.cipherKey) return message;
try {
return crypto.decrypt(message);
} catch (e) {
return message;
}
} | Base | 1 |
handleResponse: async ({ PubNubFile, config, cryptography }, res, params) => {
let { body } = res.response;
if (PubNubFile.supportsEncryptFile && (params.cipherKey ?? config.cipherKey)) {
body = await cryptography.decrypt(params.cipherKey ?? config.cipherKey, body);
}
return PubNubFile.create({
data: body,
name: res.response.name ?? params.name,
mimeType: res.response.type,
});
}, | Base | 1 |
const preparePayload = ({ crypto, config }, payload) => {
let stringifiedPayload = JSON.stringify(payload);
if (config.cipherKey) {
stringifiedPayload = crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
return stringifiedPayload || '';
}; | Base | 1 |
function __processMessage(modules, message) {
const { config, crypto } = modules;
if (!config.cipherKey) return message;
try {
return crypto.decrypt(message);
} catch (e) {
return message;
}
} | Base | 1 |
function prepareMessagePayload(modules, messagePayload) {
const { crypto, config } = modules;
let stringifiedPayload = JSON.stringify(messagePayload);
if (config.cipherKey) {
stringifiedPayload = crypto.encrypt(stringifiedPayload);
stringifiedPayload = JSON.stringify(stringifiedPayload);
}
return stringifiedPayload;
} | Base | 1 |
this.encryptFile = (key, file) => cryptography.encryptFile(key, file, this.File); | Base | 1 |
this.decryptFile = (key, file) => cryptography.decryptFile(key, file, this.File); | Base | 1 |
decryptBuffer(key, ciphertext) {
const bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH);
const bCiphertext = ciphertext.slice(NodeCryptography.IV_LENGTH);
const aes = createDecipheriv(this.algo, key, bIv);
return Buffer.concat([aes.update(bCiphertext), aes.final()]);
} | Base | 1 |
encryptStream(key, stream) {
const output = new PassThrough();
const bIv = this.getIv();
const aes = createCipheriv(this.algo, key, bIv);
output.write(bIv);
stream.pipe(aes).pipe(output);
return output;
} | Base | 1 |
async decryptArrayBuffer(key, ciphertext) {
const abIv = ciphertext.slice(0, 16);
return crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(16));
} | Base | 1 |
async encryptString(key, plaintext) {
const abIv = crypto.getRandomValues(new Uint8Array(16));
const abPlaintext = Buffer.from(plaintext).buffer;
const abPayload = await crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext);
const ciphertext = concatArrayBuffer(abIv.buffer, abPayload);
return Buffer.from(ciphertext).toString('utf8');
} | Base | 1 |
async encryptFile(key, file, File) {
const bKey = await this.getKey(key);
const abPlaindata = await file.toArrayBuffer();
const abCipherdata = await this.encryptArrayBuffer(bKey, abPlaindata);
return File.create({
name: file.name,
mimeType: 'application/octet-stream',
data: abCipherdata,
});
} | Base | 1 |
async decrypt(key, input) {
const cKey = await this.getKey(key);
if (input instanceof ArrayBuffer) {
return this.decryptArrayBuffer(cKey, input);
}
if (typeof input === 'string') {
return this.decryptString(cKey, input);
}
throw new Error('Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer');
} | Base | 1 |
async getKey(key) {
const bKey = Buffer.from(key);
const abHash = await crypto.subtle.digest('SHA-256', bKey.buffer);
const abKey = Buffer.from(Buffer.from(abHash).toString('hex').slice(0, 32), 'utf8').buffer;
return crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt']);
} | Base | 1 |
async decryptFile(key, file, File) {
const bKey = await this.getKey(key);
const abCipherdata = await file.toArrayBuffer();
const abPlaindata = await this.decryptArrayBuffer(bKey, abCipherdata);
return File.create({
name: file.name,
data: abPlaindata,
});
} | Base | 1 |
async decryptString(key, ciphertext) {
const abCiphertext = Buffer.from(ciphertext);
const abIv = abCiphertext.slice(0, 16);
const abPayload = abCiphertext.slice(16);
const abPlaintext = await crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload);
return Buffer.from(abPlaintext).toString('utf8');
} | Base | 1 |
constructor({ stream, data, encoding, name, mimeType }) {
if (stream instanceof Readable) {
this.data = stream;
if (stream instanceof ReadStream) {
// $FlowFixMe: incomplete flow node definitions
this.name = basename(stream.path);
}
} else if (data instanceof Buffer) {
this.data = Buffer.from(data);
} else if (typeof data === 'string') {
// $FlowFixMe: incomplete flow node definitions
this.data = Buffer.from(data, encoding ?? 'utf8');
}
if (name) {
this.name = basename(name);
}
if (mimeType) {
this.mimeType = mimeType;
}
if (this.data === undefined) {
throw new Error("Couldn't construct a file out of supplied options.");
}
if (this.name === undefined) {
throw new Error("Couldn't guess filename out of the options. Please provide one.");
}
} | Base | 1 |
constructor(setup) {
// extract config.
const { listenToBrowserNetworkEvents = true } = setup;
setup.sdkFamily = 'Web';
setup.networking = new Networking({
del,
get,
post,
patch,
sendBeacon,
getfile,
postfile,
});
setup.cbor = new Cbor((arrayBuffer) => stringifyBufferKeys(CborReader.decode(arrayBuffer)), decode);
setup.PubNubFile = PubNubFile;
setup.cryptography = new WebCryptography();
super(setup);
if (listenToBrowserNetworkEvents) {
// mount network events.
window.addEventListener('offline', () => {
this.networkDownDetected();
});
window.addEventListener('online', () => {
this.networkUpDetected();
});
}
} | Base | 1 |
function pointInPolygon(testx, testy, polygon) {
let intersections = 0;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const [prevX, prevY] = polygon[j];
const [x, y] = polygon[i];
// count intersections
if (((y > testy) != (prevY > testy)) && (testx < (prevX - x) * (testy - y) / (prevY - y) + x)) {
intersections++;
}
}
// point is in polygon if intersection count is odd
return intersections & 1;
} | Base | 1 |
export function intersectLasso(markname, pixelLasso, unit) {
const { x, y, mark } = unit;
const bb = new Bounds().set(
Number.MAX_SAFE_INTEGER,
Number.MAX_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER,
Number.MIN_SAFE_INTEGER
);
// Get bounding box around lasso
for (const [px, py] of pixelLasso) {
if (px < bb.x1) bb.x1 = px;
if (px > bb.x2) bb.x2 = px;
if (py < bb.y1) bb.y1 = py;
if (py > bb.y2) bb.y2 = py;
}
// Translate bb against unit coordinates
bb.translate(x, y);
const intersection = intersect([[bb.x1, bb.y1], [bb.x2, bb.y2]],
markname,
mark);
// Check every point against the lasso
return intersection.filter(tuple => pointInPolygon(tuple.x, tuple.y, pixelLasso));
} | Base | 1 |
export function lassoAppend(lasso, x, y, minDist = 5) {
const last = lasso[lasso.length - 1];
// Add point to lasso if distance to last point exceed minDist or its the first point
if (last === undefined || Math.sqrt(((last[0] - x) ** 2) + ((last[1] - y) ** 2)) > minDist) {
lasso.push([x, y]);
return [...lasso];
}
return lasso;
} | Base | 1 |
export function lassoPath(lasso) {
return (lasso ?? []).reduce((svg, [x, y], i) => {
return svg += i == 0
? `M ${x},${y} `
: i === lasso.length - 1
? ' Z'
: `L ${x},${y} `;
}, '');
} | Base | 1 |
default: axiosDefault.mockResolvedValue({
status: 200,
statusText: 'OK',
headers: {},
data: {},
}),
})); | Base | 1 |
function handleDataChannelChat(dataMessage) {
if (!dataMessage) return;
let msgFrom = dataMessage.from;
let msgTo = dataMessage.to;
let msg = dataMessage.msg;
let msgPrivate = dataMessage.privateMsg;
let msgId = dataMessage.id;
// private message but not for me return
if (msgPrivate && msgTo != myPeerName) return;
console.log('handleDataChannelChat', dataMessage);
// chat message for me also
if (!isChatRoomVisible && showChatOnMessage) {
showChatRoomDraggable();
chatRoomBtn.className = className.chatOff;
}
// show message from
if (!showChatOnMessage) {
userLog('toast', `New message from: ${msgFrom}`);
}
playSound('chatMessage');
setPeerChatAvatarImgName('left', msgFrom);
appendMessage(msgFrom, leftChatAvatar, 'left', msg, msgPrivate, msgId);
} | Base | 1 |
function addMsgerPrivateBtn(msgerPrivateBtn, msgerPrivateMsgInput, peerId) {
// add button to send private messages
msgerPrivateBtn.addEventListener('click', (e) => {
e.preventDefault();
sendPrivateMessage();
});
// Number 13 is the "Enter" key on the keyboard
msgerPrivateMsgInput.addEventListener('keyup', (e) => {
if (e.keyCode === 13) {
e.preventDefault();
sendPrivateMessage();
}
});
msgerPrivateMsgInput.onpaste = () => {
isChatPasteTxt = true;
};
function sendPrivateMessage() {
let pMsg = checkMsg(msgerPrivateMsgInput.value.trim());
if (!pMsg) {
msgerPrivateMsgInput.value = '';
isChatPasteTxt = false;
return;
}
let toPeerName = msgerPrivateBtn.value;
emitMsg(myPeerName, toPeerName, pMsg, true, peerId);
appendMessage(myPeerName, rightChatAvatar, 'right', pMsg + '<hr>Private message to ' + toPeerName, true);
msgerPrivateMsgInput.value = '';
msgerCP.style.display = 'none';
}
} | Base | 1 |
function sendPrivateMessage() {
let pMsg = checkMsg(msgerPrivateMsgInput.value.trim());
if (!pMsg) {
msgerPrivateMsgInput.value = '';
isChatPasteTxt = false;
return;
}
let toPeerName = msgerPrivateBtn.value;
emitMsg(myPeerName, toPeerName, pMsg, true, peerId);
appendMessage(myPeerName, rightChatAvatar, 'right', pMsg + '<hr>Private message to ' + toPeerName, true);
msgerPrivateMsgInput.value = '';
msgerCP.style.display = 'none';
} | Base | 1 |
fastify.register(FastifyCsrfProtection, { getUserInfo(req) {
return req.session.get('username')
}}) | Compound | 4 |
function addDummyBuildTarget(config: any = buildConfig) {
architectHost.addTarget(
{ project: 'dummy', target: 'build' },
'@angular-devkit/architect:true',
config
);
} | Class | 2 |
async function runNgsscbuild(options: Schema & JsonObject) {
// A "run" can have multiple outputs, and contains progress information.
const run = await architect.scheduleBuilder(
'angular-server-side-configuration:ngsscbuild',
options,
{ logger }
);
// The "result" member (of type BuilderOutput) is the next output.
const output = await run.result;
// Stop the builder from running. This stops Architect from keeping
// the builder-associated states in memory, since builders keep waiting
// to be scheduled.
await run.stop();
return output;
} | Class | 2 |
export async function detectVariables(context: BuilderContext): Promise<NgsscContext> {
const detector = new VariableDetector(context.logger);
const typeScriptFiles = findTypeScriptFiles(context.workspaceRoot);
let ngsscContext: NgsscContext | null = null;
for (const file of typeScriptFiles) {
const fileContent = await readFileAsync(file, 'utf8');
const innerNgsscContext = detector.detect(fileContent);
if (!innerNgsscContext.variables.length) {
continue;
} else if (!ngsscContext) {
ngsscContext = innerNgsscContext;
continue;
}
if (ngsscContext.variant !== innerNgsscContext.variant) {
context.logger.info(
`ngssc: Detected conflicting variants (${ngsscContext.variant} and ${innerNgsscContext.variant}) being used`
);
}
ngsscContext.variables.push(
...innerNgsscContext.variables.filter((v) => !ngsscContext!.variables.includes(v))
);
}
if (!ngsscContext) {
return { variant: 'process', variables: [] };
}
context.logger.info(
`ngssc: Detected variant '${ngsscContext.variant}' with variables ` +
`'${ngsscContext.variables.join(', ')}'`
);
return ngsscContext;
} | Class | 2 |
export async function detectVariablesAndBuildNgsscJson(
options: NgsscBuildSchema,
browserOptions: BrowserBuilderOptions,
context: BuilderContext,
multiple: boolean = false
) {
const ngsscContext = await detectVariables(context);
const outputPath = join(context.workspaceRoot, browserOptions.outputPath);
const ngssc = buildNgssc(ngsscContext, options, browserOptions, multiple);
await writeFileAsync(join(outputPath, 'ngssc.json'), JSON.stringify(ngssc, null, 2), 'utf8');
} | Class | 2 |
function findTypeScriptFiles(root: string): string[] {
const directory = root.replace(/\\/g, '/');
return readdirSync(directory)
.map((f) => `${directory}/${f}`)
.map((f) => {
const stat = lstatSync(f);
if (stat.isDirectory()) {
return findTypeScriptFiles(f);
} else if (stat.isFile() && f.endsWith('.ts') && !f.endsWith('.spec.ts')) {
return [f];
} else {
return [];
}
})
.reduce((current, next) => current.concat(next), []);
} | Class | 2 |
export function is_form_content_type(request) {
return is_content_type(request, 'application/x-www-form-urlencoded', 'multipart/form-data');
} | Compound | 4 |
constructor(options: AuthenticatorOptions = {}) {
this.key = options.key || 'passport'
this.userProperty = options.userProperty || 'user'
this.use(new SessionStrategy(this.deserializeUser.bind(this)))
this.sessionManager = new SecureSessionManager({ key: this.key }, this.serializeUser.bind(this))
} | Compound | 4 |
constructor(options: SerializeFunction | { key?: string }, serializeUser?: SerializeFunction) {
if (typeof options === 'function') {
this.serializeUser = options
this.key = 'passport'
} else if (typeof serializeUser === 'function') {
this.serializeUser = serializeUser
this.key =
(options && typeof options === 'object' && typeof options.key === 'string' && options.key) || 'passport'
} else {
throw new Error('SecureSessionManager#constructor must have a valid serializeUser-function passed as a parameter')
}
} | Compound | 4 |
) => {
const { fastifyPassport, server } = getRegisteredTestServer(sessionOptions)
fastifyPassport.use(name, strategy)
return { fastifyPassport, server }
} | Compound | 4 |
export const getRegisteredTestServer = (sessionOptions: SessionOptions = null) => {
const fastifyPassport = new Authenticator()
fastifyPassport.registerUserSerializer(async (user) => JSON.stringify(user))
fastifyPassport.registerUserDeserializer(async (serialized: string) => JSON.parse(serialized))
const server = getTestServer(sessionOptions)
void server.register(fastifyPassport.initialize())
void server.register(fastifyPassport.secureSession())
return { fastifyPassport, server }
} | Compound | 4 |
export const getTestServer = (sessionOptions: SessionOptions = null) => {
const server = fastify()
loadSessionPlugins(server, sessionOptions)
server.setErrorHandler((error, request, reply) => {
console.error(error)
void reply.status(500)
void reply.send(error)
})
return server
} | Compound | 4 |
preValidation: authenticator.authenticate(strategyName, {
successRedirect: `/${namespace}`,
authInfo: false,
}),
},
() => {
return
}
)
instance.post(
`/logout-${namespace}`,
{ preValidation: authenticator.authenticate(strategyName, { authInfo: false }) },
async (request, reply) => {
await request.logout()
void reply.send('logged out')
}
)
})
}
}) | Compound | 4 |
return this.success({ namespace, id: String(counter++) })
}
this.fail()
} | Compound | 4 |
constructor(username: string, password: string) {
this.username = username;
this.password = password;
} | Class | 2 |
constructor(token: string) {
this.token = token;
} | Class | 2 |
constructor(token: string) {
this.token = token;
} | Class | 2 |
function resolveMetadataRecord(owner: object, context: Context, useMetaFromContext: boolean): MetadataRecord
{
// If registry is not to be used, it means that context.metadata is available
if (useMetaFromContext) {
return context.metadata as MetadataRecord;
}
// Obtain record from registry, or create new empty object.
let metadata: MetadataRecord = registry.get(owner) ?? {};
// In case that the owner has Symbol.metadata defined (e.g. from base class),
// then merge it current metadata. This ensures that inheritance works as
// intended, whilst a base class still keeping its original metadata.
if (Reflect.has(owner, METADATA)) {
// @ts-expect-error: Owner has Symbol.metadata!
metadata = Object.assign(metadata, owner[METADATA]);
}
return metadata;
} | Variant | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.