_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q34300
firstFunction
train
function firstFunction(args) { for (var i = 0, len = args.length; i < len; i++) { if (typeof args[i] === 'function') { return args[i]; } } return null; }
javascript
{ "resource": "" }
q34301
serializeCallback
train
function serializeCallback(args) { var callback; debug('Transforming callback in ', args); return args.map(function(arg) { if (typeof arg !== 'function') return arg; // It shouldn't be an argument after the callback function invariant(!callback, 'Only one callback function is allowed.'); callback = arg; return '__clientCallback__'; }); }
javascript
{ "resource": "" }
q34302
promisify
train
function promisify(func) { return function promisified() { var args = Array.prototype.slice.call(arguments); var context = this; return new Promise(function(resolve, reject) { try { func.apply(context, args.concat(function(err, data) { if (err) { return reject(err); } resolve(data); })); } catch(err) { reject(err); } }); }; }
javascript
{ "resource": "" }
q34303
changeConfig
train
function changeConfig(oldConfig, newConfig) { invariant(isObject(oldConfig), 'Old config is not valid'); invariant(isObject(newConfig), 'Config is not valid'); if (newConfig.host) { var host = newConfig.host; var prefix = ''; if (host.indexOf('http://') < 0 && host.indexOf('https://') < 0) { prefix += 'http://'; } oldConfig.host = prefix + newConfig.host; } if (newConfig.port) { oldConfig.port = newConfig.port; } }
javascript
{ "resource": "" }
q34304
appendCode
train
function appendCode() { if (state === "code") { state = "text"; if (!isWhitespace(codeBuffer)) { content += codeOpen + codeBuffer.replace(/^(?:\s*\n)+/, "").replace(/[\s\n]*$/, "") + codeClose; } codeBuffer = ""; } }
javascript
{ "resource": "" }
q34305
sendCommand
train
function sendCommand(command, mac, params, callback, scope) { var commandParts = []; // check for callback instead of params if (typeof params == 'function') { callback = params; params = ''; scope = callback; } var completeCommand = ''; completeCommand += command.request; commandParts.push(command.request); if (mac) { commandParts.push(mac); completeCommand += mac; } if (params) { commandParts.push(params); completeCommand += params; } var crcChecksum = crc.crc16(completeCommand).toString(16).toUpperCase(); if (crcChecksum.length < 2) { crcChecksum = "000" + crcChecksum; } else if (crcChecksum.length < 3) { crcChecksum = "00" + crcChecksum; } else if (crcChecksum.length < 4) { crcChecksum = "0" + crcChecksum; } commandParts.push(crcChecksum); completeCommand = protocolCommands.frames.start + commandParts.join("") + protocolCommands.frames.end; commandStack.push({mac: mac,command: command, ack:'', callback: callback, scope: scope}); if (options.log > 0) { console.log('---'); console.log(command.color + "SEND " , command.name + ":\t" + commandParts.join("\t") + colors.reset); } sp.write(completeCommand); // we use a counter to know how many ack we are up in compared to commands ackCounter -= 1; return completeCommand; }
javascript
{ "resource": "" }
q34306
addFileToFolder
train
function addFileToFolder(arrayBuffer) { // Construct the endpoint. var fileCollectionEndpoint = String.format(spFormFactory.getFileEndpointUri(_spPageContextInfo.webAbsoluteUrl, doclibname, foldername) + "/add(overwrite=true, url='{0}')", fileuniquename); // Send the request and return the response. // This call returns the SharePoint file. return jQuery.ajax({ url: fileCollectionEndpoint, type: "POST", data: arrayBuffer, processData: false, headers: { "accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() //,"content-length": arrayBuffer.byteLength } }); }
javascript
{ "resource": "" }
q34307
updateListItem
train
function updateListItem(itemMetadata, customFileMetadata) { // Define the list item changes. Use the FileLeafRef property to change the display name. // Assemble the file update metadata var metadata = { __metadata: { type: itemMetadata.type }, FileLeafRef: fileuniquename, Title: filedisplayname }; // Add the custom metadata fields for this file to the metadata object if (typeof(customFileMetadata) === "object") $(metadata).extend(metadata, customFileMetadata); // Send the request and return the promise. // This call does not return response content from the server. var body = JSON.stringify(metadata); return $http.post(itemMetadata.uri, body, { headers: { "X-RequestDigest": $("#__REQUESTDIGEST").val(), "content-type": "application/json;odata=verbose", "content-length": body.length, "IF-MATCH": "*", "X-HTTP-Method": "MERGE" } }); }
javascript
{ "resource": "" }
q34308
parseIpcMessage
train
function parseIpcMessage(message, cb) { var requestId; if (message._requestId == null) { // eslint-disable-line eqeqeq throw new Error('Invalid message: ' + JSON.stringify(message)); } requestId = message._requestId; delete message._requestId; return cb(+requestId, message); }
javascript
{ "resource": "" }
q34309
parseMessageLines
train
function parseMessageLines(lines, getLine, cb) { var matches, line, lineParts; if (arguments.length < 3) { cb = getLine; getLine = false; } RE_MESSAGE_LINE.lastIndex = 0; while ((matches = RE_MESSAGE_LINE.exec(lines))) { line = matches[1]; lines = matches[2]; if (line === '') { continue; } else if (getLine) { cb(line); // eslint-disable-line callback-return } else { lineParts = line.split('\t', 2); if (lineParts.length < 2 || !lineParts[0] || !lineParts[1]) { throw new Error('Invalid message: ' + line); } cb(+lineParts[0], JSON.parse(lineParts[1])); // eslint-disable-line callback-return } } return lines; }
javascript
{ "resource": "" }
q34310
sendIpc
train
function sendIpc(message) { var requestIds; clearTimeout(retryTimer); if (message) { tranRequests[message._requestId] = message; } if ((requestIds = Object.keys(tranRequests)).length) { if (!childProc) { throw new Error('Child process already exited.'); } requestIds.forEach(function(requestId) { console.info('Try to send IPC message: %d', +requestId); childProc.send(tranRequests[requestId]); }); retryTimer = setTimeout(errorHandle(sendIpc), IPC_RETRY_INTERVAL); } }
javascript
{ "resource": "" }
q34311
isOutside
train
function isOutside (feature, poly) { var a = feature.bbox = feature.bbox || extent(feature) var b = poly.bbox = poly.bbox || extent(poly) return a[2] < b[0] || a[0] > b[2] || a[3] < b[1] || a[1] > b[3] }
javascript
{ "resource": "" }
q34312
highlight
train
function highlight(value) { const el = document.createElement('div'); cm(el, { value, mode: { name: 'jsx', typescript: true }, scrollbarStyle: 'null', inputStyle: 'contenteditable' }); const dom = (0, _cheerio.load)(el.innerHTML), lines = dom('.CodeMirror-line'); // eslint-disable-next-line lodash/prefer-lodash-method lines.find('> span').removeAttr('style'); return { dom, lines }; }
javascript
{ "resource": "" }
q34313
highlightHTML
train
function highlightHTML(code = '') { if (!code) { return ''; } const { dom, lines } = highlight(code); return dom.html(lines); }
javascript
{ "resource": "" }
q34314
evaluatePackage
train
function evaluatePackage(filename, attr, format) { var pkgs = require(path.resolve(filename)).pkgs; var pkg = pkgs[attr](); var expr = nijs.jsToNix(pkg, format); return expr; }
javascript
{ "resource": "" }
q34315
evaluatePackageAsync
train
function evaluatePackageAsync(filename, attr, format, callback) { var pkgs = require(path.resolve(filename)).pkgs; slasp.sequence([ function(callback) { pkgs[attr](callback); }, function(callback, pkg) { var expr = nijs.jsToNix(pkg, format); callback(null, expr); } ], callback); }
javascript
{ "resource": "" }
q34316
onScreenBtnClick
train
function onScreenBtnClick (event) { const screenId = event.currentTarget.getAttribute('data-screen'); // if the current screen is the same as the clicked one if (screenId === screenNavigator.currentItemId) return; // display the new screen screenNavigator.showScreen(screenId); }
javascript
{ "resource": "" }
q34317
train
function( aPortNumber ) { var listener = zMIDI._listenerMap[ aPortNumber], inChannel; if ( listener ) { inChannel = zMIDI.getInChannels()[ aPortNumber ]; inChannel.close(); inChannel.removeEventListener( "midimessage", listener, true ); delete zMIDI._listenerMap[ aPortNumber ]; } }
javascript
{ "resource": "" }
q34318
train
function() { if ( zMIDI.isConnected() ) { var inputs = /** @type {Array.<MIDIInput>} */ ( [] ); var iface = zMIDI._interface; if ( typeof iface.inputs === "function" ) { inputs = iface.inputs(); } else { var it = iface.inputs[ "values" ](); for ( var o = it[ "next" ](); !o[ "done" ]; o = it[ "next" ]() ) { inputs.push( o[ "value" ] ); } } return inputs; } zMIDI._handleConnectionFailure(); return null; }
javascript
{ "resource": "" }
q34319
train
function() { if ( zMIDI.isConnected() ) { var outputs = /** @type {Array.<MIDIOutput>} */ ( [] ); var iface = zMIDI._interface; if ( typeof iface.outputs === "function" ) { outputs = iface.outputs(); } else { var it = iface.outputs[ "values" ](); for ( var o = it[ "next" ](); !o[ "done" ]; o = it[ "next" ]() ) { outputs.push( o[ "value" ] ); } } return outputs; } zMIDI._handleConnectionFailure(); return null; }
javascript
{ "resource": "" }
q34320
sendRequest
train
function sendRequest(operationName, body, callback, context) { if (_.isFunction(body)) { context = callback; callback = body; body = undefined; } body || (body = {}); body = new Buffer(_.isString(body) ? body : JSON.stringify(body)); var httpOpts = { host: SERVICE_NAME.toLowerCase() + '.' + region + '.amazonaws.com', port: 443, path: '/', method: 'POST', headers: { 'x-amz-date': basicISODate(), 'x-amz-target': SERVICE_NAME + '_' + API_VERSION + '.' + operationName, 'Content-Type': 'application/x-amz-json-1.0' } }; signRequest(httpOpts, body); httpRequest(httpOpts, body, function(error, responseBody, httpResponse) { var json; try { json = JSON.parse(responseBody); } catch (parseError) { if (!error) error = parseError; } if (_.isFunction(callback)) callback.call(context || httpResponse, error, json || responseBody); }, true); }
javascript
{ "resource": "" }
q34321
getTextBindingForToken
train
function getTextBindingForToken(Directive, tokenText) { tokenText = tokenText.trim(); let directiveInstances = PRIVATE.get(Directive); if (!directiveInstances) { directiveInstances = {}; PRIVATE.set(Directive, directiveInstances); } if (!directiveInstances[tokenText]) { directiveInstances[tokenText] = new Directive(tokenText); } return directiveInstances[tokenText]; }
javascript
{ "resource": "" }
q34322
DomainNameRule
train
function DomainNameRule(data) { if (typeof (data) === "undefined") { return; } // // matches // this.domain = data.domain; if (data.aliases instanceof Array) { this.aliases = data.aliases.slice(); } else { this.aliases = []; } // description (versions) this.description = data.description; // // rules // this.min = (typeof data.min !== "undefined") ? (parseInt(data.min, 10) || 0) : 0; this.max = (typeof data.max !== "undefined") ? (parseInt(data.max, 10) || Number.MAX_VALUE) : Number.MAX_VALUE; this.invalid = (typeof data.invalid !== "undefined") ? data.invalid : ""; this.required = (typeof data.required !== "undefined") ? data.required : ""; this.regex = data.regex; this.validregex = data.validregex; }
javascript
{ "resource": "" }
q34323
FlickrImageDownloader
train
function FlickrImageDownloader () { var that = this; that.url = ''; that.delay = 500; that.downloadFolder = ''; that.paths = {}; that.paths.base = 'https://www.flickr.com'; that.paths.photostream = 'photos/!username'; that.paths.set = that.paths.photostream + '/sets'; that.paths.favorites = that.paths.photostream + '/favorites'; that.image = {}; that.image.dataAttr = 'deferSrc'; that.image.selector = 'div#photo-display-container img.pc_img'; // Events constructor events.EventEmitter.call(that); // Setup listeners that.on('pageCountLoaded', function () { console.log('Event::pageCountLoaded'); that.getImageUrls(); }); that.on('imageUrlsLoaded', function () { console.log('Event::imageUrlsLoaded'); that.downloadImages(); }); that.on('downloadFinished', function (imageUrl) { console.log('Event::downloadFinished(' + imageUrl + ')'); }); that.on('allDownloadsFinished', function () { console.log('Event::allDownloadsFinished'); }); that.on('error', function (functionName, error) { console.log('Event::Error (' + functionName + ')', error); }); }
javascript
{ "resource": "" }
q34324
signStr
train
function signStr(str, key) { var hmac = crypto.createHmac('sha1', key); hmac.update(str); return hmac.digest('base64').replace(/\+/g, '-').replace(/\//g, '_'); }
javascript
{ "resource": "" }
q34325
train
function (changeset) { changeset.forEach(function(change) { if(change.name!=="__target__") { if(change.type==="delete") { delete proxy[change.name]; } else if(change.type==="update") { // update handler if target key value changes from function to non-function or from a non-function to a function if((typeof(change.oldValue)==="function" && typeof(target[change.name])!=="function") || (typeof(change.oldValue)!=="function" && typeof(target[change.name])==="function")) { addHandling(proxy,change.name,target[change.name]); } } else if(!proxy[change.name]) { addHandling(proxy,change.name,target[change.name]); } } })}
javascript
{ "resource": "" }
q34326
traverse
train
function traverse(obj) { each(obj, (val, indexOrProp) => { // Move deeper into the object const next = obj[indexOrProp]; // If we can go no further, then quit if (MongoObject.isBasicObject(next)) { traverse(next); } else if (Array.isArray(next)) { obj[indexOrProp] = without(next, REMOVED_MARKER); traverse(obj[indexOrProp]); } }); }
javascript
{ "resource": "" }
q34327
extractOp
train
function extractOp(position) { const firstPositionPiece = position.slice(0, position.indexOf('[')); return (firstPositionPiece.substring(0, 1) === '$') ? firstPositionPiece : null; }
javascript
{ "resource": "" }
q34328
isFreshEnough
train
function isFreshEnough(entry, req) { // If no cache-control header in request, then entry is fresh // if it hasn't expired. if (!("cache-control" in req.headers)) { return new Date().getTime() < entry.expires; } var headers = parseHeader(req.headers["cache-control"]); if ("must-revalidate" in headers) { return false; } else if ("max-stale" in headers) { // TODO Tell the client that the resource is stale, as RFC2616 requires return !headers["max-stale"] || ((headers["max-stale"] * 1000) > (new Date().getTime() - entry.expires)); // max-stale > "staleness" } else if ("max-age" in headers) { return (headers["max-age"] * 1000) > (new Date().getTime() - entry.created); // max-age > "age" } else if ("min-fresh" in headers) { return (headers["min-fresh"] * 1000) < (entry.expires - new Date().getTime()); // min-fresh < "time until expiry" } else { return new Date().getTime() < entry.expires; } }
javascript
{ "resource": "" }
q34329
yaml
train
function yaml(filename, callback) { try { const yamlString = (0, _fs.readFileSync)(filename, 'utf8'); callback(null, (0, _jsYaml.safeLoad)(yamlString, { filename })); } catch (e) { callback(e, {}); } }
javascript
{ "resource": "" }
q34330
pton6
train
function pton6(addr, dest, index = 0) { if (typeof addr !== 'string') { throw new TypeError('Argument 1 should be a string.') } if (addr.length <= 0) { einval() } const isbuffer = Buffer.isBuffer(dest) const endp = index + IPV6_OCTETS if (isbuffer) { if (endp > dest.length) { throw new Error('Too small target buffer.') } } const buf = isbuffer ? dest : Buffer.allocUnsafe(IPV6_OCTETS) let i = 0 let colonp = null let seenDigits = 0 let val = 0 let curtok = 0 let ch = 0 if (addr[i] === ':') { if (addr.length >= 2 && addr[++i] !== ':') { einval() } } curtok = i while ((ch = i++) < addr.length) { const char = code(addr[ch]) if (isDigit(char) || isLetter16(char)) { val <<= 4 if (isDigit(char)) { val |= char - CHAR0 } else if (isLetter16Low(char)) { val |= char - CHARa + 10 } else if (isLetter16Up(char)) { val |= char - CHARA + 10 } if (++seenDigits > 4) { einval() } } else if (char === CHARCOLON) { curtok = i // If it's second colon in pair. if (seenDigits === 0) { // Only one colon pair allowed. if (colonp !== null) { einval() } colonp = index continue } else if (i >= addr.length) { einval() } if (index + 2 > endp) { einval() } buf[index++] = (val >> 8) & 0xFF buf[index++] = val & 0xFF seenDigits = 0 val = 0 } else if (char === CHARPOINT) { pton4(addr.slice(curtok), buf, index) index += IPV4_OCTETS seenDigits = 0 break } else { einval() } } // Handle last pair. if (seenDigits > 0) { if (index + 2 > endp) { einval() } buf[index++] = (val >> 8) & 0xFF buf[index++] = val & 0xFF } if (colonp !== null) { const n = index - colonp if (index === endp) { einval() } buf.copyWithin(endp - n, colonp, colonp + n) fill(buf, 0, colonp, endp - n) } return buf }
javascript
{ "resource": "" }
q34331
markdownToUnwrappedHTML
train
function markdownToUnwrappedHTML(markdown) { const html = (0, _trim2.default)(md.render(markdown)), { dom, children } = (0, _jsx.parseHTML)(html); if (1 !== children.length) { return html; } const [child] = children, { type, name } = child; return 'tag' === type && 'p' === name ? dom(child).html() : html; }
javascript
{ "resource": "" }
q34332
markdownToJSX
train
function markdownToJSX(markdown = '') { markdown = (0, _trim2.default)(markdown); return markdown ? (0, _jsx.htmlToJSX)(markdownToUnwrappedHTML(markdown)) : []; }
javascript
{ "resource": "" }
q34333
_listbox
train
function _listbox() { at.write(VT_SAVE_CURSOR); // save at.write(CSI + (LAST + 2) + ';' + (AGAIN - 2) + 'r'); at.moveto(1, LAST + 2); //at.write(CSI + 'J'); // erase down KEYS.forEach(function(line, idx) { if (selected === idx) at.reverse(); var ll = line.substr(0, process.stdout.columns - 2); at.write(CSI + '4G' + ll + ESC + 'D'); if (selected === idx) at.reset(); }); _resetscroll(); at.write(VT_RESTORE_CURSOR); // restore at.reset(); }
javascript
{ "resource": "" }
q34334
Chart
train
function Chart(N) { logger.debug("Chart: " + N); this.N = N; this.outgoing_edges = new Array(N+1); this.incoming_edges = new Array(N+1); var i; for (i = 0; i <= N; i++) { this.outgoing_edges[i] = {}; this.incoming_edges[i] = {}; } }
javascript
{ "resource": "" }
q34335
visualManager
train
function visualManager (records) { let nodes, node; records.forEach(record => { nodes = record.removedNodes; if (!nodes || !nodes.length) return; for (let i=0; i<nodes.length; ++i) { node = nodes[i]; if (node.querySelectorAll) { if (!node.__visual__) select(node).selectAll('.d3-visual').each(destroy); else destroy.call(node); } } }); }
javascript
{ "resource": "" }
q34336
maximizeLargeWord
train
function maximizeLargeWord(word, hardBreakStr, maxWidth) { var availableWidth; var ch; var chWidth; var i; availableWidth = maxWidth - Format.width(hardBreakStr); for (i = 0; i < word.length; i++) { ch = word.charAt(i); chWidth = Format.width(ch); if (availableWidth >= chWidth) { availableWidth -= chWidth; } else { break; } } return { start: word.substr(0, i) + hardBreakStr, remaining: word.substr(i) }; }
javascript
{ "resource": "" }
q34337
train
function (propType, values) { propType.info = Object.assign( propType.info ? propType.info : {}, values ); if (propType.isRequired) { propType.isRequired.info = Object.assign( propType.isRequired && propType.isRequired.info ? propType.isRequired.info : {}, values ); propType.isRequired.info.isRequired = true; propType.info.isRequired = false; } return propType; }
javascript
{ "resource": "" }
q34338
copy
train
function copy(copiesMap, projectsPath, buildPath) { return _.map(copiesMap, function(dstPath, srcPath) { if (/\/$/.test(dstPath)) { //copy directory return gulp.src(path.join(projectsPath, srcPath)) .pipe(gulp.dest(path.join(buildPath, dstPath))); } else { //copy file return gulp.src(path.join(projectsPath, srcPath)) .pipe(gulpRename(dstPath)) .pipe(gulp.dest(buildPath)); }; }); }
javascript
{ "resource": "" }
q34339
train
function() { let args = Array.prototype.slice.call(arguments), ErrorClass = args[0]; if (_.isObject(ErrorClass)) { args.shift(); } else { ErrorClass = errors.RuntimeError; } args.unshift(null); // the this arg for the .bind() call throw new (Function.prototype.bind.apply(ErrorClass, args)); }
javascript
{ "resource": "" }
q34340
arrayAdapter
train
function arrayAdapter(to, from, merge) { // reset target array to.splice(0); // transfer actual values from.reduce(function(target, value, index) { // use `undefined` as always-override value target[index] = merge(undefined, value); return target; }, to); return to; }
javascript
{ "resource": "" }
q34341
weave
train
function weave(type, advised, advisedFunc, aopProxy) { let f, $execute, standalone = false, transfer = aopProxy.transfer, adviser = aopProxy.adviser; if (!advisedFunc) { standalone = true; $execute = advised; } else { $execute = advised[advisedFunc].bind(advised); } aopProxy.advised = $execute; switch(type){ case 'before': f = function () { let result = adviser.apply(advised, arguments); // Invoke the advice. result = result && !transfer ? [result] : null; return $execute.apply(advised, result || arguments); // Call the original function. }; break; case 'after': f = function () { let result = $execute.apply(advised, arguments); // Call the original function and store the result. result = result && !transfer ? [result] : null; return adviser.apply(advised, result || arguments); // Invoke the advice. }; break; case 'around': let invocation = { proceed: function () { return this.method.apply(this, this.args); } }; f = function () { invocation.args = arguments; invocation.method = $execute; invocation.name = advisedFunc; return adviser(invocation); }; break; default: console.log("AOP Error", "Unsupported advice type: " + type); } if (standalone) { return (advised = f); } else { return (advised[advisedFunc] = f); } }
javascript
{ "resource": "" }
q34342
identityTranform
train
function identityTranform(idSelector) { idSelector = idSelector || function(x) { return x.id; }; var identityMap = {}; return function(input, output, instance) { var id; // Swap out the instance we are populating in the output transform chain if // we have a cached version of it, otherwise this will be the cached // instance. if (output) { id = idSelector(output); if (!id) return; if (identityMap[id]) { instance = identityMap[id]; return instance; } else { identityMap[id] = instance; } // For input, first time we see a model, cache the instance if it has an // id. Also make sure that if our input instance has an id that its the // same identity as what we have cached. } else { id = idSelector(instance); if (!id) return; if (!identityMap[id]) identityMap[id] = instance; else if (identityMap[id] !== instance) throw new Error('Incorrect identity for model id ' + id); } }; }
javascript
{ "resource": "" }
q34343
FakeTouches
train
function FakeTouches(element) { this.element = element; this.touches = []; this.touch_type = FakeTouches.TOUCH_EVENTS; this.has_multitouch = true; }
javascript
{ "resource": "" }
q34344
triggerTouch
train
function triggerTouch(type) { var event = document.createEvent('Event'); var touchlist = this._createTouchList(this.touches); event.initEvent('touch' + type, true, true); event.touches = touchlist; event.changedTouches = touchlist; return this.element.dispatchEvent(event); }
javascript
{ "resource": "" }
q34345
triggerMouse
train
function triggerMouse(type) { var names = { start: 'mousedown', move: 'mousemove', end: 'mouseup' }; var event = document.createEvent('Event'); event.initEvent(names[type], true, true); var touchList = this._createTouchList(this.touches); if(touchList[0]) { event.pageX = touchList[0].pageX; event.pageY = touchList[0].pageY; event.clientX = touchList[0].clientX; event.clientY = touchList[0].clientY; event.button = 0; } return this.element.dispatchEvent(event); }
javascript
{ "resource": "" }
q34346
triggerPointerEvents
train
function triggerPointerEvents(type, pointerType) { var self = this; var names = { start: 'MSPointerDown', move: 'MSPointerMove', end: 'MSPointerUp' }; var touchList = this._createTouchList(this.touches); touchList.forEach(function(touch) { var event = document.createEvent('Event'); event.initEvent(names[type], true, true); event.MSPOINTER_TYPE_MOUSE = FakeTouches.POINTER_TYPE_MOUSE; event.MSPOINTER_TYPE_TOUCH = FakeTouches.POINTER_TYPE_TOUCH; event.MSPOINTER_TYPE_PEN = FakeTouches.POINTER_TYPE_PEN; event.pointerId = touch.identifier; event.pointerType = pointerType; event.pageX = touch.pageX; event.pageY = touch.pageY; event.clientX = touch.clientX; event.clientY = touch.clientY; event.buttons = (type == 'end') ? 0 : 1; self.element.dispatchEvent(event); }); return true; }
javascript
{ "resource": "" }
q34347
plugin
train
function plugin(options){ options = options || {}; var from = options.from || 'markdown'; var to = options.to || 'html5'; var args = options.args || []; var opts = options.opts || {}; var pattern = options.pattern || '**/*.md'; var extension = options.ext || '.html'; if (to === 'docx' || to === 'pdf') { opts.encoding = 'binary' } return function(files, metalsmith, done){ selectedFiles = match(Object.keys(files), pattern) async.eachLimit(selectedFiles, 100, function(file, cb){ var data = files[file]; var dir = dirname(file); var html = basename(file, extname(file)) + extension; if ('.' != dir) html = dir + '/' + html; debug('Converting file %s', file); var md = data.contents.toString(); pandoc = pdc.stream(from, to, args, opts); var result = new Buffer(0); var chunks = []; var size = 0; var error = ''; // listen on error pandoc.on('error', function (err) { debug('error: ', err); return cb(err); }); // collect result data pandoc.stdout.on('data', function (data) { chunks.push(data); size += data.length; }); // collect error data pandoc.stderr.on('data', function (data) { error += data; }); // listen on exit pandoc.on('close', function (code) { var msg = ''; if (code !== 0) msg += 'pandoc exited with code ' + code + (error ? ': ' : '.'); if (error) msg += error; if (msg) return cb(new Error(msg)); var result = Buffer.concat(chunks, size); data.contents = result; delete files[file]; files[html] = data; cb(null, result); }); // finally, send source string pandoc.stdin.end(md, 'utf8'); }, done); }; }
javascript
{ "resource": "" }
q34348
Device
train
function Device(apple_id, password, display_name) { if (!(this instanceof Device)) return new Device(apple_id, password, display_name); this.apple_id = apple_id; this.password = password; this.display_name = display_name; this.devices = []; this.authenticated = false; }
javascript
{ "resource": "" }
q34349
addDevices
train
function addDevices(deviceArr) { deviceArr.forEach(function(el, i) { self.devices.push({ name: deviceArr[i]['name'], deviceId: deviceArr[i]['id'] }); }); }
javascript
{ "resource": "" }
q34350
train
function(res) { function addCookie(cookie) { try { cookieJar.setCookieSync(cookie, config.base_url); } catch (err) { throw err; } } if (Array.isArray(res.headers['set-cookie'])) { res.headers['set-cookie'].forEach(addCookie); } else { addCookie(res.headers['set-cookie']); } }
javascript
{ "resource": "" }
q34351
plugin
train
function plugin( _options ) { let options = _options || {}; return ( files, metalsmith, done ) => { let app = new Youtube( options, files ); app.parse( function() { done(); }); }; }
javascript
{ "resource": "" }
q34352
merge
train
function merge(to, from) { // if no suitable adapters found // just return overriding value var result = from , typeOf = getTypeOfAdapter.call(this) , type = typeOf(from) , adapter = getMergeByTypeAdapter.call(this, type) ; // if target object isn't the same type as the source object, // then override with new instance of the same type if (typeOf(to) != type) { to = getInitialValue(type, adapter); } // bind merge callback to the current context // so not to loose runtime flags result = adapter.call(this, to, from, merge.bind(this)); return result; }
javascript
{ "resource": "" }
q34353
getMergeByTypeAdapter
train
function getMergeByTypeAdapter(type) { var adapter = adapters[type] || passThru; // only if usage of custom adapters is authorized // to prevent global context leaking in if (this.useCustomAdapters === behaviors.useCustomAdapters && typeof this[type] == 'function' ) { adapter = this[type]; } return adapter; }
javascript
{ "resource": "" }
q34354
getInitialValue
train
function getInitialValue(type, adapter) { var value // should be either `window` or `global` , glob = typeof window == 'object' ? window : global // capitalize the first letter to make object constructor , objectType = type[0].toUpperCase() + type.substr(1) ; if (typeof adapter.initialValue == 'function') { value = adapter.initialValue(); } else if (objectType in glob) { // create new type object and get it's actual value // e.g. `new String().valueOf() // -> ''` value = new glob[objectType]().valueOf(); } // set initial value as `undefined` if no initialValue method found return value; }
javascript
{ "resource": "" }
q34355
train
function (filename) { if (!fs.existsSync(filename)) { logger.error({ method: "edit_add_cookbook_ids", filename: filename }, "file does not exist"); return; } var encoding = 'utf8'; var changed = false; var contents = fs.readFileSync(filename, encoding); var _replacer = function (full, cookbook_name) { changed = true; return util.format('homestar.cookbook(%s, "%s");', cookbook_name, uuid.v4()); }; contents = contents.replace(/^\s*homestar\s*.\s*cookbook\s*[(]\s*("[^"]*")\s*[)](\s*;)?/mg, _replacer); contents = contents.replace(/^\s*homestar\s*.\s*cookbook\s*[(]\s*('[^"]*')\s*[)](\s*;)?/mg, _replacer); if (changed) { fs.writeFileSync(filename, contents, { encoding: encoding }); logger.info({ method: "edit_add_cookbook_ids", filename: filename }, "updated recipe"); } }
javascript
{ "resource": "" }
q34356
copy_row
train
function copy_row(nnz, offset, A, /*int* index, // const int* double* value, // const double* */ x) // x = sparseVector { for(var i=nnz-1; i>=0; --i) if(A.value[i + offset]){ x.push_front(new SparseEntry(A.column_index[i + offset], A.value[i + offset])); } return true; }
javascript
{ "resource": "" }
q34357
solcOutputLike
train
function solcOutputLike(obj) { let isSolcLike = false; Object.keys(obj).forEach((key) => { if (!isSolcLike && typeof obj[key] === 'object') { isSolcLike = (typeof obj[key].bytecode === 'string' && typeof obj[key].interface === 'string'); } }); return isSolcLike; }
javascript
{ "resource": "" }
q34358
Registry
train
function Registry(opt_options) { if (!(this instanceof Registry)) { return new Registry(opt_options); } opt_options = opt_options || {}; this.breakOnError = opt_options.breakOnError || false; this.depth = opt_options.depth || 10; // regex to match "$schema.*" this._match = /"\$id:[a-z0-9_-]*"/ig; // regex to escape strings for usage as regex this._escape = /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g; this.schemas = {}; }
javascript
{ "resource": "" }
q34359
train
function (items, i, j) { var k = items[i]; items[i] = items[j]; items[j] = k; }
javascript
{ "resource": "" }
q34360
train
function (source, callback, context) { var results = []; var i = source.length; while (i--) { results[i] = callback.call(context || source, source[i], i); } return results; }
javascript
{ "resource": "" }
q34361
train
function (value, min, max) { var interval; if (min > max) { max = min + max; min = max - min; max = max - min; } interval = max - min; return min + ((value % interval) + interval) % interval; }
javascript
{ "resource": "" }
q34362
train
function (number, width) { number += ''; width -= number.length; if (width > 0) { return new Array(width + 1).join('0') + number; } return number + ''; }
javascript
{ "resource": "" }
q34363
fixHues
train
function fixHues(h1, h2) { var diff = Math.abs(NAMED_HUE_INDEX[h1] - NAMED_HUE_INDEX[h2]); if (diff !== 1 && diff !== 5) { return false; } var result = { h1: h1, h2: h2 }; if (h1 === 0 && h2 === 300) { result.h1 = 360; } else if (h2 === 0 && h1 === 300) { result.h2 = 360; } return result; }
javascript
{ "resource": "" }
q34364
parseNamedHues
train
function parseNamedHues(value) { var tokens = value.split(/\s+/); var l = tokens.length; if (l < 1 || l > 2) { return false; } var t1 = tokens[l - 1].toLowerCase(); if (!(t1 in BASE_HUE)) { return false; } var h1 = BASE_HUE[t1]; // single-value syntax if (l === 1) { return h1; } // double-value syntax var h2; var t2 = tokens[0].toLowerCase(); var hues; if (t2 in BASE_HUE) { h2 = BASE_HUE[t2]; hues = fixHues(h1, h2); return hues ? (hues.h1 + hues.h2) / 2 : false; } else if (t2 in SPLASH_HUE) { h2 = SPLASH_HUE[t2]; hues = fixHues(h1, h2); return hues ? (hues.h1 + (hues.h2 - hues.h1) / 4) : false; } else { var found = t2.match(/(\w+)\(\s*([^\)]+)\s*\)/i); if (!found) { return false; } t2 = found[1]; if (t2 in SPLASH_HUE) { h2 = SPLASH_HUE[t2]; hues = fixHues(h1, h2); var percent = DATATYPES[PERCENT].parse(found[2]); if (percent === false) { return percent; } return hues ? (hues.h1 + (hues.h2 - hues.h1) * percent) : false; } } return false; }
javascript
{ "resource": "" }
q34365
Octet
train
function Octet() { Channel.apply(this, arguments); this.dataType = INTEGER | PERCENT; this.cssType = INTEGER; this.range = [0, 255]; this.filter = CLAMP; this.initial = 255; }
javascript
{ "resource": "" }
q34366
Ratio
train
function Ratio() { Channel.apply(this, arguments); this.dataType = NUMBER | PERCENT; this.cssType = NUMBER; this.range = [0, 1]; this.filter = CLAMP; this.initial = 1; }
javascript
{ "resource": "" }
q34367
Hue
train
function Hue() { Channel.apply(this, arguments); this.dataType = NUMBER | HUE; this.cssType = NUMBER; this.range = [0, 360]; this.filter = MOD; this.initial = 0; }
javascript
{ "resource": "" }
q34368
ADD_ALPHA
train
function ADD_ALPHA() { var space = this.space(); var channels = SPACES[space].channels; var result = []; var l = channels.length; for (var i = 0; i < l; i++) { result.push(this[channels[i].name]()); } result.push(1); return new kolor[space + 'A'](result); }
javascript
{ "resource": "" }
q34369
REMOVE_ALPHA
train
function REMOVE_ALPHA() { var space = this.space(); var channels = SPACES[space].channels; var result = []; var l = channels.length; for (var i = 0; i < l - 1; i++) { result.push(this[channels[i].name]()); } return new kolor[space.slice(0, -1)](result); }
javascript
{ "resource": "" }
q34370
RGBA_TO_CMYK
train
function RGBA_TO_CMYK() { var r = this.r() / 255; var g = this.g() / 255; var b = this.b() / 255; var black = 1 - Math.max(r, g, b); if (black === 0) { return kolor.cmyk(0, 0, 0, 0); } var c = (1 - r - black) / (1 - black); var m = (1 - g - black) / (1 - black); var y = (1 - b - black) / (1 - black); return kolor.cmyk(c, m, y, black, this.a()); }
javascript
{ "resource": "" }
q34371
RGBA_TO_HSLA
train
function RGBA_TO_HSLA() { var r = this.r() / 255; var g = this.g() / 255; var b = this.b() / 255; var a = this.a(); var max = Math.max(r, g, b); var min = Math.min(r, g, b); var diff = max - min; var sum = max + min; var h; var s; var l; if (max === min) { h = 0; } else if (max === r && g >= b) { h = 60 * (g - b) / diff + 0; } else if (max === r && g < b) { h = 60 * (g - b) / diff + 360; } else if (max === g) { h = 60 * (b - r) / diff + 120; } else { // max === b h = 60 * (r - g) / diff + 240; } l = sum / 2; if (l === 0 || max === min) { s = 0; } else if (0 < l && l <= 0.5) { s = diff / sum; } else { // l > 0.5 s = diff / (2 - sum); } return kolor.hsla(h, s, l, a); }
javascript
{ "resource": "" }
q34372
RGBA_TO_HSVA
train
function RGBA_TO_HSVA() { var r = this.r() / 255; var g = this.g() / 255; var b = this.b() / 255; var a = this.a(); var max = Math.max(r, g, b); var min = Math.min(r, g, b); var diff = max - min; var h; var s; if (max === min) { h = 0; } else if (max === r && g >= b) { h = 60 * (g - b) / diff + 0; } else if (max === r && g < b) { h = 60 * (g - b) / diff + 360; } else if (max === g) { h = 60 * (b - r) / diff + 120; } else { // max === b h = 60 * (r - g) / diff + 240; } if (max === 0) { s = 0; } else { s = diff / max; } var v = max; return kolor.hsva(h, s, v, a); }
javascript
{ "resource": "" }
q34373
HSLA_TO_RGBA
train
function HSLA_TO_RGBA() { var h = this.h(); var s = this.s(); var l = this.l(); var a = this.a(); var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; var hk = h / 360; var t = {}; var rgb = {}; t.r = hk + 1 / 3; t.g = hk; t.b = hk - 1 / 3; var c; for (c in t) { t[c] < 0 && t[c] ++; t[c] > 1 && t[c] --; } for (c in t) { if (t[c] < 1 / 6) { rgb[c] = p + ((q - p) * 6 * t[c]); } else if (1 / 6 <= t[c] && t[c] < 0.5) { rgb[c] = q; } else if (0.5 <= t[c] && t[c] < 2 / 3) { rgb[c] = p + ((q - p) * 6 * (2 / 3 - t[c])); } else { // t[c] >= 2 / 3 rgb[c] = p; } rgb[c] *= 255; } return kolor.rgba(rgb.r, rgb.g, rgb.b, a); }
javascript
{ "resource": "" }
q34374
HSLA_TO_HSVA
train
function HSLA_TO_HSVA() { var h = this.h(); var s = this.s(); var l = this.l(); var a = this.a(); l *= 2; s *= (l <= 1) ? l : 2 - l; var v = (l + s) / 2; var sv = (2 * s) / (l + s); return kolor.hsva(h, sv, v, a); }
javascript
{ "resource": "" }
q34375
HSVA_TO_RGBA
train
function HSVA_TO_RGBA() { var h = this.h(); var s = this.s(); var v = this.v(); var a = this.a(); var hi = Math.floor(h / 60); var f = h / 60 - hi; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); var rgba; switch (hi) { case 0: rgba = [v, t, p, a]; break; case 1: rgba = [q, v, p, a]; break; case 2: rgba = [p, v, t, a]; break; case 3: rgba = [p, q, v, a]; break; case 4: rgba = [t, p, v, a]; break; case 5: rgba = [v, p, q, a]; break; default: rgba = [0, 0, 0, a]; } for (var i = rgba.length - 1; i--;) { rgba[i] *= 255; } return kolor.rgba(rgba); }
javascript
{ "resource": "" }
q34376
HSVA_TO_HSLA
train
function HSVA_TO_HSLA() { var h = this.h(); var s = this.s(); var v = this.v(); var a = this.a(); var l = (2 - s) * v; var sl = s * v; sl /= (l <= 1) ? l : 2 - l; sl = sl || 0; l /= 2; return kolor.hsla(h, sl, l, a); }
javascript
{ "resource": "" }
q34377
HSVA_TO_HWB
train
function HSVA_TO_HWB() { var h = this.h(); var s = this.s(); var v = this.v(); var a = this.a(); return kolor.hwb(h, (1 - s) * v, 1 - v, a); }
javascript
{ "resource": "" }
q34378
HWB_TO_HSVA
train
function HWB_TO_HSVA() { var h = this.h(); var w = this.w(); var b = this.b(); var a = this.a(); return kolor.hsva(h, 1 - w / (1 - b), 1 - b, a); }
javascript
{ "resource": "" }
q34379
GRAY_TO_RGBA
train
function GRAY_TO_RGBA() { var s = this.s(); var a = this.a(); return kolor.rgba(s, s, s, a); }
javascript
{ "resource": "" }
q34380
CMYK_TO_RGBA
train
function CMYK_TO_RGBA() { var c = this.c(); var m = this.m(); var y = this.y(); var black = this.b(); var r = 1 - Math.min(1, c * (1 - black) + black); var g = 1 - Math.min(1, m * (1 - black) + black); var b = 1 - Math.min(1, y * (1 - black) + black); return kolor.rgba(r * 255, g * 255, b * 255, this.a()); }
javascript
{ "resource": "" }
q34381
getConverters
train
function getConverters(from, to) { if (from === to) { return []; } if (CONVERTERS[from][to]) { return [to]; } var queue = [from]; var path = {}; path[from] = []; while (queue.length) { var v = queue.shift(); for (var w in CONVERTERS[v]) { if (!path[w]) { queue.push(w); path[w] = path[v].concat([w]); if (w === to) { return path[w]; } } } } return null; }
javascript
{ "resource": "" }
q34382
filterValue
train
function filterValue(value, channel) { var type; for (var key in DATATYPES) { type = DATATYPES[key]; if (type.flag & channel.dataType) { var val = type.parse(value); if (val !== false) { if (type.flag === PERCENT) { val *= Math.abs(channel.range[1] - channel.range[0]); } return channel.filter(val); } } } return channel.initial; }
javascript
{ "resource": "" }
q34383
train
function(event_name, fn, context, listener_args) { return this._addListener(event_name, fn, context, listener_args, this._listeners) }
javascript
{ "resource": "" }
q34384
train
function(event_name, fn, context, listener_args, listeners_by_event) { // otherwise, listener would be called on window object if (Lava.schema.DEBUG && !context) Lava.t('Listener was created without a context'); // note 1: member count for a plain object like this must not exceed 8 // otherwise, chrome will slow down greatly (!) // note 2: there is no 'remove()' method inside the listener, cause depending on implementation, // it may either slow down script execution or lead to memory leaks var listener = { event_name: event_name, fn: fn, fn_original: fn, context: context, listener_args: listener_args }; if (listeners_by_event[event_name] != null) { listeners_by_event[event_name].push(listener); } else { listeners_by_event[event_name] = [listener]; } return listener; }
javascript
{ "resource": "" }
q34385
train
function(listener, listeners_by_event) { var list = listeners_by_event[listener.event_name], index; if (list) { index = list.indexOf(listener); if (index != -1) { list.splice(index, 1); if (list.length == 0) { listeners_by_event[listener.event_name] = null; } } } }
javascript
{ "resource": "" }
q34386
train
function(listeners, event_args) { var copy = listeners.slice(), // cause they may be removed during the fire cycle i = 0, count = listeners.length, listener; for (; i < count; i++) { listener = copy[i]; listener.fn.call(listener.context, this, event_args, listener.listener_args); } }
javascript
{ "resource": "" }
q34387
train
function(properties_object) { if (Lava.schema.DEBUG && properties_object && properties_object.isProperties) Lava.t("setProperties expects a plain JS object as an argument, not a class"); for (var name in properties_object) { this.set(name, properties_object[name]); } }
javascript
{ "resource": "" }
q34388
train
function(config, target) { this.guid = Lava.guid++; if (config.duration) { this._duration = config.duration; } this._target = target; this._transition = config.transition || Lava.transitions[config.transition_name || 'linear']; this._config = config; }
javascript
{ "resource": "" }
q34389
train
function() { this._is_reversed = !this._is_reversed; if (this._is_running) { var now = new Date().getTime(), new_end = 2 * now - this._started_time; // it's possible in case of script lags. Must not allow negative transition values. if (now > this._end_time) { this._started_time = this._end_time; this._end_time = this._started_time + this._duration; } else { this._end_time = new_end; this._started_time = new_end - this._duration; } this._afterMirror(now); } }
javascript
{ "resource": "" }
q34390
train
function(transition_value) { for (var i = 0, count = this._animators.length; i < count; i++) { this._animators[i].animate(this._target, transition_value); } }
javascript
{ "resource": "" }
q34391
train
function(now) { if (now < this._end_time) { this._callAnimators(this._transition((now - this._started_time) / this._duration)); } else { this._callAnimators(this._transition(1)); this._finish(); } }
javascript
{ "resource": "" }
q34392
train
function(config) { if (config) { if (config.check_property_names === false) this._check_property_names = false; } this._serializeFunction = (config && config.pretty_print_functions) ? this._serializeFunction_PrettyPrint : this._serializeFunction_Normal }
javascript
{ "resource": "" }
q34393
train
function(value, padding) { var type = Firestorm.getType(value), result; if (Lava.schema.DEBUG && !(type in this._callback_map)) Lava.t("Unsupported type for serialization: " + type); result = this[this._callback_map[type]](value, padding); return result; }
javascript
{ "resource": "" }
q34394
train
function(data, padding) { var tempResult = [], i = 0, count = data.length, child_padding = padding + "\t", result; if (count == 0) { result = '[]'; } else if (count == 1) { result = '[' + this._serializeValue(data[i], padding) + ']'; } else { for (; i < count; i++) { tempResult.push(this._serializeValue(data[i], child_padding)); } result = '[' + "\n\t" + padding + tempResult.join(",\n\t" + padding) + "\n" + padding + ']'; } return result; }
javascript
{ "resource": "" }
q34395
train
function(data, padding) { var tempResult = [], child_padding = padding + "\t", name, type, result, is_complex = false, only_key = null, is_empty = true; // this may be faster than using Object.keys(data), but I haven't done speed comparison yet. // Purpose of the following code: // 1) if object has something in it then 'is_empty' will be set to false // 2) if there is only one property in it, then 'only_key' will contain it's name for (name in data) { if (only_key !== null) { // strict comparison - in case the key is valid, but evaluates to false only_key = null; break; } is_empty = false; only_key = name; } if (only_key) { type = Firestorm.getType(data[only_key]); if (type in this._complex_types) { is_complex = true; } } if (is_empty) { result = '{}'; } else if (only_key && !is_complex) { // simple values can be written in one line result = '{' + this._serializeObjectProperty(only_key, data[only_key], child_padding) + '}'; } else { for (name in data) { tempResult.push( this._serializeObjectProperty(name, data[name], child_padding) ); } result = '{' + "\n\t" + padding + tempResult.join(",\n\t" + padding) + "\n" + padding + '}'; } return result; }
javascript
{ "resource": "" }
q34396
train
function(name, value, padding) { var type = Firestorm.getType(value); // if you serialize only Lava configs, then most likely you do not need this check, // cause the property names in configs are always valid. if (this._check_property_names && (!Lava.VALID_PROPERTY_NAME_REGEX.test(name) || Lava.JS_KEYWORDS.indexOf(name) != -1)) { name = Firestorm.String.quote(name); } return name + ': ' + this[this._callback_map[type]](value, padding); }
javascript
{ "resource": "" }
q34397
train
function(data, padding) { var result = this._serializeFunction_Normal(data), lines = result.split(/\r?\n/), last_line = lines[lines.length - 1], tabs, num_tabs, i = 1, count = lines.length; if (/^\t*\}$/.test(last_line)) { if (last_line.length > 1) { // if there are tabs tabs = last_line.substr(0, last_line.length - 1); num_tabs = tabs.length; for (; i < count; i++) { if (lines[i].indexOf(tabs) == 0) { lines[i] = lines[i].substr(num_tabs); } } } lines.pop(); result = lines.join('\r\n\t' + padding) + '\r\n' + padding + last_line; } return result; }
javascript
{ "resource": "" }
q34398
train
function() { var old_uid = this._data_uids.pop(), old_value = this._data_values.pop(), old_name = this._data_names.pop(), count = this._count - 1; this._setLength(count); this._fire('items_removed', { uids: [old_uid], values: [old_value], names: [old_name] }); this._fire('collection_changed'); return old_value; }
javascript
{ "resource": "" }
q34399
train
function(value) { var result = false, index = this._data_values.indexOf(value); if (index != -1) { this.removeAt(index); result = true; } return result; }
javascript
{ "resource": "" }