_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24800
insertDisplayName
train
function insertDisplayName(path, id) { const assignment = t.assignmentExpression( '=', t.memberExpression( t.identifier(id), t.identifier('displayName') ), t.stringLiteral(id) ) // Put in the assignment expression and a semicolon path.insertAfter([assignment, t.emptyStatement()]) }
javascript
{ "resource": "" }
q24801
parse
train
function parse (dateString, locale, timezone) { _checkParams(locale, timezone) // list all available localized formats, from most specific to least return moment.tz(dateString, [moment.ISO_8601, 'llll', 'LLLL', 'lll', 'LLL', 'll', 'LL', 'l', 'L'], locale, timezone) }
javascript
{ "resource": "" }
q24802
mirrorShorthandCorners
train
function mirrorShorthandCorners (values) { if (typeof values !== 'string') { return } const valuesArr = values.split(' ') if (valuesArr.length === 2) { // swap the 1st and 2nd values [ valuesArr[0], valuesArr[1] ] = [ valuesArr[1], valuesArr[0] ] } if (valuesArr.length === 3) { // convert 3 value syntax to 4 value syntax valuesArr.push(valuesArr[1]) } if (valuesArr.length === 4) { [ valuesArr[0], valuesArr[1], valuesArr[2], valuesArr[3] ] = [ valuesArr[1], valuesArr[0], valuesArr[3], valuesArr[2] ] } return valuesArr.join(' ') }
javascript
{ "resource": "" }
q24803
mirrorHorizontalPlacement
train
function mirrorHorizontalPlacement (placement, delimiter) { return executeMirrorFunction(placement, (first, second) => { return [first, second].map(value => { return (value === 'start' || value === 'end') ? mirror[value] : value }) }, delimiter) }
javascript
{ "resource": "" }
q24804
origin
train
function origin (node) { const ownWindow = ownerWindow(node) const { location } = ownWindow if (location.protocol === 'file:') { return '*' } else if (location.origin) { return location.origin } else if (location.port) { return `${location.protocol}//${location.hostname}:${location.port}` } else { return `${location.protocol}//${location.hostname}` } }
javascript
{ "resource": "" }
q24805
_format
train
function _format (input, locale) { locale = locale || Locale.browserLocale() // eslint-disable-line no-param-reassign let result = input const { thousands, decimal } = Decimal.getDelimiters(locale) const isNegative = (result[0] === '-') // remove all characters except for digits and decimal delimiters result = result.replace(new RegExp(`[^\\d\\${decimal}]`, 'g'), '') // remove all decimal delimiters except for the last one if present result = result.replace(new RegExp(`[${decimal}](?=.*[${decimal}])`, 'g'), '') // remove the leading zeros using positive lookahead result = result.replace(new RegExp(`^[0${thousands}]+(?=\\d|0${decimal})`, ''), '') // add leading zero to decimal, if not present result = result.charAt(0) === decimal ? result.replace(/^/, '0') : result const parts = result.split(decimal) const thousandSections = [] let curr = parts[0] while (curr.length > 0) { thousandSections.unshift(curr.substr(Math.max(0, curr.length - 3), 3)) curr = curr.substr(0, curr.length - 3) } result = thousandSections.join(thousands) if (parts[1]) { result = `${result}${decimal}${parts[1]}` } if (isNegative && result) { result = `-${result}` } return result }
javascript
{ "resource": "" }
q24806
scopeCssText
train
function scopeCssText (cssText, scope) { return transformCss(cssText, (rule) => { const transformed = {...rule} if (!rule.isScoped) { transformed.selector = scopeRule(rule, scope) transformed.isScoped = true } return transformed }) }
javascript
{ "resource": "" }
q24807
train
function(oneaccidental) { var key = this.key(), limit = oneaccidental ? 2 : 3; return ['m3', 'm2', 'm-2', 'm-3'] .map(this.interval.bind(this)) .filter(function(note) { var acc = note.accidentalValue(); var diff = key - (note.key() - acc); if (diff < limit && diff > -limit) { var product = vector.mul(knowledge.sharp, diff - acc); note.coord = vector.add(note.coord, product); return true; } }); }
javascript
{ "resource": "" }
q24808
set
train
function set(property, value, defaultValue) { if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else { this[property] = value; } }
javascript
{ "resource": "" }
q24809
train
function (buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = new TableStore.util.Buffer(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; }
javascript
{ "resource": "" }
q24810
top
train
function top(date, fmt) { fmt = fmt || '%Y-%M-%dT%H:%m:%sZ'; function pad(value) { return (value.toString().length < 2) ? '0' + value : value; }; return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) { switch (fmtCode) { case 'Y': return date.getUTCFullYear(); case 'M': return pad(date.getUTCMonth() + 1); case 'd': return pad(date.getUTCDate()); case 'H': return pad(date.getUTCHours()); case 'm': return pad(date.getUTCMinutes()); case 's': return pad(date.getUTCSeconds()); default: throw new Error('Unsupported format code: ' + fmtCode); } }); }
javascript
{ "resource": "" }
q24811
format
train
function format(date, formatter) { if (!formatter) formatter = 'unixSeconds'; return TableStore.util.date[formatter](TableStore.util.date.from(date)); }
javascript
{ "resource": "" }
q24812
Request
train
function Request(config, operation, params) { var endpoint = new TableStore.Endpoint(config.endpoint); var region = config.region; this.config = config; if (config.maxRetries !== undefined) { TableStore.DefaultRetryPolicy.maxRetryTimes = config.maxRetries; } //如果在sdk外部包装了一层domain,就把它传到this.domain this.domain = domain && domain.active; this.operation = operation; this.params = params || {}; this.httpRequest = new TableStore.HttpRequest(endpoint, region); this.startTime = TableStore.util.date.getDate(); this.response = new TableStore.Response(this); this.restartCount = 0; this._asm = new AcceptorStateMachine(fsm.states, 'build'); TableStore.SequentialExecutor.call(this); this.emit = this.emitEvent; }
javascript
{ "resource": "" }
q24813
KdbxUuid
train
function KdbxUuid(ab) { if (ab === undefined) { ab = new ArrayBuffer(UuidLength); } if (typeof ab === 'string') { ab = ByteUtils.base64ToBytes(ab); } this.id = ab.byteLength === 16 ? ByteUtils.bytesToBase64(ab) : undefined; this.empty = true; if (ab) { var bytes = new Uint8Array(ab); for (var i = 0, len = bytes.length; i < len; i++) { if (bytes[i] !== 0) { this.empty = false; return; } } } }
javascript
{ "resource": "" }
q24814
BinaryStream
train
function BinaryStream(arrayBuffer) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(1024); this._dataView = new DataView(this._arrayBuffer); this._pos = 0; this._canExpand = !arrayBuffer; }
javascript
{ "resource": "" }
q24815
getBytes
train
function getBytes(len) { if (!len) { return new Uint8Array(0); } algo.getBytes(Math.round(Math.random() * len) + 1); var result = algo.getBytes(len); var cryptoBytes = CryptoEngine.random(len); for (var i = cryptoBytes.length - 1; i >= 0; --i) { result[i] ^= cryptoBytes[i]; } return result; }
javascript
{ "resource": "" }
q24816
encrypt
train
function encrypt(key, kdfParams) { var uuid = kdfParams.get('$UUID'); if (!uuid || !(uuid instanceof ArrayBuffer)) { return Promise.reject(new KdbxError(Consts.ErrorCodes.FileCorrupt, 'no kdf uuid')); } var kdfUuid = ByteUtils.bytesToBase64(uuid); switch (kdfUuid) { case Consts.KdfId.Argon2: return encryptArgon2(key, kdfParams); case Consts.KdfId.Aes: return encryptAes(key, kdfParams); default: return Promise.reject(new KdbxError(Consts.ErrorCodes.Unsupported, 'bad kdf')); } }
javascript
{ "resource": "" }
q24817
arrayBufferEquals
train
function arrayBufferEquals(ab1, ab2) { if (ab1.byteLength !== ab2.byteLength) { return false; } var arr1 = new Uint8Array(ab1); var arr2 = new Uint8Array(ab2); for (var i = 0, len = arr1.length; i < len; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }
javascript
{ "resource": "" }
q24818
bytesToString
train
function bytesToString(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } return textDecoder.decode(arr); }
javascript
{ "resource": "" }
q24819
base64ToBytes
train
function base64ToBytes(str) { if (typeof atob === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have atob var buffer = Buffer.from(str, 'base64'); return new Uint8Array(buffer); } var byteStr = atob(str); var arr = new Uint8Array(byteStr.length); for (var i = 0; i < byteStr.length; i++) { arr[i] = byteStr.charCodeAt(i); } return arr; }
javascript
{ "resource": "" }
q24820
bytesToBase64
train
function bytesToBase64(arr) { if (arr instanceof ArrayBuffer) { arr = new Uint8Array(arr); } if (typeof btoa === 'undefined' && typeof Buffer === 'function') { // node.js doesn't have btoa var buffer = Buffer.from(arr); return buffer.toString('base64'); } var str = ''; for (var i = 0; i < arr.length; i++) { str += String.fromCharCode(arr[i]); } return btoa(str); }
javascript
{ "resource": "" }
q24821
arrayToBuffer
train
function arrayToBuffer(arr) { if (arr instanceof ArrayBuffer) { return arr; } var ab = arr.buffer; if (arr.byteOffset === 0 && arr.byteLength === ab.byteLength) { return ab; } return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength); }
javascript
{ "resource": "" }
q24822
sha256
train
function sha256(data) { if (!data.byteLength) { return Promise.resolve(ByteUtils.arrayToBuffer(ByteUtils.hexToBytes(EmptySha256))); } if (subtle) { return subtle.digest({ name: 'SHA-256' }, data); } else if (nodeCrypto) { return new Promise(function(resolve) { var sha = nodeCrypto.createHash('sha256'); var hash = sha.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'SHA256 not implemented')); } }
javascript
{ "resource": "" }
q24823
hmacSha256
train
function hmacSha256(key, data) { if (subtle) { var algo = { name: 'HMAC', hash: { name: 'SHA-256' } }; return subtle.importKey('raw', key, algo, false, ['sign']) .then(function(subtleKey) { return subtle.sign(algo, subtleKey, data); }); } else if (nodeCrypto) { return new Promise(function(resolve) { var hmac = nodeCrypto.createHmac('sha256', Buffer.from(key)); var hash = hmac.update(Buffer.from(data)).digest(); resolve(hash.buffer); }); } else { return Promise.reject(new KdbxError(Consts.ErrorCodes.NotImplemented, 'HMAC-SHA256 not implemented')); } }
javascript
{ "resource": "" }
q24824
safeRandom
train
function safeRandom(len) { var randomBytes = new Uint8Array(len); while (len > 0) { var segmentSize = len % maxRandomQuota; segmentSize = segmentSize > 0 ? segmentSize : maxRandomQuota; var randomBytesSegment = new Uint8Array(segmentSize); webCrypto.getRandomValues(randomBytesSegment); len -= segmentSize; randomBytes.set(randomBytesSegment, len); } return randomBytes; }
javascript
{ "resource": "" }
q24825
random
train
function random(len) { if (subtle) { return safeRandom(len); } else if (nodeCrypto) { return new Uint8Array(nodeCrypto.randomBytes(len)); } else { throw new KdbxError(Consts.ErrorCodes.NotImplemented, 'Random not implemented'); } }
javascript
{ "resource": "" }
q24826
chacha20
train
function chacha20(data, key, iv) { return Promise.resolve().then(function() { var algo = new ChaCha20(new Uint8Array(key), new Uint8Array(iv)); return ByteUtils.arrayToBuffer(algo.encrypt(new Uint8Array(data))); }); }
javascript
{ "resource": "" }
q24827
configure
train
function configure(newSubtle, newWebCrypto, newNodeCrypto) { subtle = newSubtle; webCrypto = newWebCrypto; nodeCrypto = newNodeCrypto; }
javascript
{ "resource": "" }
q24828
train
function(value, salt) { Object.defineProperty(this, '_value', { value: new Uint8Array(value) }); Object.defineProperty(this, '_salt', { value: new Uint8Array(salt) }); }
javascript
{ "resource": "" }
q24829
getHmacKey
train
function getHmacKey(key, blockIndex) { var shaSrc = new Uint8Array(8 + key.byteLength); shaSrc.set(new Uint8Array(key), 8); var view = new DataView(shaSrc.buffer); view.setUint32(0, blockIndex.lo, true); view.setUint32(4, blockIndex.hi, true); return CryptoEngine.sha512(ByteUtils.arrayToBuffer(shaSrc)).then(function(sha) { ByteUtils.zeroBuffer(shaSrc); return sha; }); }
javascript
{ "resource": "" }
q24830
getBlockHmac
train
function getBlockHmac(key, blockIndex, blockLength, blockData) { return getHmacKey(key, new Int64(blockIndex)).then(function(blockKey) { var blockDataForHash = new Uint8Array(blockData.byteLength + 4 + 8); var blockDataForHashView = new DataView(blockDataForHash.buffer); blockDataForHash.set(new Uint8Array(blockData), 4 + 8); blockDataForHashView.setInt32(0, blockIndex, true); blockDataForHashView.setInt32(8, blockLength, true); return CryptoEngine.hmacSha256(blockKey, blockDataForHash.buffer); }); }
javascript
{ "resource": "" }
q24831
parse
train
function parse(xml) { var parser = domParserArg ? new dom.DOMParser(domParserArg) : new dom.DOMParser(); var doc; try { doc = parser.parseFromString(xml, 'application/xml'); } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + e.message); } if (!doc.documentElement) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml'); } var parserError = doc.getElementsByTagName('parsererror')[0]; if (parserError) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad xml: ' + parserError.textContent); } return doc; }
javascript
{ "resource": "" }
q24832
getChildNode
train
function getChildNode(node, tagName, errorMsgIfAbsent) { if (node && node.childNodes) { for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { if (cn[i].tagName === tagName) { return cn[i]; } } } if (errorMsgIfAbsent) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, errorMsgIfAbsent); } else { return null; } }
javascript
{ "resource": "" }
q24833
addChildNode
train
function addChildNode(node, tagName) { return node.appendChild((node.ownerDocument || node).createElement(tagName)); }
javascript
{ "resource": "" }
q24834
getText
train
function getText(node) { if (!node || !node.childNodes) { return undefined; } return node.protectedValue ? node.protectedValue.text : node.textContent; }
javascript
{ "resource": "" }
q24835
getBytes
train
function getBytes(node) { var text = getText(node); return text ? ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text)) : undefined; }
javascript
{ "resource": "" }
q24836
setBytes
train
function setBytes(node, bytes) { if (typeof bytes === 'string') { bytes = ByteUtils.base64ToBytes(bytes); } setText(node, bytes ? ByteUtils.bytesToBase64(ByteUtils.arrayToBuffer(bytes)) : undefined); }
javascript
{ "resource": "" }
q24837
getDate
train
function getDate(node) { var text = getText(node); if (!text) { return undefined; } if (text.indexOf(':') > 0) { return new Date(text); } var bytes = new DataView(ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(text))); var secondsFrom00 = new Int64(bytes.getUint32(0, true), bytes.getUint32(4, true)).value; var diff = (secondsFrom00 - EpochSeconds) * 1000; return new Date(diff); }
javascript
{ "resource": "" }
q24838
setDate
train
function setDate(node, date, binary) { if (date) { if (binary) { var secondsFrom00 = Math.floor(date.getTime() / 1000) + EpochSeconds; var bytes = new DataView(new ArrayBuffer(8)); var val64 = Int64.from(secondsFrom00); bytes.setUint32(0, val64.lo, true); bytes.setUint32(4, val64.hi, true); setText(node, ByteUtils.bytesToBase64(bytes.buffer)); } else { setText(node, date.toISOString().replace(dateRegex, '')); } } else { setText(node, ''); } }
javascript
{ "resource": "" }
q24839
setNumber
train
function setNumber(node, number) { setText(node, typeof number === 'number' && !isNaN(number) ? number.toString() : undefined); }
javascript
{ "resource": "" }
q24840
setBoolean
train
function setBoolean(node, boolean) { setText(node, boolean === undefined ? '' : boolean === null ? 'null' : boolean ? 'True' : 'False'); }
javascript
{ "resource": "" }
q24841
strToBoolean
train
function strToBoolean(str) { switch (str && str.toLowerCase && str.toLowerCase()) { case 'true': return true; case 'false': return false; case 'null': return null; } return undefined; }
javascript
{ "resource": "" }
q24842
setUuid
train
function setUuid(node, uuid) { var uuidBytes = uuid instanceof KdbxUuid ? uuid.toBytes() : uuid; setBytes(node, uuidBytes); }
javascript
{ "resource": "" }
q24843
setProtectedText
train
function setProtectedText(node, text) { if (text instanceof ProtectedValue) { node.protectedValue = text; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else { setText(node, text); } }
javascript
{ "resource": "" }
q24844
getProtectedBinary
train
function getProtectedBinary(node) { if (node.protectedValue) { return node.protectedValue; } var text = node.textContent; var ref = node.getAttribute(XmlNames.Attr.Ref); if (ref) { return { ref: ref }; } if (!text) { return undefined; } var compressed = strToBoolean(node.getAttribute(XmlNames.Attr.Compressed)); var bytes = ByteUtils.base64ToBytes(text); if (compressed) { bytes = pako.ungzip(bytes); } return ByteUtils.arrayToBuffer(bytes); }
javascript
{ "resource": "" }
q24845
setProtectedBinary
train
function setProtectedBinary(node, binary) { if (binary instanceof ProtectedValue) { node.protectedValue = binary; node.setAttribute(XmlNames.Attr.Protected, 'True'); } else if (binary && binary.ref) { node.setAttribute(XmlNames.Attr.Ref, binary.ref); } else { setBytes(node, binary); } }
javascript
{ "resource": "" }
q24846
traverse
train
function traverse(node, callback) { callback(node); for (var i = 0, cn = node.childNodes, len = cn.length; i < len; i++) { var childNode = cn[i]; if (childNode.tagName) { traverse(childNode, callback); } } }
javascript
{ "resource": "" }
q24847
setProtectedValues
train
function setProtectedValues(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected))) { try { var value = ByteUtils.arrayToBuffer(ByteUtils.base64ToBytes(node.textContent)); if (value.byteLength) { var salt = protectSaltGenerator.getSalt(value.byteLength); node.protectedValue = new ProtectedValue(value, salt); } } catch (e) { throw new KdbxError(Consts.ErrorCodes.FileCorrupt, 'bad protected value at line ' + node.lineNumber + ': ' + e); } } }); }
javascript
{ "resource": "" }
q24848
updateProtectedValuesSalt
train
function updateProtectedValuesSalt(node, protectSaltGenerator) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { var newSalt = protectSaltGenerator.getSalt(node.protectedValue.byteLength); node.protectedValue.setSalt(newSalt); node.textContent = node.protectedValue.toString(); } }); }
javascript
{ "resource": "" }
q24849
unprotectValues
train
function unprotectValues(node) { traverse(node, function(node) { if (strToBoolean(node.getAttribute(XmlNames.Attr.Protected)) && node.protectedValue) { node.removeAttribute(XmlNames.Attr.Protected); node.setAttribute(XmlNames.Attr.ProtectedInMemPlainXml, 'True'); node.textContent = node.protectedValue.getText(); } }); }
javascript
{ "resource": "" }
q24850
train
function(id, createdAt, updatedAt) { var _this = this; _this['id'] = id; _this['created_at'] = createdAt; _this['updated_at'] = updatedAt; }
javascript
{ "resource": "" }
q24851
train
function(resolve, reject) { console.log(thisPromiseCount + ') Promise started (Async code started)'); // This only is an example to create asynchronism global.setTimeout( function() { // We fulfill the promise ! resolve(thisPromiseCount); }, Math.random() * 2000 + 1000); }
javascript
{ "resource": "" }
q24852
train
function(projectConfig, experimentId) { var experiment = projectConfig.experimentIdMap[experimentId]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); } return experiment.layerId; }
javascript
{ "resource": "" }
q24853
train
function(projectConfig, attributeKey, logger) { var attribute = projectConfig.attributeKeyMap[attributeKey]; var hasReservedPrefix = attributeKey.indexOf(RESERVED_ATTRIBUTE_PREFIX) === 0; if (attribute) { if (hasReservedPrefix) { logger.log(LOG_LEVEL.WARN, sprintf('Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.', attributeKey, RESERVED_ATTRIBUTE_PREFIX)); } return attribute.id; } else if (hasReservedPrefix) { return attributeKey; } logger.log(LOG_LEVEL.DEBUG, sprintf(ERROR_MESSAGES.UNRECOGNIZED_ATTRIBUTE, MODULE_NAME, attributeKey)); return null; }
javascript
{ "resource": "" }
q24854
train
function(projectConfig, eventKey) { var event = projectConfig.eventKeyMap[eventKey]; if (event) { return event.id; } return null; }
javascript
{ "resource": "" }
q24855
train
function(projectConfig, experimentKey) { return module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_RUNNING_STATUS || module.exports.getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_LAUNCHED_STATUS; }
javascript
{ "resource": "" }
q24856
train
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.audienceConditions || experiment.audienceIds; }
javascript
{ "resource": "" }
q24857
train
function(projectConfig, variationId) { if (projectConfig.variationIdMap.hasOwnProperty(variationId)) { return projectConfig.variationIdMap[variationId].key; } return null; }
javascript
{ "resource": "" }
q24858
train
function(projectConfig, experimentKey, variationKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (experiment.variationKeyMap.hasOwnProperty(variationKey)) { return experiment.variationKeyMap[variationKey].id; } return null; }
javascript
{ "resource": "" }
q24859
train
function(projectConfig, experimentKey) { if (projectConfig.experimentKeyMap.hasOwnProperty(experimentKey)) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (!!experiment) { return experiment; } } throw new Error(sprintf(ERROR_MESSAGES.EXPERIMENT_KEY_NOT_IN_DATAFILE, MODULE_NAME, experimentKey)); }
javascript
{ "resource": "" }
q24860
train
function(projectConfig, experimentKey) { var experiment = projectConfig.experimentKeyMap[experimentKey]; if (fns.isEmpty(experiment)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_KEY, MODULE_NAME, experimentKey)); } return experiment.trafficAllocation; }
javascript
{ "resource": "" }
q24861
train
function(projectConfig, experimentId, logger) { if (projectConfig.experimentIdMap.hasOwnProperty(experimentId)) { var experiment = projectConfig.experimentIdMap[experimentId]; if (!!experiment) { return experiment; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.INVALID_EXPERIMENT_ID, MODULE_NAME, experimentId)); return null; }
javascript
{ "resource": "" }
q24862
train
function(projectConfig, featureKey, logger) { if (projectConfig.featureKeyMap.hasOwnProperty(featureKey)) { var feature = projectConfig.featureKeyMap[featureKey]; if (!!feature) { return feature; } } logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; }
javascript
{ "resource": "" }
q24863
train
function(projectConfig, featureKey, variableKey, logger) { var feature = projectConfig.featureKeyMap[featureKey]; if (!feature) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.FEATURE_NOT_IN_DATAFILE, MODULE_NAME, featureKey)); return null; } var variable = feature.variableKeyMap[variableKey]; if (!variable) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIABLE_KEY_NOT_IN_DATAFILE, MODULE_NAME, variableKey, featureKey)); return null; } return variable; }
javascript
{ "resource": "" }
q24864
train
function(projectConfig, variable, variation, logger) { if (!variable || !variation) { return null; } if (!projectConfig.variationVariableUsageMap.hasOwnProperty(variation.id)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT, MODULE_NAME, variation.id)); return null; } var variableUsages = projectConfig.variationVariableUsageMap[variation.id]; var variableUsage = variableUsages[variable.id]; return variableUsage ? variableUsage.value : null; }
javascript
{ "resource": "" }
q24865
train
function(variableValue, variableType, logger) { var castValue; switch (variableType) { case FEATURE_VARIABLE_TYPES.BOOLEAN: if (variableValue !== 'true' && variableValue !== 'false') { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } else { castValue = variableValue === 'true'; } break; case FEATURE_VARIABLE_TYPES.INTEGER: castValue = parseInt(variableValue, 10); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; case FEATURE_VARIABLE_TYPES.DOUBLE: castValue = parseFloat(variableValue); if (isNaN(castValue)) { logger.log(LOG_LEVEL.ERROR, sprintf(ERROR_MESSAGES.UNABLE_TO_CAST_VALUE, MODULE_NAME, variableValue, variableType)); castValue = null; } break; default: // type is STRING castValue = variableValue; break; } return castValue; }
javascript
{ "resource": "" }
q24866
train
function(config) { configValidator.validateDatafile(config.datafile); if (config.skipJSONValidation === true) { config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.SKIPPING_JSON_VALIDATION, MODULE_NAME)); } else if (config.jsonSchemaValidator) { config.jsonSchemaValidator.validate(projectConfigSchema, config.datafile); config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_DATAFILE, MODULE_NAME)); } return module.exports.createProjectConfig(config.datafile); }
javascript
{ "resource": "" }
q24867
train
function(audienceConditions, audiencesById, userAttributes, logger) { // if there are no audiences, return true because that means ALL users are included in the experiment if (!audienceConditions || audienceConditions.length === 0) { return true; } if (!userAttributes) { userAttributes = {}; } var evaluateConditionWithUserAttributes = function(condition) { return customAttributeConditionEvaluator.evaluate(condition, userAttributes, logger); }; var evaluateAudience = function(audienceId) { var audience = audiencesById[audienceId]; if (audience) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.EVALUATING_AUDIENCE, MODULE_NAME, audienceId, JSON.stringify(audience.conditions))); var result = conditionTreeEvaluator.evaluate(audience.conditions, evaluateConditionWithUserAttributes); var resultText = result === null ? 'UNKNOWN' : result.toString().toUpperCase(); logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.AUDIENCE_EVALUATION_RESULT, MODULE_NAME, audienceId, resultText)); return result; } return null; }; return conditionTreeEvaluator.evaluate(audienceConditions, evaluateAudience) || false; }
javascript
{ "resource": "" }
q24868
train
function(eventTags) { if (typeof eventTags === 'object' && !Array.isArray(eventTags) && eventTags !== null) { return true; } else { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_TAGS, MODULE_NAME)); } }
javascript
{ "resource": "" }
q24869
DecisionService
train
function DecisionService(options) { this.userProfileService = options.userProfileService || null; this.logger = options.logger; this.forcedVariationMap = {}; }
javascript
{ "resource": "" }
q24870
train
function(config) { if (config.errorHandler && (typeof config.errorHandler.handleError !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_ERROR_HANDLER, MODULE_NAME)); } if (config.eventDispatcher && (typeof config.eventDispatcher.dispatchEvent !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_EVENT_DISPATCHER, MODULE_NAME)); } if (config.logger && (typeof config.logger.log !== 'function')) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_LOGGER, MODULE_NAME)); } return true; }
javascript
{ "resource": "" }
q24871
train
function(datafile) { if (!datafile) { throw new Error(sprintf(ERROR_MESSAGES.NO_DATAFILE_SPECIFIED, MODULE_NAME)); } if (typeof datafile === 'string' || datafile instanceof String) { // Attempt to parse the datafile string try { datafile = JSON.parse(datafile); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_MALFORMED, MODULE_NAME)); } } if (SUPPORTED_VERSIONS.indexOf(datafile.version) === -1) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE_VERSION, MODULE_NAME, datafile.version)); } return true; }
javascript
{ "resource": "" }
q24872
train
function(eventObj, callback) { // Non-POST requests not supported if (eventObj.httpVerb !== 'POST') { return; } var parsedUrl = url.parse(eventObj.url); var path = parsedUrl.path; if (parsedUrl.query) { path += '?' + parsedUrl.query; } var dataString = JSON.stringify(eventObj.params); var requestOptions = { host: parsedUrl.host, path: parsedUrl.path, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': dataString.length.toString(), } }; var requestCallback = function(response) { if (response && response.statusCode && response.statusCode >= 200 && response.statusCode < 400) { callback(response); } }; var req = (parsedUrl.protocol === 'http:' ? http : https).request(requestOptions, requestCallback); // Add no-op error listener to prevent this from throwing req.on('error', function() {}); req.write(dataString); req.end(); return req; }
javascript
{ "resource": "" }
q24873
train
function(bucketerParams) { // Check if user is in a random group; if so, check if user is bucketed into a specific experiment var experiment = bucketerParams.experimentKeyMap[bucketerParams.experimentKey]; var groupId = experiment['groupId']; if (groupId) { var group = bucketerParams.groupIdMap[groupId]; if (!group) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_GROUP_ID, MODULE_NAME, groupId)); } if (group.policy === RANDOM_POLICY) { var bucketedExperimentId = module.exports.bucketUserIntoExperiment(group, bucketerParams.bucketingId, bucketerParams.userId, bucketerParams.logger); // Return if user is not bucketed into any experiment if (bucketedExperimentId === null) { var notbucketedInAnyExperimentLogMessage = sprintf(LOG_MESSAGES.USER_NOT_IN_ANY_EXPERIMENT, MODULE_NAME, bucketerParams.userId, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notbucketedInAnyExperimentLogMessage); return null; } // Return if user is bucketed into a different experiment than the one specified if (bucketedExperimentId !== bucketerParams.experimentId) { var notBucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, notBucketedIntoExperimentOfGroupLogMessage); return null; } // Continue bucketing if user is bucketed into specified experiment var bucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId); bucketerParams.logger.log(LOG_LEVEL.INFO, bucketedIntoExperimentOfGroupLogMessage); } } var bucketingId = sprintf('%s%s', bucketerParams.bucketingId, bucketerParams.experimentId); var bucketValue = module.exports._generateBucketValue(bucketingId); var bucketedUserLogMessage = sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_VARIATION_BUCKET, MODULE_NAME, bucketValue, bucketerParams.userId); bucketerParams.logger.log(LOG_LEVEL.DEBUG, bucketedUserLogMessage); var entityId = module.exports._findBucket(bucketValue, bucketerParams.trafficAllocationConfig); if (entityId === null) { var userHasNoVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_NO_VARIATION, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.DEBUG, userHasNoVariationLogMessage); } else if (entityId === '' || !bucketerParams.variationIdMap.hasOwnProperty(entityId)) { var invalidVariationIdLogMessage = sprintf(LOG_MESSAGES.INVALID_VARIATION_ID, MODULE_NAME); bucketerParams.logger.log(LOG_LEVEL.WARNING, invalidVariationIdLogMessage); return null; } else { var variationKey = bucketerParams.variationIdMap[entityId].key; var userInVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_VARIATION, MODULE_NAME, bucketerParams.userId, variationKey, bucketerParams.experimentKey); bucketerParams.logger.log(LOG_LEVEL.INFO, userInVariationLogMessage); } return entityId; }
javascript
{ "resource": "" }
q24874
train
function(group, bucketingId, userId, logger) { var bucketingKey = sprintf('%s%s', bucketingId, group.id); var bucketValue = module.exports._generateBucketValue(bucketingKey); logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_EXPERIMENT_BUCKET, MODULE_NAME, bucketValue, userId)); var trafficAllocationConfig = group.trafficAllocation; var bucketedExperimentId = module.exports._findBucket(bucketValue, trafficAllocationConfig); return bucketedExperimentId; }
javascript
{ "resource": "" }
q24875
train
function(bucketValue, trafficAllocationConfig) { for (var i = 0; i < trafficAllocationConfig.length; i++) { if (bucketValue < trafficAllocationConfig[i].endOfRange) { return trafficAllocationConfig[i].entityId; } } return null; }
javascript
{ "resource": "" }
q24876
train
function(bucketingKey) { try { // NOTE: the mmh library already does cast the hash value as an unsigned 32bit int // https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L115 var hashValue = murmurhash.v3(bucketingKey, HASH_SEED); var ratio = hashValue / MAX_HASH_VALUE; return parseInt(ratio * MAX_TRAFFIC_VALUE, 10); } catch (ex) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_BUCKETING_ID, MODULE_NAME, bucketingKey, ex.message)); } }
javascript
{ "resource": "" }
q24877
train
function(eventObj, callback) { var url = eventObj.url; var params = eventObj.params; if (eventObj.httpVerb === POST_METHOD) { var req = new XMLHttpRequest(); req.open(POST_METHOD, url, true); req.setRequestHeader('Content-Type', 'application/json'); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(params); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(JSON.stringify(params)); } else { // add param for cors headers to be sent by the log endpoint url += '?wxhr=true'; if (params) { url += '&' + toQueryString(params); } var req = new XMLHttpRequest(); req.open(GET_METHOD, url, true); req.onreadystatechange = function() { if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') { try { callback(); } catch (e) { // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface) } } }; req.send(); } }
javascript
{ "resource": "" }
q24878
getCommonEventParams
train
function getCommonEventParams(options) { var attributes = options.attributes; var configObj = options.configObj; var anonymize_ip = configObj.anonymizeIP; var botFiltering = configObj.botFiltering; if (anonymize_ip === null || anonymize_ip === undefined) { anonymize_ip = false; } var visitor = { snapshots: [], visitor_id: options.userId, attributes: [] }; var commonParams = { account_id: configObj.accountId, project_id: configObj.projectId, visitors: [visitor], revision: configObj.revision, client_name: options.clientEngine, client_version: options.clientVersion, anonymize_ip: anonymize_ip, enrich_decisions: true, }; // Omit attribute values that are not supported by the log endpoint. fns.forOwn(attributes, function(attributeValue, attributeKey) { if (attributeValidator.isAttributeValid(attributeKey, attributeValue)) { var attributeId = projectConfig.getAttributeId(options.configObj, attributeKey, options.logger); if (attributeId) { commonParams.visitors[0].attributes.push({ entity_id: attributeId, key: attributeKey, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: attributes[attributeKey], }); } } }); if (typeof botFiltering === 'boolean') { commonParams.visitors[0].attributes.push({ entity_id: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, key: enums.CONTROL_ATTRIBUTES.BOT_FILTERING, type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, value: botFiltering, }); } return commonParams; }
javascript
{ "resource": "" }
q24879
getImpressionEventParams
train
function getImpressionEventParams(configObj, experimentId, variationId) { var impressionEventParams = { decisions: [{ campaign_id: projectConfig.getLayerId(configObj, experimentId), experiment_id: experimentId, variation_id: variationId, }], events: [{ entity_id: projectConfig.getLayerId(configObj, experimentId), timestamp: fns.currentTimestamp(), key: ACTIVATE_EVENT_KEY, uuid: fns.uuid(), }] }; return impressionEventParams; }
javascript
{ "resource": "" }
q24880
getVisitorSnapshot
train
function getVisitorSnapshot(configObj, eventKey, eventTags, logger) { var snapshot = { events: [] }; var eventDict = { entity_id: projectConfig.getEventId(configObj, eventKey), timestamp: fns.currentTimestamp(), uuid: fns.uuid(), key: eventKey, }; if (eventTags) { var revenue = eventTagUtils.getRevenueValue(eventTags, logger); if (revenue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.REVENUE] = revenue; } var eventValue = eventTagUtils.getEventValue(eventTags, logger); if (eventValue !== null) { eventDict[enums.RESERVED_EVENT_KEYWORDS.VALUE] = eventValue; } eventDict['tags'] = eventTags; } snapshot.events.push(eventDict); return snapshot; }
javascript
{ "resource": "" }
q24881
train
function(options) { var impressionEvent = { httpVerb: HTTP_VERB }; var commonParams = getCommonEventParams(options); impressionEvent.url = ENDPOINT; var impressionEventParams = getImpressionEventParams(options.configObj, options.experimentId, options.variationId); // combine Event params into visitor obj commonParams.visitors[0].snapshots.push(impressionEventParams); impressionEvent.params = commonParams; return impressionEvent; }
javascript
{ "resource": "" }
q24882
train
function(options) { var conversionEvent = { httpVerb: HTTP_VERB, }; var commonParams = getCommonEventParams(options); conversionEvent.url = ENDPOINT; var snapshot = getVisitorSnapshot(options.configObj, options.eventKey, options.eventTags, options.logger); commonParams.visitors[0].snapshots = [snapshot]; conversionEvent.params = commonParams; return conversionEvent; }
javascript
{ "resource": "" }
q24883
evaluate
train
function evaluate(condition, userAttributes, logger) { if (condition.type !== CUSTOM_ATTRIBUTE_CONDITION_TYPE) { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_CONDITION_TYPE, MODULE_NAME, JSON.stringify(condition))); return null; } var conditionMatch = condition.match; if (typeof conditionMatch !== 'undefined' && MATCH_TYPES.indexOf(conditionMatch) === -1) { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNKNOWN_MATCH_TYPE, MODULE_NAME, JSON.stringify(condition))); return null; } var attributeKey = condition.name; if (!userAttributes.hasOwnProperty(attributeKey) && conditionMatch != EXISTS_MATCH_TYPE) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.MISSING_ATTRIBUTE_VALUE, MODULE_NAME, JSON.stringify(condition), attributeKey)); return null; } var evaluatorForMatch = EVALUATORS_BY_MATCH_TYPE[conditionMatch] || exactEvaluator; return evaluatorForMatch(condition, userAttributes, logger); }
javascript
{ "resource": "" }
q24884
existsEvaluator
train
function existsEvaluator(condition, userAttributes) { var userValue = userAttributes[condition.name]; return typeof userValue !== 'undefined' && userValue !== null; }
javascript
{ "resource": "" }
q24885
greaterThanEvaluator
train
function greaterThanEvaluator(condition, userAttributes, logger) { var conditionName = condition.name; var userValue = userAttributes[conditionName]; var userValueType = typeof userValue; var conditionValue = condition.value; if (!fns.isFinite(conditionValue)) { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition))); return null; } if (userValue === null) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName)); return null; } if (!fns.isNumber(userValue)) { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName)); return null; } if (!fns.isFinite(userValue)) { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.OUT_OF_BOUNDS, MODULE_NAME, JSON.stringify(condition), conditionName)); return null; } return userValue > conditionValue; }
javascript
{ "resource": "" }
q24886
substringEvaluator
train
function substringEvaluator(condition, userAttributes, logger) { var conditionName = condition.name; var userValue = userAttributes[condition.name]; var userValueType = typeof userValue; var conditionValue = condition.value; if (typeof conditionValue !== 'string') { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition))); return null; } if (userValue === null) { logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName)); return null; } if (typeof userValue !== 'string') { logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName)); return null; } return userValue.indexOf(conditionValue) !== -1; }
javascript
{ "resource": "" }
q24887
evaluate
train
function evaluate(conditions, leafEvaluator) { if (Array.isArray(conditions)) { var firstOperator = conditions[0]; var restOfConditions = conditions.slice(1); if (DEFAULT_OPERATOR_TYPES.indexOf(firstOperator) === -1) { // Operator to apply is not explicit - assume 'or' firstOperator = OR_CONDITION; restOfConditions = conditions; } switch (firstOperator) { case AND_CONDITION: return andEvaluator(restOfConditions, leafEvaluator); case NOT_CONDITION: return notEvaluator(restOfConditions, leafEvaluator); default: // firstOperator is OR_CONDITION return orEvaluator(restOfConditions, leafEvaluator); } } var leafCondition = conditions; return leafEvaluator(leafCondition); }
javascript
{ "resource": "" }
q24888
andEvaluator
train
function andEvaluator(conditions, leafEvaluator) { var sawNullResult = false; for (var i = 0; i < conditions.length; i++) { var conditionResult = evaluate(conditions[i], leafEvaluator); if (conditionResult === false) { return false; } if (conditionResult === null) { sawNullResult = true; } } return sawNullResult ? null : true; }
javascript
{ "resource": "" }
q24889
notEvaluator
train
function notEvaluator(conditions, leafEvaluator) { if (conditions.length > 0) { var result = evaluate(conditions[0], leafEvaluator); return result === null ? null : !result; } return null; }
javascript
{ "resource": "" }
q24890
Optimizely
train
function Optimizely(config) { var clientEngine = config.clientEngine; if (clientEngine !== enums.NODE_CLIENT_ENGINE && clientEngine !== enums.JAVASCRIPT_CLIENT_ENGINE) { config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.INVALID_CLIENT_ENGINE, MODULE_NAME, clientEngine)); clientEngine = enums.NODE_CLIENT_ENGINE; } this.clientEngine = clientEngine; this.clientVersion = config.clientVersion || enums.NODE_CLIENT_VERSION; this.errorHandler = config.errorHandler; this.eventDispatcher = config.eventDispatcher; this.__isOptimizelyConfigValid = config.isValidInstance; this.logger = config.logger; this.projectConfigManager = new projectConfigManager.ProjectConfigManager({ datafile: config.datafile, datafileOptions: config.datafileOptions, jsonSchemaValidator: config.jsonSchemaValidator, sdkKey: config.sdkKey, skipJSONValidation: config.skipJSONValidation, }); this.__disposeOnUpdate = this.projectConfigManager.onUpdate(function(configObj) { this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.UPDATED_OPTIMIZELY_CONFIG, MODULE_NAME, configObj.revision, configObj.projectId)); this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE); }.bind(this)); this.__readyPromise = this.projectConfigManager.onReady(); var userProfileService = null; if (config.userProfileService) { try { if (userProfileServiceValidator.validate(config.userProfileService)) { userProfileService = config.userProfileService; this.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_USER_PROFILE_SERVICE, MODULE_NAME)); } } catch (ex) { this.logger.log(LOG_LEVEL.WARNING, ex.message); } } this.decisionService = decisionService.createDecisionService({ userProfileService: userProfileService, logger: this.logger, }); this.notificationCenter = notificationCenter.createNotificationCenter({ logger: this.logger, errorHandler: this.errorHandler, }); this.eventProcessor = new eventProcessor.LogTierV1EventProcessor({ dispatcher: this.eventDispatcher, flushInterval: config.eventFlushInterval || DEFAULT_EVENT_FLUSH_INTERVAL, maxQueueSize: config.eventBatchSize || DEFAULT_EVENT_MAX_QUEUE_SIZE, }); this.eventProcessor.start(); this.__readyTimeouts = {}; this.__nextReadyTimeoutId = 0; }
javascript
{ "resource": "" }
q24891
train
function(userProfileServiceInstance) { if (typeof userProfileServiceInstance.lookup !== 'function') { throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'lookup\'')); } else if (typeof userProfileServiceInstance.save !== 'function') { throw new Error(sprintf(ERROR_MESSAGES.INVALID_USER_PROFILE_SERVICE, MODULE_NAME, 'Missing function \'save\'')); } return true; }
javascript
{ "resource": "" }
q24892
ProjectConfigManager
train
function ProjectConfigManager(config) { try { this.__initialize(config); } catch (ex) { logger.error(ex); this.__updateListeners = []; this.__configObj = null; this.__readyPromise = Promise.resolve({ success: false, reason: getErrorMessage(ex, 'Error in initialize'), }); } }
javascript
{ "resource": "" }
q24893
train
function(jsonSchema, jsonObject) { if (!jsonSchema) { throw new Error(sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, MODULE_NAME)); } if (!jsonObject) { throw new Error(sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, MODULE_NAME)); } var result = validate(jsonObject, jsonSchema); if (result.valid) { return true; } else { if (fns.isArray(result.errors)) { throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE, MODULE_NAME, result.errors[0].property, result.errors[0].message)); } throw new Error(sprintf(ERROR_MESSAGES.INVALID_JSON, MODULE_NAME)); } }
javascript
{ "resource": "" }
q24894
train
function(eventTags, logger) { if (eventTags && eventTags.hasOwnProperty(REVENUE_EVENT_METRIC_NAME)) { var rawValue = eventTags[REVENUE_EVENT_METRIC_NAME]; var parsedRevenueValue = parseInt(rawValue, 10); if (isNaN(parsedRevenueValue)) { logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_REVENUE, MODULE_NAME, rawValue)); return null; } logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_REVENUE_VALUE, MODULE_NAME, parsedRevenueValue)); return parsedRevenueValue; } return null; }
javascript
{ "resource": "" }
q24895
train
function(eventTags, logger) { if (eventTags && eventTags.hasOwnProperty(VALUE_EVENT_METRIC_NAME)) { var rawValue = eventTags[VALUE_EVENT_METRIC_NAME]; var parsedEventValue = parseFloat(rawValue); if (isNaN(parsedEventValue)) { logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_VALUE, MODULE_NAME, rawValue)); return null; } logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_NUMERIC_VALUE, MODULE_NAME, parsedEventValue)); return parsedEventValue; } return null; }
javascript
{ "resource": "" }
q24896
train
function(attributes) { if (typeof attributes === 'object' && !Array.isArray(attributes) && attributes !== null) { lodashForOwn(attributes, function(value, key) { if (typeof value === 'undefined') { throw new Error(sprintf(ERROR_MESSAGES.UNDEFINED_ATTRIBUTE, MODULE_NAME, key)); } }); return true; } else { throw new Error(sprintf(ERROR_MESSAGES.INVALID_ATTRIBUTES, MODULE_NAME)); } }
javascript
{ "resource": "" }
q24897
train
function(corner, size, scale) { scale = scale || 1; size = size || this.size; var width = size[0] * scale, height = size[1] * scale, width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2), // Define tip coordinates in terms of height and width values tips = { br: [0,0, width,height, width,0], bl: [0,0, width,0, 0,height], tr: [0,height, width,0, width,height], tl: [0,0, 0,height, width,height], tc: [0,height, width2,0, width,height], bc: [0,0, width,0, width2,height], rc: [0,0, width,height2, 0,height], lc: [width,0, width,height, 0,height2] }; // Set common side shapes tips.lt = tips.br; tips.rt = tips.bl; tips.lb = tips.tr; tips.rb = tips.tl; return tips[ corner.abbrev() ]; }
javascript
{ "resource": "" }
q24898
train
function() { if(!this.rendered) { return; } // Set tracking flag var posOptions = this.options.position; this.tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse); // Reassign events this._unassignEvents(); this._assignEvents(); }
javascript
{ "resource": "" }
q24899
convertNotation
train
function convertNotation(options, notation) { var i = 0, obj, option = options, // Split notation into array levels = notation.split('.'); // Loop through while(option = option[ levels[i++] ]) { if(i < levels.length) { obj = option; } } return [obj || options, levels.pop()]; }
javascript
{ "resource": "" }