_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41500
logger
train
function logger(options) { DEBUG && debug('configure http logger middleware', options); var format; if (typeof options === 'string') { format = options; options = {}; } else { format = options.format || 'combined'; delete options.format; } if (options.debug) { try { return require('morgan-debug')(options.debug, format, options); } catch (e) { console.error('**fatal** failed to configure logger with debug', e); return process.exit(2); } } if (options.file) { try { var file = path.resolve(process.cwd(), options.file); // replace stream options with stream object delete options.file; options.stream = require('fs').createWriteStream(file, {flags: 'a'}); } catch (e) { console.error('**fatal** failed to configure logger with file stream', e); return process.exit(2); } } console.warn('**fallback** use default logger middleware'); return require('morgan')(format, options); }
javascript
{ "resource": "" }
q41501
handlePeopleRetrieved
train
function handlePeopleRetrieved(state, action) { if (action.error) { return { ...state, people: null, error: getErrorDescription(action.payload) }; } return { ...state, people: action.payload, error: null }; }
javascript
{ "resource": "" }
q41502
train
function(element, options) { var event; options = options || {}; options.canBubble = ('false' === options.canBubble ? false : true); options.cancelable = ('false' === options.cancelable ? false : true); options.view = options.view || window; try { event = new Event(options.type, { bubbles: options.canBubble, cancelable: options.cancelable, view: options.view, relatedTarget: options.relatedTarget }); return element.dispatchEvent(event); } catch(e) { try { event = document.createEvent("Event"); event.initEvent(options.type, options.canBubble, options.cancelable); this.setEventProperty(event, 'relatedTarget', options.relatedTarget); return element.dispatchEvent(event); } catch(e) { // old IE fallback event = document.createEventObject(); event.eventType = options.type; event.relatedTarget = options.relatedTarget; return element.fireEvent('on'+options.type, event) } } }
javascript
{ "resource": "" }
q41503
bind
train
function bind(method, path, controller, action) { let handler = controllerRegistry[controller] && controllerRegistry[controller][action] if (!handler) { console.warn(`can't bind route ${ path } to unknown action ${ controller }.${ action }`) return } const policyName = LocalUtil.getPolicyName(policy, controller, action) let currentPolicy if (policyName) currentPolicy = policyRegistry[policyName] if (currentPolicy) { router[method](path, currentPolicy, handler) } else { router[method](path, handler) } }
javascript
{ "resource": "" }
q41504
verify
train
function verify(pattern, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } if (typeof callback !== 'function') { errs.type('expect `callback` to be function'); } if (typeof pattern !== 'string') { errs.type('expect `pattern` to be string'); } if (!regex.test(pattern)) { errs.error('expect `pattern` to be `user/repo#branch`'); } if (!isObject(opts)) { errs.type('expect `opts` to be object'); } opts = typeof opts.token === 'string' ? { headers: { Authorization: 'token ' + opts.token } } : undefined; memo(regex.exec(pattern)); if (!cache.branch) { errs.error('should give a branch or tag in `pattern`'); } return { opts: opts, callback: callback } }
javascript
{ "resource": "" }
q41505
updateCurrentInput
train
function updateCurrentInput(input) { if (input !== currentInput) { body.classList.remove(`current-input-${currentInput}`); body.classList.add(`current-input-${input}`); currentInput = input; } }
javascript
{ "resource": "" }
q41506
ArrayindexOf
train
function ArrayindexOf(thing) { var index = 0; var count = this.length; while (index < count) { if (this[index] === thing) return index index = index + 1 } return -1 }
javascript
{ "resource": "" }
q41507
int64
train
function int64(name) { return joi.alternatives().meta({ cql: true, type: name }).try( // a string that represents a number that is larger than JavaScript can handle joi.string().regex(/^\-?\d{1,19}$/m), // any integer that can be represented in JavaScript joi.number().integer() ); }
javascript
{ "resource": "" }
q41508
decimal
train
function decimal(name) { return joi.alternatives().meta({ cql: true, type: name }).try( // a string that represents a number that is larger than JavaScript can handle joi.string().regex(/^\-?\d+(\.\d+)?$/m), // any number that can be represented in JavaScript joi.number() ); }
javascript
{ "resource": "" }
q41509
train
function (keyType, valueType) { var meta = findMeta(valueType); return joi.object().meta({ cql: true, type: 'map', mapType: ['text', meta.type], serialize: convertMap(meta.serialize), deserialize: convertMap(meta.deserialize) }).pattern(/[\-\w]+/, valueType); }
javascript
{ "resource": "" }
q41510
train
function (type) { var meta = findMeta(type); var set = joi.array().sparse(false).unique().items(type); return joi.alternatives().meta({ cql: true, type: 'set', setType: meta.type, serialize: convertArray(meta.serialize), deserialize: convertArray(meta.deserialize) }).try(set, joi.object().keys({ add: set, remove: set }).or('add', 'remove').unknown(false)); }
javascript
{ "resource": "" }
q41511
train
function (type) { var meta = findMeta(type); var list = joi.array().sparse(false).items(type); return joi.alternatives().meta({ cql: true, type: 'list', listType: meta.type, serialize: convertArray(meta.serialize), deserialize: convertArray(meta.deserialize) }).try(list, joi.object().keys({ prepend: list, append: list, remove: list, index: joi.object().pattern(/^\d+$/, type) }).or('prepend', 'append', 'remove', 'index').unknown(false)); }
javascript
{ "resource": "" }
q41512
train
function (validator, options) { var when = options.default; var fn = function (context, config) { if ((when === config.context.operation) || (when === 'update' && ['create', 'update'].indexOf(config.context.operation) > -1) ) { return new Date().toISOString(); } return undef; }; fn.isJoi = true; return validator.default(fn); }
javascript
{ "resource": "" }
q41513
train
function (validator, options) { var fn = function (context, config) { if (config.context.operation === 'create') return options.default === 'empty' ? '00000000-0000-0000-0000-000000000000' : uuid[options.default](); return undef; }; fn.isJoi = true; return validator.default(fn); }
javascript
{ "resource": "" }
q41514
defaultify
train
function defaultify(type, validator, options) { return options && options.default ? defaults[type](validator, options) : validator; }
javascript
{ "resource": "" }
q41515
findMeta
train
function findMeta(any, key) { key = key || 'cql'; var meta = (any.describe().meta || []).filter(function (m) { return key in m; }); return meta[meta.length - 1]; }
javascript
{ "resource": "" }
q41516
convertToJsonOnValidate
train
function convertToJsonOnValidate(any) { var validate = any._validate; any._validate = function () { var result = validate.apply(this, arguments); if (!result.error && result.value) { result.value = JSON.stringify(result.value); } return result; }; return any; }
javascript
{ "resource": "" }
q41517
defaultUuid
train
function defaultUuid(options, version) { if (options && options.default) { if ([version, 'empty'].indexOf(options.default) > -1) { return options.default; } return version; } return undef; }
javascript
{ "resource": "" }
q41518
handleAdminEvents
train
function handleAdminEvents() { //listen for clicks that bubble in up in the admin bar document.body.addEventListener('click', function (ev) { if(ev.target.hasAttribute('data-edit-include')) { launchPluginEditor(ev.target); } else if(ev.target.hasAttribute('data-add-include')) { launchAddInclude(ev.target); } }); //intercept link clicks so the parent frame changes window.pagespace.interceptLinks = function(ev) { if(ev.target.tagName.toUpperCase() === 'A' && ev.target.getAttribute('href').indexOf('/') === 0) { var href = ev.target.getAttribute('href'); window.parent.location.assign('/_dashboard#/view-page/preview' + href); ev.preventDefault(); } }; document.body.addEventListener('click', window.pagespace.interceptLinks); }
javascript
{ "resource": "" }
q41519
getIncludeDragData
train
function getIncludeDragData(ev) { var data = ev.dataTransfer.getData('include-info'); return data ? JSON.parse(data) : null; }
javascript
{ "resource": "" }
q41520
train
function(callback) { helpers.walk(buildInfo.srcApps, function(err, results) { if (err) return callback("Error walking files."); callback(null, results); }); }
javascript
{ "resource": "" }
q41521
train
function(callback) { helpers.walk(buildInfo.srcVendors, function(err, results) { if (err) return callback("Error walking files."); callback(null, results); }); }
javascript
{ "resource": "" }
q41522
getUniqueRandomNumberAsync
train
function getUniqueRandomNumberAsync(callback) { if (cb.check(callback)) { return; } setTimeout(() => { debugger cb.done(Math.random()); }, 1000); }
javascript
{ "resource": "" }
q41523
initServiceModel
train
function initServiceModel(connectionUrl) { log.logger.debug("initServiceModel ", {connectionUrl: connectionUrl}); if (!connectionUrl) { log.logger.error("No Connection Url Specified"); return null; } //If the connection has not already been created, create it and initialise the Service Schema For That Domain if (!domainMongooseConnections[connectionUrl]) { log.logger.debug("No Connection Exists for " + connectionUrl + ", creating a new one"); domainMongooseConnections[connectionUrl] = mongoose.createConnection(connectionUrl); domainMongooseConnections[connectionUrl].model(SERVICE_MODEL, ServiceSchema); //Setting Up Event Listeners domainMongooseConnections[connectionUrl].on('connecting', function(msg){ log.logger.debug("Mongoose Connecting", {msg: msg, connectionUrl: connectionUrl}); }); domainMongooseConnections[connectionUrl].on('error', function(msg){ log.logger.error("Mongoose Connection Error", {msg: msg, connectionUrl: connectionUrl}); }); domainMongooseConnections[connectionUrl].on('connected', function(msg){ log.logger.debug("Mongoose Connected", {msg: msg, connectionUrl: connectionUrl}); }); } else { log.logger.debug("Connection Already Exists."); } return domainMongooseConnections[connectionUrl]; }
javascript
{ "resource": "" }
q41524
create
train
function create( arr ) { var f = ''; f += 'return function fill( len ) {'; f += 'var arr = new Array( len );'; f += 'for ( var i = 0; i < len; i++ ) {'; f += 'arr[ i ] = ' + serialize( arr ) + ';'; f += '}'; f += 'return arr;'; f += '}'; return ( new Function( f ) )(); }
javascript
{ "resource": "" }
q41525
hash
train
function hash() { var ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [Math.floor(Math.random() * 100)]; var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36; if (!ids.splice) { throw new TypeError('The ids argument should be an array of numbers'); } if (typeof n !== 'number' || n < 0) { throw new TypeError('The number of salts should be a positive integer'); } if (typeof base !== 'number' || base < 16 || base > 36) { throw new TypeError('The base should be a number between 16 and 36'); } // Create the salts. This will be the same for all hashes var salts = _createSalts(n, base); // Combine the salts and the actual var hashes = ids.map(function (id) { if (typeof id !== 'number') { throw new TypeError('The ids you\'re hashing should only be numbers'); } return _createHash(id, salts, base); }); return { ids: ids, hashes: hashes, salts: salts, base: base }; }
javascript
{ "resource": "" }
q41526
bunch
train
function bunch() { var num = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36; if (typeof num !== 'number') { throw new TypeError('The num should be a number'); } if (typeof n !== 'number' || n < 0) { throw new TypeError('The number of salts should be a positive integer'); } if (typeof base !== 'number' || base < 16 || base > 36) { throw new TypeError('The base should be a number between 16 and 36'); } // Create the ids var ids = []; for (var i = 0; i < num; i++) { ids.push(Math.floor(Math.random() * Math.pow(10, num.toString(10).length + 2))); } // Create the salts. This will be the same for all hashes var salts = _createSalts(n, base); // Combine the salts and the actual var hashes = ids.map(function (id) { return _createHash(id, salts, base); }); return { ids: ids, hashes: hashes, salts: salts, base: base }; }
javascript
{ "resource": "" }
q41527
request
train
function request(path, json) { return new Promise(function (resolve, reject) { oauth._performSecureRequest(config.telldusToken, config.telldusTokenSecret, 'GET', 'https://api.telldus.com/json' + path, null, json, !!json ? 'application/json' : null, function (err, body, response) { _parseResponse(err, body, response, resolve, reject); }); }); }
javascript
{ "resource": "" }
q41528
clearAjax
train
function clearAjax() { each(function(request) { try { request.onload = noop; request.onerror = noop; request.onabort = noop; request.onreadystatechange = noop; each(function(added) { request[added[0]].apply(request, added[1]); }, request._queue || []); request.abort(); } catch (e) { // Ignore error } }, requests); requests.length = []; }
javascript
{ "resource": "" }
q41529
getMoment
train
function getMoment(modelValue) { return moment(modelValue, angular.isString(modelValue) ? configuration.parseFormat : undefined) }
javascript
{ "resource": "" }
q41530
debounce
train
function debounce(callback) { let timeout = null; return () => { if (timeout !== null) { return; } timeout = setTimeout(() => { timeout = null; callback(); }, 0); } }
javascript
{ "resource": "" }
q41531
add
train
function add(keyId, sshKey, callback) { try { sshKeyparser(sshKey); }catch (e) { return callback(e); } commons.post(format('/%s/keys/', deis.version), { id: keyId || deis.username, 'public': sshKey },callback); }
javascript
{ "resource": "" }
q41532
remove
train
function remove(keyId, callback) { commons.del(format('/%s/keys/%s', deis.version, keyId), callback); }
javascript
{ "resource": "" }
q41533
exposeAPI
train
function exposeAPI(log){ return { emerg: log(_loglevel.EMERGENCY), emergency: log(_loglevel.EMERGENCY), alert: log(_loglevel.ALERT), crit: log(_loglevel.CRITICAL), critical: log(_loglevel.CRITICAL), error: log(_loglevel.ERROR), err: log(_loglevel.ERROR), warning: log(_loglevel.WARNING), warn: log(_loglevel.WARNING), notice: log(_loglevel.NOTICE), log: log(_loglevel.INFO), info: log(_loglevel.INFO), debug: log(_loglevel.DEBUG) }; }
javascript
{ "resource": "" }
q41534
createLogger
train
function createLogger(instance){ // generator function log(level){ return function(...args){ // logging backend available ? if (_loggingBackends.length > 0){ // trigger backends _loggingBackends.forEach(function(backend){ backend.apply(backend, [instance, level, args]); }); // use default backend }else{ _defaultBackend.apply(_defaultBackend, [instance, level, args]); } } } return exposeAPI(log); }
javascript
{ "resource": "" }
q41535
getLogger
train
function getLogger(instance){ // create new instance if not available if (!_loggerInstances[instance]){ _loggerInstances[instance] = createLogger(instance); } return _loggerInstances[instance]; }
javascript
{ "resource": "" }
q41536
addLoggingBackend
train
function addLoggingBackend(backend, minLoglevel=99){ // function or string input supported if (typeof backend === 'function'){ _loggingBackends.push(backend); // lookup }else{ if (backend === 'fancy-cli'){ _loggingBackends.push(_fancyCliLogger(minLoglevel)); }else if (backend === 'cli'){ _loggingBackends.push(_simpleCliLogger(minLoglevel)); }else{ throw new Error('Unknown backend <' + backend + '>'); } } }
javascript
{ "resource": "" }
q41537
StanzaFetcher
train
function StanzaFetcher(db, getInterchangeSession) { var self = this; self.db = db; self._closed = false; self.getInterchangeSession = getInterchangeSession; self._highWaterMarks = new Chain(self._fetchMostRecentStanzaSeq.bind(self)); events.EventEmitter.call(this); }
javascript
{ "resource": "" }
q41538
render
train
function render (vnode, parent, context) { // render var i = 0 var rendered = rawRender(vnode) // mount if (typeof parent === 'function') { var nodes = rendered.nodes.length < 2 ? rendered.nodes[0] : rendered.nodes parent(nodes) } else if (parent) { for (i = 0; i < rendered.nodes.length; i++) { parent.appendChild(rendered.nodes[i]) } } // dispatch callback refs and didmounts var mockComponent = { _collector: rendered } // for dispatch convenience dispatchRefs(mockComponent) dispatch(mockComponent, function (c) { c.mounted = true c.componentDidMount && c.componentDidMount(c.props) }) // Add items to context if (context && context._collector) { var c = context._collector for (i = 0; i < rendered.components.length; i++) { rendered.components[i]._parent = context } if (c.refs) c.refs = c.refs.concat(rendered.refs) if (c.components) c.components = c.components.concat(rendered.components) } mockComponent = undefined return rendered }
javascript
{ "resource": "" }
q41539
HttpError
train
function HttpError(message, status, cause) { this.status = status || StatusCode.UNKNOWN; HttpError.super_.call(this, errors.ErrorCode.HTTP + this.status, message || StatusLine[this.status] || StatusLine[StatusCode.UNKNOWN], cause); }
javascript
{ "resource": "" }
q41540
train
function(path, callbackSuccess, callbackError) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { callbackSuccess(xhr.responseText); } else { callbackError(); } } }; xhr.open('GET', path, false); try { xhr.send(); } catch (e) { callbackError(); } }
javascript
{ "resource": "" }
q41541
initPool
train
function initPool(name, config){ // new pool const pool = _mysql.createPool(config); // create pool wrapper _pools[name || '_default'] = { _instance: pool, getConnection: function(scope){ return _poolConnection.getConnection(pool, scope); } } }
javascript
{ "resource": "" }
q41542
merge
train
function merge(target) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } for (var arg, len = args.length, index = 0; arg = args[index], index < len; index += 1) { for (var all in arg) { if (typeof HTMLElement !== 'undefined' && arg instanceof HTMLElement || typeof propDetails(arg, all).value !== 'undefined' && (!target[all] || propDetails(target, all).writable)) { if (all !== 'attributes') target[all] = arg[all]; } } } return target; }
javascript
{ "resource": "" }
q41543
getInnerHTML
train
function getInnerHTML(node) { if (!node.children) return ''; if (!isArray(node.children) && typeof HTMLCollection !== 'undefined' && !(node.children instanceof HTMLCollection)) node.children = [node.children]; return (isArray(node) && node || (typeof HTMLCollection !== 'undefined' && node.children instanceof HTMLCollection ? [].slice.call(node.children) : node.children)).map(function (child) { if ((typeof child === 'undefined' ? 'undefined' : _typeof(child)) !== 'object') { return '' + child; } else if (isArray(child)) { return getInnerHTML(child); } else { var attributes = [''].concat(Object.keys(child.attributes).map(function (attr) { return attr + '="' + child.attributes[attr].value + '"'; })); if (['img', 'link', 'meta', 'input', 'br', 'area', 'base', 'param', 'source', 'hr', 'embed'].indexOf(child.tagName) < 0) { return '<' + child.tagName + attributes.join(' ') + '>' + getInnerHTML(child) + '</' + child.tagName + '>'; } else { return '<' + child.tagName + attributes.join(' ') + '/>'; } } }).join(''); }
javascript
{ "resource": "" }
q41544
createElement
train
function createElement(node, document) { var tag = void 0; if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') { // we have a text node, so create one tag = document.createTextNode('' + node); } else { tag = document.createElement(node.tagName); // add all required attributes Object.keys(node.attributes).forEach(function (attr) { tag.setAttribute(attr, node.attributes[attr].value); }); // define it's inner structure tag.innerHTML = getInnerHTML(node); tag.__hash = node.__hash; attachSetAttribute(tag); } return tag; }
javascript
{ "resource": "" }
q41545
train
function(opts) { EventEmitter.call(this); opts = opts || {}; this.maxLength = opts.maxLength || DEFAULT_MAX_LENGTH; this.offset = 0; this.left = 0; this.length = 0; this.buf = null; this.state = ST_LENGTH; }
javascript
{ "resource": "" }
q41546
send
train
function send(socket, host, port, loggingObject) { var buffer = new Buffer(JSON.stringify(loggingObject)); socket.send(buffer, 0, buffer.length, port, host, function(err, bytes) { if (err) { console.error('log4js-logstash-appender (%s:%p) - %s', host, port, util.inspect(err)); } }); }
javascript
{ "resource": "" }
q41547
appender
train
function appender(configuration) { var socket = dgram.createSocket('udp4'); return function(loggingEvent) { var loggingObject = { name: loggingEvent.categoryName, message: layout(loggingEvent), severity: loggingEvent.level.level, severityText: loggingEvent.level.levelStr, }; if (configuration.application) { loggingObject.application = configuration.application; } if (configuration.environment) { loggingObject.environment = configuration.environment; } if (MDC && MDC.active) { Object.keys(MDC.active).forEach(function(key) { loggingObject[key] = MDC.active[key]; }); } send(socket, configuration.host, configuration.port, loggingObject); }; }
javascript
{ "resource": "" }
q41548
inarray
train
function inarray (list, item) { list = Object.prototype.toString.call(list) === '[object Array]' ? list : [] var idx = -1 var end = list.length while (++idx < end) { if (list[idx] === item) return true } return false }
javascript
{ "resource": "" }
q41549
getIncludes
train
function getIncludes(file) { var content = String(file.contents); var matches = []; while (regexMatch = DIRECTIVE_REGEX.exec(content)) { matches.push(regexMatch); } // For every require fetch it's matching files var fileLists = _.map(matches, function(match) { return globMatch(match, file).sort(); }); // Merge all matching file lists into one concat list var order = _.reduce(fileLists, function(memo, fileList) { return _.union(memo, fileList); }, []); // And self to include list order.push(file.relative); return order; }
javascript
{ "resource": "" }
q41550
globMatch
train
function globMatch(match, file) { var directiveType = match[1]; var globPattern = match[2]; // relative file // require all files under a directory if (directiveType.indexOf('_tree') !== -1) { globPattern = globPattern.concat('/**/*'); directiveType = directiveType.replace('_tree', ''); } // require only first level files in a directory if (directiveType.indexOf('_directory') !== -1) { globPattern = globPattern.concat('/*'); directiveType = directiveType.replace('_directory', ''); } // Only require and include directives are allowed if (directiveType !== 'require' && directiveType !== 'include') { return []; } // Add file extension to glob pattern if not already set var jsExt = '.js'; if (globPattern.substr(globPattern.length-jsExt.length).indexOf(jsExt) !== 0) { globPattern += jsExt; } // Append the current dir to include so we can match the glob against the file list var relativeDir = getRelativeDir(file); globPattern = relativeDir+globPattern; var possibleIncludes = []; _.each(_.keys(allFiles), function(fileName) { // Only process files in the current directory. ../ will not work. if (fileName.indexOf(relativeDir) !== 0) { return; } possibleIncludes.push(fileName); }); return minimatch.match(possibleIncludes, globPattern); }
javascript
{ "resource": "" }
q41551
_inputInterfaces
train
function _inputInterfaces (interfaces, msg, type, options, i = 0) { return i >= interfaces.length ? Promise.resolve() : Promise.resolve().then(() => { let result = null; switch (type) { case "log": result = interfaces[i].log(msg, options); break; case "success": result = interfaces[i].success(msg, options); break; case "information": result = interfaces[i].information(msg, options); break; case "warning": result = interfaces[i].warning(msg, options); break; case "error": result = interfaces[i].error(msg, options); break; default: // nothing to do here break; } return null === result ? Promise.resolve() : Promise.resolve().then(() => { if ("boolean" === typeof result) { return result ? Promise.resolve() : Promise.reject( new Error("Impossible to log \"" + msg + "\" message with \"" + type + "\" type on all the interfaces") ); } else { return "object" === typeof result && result instanceof Promise ? result : Promise.resolve(); } }).then(() => { return _inputInterfaces(interfaces, msg, type, options, i + 1); }); }); }
javascript
{ "resource": "" }
q41552
auth
train
function auth(endo, options) { options || (options = {}); // // add token utility methods, binding first options arg // endo.createToken = auth.createToken.bind(null, options.sign); endo.verifyToken = auth.verifyToken.bind(null, options.verify); // // verify provided credentials are valid and set user auth on request // var _parseRequest = endo.parseRequest; endo.parseRequest = function() { var request = _parseRequest.apply(this, arguments); return Promise.resolve(request).then(this.authenticate.bind(this)); }; endo.authenticate = function (request) { // // no auth if request already contains user auth data // if (request.user !== undefined) { return; } // // parse authorization header for JWT token // request.headers || (request.headers || {}); var header = request.headers && request.headers.authorization || ''; var match = header.match(BEARER_RE); if (!match) { throw new util.UnauthorizedError('Token required'); } return auth.verifyToken(match[1]) .then(endo.handleAuthentication.bind(endo, request)) }; // // implementations may wrap this method perform additional verification // endo.handleAuthentication = function (request, data) { request.user = data || null; }; return endo; }
javascript
{ "resource": "" }
q41553
hslToRgb
train
function hslToRgb(h, s, l) { h /= 360; s /= 100; l /= 100; var r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return ({ r: r * 255, g: g * 255, b: b * 255 }); }
javascript
{ "resource": "" }
q41554
isCombinableSplit
train
function isCombinableSplit(tokenized) { if (tokenized.tokens.length <= 1) { return false; } for (var i = 1; i < tokenized.tokens.length; ++i) { if (!tokenized.fusable[i]) { return false; } } return true; }
javascript
{ "resource": "" }
q41555
toCssModule
train
function toCssModule(styles) { var done = false; var res; new modules().load(styles, prefix + uni()).then(function(next) { done = true; res = next; }); deasync.loopWhile(function() { return !done; }); return res; }
javascript
{ "resource": "" }
q41556
SDFSplitter
train
function SDFSplitter(handler) { parser.SDFTransform.call(this); this.on('data', function (chunk) { handler(String(chunk)); }); }
javascript
{ "resource": "" }
q41557
PygmentizeOptions
train
function PygmentizeOptions (options) { if(!(this instanceof PygmentizeOptions)) return new PygmentizeOptions(options); if(options.lexer && validate.lexer.test(options.lexer)) this.lexer = options.lexer; if(options.guess && !this.lexer) this.guess = true; if(options.formatter && validate.formatter.test(options.formatter)) this.formatter = options.formatter; else this.formatter = 'html' }
javascript
{ "resource": "" }
q41558
train
function(app, opts) { this.app = app; this.handlerMap = {}; if(!!opts.reloadHandlers) { watchHandlers(app, this.handlerMap); } this.enableForwardLog = opts.enableForwardLog || false; }
javascript
{ "resource": "" }
q41559
train
function(app, serverType, handlerMap) { let p = pathUtil.getHandlerPath(app.getBase(), serverType); if(p) { handlerMap[serverType] = Loader.load(p, app); } }
javascript
{ "resource": "" }
q41560
train
function() { if (!this.hasOwnProperty("_postalSubscriptions")) { this._postalSubscriptions = {}; } for (var topic in this.subscriptions) { if (this.subscriptions.hasOwnProperty(topic)) { var callback = this.subscriptions[topic]; this.subscribe(topic, callback); } } }
javascript
{ "resource": "" }
q41561
fromShape
train
function fromShape(obj, propType, options=null) { const declaration = propType[SHAPE]; if (!(declaration instanceof Declaration)) { throw new Error('fromShape called with a non-shape property type'); } const shape = declaration.shape; const instance = {}; const checker = {}; Object.keys(shape).forEach(key => { const type = shape[key]; if (type[SHAPE] instanceof Reshape) { // Add the reshape function to the resulting instance. addReshape(instance, key); return; } let value = obj[key]; if (value === undefined) { // The object does not have the declared shape. // An error will be returned by PropTypes.shape. return; } if (type[SHAPE] instanceof Declaration) { // This is a nested shape type. instance[key] = fromShape(value, type); return; } if (checker.toString.call(value) === '[object Function]') { // This can be an unbound method: try to bind it. value = value.bind(obj); } instance[key] = value; }); options = options || {}; if (options.mutable) { return instance; } return deepFreeze(instance); }
javascript
{ "resource": "" }
q41562
isRequiredWrapper
train
function isRequiredWrapper(propType) { const isRequired = (props, propName, componentName, ...rest) => { if (!props[propName]) { return new Error( `the property "${propName}" is marked as required for the component ` + `"${componentName}" but "${props[propName]}" has been provided` ); } return propType(props, propName, componentName, ...rest); }; isRequired[SHAPE] = propType[SHAPE]; return isRequired; }
javascript
{ "resource": "" }
q41563
frozenWrapper
train
function frozenWrapper(propType) { const checkFrozen = (obj, propName, componentName) => { if (!Object.isFrozen(obj)) { throw new Error( `the property "${propName}" provided to component ` + `"${componentName}" is not frozen` ); } forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if (prop !== null && (type === 'object' || type === 'function')) { checkFrozen(prop, `${propName}.${name}`, componentName); } }); }; const frozen = (props, propName, componentName, ...rest) => { const propValue = props[propName]; if (!propValue) { return null; } try { checkFrozen(propValue, propName, componentName); } catch (err) { return err; } return propType(props, propName, componentName, ...rest); }; frozen[SHAPE] = propType[SHAPE]; return frozen; }
javascript
{ "resource": "" }
q41564
deepFreeze
train
function deepFreeze(obj) { Object.freeze(obj); forEachKeyValue(obj, (name, prop) => { const type = typeof obj; if ( prop !== null && (type === 'object' || type === 'function') && !Object.isFrozen(prop) ) { deepFreeze(prop); } }); return obj; }
javascript
{ "resource": "" }
q41565
train
function (level) { var lowerCaseLevel = level.toLowerCase(); if (_.contains(LEVELS, lowerCaseLevel)) { return lowerCaseLevel; } else { return LEVEL_OFF; } }
javascript
{ "resource": "" }
q41566
HouseCode
train
function HouseCode(houseCode) { this.raw = null; switch (typeof houseCode) { case "string": if (houseCode !== "" && houseCode.length === 1) { var index = houseCode.charCodeAt(0) - 65; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("House code string out of range."); } } else { throw new Error("Invalid house code."); } break; default: if (deviceCodes.indexOf(houseCode) !== -1) { this.raw = houseCode; } else { throw new Error("House code number out of range."); } break; } return this.raw; }
javascript
{ "resource": "" }
q41567
UnitCode
train
function UnitCode(unitCode) { switch (typeof unitCode) { case "string": unitCode = parseInt(unitCode, 10); if (unitCode || unitCode === 0) { var index = unitCode - 1; if ((index >= 0) && (index <= (deviceCodes.length - 1))) { this.raw = deviceCodes[index]; } else { throw new Error("Unit code string out of range."); } } else { throw new Error("Invalid unit code."); } break; default: if (deviceCodes.indexOf(unitCode) !== -1) { this.raw = unitCode; } else { throw new Error("Unit code number out of range."); } break; } return this.raw; }
javascript
{ "resource": "" }
q41568
Address
train
function Address(address) { this.houseCode = null; this.unitCode = null; try { switch (typeof address) { case "object": if (_.isArray(address) && address.length === 2) { this.houseCode = new HouseCode(address[0]); this.unitCode = new UnitCode(address[1]); } else { if (address.houseCode !== undefined && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.unitCode !== undefined && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } break; case "string": try { address = JSON.parse(address); if (address.hasOwnProperty("houseCode") && address.houseCode !== null) { this.houseCode = new HouseCode(address.houseCode); } if (address.hasOwnProperty("unitCode") && address.unitCode !== null) { this.unitCode = new UnitCode(address.unitCode); } } catch (e) { this.houseCode = new HouseCode((address.toUpperCase().match(/[A-P]+/)||[null])[0]); this.unitCode = new UnitCode((address.match(/\d+/)||[null])[0]); } break; case "number": this.houseCode = new HouseCode(address>>>4); this.unitCode = new UnitCode(address&0x0F); break; default: throw new Error("Invalid address."); break; } } catch (e) { throw new Error('Address out of range.'); } }
javascript
{ "resource": "" }
q41569
normalize
train
function normalize(recordTypes, recordTypeName, record, lang, validationSets) { // check that we have the record if ((record === null) || ((typeof record) !== 'object')) throw new common.X2UsageError('Record object was not provided.'); // get the record type descriptor (or throw error if invalid record type) const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // extract validation sets var sets = new Set( (validationSets ? validationSets.trim() + ',*' : '*').split(/\s*,\s*/)); // create validation context const ctx = new ValidationContext( recordTypes, recordTypeDesc, new MessageResolver(lang || '*'), sets); // run recursive validation/normalization of the record properties normalizeChildren(ctx, recordTypeDesc, null, record, sets); // validate/normalize the record as a whole const recordValidators = getValidators(recordTypeDesc, false, sets); if (recordValidators) for (let validator of recordValidators) validator(ctx, record); // return the result return ctx.getResult(); }
javascript
{ "resource": "" }
q41570
getValidators
train
function getValidators(subjDesc, element, validationSets) { const validators = subjDesc.validators; if (!validators) return null; const allValidators = new Array(); for (let set in validators) { if (element && !set.startsWith('element:')) continue; if (validationSets.has(element ? set.substring('element:'.length) : set)) for (let validator of validators[set]) allValidators.push(validator); } return (allValidators.length > 0 ? allValidators : null); }
javascript
{ "resource": "" }
q41571
list
train
function list(appName, callback) { commons.get(format('/%s/apps/%s/perms/', deis.version, appName), callback); }
javascript
{ "resource": "" }
q41572
UI
train
function UI (input, output) { this.rl = readline.createInterface({ input: input || ttys.stdin, output: output || ttys.stdout }) // Delegated events bind. this.onLine = (function onLine () { _events.line.apply(this, arguments) }).bind(this) this.onKeypress = (function onKeypress () { if (this.rl) { _events.keypress.apply(this, arguments) } }).bind(this) this.forceClose = this.forceClose.bind(this) this.rl.addListener('line', this.onLine) this.rl.input.addListener('keypress', this.onKeypress) this.rl.on('SIGINT', this.forceClose) process.on('exit', this.forceClose) }
javascript
{ "resource": "" }
q41573
lazyLoad
train
function lazyLoad(imgs, options) { var setting = { effect: 'fadeIn', effect_speed: 10, placeholder: 'data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==' }, $imgs; if (typeof imgs === 'undefined') { $imgs = $('img.lazy'); } else { $imgs = imgs; } if (typeof options !== 'undefined') { $.extend(setting, options); } $imgs.lazyload(setting); }
javascript
{ "resource": "" }
q41574
list
train
function list(appName, callback) { var url = format('/%s/apps/%s/config/', deis.version, appName); commons.get(url, function onListResponse(err, result) { callback(err, result ? result.tags : null); }); }
javascript
{ "resource": "" }
q41575
set
train
function set(appName, tagValues, callback) { if (!isObject(tagValues)) { return callback(new Error('To set a variable pass an object')); } commons.post(format('/%s/apps/%s/config/', deis.version, appName), { tags: tagValues },function onSetResponse(err, result) { callback(err, result ? result.tags : null); }); }
javascript
{ "resource": "" }
q41576
unset
train
function unset(appName, tagNames, callback) { if (!util.isArray(tagNames)) { return callback(new Error('To unset a tag pass an array of names')); } var keyValues = {}; tagNames.forEach(function eachTag(tagName) { keyValues[tagName] = null; }); set(appName, keyValues, callback); }
javascript
{ "resource": "" }
q41577
getLevel
train
function getLevel(base, index) { var level = (0, _bigInteger2.default)('0'); var current = index; var parent = void 0; while (current.gt(zero)) { parent = current.prev().divide(base); level = level.next(); current = parent; } return level; }
javascript
{ "resource": "" }
q41578
SpotSpec
train
function SpotSpec (options) { if (this.constructor.name === 'Object') { throw new Error('Object must be instantiated using new') } let self = this let specOptions = Object.assign({}, options) // Have the superclass constuct as an EC2 service Service.call(this, SvcAws.EC2, specOptions) this.logger.info('Loading EC2 for: ' + specOptions.keys.region) this.once(Const.EVENT_INITIALIZED, function onComplete (err, data) { /** * Emitted as the response to constuct SpotSpec * @event SpotSpec#initialized * @param {?error} err - Only on error * @param {object} [initData] - Null on error */ Intern.emitAsync.call(self, Const.EVENT_INITIALIZED, err, data) }) }
javascript
{ "resource": "" }
q41579
train
function ( options ) { _.bindAll( this, "selectNext", "selectPrev", "onSelect", "render" ); this.collection = options.collection; this.listenTo( this.collection, "select:one", this.onSelect ); this.listenTo( this.collection, "remove", this.render ); this.render(); }
javascript
{ "resource": "" }
q41580
BufferStreamReader
train
function BufferStreamReader (data, options) { if (!(this instanceof BufferStreamReader)) { return new BufferStreamReader(data); } if (!options) { options = {}; } stream.Readable.call(this, options); this._data = null; this._chunkSize = options.chunkSize || -1; if (typeof data === 'string') { this._data = new Buffer(data, options.encoding || 'utf8'); } else if (Buffer.isBuffer(data)) { this._data = data; } }
javascript
{ "resource": "" }
q41581
RootContext
train
function RootContext(argv, profileFilenames, view) { var self = { commands: COMMANDS, // Overwritten when interactive profileFilenames: profileFilenames, interactive: false, argv: argv, view: view, config: null, nick: null, privkey: null, hubClient: null, voxClient: null, }; self.initWithConfig = function(config) { if (self.voxClient) { throw new Error('Already initialized!'); } self.config = config; self.nick = config.nick; self.voxClient = new VoxClient({ config: config, agentString: AGENT_STRING, }); return self.voxClient.connect(); } self.reinitWithConfig = function(config) { self.close(); return self.initWithConfig(config); } self.close = function() { if (self.voxClient) { self.voxClient.close(); self.voxClient = null; } } /** * Logs connection status events. */ self.listenForConnectionStatusEvents = function() { self.voxClient.on('connect', function(info) { self.view.log(colors.cyan.dim('Connected: ' + info.interchangeUrl)); }); self.voxClient.on('disconnect', function(info) { self.view.log(colors.red.dim('Disconnected: ' + info.interchangeUrl)); }); self.voxClient.on('error', function(info) { self.view.log(colors.red.dim('Connection error: ' + info.interchangeUrl)); }); self.voxClient.on('reconnect_failed', function(info) { self.view.log(colors.red.dim('Reconnection failed: ' + info.interchangeUrl)); }); } self.printJson = function(obj_or_name, obj) { if (obj !== undefined) { self.view.log('%s %s', obj_or_name, JSON.stringify(obj)); } else { self.view.log(JSON.stringify(obj_or_name)); } } return self; }
javascript
{ "resource": "" }
q41582
progress
train
function progress( _line ){ messages[ _line ].progress++; if( (messages[ _line ].progress + messages[ _line ].diff) > 0 ){ messages[ _line ].progress = 0; } }
javascript
{ "resource": "" }
q41583
anim
train
function anim( _line ){ var msg = messages[ _line ]; lcd.cursor( _line, 0 ); if( msg.progress === 0 ){ lcd.print( msg.msg ); progress( _line ); (function( _line ){ timeout = setTimeout(function(){ anim( _line ) }, anim_settings.firstCharPauseDuration ); })( _line ); }else{ lcd.print( msg.msg.substr( msg.progress ) ); progress( _line ); (function( _line ){ var time = anim_settings.scrollingDuration; if( messages[ _line ].progress === 0 ){ time = anim_settings.lastCharPauseDuration; } timeout = setTimeout( function(){ anim( _line ); }, time ); })( _line ); } }
javascript
{ "resource": "" }
q41584
Commit
train
function Commit(events, sequenceID, sequenceSlot, aggregateType, metadata){ if(!Array.isArray(events)){ throw new Error('events must be an array while constructing Commit'); } if(typeof(sequenceID) !== 'string'){ throw new Error('sequenceID is not a string while constructing Commit'); } if(!sequenceSlot){ throw new Error('sequenceSlot not a number, or zero, while constructing Commit'); } this.events = events; this.sequenceID = sequenceID; this.sequenceSlot = sequenceSlot; this.aggregateType = aggregateType; this.metadata = metadata ? metadata : {}; }
javascript
{ "resource": "" }
q41585
init
train
function init(ctx) { if (glEnums == null) { glEnums = { }; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'number') { glEnums[ctx[propertyName]] = propertyName; } } } }
javascript
{ "resource": "" }
q41586
glEnumToString
train
function glEnumToString(value) { checkInit(); var name = glEnums[value]; return (name !== undefined) ? name : ("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")"); }
javascript
{ "resource": "" }
q41587
glFunctionArgsToString
train
function glFunctionArgsToString(functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } return argStr; }
javascript
{ "resource": "" }
q41588
makeDebugContext
train
function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc) { init(ctx); opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + glFunctionArgToString(functionName, ii, args[ii]); } error("WebGL error "+ glEnumToString(err) + " in "+ functionName + "(" + argStr + ")"); }; // Holds booleans for each GL error so after we get the error ourselves // we can still return it to the client app. var glErrorShadow = { }; // Makes a function that calls a WebGL function and then calls getError. function makeErrorWrapper(ctx, functionName) { return function() { if (opt_onFunc) { opt_onFunc(functionName, arguments); } var result = ctx[functionName].apply(ctx, arguments); var err = ctx.getError(); if (err != 0) { glErrorShadow[err] = true; opt_onErrorFunc(err, functionName, arguments); } return result; }; } // Make a an object that has a copy of every property of the WebGL context // but wraps all functions. var wrapper = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'function') { wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); } else { makePropertyWrapper(wrapper, ctx, propertyName); } } // Override the getError function with one that returns our saved results. wrapper.getError = function() { for (var err in glErrorShadow) { if (glErrorShadow.hasOwnProperty(err)) { if (glErrorShadow[err]) { glErrorShadow[err] = false; return err; } } } return ctx.NO_ERROR; }; return wrapper; }
javascript
{ "resource": "" }
q41589
createServer
train
function createServer(serverName) { console.log("creating server", serverName) var server = servers[serverName] = net.createServer(handleConnection) ports.service(serverName, listen) function handleConnection(connection) { console.log("got incoming connection", connection) var stream = proxy.connect(serverName) , buffer = PauseStream().pause() , intermediate = through(stringer) connection.pipe(buffer) process.nextTick(pipe) function pipe() { buffer.pipe(intermediate) .pipe(stream).pipe(connection) buffer.resume() } } function listen(port, ready) { server.listen(port, ready) } }
javascript
{ "resource": "" }
q41590
modifyOutRules
train
function modifyOutRules(rules) { for (let i = 0; i < rules.length; ++i) { if (rules[i].test) { switch ('' + rules[i].test) { // Images case '/\\.(png|jpe?g|gif)$/': modifyOutRule(rules[i], 'images'); break; // Fonts case '/\\.(woff2?|ttf|eot|svg|otf)$/': modifyOutRule(rules[i], 'fonts'); break; default: } } } }
javascript
{ "resource": "" }
q41591
modifyOutRule
train
function modifyOutRule(rule, type) { rule.test = new RegExp( '\\.(' + Config.out[type].extensions.join('|') + ')$' ); }
javascript
{ "resource": "" }
q41592
loadModelNames
train
function loadModelNames(modelPath) { modelPath = modelPath || envModelPath; debuglog(() => `modelpath is ${modelPath} `); var mdls = FUtils.readFileAsJSON('./' + modelPath + '/models.json'); mdls.forEach(name => { if (name !== makeMongoCollectionName(name)) { throw new Error('bad modelname, must terminate with s and be lowercase'); } }); return mdls; }
javascript
{ "resource": "" }
q41593
makeMongooseModelName
train
function makeMongooseModelName(collectionName) { if (collectionName !== collectionName.toLowerCase()) { throw new Error('expect lowercase, was ' + collectionName); } if (collectionName.charAt(collectionName.length - 1) === 's') { return collectionName.substring(0, collectionName.length - 1); } throw new Error('expected name with trailing s'); }
javascript
{ "resource": "" }
q41594
makeMongoCollectionName
train
function makeMongoCollectionName(modelName) { if (modelName !== modelName.toLowerCase()) { throw new Error('expect lowercase, was ' + modelName); } if (modelName.charAt(modelName.length - 1) !== 's') { return modelName + 's'; } return modelName; }
javascript
{ "resource": "" }
q41595
token
train
function token(value) { if ( !arguments.length ) return cred.token; cred.token = (value && value.length > 0 ? value : undefined); return that; }
javascript
{ "resource": "" }
q41596
generateAuthorizationHeaderValue
train
function generateAuthorizationHeaderValue(signedHeaders, signKey, signingMsg) { var signature = CryptoJS.HmacSHA256(signingMsg, signKey); var authHeader = 'SNWS2 Credential=' +cred.token +',SignedHeaders=' +signedHeaders.join(';') +',Signature=' +CryptoJS.enc.Hex.stringify(signature); return authHeader; }
javascript
{ "resource": "" }
q41597
computeAuthorization
train
function computeAuthorization(url, method, data, contentType, date) { date = (date || new Date()); var uri = URI.parse(url); var canonQueryParams = canonicalQueryParameters(uri, data, contentType); var canonHeaders = canonicalHeaders(uri, contentType, date, bodyContentDigest); var bodyContentDigest = bodyContentSHA256(data, contentType); var canonRequestMsg = generateCanonicalRequestMessage({ method: method, uri: uri, queryParams : canonQueryParams, headers : canonHeaders, bodyDigest: bodyContentDigest }); var signingMsg = generateSigningMessage(date, canonRequestMsg); var signKey = signingKey(date); var authHeader = generateAuthorizationHeaderValue(canonHeaders.headerNames, signKey, signingMsg); return { header: authHeader, date: date, dateHeader: canonHeaders.headers['x-sn-date'], verb: method, canonicalUri: uri.path, canonicalQueryParameters: canonQueryParams, canonicalHeaders: canonHeaders, bodyContentDigest: bodyContentDigest, canonicalRequestMessage: canonRequestMsg, signingMessage: signingMsg, signingKey: signKey }; }
javascript
{ "resource": "" }
q41598
json
train
function json(url, method, data, contentType, callback) { var requestUrl = url; // We might be passed to queue, and then our callback will be the last argument (but possibly not #5 // if the original call to queue didn't pass all arguments) so we check for that at the start and // adjust what we consider the method, data, and contentType parameter values. if ( arguments.length > 0 ) { if ( arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function' ) { callback = arguments[arguments.length - 1]; } if ( typeof method !== 'string' ) { method = undefined; } if ( typeof data !== 'string' ) { data = undefined; } if ( typeof contentType !== 'string' ) { contentType = undefined; } } method = (method === undefined ? 'GET' : method.toUpperCase()); if ( method === 'POST' || method === 'PUT' ) { // extract any URL request parameters and put into POST body if ( !data ) { (function() { var queryIndex = url.indexOf('?'); if ( queryIndex !== -1 ) { if ( queryIndex + 1 < url.length - 1 ) { data = url.substring(queryIndex + 1); } requestUrl = url.substring(0, queryIndex); contentType = 'application/x-www-form-urlencoded; charset=UTF-8'; } }()); } } var xhr = d3.json(requestUrl); if ( contentType !== undefined ) { xhr.header('Content-Type', contentType); } xhr.on('beforesend', function(request) { var authorization = computeAuthorization(url, method, data, contentType, new Date()); // set the headers on our request request.setRequestHeader('Authorization', authorization.header); if ( authorization.bodyContentDigest && shouldIncludeContentDigest(contentType) ) { request.setRequestHeader('Digest', authorization.canonicalHeaders.headers['digest']); } request.setRequestHeader('X-SN-Date', authorization.canonicalHeaders.headers['x-sn-date']); }); // register a load handler always, just so one is present xhr.on('load.internal', function() { //sn.log('URL {0} response received.', url); }); if ( callback !== undefined ) { xhr.send(method, data, callback); } return xhr; }
javascript
{ "resource": "" }
q41599
check
train
function check(log, validity, req, res, type, full, finalValidator, callback) { var validator, v; log.info.call(log, 'deserializing and validating request body', { serializerType: type, full: full, finalValidator: finalValidator ? true : false }); if (!req.body) { callback(new Error('Empty Request Body')); return; } if (!validity.hasOwnProperty(type)) { throw new Error('Unrecognized type: ' + type); } v = new Valve(validity[type]); if (req.ctx) { req.ctx.setValve(v); } if (finalValidator) { v.addFinalValidator(finalValidator); } v.baton = {req: req}; validator = full ? v.check : v.checkPartial; validator.call(v, req.body, function(err, cleaned) { if (err) { log.debug.call(log, 'validation_check (error)', {request: req, body: req.body}); callback(err); return; } log.debug.call(log, 'validation_check (success)', {request: req, cleaned: cleaned}); callback(null, cleaned); }); }
javascript
{ "resource": "" }