_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q22600
formatClassicOptions
train
function formatClassicOptions(options) { return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 't...
javascript
{ "resource": "" }
q22601
enqueue
train
function enqueue(fn) { window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); }
javascript
{ "resource": "" }
q22602
variation
train
function variation(id) { var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; }
javascript
{ "resource": "" }
q22603
push
train
function push(callback) { window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); }
javascript
{ "resource": "" }
q22604
chunkLength
train
function chunkLength (chunk, encoding) { if (!chunk) { return 0 } return !Buffer.isBuffer(chunk) ? Buffer.byteLength(chunk, encoding) : chunk.length }
javascript
{ "resource": "" }
q22605
shouldCompress
train
function shouldCompress (req, res) { var type = res.getHeader('Content-Type') if (type === undefined || !compressible(type)) { debug('%s not compressible', type) return false } return true }
javascript
{ "resource": "" }
q22606
shouldTransform
train
function shouldTransform (req, res) { var cacheControl = res.getHeader('Cache-Control') // Don't compress for Cache-Control: no-transform // https://tools.ietf.org/html/rfc7234#section-5.2.2.4 return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl) }
javascript
{ "resource": "" }
q22607
toBuffer
train
function toBuffer (chunk, encoding) { return !Buffer.isBuffer(chunk) ? Buffer.from(chunk, encoding) : chunk }
javascript
{ "resource": "" }
q22608
transform
train
function transform(hash, styles, settings = {}) { generator = settings.generator offset = settings.offset filename = settings.filename splitRules = [] stylis.set({ prefix: typeof settings.vendorPrefixes === 'boolean' ? settings.vendorPrefixes : true }) stylis(hash, styles) i...
javascript
{ "resource": "" }
q22609
addClasses
train
function addClasses (el, classStr) { if (typeof classStr !== 'string' || classStr.length === 0) { return } var classes = classStr.split(' ') for (var i = 0; i < classes.length; i++) { var className = classes[i] if (className.length) { el.classList.add(className) } } }
javascript
{ "resource": "" }
q22610
close
train
function close (vexOrId) { var id if (vexOrId.id) { id = vexOrId.id } else if (typeof vexOrId === 'string') { id = vexOrId } else { throw new TypeError('close requires a vex object or id string') } if (!vexes[id]) { return false } return vexes[id].close() }
javascript
{ "resource": "" }
q22611
rollback
train
function rollback(newVersion) { if (strategy === 'stable') { // reset master shell.exec('git reset --hard origin/master'); shell.exec('git checkout develop'); } else { // remove last commit shell.exec('git reset --hard HEAD~1'); } // remove local created tag shell.exec(`git tag -d v${newV...
javascript
{ "resource": "" }
q22612
transformTemplates
train
function transformTemplates(templates) { const allTemplates = { ...templates, submit: templates.searchableSubmit, reset: templates.searchableReset, loadingIndicator: templates.searchableLoadingIndicator, }; const { searchableReset, searchableSubmit, searchableLoadingIndicator, ......
javascript
{ "resource": "" }
q22613
clearRefinements
train
function clearRefinements({ helper, attributesToClear = [] }) { let finalState = helper.state; attributesToClear.forEach(attribute => { if (attribute === '_tags') { finalState = finalState.clearTags(); } else { finalState = finalState.clearRefinements(attribute); } }); if (attributesTo...
javascript
{ "resource": "" }
q22614
prepareTemplateProps
train
function prepareTemplateProps({ defaultTemplates, templates, templatesConfig, }) { const preparedTemplates = prepareTemplates(defaultTemplates, templates); return { templatesConfig, ...preparedTemplates, }; }
javascript
{ "resource": "" }
q22615
getDependencies
train
function getDependencies(bundleType, entry) { const packageJson = require(path.dirname(require.resolve(entry)) + "/package.json") // Both deps and peerDeps are assumed as accessible. return Array.from( new Set([ ...Object.keys(packageJson.dependencies || {}), ...Object.keys(packageJson.peerDep...
javascript
{ "resource": "" }
q22616
inputSymbol
train
async function inputSymbol(symbol) { if (typeof symbol === 'undefined') { STSymbol = readlineSync.question(chalk.yellow(`Enter the symbol of a registered security token or press 'Enter' to exit: `)); } else { STSymbol = symbol; } if (STSymbol == "") process.exit(); STAddress = awai...
javascript
{ "resource": "" }
q22617
addModule
train
async function addModule() { let options = ['Permission Manager', 'Transfer Manager', 'Security Token Offering', 'Dividends', 'Burn']; let index = readlineSync.keyInSelect(options, 'What type of module would you like to add?', { cancel: 'Return' }); switch (options[index]) { case 'Permission Manager': c...
javascript
{ "resource": "" }
q22618
cleanupOS
train
function cleanupOS(os, pattern, label) { // Platform tokens are defined at: // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx var data = { '10.0': '10', '6.4': '10 Technic...
javascript
{ "resource": "" }
q22619
each
train
function each(object, callback) { var index = -1, length = object ? object.length : 0; if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) { while (++index < length) { callback(object[index], index, object); } } else { forOwn(object, callback); } ...
javascript
{ "resource": "" }
q22620
format
train
function format(string) { string = trim(string); return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string); }
javascript
{ "resource": "" }
q22621
forOwn
train
function forOwn(object, callback) { for (var key in object) { if (hasOwnProperty.call(object, key)) { callback(object[key], key, object); } } }
javascript
{ "resource": "" }
q22622
getManufacturer
train
function getManufacturer(guesses) { return reduce(guesses, function(result, value, key) { // Lookup the manufacturer by product or scan the UA for the manufacturer. return result || ( value[product] || value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + q...
javascript
{ "resource": "" }
q22623
getOS
train
function getOS(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua) )) { result = cleanupOS(result, pattern, guess.labe...
javascript
{ "resource": "" }
q22624
getProduct
train
function getProduct(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) ||...
javascript
{ "resource": "" }
q22625
getVersion
train
function getVersion(patterns) { return reduce(patterns, function(result, pattern) { return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; }); }
javascript
{ "resource": "" }
q22626
Characteristic
train
function Characteristic(displayName, UUID, props) { this.displayName = displayName; this.UUID = UUID; this.iid = null; // assigned by our containing Service this.value = null; this.status = null; this.eventOnlyCharacteristic = false; this.props = props || { format: null, unit: null, minValue: ...
javascript
{ "resource": "" }
q22627
AccessoryInfo
train
function AccessoryInfo(username) { this.username = username; this.displayName = ""; this.category = ""; this.pincode = ""; this.signSk = bufferShim.alloc(0); this.signPk = bufferShim.alloc(0); this.pairedClients = {}; // pairedClients[clientUsername:string] = clientPublicKey:Buffer this.configVersion = ...
javascript
{ "resource": "" }
q22628
EventedHTTPServerConnection
train
function EventedHTTPServerConnection(clientSocket) { this.sessionID = uuid.generate(clientSocket.remoteAddress + ':' + clientSocket.remotePort); this._remoteAddress = clientSocket.remoteAddress; // cache because it becomes undefined in 'onClientSocketClose' this._pendingClientSocketData = bufferShim.alloc(0); //...
javascript
{ "resource": "" }
q22629
Service
train
function Service(displayName, UUID, subtype) { if (!UUID) throw new Error("Services must be created with a valid UUID."); this.displayName = displayName; this.UUID = UUID; this.subtype = subtype; this.iid = null; // assigned later by our containing Accessory this.characteristics = []; this.optionalChara...
javascript
{ "resource": "" }
q22630
clone
train
function clone(object, extend) { var cloned = {}; for (var key in object) { cloned[key] = object[key]; } for (var key in extend) { cloned[key] = extend[key]; } return cloned; }
javascript
{ "resource": "" }
q22631
Accessory
train
function Accessory(displayName, UUID) { if (!displayName) throw new Error("Accessories must be created with a non-empty displayName."); if (!UUID) throw new Error("Accessories must be created with a valid UUID."); if (!uuid.isValid(UUID)) throw new Error("UUID '" + UUID + "' is not a valid UUID. Try using the pr...
javascript
{ "resource": "" }
q22632
HAPServer
train
function HAPServer(accessoryInfo, relayServer) { this.accessoryInfo = accessoryInfo; this.allowInsecureRequest = false; // internal server that does all the actual communication this._httpServer = new EventedHTTPServer(); this._httpServer.on('listening', this._onListening.bind(this)); this._httpServer.on('...
javascript
{ "resource": "" }
q22633
HAPEncryption
train
function HAPEncryption() { // initialize member vars with null-object values this.clientPublicKey = bufferShim.alloc(0); this.secretKey = bufferShim.alloc(0); this.publicKey = bufferShim.alloc(0); this.sharedSec = bufferShim.alloc(0); this.hkdfPairEncKey = bufferShim.alloc(0); this.accessoryToControllerCo...
javascript
{ "resource": "" }
q22634
Advertiser
train
function Advertiser(accessoryInfo, mdnsConfig) { this.accessoryInfo = accessoryInfo; this._bonjourService = bonjour(mdnsConfig); this._advertisement = null; this._setupHash = this._computeSetupHash(); }
javascript
{ "resource": "" }
q22635
loadDirectory
train
function loadDirectory(dir) { // exported accessory objects loaded from this dir var accessories = []; fs.readdirSync(dir).forEach(function(file) { // "Accessories" are modules that export a single accessory. if (file.split('_').pop() === 'accessory.js') { debug('Parsing accessory: %s', file); ...
javascript
{ "resource": "" }
q22636
TimelineWindow
train
function TimelineWindow(client, timelineSet, opts) { opts = opts || {}; this._client = client; this._timelineSet = timelineSet; // these will be TimelineIndex objects; they delineate the 'start' and // 'end' of the window. // // _start.index is inclusive; _end.index is exclusive. this._...
javascript
{ "resource": "" }
q22637
train
function(timeline) { let eventIndex; const events = timeline.getEvents(); if (!initialEventId) { // we were looking for the live timeline: initialise to the end eventIndex = events.length; } else { for (let i = 0; i < events.length; i++) { ...
javascript
{ "resource": "" }
q22638
createOlmSession
train
function createOlmSession(olmAccount, recipientTestClient) { return recipientTestClient.awaitOneTimeKeyUpload().then((keys) => { const otkId = utils.keys(keys)[0]; const otk = keys[otkId]; const session = new global.Olm.Session(); session.create_outbound( olmAccount, rec...
javascript
{ "resource": "" }
q22639
encryptOlmEvent
train
function encryptOlmEvent(opts) { expect(opts.senderKey).toBeTruthy(); expect(opts.p2pSession).toBeTruthy(); expect(opts.recipient).toBeTruthy(); const plaintext = { content: opts.plaincontent || {}, recipient: opts.recipient.userId, recipient_keys: { ed25519: opts.re...
javascript
{ "resource": "" }
q22640
encryptMegolmEvent
train
function encryptMegolmEvent(opts) { expect(opts.senderKey).toBeTruthy(); expect(opts.groupSession).toBeTruthy(); const plaintext = opts.plaintext || {}; if (!plaintext.content) { plaintext.content = { body: '42', msgtype: "m.text", }; } if (!plaintext.typ...
javascript
{ "resource": "" }
q22641
encryptGroupSessionKey
train
function encryptGroupSessionKey(opts) { return encryptOlmEvent({ senderKey: opts.senderKey, recipient: opts.recipient, p2pSession: opts.p2pSession, plaincontent: { algorithm: 'm.megolm.v1.aes-sha2', room_id: opts.room_id, session_id: opts.groupSess...
javascript
{ "resource": "" }
q22642
WebStorageSessionStore
train
function WebStorageSessionStore(webStore) { this.store = webStore; if (!utils.isFunction(webStore.getItem) || !utils.isFunction(webStore.setItem) || !utils.isFunction(webStore.removeItem) || !utils.isFunction(webStore.key) || typeof(webStore.length) !== 'number' ) { ...
javascript
{ "resource": "" }
q22643
train
function() { const prefix = keyEndToEndDevicesForUser(''); const devices = {}; for (let i = 0; i < this.store.length; ++i) { const key = this.store.key(i); const userId = key.substr(prefix.length); if (key.startsWith(prefix)) devices[userId] = getJsonItem(this...
javascript
{ "resource": "" }
q22644
train
function() { const deviceKeys = getKeysWithPrefix(this.store, keyEndToEndSessions('')); const results = {}; for (const k of deviceKeys) { const unprefixedKey = k.substr(keyEndToEndSessions('').length); results[unprefixedKey] = getJsonItem(this.store, k); } ...
javascript
{ "resource": "" }
q22645
train
function() { const prefix = E2E_PREFIX + 'inboundgroupsessions/'; const result = []; for (let i = 0; i < this.store.length; i++) { const key = this.store.key(i); if (!key.startsWith(prefix)) { continue; } // we can't use split, as t...
javascript
{ "resource": "" }
q22646
train
function() { const roomKeys = getKeysWithPrefix(this.store, keyEndToEndRoom('')); const results = {}; for (const k of roomKeys) { const unprefixedKey = k.substr(keyEndToEndRoom('').length); results[unprefixedKey] = getJsonItem(this.store, k); } return resu...
javascript
{ "resource": "" }
q22647
IndexedDBStore
train
function IndexedDBStore(opts) { MemoryStore.call(this, opts); if (!opts.indexedDB) { throw new Error('Missing required option: indexedDB'); } if (opts.workerScript) { // try & find a webworker-compatible API let workerApi = opts.workerApi; if (!workerApi) { ...
javascript
{ "resource": "" }
q22648
degradable
train
function degradable(func, fallback) { return async function(...args) { try { return await func.call(this, ...args); } catch (e) { console.error("IndexedDBStore failure, degrading to MemoryStore", e); this.emit("degraded", e); try { // W...
javascript
{ "resource": "" }
q22649
MatrixBaseApis
train
function MatrixBaseApis(opts) { utils.checkObjectHasKeys(opts, ["baseUrl", "request"]); this.baseUrl = opts.baseUrl; this.idBaseUrl = opts.idBaseUrl; const httpOpts = { baseUrl: opts.baseUrl, idBaseUrl: opts.idBaseUrl, accessToken: opts.accessToken, request: opts.reques...
javascript
{ "resource": "" }
q22650
_scheduleRealCallback
train
function _scheduleRealCallback() { if (_realCallbackKey) { global.clearTimeout(_realCallbackKey); } const first = _callbackList[0]; if (!first) { debuglog("_scheduleRealCallback: no more callbacks, not rescheduling"); return; } const now = _now(); const delayMs = M...
javascript
{ "resource": "" }
q22651
Room
train
function Room(roomId, client, myUserId, opts) { opts = opts || {}; opts.pendingEventOrdering = opts.pendingEventOrdering || "chronological"; this.reEmitter = new ReEmitter(this); if (["chronological", "detached"].indexOf(opts.pendingEventOrdering) === -1) { throw new Error( "opts.p...
javascript
{ "resource": "" }
q22652
calculateRoomName
train
function calculateRoomName(room, userId, ignoreRoomNameEvent) { if (!ignoreRoomNameEvent) { // check for an alias, if any. for now, assume first alias is the // official one. const mRoomName = room.currentState.getStateEvents("m.room.name", ""); if (mRoomName && mRoomName.getContent(...
javascript
{ "resource": "" }
q22653
InteractiveAuth
train
function InteractiveAuth(opts) { this._matrixClient = opts.matrixClient; this._data = opts.authData || {}; this._requestCallback = opts.doRequest; // startAuthStage included for backwards compat this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage; this._completionDeferred = nul...
javascript
{ "resource": "" }
q22654
train
function() { this._completionDeferred = Promise.defer(); // wrap in a promise so that if _startNextAuthStage // throws, it rejects the promise in a consistent way return Promise.resolve().then(() => { // if we have no flows, try a request (we'll have // just a se...
javascript
{ "resource": "" }
q22655
train
function() { if (!this._data.session) return; let authDict = {}; if (this._currentStage == EMAIL_STAGE_TYPE) { // The email can be validated out-of-band, but we need to provide the // creds so the HS can go & check it. if (this._emailSid) { co...
javascript
{ "resource": "" }
q22656
train
function(loginType) { let params = {}; if (this._data && this._data.params) { params = this._data.params; } return params[loginType]; }
javascript
{ "resource": "" }
q22657
train
function(auth, background) { const self = this; // hackery to make sure that synchronous exceptions end up in the catch // handler (without the additional event loop entailed by q.fcall or an // extra Promise.resolve().then) let prom; try { prom = this._reque...
javascript
{ "resource": "" }
q22658
train
function() { const nextStage = this._chooseStage(); if (!nextStage) { throw new Error("No incomplete flows from the server"); } this._currentStage = nextStage; if (nextStage == 'm.login.dummy') { this.submitAuthDict({ type: 'm.login.dummy'...
javascript
{ "resource": "" }
q22659
train
function() { const flow = this._chooseFlow(); console.log("Active flow => %s", JSON.stringify(flow)); const nextStage = this._firstUncompletedStage(flow); console.log("Next stage: %s", nextStage); return nextStage; }
javascript
{ "resource": "" }
q22660
train
function() { const flows = this._data.flows || []; // we've been given an email or we've already done an email part const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid); const haveMsisdn = ( Boolean(this._inputs.phoneCountry) && Boolean...
javascript
{ "resource": "" }
q22661
train
function(flow) { const completed = (this._data || {}).completed || []; for (let i = 0; i < flow.stages.length; ++i) { const stageType = flow.stages[i]; if (completed.indexOf(stageType) === -1) { return stageType; } } }
javascript
{ "resource": "" }
q22662
RoomMember
train
function RoomMember(roomId, userId) { this.roomId = roomId; this.userId = userId; this.typing = false; this.name = userId; this.rawDisplayName = userId; this.powerLevel = 0; this.powerLevelNorm = 0; this.user = null; this.membership = null; this.events = { member: null, ...
javascript
{ "resource": "" }
q22663
RoomState
train
function RoomState(roomId, oobMemberFlags = undefined) { this.roomId = roomId; this.members = { // userId: RoomMember }; this.events = { // eventType: { stateKey: MatrixEvent } }; this.paginationToken = null; this._sentinels = { // userId: RoomMember }; this....
javascript
{ "resource": "" }
q22664
OlmEncryption
train
function OlmEncryption(params) { base.EncryptionAlgorithm.call(this, params); this._sessionPrepared = false; this._prepPromise = null; }
javascript
{ "resource": "" }
q22665
expectAliQueryKeys
train
function expectAliQueryKeys() { // can't query keys before bob has uploaded them expect(bobTestClient.deviceKeys).toBeTruthy(); const bobKeys = {}; bobKeys[bobDeviceId] = bobTestClient.deviceKeys; aliTestClient.httpBackend.when("POST", "/keys/query") .respond(200, function(path, content...
javascript
{ "resource": "" }
q22666
expectBobQueryKeys
train
function expectBobQueryKeys() { // can't query keys before ali has uploaded them expect(aliTestClient.deviceKeys).toBeTruthy(); const aliKeys = {}; aliKeys[aliDeviceId] = aliTestClient.deviceKeys; console.log("query result will be", aliKeys); bobTestClient.httpBackend.when( "POST", "/k...
javascript
{ "resource": "" }
q22667
expectAliClaimKeys
train
function expectAliClaimKeys() { return bobTestClient.awaitOneTimeKeyUpload().then((keys) => { aliTestClient.httpBackend.when( "POST", "/keys/claim", ).respond(200, function(path, content) { const claimType = content.one_time_keys[bobUserId][bobDeviceId]; expect(cl...
javascript
{ "resource": "" }
q22668
aliSendsFirstMessage
train
function aliSendsFirstMessage() { return Promise.all([ sendMessage(aliTestClient.client), expectAliQueryKeys() .then(expectAliClaimKeys) .then(expectAliSendMessageRequest), ]).spread(function(_, ciphertext) { return ciphertext; }); }
javascript
{ "resource": "" }
q22669
aliSendsMessage
train
function aliSendsMessage() { return Promise.all([ sendMessage(aliTestClient.client), expectAliSendMessageRequest(), ]).spread(function(_, ciphertext) { return ciphertext; }); }
javascript
{ "resource": "" }
q22670
expectAliSendMessageRequest
train
function expectAliSendMessageRequest() { return expectSendMessageRequest(aliTestClient.httpBackend).then(function(content) { aliMessages.push(content); expect(utils.keys(content.ciphertext)).toEqual([bobTestClient.getDeviceKey()]); const ciphertext = content.ciphertext[bobTestClient.getDevic...
javascript
{ "resource": "" }
q22671
expectBobSendMessageRequest
train
function expectBobSendMessageRequest() { return expectSendMessageRequest(bobTestClient.httpBackend).then(function(content) { bobMessages.push(content); const aliKeyId = "curve25519:" + aliDeviceId; const aliDeviceCurve25519Key = aliTestClient.deviceKeys.keys[aliKeyId]; expect(utils.k...
javascript
{ "resource": "" }
q22672
OlmDevice
train
function OlmDevice(cryptoStore) { this._cryptoStore = cryptoStore; this._pickleKey = "DEFAULT_KEY"; // don't know these until we load the account from storage in init() this.deviceCurve25519Key = null; this.deviceEd25519Key = null; this._maxOneTimeKeys = null; // we don't bother stashing o...
javascript
{ "resource": "" }
q22673
MegolmEncryption
train
function MegolmEncryption(params) { base.EncryptionAlgorithm.call(this, params); // the most recent attempt to set up a session. This is used to serialise // the session setups, so that we have a race-free view of which session we // are using, and which devices we have shared the keys with. It resolve...
javascript
{ "resource": "" }
q22674
Group
train
function Group(groupId) { this.groupId = groupId; this.name = null; this.avatarUrl = null; this.myMembership = null; this.inviter = null; }
javascript
{ "resource": "" }
q22675
User
train
function User(userId) { this.userId = userId; this.presence = "offline"; this.presenceStatusMsg = null; this._unstable_statusMessage = ""; this.displayName = userId; this.rawDisplayName = userId; this.avatarUrl = null; this.lastActiveAgo = 0; this.lastPresenceTs = 0; this.current...
javascript
{ "resource": "" }
q22676
FilterComponent
train
function FilterComponent(filter_json) { this.filter_json = filter_json; this.types = filter_json.types || null; this.not_types = filter_json.not_types || []; this.rooms = filter_json.rooms || null; this.not_rooms = filter_json.not_rooms || []; this.senders = filter_json.senders || null; t...
javascript
{ "resource": "" }
q22677
train
function() { const params = { access_token: this.opts.accessToken, }; return { base: this.opts.baseUrl, path: "/_matrix/media/v1/upload", params: params, }; }
javascript
{ "resource": "" }
q22678
train
function(path, queryParams, prefix) { let queryString = ""; if (queryParams) { queryString = "?" + utils.encodeParams(queryParams); } return this.opts.baseUrl + prefix + path + queryString; }
javascript
{ "resource": "" }
q22679
parseErrorResponse
train
function parseErrorResponse(response, body) { const httpStatus = response.statusCode; const contentType = getResponseContentType(response); let err; if (contentType) { if (contentType.type === 'application/json') { err = new module.exports.MatrixError(JSON.parse(body)); } el...
javascript
{ "resource": "" }
q22680
keysFromRecoverySession
train
function keysFromRecoverySession(sessions, decryptionKey, roomId) { const keys = []; for (const [sessionId, sessionData] of Object.entries(sessions)) { try { const decrypted = keyFromRecoverySession(sessionData, decryptionKey); decrypted.session_id = sessionId; decryp...
javascript
{ "resource": "" }
q22681
_encryptEventIfNeeded
train
function _encryptEventIfNeeded(client, event, room) { if (event.isEncrypted()) { // this event has already been encrypted; this happens if the // encryption step succeeded, but the send step failed on the first // attempt. return null; } if (!client.isRoomEncrypted(event.get...
javascript
{ "resource": "" }
q22682
_maybeUploadOneTimeKeys
train
function _maybeUploadOneTimeKeys(crypto) { // frequency with which to check & upload one-time keys const uploadPeriod = 1000 * 60; // one minute // max number of keys to upload at once // Creating keys can be an expensive operation so we limit the // number we generate in one go to avoid blocking t...
javascript
{ "resource": "" }
q22683
_uploadOneTimeKeys
train
async function _uploadOneTimeKeys(crypto) { const oneTimeKeys = await crypto._olmDevice.getOneTimeKeys(); const oneTimeJson = {}; const promises = []; for (const keyId in oneTimeKeys.curve25519) { if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { const k = { key: ...
javascript
{ "resource": "" }
q22684
EventTimelineSet
train
function EventTimelineSet(room, opts) { this.room = room; this._timelineSupport = Boolean(opts.timelineSupport); this._liveTimeline = new EventTimeline(this); // just a list - *not* ordered. this._timelines = [this._liveTimeline]; this._eventIdToTimeline = {}; this._filter = opts.filter |...
javascript
{ "resource": "" }
q22685
train
async function(crypto) { // start with a couple of sanity checks. if (!this.isEncrypted()) { throw new Error("Attempt to decrypt event which isn't encrypted"); } if ( this._clearEvent && this._clearEvent.content && this._clearEvent.content.msgtype...
javascript
{ "resource": "" }
q22686
train
function(crypto, userId) { const wireContent = this.getWireContent(); return crypto.requestRoomKey({ algorithm: wireContent.algorithm, room_id: this.getRoomId(), session_id: wireContent.session_id, sender_key: wireContent.sender_key, }, this.getKey...
javascript
{ "resource": "" }
q22687
train
function(userId) { // send the request to all of our own devices, and the // original sending device if it wasn't us. const wireContent = this.getWireContent(); const recipients = [{ userId, deviceId: '*', }]; const sender = this.getSender(); if (sende...
javascript
{ "resource": "" }
q22688
train
function(decryptionResult) { this._clearEvent = decryptionResult.clearEvent; this._senderCurve25519Key = decryptionResult.senderCurve25519Key || null; this._claimedEd25519Key = decryptionResult.claimedEd25519Key || null; this._forwardingCurve25519KeyChain = ...
javascript
{ "resource": "" }
q22689
train
function(redaction_event) { // quick sanity-check if (!redaction_event.event) { throw new Error("invalid redaction_event in makeRedacted"); } // we attempt to replicate what we would see from the server if // the event had been redacted before we saw it. // ...
javascript
{ "resource": "" }
q22690
EventTimeline
train
function EventTimeline(eventTimelineSet) { this._eventTimelineSet = eventTimelineSet; this._roomId = eventTimelineSet.room ? eventTimelineSet.room.roomId : null; this._events = []; this._baseIndex = 0; this._startState = new RoomState(this._roomId); this._startState.paginationToken = null; t...
javascript
{ "resource": "" }
q22691
train
function(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks) { if (typeof mxc !== "string" || !mxc) { return ''; } if (mxc.indexOf("mxc://") !== 0) { if (allowDirectLinks) { return mxc; } else { ...
javascript
{ "resource": "" }
q22692
train
function(baseUrl, identiconString, width, height) { if (!identiconString) { return null; } if (!width) { width = 96; } if (!height) { height = 96; } const params = { width: width, height: height, ...
javascript
{ "resource": "" }
q22693
train
function(room) { this.rooms[room.roomId] = room; // add listeners for room member changes so we can keep the room member // map up-to-date. room.currentState.on("RoomState.members", this._onRoomMember.bind(this)); // add existing members const self = this; room.cu...
javascript
{ "resource": "" }
q22694
train
function(event, state, member) { if (member.membership === "invite") { // We do NOT add invited members because people love to typo user IDs // which would then show up in these lists (!) return; } const user = this.users[member.userId] || new User(member.use...
javascript
{ "resource": "" }
q22695
train
function(filter) { if (!filter) { return; } if (!this.filters[filter.userId]) { this.filters[filter.userId] = {}; } this.filters[filter.userId][filter.filterId] = filter; }
javascript
{ "resource": "" }
q22696
train
function(userId, filterId) { if (!this.filters[userId] || !this.filters[userId][filterId]) { return null; } return this.filters[userId][filterId]; }
javascript
{ "resource": "" }
q22697
train
function(events) { const self = this; events.forEach(function(event) { self.accountData[event.getType()] = event; }); }
javascript
{ "resource": "" }
q22698
startClient
train
function startClient(httpBackend, client) { httpBackend.when("GET", "/pushrules").respond(200, {}); httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" }); httpBackend.when("GET", "/sync").respond(200, INITIAL_SYNC_DATA); client.startClient(); // set up a promise which will resolve...
javascript
{ "resource": "" }
q22699
selectQuery
train
function selectQuery(store, keyRange, resultMapper) { const query = store.openCursor(keyRange); return new Promise((resolve, reject) => { const results = []; query.onerror = (event) => { reject(new Error("Query failed: " + event.target.errorCode)); }; // collect resul...
javascript
{ "resource": "" }