code stringlengths 12 2.05k | label_name stringclasses 5
values | label int64 0 4 |
|---|---|---|
}
actionItems() {
let composing = new PrivateComposing(this.user);
const items = new ItemList();
if (app.session.user && app.forum.attribute('canStartPrivateDiscussion')) {
items.add('start_private', composing.component());
}
| Class | 2 |
PageantSock.prototype.connect = function() {
this.emit('connect');
}; | Base | 1 |
const addReplyToEvent = (event: any) => {
event.reply = (...args: any[]) => {
event.sender.sendToFrame(event.frameId, ...args);
};
}; | Class | 2 |
): void => {
const name = createElement('h2', CLASS_CATEGORY_NAME);
name.innerHTML =
this.i18n.categories[category] || defaultI18n.categories[category];
this.emojis.appendChild(name);
this.headers.push(name);
this.emojis.appendChild(
new EmojiContainer(
emojis,
true,
... | Base | 1 |
constructor({ log, port }: { log: LogEntry; port?: number }) {
this.log = log
this.debugLog = this.log.placeholder({ level: LogLevel.debug, childEntriesInheritLevel: true })
this.garden = undefined
this.port = port
this.authKey = randomString(64)
this.incomingEvents = new EventBus()
this.a... | Base | 1 |
function generate(target, hierarchies, forceOverride) {
let current = target;
hierarchies.forEach(info => {
const descriptor = normalizeDescriptor(info);
const { value, type, create, override, created, skipped, got } = descriptor;
const name = getNonEmptyPropName(current, descriptor);
... | Variant | 0 |
constructor({asset, message, onClick}: Params, element: HTMLElement) {
super(message);
this.asset = asset;
this.message = message;
this.isVisible = ko.observable(false);
this.onClick = (_data, event) => onClick(message, event);
this.dummyImageUrl = `data:image/svg+xml;utf8,<svg xmlns='http://... | Base | 1 |
setEntries(entries) {
if (entries.length === 0) {
this.emptyList();
return;
}
let htmlToInsert = '';
for (let timesheet of entries) {
let label = this.attributes['template']
.replace('%customer%', timesheet.project.customer.name)
... | Base | 1 |
export function loadEmailAddressesAndLoginMethods(userId: UserId, success: UserAcctRespHandler) {
get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => {
success(response);
});
} | Base | 1 |
const assigner = ( ...args: any[] ) => {
console.log( { args } )
return args.reduce( ( a, b ) => {
if ( untracker.includes( a ) ) throw new TypeError( `can't convert ${a} to object` )
if ( useuntrack && untracker.includes( b ) ) return a
Object.keys( b ).forEach( key => {
if ( untrac... | Base | 1 |
function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {
const response = new ResponseClass({
responseHeader: { serviceResult: statusCode }
});
return channel.send_response("MSG", response, message);
} | Class | 2 |
function checkCredentials(req, res, next) {
if (!sqlInit.isDbInitialized()) {
res.status(400).send('Database is not initialized yet.');
return;
}
if (!passwordService.isPasswordSet()) {
res.status(400).send('Password has not been set yet. Please set a password and repeat the action'... | Base | 1 |
function simulateTransation(request: FindServersRequest, response: FindServersResponse, callback: SimpleCallback) {
serverSChannel.once("message", (message: Message) => {
doDebug && console.log("server receiving message =", response.responseHeader.requestHandle);
resp... | Class | 2 |
async function installMonitoredItem(subscription, nodeId) {
debugLog("installMonitoredItem", nodeId.toString());
const monitoredItem = await subscription.monitor(
{ nodeId, attributeId: AttributeIds.Value },
{
samplingInterval: 0, // reports immediately
discardOldest: tru... | Class | 2 |
schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propertyMetadata.type)};
}
schemaTypeOptions = cleanProps({...schemaTypeOptions, ...rawMongooseSchema});
if (propertyMetadata.isCollection) {
if (propertyMetadata.isArray) {
schemaTypeOptions = [schemaTypeOptions];
} else {
// Ca... | Base | 1 |
__(key) {
self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent`
The req.__() and res.__() functions are deprecated and do not localize in A3.
Use req.t instead.
`);
return key;
} | Base | 1 |
provisionCallback: (user, renew, cb) => {
cb(null, 'zzz');
}
});
xoauth2.getToken(false, function(err, accessToken) {
expect(err).to.not.exist;
expect(accessToken).to.equal('zzz');
done();
});
}); | Base | 1 |
private _on_receive_message_chunk(messageChunk: Buffer) {
/* istanbul ignore next */
if (doDebug1) {
const _stream = new BinaryStream(messageChunk);
const messageHeader = readMessageHeader(_stream);
debugLog("CLIENT RECEIVED " + chalk.yellow(JSON.stringify(me... | Class | 2 |
const {type, store = JsonEntityStore.from(type), ...next} = options;
const propertiesMap = getPropertiesStores(store);
let keys = Object.keys(src);
const additionalProperties = propertiesMap.size ? !!store.schema.get("additionalProperties") || options.additionalProperties : true;
const out: any = new type(sr... | Base | 1 |
function onconnect() {
var buf;
if (isSigning) {
/*
byte SSH2_AGENTC_SIGN_REQUEST
string key_blob
string data
uint32 flags
*/
var p = 9;
buf = Buffer.allocUnsafe(4 + 1 + 4 + keylen + 4 + datalen + 4);
writeUInt32BE(buf, buf.le... | Base | 1 |
static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {
// # Parse data as unsigned-big-endian encoded integer.
// # For empty data different possibilities may occur:
// # minByteLen <= 0 : return 0
// # raise_on_Null == Fal... | Class | 2 |
get lokadIdHex() { return "534c5000" } | Class | 2 |
function exportBranch(req, res) {
const {branchId, type, format, version, taskId} = req.params;
const branch = becca.getBranch(branchId);
if (!branch) {
const message = `Cannot export branch ${branchId} since it does not exist.`;
log.error(message);
res.status(500).send(message);
... | Base | 1 |
module.exports = function(key) {
key = normalizeKey(key.split('@').pop());
return normalized[key] || false;
}; | Base | 1 |
function _ondata(data) {
bc += data.length;
if (state === 'secret') {
// the secret we sent is echoed back to us by cygwin, not sure of
// the reason for that, but we ignore it nonetheless ...
if (bc === 16) {
bc = 0;
... | Base | 1 |
triggerMassAction: function (massActionUrl, type) {
const self = this.relatedListInstance;
let validationResult = self.checkListRecordSelected();
if (validationResult != true) {
let progressIndicatorElement = $.progressIndicator(),
selectedIds = self.readSelectedIds(true),
excludedIds = self.re... | Compound | 4 |
updateOidcSettings(configuration) {
checkAdminAuthentication(this)
ServiceConfiguration.configurations.remove({
service: 'oidc',
})
ServiceConfiguration.configurations.insert(configuration)
} | Class | 2 |
export declare function applyCommandArgs(configuration: any, argv: string[]): void;
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void; | Base | 1 |
error: err => {
reject(err)
this.fetching = this.fetching.remove(this.hash(session))
}, | Base | 1 |
function userBroadcast(msg, source) {
var sourceMsg = '> ' + msg;
var name = '{cyan-fg}{bold}' + source.name + '{/}';
msg = ': ' + msg;
for (var i = 0; i < users.length; ++i) {
var user = users[i];
var output = user.output;
if (source === user)
output.add(sourceMsg);
else
output.add(... | Base | 1 |
getScriptOperations(script: Buffer) {
let ops: PushDataOperation[] = [];
try {
let n = 0;
let dlen: number;
while (n < script.length) {
let op: PushDataOperation = { opcode: script[n], data: null }
n += 1;
if(op.opco... | Class | 2 |
response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing);
}
await send_registered_server_request(discoveryServerEndpointUrl, request, check_response);
}); | Class | 2 |
export function setupCleanupOnExit(cssPath: string) {
if (!hasSetupCleanupOnExit){
process.on('SIGINT', () => {
console.log('Exiting, running CSS cleanup');
exec(`rm -r ${cssPath}`, function(error) {
if (error) {
console.error(error);
process.exit(1);
}
co... | Base | 1 |
function simulateOpenSecureChannel(callback: SimpleCallback) {
clientChannel.create("fake://foobar:123", (err?: Error) => {
if (param.shouldFailAtClientConnection) {
if (!err) {
return callback(new Error(" Shoul... | Class | 2 |
function applyCommandArgs(configuration, argv) {
if (!argv || !argv.length) {
return;
}
argv = argv.slice(2);
const parsedArgv = yargs(argv);
const argvKeys = Object.keys(parsedArgv);
if (!argvKeys.length) {
return;
}
debug("Appling command arguments:", parsedArgv);
i... | Base | 1 |
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
if (typeof channel !== 'string') {
throw new Error('Missing required channel argument');
} else if (typeof frameId !== 'number') {
throw new Error('Missing required frameId argument');
}
return this._sendToFrame(false /* interna... | Class | 2 |
export function verify_multi_chunk_message(packets: any[]) {
const messageBuilder = new MessageBuilder({});
messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);
messageBuilder.on("full_message_body", (fullMessageBody: Buffer) => {
console.log("full_message_body received:");
... | Class | 2 |
function text({ url, host }: Record<"url" | "host", string>) {
return `Sign in to ${host}\n${url}\n\n`
} | Base | 1 |
await manager.update(User, organizationUser.userId, { invitationToken: uuid.v4(), password: uuid.v4() });
}); | Class | 2 |
constructor(options?: { signatureLength?: number }) {
super();
this.id = "";
this._tick0 = 0;
this._tick1 = 0;
this._hasReceivedError = false;
this.blocks = [];
this.messageChunks = [];
this._expectedChannelId = 0;
options = options || {};
... | Class | 2 |
async signup(params: any) {
// Check if the installation allows user signups
if (process.env.DISABLE_SIGNUPS === 'true') {
return {};
}
const { email } = params;
const existingUser = await this.usersService.findByEmail(email);
if (existingUser) {
throw new NotAcceptableException('... | Class | 2 |
function escapeShellArg(arg) {
return arg.replace(/'/g, `'\\''`);
} | Base | 1 |
putComment(comment, isMarkdown, commentId, author) {
const { pageId, revisionId } = this.getPageContainer().state;
return this.appContainer.apiPost('/comments.update', {
commentForm: {
comment,
page_id: pageId,
revision_id: revisionId,
is_markdown: isMarkdown,
co... | Base | 1 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, | Base | 1 |
onBannerChange (input: HTMLInputElement) {
this.bannerfileInput = new ElementRef(input)
const bannerfile = this.bannerfileInput.nativeElement.files[0]
if (bannerfile.size > this.maxBannerSize) {
this.notifier.error('Error', $localize`This image is too large.`)
return
}
const formData... | Base | 1 |
function set(target, path, val) {
"use strict";
try {
return add(target, path, val);
} catch(ex) {
console.error(ex);
return;
}
} | Base | 1 |
node.addEventListener("mouseenter", () => {
const t = tooltip();
t.innerHTML = getter();
}); | Base | 1 |
requestResetPassword(req) {
const config = req.config;
if (!config) {
this.invalidRequest();
}
if (!config.publicServerURL) {
return this.missingPublicServerURL();
}
const { username, token } = req.query;
if (!username || !token) {
return this.invalidLink(req);
}
... | Class | 2 |
export function escape<T>(input: T): T extends SafeValue ? T['value'] : T {
return typeof input === 'string'
? string.escapeHTML(input)
: input instanceof SafeValue
? input.value
: input
} | Base | 1 |
const unSet = (obj, path, options = {}, tracking = {}) => {
let internalPath = path;
options = {
"transformRead": returnWhatWasGiven,
"transformKey": returnWhatWasGiven,
"transformWrite": returnWhatWasGiven,
...options
};
// No object data
if (obj === undefined || obj === null) {
return;
}
// No ... | Base | 1 |
function PageantSock() {
this.proc = undefined;
this.buffer = null;
} | Base | 1 |
export function parse(data: string, params?: IParseConfig): IIniObject {
const {
delimiter = '=',
comment = ';',
nothrow = false,
autoTyping = true,
dataSections = [],
} = { ...params };
let typeParser: ICustomTyping;
if (typeof autoTyping === 'function') {
typeParser = autoTyping;
} e... | Variant | 0 |
export function cleanObject(obj: any): any {
return Object.entries(obj).reduce(
(obj, [key, value]) =>
value === undefined
? obj
: {
...obj,
[key]: value
},
{}
);
} | Base | 1 |
constructor(options?: MessageChunkerOptions) {
options = options || {};
this.sequenceNumberGenerator = new SequenceNumberGenerator();
this.maxMessageSize = options.maxMessageSize || 16 *1024*1024;
this.update(options);
} | Class | 2 |
function main() {
try {
let tag = process.env.GITHUB_REF;
if (core.getInput('tag')) {
tag = `refs/tags/${core.getInput('tag')}`;
}
exec(`git for-each-ref --format='%(contents)' ${tag}`, (err, stdout) => {
if (err) {
core.setFailed(err);
} else {
core.setOutput('git-t... | Base | 1 |
get: (path) => {
useCount++;
expect(path).toEqual('somepath');
},
})
).not.toThrow();
expect(useCount).toBeGreaterThan(0);
}); | Class | 2 |
constructor() {
super();
this.name = this.constructor.name + counter;
counter += 1;
this._timerId = null;
this._timeout = 30000; // 30 seconds timeout
this._socket = null;
this.headerSize = 8;
this.protocolVersion = 0;
this._disconnecting = ... | Class | 2 |
export async function recursiveReadDir(dir: string): Promise<string[]> {
const subdirs = await readdir(dir);
const files = await Promise.all(
subdirs.map(async subdir => {
const res = resolve(dir, subdir);
return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res];
}),
);
return ... | Base | 1 |
func cssGogsMinCss() (*asset, error) {
bytes, err := cssGogsMinCssBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "css/gogs.min.css", size: 64378, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xd9, 0x49, 0xa9, 0x99, 0... | Base | 1 |
link: new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
const context = operation.getContext();
const {
response: { headers },
} = context;
expect(headers.get('access-control-allow-origin')... | Class | 2 |
async handler(ctx) {
ctx.logStream.write(`Writing catalog-info.yaml`);
const { entity } = ctx.input;
await fs.writeFile(
resolvePath(ctx.workspacePath, 'catalog-info.yaml'),
yaml.stringify(entity),
);
}, | Base | 1 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
totalHours,
} | Base | 1 |
) => {
if (!info || !info.sessionToken) {
throw new Parse.Error(
Parse.Error.INVALID_SESSION_TOKEN,
'Invalid session token'
);
}
const sessionToken = info.sessionToken;
const selectedFields = getFieldNames(queryInfo)
.filter(field => field.startsWith(keysPrefix))
.map(field => field.... | Class | 2 |
export function escapeCommentText(value: string): string {
return value.replace(END_COMMENT, END_COMMENT_ESCAPED);
} | Base | 1 |
export default async function email(
identifier: string,
options: InternalOptions<"email">
) {
const { url, adapter, provider, logger, callbackUrl } = options
// Generate token
const token =
(await provider.generateVerificationToken?.()) ?? | Base | 1 |
groupNames: groups.join(", "),
}),
"warning"
);
}
}); | Base | 1 |
export function escape(value: unknown, is_attr = false) {
const str = String(value);
const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
pattern.lastIndex = 0;
let escaped = '';
let last = 0;
while (pattern.test(str)) {
const i = pattern.lastIndex - 1;
const ch = str[i];
escaped += str.substring... | Base | 1 |
func cssGogsMinCssMap() (*asset, error) {
bytes, err := cssGogsMinCssMapBytes()
if err != nil {
return nil, err
}
info := bindataFileInfo{name: "css/gogs.min.css.map", size: 22926, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)}
a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x46, 0x89, 0xb... | Base | 1 |
await getManager().transaction(async (manager) => {
const organizationUser = await manager.findOne(OrganizationUser, { where: { id } });
const user = await manager.findOne(User, { where: { id: organizationUser.userId } });
await this.usersService.throwErrorIfRemovingLastActiveAdmin(user);
... | Class | 2 |
return { session: new Capnp.Capability(new ExternalWebSession(this.url, options), ApiSession) }; | Base | 1 |
async function validateSPLTokenTransfer(
message: Message,
meta: ConfirmedTransactionMeta,
recipient: Recipient,
splToken: SPLToken
): Promise<[BigNumber, BigNumber]> {
const recipientATA = await getAssociatedTokenAddress(splToken, recipient);
const accountIndex = message.accountKeys.findIndex((... | Class | 2 |
redirect: `${url}/error?${new URLSearchParams({
error: error as string,
})}`,
}
}
try {
const redirect = await emailSignin(email, options)
return { redirect }
} catch (error) {
logger.error("SIGNIN_EMAIL_ERROR", {
error: error as Error,
prov... | Class | 2 |
export function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPa... | Variant | 0 |
function cleaner() {
setTimeout(() => {
if (ids.length < 1) { return; }
ActiveRooms.forEach((element, index) => {
element.Players.forEach((element2, index2) => {
if (!ids.includes(element2.Id)) {
ActiveRooms[index].Players.splice(index2, 1);
ActiveRooms[index].Players.forEach... | Compound | 4 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, | Base | 1 |
html: html({ url, host, theme }),
})
const failed = result.rejected.concat(result.pending).filter(Boolean)
if (failed.length) {
throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`)
}
},
options,
}
} | Class | 2 |
text: text({ url, host }),
html: html({ url, host, email }),
})
},
options,
}
} | Base | 1 |
function formatMessage(msg, output) {
var output = output;
output.parseTags = true;
msg = output._parseTags(msg);
output.parseTags = false;
return msg;
} | Base | 1 |
function localMessage(msg, source) {
var output = source.output;
output.add(formatMessage(msg, output));
} | Base | 1 |
async convert(input, options) {
this[_validate]();
options = this[_parseOptions](options);
const output = await this[_convert](input, options);
return output;
} | Base | 1 |
text: () => string
): { destroy: () => void; update: (t: () => string) => void } { | Base | 1 |
async function logPlatform(logger: Logger): Promise<void> {
const os = require('os');
let platform = os.platform();
logger.log(`OS is ${platform}`);
if (platform === 'darwin' || platform === 'win32') {
return;
}
const osInfo = require('linux-os-info');
const result = await osInfo();
const dist... | Class | 2 |
function reject(req, res, message) {
log.info(`${req.method} ${req.path} rejected with 401 ${message}`);
res.status(401).send(message);
} | Base | 1 |
([ key, value ]) => ({ [key]: list.bind(null, value) }),
), | Base | 1 |
function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {
// eslint-disable-next-line no-undef
const wr = new WeakRef<CallIntoRenderer>(value);
const mapKey = id[0] + '~' + id[1];
rendererFunctionCache.set(mapKey, wr);
finalizationRegistr... | Class | 2 |
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;
export declare function getDeepProperty(obj: any, propertyPath: string): any; | Base | 1 |
calculateGenesisCost(genesisOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {
return this.calculateMintOrGenesisCost(genesisOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);
} | Class | 2 |
module.exports = async function(path) {
if (!path || typeof path !== 'string') {
throw new TypeError(`string was expected, instead got ${path}`);
}
const absolute = resolve(path);
if (!(await exist(absolute))) {
throw new Error(`Could not find file at path "${absolute}"`);
}
const ts = await exec(`git log ... | Base | 1 |
template({ labelInfo, labelHead, iconSync, iconAdd, pfx, ppfx }: any) {
return `
<div id="${pfx}up" class="${pfx}header">
<div id="${pfx}label" class="${pfx}header-label">${labelHead}</div>
<div id="${pfx}status-c" class="${pfx}header-status">
<span id="${pfx}input-c" data-states-c>
... | Base | 1 |
function detailedDataTableMapper(entry) {
const project = Projects.findOne({ _id: entry.projectId })
const mapping = [project ? project.name : '',
dayjs.utc(entry.date).format(getGlobalSetting('dateformat')),
entry.task,
projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === e... | Base | 1 |
constructor (
private sanitizer: DomSanitizer,
private serverService: ServerService,
private notifier: Notifier
) { } | Base | 1 |
[req.locale]: self.getBrowserBundles(req.locale)
};
if (req.locale !== self.defaultLocale) {
i18n[self.defaultLocale] = self.getBrowserBundles(self.defaultLocale);
}
const result = {
i18n,
locale: req.locale,
defaultLocale: self.defaultLo... | Base | 1 |
function networkStats(ifaces, callback) {
let ifacesArray = [];
// fallback - if only callback is given
if (util.isFunction(ifaces) && !callback) {
callback = ifaces;
ifacesArray = [getDefaultNetworkInterface()];
} else {
ifaces = ifaces || getDefaultNetworkInterface();
ifaces = ifaces.trim().t... | Base | 1 |
get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
})) | Class | 2 |
onUpdate: function(username, accessToken) {
users[username] = accessToken;
} | Base | 1 |
get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })
})) | Class | 2 |
parse(cookieStr) {
let cookie = {};
(cookieStr || '')
.toString()
.split(';')
.forEach(cookiePart => {
let valueParts = cookiePart.split('=');
let key = valueParts
.shift()
.trim()
... | Base | 1 |
Server.loadMyself((anyMe: Me | NU, stuffForMe?: StuffForMe) => {
// @ifdef DEBUG
// Might happen if there was no weakSessionId, and also, no cookie.
dieIf(!anyMe, 'TyE4032SMH57');
// @endif
const newMe = anyMe as Me;
if (isInSomeEmbCommentsIframe()) {
// Tell the embedded comments or emb... | Base | 1 |
module.exports = (yargs) => {
yargs.command('exec <container name> [commands...]', 'Execute command in docker container', () => {}, async (argv) => {
const containers = docker.getContainers();
const services = Object.keys(containers);
if (services.includes(argv.containername) || services.so... | Class | 2 |
userPassword: bcrypt.hashSync(req.body.userPassword, 10),
isAdmin: isAdmin
};
// check for existing user
db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => {
if(user){
// user already exists with that email address
console.error(colors.red('Fa... | Class | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.