_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q4100
ConfbridgeMute
train
function ConfbridgeMute(conference, channel) { ConfbridgeMute.super_.call(this, 'ConfbridgeMute'); this.set('Conference', conference); this.set('Channel', channel); }
javascript
{ "resource": "" }
q4101
ConfbridgeUnmute
train
function ConfbridgeUnmute(conference, channel) { ConfbridgeUnmute.super_.call(this, 'ConfbridgeUnmute'); this.set('Conference', conference); this.set('Channel', channel); }
javascript
{ "resource": "" }
q4102
AGI
train
function AGI(channel, command, commandId) { AGI.super_.call(this, 'AGI'); this.set('Channel', channel); this.set('Command', command); this.set('CommandID', commandId); }
javascript
{ "resource": "" }
q4103
BlindTransfer
train
function BlindTransfer(channel, context, extension) { BlindTransfer.super_.call(this, 'BlindTransfer'); this.set('Channel', channel); this.set('Context', context); this.set('Exten', extension); }
javascript
{ "resource": "" }
q4104
Filter
train
function Filter(operation, filter) { Filter.super_.call(this, 'Filter'); this.set('Operation', operation); this.set('Filter', filter); }
javascript
{ "resource": "" }
q4105
Nami
train
function Nami(amiData) { var self = this; Nami.super_.call(this); this.logLevel = 3; // debug level by default. var genericLog = function(minLevel, fun, msg) { if(self.logLevel >= minLevel) { fun(msg); } }; this.logger = amiData.logger || { error: function(msg) { genericLog(0, console.error, msg)}, warn: function(msg) { genericLog(1, console.warn, msg)}, info: function(msg) { genericLog(2, console.info, msg)}, debug: function(msg) { genericLog(3, console.log, msg)} }; this.connected = false; this.amiData = amiData; this.EOL = "\r\n"; this.EOM = this.EOL + this.EOL; this.welcomeMessage = "Asterisk Call Manager/.*" + this.EOL; this.received = false; this.responses = { }; this.callbacks = { }; this.on('namiRawMessage', this.onRawMessage); this.on('namiRawResponse', this.onRawResponse); this.on('namiRawEvent', this.onRawEvent); }
javascript
{ "resource": "" }
q4106
simpleIntersection
train
function simpleIntersection(array1, array2) { return array1 // Remove falsy elements .filter(el => el) // Match elements belonging in the two arrays .filter(el => array2.indexOf(el) !== -1) // Remove duplicates .filter((el, idx, arr) => arr.indexOf(el) === idx); }
javascript
{ "resource": "" }
q4107
generate
train
function generate(bind, el, param, value) { var div = element('div', {'class': BindClass}); div.appendChild(element('span', {'class': NameClass}, (param.name || param.signal) )); el.appendChild(div); var input = form; switch (param.input) { case 'checkbox': input = checkbox; break; case 'select': input = select; break; case 'radio': input = radio; break; case 'range': input = range; break; } input(bind, div, param, value); }
javascript
{ "resource": "" }
q4108
form
train
function form(bind, el, param, value) { var node = element('input'); for (var key in param) { if (key !== 'signal' && key !== 'element') { node.setAttribute(key === 'input' ? 'type' : key, param[key]); } } node.setAttribute('name', param.signal); node.value = value; el.appendChild(node); node.addEventListener('input', function() { bind.update(node.value); }); bind.elements = [node]; bind.set = function(value) { node.value = value; }; }
javascript
{ "resource": "" }
q4109
checkbox
train
function checkbox(bind, el, param, value) { var attr = {type: 'checkbox', name: param.signal}; if (value) attr.checked = true; var node = element('input', attr); el.appendChild(node); node.addEventListener('change', function() { bind.update(node.checked); }); bind.elements = [node]; bind.set = function(value) { node.checked = !!value || null; } }
javascript
{ "resource": "" }
q4110
select
train
function select(bind, el, param, value) { var node = element('select', {name: param.signal}); param.options.forEach(function(option) { var attr = {value: option}; if (valuesEqual(option, value)) attr.selected = true; node.appendChild(element('option', attr, option+'')); }); el.appendChild(node); node.addEventListener('change', function() { bind.update(param.options[node.selectedIndex]); }); bind.elements = [node]; bind.set = function(value) { for (var i=0, n=param.options.length; i<n; ++i) { if (valuesEqual(param.options[i], value)) { node.selectedIndex = i; return; } } }; }
javascript
{ "resource": "" }
q4111
radio
train
function radio(bind, el, param, value) { var group = element('span', {'class': RadioClass}); el.appendChild(group); bind.elements = param.options.map(function(option) { var id = OptionClass + param.signal + '-' + option; var attr = { id: id, type: 'radio', name: param.signal, value: option }; if (valuesEqual(option, value)) attr.checked = true; var input = element('input', attr); input.addEventListener('change', function() { bind.update(option); }); group.appendChild(input); group.appendChild(element('label', {'for': id}, option+'')); return input; }); bind.set = function(value) { var nodes = bind.elements, i = 0, n = nodes.length; for (; i<n; ++i) { if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true; } }; }
javascript
{ "resource": "" }
q4112
range
train
function range(bind, el, param, value) { value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2; var min = param.min || Math.min(0, +value) || 0, max = param.max || Math.max(100, +value) || 100, step = param.step || tickStep(min, max, 100); var node = element('input', { type: 'range', name: param.signal, min: min, max: max, step: step }); node.value = value; var label = element('label', {}, +value); el.appendChild(node); el.appendChild(label); function update() { label.textContent = node.value; bind.update(+node.value); } // subscribe to both input and change node.addEventListener('input', update); node.addEventListener('change', update); bind.elements = [node]; bind.set = function(value) { node.value = value; label.textContent = value; }; }
javascript
{ "resource": "" }
q4113
randCol
train
function randCol (r, g, b, a) { return "rgba(" + Math.floor(Math.random() * r).toString() + "," + Math.floor(Math.random() * g).toString() + "," + Math.floor(Math.random() * b).toString() + "," + a + ")"; }
javascript
{ "resource": "" }
q4114
render
train
function render (callback) { if (effectAttrs.speed !== undefined) { setTimeout(function () { id = requestAnimationFrame(callback); }, effectAttrs.speed); } else { id = requestAnimationFrame(callback); } }
javascript
{ "resource": "" }
q4115
xmlparser
train
function xmlparser(options) { var parserOptions = util._extend({ async: false, explicitArray: true, normalize: true, normalizeTags: true, trim: true }, options || {}); return xmlbodyparser; /** * Provide connect/express-style middleware * * @param {IncomingMessage} req * @param {ServerResponse} res * @param {Function} next * @return {*} */ function xmlbodyparser(req, res, next) { var data = ''; var parser = new xml2js.Parser(parserOptions); /** * @param {Error} err * @param {Object} [xml] */ var responseHandler = function (err, xml) { if (err) { err.status = 400; return next(err); } req.body = xml || req.body; req.rawBody = data; next(); }; if (req._body) { return next(); } req.body = req.body || {}; if (!hasBody(req) || !module.exports.regexp.test(mime(req))) { return next(); } req._body = true; // explicitly cast incoming to string req.setEncoding('utf-8'); req.on('data', function (chunk) { data += chunk; }); // in case `parseString` callback never was called, ensure response is sent parser.saxParser.onend = function() { if (req.complete && req.rawBody === undefined) { return responseHandler(null); } }; req.on('end', function () { // invalid xml, length required if (data.trim().length === 0) { return next(error(411)); } parser.parseString(data, responseHandler); }); } }
javascript
{ "resource": "" }
q4116
hasBody
train
function hasBody(req) { var encoding = 'transfer-encoding' in req.headers; var length = 'content-length' in req.headers && req.headers['content-length'] !== '0'; return encoding || length; }
javascript
{ "resource": "" }
q4117
_processOnKeyUp__noWords
train
function _processOnKeyUp__noWords(evt) { let key = evt.keyCode || evt.which; let char = String.fromCharCode(key); if (key == 13) { this._onSelectedCB(this._input.value); }else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8){ let prefix = this._input.value; if (prefix != '') this._keyListenerDebounced(prefix); } }
javascript
{ "resource": "" }
q4118
_processOnKeyUp
train
function _processOnKeyUp(evt) { let key = evt.keyCode || evt.which; let char = String.fromCharCode(key); let self = this; if (key === 38) { if (self._idx > 0) { _unselectWord(self._words[self._idx]); self._idx--; } self._words[self._idx].className += ' ac__word--selected'; } else if (key == 40) { if (self._idx < self._words.length - 1) { _unselectWord(self._words[self._idx]); self._idx++; } self._words[self._idx].className += ' ac__word--selected'; } else if (key == 13) { if (self._words.length && self._idx > -1) self._onSelectedCB(_getStringFromWordElement(self._words[self._idx])); else self._onSelectedCB(self._input.value); } else if (/[a-zA-Z0-9-_ ]/.test(char) || key === 8) { self._idx = -1; let prefix = self._input.value; if (prefix != '') self._keyListenerDebounced(prefix); else _flushWordsContainer.call(self); } }
javascript
{ "resource": "" }
q4119
_buildScriptContainer
train
function _buildScriptContainer(){ let parent = document.getElementById('ac__script'); if (parent == null){ parent = document.createElement('div'); parent.id = 'ac__script'; parent.appendChild(document.createElement('script')); document.body.appendChild(parent); } }
javascript
{ "resource": "" }
q4120
_paintWords
train
function _paintWords(prefix, words){ _flushWordsContainer.call(this); this._words = []; let docFrag = document.createDocumentFragment(); for (let i = 0; i < words.length; i++){ let wordElement = document.createElement('p'); wordElement.className = 'ac__word'; wordElement.style.cursor = 'pointer'; let prefixElement = document.createElement('span'); prefixElement.className = 'ac__prefix'; prefixElement.style.pointerEvents = 'none'; let suffix = document.createTextNode(words[i].slice(prefix.length)); prefixElement.appendChild(document.createTextNode(prefix)); wordElement.appendChild(prefixElement); wordElement.appendChild(suffix); docFrag.appendChild(wordElement); this._words.push(wordElement); } this._container.appendChild(docFrag); }
javascript
{ "resource": "" }
q4121
_getSuggestions
train
function _getSuggestions(prefix) { let scriptContainer = document.getElementById('ac__script'); let newScript = document.createElement('script'); newScript.src = 'http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q='+prefix+'&callback=AmazonAutocomplete.AmazonJSONPCallbackHandler_'+this._id; scriptContainer.replaceChild(newScript, scriptContainer.firstChild); }
javascript
{ "resource": "" }
q4122
layoutInit
train
function layoutInit() { IBMChat.subscribe('layout:choose', function(data) { var widget = new Choose(data); widgets[data.uuid] = widget; }); IBMChat.subscribe('layout:confirm', function(data) { var widget = new Choose(data); widgets[data.uuid] = widget; }); }
javascript
{ "resource": "" }
q4123
requireExtended
train
function requireExtended(name) { var module = require(name); if (module && module.__esModule === true && typeof module.default !== 'undefined') { if (typeof module.__module !== 'undefined') { // if __module is specified as a named export, add it to the default export _.defaults(module.default, {__module: module.__module}) } return module.default; } return module; }
javascript
{ "resource": "" }
q4124
CloudRequest
train
function CloudRequest(options) { if (!(this instanceof CloudRequest)) return new CloudRequest(options); merge(this, defaultOptions, options); if (this.debug) debug.enabled = true; if (typeof this.request === 'undefined') { this.jar = request.jar(); this.request = request.defaults({ jar: this.jar }); if (this.debugNet) { this.request.debug = true; require('request-debug')(this.request); } } debug('CloudAPI-request initialized with options %o', options); }
javascript
{ "resource": "" }
q4125
UnifiAPI
train
function UnifiAPI(options) { if (!(this instanceof UnifiAPI)) return new UnifiAPI(options); merge(this, defaultOptions, options); this.debugging(this.debug); if (typeof this.net === 'undefined') { this.net = new UnifiRequest(merge(true, defaultOptions, options)); } debug('UnifiAPI Initialized with options %o', options); }
javascript
{ "resource": "" }
q4126
run
train
function run(cmd) { try { if (isWindows) cmd = 'cmd /C ' + cmd; var code = shell.exec(cmd); return code; } catch (err) { if (err) { console.error(err) } return 1; } }
javascript
{ "resource": "" }
q4127
exec
train
function exec(command) { var tempName = temp.path({suffix: '.exec'}); var cmd; if (isWindows) cmd = command + ' > ' + tempName + ' 2>&1'; else cmd = '(' + command + ') > ' + tempName + ' 2>&1'; var code = run(cmd); var text; if (fs.existsSync(tempName)) { try { text = fs.readFileSync(tempName, 'utf8'); fs.unlink(tempName); } catch (err) { throw new Error('ERROR: could not delete capture file'); } } else { throw new Error('ERROR: output not captured'); } return { code: code, stdout: text } }
javascript
{ "resource": "" }
q4128
resolvePastAndFuture
train
function resolvePastAndFuture(past, future, future5) { return function(d, millis) { var isFuture = millis < 0; if (!isFuture) { return past; } else { if (d <= 4) { return future; } else { return future5; } } }; }
javascript
{ "resource": "" }
q4129
onData
train
function onData(data) { data = data.toString("ascii"); bufferedData += data; if (debug) console.log("Server: " + util.inspect(data)); if (checkResp === true) { if (bufferedData.substr(0, 3) === "+OK") { checkResp = false; response = true; } else if (bufferedData.substr(0, 4) === "-ERR") { checkResp = false; response = false; // The following is only used for SASL } else if (multiline === false) { checkResp = false; response = true; } } if (checkResp === false) { if (multiline === true && (response === false || bufferedData.substr(bufferedData.length-5) === "\r\n.\r\n")) { // Make a copy to avoid race conditions var responseCopy = response; var bufferedDataCopy = bufferedData; response = null; checkResp = true; multiline = false; bufferedData = ""; callback(responseCopy, bufferedDataCopy); } else if (multiline === false) { // Make a copy to avoid race conditions var responseCopy = response; var bufferedDataCopy = bufferedData; response = null; checkResp = true; multiline = false; bufferedData = ""; callback(responseCopy, bufferedDataCopy); } } }
javascript
{ "resource": "" }
q4130
loadStyles
train
function loadStyles(css, doc) { // default to the global `document` object if (!doc) doc = document; var head = doc.head || doc.getElementsByTagName('head')[0]; // no <head> node? create one... if (!head) { head = doc.createElement('head'); var body = doc.body || doc.getElementsByTagName('body')[0]; if (body) { body.parentNode.insertBefore(head, body); } else { doc.documentElement.appendChild(head); } } var style = doc.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { // IE style.styleSheet.cssText = css; } else { // the world style.appendChild(doc.createTextNode(css)); } head.appendChild(style); return style; }
javascript
{ "resource": "" }
q4131
Engine
train
function Engine(options) { Options.call(this, options); this.views = {}; this.defaultTemplates(); this.defaultOptions(); if (this.enabled('debug')) { this.debug(); } }
javascript
{ "resource": "" }
q4132
normalize
train
function normalize (obj) { if (!obj.dtype) { obj.dtype = defaultDtype[obj.type] || 'array' } //provide limits switch (obj.dtype) { case 'float32': case 'float64': case 'audiobuffer': case 'ndsamples': case 'ndarray': obj.min = -1 obj.max = 1 break; case 'uint8': obj.min = 0 obj.max = 255 break; case 'uint16': obj.min = 0 obj.max = 65535 break; case 'uint32': obj.min = 0 obj.max = 4294967295 break; case 'int8': obj.min = -128 obj.max = 127 break; case 'int16': obj.min = -32768 obj.max = 32767 break; case 'int32': obj.min = -2147483648 obj.max = 2147483647 break; default: obj.min = -1 obj.max = 1 break; } return obj }
javascript
{ "resource": "" }
q4133
tracker
train
function tracker(emitters, namespace, appId, encodeBase64) { if (!(emitters instanceof Array)) { emitters = [emitters]; } encodeBase64 = encodeBase64 !== false; var trackerCore = core(encodeBase64, sendPayload); trackerCore.setPlatform('srv'); // default platform trackerCore.setTrackerVersion('node-' + version); trackerCore.setTrackerNamespace(namespace); trackerCore.setAppId(appId); /** * Send the payload for an event to the endpoint * * @param object payload Dictionary of name-value pairs for the querystring */ function sendPayload(payload) { var builtPayload = payload.build(); for (var i=0; i<emitters.length; i++) { emitters[i].input(builtPayload); } } var trackEcommerceTransaction = trackerCore.trackEcommerceTransaction; /** * Track an ecommerce transaction and all items in that transaction * Each item is represented by a dictionary which may have the following fields: * 1. string sku Required. SKU code of the item. * 2. string name Optional. Name of the item. * 3. string category Optional. Category of the item. * 4. string price Required. Price of the item. * 5. string quantity Required. Purchase quantity. * 6. array context Optional. Custom context relating to the item. * 7. number tstamp Optional. Timestamp for the item. * * @param string orderId Required. Internal unique order id number for this transaction. * @param string affiliation Optional. Partner or store affiliation. * @param string total Required. Total amount of the transaction. * @param string tax Optional. Tax amount of the transaction. * @param string shipping Optional. Shipping charge for the transaction. * @param string city Optional. City to associate with transaction. * @param string state Optional. State to associate with transaction. * @param string country Optional. Country to associate with transaction. * @param string currency Optional. Currency to associate with this transaction. * @param array items Optional. Items which make up the transaction. * @param array context Optional. Context relating to the event. * @param number tstamp Optional. Timestamp for the event. */ trackerCore.trackEcommerceTransaction = function (orderId, affiliation, total, tax, shipping, city, state, country, currency, items, context, tstamp) { trackEcommerceTransaction( orderId, affiliation, total, tax, shipping, city, state, country, currency, context, tstamp ); if (items) { for (var i=0; i<items.length; i++) { var item = items[i]; trackerCore.trackEcommerceTransactionItem( orderId, item.sku, item.name, item.category, item.price, item.quantity, currency, item.context, tstamp ); } } }; return trackerCore; }
javascript
{ "resource": "" }
q4134
sendPayload
train
function sendPayload(payload) { var builtPayload = payload.build(); for (var i=0; i<emitters.length; i++) { emitters[i].input(builtPayload); } }
javascript
{ "resource": "" }
q4135
emitter
train
function emitter(endpoint, protocol, port, method, bufferSize, callback, agentOptions) { protocol = (protocol || 'http').toLowerCase(); method = (method || 'get').toLowerCase(); if (bufferSize === null || typeof bufferSize === 'undefined') { bufferSize = method === 'get' ? 0 : 10; } var portString = port ? ':' + port : ''; var path = method === 'get' ? '/i' : '/com.snowplowanalytics.snowplow/tp2'; var targetUrl = protocol + '://' + endpoint + portString + path; var buffer = []; /** * Send all events queued in the buffer to the collector */ function flush() { var temp = buffer; buffer = []; if (method === 'post') { var postJson = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0', data: temp.map(valuesToStrings) }; request.post({ url: targetUrl, json: postJson, agentOptions: agentOptions, headers: { 'content-type': 'application/json; charset=utf-8' } }, callback); } else { for (var i=0; i<temp.length; i++) { request.get({ url: targetUrl, agentOptions: agentOptions, qs: temp[i] }, callback); } } } return { flush: flush, input: function (payload) { buffer.push(payload); if (buffer.length >= bufferSize) { flush(); } } }; }
javascript
{ "resource": "" }
q4136
flush
train
function flush() { var temp = buffer; buffer = []; if (method === 'post') { var postJson = { schema: 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0', data: temp.map(valuesToStrings) }; request.post({ url: targetUrl, json: postJson, agentOptions: agentOptions, headers: { 'content-type': 'application/json; charset=utf-8' } }, callback); } else { for (var i=0; i<temp.length; i++) { request.get({ url: targetUrl, agentOptions: agentOptions, qs: temp[i] }, callback); } } }
javascript
{ "resource": "" }
q4137
valuesToStrings
train
function valuesToStrings(payload) { var stringifiedPayload = {}; for (var key in payload) { if (payload.hasOwnProperty(key)) { stringifiedPayload[key] = payload[key].toString(); } } return stringifiedPayload; }
javascript
{ "resource": "" }
q4138
train
function(entity, options) { options = options || {}; options.checkext = options.checkext || checkext; options.extlist = options.extlist || extlist; options.logFormat = options.logFormat || '%s: %s'; options.logger = options.logger || console; options.ignore = options.ignore || false; options.cwd = options.cwd || ''; this.options = options; this.scripts = []; if (!(options.extlist instanceof RegExp) && options.extlist instanceof Array){ this.__log('Converting extension list to regular expression'); options.extlist = new RegExp('(.*)(' + options.extlist.join('$|').replace(/\./g,'\\.') + ')'); }; this.__log('Using regular expression' + options.extlist + 'for extenstion matching'); this.then(entity); return this; }
javascript
{ "resource": "" }
q4139
createNamespace
train
function createNamespace(parent, parts) { var part = getName(parts.shift()); if (!parent[part]) { parent[part] = {}; } if (parts.length) { parent = createNamespace(parent[part], parts); } return parent; }
javascript
{ "resource": "" }
q4140
getName
train
function getName(script) { var script = path.basename(script, path.extname(script)).replace(/[^a-zA-Z0-9]/g, '.') , parts = script.split('.') , name = parts.shift(); if (parts.length) { for (var p in parts) { name += parts[p].charAt(0).toUpperCase() + parts[p].substr(1, parts[p].length); } } return name; }
javascript
{ "resource": "" }
q4141
assertValidFieldType
train
function assertValidFieldType(pojoName, fieldName, pojo, expectedType) { var value = pojo[fieldName]; var actualType = typeof value; if (value === undefined || value === null) { return; } switch (expectedType) { case BOOLEAN_TYPE: if (actualType !== BOOLEAN_TYPE && actualType !== NUMBER_TYPE) { err(); } pojo[fieldName] = Boolean(value); return; case NUMBER_TYPE: if (actualType === NUMBER_TYPE) { return; } if (actualType === STRING_TYPE) { var newValue = parseFloat(value); if (isNaN(newValue)) { err(); } pojo[fieldName] = newValue; } return; case STRING_TYPE: if (actualType !== STRING_TYPE) { pojo[fieldName] = value.toString(); } return; case DATE_EXPECTED_TYPE: var getTime = value.getTime; if (typeof getTime === FUNCTION_TYPE) { var timeValue = value.getTime(); if (isNaN(timeValue)) { err(); } if (!(value instanceof Date)) { pojo[fieldName] = new Date(timeValue); } return; } if (actualType === STRING_TYPE) { var newDate = new Date(value); if (!isNaN(newDate.getTime())) { pojo[fieldName] = newDate; return; } } err(); return; case BUFFER_EXPECTED_TYPE: if (!BUFFER_EXISTS) { return; } if (!(value instanceof Buffer)) { err(); } return; } // one pojo of array of array of pojos? if (expectedType.length > 3 && expectedType.substr(expectedType.length - 2, 2) === '[]') { var individualPojoType = expectedType.substr(0, expectedType.length - 6); var asserter_1 = asserters[individualPojoType]; if (typeof asserter_1 !== FUNCTION_TYPE) { err(); } if (isNaN(value.length)) { err(); } for (var i = 0; i < value.length; i++) { try { asserter_1(value[i], true); } catch (e) { err('Error at index \'' + i + '\': ' + e.message); } } // all instances valid return; } var asserter = asserters[expectedType.substr(0, expectedType.length - 4)]; if (typeof asserter !== FUNCTION_TYPE) { expectedTypeErr(); } try { asserter(value, true); } catch (e) { err(e.message); } function err(extraMessage) { var message = 'Invalid ' + pojoName + ' provided. Field \'' + fieldName + '\' with value \'' + safeValue(value) + '\' is not a valid \'' + expectedType + '\'.'; if (extraMessage !== undefined) { message += ' ' + extraMessage; } throw new Error(message); } function expectedTypeErr() { throw new Error('Cannot validate \'' + pojoName + '\' field \'' + fieldName + '\' since expected type provided \'' + expectedType + '\' is not understood.'); } }
javascript
{ "resource": "" }
q4142
getCORSRequest
train
function getCORSRequest() { var xhr = new root.XMLHttpRequest(); if ('withCredentials' in xhr) { return xhr; } else if (!!root.XDomainRequest) { return new XDomainRequest(); } else { throw new Error('CORS is not supported by your browser'); } }
javascript
{ "resource": "" }
q4143
toBase64URL
train
function toBase64URL(data) { if (typeof data === 'string') { data = new Buffer(data); } return data.toString('base64') .replace(/=+/g, '') // remove '='s .replace(/\+/g, '-') // '+' → '-' .replace(/\//g, '_'); // '/' → '_' }
javascript
{ "resource": "" }
q4144
ping
train
function ping() { result = fn.apply(context || this, args || []); context = args = null; executed = true; }
javascript
{ "resource": "" }
q4145
wrapper
train
function wrapper() { context = this; args = arguments; if (!no_postpone) { cancel(); timeout = $timeout(ping, wait); } else if (executed) { executed = false; timeout = $timeout(ping, wait); } }
javascript
{ "resource": "" }
q4146
set
train
function set(props, req, language) { if(language) { req.language = language; } else { language = req.language = acceptLanguage.get(req.headers['accept-language']); } if(typeof props.localizations === 'function') { req.localizations = props.localizations(language); } }
javascript
{ "resource": "" }
q4147
enable
train
function enable(app, route, repoDir){ expressApp = app; routePfx = route; if(repoDir){ reader.setRepoDir(repoDir); } app.post(route, androidUpdate.updater); app.get(route, function (req, res){ res.send(reader.available()); }); }
javascript
{ "resource": "" }
q4148
DragDropTouch
train
function DragDropTouch() { this._lastClick = 0; // enforce singleton pattern if (DragDropTouch._instance) { throw 'DragDropTouch instance already created.'; } // listen to touch events if ('ontouchstart' in document) { var d = document, ts = this._touchstart.bind(this), tm = this._touchmove.bind(this), te = this._touchend.bind(this); d.addEventListener('touchstart', ts); d.addEventListener('touchmove', tm); d.addEventListener('touchend', te); d.addEventListener('touchcancel', te); } }
javascript
{ "resource": "" }
q4149
registerClass
train
function registerClass(rule, className) { // Skip falsy values if (!className) return true // Support array of class names `{composes: ['foo', 'bar']}` if (Array.isArray(className)) { for (let index = 0; index < className.length; index++) { const isSetted = registerClass(rule, className[index]) if (!isSetted) return false } return true } // Support space separated class names `{composes: 'foo bar'}` if (className.indexOf(' ') > -1) { return registerClass(rule, className.split(' ')) } const {parent} = rule.options // It is a ref to a local rule. if (className[0] === '$') { const refRule = parent.getRule(className.substr(1)) if (!refRule) { warning(false, '[JSS] Referenced rule is not defined. \r\n%s', rule) return false } if (refRule === rule) { warning(false, '[JSS] Cyclic composition detected. \r\n%s', rule) return false } parent.classes[rule.key] += ` ${parent.classes[refRule.key]}` return true } rule.options.parent.classes[rule.key] += ` ${className}` return true }
javascript
{ "resource": "" }
q4150
buildDependencyGraph
train
function buildDependencyGraph(module, dependencies, graph) { if (module && !graph[module]) { graph[module] = []; } var dependencyNames = Object.keys(dependencies); dependencyNames.forEach(function(dependencyName) { var dependency = dependencies[dependencyName]; if (module && graph[module].indexOf(dependencyName) === -1) { graph[module].push(dependencyName); } // Traverse down to this dependency dependencies: // Dependency-ception. if (dependency.dependencies) { buildDependencyGraph(dependencyName, dependency.dependencies, graph); } }); }
javascript
{ "resource": "" }
q4151
resolveDependencyGraph
train
function resolveDependencyGraph(module, resolved, unresolved, dependencies) { var moduleDependencies; if (module) { moduleDependencies = dependencies[module]; if (!moduleDependencies) { throw new Error('Component ' + module + ' not installed. Try bower install --save ' + module); } unresolved.push(module); } else { moduleDependencies = Object.keys(dependencies); } moduleDependencies.forEach(function(moduleDependency) { if (resolved.indexOf(moduleDependency) === -1) { if (unresolved.indexOf(moduleDependency) !== -1) { throw new Error('Circular reference detected for ' + module + ' - ' + moduleDependency); } resolveDependencyGraph(moduleDependency, resolved, unresolved, dependencies); } }); if (module) { resolved.push(module); unresolved = unresolved.splice(unresolved.indexOf(module), 1); } }
javascript
{ "resource": "" }
q4152
extractDestData
train
function extractDestData(data) { if (destinationConfigExists(data)) { if (data.dest instanceof Object) { return extractMultiDestValues(data.dest); } else { return extractBackportDestination(data.dest); } } return []; }
javascript
{ "resource": "" }
q4153
concatenateAndWriteFile
train
function concatenateAndWriteFile(files, destination, separator) { if (!destination || !files || !files.length) return; files = _.map(files, process); var src = files.join(separator || grunt.util.linefeed); grunt.file.write(destination, src); grunt.log.writeln('File ' + destination.cyan + ' created.'); }
javascript
{ "resource": "" }
q4154
bowerList
train
function bowerList(kind) { return function(done) { var params = _.extend({}, bowerOptions); params[kind] = true; bower.commands.list(params, {offline: true}) .on('error', grunt.fail.fatal.bind(grunt.fail)) .on('end', function(data) { done(null, data); // null means "no error" for async.parallel }); }; }
javascript
{ "resource": "" }
q4155
expandForAll
train
function expandForAll(array, makeMask) { var files = []; ensureArray(array).forEach(function(item) { files = files.concat(grunt.file.expand(makeMask(item))); }); return files; }
javascript
{ "resource": "" }
q4156
joinPathWith
train
function joinPathWith(prepend, append) { return function(pathPart) { // path.join(prepend..., pathPart, append...) var params = ensureArray(prepend || []).concat([pathPart], ensureArray(append || [])); return path.join.apply(path, params); }; }
javascript
{ "resource": "" }
q4157
isFileExtension
train
function isFileExtension(filepath, extension) { return typeof filepath === 'string' && path.extname(filepath) === extension && fs.existsSync(filepath) && fs.lstatSync(filepath).isFile() ; }
javascript
{ "resource": "" }
q4158
getFileSize
train
function getFileSize(filepath, options) { var stats = fs.statSync(filepath); return filesize(stats.size, options); }
javascript
{ "resource": "" }
q4159
toFileStats
train
function toFileStats(componentName, filepath) { return { src: path.relative(bowerDir, filepath), component: componentName, size: getFileSize(filepath) }; }
javascript
{ "resource": "" }
q4160
logGroupStats
train
function logGroupStats(groupName, groupOrder, groupDest, files) { if (!groupDest) { return false; } if (!grunt.option('no-color')) { groupDest = groupDest.cyan; } grunt.verbose.subhead('%s: -> %s', groupName, groupDest); groupOrder.forEach(function(component) { if (_.isArray(files[component]) && files[component].length) { files[component].forEach(function(file) { if (!grunt.option('no-color')) { file.component = file.component.yellow; file.size = file.size.green; } grunt.verbose.writeln(' ./%s [%s] - %s', file.src, file.component, file.size); }); } }); }
javascript
{ "resource": "" }
q4161
freezeAllProcessDir
train
function freezeAllProcessDir(dir, basePath, result) { fs.readdirSync(dir).forEach(function(file) { file = PATH.resolve(dir, file); var stat = fs.statSync(file); if (stat.isFile()) { freezeAllProcessFile(file, basePath, result); } else if (stat.isDirectory()) { freezeAllProcessDir(file, basePath, result); } }); }
javascript
{ "resource": "" }
q4162
mkpath
train
function mkpath(path) { var dirs = path.split(PATH.sep); var _path = ''; var winDisk = /^\w{1}:\\$/; dirs.forEach(function(dir) { dir = dir || PATH.sep; if (dir) { _path = _path ? PATH.join(_path, dir) : dir; // fs.mkdirSync('/') raises EISDIR (invalid operation) exception on OSX 10.8.4/node 0.10 // fs.mkdirSync('D:\\') raises EPERM (operation not permitted) exception on Windows 7/node 0.10 // not tested in other configurations if (_path === '/' || winDisk.test(PATH.resolve(dir))) { return; } // @see https://github.com/veged/borschik/issues/90 try { fs.mkdirSync(_path); } catch(e) { // ignore EEXIST error if (e.code !== 'EEXIST') { throw new Error(e) } } } }); }
javascript
{ "resource": "" }
q4163
save
train
function save(filePath, content) { mkpath(PATH.dirname(filePath)); fs.writeFileSync(filePath, content); }
javascript
{ "resource": "" }
q4164
subArrayJoin
train
function subArrayJoin(a, separator, from, to) { return a.slice(from, to + 1).join(separator); }
javascript
{ "resource": "" }
q4165
arraySplice
train
function arraySplice(a1, from, to, a2) { var aL = a1.slice(0, from); var aR = a1.slice(to); return aL.concat(a2).concat(aR); }
javascript
{ "resource": "" }
q4166
setNestingLevel
train
function setNestingLevel(config, dir, rawValue) { // config can have value "0", so we can't use "!config[dir]" if ( !(dir in config) ) { config[dir] = Math.max(parseInt(rawValue, 10) || 0, 0); } }
javascript
{ "resource": "" }
q4167
train
function(lines, error) { var lineNumber = error.line - 1; var result = [ renderLine(lineNumber, lines[lineNumber]), renderPointer(error.col) ]; var i = lineNumber - 1; var linesAround = 2; while (i >= 0 && i >= (lineNumber - linesAround)) { result.unshift(renderLine(i, lines[i])); i--; } i = lineNumber + 1; while (i < lines.length && i <= (lineNumber + linesAround)) { result.push(renderLine(i, lines[i])); i++; } result.unshift(error.message + " (line: " + error.line + ", col: " + error.col + ", pos: " + error.pos + ")"); return result.join('\n'); }
javascript
{ "resource": "" }
q4168
parseJSON
train
function parseJSON(str) { var result; try { result = $scope.options.parserFn(str); } catch (e) { return str; } return result; }
javascript
{ "resource": "" }
q4169
error
train
function error() { this.httpRequest.upload.onerror = function onError() { $scope.$apply(function apply() { $scope.finishedUploading(); $scope.isError = true; var response = $scope.options.parserFn(this.httpRequest.responseText); $rootScope.$broadcast('$dropletError', response); $scope.onError({ response: response }); this.deferred.reject(response); }.bind(this)); }.bind(this); }
javascript
{ "resource": "" }
q4170
progress
train
function progress() { var requestLength = $scope.getRequestLength(this.files); this.httpRequest.upload.onprogress = function onProgress(event) { $scope.$apply(function apply() { if (event.lengthComputable) { // Update the progress object. $scope.requestProgress.percent = Math.round((event.loaded / requestLength) * 100); $scope.requestProgress.loaded = event.loaded; $scope.requestProgress.total = requestLength; } }); }; }
javascript
{ "resource": "" }
q4171
walk
train
function walk(wpath, type, excludeDir, callback) { // regex - any chars, then dash type, 's' is optional, with .js or .coffee extension, case-insensitive // e.g. articles-MODEL.js or mypackage-routes.coffee var rgx = new RegExp('(.*)-' + type + '(s?).(js|coffee)$', 'i'); if (!fs.existsSync(wpath)) return; fs.readdirSync(wpath).forEach(function(file) { var newPath = path.join(wpath, file); var stat = fs.statSync(newPath); if (stat.isFile() && (rgx.test(file) || (baseRgx.test(file)) && ~newPath.indexOf(type))) { // if (!rgx.test(file)) console.log(' Consider updating filename:', newPath); callback(newPath); } else if (stat.isDirectory() && file !== excludeDir && ~newPath.indexOf(type)) { walk(newPath, type, excludeDir, callback); } }); }
javascript
{ "resource": "" }
q4172
preload
train
function preload(gpath, type) { glob.sync(gpath).forEach(function(file) { walk(file, type, null, require); }); }
javascript
{ "resource": "" }
q4173
findAssertionSourceInTrace
train
function findAssertionSourceInTrace(trace) { var found = null; for (var i = 0, l = trace.length; i < l; ++i) { if ( trace[i].file === stSkipStart.file && trace[i].line >= stSkipStart.line && trace[i].line <= stSkipEnd.line ) { break; } found = trace[i]; } return found; }
javascript
{ "resource": "" }
q4174
prepArgs
train
function prepArgs(args, name, event, defaults) { args = Array.from(args); var namespace = [name]; if (!Array.isArray(event)) { event = event.split(delimiter); } namespace = namespace.concat(event); args.shift();//remove the event args.unshift(namespace); if (defaults) { args.push(defaults); } return args; }
javascript
{ "resource": "" }
q4175
train
function (config) { /** @type {SplunkLogger} */ this.logger = new SplunkLogger(config); // If using the common logger's default name, change it if (this.logger.config.name.match("splunk-javascript-logging/\\d+\\.\\d+\\.\\d+")) { this.logger.config.name = "splunk-bunyan-logger/0.10.1"; } // Overwrite the common library's error callback var that = this; this.logger.error = function(err, context) { that.emit("error", err, context); }; /* jshint unused:false */ /** * A callback function called after sending a request to Splunk: * <code>function(err, response, body)</code>. Defaults * to an empty function. * * @type {function} */ this.send = function(err, resp, body) {}; }
javascript
{ "resource": "" }
q4176
train
function (level) { switch(level) { case 10: return module.exports.levels.TRACE; case 20: return module.exports.levels.DEBUG; case 40: return module.exports.levels.WARN; case 50: return module.exports.levels.ERROR; case 60: return module.exports.levels.FATAL; default: return module.exports.levels.INFO; } }
javascript
{ "resource": "" }
q4177
train
function(declarations) { var strCss = ''; if (declarations.type === 'declaration') { strCss += '\n\t' + processDeclaration(declarations); } else if (declarations.type === 'comment') { strCss += ' ' + processComment(declarations); } return strCss; }
javascript
{ "resource": "" }
q4178
train
function(rule) { var strCss = ''; strCss += rule.selectors.join(',\n') + ' {'; rule.declarations.forEach(function(rules) { strCss += commentOrDeclaration(rules); }); strCss += '\n}\n\n'; return strCss; }
javascript
{ "resource": "" }
q4179
train
function(rule) { var strCss = ''; if (rule.type === 'rule') { strCss += processRule(rule); } else if (rule.type === 'comment') { strCss += processComment(rule) + '\n\n'; } return strCss; }
javascript
{ "resource": "" }
q4180
train
function(frame) { var strCss = ''; if (frame.type === 'keyframe') { strCss += frame.values.join(',') + ' {'; frame.declarations.forEach(function(declaration) { strCss += commentOrDeclaration(declaration); }); strCss += '\n}\n\n'; } else if (frame.type === 'comment') { strCss += processComment(frame) + '\n\n'; } return strCss; }
javascript
{ "resource": "" }
q4181
train
function(media) { var strCss = ''; strCss += '@media ' + media.rule + ' {\n\n'; media.rules.forEach(function(rule) { strCss += commentOrRule(rule); }); strCss += '}\n\n'; log(' @media ' + media.rule); return strCss; }
javascript
{ "resource": "" }
q4182
train
function(a, b, isMax) { var sortValA = a.sortVal, sortValB = b.sortVal; isMax = typeof isMax !== 'undefined' ? isMax : false; // consider print for sorting if sortVals are equal if (sortValA === sortValB) { if (a.rule.match(/print/)) { // a contains print and should be sorted after b return 1; } if (b.rule.match(/print/)) { // b contains print and should be sorted after a return -1; } } // return descending sort order for max-(width|height) media queries if (isMax) { return sortValB - sortValA; } // return ascending sort order return sortValA - sortValB; }
javascript
{ "resource": "" }
q4183
train
function(media) { if (options.use_external) { media.forEach(function(item) { strMediaStyles += processMedia(item); }); } else { media.forEach(function(item) { strStyles += processMedia(item); }); } }
javascript
{ "resource": "" }
q4184
strict
train
function strict(query) { return foldl(function(acc, val, key) { if (has.call(allowedKeys, key)) acc[key] = val; return acc; }, {}, utm(query)); }
javascript
{ "resource": "" }
q4185
installTimers
train
function installTimers(pluginConfig, lambdaContext) { const timeRemaining = lambdaContext.getRemainingTimeInMillis(); const memoryLimit = lambdaContext.memoryLimitInMB; function timeoutWarningFunc(cb) { const Raven = pluginConfig.ravenClient; ravenInstalled && Raven.captureMessage("Function Execution Time Warning", { level: "warning", extra: { TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis() } }, cb); } function timeoutErrorFunc(cb) { const Raven = pluginConfig.ravenClient; ravenInstalled && Raven.captureMessage("Function Timed Out", { level: "error", extra: { TimeRemainingInMsec: lambdaContext.getRemainingTimeInMillis() } }, cb); } function memoryWatchFunc(cb) { const used = process.memoryUsage().rss / 1048576; const p = (used / memoryLimit); if (p >= 0.75) { const Raven = pluginConfig.ravenClient; ravenInstalled && Raven.captureMessage("Low Memory Warning", { level: "warning", extra: { MemoryLimitInMB: memoryLimit, MemoryUsedInMB: Math.floor(used) } }, cb); if (memoryWatch) { clearTimeout(memoryWatch); memoryWatch = null; } } else { memoryWatch = setTimeout(memoryWatchFunc, 500); } } if (pluginConfig.captureTimeoutWarnings) { // We schedule the warning at half the maximum execution time and // the error a few milliseconds before the actual timeout happens. timeoutWarning = setTimeout(timeoutWarningFunc, timeRemaining / 2); timeoutError = setTimeout(timeoutErrorFunc, Math.max(timeRemaining - 500, 0)); } if (pluginConfig.captureMemoryWarnings) { // Schedule memory watch dog interval. Note that we're not using // setInterval() here as we don't want invokes to be skipped. memoryWatch = setTimeout(memoryWatchFunc, 500); } }
javascript
{ "resource": "" }
q4186
clearTimers
train
function clearTimers() { if (timeoutWarning) { clearTimeout(timeoutWarning); timeoutWarning = null; } if (timeoutError) { clearTimeout(timeoutError); timeoutError = null; } if (memoryWatch) { clearTimeout(memoryWatch); memoryWatch = null; } }
javascript
{ "resource": "" }
q4187
wrapCallback
train
function wrapCallback(pluginConfig, cb) { return (err, data) => { // Stop watchdog timers clearTimers(); // If an error was thrown we'll report it to Sentry if (err && pluginConfig.captureErrors) { const Raven = pluginConfig.ravenClient; ravenInstalled && Raven.captureException(err, {}, () => { cb(err, data); }); } else { cb(err, data); } }; }
javascript
{ "resource": "" }
q4188
first
train
function first(arr, fn) { const l = arr.length; for (let i = 0; i < l; i += 1) { const res = fn(arr[i], i); if (res) { return res; } } return null; }
javascript
{ "resource": "" }
q4189
splitArgs
train
function splitArgs(str) { const out = []; let inString = false; let currentArg = ''; for (let index = 0; index < str.length; index += 1) { const c = str[index]; if (c === ',' && !inString) { out.push(currentArg.trim()); currentArg = ''; } else if (currentArg.length === 0 && c === '"' && !inString) { currentArg += c; inString = true; } else if (inString && c === '"' && str[index - 1] !== '\\') { currentArg += c; inString = false; } else if (!(c === ' ' && currentArg.length === 0)) { currentArg += c; } } out.push(currentArg.trim()); return out; }
javascript
{ "resource": "" }
q4190
load
train
function load(template) { return new Promise((resolve, reject) => { const promise = Benchpress.loader(template, (templateFunction) => { resolve(templateFunction); }); if (promise && promise.then) { promise.then(resolve, reject); } }); }
javascript
{ "resource": "" }
q4191
render
train
function render(template, data, block) { data = Benchpress.addGlobals(data || {}); return Promise.try(() => { Benchpress.cache[template] = Benchpress.cache[template] || load(template); return Benchpress.cache[template]; }).then((templateFunction) => { if (block) { templateFunction = templateFunction.blocks && templateFunction.blocks[block]; } if (!templateFunction) { return ''; } return runtime(Benchpress.helpers, data, templateFunction); }); }
javascript
{ "resource": "" }
q4192
compileRender
train
function compileRender(templateSource, data, block) { const hash = md5(templateSource); return Promise.try(() => { const cached = compileRenderCache.get(hash); if (cached) { compileRenderCache.ttl(hash); return cached; } const templateFunction = precompile(templateSource, {}) .then(code => evaluate(code)); compileRenderCache.set(hash, templateFunction); return templateFunction; }).then((templateFunction) => { if (block) { templateFunction = templateFunction.blocks && templateFunction.blocks[block]; } if (!templateFunction) { return ''; } return runtime(Benchpress.helpers, data, templateFunction); }).catch((err) => { err.message = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.message}`; err.stack = `Render failed for template ${templateSource.slice(0, 20)}:\n ${err.stack}`; throw err; }); }
javascript
{ "resource": "" }
q4193
expressionPaths
train
function expressionPaths(basePath, expression) { const expr = Object.assign({}, expression); if (expr.tokenType === 'SimpleExpression') { if (expr.path === '@value') { expr.path = basePath; } else { expr.path = paths.resolve(basePath, expr.path); } } else if (expr.tokenType === 'HelperExpression') { expr.args = expr.args.map((arg) => { if (arg.tokenType === 'StringLiteral') { return arg; } return expressionPaths(basePath, arg); }); } return expr; }
javascript
{ "resource": "" }
q4194
__express
train
function __express(filepath, data, next) { data = Benchpress.addGlobals(data); data._locals = null; if (Benchpress.cache[filepath]) { render(filepath, data, Benchpress.cache[filepath], next); return; } fs.readFile(filepath, 'utf-8', (err, code) => { if (err) { next(err); return; } let template; try { template = Benchpress.cache[filepath] = evaluate(code); } catch (e) { e.message = `Evaluate failed for template ${filepath}:\n ${e.message}`; e.stack = `Evaluate failed for template ${filepath}:\n ${e.stack}`; process.nextTick(next, e); return; } render(filepath, data, template, next); }); }
javascript
{ "resource": "" }
q4195
resolve
train
function resolve(basePath, relPath) { // already relative, so easy work if (/^\.\.?\//.test(relPath)) { return relative(basePath, relPath); } // otherwise we have to figure out if this is something like // BEGIN a.b.c // `- {a.b.c.d} // or if it's an absolute path const base = basePath.split('.'); const rel = relPath.split('.'); // find largest possible match in the base path // decrease size of slice until a match is found let found = false; let relStart; let baseLen; for (let l = rel.length; l > 0 && !found; l -= 1) { // slide through array from end to start until a match is found for (let j = base.length - l; j >= 0 && !found; j -= 1) { // check every element from (j) to (j + l) for equality // if not equal, break right away for (let i = 0; i < l; i += 1) { if (base[j + i].replace(/\[\d+]$/, '') === rel[i]) { found = true; if (i === l - 1) { relStart = l; baseLen = j + l; } } else { found = false; break; } } } } if (found) { return base.slice(0, baseLen).concat(rel.slice(relStart)).join('.'); } // assume its an absolute path return relPath; }
javascript
{ "resource": "" }
q4196
guard
train
function guard(value) { return value == null || (Array.isArray(value) && value.length === 0) ? '' : value; }
javascript
{ "resource": "" }
q4197
iter
train
function iter(obj, each) { if (!obj || typeof obj !== 'object') { return ''; } let output = ''; const keys = Object.keys(obj); const length = keys.length; for (let i = 0; i < length; i += 1) { const key = keys[i]; output += each(key, i, length, obj[key]); } return output; }
javascript
{ "resource": "" }
q4198
helper
train
function helper(context, helpers, helperName, args) { if (typeof helpers[helperName] !== 'function') { return ''; } try { const out = helpers[helperName].apply(context, args); return out || ''; } catch (e) { return ''; } }
javascript
{ "resource": "" }
q4199
runtime
train
function runtime(helpers, context, templateFunction) { return guard(templateFunction(helpers, context, guard, iter, helper)).toString(); }
javascript
{ "resource": "" }